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.
Related
I am using uPLibrary.Networking.M2Mqtt to connect to MQTT broker.
var telemetryClient = new uPLibrary.Networking.M2Mqtt.MqttClient(
mqttBaseAddress, MqttSettings.MQTT_BROKER_DEFAULT_SSL_PORT, true,
new X509Certificate2($"certs/{rootCert}"), new X509Certificate2($"certs/{cert}", $"{certPw}"),
MqttSslProtocols.TLSv1_2
);
if (!telemetryClient.IsConnected)
{
try
{ // Following line is getting exceptions
telemetryClient.Connect(clientId, null, null, true, 10);
telemetryClient.ConnectionClosed += (sender, args) =>
{
IoTCoreTelemetryStreamHealth.PublishEvent(IoTCoreTelemetryStreamHealth.Event.Disconnected);
};
telemetryClient.Subscribe(new[] { topic }, new[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE });
IoTCoreTelemetryStreamHealth.PublishEvent(IoTCoreTelemetryStreamHealth.Event.Connected);
}
catch (Exception exception)
{
CloseTelemetryStream(telemetryClient, true, topic);
Task.Delay(DelayBeforeReconnect).ContinueWith(t => ConnectAndSubscribeForTelemetryTopic(serialNumber, src, clientId, telemetryClient, telemetryStreamType, topic));
}
}
This has been working for a long time, without any serious issues.
After a while (months), I started getting two exceptions constantly, one after the other a lot of times from this line:
telemetryClient.Connect(clientId, null, null, true, 10);
The exceptions are:
uPLibrary.Networking.M2Mqtt.Exceptions.MqttCommunicationException:
Exception of type 'uPLibrary.Networking.M2Mqtt.Exceptions.MqttCommunicationException' was thrown. at
uPLibrary.Networking.M2Mqtt.MqttClient.SendReceive(Byte[] msgBytes, Int32 timeout) at
uPLibrary.Networking.M2Mqtt.MqttClient.Connect(String clientId, String username, String password, Boolean willRetain, Byte willQosLevel, Boolean willFlag, String willTopic, String willMessage, Boolean cleanSession, UInt16 keepAlivePeriod)
and
System.OutOfMemoryException:
Exception of type 'System.OutOfMemoryException' was thrown. at
System.Threading.Thread.StartInternal() at
uPLibrary.Networking.M2Mqtt.MqttClient.Connect(String clientId, String username, String password, Boolean willRetain, Byte willQosLevel, Boolean willFlag, String willTopic, String willMessage, Boolean cleanSession, UInt16 keepAlivePeriod) at
DevicePortal.Telemetry.Service.Services.IotCoreServiceBase.ConnectAndSubscribeForTelemetryTopic(String serialNumber, String src, String clientId, MqttClient telemetryClient, String telemetryStreamType, String topic) in /src/DevicePortal.Telemetry.Service/Services/IotCoreServiceBase.cs:line 179
//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.
There is a special working progress where we encrypt and decrypt an input.
Suddenly, yesterday, there was an encrypted string we weren't able to decrypt.
It seems my cryptographic knowledge aren't good enough to solve this problem.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Crypto
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public static class Crypto
{
public static void Main()
{
//String NotWorking_dec = "鈦ꧪ㧘聯ꢮ玗硴廜᭮⸂濅�";
String enc ="mIAU::__*?";
//String dec = "砿첩뜞ꦽ嶾蝡泛ɝࠪ塤偏ꍨ";
Console.WriteLine(decrypt(dec));
//writeFile(encrypt(enc));
Console.ReadLine();
}
private static string key = "ZlKMpRwoPLmNXEpCLxEa6g==";
private static string iv = "U5ZB4W4bQqg=";
private static ICryptoTransform enc;
private static ICryptoTransform dec;
static Crypto()
{
RC2 rc = System.Security.Cryptography.RC2.Create();
enc = rc.CreateEncryptor(Convert.FromBase64String(key), Convert.FromBase64String(iv));
dec = rc.CreateDecryptor(Convert.FromBase64String(key), Convert.FromBase64String(iv));
}
public static String encrypt(String value)
{
byte[] input = toBytes(value);
return toString(enc.TransformFinalBlock(input, 0, input.Length));
}
public static String decrypt(String value)
{
byte[] input = toBytes(value);
Console.WriteLine(input.Length);
return toString(dec.TransformFinalBlock(input, 0, input.Length));
}
private static void writeFile(String value)
{
try
{
StreamWriter sw = new StreamWriter("output.tmp", true);
sw.WriteLine(value);
sw.Close();
}
catch (Exception ex) { }
}
private static byte[] toBytes(String value)
{
return Encoding.Unicode.GetBytes(value);
}
private static String toString(byte[] value)
{
return Encoding.Unicode.GetString(value);
}
}
}
This working progress works for months.
You are able to test it with the input
mIAU::__*?
you get
砿첩뜞ꦽ嶾蝡泛ɝࠪ塤偏ꍨ
decrypt it and you get again
mIAU::__*?
But the encrypted String "鈦ꧪ㧘聯ꢮ玗硴廜᭮⸂濅�" throws errors: (Of course we used the same key and iv)
BAD DATA
bei System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
bei System.Security.Cryptography.Utils._DecryptData(SafeKeyHandle hKey, Byte[] data, Int32 ib, Int32 cb, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode PaddingMode, Boolean fDone)
bei System.Security.Cryptography.CryptoAPITransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
bei Crypto.Crypto.decrypt(String value) in c:\Users\Td\Documents\Visual Studio 2013\Projects\Crypto\Crypto\Program.cs:Zeile 56.
bei Crypto.Crypto.Main() in c:\Users\Td\Documents\Visual Studio 2013\Projects\Crypto\Crypto\Program.cs:Zeile 23.
bei System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
bei System.AppDomain.nExecuteAssembly(RuntimeAssembly assembly, String[] args)
bei System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
bei System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
bei System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
bei System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
bei System.Activator.CreateInstance(ActivationContext activationContext)
bei Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
bei System.Threading.ThreadHelper.ThreadStart_Context(Object state)
bei System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
bei System.Threading.ThreadHelper.ThreadStart()
You cannot simply convert random bytes to strings and back. Not all bytes are valid character encodings. You need to apply for instance base 64 encoding to your binary ciphertext if you require text. Otherwise you will loose data, depending on the value of the ciphertext. And the ciphertext will contain random byte values. So it may fail now and then, as you are currently experiencing.
Java silently converts unknown bytes to characters by default, for instance it will create a � character if it cannot convert byte(s) to a character. This is why this particular string fails.
Besides that, Unicode contains a lot of characters that are not easily printable, and even characters that can be created using either two Unicode code points or a single one. So a Unicode string may have multiple possible encodings, so it is doubly unsuitable for conveying binary data.
All in all, text should not be directly used to convey binary data. The data needs to be encoded first.
I have a very basic ASP.NET response filter that works "fine." I use it to replace the domain for static resources.
My code in the controller looks like this:
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
_cdnRewriter.Stream = filterContext.RequestContext.HttpContext.Response.Filter;
filterContext.RequestContext.HttpContext.Response.Filter = _cdnRewriter;
}
And the rewrite filter itself:
public override void Write(byte[] buffer, int offset, int count)
{
var html = Encoding.Default.GetString(buffer, offset, count);
//manipulate html
byte[] outData = Encoding.Default.GetBytes(html);
Stream.Write(outData, 0, outData.GetLength(0));
}
For certain pages on my site (I can't find the rhyme or reason yet), I get a "HTTP Web Exception: Invalid use of response filter" perhaps 90% of the time. Simply refreshing a dozen times will get the correct output, but refreshing again will show the exception:
[HttpException (0x80004005): Invalid use of response filter]
System.Web.HttpResponseStreamFilterSink.VerifyState() +4097234
System.Web.HttpResponseStreamFilterSink.Write(Byte[] buffer, Int32 offset, Int32 count) +28
NeoSmart.Web.CdnRewriteFilter.Write(Byte[] buffer, Int32 offset, Int32 count) +452
System.Web.HttpWriter.FilterIntegrated(Boolean finalFiltering, IIS7WorkerRequest wr) +359
System.Web.HttpResponse.FilterOutput() +121
System.Web.CallFilterExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +119
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +165
Am I doing something wrong in my response filter?
I probably should have known better: response filters should not be shared. I was using an object per class, creating a new response filter each time the OnActionExecuted function was called resolved the issue.
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.