All of the sudden all of the calls to my web services get this error:
2010-11-04 17:42:16,321 [9] ERROR ABCKiosk - System.InvalidOperationException: Response is not well-formed XML. ---> System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlTextReader.Read()
at System.Xml.XmlReader.MoveToContent()
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
--- End of inner exception stack trace ---
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at ABCKiosk.WebServices.Services.ActivityLog(String kioskID, String KTID, String activityType, Int32 errorCodeFromIncentOne, String msgFromIncentOne, DateTime kioskTime) in D:\SMS SHANE\KIOSK\ABCNC_Kiosk\Implementation\Source Code\ABCKioskClient\ABCKiosk\Web References\WebServices\Reference.cs:line 121
at ABCKiosk.FrmMain.FrmMain_KeyUp(Object sender, KeyEventArgs e) in D:\SMS SHANE\KIOSK\ABCNC_Kiosk\Implementation\Source Code\ABCKioskClient\ABCKiosk\FrmMain.cs:line 110
Before every were fine :( anyone know where is the problem and how to solve this?
Many thanks!
UPDATE - PROVIDE MORE INFORMATION
Here is one of my web methods:
[WebMethod(EnableSession = true)]
public CommonResult ActivityLog(string kioskID, string KTID,
string activityType, int errorCodeFromIncentOne, string msgFromIncentOne, DateTime kioskTime)
{
XMLParser parser = new XMLParser(Server.MapPath(Constant.XML_CONFIGURATION_FILE_PATH));
CommonResult result = new CommonResult();
try
{
AccountDAO accountDAO = new AccountDAO();
ActivityLogDAO activityLogDAO = new ActivityLogDAO();
KioskDAO kioskDAO = new KioskDAO();
// check if this kiosk is existed
if (!kioskDAO.IsKioskIDExisted(kioskID))
{
result.ErrorCode = Constant.ERROR_CODE_KIOSKID_NOT_EXISTED;
result.Message = "abc";
return result;
}
// check if this KTID is existed
if (!accountDAO.IsKTIDExisted(KTID))
{
result.ErrorCode = Constant.ERROR_CODE_KTID;
result.Message = "abc";
return result;
}
// check if this customer already logged for today
if (activityLogDAO.IsLoggedForToday(KTID, DateTime.Now))
{
result.ErrorCode = Constant.ERROR_CODE_LOG_LIMIT;
result.Message = "abc";
return result;
}
// begin log this activity to database
activityLogDAO.ActivityLog(KTID, kioskID, kioskTime);
// return success
result.ErrorCode = Constant.ERROR_CODE_SUCCESS;
result.Message = "abc";
return result;
}
catch (Exception e)
{
result.ErrorCode = Constant.ERROR_CODE_SYSTEM_ERROR;
result.Message = "abc";
return result;
}
}
UPDATE
I tried running the webmethod locally, inspected the return page and saw this in the page source:
<b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
<br><br>
<b> Exception Details: </b>System.InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/ActivityLog'.<br><br>
<b>Source Error:</b> <br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code>
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code>
</td>
</tr>
</table>
<br>
<b>Stack Trace:</b> <br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
[InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/ActivityLog'.]
System.Web.Services.Protocols.WebServiceHandlerFactory.CoreGetHandler(Type type, HttpContext context, HttpRequest request, HttpResponse response) +405913
System.Web.Services.Protocols.WebServiceHandlerFactory.GetHandler(HttpContext context, String verb, String url, String filePath) +212
System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated) +47
System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig) +193
System.Web.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +93
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
</pre></code>
I found out the bug myself, all because of a single line Response.Write() in the Session_Start() that mess up everything :(
Related
//i have left out some parameters for readability
public static string MailForCandidate(string username, string FromAddr, string ToAddr, string strSubject)
{
try
{
MailMessage msg = new MailMessage();
string strMailBody = "Test body";
msg.To = ToAddr;
msg.From = FromAddr;
msg.BodyFormat = MailFormat.Html;
msg.Priority = MailPriority.High;
msg.Subject = strSubject;
msg.Body = strMailBody.ToString();
SmtpMail.SmtpServer = ConfigurationManager.AppSettings["mailServer"].ToString();
try
{
SmtpMail.Send(msg);
msg = null;
return "";
}
catch (Exception ex)
{
Util.Common.LogErrorMessage(ex);
msg = null;
return username;
}
}
catch (Exception ex)
{
throw ex;
}
}
I have the above function that i'm using to send emails from an IIS hosted .NET 3.5 asp.net application.
The emails are sent at the click of a button and the recipients are being read from a database table.
The problem i'm having is that some recipients get their emails with out any issue, others take far too long to receive their emails (sometimes after 24 hours) at which time the event they are supposed to participate in has expired (and this has legal implications to my company). And then finally, others do not receive the email completely.
The above MailForCandidate function is being called from SendCandidateMail below.
private void SendCandidateMail(int intEmailType)
{
try
{
ArrayList arrPending = new ArrayList();
ArrayList arrUnsent = new ArrayList();
string strCandidatename = string.Empty;
string stractualname = string.Empty;
int intUnsentCandCount = 0;
if (hdnUnsentNames.Value.Trim() != string.Empty)
{
arrUnsent.AddRange(hdnUnsentNames.Value.Split(','));
}
if (hdnPendingNames.Value.Trim() != string.Empty)
{
arrPending.AddRange(hdnPendingNames.Value.Split(','));
}
hdnUnsentNames.Value = string.Empty;
hdnPendingNames.Value = string.Empty;
if (!string.IsNullOrEmpty(hdnUnsent.Value) && !string.Empty.Equals(hdnUnsent.Value))
{
string[] strUnsIds = hdnUnsent.Value.Split('~');
for (int i = 0; i < strUnsIds.Length; i++)
{
DataSet dtsetCandidate = CandidatesListBL.GetCandidateDetails(Convert.ToInt32(strUnsIds[i]));
stractualname = arrUnsent[i].ToString();
if (dtsetCandidate.Tables[0].Rows.Count > 0)
{
if (dtsetCandidate.Tables[0].Rows[0]["Time"].ToString() != "0")
{
//i have left out some parameters for readability
strCandidatename = SendMail.MailForCandidate(dtsetCandidate.Tables[0].Rows[0]["User_Id"].ToString(), intEmailType);
}
else
strCandidatename = SendMail.MailForCandidateNoTime(dtsetCandidate.Tables[0].Rows[0]["User_Id"].ToString(), intEmailType);
if (strCandidatename.Trim().Equals(string.Empty))
{
hdnUnsentNames.Value = hdnUnsentNames.Value + stractualname + ",";
intUnsentCandCount = intUnsentCandCount + 1;
if (Convert.ToInt32(EnumMaster.EmailType.Customized) != intEmailType)
{
CandidatesListBL.UpdateCandidateStatus(Convert.ToInt32(strUnsIds[i]), "Sent");
CandidatesListBL.UpdateDateSent(Convert.ToInt32(strUnsIds[i]));
}
}
}
}
hdnUnsent.Value = string.Empty;
}
}
catch (Exception ex)
{
WESMessage.DisplayMessage(this, this.UpdatePanel1, DanielHac.TamperProofString.QueryStringEncode("MailFailed"), this.strinfo);
Common.LogErrorMessage(ex);
}
}
Below is what is being logged in the error log text file.
01/22/2017 3:23:04 PM ==> Exception Message: Thread was being aborted.
01/22/2017 3:23:04 PM ==> Exception Source: App_Code
Exception Target Site: System.String MailForCandidate(System.String, System.String, System.String, System.Collections.ArrayList, System.String, System.String, System.String, System.String, System.String, System.String, UserSession, System.String, System.String, Int32, Int32)
Exception Stack Trace: at WES.Util.SendMail.MailForCandidate(String strUserID, String username, String password, ArrayList alFiles, String FromName, String FromAddr, String ToAddr, String title, String strSubject, String strCustomMsg, UserSession UserObj, String strDeadLine, String strTime, Int32 intOfficeId, Int32 intMailType)
at Pages_ExerciseDetails.SendCandidateMail(Int32 intEmailType)
Exception To String: System.Threading.ThreadAbortException: Thread was being aborted.
at WES.Util.SendMail.MailForCandidate(String strUserID, String username, String password, ArrayList alFiles, String FromName, String FromAddr, String ToAddr, String title, String strSubject, String strCustomMsg, UserSession UserObj, String strDeadLine, String strTime, Int32 intOfficeId, Int32 intMailType)
at Pages_ExerciseDetails.SendCandidateMail(Int32 intEmailType)
And
01/22/2017 3:23:04 PM ==> Exception Message: Thread was being aborted.
01/22/2017 3:23:04 PM ==> Exception Source: App_Web_kxc2lbj5
Exception Target Site: Void SendCandidateMail(Int32)
Exception Stack Trace: at Pages_ExerciseDetails.SendCandidateMail(Int32 intEmailType)
at Pages_ExerciseDetails.ibtnSend_Click(Object sender, EventArgs e)
Exception To String: System.Threading.ThreadAbortException: Thread was being aborted.
at Pages_ExerciseDetails.SendCandidateMail(Int32 intEmailType)
at Pages_ExerciseDetails.ibtnSend_Click(Object sender, EventArgs e)
Also
01/22/2017 3:23:04 PM ==> Exception Message: Request timed out.
101/22/2017 3:23:04 PM ==> Exception Source: Exception Target Site:
Exception Stack Trace: Exception To String: System.Web.HttpException:
Request timed out.
Then
101/22/2017 3:31:35 PM ==> Exception Message: Exception of type
'System.Exception' was thrown. 01/22/2017 3:31:35 PM ==> Exception
Source: App_Web_kxc2lbj5 Exception Target Site: Void
SendCandidateMail(Int32) Exception Stack Trace: at
Pages_ExerciseDetails.SendCandidateMail(Int32 intEmailType) Exception
To String: System.Exception: Exception of type 'System.Exception' was
thrown. at Pages_ExerciseDetails.SendCandidateMail(Int32
intEmailType)
I'm find it hard to troubleshot because it is occurring in production ONLY. In QA and Dev, emails are just going fine using the same SMTP server.
I will just post my comment here as the answer.
I resolved this bu just discarding the obsolete system.web.mail. I
re-wrote the code using System.Net.Mail & all issues are resolved,
performs even much faster.
Recently I have upgraded my project from .NET Framework 3.5 to 4.0. For WCF I am using custom basic authentication.
Before conversion, all was working fine. However, after conversion I am getting "Unexpected end of file error". The stack strace is as below :
at System.Xml.EncodingStreamWrapper.ProcessBuffer(Byte[] buffer, Int32 offset, Int32 count, Encoding encoding)
at System.Xml.XmlUTF8TextReader.SetInput(Byte[] buffer, Int32 offset, Int32 count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
at System.Xml.XmlDictionaryReader.CreateTextReader(Byte[] buffer, Int32 offset, Int32 count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
at System.ServiceModel.Channels.TextMessageEncoderFactory.TextMessageEncoder.WriteMessage(Message message, Int32 maxMessageSize, BufferManager bufferManager, Int32 messageOffset)
at System.ServiceModel.Channels.WebMessageEncoderFactory.WebMessageEncoder.WriteMessage(Message message, Int32 maxMessageSize, BufferManager bufferManager, Int32 messageOffset)
at System.ServiceModel.Channels.HttpOutput.SerializeBufferedMessage(Message message)
at System.ServiceModel.Channels.HttpOutput.Send(TimeSpan timeout)
at System.ServiceModel.Channels.HttpPipeline.EmptyHttpPipeline.SendReplyCore(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.HttpPipeline.EmptyHttpPipeline.SendReply(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.HttpRequestContext.OnReply(Message message, TimeSpan timeout)
at System.ServiceModel.Activation.HostedHttpContext.OnReply(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.RequestContextBase.Reply(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.RequestContextBase.Reply(Message message)
at ihv1Role.auth.BasicAuthenticationInterceptor.ProcessRequest(RequestContext& requestContext) in d:\src\auth\BasicAuthenticationInterceptor.cs:line 78
The class and method in which I am getting error are as below :
p
ublic class BasicAuthenticationInterceptor : RequestInterceptor
{
MembershipProvider provider;
string realm;
public BasicAuthenticationInterceptor(MembershipProvider provider, string realm)
: base(false)
{
this.provider = provider;
this.realm = realm;
}
protected string Realm
{
get { return realm; }
}
protected MembershipProvider Provider
{
get { return provider; }
}
public override void ProcessRequest(ref RequestContext requestContext)
{
HttpRequestMessageProperty request = (HttpRequestMessageProperty)requestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name];
string[] credentials = ExtractCredentials(requestContext.RequestMessage);
if (credentials.Length > 0 && AuthenticateUser(credentials[0], credentials[1], IsTestMode))
{
InitializeSecurityContext(requestContext.RequestMessage, credentials[0]);
}
else
{
Message reply = Message.CreateMessage(MessageVersion.None, null);
HttpResponseMessageProperty responseProperty = new HttpResponseMessageProperty() { StatusCode = HttpStatusCode.Unauthorized };
responseProperty.Headers.Add("WWW-Authenticate",
String.Format("Basic realm=\"{0}\"", Realm));
reply.Properties[HttpResponseMessageProperty.Name] = responseProperty;
requestContext.Reply(reply); // **Here I am getting error**
requestContext = null;
}
}
}
If the username and password in header are valid then whole service runs well. I am getting this error only if request is not authenticated.
Any solution?
Thanks
Resolved it my self :
I had added tag twice in Web.config.
Removed it and now my service is working fine.
I have the following POST edit action method:-
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(RackJoin rj,FormCollection formValues)
{
try
{
if (ModelState.IsValid)
{
repository.InsertOrUpdateRack(rj.Rack, User.Identity.Name, rj.Resource.RESOURCEID);
repository.Save();
return RedirectToAction("Index");
}
}
catch (DbUpdateConcurrencyException ex)
{
var entry = ex.Entries.Single();
var databaseValues = (Rack)entry.GetDatabaseValues().ToObject();
var clientValues = (Rack)entry.Entity;
var entry2 = ex.Entries.Single();
var databaseValues2 = (Resource)entry2.GetDatabaseValues().ToObject();
var clientValues2 = (Resource)entry2.Entity;
if (databaseValues.RU != clientValues.RU)
ModelState.AddModelError("Rack.RU", "Current value: "
+ databaseValues.RU);
but when the DbUpdateConcurrencyException exception is raised i am getting the following exception on the following line of code var databaseValues2 = (Resource)entry2.GetDatabaseValues().ToObject();:-
Unable to cast object of type 'System.Data.Entity.DynamicProxies.Rack_81556130B3DB7E3D4F63B9FF3F15832A81A86055EED840211E95A71E1342027D' to type 'TMS.Models.Resource'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidCastException: Unable to cast object of type 'System.Data.Entity.DynamicProxies.Rack_81556130B3DB7E3D4F63B9FF3F15832A81A86055EED840211E95A71E1342027D' to type 'TMS.Models.Resource'.
Source Error:
Line 175: var clientValues = (Rack)entry.Entity;
Line 176: var entry2 = ex.Entries.Single();
Line 177: var databaseValues2 = (Resource)entry2.GetDatabaseValues().ToObject();
Line 178: var clientValues2 = (Resource)entry2.Entity;
Line 179:
Source File: c:\Users\Administrator\Documents\Visual Studio 2012\Projects\TMS\TMS\Controllers\RackController.cs Line: 177
Stack Trace:
[InvalidCastException: Unable to cast object of type 'System.Data.Entity.DynamicProxies.Rack_81556130B3DB7E3D4F63B9FF3F15832A81A86055EED840211E95A71E1342027D' to type 'TMS.Models.Resource'.]
TMS.Controllers.RackController.Edit(RackJoin rj, FormCollection formValues) in c:\Users\Administrator\Documents\Visual Studio 2012\Projects\TMS\TMS\Controllers\RackController.cs:177
lambda_method(Closure , ControllerBase , Object[] ) +245
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +59
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +435
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +60
System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeSynchronousActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +50
System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +75
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +44
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +139
I'm not entirely clear what's going on in this section of code, are you meant to be retrieving the Resource from the second context you mentioned in your comment?
var entry = ex.Entries.Single();
var databaseValues = (Rack)entry.GetDatabaseValues().ToObject();
var clientValues = (Rack)entry.Entity;
var entry2 = ex.Entries.Single();
var databaseValues2 = (Resource)entry2.GetDatabaseValues().ToObject();
var clientValues2 = (Resource)entry2.Entity;
If you called Single() on a sequence that contained more than one element, you would generate an exception; since Single isn't generating an exception, you only have one entry present which you're using in both cases.
In the first you want to treat it as a Rack, which doesn't seem to generate a complaint. In the second, you're treating it as a Resource, which seems to be incompatible with Rack, the cause of your complaint.
InvalidCastException: Unable to cast object of type 'System.Data.Entity.DynamicProxies.Rack_81...' to type 'TMS.Models.Resource'.]
The reason your exception only contains that particular entity may well be found in your InsertOrUpdateRack method.
When i try to execute the following script..i get an error .I am trying to receive data using JSON.
function loadData() {
isLoading = true;
$('#loaderCircle').show();
alert("OOOOO");
$.ajax({
url: apiURL,
dataType: 'json',
data: { page: page }, // Page parameter to make sure we load new data
success: function(data) {
isLoading = false;
$('#loaderCircle').hide();
// Increment page index for future calls.
page++;
// Create HTML for the images.
var html = '';
var i = 0, length = data.length, image;
alert(data.length);
for (; i < length; i++) {
image = data[i];
html += '<li class="polaroid"><div class="optionbg"></div><div class="optionback"><span>Necklaces</span></div><div class="options"><span class="favs">14</span><span class="fav">like it!</span></div><img src="' + image.preview + '" width="180" height="' + Math.round(image.height / image.width * 180) + '"></li>';
}
// Add image HTML to the page.
$('#tiles').append(html);
// Apply layout.
applyLayout();
},
error: function(result) {
$('#qqq').text(JSON.stringify(result));
//alert(JSON.stringify(result));
}
});
};
Webservice:
<WebMethod(Description:="Gets the Categories")> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
Public Function GetCategories() As String
Dim details As New List(Of Nodes)()
Using ds As Data.DataSet = db.ExecuteDataSet(CommandType.Text, "SELECT NodeID,NodeName FROM Nodes WHERE ParentID='1'")
Dim JaggedArray As String()() = New String(ds.Tables(0).Rows.Count - 1)() {}
Dim i As Integer = 0
For Each rs As DataRow In ds.Tables(0).Rows
Dim node As New Nodes()
node.NodeId = rs("NodeId").ToString
node.NodeName = rs("NodeName").ToString
details.Add(node)
'JaggedArray(i) = New String() {rs("NodeName").ToString(), rs("NodeID").ToString()}
i = i + 1
Next
End Using
Dim js As New JavaScriptSerializer()
Dim strJSON As String = js.Serialize(details.ToArray)
Return strJSON
End Function
JSON Output:
<string xmlns="http://localhost:54511/">
[{"NodeId":"BK01","NodeName":"Books","ParentId":null,"Likes":null},{"NodeId":"CO01","NodeName":"Computers","ParentId":null,"Likes":null},{"NodeId":"GA01","NodeName":"Gaming","ParentId":null,"Likes":null},{"NodeId":"MO01","NodeName":"Mobile & Accessories","ParentId":null,"Likes":null}]
</string>
Error:
{"readyState":4,"responseText":"<html>\r\n <head>\r\n <title>Request format is unrecognized for URL unexpectedly ending in '/GetCategories'.</title>\r\n <style>\r\n body {font-family:\"Verdana\";font-weight:normal;font-size: .7em;color:black;} \r\n p {font-family:\"Verdana\";font-weight:normal;color:black;margin-top: -5px}\r\n b {font-family:\"Verdana\";font-weight:bold;color:black;margin-top: -5px}\r\n H1 { font-family:\"Verdana\";font-weight:normal;font-size:18pt;color:red }\r\n H2 { font-family:\"Verdana\";font-weight:normal;font-size:14pt;color:maroon }\r\n pre {font-family:\"Lucida Console\";font-size: .9em}\r\n .marker {font-weight: bold; color: black;text-decoration: none;}\r\n .version {color: gray;}\r\n .error {margin-bottom: 10px;}\r\n .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }\r\n </style>\r\n </head>\r\n\r\n <body bgcolor=\"white\">\r\n\r\n <span><H1>Server Error in '/EntLib5' Application.<hr width=100% size=1 color=silver></H1>\r\n\r\n <h2> <i>Request format is unrecognized for URL unexpectedly ending in '/GetCategories'.</i> </h2></span>\r\n\r\n <font face=\"Arial, Helvetica, Geneva, SunSans-Regular, sans-serif \">\r\n\r\n <b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.\r\n\r\n <br><br>\r\n\r\n <b> Exception Details: </b>System.InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/GetCategories'.<br><br>\r\n\r\n <b>Source Error:</b> <br><br>\r\n\r\n <table width=100% bgcolor=\"#ffffcc\">\r\n <tr>\r\n <td>\r\n <code>\r\n\r\nAn unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code>\r\n\r\n </td>\r\n </tr>\r\n </table>\r\n\r\n <br>\r\n\r\n <b>Stack Trace:</b> <br><br>\r\n\r\n <table width=100% bgcolor=\"#ffffcc\">\r\n <tr>\r\n <td>\r\n <code><pre>\r\n\r\n[InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/GetCategories'.]\r\n System.Web.Services.Protocols.WebServiceHandlerFactory.CoreGetHandler(Type type, HttpContext context, HttpRequest request, HttpResponse response) +405913\r\n System.Web.Services.Protocols.WebServiceHandlerFactory.GetHandler(HttpContext context, String verb, String url, String filePath) +212\r\n System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated) +47\r\n System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig) +193\r\n System.Web.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +93\r\n System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155\r\n</pre></code>\r\n\r\n </td>\r\n </tr>\r\n </table>\r\n\r\n <br>\r\n\r\n <hr width=100% size=1 color=silver>\r\n\r\n <b>Version Information:</b> Microsoft .NET Framework Version:2.0.50727.4971; ASP.NET Version:2.0.50727.4971\r\n\r\n </font>\r\n\r\n </body>\r\n</html>\r\n<!-- \r\n[InvalidOperationException]: Request format is unrecognized for URL unexpectedly ending in '/GetCategories'.\r\n at System.Web.Services.Protocols.WebServiceHandlerFactory.CoreGetHandler(Type type, HttpContext context, HttpRequest request, HttpResponse response)\r\n at System.Web.Services.Protocols.WebServiceHandlerFactory.GetHandler(HttpContext context, String verb, String url, String filePath)\r\n at System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated)\r\n at System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig)\r\n at System.Web.HttpApplication.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()\r\n at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)\r\n-->","status":500,"statusText":"Internal Server Error"}
Mey be here you can find the solution: http://aspadvice.com/blogs/ssmith/archive/2007/09/04/FIX-Request-format-is-unrecognized-for-URL-unexpectedly-ending-in.aspx
I have an issue with Elmah, I've overriden the Mailing method. And I want it to dispose of the mail (not send it basically) when my App isn't in Live mode. Problem is when I do this, when my ErrorHandler (in my ASP.NET MVC app) tries to raise the exception with Elmah, i get the error: Cannot access a disposed object. Object name:'System.Net.Mail.MailMessage'. So I need to figure out a way around this. Code below:
Emailing method:
public static void ErrorMail_Mailing(object sender, ErrorMailEventArgs e)
{
if (!GlobalHelper.IsLiveMode)
{
//e.Mail.Dispose();
}
else
{
MailAddressCollection MAC = new MailAddressCollection();
foreach (string a in EmailRecipients.Split(','))
{
MAC.Add(a);
}
string b = "errors#" + GlobalHelper.AppName + ".com";
e.Mail.From = new MailAddress(b);
e.Mail.To.Clear(); // Clears existing mail addresses
e.Mail.To.Add(MAC.ToString());
e.Mail.Subject = GlobalHelper.AppName+ " Error: ("+e.Error.Type.Substring(0,10)+") Deployment Level:"+GlobalHelper.DeploymentMode;
}
Errorhandler method:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class CustomHandleErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext context)
{
// Bail if we can't do anything; app will crash.
if (context == null)
return;
var ex = context.Exception ?? new Exception("No further information exists.");
// Can show Data on view page /w this code
// var data = new ErrorPresentation
//{
// ErrorMessage = HttpUtility.HtmlEncode(ex.Message),
// TheException = ex,
// ShowMessage = !(filterContext.Exception == null),
// ShowLink = false
//};
//filterContext.Result = View("ErrorPage", data);
context.ExceptionHandled = true;
//Log to Elmah
ErrorSignal.FromCurrentContext().Raise(ex);
//Show Custom view page
context.Result = new ViewResult { ViewName = "Error" };
}
}
Stack trace:
System.Net.Mail.SmtpException: Failure sending mail. ---> System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Mail.MailMessage'.
at System.Net.Mail.MailMessage.get_AlternateViews()
at System.Net.Mail.MailMessage.SetContent()
at System.Net.Mail.SmtpClient.Send(MailMessage message)
--- End of inner exception stack trace ---
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at Elmah.ErrorMailModule.SendMail(MailMessage mail)
at Elmah.ErrorMailModule.ReportError(Error error)
at Elmah.ErrorMailModule.OnError(Exception e, HttpContext context)
at Elmah.ErrorMailModule.OnErrorSignaled(Object sender, ErrorSignalEventArgs args)
at Elmah.ErrorSignalEventHandler.Invoke(Object sender, ErrorSignalEventArgs args)
at Elmah.ErrorSignal.Raise(Exception e, HttpContext context)
at Elmah.ErrorSignal.Raise(Exception e)
at MusingMonkey.Utilities.Filters.CustomHandleErrorAttribute.OnException(ExceptionContext context) in C:\Users\William-Business\Desktop\TWB\TWB Central\Projects\MusingMonkey\MusingMonkey\Utilities\Filters\ErrorHandler.cs:line 34
at System.Web.Mvc.ControllerActionInvoker.InvokeExceptionFilters(ControllerContext controllerContext, IList`1 filters, Exception exception)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state)
at System.Web.Mvc.Controller.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)
at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass6.<>c__DisplayClassb.<BeginProcessRequest>b__3(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass6.<BeginProcessRequest>b__2()
at System.Web.Mvc.SecurityUtil.<>c__DisplayClassb`1.<ProcessInApplicationTrust>b__a()
at System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f)
at System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action)
at System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust[TResult](Func`1 func)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
The problem is that ELMAH is trying to use the MailMessage in order to send it but you have already disposed the object. The best solution for you would be to not do this via the event, but by inheriting from the ErrorMailModule and overriding it's SendMail method like this:
protected override void SendMail(MailMessage mail)
{
if (!GlobalHelper.IsLiveMode)
base.SendMail(mail);
}
You can then continue to do the rest in your Mailing event handler.