I'm using Application Insights for a WPF Application. Tracking of PageViews and custom events is working.
Now I would like to track crashes. My idea was to:
private void AppDispatcherUnhandledException(object sender,
DispatcherUnhandledExceptionEventArgs e)
{
telemetryClient.TrackException(e.Exception);
telemetryClient.Flush();
}
The code is called when a unhandled exception occurs but it is not shown as "Crash" in the Application Insights portal. I have read somewhere that TrackException does not count as "Crash" when the application does not really crash.
Desktop (e.g. WPF) applications must use the low level API of Application Insights. I have not found a way to tell Application Insights that the WPF Application is crashing.
How could I do that?
For WPF applications, there is no inherent support for capturing crashes. Your statement "The code is called when a unhandled exception occurs but it is not shown as "Crash" in the Application Insights portal. I have read somewhere that TrackException does not count as "Crash" when the application does not really crash." - is true.
Here is the documentation describing it.
If you still want to treat the exceptions that you are handling to be treated as crashes, the one way that you can do that is by treating the tracked exception as unhandled.
Here is how -
var exceptionTelemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(new Exception());
exceptionTelemetry.HandledAt = Microsoft.ApplicationInsights.DataContracts.ExceptionHandledAt.Unhandled;
telemetryClient.TrackException(exceptionTelemetry);
Related
I have written a console application and a companion class library to export some data from a cloud service. The application is called by SQL Server Integration Services which relies on the exit code returned by the application to determine if it worked correctly or not.
Intermittently the application returns an exit code of -532462766 (0xE0434352) which is the generic error code for a .NET unhandled exception. I'm totally flummoxed as to why this is happening.
The log files generated by the applications do not show any issues and they look like everything has completed successfully.
There are no entries in the Application Event Viewer logs.
The application even has an unhandled exception handler:
AppDomain.CurrentDomain.UnhandledException += UnhandledErrorHandler;
...
private void UnhandledErrorHandler(object sender, UnhandledExceptionEventArgs e) {
logWriter.Write(e.ExceptionObject.ToString(), logLevel.Fatal);
logWriter.Write("Exiting now...", logLevel.Fatal);
Dispose();
}
I've even written a batch file to execute the application and log the exit code before passing it along to SSIS. The exit codes that SSIS are receiving are the ones that seem to be returned by the application. But I cannot see an unhandled exception happening anywhere.
The console application returns the exit code by defining Main() like so:
class Program {
static int Main(string[] args) {
...
return (Success) ? 0 : 1;
}
Because it is intermittent (and the data extraction can take a couple of hours) I can't just run it in Visual Studio and debug it. I have a suspicion it might be related to the fact that the application does run for such a long time but I can't seem to confirm that.
Is there anything else that can cause a .NET application to return that exit code? Am I missing something in my troubleshooting?
quick check: wrap your entire code inside a try catch block and save the exception in a log file.
static int Main(string[] args)
{
try
{
//your existing code....
}
catch(Exception Ex)
{
//write your log results here.
}
}
Check if you are using multiple app domains. I encountered this same issue when an exception X was thrown in AppDomain B and could not cross to AppDomain A because it was not serializable. See also best practices for exceptions (search for 'across app domains'):
When you create user-defined exceptions, you must ensure that the
metadata for the exceptions is available to code that is executing
remotely, including when exceptions occur across app domains. For
example, suppose App Domain A creates App Domain B, which executes
code that throws an exception. For App Domain A to properly catch and
handle the exception, it must be able to find the assembly that
contains the exception thrown by App Domain B. If App Domain B throws
an exception that is contained in an assembly under its application
base, but not under App Domain A's application base, App Domain A will
not be able to find the exception, and the common language runtime
will throw a FileNotFoundException exception. To avoid this situation,
you can deploy the assembly that contains the exception information in
two ways:
Put the assembly into a common application base shared by
both app domains.
or
If the domains do not share a common application base, sign the assembly that contains the exception information with a strong name
and deploy the assembly into the global assembly cache.
I am using the following code to check for network access in the start of my application
public async void CheckNetwork()
{
if (!NetworkAvailabilty.Instance.IsNetworkAvailable)
{
MessageDialog Message = new MessageDialog("Network access not available.", "Network Error");
Message.Commands.Add(new UICommand("Close"));
await Message.ShowAsync();
Application.Current.Exit();
}
}
This works as expected in Windows 10 desktop. But when I am running the app in my Phone, it fails to close the app. What could be the reason for this and how to force close my app ?
As a design principle, you are not supposed to manually close an app. Please refer to this link (adressed to WP8 developers, but is still valid).
But, if you are working on a test app for yourself, you can throw an exception which is the only way possible to close the app.
throw new Exception();
Please don't do that if you aim to publish your app on the market :
An unhandled exception in your app consumes resources unnecessarily both on the user’s phone and on the Windows Phone servers.
The phone generates and uploads crash dumps for unhandled exceptions to help you find and fix bugs in your code. Crashing your app to close it wastes the user’s battery power and network bandwidth.
try Application.Current.Terminate() instead of Exit()
Try execute ApplicationView.GetForCurrentView().TryConsolidateAsync().
In some cases my Windows Phone application fails with the ExecutionEngineException.
There are no real steps to reproduce the fail, so I'm not quite sure where to dig in.
The documentation states that this exception is deprecated and no more thrown in the runtime.
Mostly this exception occurs during the navigation between views (At different places in the code). Sometimes I'm getting this exception while trying to get the response. Particular code below:
void ResponseCallback(IAsyncResult ar)
{
var request = ar.AsyncState as HttpWebRequest;
try
{
if (request == null) return;
var response = request.EndGetResponse(ar); // at this point I'm getting the exception.
SetLicenseResponse(response.GetResponseStream());
}
catch (WebException e)
{
Console.LogError("ResponseCallback exception:" + e.InnerException);
}
}
The external libraries used in the application are:
Microsoft.Web.Media.SmoothStreaming
Microsoft.Phone.Controls.Toolkit
As well the application consumes two external web services.
The service reference generated is wrapped in async-await service consumers with the usage of the TaskCompletionSource classes.
As well there are several quite big ListBoxes that are using the VirtualizingStackPanel's as Items Panels.
According to the information I've found in the internet the exception may be caused if garbage collection is invoked from the parallel threads, however I'm not invoking the GarbageCollector in the code explicitly.
Please advice where to start.
Thanks in advance.
Note: The application fails with the particular exception mostly while debugging on the device. I'm not using the emulator for the debugging purposes. I haven't noticed that exception in logs while running the application in normal mode, however there is a possibility that the exception was not handled properly to appear in logs.
I am fairly new to Windows services. I created an installer for my c# Windows service and the installation on the server (Windows Server 2003) appears to have worked. When it's started, it writes Service started successfully to the log. When it's stopped, it writes Service stopped successfully. However, sometimes the service stops running without writing anything to the log, so I start it back up manually. When I look at the log afterward, it says Service started successfully as expected. It's weird seeing that in the log twice in a row being that it's obviously missing an entry where the service had somehow stopped running.
What could be the potential causes for this? I have the service set up as automatic and installed it to run for all users. I was under the impression that this means the service starts automatically whenever the machine boots up. How can I find out why it stopped? Do services that crash automatically write to the event log or do I have to handle exceptions in such a way that they log their own reason for the crash?
Edit: Some additional info:
I have it set up to log on as Local System Account
Under Recovery options, I have it set up to restart on first failure. I don't have anything for second or subsequent failures.
Update: An answerer recommended a global exception handler. While I won't implement this as a permanent fix, it will at least help me figure out where the problem is occurring. I actually tested this with my installed service and it works. I found out that unhandled exceptions actually do crash the service without writing anything to the log at all. I thought it'd at least report some application error, but it doesn't.
static void Main()
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
//other code here
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Utilities.WriteIt(e.ExceptionObject as Exception);
}
It's always best to handle the exceptions. At least use a global exception handler and write it to a logfile
It sounds like your service is failing unexpectedly without doing any form of exception-handling and/or logging. Windows services do not automatically write exceptions to the Event Log - it's up to you to handle exceptions and (if they're fatal) write them out somewhere so that you can diagnose the problem.
At the very least, I'd recommend a logfile somewhere (perhaps in the service executable folder, or preferably somewhere else that's easy to get to and won't run afoul of permissioning issues) and a standard logging method that all your exception-handlers call to write their messages to.
If a service quits unexpectedly because of some exception, I am not sure it would end up in the Event Log automatically.
I would highly recommend a logging suite like log4net for more thorough logging. You'll be able to provide a multitude of logging 'levels' (debug traces to see if you reached some code, info traces for important events, error traces to log exceptions).
You can look here for an example of a EventLogAppender. However, I would suggest starting with getting a FileAppender, one of the easiest logs to create, working first and then add a second appender for the Event Log.
I am using the Mathematica .Net/Link platform to create a web service to format and calculate math problems. However I am unable to get it working.
I create it using this code:
_Log.IpDebug("Starting the Kernel Link");
if (string.IsNullOrEmpty(_MathLinkArguments))
_InternelKernel = MathLinkFactory.CreateKernelLink();
else
_InternelKernel = MathLinkFactory.CreateKernelLink(_MathLinkArguments);
_Log.IpDebug("Kernel Link Started");
_InternelKernel.WaitAndDiscardAnswer();
The value of _MathLinkArguments is -linkmode launch -linkname \"C:\\Program Files\\Wolfram Research\\Mathematica\\7.0\\Math.exe\".
This piece of code is called from the Application_Start method of the global.asax.cs file.
When it gets to the WaitAndDiscardAnswer() call it gives the server error:
Error code: 11. Connected MathLink program has closed the link, but there might still be data underway.
Note: The SampleCode given with the .NET/Link package (both a console app and a WinForms app) works.
Edit:
I copied the console app sample code given with Mathematica into an asp.net page and it gave me the same error the first load and then on subsequent loads it gave me:
Error code: 1. MathLink connection was lost.
Edit2:
I forgot to mention that when I have procmon and task manager open while running my app, I can tell that Math.exe starts but it immediately exits, which makes those error code make complete sense...but doesn't explain why that happened.
To allow the .Net/Link to work in Asp.net (at least in IIS 7.5) you need to enable the property loadUserProfile on the app pool for the web site.
I am not entirely sure why this is the case, but from what I found while trying to debug this, there are some things that are gotten from the user's profile. I know for a fact that the default location of the kernel is, which explains why I couldn't use it with no arguments, and so I can only assume that other things are needed as well and without the profile it couldn't determine that.
But whatever the reason is this is required, it is, or at least it is a fix if you are getting similar problems like this in your own application.
I got the same error in a .Net WinForm application.
mathKernel = new MathKernel();
mathKernel.Compute("<< XYZ`XYZGraphs`");
The error occurred on loading the package straight after instantiating the MathKernel.
To resolve it you can wait a couple of seconds and then instantiating the MathKernel works fine. During this state where there might still be data underway the following conditions are both false:
if (!MathKernel.IsConnected)
{
MathKernel.Connect();
}
if (MathKernel.IsComputing)
{
MathKernel.Abort();
}
Edit:
I've recieved the error again and this time was able to determine the problem.
Using a command line open the MathKernel.exe and view the error message: