Exception in Release mode only while reflectively creating objects - c#

My application is failing only when I attempt to launch it in release mode. Debug mode works fine. I am getting an error that reads
An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll
Additional information: Exception has been thrown by the target of an invocation.
Because this only happens in release, it's been a bit difficult to debug. However, if I uncheck the "Optimize code" checkbox in the project properties, I am able to see an exception thrown in this method:
private static T MakeObject<T>(Type type) where T :class
{
//Default reflective behavior to create an instance with an empty constructor
//
//*note: .GetConstructor can return null.
object obj = null;
T tObj = default(T);
ConstructorInfo ci = type.GetConstructor(TypeInfo.EmptyTypes);
if (ci != null)
{
obj = ci.Invoke(new object[] { /* Empty */});
tObj = obj as T;
}
if (tObj == null)
throw new InvalidCastException("Fatal error occurred within NavigationService (GetConstructor). Type: " + type.ToString());
return tObj;
}
on this line:
ConstructorInfo ci = type.GetConstructor(TypeInfo.EmptyTypes);
The exception reads:
An exception of type 'System.NullReferenceException' occurred in LWDCloudManager.exe but was not handled in user code
Additional information: Object reference not set to an instance of an object.
Does anyone have any suggestions on how I might be able either fix this issue, or how to dig deeper and understand why this could be happening in release mode only?

I discovered the problem. Actually kind of a stupid problem/oversight by me. Recently my company decided that instead of throwing exceptions in internal methods, we would just use Debug.Asserts, so I went and changed all of them. One of the lines of code ahead of this issue was a debug assert wrapped around a call to a TryGetValue call on a dictionary. Because I was attempting to run in release mode, the debug.assert was not executed, thus the value was not retrieved from the dictionary resulting in a null being passed. Thanks for the help guys

Related

An assignment generates a System.NullReferenceException

IObjectVmFactory objectVMFactory = this.Container.Resolve<IObjectVmFactory>();
This throws a NullReferenceException.
If I do not assign the result of this.Container.Resolve to a variable, it does not throw:
this.Container.Resolve<IObjectVmFactory>().AnyMethod(...)
This has no sense to me ... someone can give me some explanation?
Extra information:
this.Container is not null for sure. Triple checked. And if it was null the second line would fail.
The class implementing IObjectVmFactory has no defined constructor so the exception is not happening inside the IObjectVmFactory implementation.
The exception has no inner exceptions and points directly to the first line.
Executing the line directly on the Inmediate Window generates a ('' is null) message.
Thanks!
My project's configuration was in Release, not Debug. In release mode, it throws an exception at the assignment. In debug, it throws on the step AFTER the assignment:
Foo member { get; }
public Bar(Foo foo)
{
// crashes here on release
member = foo;
// crashes here in debug (foo.Collection was null)
foreach (var thing in foo.Collection)
thing.DoSomething();
}
So it looks like having the project's configuration in release may cause the error. Try switching the configuration to debug and find where it's failing.
Go to Build -> Configuration Manager
Select your project
Change the configuration from Release to Debug.
Build and see if the error occurs at the same place.

Better TypeInitializationException (innerException is also null)

Intro
When an user creates a mistake in the configuration of NLog (like invalid XML), We (NLog) throw a NLogConfigurationException. The exception contains the description what is wrong.
But sometimes this NLogConfigurationException is "eaten" by a System.TypeInitializationException if the first call to NLog is from a static field/property.
Example
E.g. if the user has this program:
using System;
using System.Collections.Generic;
using System.Linq;
using NLog;
namespace TypeInitializationExceptionTest
{
class Program
{
//this throws a NLogConfigurationException because of bad config. (like invalid XML)
private static Logger logger = LogManager.GetCurrentClassLogger();
static void Main()
{
Console.WriteLine("Press any key");
Console.ReadLine();
}
}
}
and there is a mistake in the config, NLog throws:
throw new NLogConfigurationException("Exception occurred when loading configuration from " + fileName, exception);
But the user will see:
"Copy exception details to the clipboard":
System.TypeInitializationException was unhandled
Message: An unhandled exception of type 'System.TypeInitializationException' occurred in mscorlib.dll
Additional information: The type initializer for 'TypeInitializationExceptionTest.Program' threw an exception.
So the message is gone!
Questions
Why is innerException not visible? (tested in Visual Studio 2013).
Can I send more info to the TypeInitializationException? Like a message? We already sending an innerException.
Can we use another exception or are there properties on Exception so that more info is reported?
Is there another way to give (more) feedback to the user?
Notes
of course we have no influence on the program written by the user.
I'm one of the maintainers of NLog.
Do you like to test it by yourself? Checkout https://github.com/NLog/NLog/tree/TypeInitializationException-tester and start NLog/src/NLog.netfx45.sln
Edit:
please note that I'm the library maintainer, not the user of the library. I cannot change the calling code!
I'll just point out the underlying problem you are dealing with here. You are fighting a bug in the debugger, it has a very simple workaround. Use Tools > Options > Debugging > General > tick the "Use Managed Compatibility Mode" checkbox. Also untick Just My Code for the most informative debugging report:
If Just My Code is ticked then the exception report is less informative but still can be drilled down easily by clicking the "View Detail" link.
The option name is unnecessarily cryptic. What it really does is tell Visual Studio to use an older version of the debugging engine. Anybody that uses VS2013 or VS2015 will have this trouble with the new engine, possibly VS2012. Also the basic reason that this issue did not have be addressed in NLog before.
While this is a very good workaround, it is not exactly easy to discover. Nor would programmers particularly like to use the old engine, shiny new features like return value debugging and E+C for 64-bit code are not supported by the old engine. Whether this is a truly a bug, an oversight or a technical limitation in the new engine is hard to guess. This is excessively ugly so don't hesitate to label it "bug", I strongly recommend you take this to connect.microsoft.com. Everybody will be ahead when it gets fixed, I scratched my head over this at least once that I remember. Drilled it down by using Debug > Windows > Exceptions > ticked CLR Exceptions at the time.
A workaround for this very unfortunate behavior is sure to be ugly. You do have to delay raising the exception until program execution has progressed far enough. I don't know your codebase well enough, but delaying parsing the config until the first logging command ought to take care of it. Or store the exception object and throw it on the first log command, probably easier.
The reason I see is because the Type initialization of Entry point class is failed. Since no type was initialized, so the Type loader has nothing to report about the failed type in TypeInitializationException.
But if you change the Static initializer of logger to other class and then refer that class in Entry method. you'll get the InnerException on TypeInitialization exception.
static class TestClass
{
public static Logger logger = LogManager.GetCurrentClassLogger();
}
class Program
{
static void Main(string[] args)
{
var logger = TestClass.logger;
Console.WriteLine("Press any key");
Console.ReadLine();
}
}
Now you'll get the InnerException because the Entry type was loaded to report the TypeInitializationException.
Hope now you get the idea to keep the Entry point clean and Bootstrap the application from Main() instead of static property of Entry point class.
Update 1
You can also utilize the Lazy<> to avoid the execution of configuration initialization at declaration.
class Program
{
private static Lazy<Logger> logger = new Lazy<Logger>(() => LogManager.GetCurrentClassLogger());
static void Main(string[] args)
{
//this will throw TypeInitialization with InnerException as a NLogConfigurationException because of bad config. (like invalid XML)
logger.Value.Info("Test");
Console.WriteLine("Press any key");
Console.ReadLine();
}
}
Alternatively, try Lazy<> in the LogManager for logger instantiation so that the configuration initialization happens when actually the first log statement occurs.
Update 2
I analyzed the source code of NLog and seems like it's already implemented and It make sense. According to the comments on property "NLog should not throw exception unless specified by property LogManager.ThrowExceptions in LogManager.cs".
Fix - In the LogFactory class the private method GetLogger() has the initialization statement which is causing the exception to happen. If you introduce a try catch with the check of property ThrowExceptions then you can prevent the initialization exception.
if (cacheKey.ConcreteType != null)
{
try
{
newLogger.Initialize(cacheKey.Name, this.GetConfigurationForLogger(cacheKey.Name, this.Configuration), this);
}
catch (Exception ex)
{
if(ThrowExceptions && ex.MustBeRethrown())
throw;
}
}
Also it would be great to have these exceptions/errors stored somewhere so that It can be traced why Logger initialization failed because the they were ignored due to ThrowException.
I said in an earlier comment that I'm unable to reproduce your issue. Then it occurred to me you were only looking for it in the popup exception dialog, which doesn't display a show details link.
So here's how you can get at the InnerException anyway, because it definitely is there, except Visual Studio doesn't report it for some reason (probably because it's in the entry point type as vendettamit figured out).
So, when you run the tester branch, you get the following dialog:
And it doesn't show the View Details link.
The Copy exception detail to the clipboard isn't particularly helpful either:
System.TypeInitializationException was unhandled
Message: An unhandled exception of type 'System.TypeInitializationException' occurred in mscorlib.dll
Additional information: The type initializer for 'TypeInitializationExceptionTest.Program' threw an exception.
Now, dismiss the dialog with the OK button and head towards the Locals debug window. Here's what you'll see:
See? The InnerException definitely is there, and you found a VS quirk :-)
Problem is the static initialization happens when the class is first referenced. In your Program it happens even before the Main() method. So as rule of thumb - avoid any code that can fail in static initialization method. As for your particular problem - use lazy approach instead:
private static Lazy<Logger> logger =
new Lazy<Logger>(() => LogManager.GetCurrentClassLogger());
static void Main() {
logger.Value.Log(...);
}
So the initialization of logger will happen (and possibly fail) when you'll first access the logger - not in some crazy static context.
UPDATE
It is ultimately burden of user of your library to stick to the best practices. So if it were me I'd keep it as it is. There are few options though if you really have to solve it on your end:
1) Don't throw exception - ever - this is valid approach in logging engine, and how log4net works - i.e.
static Logger GetCurrentClassLogger() {
try {
var logger = ...; // current implementation
} catch(Exception e) {
// let the poor guy now something is wrong - provided he is debugging
Debug.WriteLine(e);
// null logger - every single method will do nothing
return new NullLogger();
}
}
2) wrap the lazy approach around the implementation of Logger class (I know your Logger class is much more complex, for sake of this problem let's assume it has just one method Log and it takes string className to construct Logger instance.
class LoggerProxy : Logger {
private Lazy<Logger> m_Logger;
// add all arguments you need to construct the logger instance
public LoggerProxy(string className) {
m_Logger = new Lazy<Logger>(() => return new Logger(className));
}
public void Log(string message) {
m_Logger.Value.Log(message);
}
}
static Logger GetCurrentClassLogger() {
var className = GetClassName();
return new LoggerProxy(className);
}
You'll get rid of this problem (the real initialization will happen while first log method is called and it is backward-compatible approach); only problem is you've added another layer (I don't expect any drastic downgrade of performance, but some logging engines are really into micro-optimization).
The only solution I see now is:
move the static initializes (fields) to a static constructor with a try catch
System.TypeInitializationException is always or almost always occurred from not correct initialisation the static members of a class.
You have to check LogManager.GetCurrentClassLogger() via debugger. I'm sure the error is occurred inside that part of code.
//go into LogManager.GetCurrentClassLogger() method
private static Logger logger = LogManager.GetCurrentClassLogger();
Also i suggest you double check your app.config and make sure you haven't included anything wrong.
System.TypeInitializationException is thrown whenever a static constructor throws an exception, or whenever you attempt to access a class where the static constructor threw an exception.
When .NET loads the type, it must prepare all it's static fields before the first time that you use the type. Sometimes, initialization requires running code. It is when that code fails that you get a System.TypeInitializationException.
According the docs
When a class initializer fails to initialize a type, a TypeInitializationException is created and passed a reference to the exception thrown by the type's class initializer. The InnerException property of TypeInitializationException holds the underlying exception.
TypeInitializationException uses the HRESULT COR_E_TYPEINITIALIZATION, that has the value 0x80131534.
For a list of initial property values for an instance of TypeInitializationException, see the TypeInitializationException constructors.
1) The InnerException is not visible it is very typical for this type of Exception. The version of Visual Studio doesn't matter (ensure that the "Enable the exception assistant" option is checked - Tools> Options>Debugging>General)
2) Usually the TypeInitializationException hides the real exception which can be viewed via InnerException. But the test example below shows how you can populate inner exception info:
public class Test {
static Test() {
throw new Exception("InnerExc of TypeInitializationExc");
}
static void Main(string[] args) {
}
}
But sometimes this NLogConfigurationException is "eaten" by an
System.TypeInitializationException if the first call to NLog is from a
static field/property.
Nothing strange. Someone missed the try catch block somewhere.

'System.Reflection.TargetInvocationException' when calling Activator.CreateInstance()

I am receiving this error:
A first chance exception of type 'System.Reflection.TargetInvocationException'
occurred in mscorlib.dll
and also:
Exception has been thrown by the target of an invocation.
when running this method, and the error is occurring on the CreateInstance(Type.GetType(instantiationString), parameters) call:
public static Report instantiateReport(ReportInfo reportInfo)
{
string instantiationString;
Report reportToReturn;
ReportInfo[] parameters = new ReportInfo[1];
parameters[0] = reportInfo;
instantiationString = reportInfo.Report.InstantiationPath;
reportToReturn = (Report)Activator.CreateInstance(Type.GetType(instantiationString), parameters);
return reportToReturn;
}
ReportInfo is just a custom class that contains variables that help me build the report that I am trying to instantiate and when I investigate it, everything is completely fine. The instantiationString just helps me understand which report is trying to be created at the call and that way I can use the Type.GetType() method. I really have no idea what kind of error this is or what could be going wrong. I researched it a bit but didn't receive any helpful answer so any help is appreciated.
EDIT After looking at the inner exception I am getting Object reference not set to an instance of an object. message. This is strange because neither the ReportInfo or the GetType() methods have a null reference. Say one of the variables within ReportInfo was null, could that cause an issue? It shouldn't right?
FIXED After delving into the stack trace of the inner exception I found that there was some conflicting code causing issues elsewhere. Problem solved.

Is that possible to capture which object on Object reference not set to an instance of an object. error

I have an ASP.net website with C#. Current framework is 4.5
I have a global unexpected error catching function.
It is located at global.asax
Here how i catch
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
if (Server.GetLastError() != null)
if (Server.GetLastError().GetBaseException() != null)
{
Exception objErr = Server.GetLastError().GetBaseException();
ErrorLogger.LogError(Request.Url.ToString(), objErr.Message.ToString(), objErr.StackTrace.ToString());
if (objErr.Message.IndexOf("does not exist") != -1)
{
Response.RedirectPermanent("Error404.aspx");
}
}
}
Now it catches errors and many times there are plenty of information to debug the error. However there is 1 error that i can not get enough information.
It is Object reference not set to an instance of an object.
It doesn't give any information about which object it is. Are there any way to get more information about it ?
Here a typical error
Object reference not set to an instance of an object.
at gamepage.Page_Load(Object sender, EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Thank you very much for answers.
A NullReferenceException does not carry information about the variable which is null, no.
It doesn't give any information about which object it is.
That's just it... it isn't an object. It's a reference to where an object is expected, but there's no object there. null is literally the absence of information.
The way to handle a NullReferenceException is to carefully craft your code so that either:
It doesn't happen, or
It happens in a potentially expected way, and you check for it and either throw a custom informative exception (which can still be a NullReferenceException with simply a custom message) or in some way log/persist the information and meaningfully continue execution of the application.
Since no code or developer is perfect, it's fully expected that from time to time one will slip through the checks and balances. This is ok. It should be easy to identify which object is null in this case. The stack trace should point to a specific method (perhaps even a specific line of code, depending on what information is available to the runtime) and there shouldn't be a whole lot of potential NullReferenceExceptions there. If there are, the method is sloppy and should be cleaned up anyway.
When it happens, identify the object which was null by debugging and investigation, and update the code to handle the potential null case for that object.
One thing you could do to help with tracking down the problem would be to find the method that has errored, and possibly even the line of code within that by performing a runtime stacktrace, something like:
var st = new StackTrace();
var errorInfo = String.Join("...", st.GetFrames().Select(x =>
{
var m = x.GetMethod();
var t = m.DeclaringType;
return String.Format("{0}.{1} # {2}:{3}:{4}", t == null ? "" : t.Name, m.Name, x.GetFileName(), x.GetFileLineNumber(), x.GetFileColumnNumber());
});
that will allow you to find the code and fix it. I've not used such an approach in a global error trap such as the Application_Error event handler you are using, but I have used this approach to see where calls are coming from in other scenarios successfully, often to track down event handlers that are subscribed to an event.
Use try..catch when you use any object and throw error with inner exception and stacks trace so you can log that error and get more information about specific error.

Log external but not own assembly first chance exceptions

Catching Own First Chance Exceptions
AppDomain.CurrentDomain.FirstChanceException += FirstChanceException;
private static void FirstChanceException(object sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e)
{
// I would like to log exceptions happening outside my assembly?
// But this event does not receive external FirstChanceExceptions
// (unlike Visual Studio debug output)
myLogger.Log(e.Exception);
}
Example
I would like to log A first chance exception of type 'System.IO.IOException' occurred in WindowsBase.dll
But not log A first chance exception of type 'System.DivideByZeroException' occurred in MyApp.exe
Solution?
Is there a way to get notified of those exceptions arising in dlls such as mscorlib.dll?
Note the interest is to log in the production release, not only in debugging.
Why
Exceptions that occur in external dll dependencies can cause trouble, even if they are handled there.
For example, due to an exception a null value may be returned from an external method (instead of returning the desired output of x) and even though my code mostly handles such abnormal output it is useful to know what exactly went wrong and where - because while I may be able to avoid fatal exceptions then more often than not that null value makes part of my app non-functional. So logging the external first chance exception would provide valuable information to help rectify the issue / turn that null into x. And this may be present in only given environments / for specific users etc...
You can use StackTrace class to check what is the source of the exception:
var stackTrace = new StackTrace(e.Exception);
var sourceFrame = stackTrace.GetFrame(0);
var throwingMethod = sourceFrame.GetMethod();
var sourceAssembly = throwingMethod.DeclaringType.Assembly;
var assemblyName = sourceAssembly.GetName().Name;
bool isMyApp = assemblyName == "MyApp";

Categories

Resources