System.TypeInitializationException - c#

I am writing tests to test Infopath Forms to open in Form Control, my test method is as
[TestMethod]
public void Validate_OpenInfopathInFormControl()
{
Helper.OpenForm();
//Other Code
}
I have written Helper class as
public class Helper
{
public static void OpenForm()
{
//Code to Open Form
}
}
But everytime I execute this code, this gives me:
Test method
InfoPathTest.TestAPI.Validate_OpenInfopathInFormControl
threw exception:
System.TypeInitializationException:
The type initializer for
'InfoPathTest.Helpers.Helper' threw an
exception. --->
System.NullReferenceException: Object
reference not set to an instance of an
object..
When I try to debug, it fails when Helper class needs to be initialized. This is really eating my head, is there any solution for this?
Here is the complete helper class:
namespace InfoPathTest.Helpers
{
public class Helper
{
//This is the form i need to OPEN
private static MainForm f = new MainForm();
private static bool _isOpen = false;
public static bool isOpen
{
set { _isOpen = value; }
get { return _isOpen; }
}
public static void OpenForm()
{
try
{
f.Show();
}
catch (Exception ex)
{
throw ex;
}
_isOpen = true;
}
public static void CloseForm()
{
f.Hide();
}
}
}

Your test calls Helper.OpenForm() and as you have no static constructor, the only thing I can see that would cause the exception to be thrown is:
private static MainForm f = new MainForm();
Therefore something in the constructor for MainForm is likely throwing an exception. Put a breakpoint on the first line of the constructor for MainForm and step through until you see where the exception is thrown.
Alternatively you might find it easier to determine what the problem is, at least initially, by writing a new test you can step through that calls new MainForm() directly:
[TestMethod]
public void Validate_OpenInfopathInFormControl()
{
var form = new MainForm();
}
Put a breakpoint on the only line of the test and step into the constructor to determine why it's throwing a NullReferenceException.

The type initialiser, in this case, is where your static fields are initialised; That is, these two lines:
private static MainForm f = new MainForm();
private static bool _isOpen = false;
The initialisation of a bool isn't going to cause any kind of exception, so it's highly likely that the source of the error is in the MainForm constructor.
Does the TypeInitializationException object contain any inner exceptions? If so, they should give you more info about the real cause of the error.

You have an error in your static constructor (they are called Type Initializers). The inner exception is a NullReference exception. If you post your code we might be able to help you.
The rules determine when type initializers get run are complex, but it is guaranteed that they are run before you access the type in any way. It might not be directly obvious to you that you have a type initializer on your Helper class because you might use implicit initialization:
public class Helper
{
static int i = 10; // This assignment will end up in a type initializer
static Helper()
{
// Explicit type initializer
// The compiler will make sure both, implicit and explicit initializations are run
}
}

Related

C# Unity > Static instance member not causing constructor to be called

I have noticed a rather weird behaviour in my application I am creating;
I have a class I defined that has a static "instance" variable of the class type.
I would assume that (as per code attached) the constructor would be called.
Alas, it is not, unless I use the Void.get in a non-static field anywhere in my code.
public class Void : TilePrototype {
public static Tile get = new Tile((int)TileEntities.Void);
public static Void instance = new Void();
public Void() {
Debug.Log("created");
id = (int)TileEntities.Void;
isBlocking = true;
register();
}
public override RenderTile render(Tile tile){
return new RenderTile(0, new Color(0, 0, 0, 0));
}
So when I have something like :
public static TileStack empty = new TileStack(Void.get, Void.get);
the Void class constructor never gets called. But, if I have:
Tile t = Void.get;
Anywhere in my code it will be called.
Why?
Thanks.
This is a really really subtle and nuanced area of C#; basically, you've stumbled into "beforefieldinit" and the difference between a static constructor and a type initializer. You can reasonably ask "when does a static constructor run?", and MSDN will tell you:
It is called automatically before the first instance is created or any static members are referenced.
Except... public static TileStack empty = new TileStack(Void.get, Void.get); isn't a static constructor! It is a static field initializer. And that has different rules, which basically are "I'll run when I must, no later, possibly sooner". To illustrate with an example: the following will not (probably) run your code, because it doesn't have to - there isn't anything demanding the field:
class Program
{
static void Main()
{
GC.KeepAlive(new Foo());
}
}
public class Foo
{
public static TileStack empty = new TileStack(Void.get, Void.get);
}
However, if we make a tiny tweak:
public class Foo
{
public static TileStack empty = new TileStack(Void.get, Void.get);
static Foo() { } // <=== added this
}
Now it has a static constructor, so it must obey the "before the first instance is created" part, which means it needs to also run the static field initializers, and so on and so on.
Without this, the static field initializer can be deferred until something touches the static fields. If any of your code actually touches empty, then it will run the static field initializer, and the instance will be created. Meaning: this would also have this effect:
class Program
{
static void Main()
{
GC.KeepAlive(Foo.empty);
}
}
public class Foo
{
public static TileStack empty = new TileStack(Void.get, Void.get);
}
This ability to defer execution of the static initialization until the static fields are actually touched is called "beforefieldinit", and it is enabled if a type has a static field initializer but no static constructor. If "beforefieldinit" isn't enabled, then the "before the first instance is created or any static members are referenced" logic applies.
Thanks to Marc Gravell's aswer I came up with this contraption (and admittedly I do like the new solution more than the old one, so thanks again!)
Modifications done to the Void class:
public class Void : TilePrototype {
public static Void instance = new Void();
public static Tile get {
get {
return new Tile(instance.id);
}
}
public Void() {
isBlocking = true;
}
public override RenderTile render(Tile tile){
return new RenderTile(0, new Color(0, 0, 0, 0));
}
}
So as You can see I made the "get" variable a property, so that it's evaluated later, when you actually need the tile, not on construction.
I've changed all "get"s this way.
Second change is in the TilePrototype:
public class TilePrototype {
public static Dictionary<int, TilePrototype> tilePrototypeDictionary = new Dictionary<int, TilePrototype>();
public static void registerPrototype(int id, TilePrototype tp){
tp.id = id;
tilePrototypeDictionary.Add(id, tp);
}
public static bool registered = false;
public static void registerAll(){
if( registered ) return;
registerPrototype(0, Void.instance);
registerPrototype(1, Air.instance);
registerPrototype(2, Floor.instance);
registerPrototype(3, Wall.instance);
(...)
Here I've added the registerPrototype and registerAll functions.
This gives me easy access to all the registered type ids (by say Wall.instance.id) as well as the other way around (from id to instance via the Dictionary)
I also have all registered things in one place, with the possibility of runtime adding more
Overall, much neater, and here I assure that all tiles are registered properly and assigned proper IDs.
Change of ID is simple and in one place and everywhere else, access to this ID is done via a short .instance.id
Thanks again for the help :)

C# Exception Listener

C# Question. Arbitrary class Class has method Foo(), a method which can throw an exception. Is there some way to add a private callback mechanism bar() to Class, such that if Foo() throws an exception, bar() execution will be triggered before the throw keeps going up the chain? If that can't happen, what about after the exception is caught?
-- Edit --
Since some of the initial comments are "this is confusing what are you doing dude" I'll address it further.
The reason I would like an exception listener is because I have some publicly readable boolean state about class Class, which I want to be set to true whenever an exception has been thrown. Since there could be potentially multiple functions within Class which throw exceptions, I don't want to do the boiler plate work of setting hasError to true each time an exception is thrown. Automate, baby.
So our interface, and main function are:
public interface IObjectProvider
{
IEnumerable<object> Allobjects { get; }
}
public interface IContext
{
delegate bool ContextIsStillValid(object o);
delegate void Run(object o);
}
// main program
public static void Main() {
IContext context = initcontext(...);
IObjectProvider objectProvider = initobjectprovider(...);
// ...program executes for awhile...
foreach(var obj in objectProvider.AllObjects)
{
if(context.ContextIsStillValid(obj))
{
try
{
context.Run(obj);
}
catch(Exception e)
{
// log the error
}
}
}
}
In the above code snippet, we specify some IContext which will 'Run' using some object, if and only if that IContext first successfully passes a 'Validation' check using that same object. Fine. Now, a common variation of implementation for IContext is the following (take my word, it is):
public class Class : IContext {
private bool _hasError = false;
// so our validation check is implemented with an internal flag.
// how is it set?
public bool ContextIsStillValid = (o) => !_hasError;
public void Run =
(o) =>
{
string potentially_null_string = getstring(...);
if(potentially_null_string == null)
{
// our internal flag is set upon the need to throw an exception
this._hasError = true;
throw new Exception("string was null at wrong time");
}
Global.DoSomethingWith(potentially_null_string.Split(',');
};
}
Here, we've demonstrated a common implementation of IContext, such that once the Run method throws a single Exception, the Run method should become unreachable due to IsContextStillValid subsequently always returning false.
Now imagine that there are other Exception-throwing calls within our implementation of Run(object). The problem is that every time we want to throw a new exception, we have to duplicate code to the effect of _hasError = true; throw new Exception(...);. Ideally, an exception listener would resolve this issue for us, and I am curious if any of you know how to implement one.
Hope that helps.
public class MyClass
{
public void Foo()
{
try
{
//Execute some code that might fail
}
catch
{
bar();
throw;
}
}
private void bar()
{
//do something before throwing
}
}

Method may only be called on a Type for which Type.IsGenericParameter is true and The type initializer for 'XYZ' threw an exception

I have a set up similar to this:
Program.cs
{
public static void Main(string[] args)
{
XYZ.SomeMethod(); //--> XYZ is accessed for the firsttime here
}
private void OnDBInstall(object sender, EventArgs e)
{
//after Db install is complete
if(success)
{
InvokeMethod(SomeEvent) //-->this is the second time XYZ is accessed
}
}
}
public static class Utility
{
public static void InvokeSomeMEthods(EventHandler<T> h)
{
if(h!=null)
{
foreach(EventHandler<T> eh in h.GetInvocationList())
{
eh.Invoke(null, EventArgs.Empty);
}
}
}
}
public static class XYZ
{
private static XYZCache _cache = new XYZCache();
static XYZ()
{
SomeEvent += OnSomeEvent;
_cache.Initialize();
}
static void OnSomeEvent(object sender, EventArgs e)
{
_cache.Initialize();
}
static void SomeMethod()
{
//some db call
}
}
internal class XYZCache
{
internal void Initialize()
{
//some db call
}
}
I get multiple exceptions at different stages. When XYZ.SomeMethod() is called the first time, I get, "Cannot open database ".." requested by the login. The login failed". OK this is good because the database doesn't exist at that point. I should have checked if the DB exist first before making any Db calls. And this exception is left unhandled.
Then the other exceptions I get at eh.Invoke (DB is created and available at this point): "The type initializer for 'XYZ' threw an exception", "Method may only be called on a Type for which Type.IsGenericParameter is true.", and I also get "Cannot open database ".." requested by the login. The login failed". When I get these exception, OnSomeEvent in XYZ class is not even invoked so _cache is not accessed.
"The type initializer for 'XYZ' threw an exception" is very misleading since this is not the first time XYZ is accessed.
if XYZ.SomeMethod() is wrapped by a try catch, then everything is good. Is there a way to handle this situation without try catch? I also cannot check for the DB existence because of some weird reason.
Note: I already read this post this is very useful: Method may only be called on a Type for which Type.IsGenericParameter is true

Multiple events get different instances of a field declared in singleton?

Edit: My bad, no strage events behavior. Error was somewhere else in code. Thx everybody for help. Please ignore this question
Please can someone explain to me what is happening here. I'm experiencing an unexpected event behaviour.
There is a singleton class:
internal class QueueListener
{
private static readonly object QueueChangeLock = new object();
private readonly List<IQueuedJobExecutioner> jobsQueue = new List<IQueuedJobExecutioner>();
// Here comes singleton private constructor, Instance property, all classic.
// Important line in constructor is this:
QueueManager.NewJobQueued += NewJobQueuedHandler;
private void NewJobQueuedHandler(object sender, NewJobQueuedEventArgs args)
{
lock (QueueChangeLock)
{
// This is the problematic place, note this!
jobsQueue.Add(args.QueuedJobExecutioner);
}
}
}
Now there is a second class:
public class QueueManager
{
public static event NewJobQueuedEventHandler NewJobQueued;
protected void RaiseNewJobQueuedEvent(IQueuedJobExecutioner queuedJobExecutioner)
{
if (NewJobQueued != null)
{
NewJobQueued(this, new NewJobQueuedEventArgs { QueuedJobExecutioner = queuedJobExecutioner });
}
}
}
Both classes reside on a server. Via WCF calls client executes sth like new QueueManager().MyMethod(), which calls RaiseNewJobQueuedEvent.
Everything works fine, however if two events are raised almost at the same time, I see in debugger the following at the problematic place (see comment in QueueListener):
First event comes. jobsQueue has no members.
jobsQueue.Add() is executed. jobsQueue has 1 member.
Second event comes. jobsQueue has no members! How? It's in a singleton and we just added a member!
jobsQueue.Add() is executed. jobsQueue has 1 member. Again. Member added in step 2 has been lost.
Not judging the design itself (it has some "historical" reasons), why exactly is this happening? Is this expected behavior and event somehow gets at some point a snapshot of jobsQueue or this is nonesense and I'm just missing some part of the puzzle?
Edit:
I'd say it is a singleton, and is implemented like this (these lines were omitted in original post):
class QueueListener
{
private static readonly object SyncRoot = new object();
private QueueListener()
{
//...
}
public static QueueListener Instance
{
get
{
if (instance == null)
{
lock (SyncRoot)
{
if (instance == null)
{
instance = new QueueListener();
}
}
}
return instance;
}
}
}
Yuval is correct, your class is not a singleton. A singleton is created when you have a public static method to create an instance and a private constructor. The private constructor ensures that the only way to create an instance is through the public method.
Please see https://msdn.microsoft.com/en-us/library/ff650316.aspx for more details.
Your QueueListener class is not actually a singleton. What that means for you is that you are creating multiple instances of it. To fix that you have to add the static keyword in the class declaration and declare a static constructor as well. Try changing your class to what is shown below:
internal static class QueueListener
{
private static readonly object QueueChangeLock = new object();
private static readonly List<IQueuedJobExecutioner> jobsQueue = new List<IQueuedJobExecutioner>();
// This is the singleton constructor that will be called
static QueueListener()
{
// Here comes singleton private constructor, Instance property, all classic.
// Important line in constructor is this:
QueueManager.NewJobQueued += NewJobQueuedHandler;
}
// Rest of class code...
}

How constructor calling occurs in case of c# custom exception handling?

Here's is my program
class Program
{
static void Main(string[] args)
{
throw new UserAlreadyLoggedInException("Hello");
}
}
public class UserAlreadyLoggedInException : Exception
{
public UserAlreadyLoggedInException(string message) : base(message)
{
Console.WriteLine("Here");
}
}
Now, I know that base class constructor runs before derived class constructor. But when I run the above code the output comes out to be
Here
Unhandled Exception:Testing.UserAlreadyLoggedInException:Hello.
How come "Here" is printed before Unhandled.....?
You first have to create the exception, before you can be thrown.
Creation of the exception instance initiated by new UserAlreadyLoggedInException;
UserAlreadyLoggedInException constructor called;
Call to Console.WriteLine inside constructor;
Constructor done;
Throwing of the newly created exception instance;
The exception isn't handled, thus the application error handler writes the error to the console.
Why don't you try this:
static class Program
{
static void Main()
{
throw new UserAlreadyLoggedInException("Hello");
}
}
class LoginException : Exception
{
public LoginException(string message) : base(message)
{
Console.WriteLine("least derived class");
}
}
class UserAlreadyLoggedInException : LoginException
{
public UserAlreadyLoggedInException(string message) : base(message)
{
Console.WriteLine("most derived class");
}
}
You can also try writing your Main method like this:
static void Main()
{
var ualie = new UserAlreadyLoggedInException("Hello");
Console.WriteLine("nothing bad has happened yet; nothing thrown yet");
throw ualie;
}
So constructing an Exception instance with the new keyword does not "raise" or "throw" an exception. You need throw for that. The throw statement works by first evaluating the expression that comes after the throw keyword. The result of that evaluation will be a reference to an exception instance. After evaluating the expression, throw "throws" the exception referred by the value of the expression.
Your misunderstanding is that the Exception "explodes" as soon as the instance constructor to System.Exception runs. That is not the case.
If you add a try/catch of your own the program flow becomes more apparent. Note that Exception's constructor does not write anything it just stores the message string for later use.
class Program
{
static void Main(string[] args)
{
try
{
throw new UserAlreadyLoggedInException("Hello");
}
catch (Exception e)
{
Console.WriteLine("My handled exception: {0}", e.Message);
}
}
}
public class UserAlreadyLoggedInException : Exception
{
public UserAlreadyLoggedInException(string message) : base(message)
{
Console.WriteLine("Here");
}
}
The exception is printed to the console after it has been instantiated and thrown.
The instantiation prints "Here", then the runtime catches it and prints the "Unhandled Exception:" ToString() representation.

Categories