SQLite AccessViolationException in WCF service - c#

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.

Related

Try/catch not catching HttpListenerException

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.

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.

Under what circumstance C# ASP.NET HttpContext.Current.Session throws, IndexOutOfRangeException?

I am getting an error that doesn't happen very often, but the client has seen it and wants it fixed.
Basically, it's an IndexOutOfRangeException exception, but what's odd is that the trace points to System.Web.HttpContext.Current. How is that possible?
The line that it fails on is like this:
at
System.Collections.ArrayList.Add(Object value) at
System.Collections.Specialized.NameObjectCollectionBase.BaseAdd(String
name, Object value) at
System.Web.SessionState.SessionStateItemCollection.set_Item(String
name, Object value) at
WebStateManager.set_Item(String key, Object value)
in
\WebStateManager.cs:line
53 at UIStateManager.get_BookingParameters() in
WS\App_Code\Managers\UIStateManager.cs:line
2746
Index was outside the bounds of
the array.
System.Web.HttpContext context = System.Web.HttpContext.Current;
If it was an array, I could do counts and other checks, but what kind of check would I do here other than a try-catch?
enter link description here
public class Example
{
public static void Main()
{
int[] values1 = { 3, 6, 9, 12, 15, 18, 21 };
int[] values2 = new int[6];
// Assign last element of the array to the new array.
values2[values1.Length - 1] = values1[values1.Length - 1];
}
}
// The example displays the following output:
// Unhandled Exception:
// System.IndexOutOfRangeException:
// Index was outside the bounds of the array.
// at Example.Main()
My Project Code
public override object this[string key]
{
get
{
if (Helpers.CommonFunctions.IsHttpSessionNull)
{ return null; }
return HttpContext.Current.Session[key + Helpers.CommonFunctions.GetAppDomainMultiplexer()];
}
set
{
if (Helpers.CommonFunctions.IsHttpSessionNull)
{ return; }
if (value == null)
{
try
{
if (HttpContext.Current.Session[key + Helpers.CommonFunctions.GetAppDomainMultiplexer()] != null)
{
HttpContext.Current.Session.Remove(key + Helpers.CommonFunctions.GetAppDomainMultiplexer());
}
}
catch
{
}
}
else
{
HttpContext.Current.Session[key + Helpers.CommonFunctions.GetAppDomainMultiplexer()] = value;
}
}
}
The fault stack trace is as follows;
0:072> !clrstack
OS Thread Id: 0x31ec (72)
Child SP IP Call Site
000000aea766d968 000007f9736a4650 [HelperMethodFrame: 000000aea766d968]
000000aea766da50 000007f9674e0e5a System.Collections.ArrayList.Add(System.Object)
000000aea766da90 000007f966655292 System.Collections.Specialized.NameObjectCollectionBase.BaseAdd(System.String, System.Object)
000000aea766dae0 000007f9650ac4c9 System.Web.SessionState.SessionStateItemCollection.set_Item(System.String, System.Object)
000000aea766db20 000007f90ed89ce9 UTL.WebStateManager.set_Item(System.String, System.Object)
000000aea766dbf0 000007f90f29370c WebStateManagerHelper.get_OriginalPNR()
000000aea766dc80 000007f90f29242d QueryDynamicLoggingComponent.LogTransaction(System.String, System.String)
000000aea766e110 000007f90f2917e3 WSHelper.Log(System.String, System.String, Boolean, System.String)
000000aea766e160 000007f90f28fd17 WSHelper.GetResponse(System.String, SecurityInfo, System.String, System.String, System.String ByRef, System.String, System.String)
000000aea766e5d0 000007f90f29eae6 WSHelper.SendQuery(System.String, SecurityInfo, System.String)
000000aea766e7f0 000007f90f29e7f8 WSHelper.SendQuery(SecurityInfo, System.String)
000000aea766e840 000007f90f29e4af APIWSPool.SendAndReceiveQueryToString(Agency, System.String, Token, Boolean)
000000aea766e940 000007f90f29e374 APIWSPool.SendAndReceiveQuery(Agency, Token, Boolean)
000000aea766e9b0 000007f90f6168f4 FlightBookingManager.SearchFlightForMPSearchedFlightRecommendations1(Agency, FlightFareDrivenSearchInfo, Boolean)
000000aea766eb80 000007f90f615ec1 ApiFlightBookingProvider.SearchFlightForMPSearchedFlightRecommendations1(Agency, FlightFareDrivenSearchInfo, Boolean)
000000aea766ebe0 000007f90f6158f2 APICOM.Threading.OWCOutboundSearchThread.Work()
000000aea766edb0 000007f9674e2d45 System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
000000aea766ef10 000007f9674e2ab9 System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
000000aea766ef40 000007f9674e2a97 System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
000000aea766ef90 000007f9674fa161 System.Threading.ThreadHelper.ThreadStart()
000000aea766f2a8 000007f96e0eab53 [GCFrame: 000000aea766f2a8]
000000aea766f5f8 000007f96e0eab53 [DebuggerU2MCatchHandlerFrame: 000000aea766f5f8]
000000aea766f788 000007f96e0eab53 [ContextTransitionFrame: 000000aea766f788]
000000aea766f9a8 000007f96e0eab53 [DebuggerU2MCatchHandlerFrame: 000000aea766f9a8]
SessionStateItemCollection is not thread-safe (see https://msdn.microsoft.com/en-us/library/system.web.sessionstate.sessionstateitemcollection(v=vs.110).aspx), and you likely have multiple threads writing / reading from the session state at the same time.
You need to find your code that accesses HttpContext.Session or Page.Session and make sure that code is not running in a background thread.
See https://msdn.microsoft.com/en-us/library/system.indexoutofrangeexception(v=vs.110).aspx - (search for "Violating thread safety")
Below is some example code using locking to try and avoid the issue. This code is very quick and dirty. I do not recommend it. But short of re-architecting your system, it may be worthwhile. If you use this technique, you must put it around every use of Session.
public override object this[string key]
{
get
{
if (Helpers.CommonFunctions.IsHttpSessionNull)
{ return null; }
lock (HttpContext.Current.Session)
{
return HttpContext.Current.Session[key + Helpers.CommonFunctions.GetAppDomainMultiplexer()];
}
}
set
{
if (Helpers.CommonFunctions.IsHttpSessionNull)
{ return; }
lock (HttpContext.Current.Session)
{
if (value == null)
{
try
{
if (HttpContext.Current.Session[key + Helpers.CommonFunctions.GetAppDomainMultiplexer()] != null)
{
HttpContext.Current.Session.Remove(key + Helpers.CommonFunctions.GetAppDomainMultiplexer());
}
}
catch
{
}
}
else
{
HttpContext.Current.Session[key + Helpers.CommonFunctions.GetAppDomainMultiplexer()] = value;
}
}
}

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?

Categories

Resources