Try/catch not catching HttpListenerException - c#

I made a simple http endpoint using Grapevine (which is just an interface for HttpListener). Sometimes the connection drops before I SendResponse which leads to a HttpListenerException, but I don't understand why the try/catch doesn't handle the exception and the whole server crashes.
Error:
Application: Movimiento de Placas.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Net.HttpListenerException
Stack:
at System.Net.HttpResponseStream.Write(Byte[], Int32, Int32)
at Grapevine.Interfaces.Server.HttpResponse.SendResponse(Byte[])
at Grapevine.Server.HttpResponseExtensions.SendResponse(Grapevine.Interfaces.Server.IHttpResponse, System.String)
at Grapevine.Server.Router.Route(System.Object)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(System.Object)
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
Code:
[RestRoute(HttpMethod = HttpMethod.POST, PathInfo = "/patente")]
public IHttpContext ModificarPantalla(IHttpContext context)
{
var dict = HttpUtility.ParseQueryString(context.Request.Payload);
var json = new JavaScriptSerializer().Serialize(
dict.Keys.Cast<string>()
.ToDictionary(k => k, k => dict[k]));
var contenido = JsonConvert.DeserializeObject<Patente>(json);
Server.FormRef.CargarPatente(contenido.Plate, contenido.idCamera);
UltimaFoto.Fecha = DateTime.Now;
Task.Run(() => Sqlite.InsertarPatente(contenido));
try
{
context.Response.SendResponse(HttpStatusCode.Ok); //exception occurs here
}
catch (Exception ex)
{
}
return context;
}

This is a known issue. There is a PR that's been hanging around for a while now that fixes this, I'm merging it in now, along with an update that will add support for .NET Standard. This should be available by the end of the week.
Update: Grapevine 4.1.2 is available on Nuget.org as of August 9, 2019

This could happen if SendResponse was async and you didnt await it.

Related

The process was terminated due to an unhandled exception. System.Net.HttpWebRequest.GetResponse() exception in ews

Hello everyone i am stuck with this exception and it is stopping my service. please help following is the full stack trace.
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Net.WebException at System.Net.HttpWebRequest.GetResponse()
at
Microsoft.Exchange.WebServices.Data.EwsHttpWebRequest.Microsoft.Exchange.WebServices.Data.IEwsHttpWebRequest.GetResponse()
at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.GetEwsHttpWebResponse(Microsoft.Exchange.WebServices.Data.IEwsHttpWebRequest)
Exception Info: Microsoft.Exchange.WebServices.Data.ServiceRequestException
at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.GetEwsHttpWebResponse(Microsoft.Exchange.WebServices.Data.IEwsHttpWebRequest)
at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.ValidateAndEmitRequest(Microsoft.Exchange.WebServices.Data.IEwsHttpWebRequest ByRef)
at Microsoft.Exchange.WebServices.Data.HangingServiceRequestBase.InternalExecute()
at Microsoft.Exchange.WebServices.Data.StreamingSubscriptionConnection.Open()
at ERSupportGetOutlookEmail.EmailExchange.OnDisconnect(System.Object, Microsoft.Exchange.WebServices.Data.SubscriptionErrorEventArgs)
at Microsoft.Exchange.WebServices.Data.StreamingSubscriptionConnection.InternalOnDisconnect(System.Exception)
at Microsoft.Exchange.WebServices.Data.StreamingSubscriptionConnection.OnRequestDisconnect(System.Object, Microsoft.Exchange.WebServices.Data.HangingRequestDisconnectEventArgs)
at Microsoft.Exchange.WebServices.Data.HangingServiceRequestBase.InternalOnDisconnect(Microsoft.Exchange.WebServices.Data.HangingRequestDisconnectReason, System.Exception)
at Microsoft.Exchange.WebServices.Data.GetStreamingEventsResponse.ReadElementsFromXml(Microsoft.Exchange.WebServices.Data.EwsServiceXmlReader)
at Microsoft.Exchange.WebServices.Data.ServiceResponse.LoadFromXml(Microsoft.Exchange.WebServices.Data.EwsServiceXmlReader, System.String)
at Microsoft.Exchange.WebServices.Data.GetStreamingEventsRequest.ParseResponse(Microsoft.Exchange.WebServices.Data.EwsServiceXmlReader)
at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.ReadResponse(Microsoft.Exchange.WebServices.Data.EwsServiceXmlReader)
at Microsoft.Exchange.WebServices.Data.HangingServiceRequestBase.ParseResponses(System.Object)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(System.Object)
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
Here is my code please look into this
public async System.Threading.Tasks.Task Watch()
{
//Configuration options for a public client application (desktop/mobile app)
var pcaOptions = new PublicClientApplicationOptions
{
ClientId = ConfigurationManager.AppSettings["appId"],
TenantId = ConfigurationManager.AppSettings["tenantId"]
};
//Creates a PublicClientApplicationBuilder from a clientID.
var pca = PublicClientApplicationBuilder
.CreateWithApplicationOptions(pcaOptions).Build();
//access permission.
var ewsScopes = new string[] { "https://outlook.office.com/EWS.AccessAsUser.All" };
try
{
// Make the interactive token request
var authResult = await pca.AcquireTokenByUsernamePassword(ewsScopes, EmailID, ConvertToSecureString(Password)).ExecuteAsync();
//var authResult = await pca.AcquireTokenInteractive(ewsScopes).ExecuteAsync();
// Configure the ExchangeService with the access token
ewsClient = new ExchangeService();
ewsClient.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);
Console.WriteLine("New Email details will display below:-");
// Make an EWS call
CreateStreamingSubscription(); //Creating subscription.
}
catch (MsalException ex)
{
Email.onErrorOccur(ex.Message, "EmailExchange Watch event MsalException", ex.StackTrace);
}
catch (Exception ex)
{
Email.onErrorOccur(ex.Message, "EmailExchange Watch event", ex.StackTrace);
}
}
On the code you posted its whats in CreateStreamingSubscription that is causing the exception, its just being caught by the code block you posted which isn't doing any Exchange requests just authentication. Can you give more detail on when it happens eg does the code work for a while and this happens or it just doesn't work? if it just doesn't work may TLS 1.2 so i would suggest including in
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

SSIS script task is only working with debugging mode

I am using VS 2017 and SQL server 2016 to do the job. I create a script task that tries to send email by using SendGrid. If I put a break point inside the script task, I won't have problem to execute my SSIS package and then get the email. However, if I simply execute the package, the entire package still can be executed successfully but I cannot get the email, which I suspect that script task does not get executed. The following is the code of my script task
public void Main()
{
string User_Email = Dts.Variables["User::UserEmail"].Value.ToString();
try
{
if (!File.Exists(Dts.Variables["User::OutputPath"].Value.ToString()))
throw new FileNotFoundException();
File.Copy(Dts.Variables["User::OutputPath"].Value.ToString(), Dts.Variables["User::DestinationPath"].Value.ToString() + Dts.Variables["User::co_num"].Value.ToString() + ".pdf", true);
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
SendGridMailHelper.SendOrderVerification(User_Email, "user name");
}
catch (FileNotFoundException)
{
MessageBox.Show("The file is not found in the specified location");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Dts.TaskResult = (int)ScriptResults.Success;
}
static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
if (args.Name.Contains("SendGrid"))
{
string path = #"F:\DLL\";
return System.Reflection.Assembly.LoadFile(System.IO.Path.Combine(path, "SendGrid.dll"));
}
if (args.Name.Contains("System.Net.Http"))
{
string path = #"F:\DLL\";
return System.Reflection.Assembly.LoadFile(System.IO.Path.Combine(path, "System.Net.Http.dll"));
}
if (args.Name.Contains("Newtonsoft.Json"))
{
string path = #"F:\DLL\";
return System.Reflection.Assembly.LoadFile(System.IO.Path.Combine(path, "Newtonsoft.Json.dll"));
}
return null;
}
To be safe, I checked the windows log and it showed the run time error when I run the package without adding check points. However, I cannot figure it out what it means. Any thoughts will be very helpful. Thank you.
Application: DtsDebugHost.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.MissingMethodException
at ST_b240be27e55248ea869be51aa06a2018.SendGridMailHelper+<_SendEmail>d__7.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[[ST_b240be27e55248ea869be51aa06a2018.SendGridMailHelper+<_SendEmail>d__7, ST_b240be27e55248ea869be51aa06a2018, Version=1.0.6877.42064, Culture=neutral, PublicKeyToken=null]](<_SendEmail>d__7 ByRef)
at ST_b240be27e55248ea869be51aa06a2018.SendGridMailHelper._SendEmail(System.Collections.Generic.List`1, System.Object, System.String)
at ST_b240be27e55248ea869be51aa06a2018.SendGridMailHelper+d__9.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()

Unhandled exception at Grapevine.Interfaces.Server.HttpResponse.SendResponse

I have a server which listens to HTTP POSTs that several client make sending information. I use Grapevine as http server because methods are really simple and didn't need the complexity of ASP.
Sometimes I get this random
error:
2017-12-12 15:39:25.5642|ERROR|Omnibox_Server.Modelo.HttpServer.Controllers.OpenALPRController|System.Net.HttpListenerException (0x80004005): The I/O operation has been aborted because of either a thread exit or an application request
at System.Net.HttpRequestStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.IO.StreamReader.ReadBuffer()
at System.IO.StreamReader.ReadToEnd()
at Grapevine.Interfaces.Server.HttpRequest.get_Payload()
at Omnibox_Server.Modelo.HttpServer.Controllers.OpenALPRController.PostPatente(IHttpContext context)
This is the
class/method:
namespace Omnibox_Server.Modelo.HttpServer.Controllers
{
[RestResource(BasePath = "/openalpr")]
public class OpenALPRController
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
[RestRoute(HttpMethod = HttpMethod.POST, PathInfo = "/patente")]
public IHttpContext PostPatente(IHttpContext context)
{
try
{
context.Response.StatusCode = HttpStatusCode.Ok;
context.Response.ContentType = ContentType.JSON;
context.Response.ContentEncoding = Encoding.UTF8;
var fotoOpenAlpr = JsonConvert.DeserializeObject<FotoOpenALPR>(context.Request.Payload); //<--- exception occurs here? shouldn't try/catch work?
var ip = context.Request.RemoteEndPoint;
if (fotoOpenAlpr.agent_uid != null)
Task.Run(async () =>
{
if (fotoOpenAlpr.is_parked) return;
await fotoOpenAlpr.ObtenerFoto(ip.Address);
try
{
var foto = new Foto(fotoOpenAlpr);
if (foto.IdOmnibox == 0) Logger.Info("Omnibox sin ID con IP " + ip.Address);
await foto.Procesar();
}
catch (Exception e)
{
}
});
context.Response.SendResponse(HttpStatusCode.Ok); //or maybe exception triggers here?
}
catch (Exception e)
{
Logger.Error(e);
}
return context;
}
}
}
An event is generated in the
windows log:
Application: Omnibox Server.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Net.HttpListenerException
at System.Net.HttpResponseStream.Write(Byte[], Int32, Int32)
at Grapevine.Interfaces.Server.HttpResponse.SendResponse(Byte[])
at Grapevine.Server.HttpResponseExtensions.SendResponse(Grapevine.Interfaces.Server.IHttpResponse, System.String)
at Grapevine.Server.Router.Route(System.Object)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(System.Object)
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
Both exception log and windows log in the event viewer have the same timestamp.
From the OP:
I fixed the issue by moving the line context.Response.SendResponse(HttpStatusCode.Ok); below the try/catch. I think what happened was that sometimes TCP pipe breaks and payload is corrupt/incomplete, therefore an exception is thrown when trying to get it, and because I didn't SendResponse(OK) another exception is thrown outside the try/catch, breaking my server.

Event Viewer reporting my C# application crashed through 'System.Environment.FailFast()'

My application is running on Windows Embedded Standard 7 and launches when the OS boots up.
Sometimes on the first load, I will get an Unknown Hard Error, and after checking the Event Viewer, I see a message of
The application requested process termination through System.Environment.FailFast(string message).
Message: Unrecoverable system error.
Needless to say, I of course have no calls to this function. I only seem to see this happen on Windows Embedded, and haven't seen this reproduced on a standard install of Windows.
I'm unsure of how to diagnose this or what 'fix' would be appropriate as I don't really know why it happens.
Edit:
The entire log in Event Viewer:
Application: WinForm.exe
Framework Version: v4.0.30319
Description: The application requested process termination through System.Environment.FailFast(string message).
Message: Unrecoverable system error.
Stack:
at System.Environment.FailFast(System.String)
at MS.Internal.Invariant.FailFast(System.String, System.String)
at System.IO.Packaging.Package.AddIfNoPrefixCollisionDetected(ValidatedPartUri,
System.IO.Packaging.PackagePart) at System.IO.Packaging.Package.GetPartHelper(System.Uri)
at System.IO.Packaging.Package.GetPart(System.Uri)
at System.Windows.Application.GetResourceOrContentPart(System.Uri)
at System.Windows.Application.LoadComponent(System.Object, System.Uri)
at Pms.PmControl.InitializeComponent()
at Pms.PmControl..ctor(Boolean)
at Pms.PmAppControl.StartWpfThread()
at System.Threading.ThreadHelper.ThreadStart_Context(System.Object)
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
at System.Threading.ThreadHelper.ThreadStart()
If you look at the code with a decompiler you will find
// System.IO.Packaging.Package
private void AddIfNoPrefixCollisionDetected(PackUriHelper.ValidatedPartUri partUri, PackagePart part)
{
this._partList.Add(partUri, part);
int num = this._partList.IndexOfKey(partUri);
Invariant.Assert(num >= 0, "Given uri must be present in the dictionary");**
string normalizedPartUriString = partUri.NormalizedPartUriString;
string text = null;
string text2 = null;
if (num > 0)
{
text = this._partList.Keys[num - 1].NormalizedPartUriString;
}
if (num < this._partList.Count - 1)
{
text2 = this._partList.Keys[num + 1].NormalizedPartUriString;
}
if ((text != null && normalizedPartUriString.StartsWith(text, StringComparison.Ordinal) && normalizedPartUriString.Length > text.Length && normalizedPartUriString[text.Length] == PackUriHelper.ForwardSlashChar) || (text2 != null && text2.StartsWith(normalizedPartUriString, StringComparison.Ordinal) && text2.Length > normalizedPartUriString.Length && text2[normalizedPartUriString.Length] == PackUriHelper.ForwardSlashChar))
{
this._partList.Remove(partUri);
throw new InvalidOperationException(SR.Get("PartNamePrefixExists"));
}
}
The code fails at the assert because that is the only method which calls FailFast
internal static void Assert(bool condition, string invariantMessage)
{
if (!condition)
{
Invariant.FailFast(invariantMessage, null);
}
}
Now the question remains why you package could not be found in the PartList array. WPF fills some things out for you. Could it be that you reference from your XAML some resource via an internet addresses or a network share which could fail if the network subsystem of your Windows embedded is not yet ready?

SQLite AccessViolationException in WCF service

We have a .NET Windows Service exposing a WCF service to an user-interface and other parts of our system. It targets .NET Framework 4.5 and uses SQLite 1.0.92 binaries to talk to the underlying SQLite database. However, the windows service crashes (automatically stopped) after running for some time with an AccessViolationException (found via Windows Event Viewer) in SQLite.Interop.dll. I have come across articles that talks about this exception in Connection close, but in all our cases we encounter this exception while querying or writing to the DB using the methods exposed by our WCF service. The stack-trace is as follows:
Application: OurServer.exe
Framework Version: **v4.0.30319**
Description: The process was terminated due to an unhandled exception.
Exception Info: System.AccessViolationException
Stack:
at System.Data.SQLite.UnsafeNativeMethods.sqlite3_bind_int(IntPtr, Int32, Int32)
at System.Data.SQLite.UnsafeNativeMethods.sqlite3_bind_int(IntPtr, Int32, Int32)
at System.Data.SQLite.SQLite3.Bind_Int32(System.Data.SQLite.SQLiteStatement, System.Data.SQLite.SQLiteConnectionFlags, Int32, Int32)
at System.Data.SQLite.SQLiteStatement.BindParameter(Int32, System.Data.SQLite.SQLiteParameter)
at System.Data.SQLite.SQLiteStatement.BindParameters()
at System.Data.SQLite.SQLiteCommand.GetStatement(Int32)
at System.Data.SQLite.SQLiteDataReader.NextResult()
at System.Data.SQLite.SQLiteDataReader..ctor(System.Data.SQLite.SQLiteCommand, System.Data.CommandBehavior)
at System.Data.SQLite.SQLiteCommand.ExecuteReader(System.Data.CommandBehavior)
at System.Data.SQLite.SQLiteCommand.ExecuteNonQuery(System.Data.CommandBehavior)
at DataAccess.Sqlite.ExecuteCommand(System.Collections.ObjectModel.Collection`1<System.String>, System.Collections.ObjectModel.Collection`1<System.Data.Common.DbParameter[]>)
at Data.Settings.Save(System.Collections.ObjectModel.Collection`1<Common.Operation>)
at DynamicClass.SyncInvokeSaveOperation(System.Object, System.Object[], System.Object[])
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(System.Object, System.Object[], System.Object[] ByRef)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(System.ServiceModel.Dispatcher.MessageRpc ByRef)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(System.ServiceModel.Dispatcher.MessageRpc ByRef)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(System.ServiceModel.Dispatcher.MessageRpc ByRef)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean)
at System.ServiceModel.Dispatcher.ChannelHandler.DispatchAndReleasePump(System.ServiceModel.Channels.RequestContext, Boolean, System.ServiceModel.OperationContext)
at System.ServiceModel.Dispatcher.ChannelHandler.HandleRequest(System.ServiceModel.Channels.RequestContext, System.ServiceModel.OperationContext)
at System.ServiceModel.Dispatcher.ChannelHandler.AsyncMessagePump(System.IAsyncResult)
at System.Runtime.Fx+AsyncThunk.UnhandledExceptionFrame(System.IAsyncResult)
at System.Runtime.AsyncResult.Complete(Boolean)
at System.Runtime.InputQueue`1+AsyncQueueReader[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].Set(Item<System.__Canon>)
at System.Runtime.InputQueue`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].EnqueueAndDispatch(Item<System.__Canon>, Boolean)
at System.Runtime.InputQueue`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].EnqueueAndDispatch(System.__Canon, System.Action, Boolean)
at System.ServiceModel.Channels.SingletonChannelAcceptor`3[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].Enqueue(System.__Canon, System.Action, Boolean)
at System.ServiceModel.Channels.ConnectionDemuxer+CompleteSingletonPreambleAndDispatchRequestAsyncResult.OnPreambleComplete(System.IAsyncResult)
at System.Runtime.Fx+AsyncThunk.UnhandledExceptionFrame(System.IAsyncResult)
at System.Runtime.AsyncResult.Complete(Boolean)
at System.ServiceModel.Channels.ServerSingletonPreambleConnectionReader+CompletePreambleAsyncResult.OnWriteCompleted(System.Object)
at System.ServiceModel.Channels.SocketConnection.OnSendAsync(System.Object, System.Net.Sockets.SocketAsyncEventArgs)
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
at System.Net.Sockets.SocketAsyncEventArgs.FinishOperationSuccess(System.Net.Sockets.SocketError, Int32, System.Net.Sockets.SocketFlags)
at System.Net.Sockets.SocketAsyncEventArgs.CompletionPortCallback(UInt32, UInt32, System.Threading.NativeOverlapped*)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32, UInt32, System.Threading.NativeOverlapped*)
We are using the SQLite assemblies from "sqlite-netFx45-binary-bundle-Win32-2012-1.0.92.0" (downloaded from http://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki). The assemblies are bundled as part of the Windows Service and are not in GAC. This behavior is consistent in both 32-bit and 64-bit machines. FYI, we are NOT using the mixed mode assemblies.
Our connection string:
Data Source=ourapp.db;Version=3;New=False;Compress=True;PRAGMA cache_size=20000; PRAGMA page_size=32768; PRAGMA synchronous=off"
and the SQLite database file is the Windows "ProgramData" folder.
The stacktrace shows the Framework version as "v4.0.30319" while we have explicitly set the target version to 4.5 in our service's application config. However, the machine has both the versions installed.
Also, I wrote a simple console application that invokes the same WCF service method from multiple threads, but could not simulate the same AccessViolationException. Hence, I don't think it could be a load or concurrent access related issue. The exception seems random and we have no way of consistently re-producing the issue other than just running the service and waiting for it to happen.
Any pointers to what could be causing this issue is greatly appreciated.
UPDATE:
Code for the two variants of ExecuteCommand being used:
public int ExecuteCommand(string query, params DbParameter[] parameters)
{
try
{
this.result = -1;
this.OpenConnection();
this.command = new SQLiteCommand(query, this.connnection);
this.HandleParameters(parameters);
this.result = this.command.ExecuteNonQuery();
}
catch (Exception ex)
{
this.result = -1;
}
finally
{
if (this.command != null)
{
this.command.Dispose();
}
this.CloseConnection();
}
return this.result;
}
public int ExecuteCommand(Collection<string> queries, Collection<DbParameter[]> parameters)
{
try
{
this.result = -1;
this.OpenConnection();
this.command = new SQLiteCommand();
this.command.Connection = this.connnection;
this.transaction = this.connnection.BeginTransaction();
for (int i = 0; i < queries.Count; i++)
{
this.command.Parameters.Clear();
this.command.CommandText = queries[i];
this.command.CommandTimeout = this.timeOut;
this.command.Transaction = this.transaction;
DbParameter[] cmdParams = new DbParameter[] { };
if (parameters != null)
{
cmdParams = parameters[i];
}
this.HandleParameters(cmdParams);
this.result += this.command.ExecuteNonQuery();
}
this.transaction.Commit();
}
catch (Exception ex)
{
if (this.transaction != null)
{
this.transaction.Rollback();
}
this.result = -1;
}
finally
{
if (this.command != null)
{
this.command.Dispose();
}
this.CloseConnection();
}
return this.result;
}
UPDATE 2: Code for Save method
Collection<DbParameter[]> dbparameters = new Collection<DbParameter[]>();
DbParameter[] dbparams;
SQLiteParameter sqlparams;
Collection<string> queries = new Collection<string>();
int icount = 0;
foreach (Operation operation in operations)
{
icount = 0;
dbparams = new DbParameter[4];
queries.Add("UPDATE table1 SET col1 = #Col1, col2 = #col2, " +
"Timestamp = #Timestamp WHERE Id = #Id");
sqlparams = new SQLiteParameter();
sqlparams.DbType = DbType.String;
sqlparams.ParameterName = "#Timestamp";
sqlparams.Value = string.Format(CultureInfo.InvariantCulture, "{0:yyyy-MM-dd HH:mm:ss}", operation.Timestamp);
dbparams[icount++] = sqlparams;
sqlparams = new SQLiteParameter();
sqlparams.DbType = DbType.String;
sqlparams.ParameterName = "#Id";
sqlparams.Value = operation.Id;
dbparams[icount++] = sqlparams;
sqlparams = new SQLiteParameter();
sqlparams.DbType = DbType.String;
sqlparams.ParameterName = "#Col1";
sqlparams.Value = operation.Col1;
dbparams[icount++] = sqlparams;
sqlparams = new SQLiteParameter();
sqlparams.DbType = DbType.String;
sqlparams.ParameterName = "#Col2";
sqlparams.Value = operation.Col2;
dbparams[icount++] = sqlparams;
dbparameters.Add(dbparams);
}
return (DataAccess.Sqlite.ExecuteCommand(queries, dbparameters) > -1);
The error is consistent With the provider loosing track of which Connections are open:
Trying to Close a Connection that does not exist
Trying to use a Connection that does not exist
The error looks like a problem with Connection pooling, but Your Connection string does not use Connection pooling and it is turned off by default.
Does anything else Access the same database With Connection pooling turned on?
The first thing you must do is to log the exception.
Your class may not be thread safe. Check that multiple thread does not call the Save method at the same time.
Also make sure you implement IDisposable to dispose of your SQLiteConnection object if it is a private member of your class.

Categories

Resources