Nullreference exception was unhandled - c#

I am creating a microsoft WPF project and ran into the following hindrance:
Null reference was unhandled Object reference not set to an instance of an object
My VS 2010 points to the following line of code:
string connectionString = ConfigurationManager.ConnectionStrings["Lab06Wpf.Properties.Settings.AppConnectionString"].ConnectionString;
Not sure why this is happening, I have a similar project where I have a similar connection string and it runs itself just fine.
The ConnectionStrings argument Lab06Wpf.Properties.Settings.AppConnectionString is valid and the connection has been tested.
Any leads anyone?

ConfigurationManager.ConnectionStrings["Lab06Wpf.Properties.Settings.AppConnectionString"]
That is returning null and your are calling ConnectionString on it. You need to find out why it is returning null. Use your debugger to see what ConnectionStrings contains and why your call is failing.

Related

LINQ-to-SQL DataContext is null on certain server

I have a very unusual problem. I have an ASP.NET application that uses LINQ-to-SQL a lot, and works fine on most servers. However the application exists on another server on the same network, and after a recent update, whenever I open a new DataContext like this:
LINQDataContext dc = new LINQDataContext();
The dc object is null, so I get object reference errors trying to use it. I cannot replicate this on my development machine, or on the other server which the application exists on, so I'm baffled about why this could be. Any ideas?
Since you are using default constructor of your DataContext, then connection string is read from web.config. So we could make a suggestion that application on that server has different config without proper connection string. But there is one more thing that we've faced once in our project. In a new version of ASP location of connection string storage in config file has changed. I don't have code at my fingertips, but you could test my suggestion by using constructor that takes connection string as a parameter. Read connection string from config manually or just hardcode it for testing purpose.
Something like this can't happen. When you call the new operator on a standard .Net type, there are two possible outcomes:
the constructor returns normally and the value is assigned
the constructor throws an exception, the value is not assigned
Unless you catch the exception right away, and ignore it, you can be sure that the variable has been assigned. This means your problem probably lies somewhere else.
(Technically, there is a third option – the constructor never returns and loops infinitely, but that's not relevant here.)

C# says my namespace causes a NullReferenceException

So I got the dreaded "yellow screen of death"(? that's what the .NET guys called it) with the error message:
[NullReferenceException: Object reference not set to an instance of an object.]
OK, that's fine, I can understand that, but the error references a line of code which reads:
<namespace1>.<namespace2>.XMLDohickey responseXML =
new <namespace1>.<namespace2>.XMLDohickey();
(names obscured to protect the innocent (: ).
I can easily see how the line after, Session[<value>].ToString();, could cause this error, but I don't understand how the error could be caused by the line it claims to be caused by.
So, is it that C# is telling me the wrong line number, or can a namespace actually be null?
As a side note -- this seems to work fine locally, on my company's DEV and QA servers, but it seems like it failed on our client's QA server...
EDIT
So... here's the deal.
Apparently, when .NET crashes, sometimes it returns the last successful line called instead of the line which actually held the error. In this case, the Session[<value>] was null (Why? No idea. that "Should never happen").
A namespace can never be null, it will never generate any runtime errors of any kind (in the way you are describing it). So your null reference is probably in Session[key].ToString(), or the constructor of XMLDoHickey. I would consider checking if the value in the session state exists before calling a method on it.
Are you sure the exception doesn't come from inside the XMLDohickey constructor?
You need to force a recompilation and probably also clear the temporary internet files.
THere are often mismatches in the line numbers and the actual instruction causing the exception when source and binaries get out of sync and this must be the case here since namespaces surely dont cause null reference exceptions :)

Object reference not set

I have a Asp.net-C# Web app, with 4-5 associated projects all written in c#. I'm using .net 3.5.
My problem is, when I try running my application from the solution, it shows an error:
"Error 17 Object reference not set to an instance of an object"
When I build/rebuild the solution, it will be gone. When I click the error it takes me no where. And another interesting thing is, there is no location specified for the error.
Please help.
The error means that some object is null, and you try to call a method or access a property on it.
For example this code will give the same error message:
string myString = null;
int length = myString.Length; //gives error since myString is null
If you can't find out where, and for some reason don't have any stack trace, try adding a try/catch block around the code you think is suspicious and see if the error is there or not.
Another solution is to just add a breakpoint, and go through your code line by line untill it explodes.
Without more details, that is the best advice I can give you.

NullReferenceException from AlphaImage.CreateFromResource()

I am using the AlphaMobileControls library for the .NET Compact Framework. I am using AlphaImage.CreateFromResource(imageResourceName) to create an AlphaImage object. The problem is that this method is throwing a NullReferenceException. Looking at the code for this method, the problem is that this line of code is returning null:
MemoryStream stream =
(MemoryStream)Assembly.GetCallingAssembly().GetManifestResourceStream(imageResourceName);
This was working fine before, and now it is not and I can't figure out why. It seems that I am passing a valid resource name. It is a resource that I added using the Resources tab of the project properties. Also in the Resources folder the image file is there and the Build Action is set to Embedded Resource. I even used this code to retrieve the available resources, and the one I am using was one of the returned values:
string[] names = Assembly.GetCallingAssembly().GetManifestResourceNames();
Then I was thinking that maybe by the time the AlphaImage.CreateFromResource() method code is running the available resources might be different. So I modified the code to include the above statement and then throw an InvalidOperationException if the passed resource is not an available resource. When I run the program and step through the code with the debugger, the added code is not there anymore and an InvalidOperationException is not thrown and the code will run until the NullReferenceException occurs. I searched my projects to see if maybe there was a reference to another version of AlphaMobileControls other than the one with the modified code, but I could not find any.
Any help will be appreciated, thanks in advance!
Inspect the result from Assembly.GetCallingAssembly().GetManifestResourceNames(); and see whether the resource name you are looking for appears here. When it doesn't, your settings on the properties of the resource (specifically "Build action: Embedded resource") will probably be set incorrect. Otherwise, maybe a folder has been renamed and you need to change the value of imageResourceName.
Aren basically answered this for me with his comment. You need to call AlphaImage.CreateFromResource() from the assembly that has the required resource. Thanks Aren.
The change I made that caused this to stop working was that I moved the class that was calling AlphaImage.CreateFromResource() into a separate library from the one that had the image resource. Therefore Assembly.GetCallingAssembly() is returning the assembly that does not have the resource.

Why doesn't Visual Studio show an exception message when my exception occurs in a static constructor?

I'm running this C# code in Visual Studio in debug mode:
public class MyHandlerFactory : IHttpHandlerFactory
{
private static Dictionary<string, bool> myDictionary = new Dictionary<string, bool>();
static MyHandlerFactory()
{
myDictionary.Add("someKey",true);
myDictionary.Add("someKey",true); // fails due to duplicate key
}
}
Outside of the static constructor, when I get to the line with the error Visual Studio highlights it and pops up a message about the exception. But in the static constructor I get no such message. I am stepping through line-by-line, so I know that I'm getting to that line and no further.
Why is this?
(I have no idea if that fact that my class implements IHttpHandlerFactory matters, but I included it just in case.)
This is VS2005, .Net 2.0
Edit: I just want to add, the fact that it's an HttpHandler does seem to matter. As the answers have indicated, the default behavior is to break on the TypeInitializationException rather than the inner exception. I tested another example without the HttpHandler and saw that this caused the program to break on the first line that used the class. But in this case there's no line in my code to break on, since the class was only called as an HttpHandler specified in my web.config file. Hence, it didn't break on the exception at all.
The problem is that the exception thrown is actually a TypeInitializationException that wraps whatever exception is thrown. I'm not sure what design tradeoffs caused this, but IMO it's one of the most annoying things in .NET development, and I'm sad to see it's still around in .NET 4.
In VS, to catch the exception ASAP, you'll need to turn on first-chance exceptions. Go to Debug > Exceptions and check "Common Language Runtime Exceptions", which will break as soon as an exception is thrown.
(Note: if you're using the Dynamic Language Runtime, you'll need to be more choosy about what exceptions are caught, since that apparently uses exceptions for flow control).
I tried your code and I got the TypeInitializationException as you expected. No problem in my VS...
But if you run this (or any other) application 'without debugging', you should always get an error message for any unhandled exceptions - no VS settings will make a difference here.
The static constructor gets run before your application is running in an appdomain. This is probably causing issues with the way VS is catching the exception, which from your description is quite non standard. It may be a limitation of 2005. That's why you should always catch within the body of the static constructor. There is an excellent discussion of this in the new book Effective C#

Categories