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

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?

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;
}
}
}

Visual Studio Crashes! - Collection was modified after the enumerator was instantiated

Hey i have a UserControl that kept crashing my Visual Studio.
So i ran another instance of VS and debugged the other VS and this is what i figured:
Collection was modified after the enumerator was instantiated.
Here is my array:
private static Color[] colors =
{
Color.FromArgb(155, 188, 255), // 40000
Color.FromArgb(156, 189, 255), // 39500
Color.FromArgb(157, 188, 255), // 39000
Color.FromArgb(156, 189, 254), // 38500
};
And here is my loop that crashes the bussines
public Heater()
{
InitializeComponent();
this.tarTemp = this.curTemp;
new Thread(() => UpdateTemp(true)).Start();
}
private delegate void UpdateTempDelegate(bool loop);
private void UpdateTemp(bool loop)
{
if (lblTemp.InvokeRequired)
{
UpdateTempDelegate del = new UpdateTempDelegate(UpdateTemp);
lblTemp.Invoke(del, loop);
}
else
{
do
{
lblTemp.Text = curTemp + C;
if (curTemp >= 0)
{
int i = curTemp - 10;
if (i < 0)
i = 0;
if (i > colors.Length - 1)
i = colors.Length - 1;
this.BackColor = colors[i]; // I'M CRASHING !!!
}
} while (loop && !this.Disposing);
}
}
The line that crashes the Visual Studio Designer is this.BackColor = colors[i];
Here is the image of the running Threads:
All threads stopped on the same line... this.BackColor = colors[i];
Here is the EventViewer crash log:
Application: devenv.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.InvalidOperationException
Stack:
at System.ThrowHelper.ThrowInvalidOperationException(System.ExceptionResource)
at System.Collections.Generic.SortedList`2+SortedListValueEnumerator[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].MoveNext()
at Microsoft.VisualStudio.Shell.ServiceProviderHierarchy.GetService(System.Type)
at System.ComponentModel.Design.ServiceContainer.GetService(System.Type)
at System.ComponentModel.Design.DesignerHost.GetService(System.Type)
at System.ComponentModel.Design.DesignerHost+Site.System.IServiceProvider.GetService(System.Type)
at System.Windows.Forms.Control.get_AmbientPropertiesService()
at System.Windows.Forms.Control.get_BackColor()
at System.Windows.Forms.Control.set_BackColor(System.Drawing.Color)
at Multiplier.Heater.UpdateTemp(Boolean)
at Multiplier.Heater.<.ctor>b__0()
at System.Threading.ThreadHelper.ThreadStart_Context(System.Object)
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()
This is the weirdest thing i encountered so far.
Help whould be appriciated.
As you found out, your code is crashing the designer, taking VS down with it. The problem is that you start a thread in design mode, triggered by the designer running some of your code at design time. It for example will run the constructor, the Load event, OnHandleCreated, etcetera. That makes for a very nice design-time experience, your control will look just like it does at runtime.
But that can also cause plenty of problems. You have to avoid running code that may cause an exception when it runs in a different execution context. Classic examples are trying to open a file without specifying the full path, opening a dbase connection with the dbase server offline or unreachable. And definitely starting a thread, InvokeRequired is not going to reliably work as the designer constructs and destroys the native window handle. The fix is simple:
public Heater()
{
InitializeComponent();
this.tarTemp = this.curTemp;
if (!this.DesignMode) {
new Thread(() => UpdateTemp(true)).Start();
}
}
You'll need to do more work, this code won't work well at runtime either. The threaded code will bomb when the form on which the user control is placed is closed. Once you fix that, odds are good that it now works correctly at design-time as well. But don't.
Are you modifying the collection using any other code? Usually this happens when you are enumerating a collection in a loop and you try to modify the collection.

Categories

Resources