I must be going out of my mind, because my unit tests are failing because the following code is throwing a null ref exception:
int pid = 0;
if (parentCategory != null)
{
Console.WriteLine(parentCategory.Id);
pid = parentCategory.Id;
}
The line that's throwing it is:
pid = parentCategory.Id;
The console.writeline is just to debug in the NUnit GUI, but that outputs a valid int.
Edit: It's single-threaded so it can't be assigned to null from some other thread, and the fact the the Console.WriteLine successfully prints out the value shows that it shouldn't throw.
Edit: Relevant snippets of the Category class:
public class Category
{
private readonly int id;
public Category(Category parent, int id)
{
Parent = parent;
parent.PerformIfNotNull(() => parent.subcategories.AddIfNew(this));
Name = string.Empty;
this.id = id;
}
public int Id
{
get { return id; }
}
}
Well if anyone wants to look at the full code, it's on Google Code at http://code.google.com/p/chefbook/source/checkout
I think I'm going to try rebooting the computer... I've seen pretty weird things fixed by a reboot. Will update after reboot.
Update: Mystery solved. Looks like NUnit shows the error line as the last successfully executed statement... Copy/pasted test into new console app and ran in VS showed that it was the line after the if statement block (not shown) that contained a null ref. Thanks for all the ideas everyone. +1 to everyone that answered.
Based on all the info so far, I think either "the line that's throwing is" is wrong (what makes you think that), or possibly your 'sources' are out of sync with your built assemblies.
This looks impossible, so some 'taken for granted assumption' is wrong, and it's probably the assumption that "the source code you're looking at matches the process you're debugging".
When things look right on the surface then it's likely something you would dismiss. Are you 350% positive that your DLL/PDB matches your source code thus giving you the right line?
Try manually deleting your assemblies and run whatever it is you're running. Does it fail as it should?
Try cleaning out your solution and recompiling. Copy the assemblies to wherever and run it again. Does it work this time? Null ref at the same spot?
Debug the surrounding lines for values you expect. parentCategory, etc. should match what you think.
Modify the code by throwing an exception. Do the stack trace lines match exactly the lines in your code?
I've had some extremely mind-boggling experiences just like this because one of my assumptions was wrong. Typical is a stale assembly. Question all assumptions.
What doesn't make sense, though, is that the OP states that the console.writeline outputs a valid int and it calls the same property as the line where he states the error is being thrown.
A stacktrace would be helpful, or being able to look at the actual unit test.
Yes, could we see the code of the category class .. in particular the Id property? Assuming the Id property is an int (and not a nullable int), the get method must be accessing a NULL object.
Id could be a nullable int type (int?) with no value, however I feel that the property Id must be doing more than just returning an int, and something inside that is null.
EDIT Your edit reveals this is more than peculiar, could you supply us with a stack trace?
I'm not an expert on C#, and am not sure if it makes a difference, but are you debugging in Debug mode, or Release mode? If you're in release mode, the line that your IDE is pointing to and the line the problem is actually on may be different (I know this is the case in C++ when using Visual Studio)
I'd have to agree with Brian... Maybe you're using outdated .pdbs and the code you're seen on debug mode does not comply with the code actually being debugged.
Try cleaning the project, and rebuilding it in debug mode.
Looks like NUnit shows the error line as the last successfully executed statement... Copy/pasted test into new console app and ran in VS showed that it was the line after the if statement block (not shown) that contained a null ref. Thanks for all the ideas everyone. +1 to everyone that answered.
Related
Look at the following code:
public static string GetCleanURL(string baseURL, string url)
{
string cleanUrl = url.ToLower();
if (cleanUrl.StartsWith("http://"))
{//It already starts with http:// It is already in the correct form return it.
return cleanUrl;
}
The 'url' value passed in is "123.123.123.123:1234/myurl/withstuff.xml". In the 'if' statement, the value for 'cleanUrl' is "123.123.123.123:1234/myurl/withstuff.xml". But for some reason, the code execution goes inside of the if block and 'return cleanUrl;' gets executed.
Here is a screenshot of the current value for 'cleanUrl':
When I plug cleanUrl.StartsWith("http://") into the 'Immediate Window' of my debugger, it returns false. Which is what I would expect. However, the execution is somehow going into the if block as though it had returned true.
Can anybody please explain how this is possible?
SOLVED !!!
I appreciate those of you who helped me out on this one.
I needed to Clean and Rebuild my project and Close and Reopen Visual Studio 2013 about 4 times before the code base and debug stuff was actually in sync. It now appears to be working correctly.
Not sure why it ever got that way, or why I needed to do Clean/Rebuild several times before things synced up. But it is working now.
So, friends, if ever you find your code is just acting crazy and not doing what it should do. Just realize that anybody in their right mind would never become a programmer. Then do a clean / rebuild a few times and pray that the oddity goes away never to return.
Thanks for all your help on this one.
I LOVE fighting with the development tools...
No, StartWith isn't buggy, and works as expected.
Try the minimal code below. Reduce your code to the minimum amount to reprouce the problem. Does this happen everytime?
Does it happen with more than one candidate string? Or only that string?
Something else is going on sorry, the following writes Doesn't start
static void Main(string[] args)
{
string cleanUrl = "123.123.123.123:1234/SomeFile.xml";
if (cleanUrl.StartsWith("http://"))
Console.WriteLine("Starts");
else
Console.WriteLine("Doesn't start");
Console.ReadLine();
}
So, I have a piece of code using WeakReferences. I know of the common .IsAlive race condition, so I didn't use that. I basically have something like this:
WeakReference lastString=new WeakReference(null);
public override string ToString()
{
if(lastString!=null)
{
var s=lastString.Target as string; //error here
if(s!=null)
{
return s;
}
}
var str=base.ToString();
lastString=new WeakReference(str);
return str;
}
Somehow, I'm getting a null reference exception at the marked line. By debugging it, I can confirm that lastString is indeed null, despite being wrapped in a null check and lastString never actually being set to null.
This only happens in a complex flow as well, which makes me think garbage collection is somehow taking my actual WeakReference object, and not just it's target.
Can someone enlighten me as to how this is happening and what the best course of action is?
EDIT:
I can't determine at all the cause of this. I ended up wrapping the error code in a try-catch just fix it for now. I'm very interested in the root cause of this though. I've been trying to reproduce this in a simple test case, but it's proven very difficult to do. Also, this only appears to happen when running under a unit test runner. If I take the code and trim it down to the minimum, it will continue to crash when running using TestDriven and Gallio, but will not fail when put into a console application
This ended up being a very hard to spot logic bug that was in plain sight.
The offending if statement really was more like this:
if(lastString!=null && limiter==null || limiter=lastLimiter)
The true grouping of this is more like this:
if((lastString!=null && limiter==null) || limiter=lastLimiter)
And as Murphy's law would dictate, somehow, in this one unrelated test case, lastLimiterand lastString got set to null by a method used no where but this one single test case.
So yea, no bug in the CLR, just my own logic bug that was very hard to spot
I have the following code inside a method:
string username = (string)context["UserName"];
string un = (string)context["UserName"];
The problem is that the first string "username" is not assigned, while the second does.
To make it more strange, when I have stopped the debugging after the first line and copied the line to the Immediate window, dropping the varible type delaration, it was assigned succesfully.
I have made rebuild all and checked project properties which seems to be OK.
The context variable is a System.Configuration.SettingsContext, which is a hash table. To be more specific, I'm implementing a profile provider, the GetPropertyValues method.
I am using VS 2012 and .NET 4.5
EDIT:
I am using code contract in my project, which uses compile time code injection for runtime checking. I disabled it and all is working well. I'll try to remove contracts one by one to find which one is causing the problem.
What you are seeing is similar to a Code Contracts bug I saw before. I wrote something about it here a few months back. If you have this bug, you probably also have a lambda or LINQ expression in your method that uses username.
For future reference, this is the bug I saw:
I had in the same method a lambda expression capturing a local variable, lets say values, and a Contract.Requires() expression checking something completely unrelated. While debugging that method, the debugger shows in Locals the variable values twice, and reports the value of values always as null even when this is clearly not the case.
To reproduce:
static void Reproduction(string argument)
{
Contract.Requires(argument != null); // <-- (1)
int[] values = new int[1];
Debug.Assert(values != null);
Func<int, bool> d = i => values[i] >= 0; // <-- (2)
Console.WriteLine(values);
}
Put a breakpoint somewhere in this method after the assignment to values and ensure that the method gets called. When the debugger hits the breakpoint, look at the Locals list of Visual Studio for the duplicate variable. Hover the mouse over values to find that it gets reported as being null, something which is clearly not the case.
The problem disappears when removing either the contract (1) or the line with the lambda (2).
After investigating and desabling contracts I found that the problem appears only when runtime contracts checking is enabled and this contract appears:
Contract.Ensures(Contract.Result<System.Configuration.SettingsPropertyValueCollection>() != null);
If I delete this line, the code works, so it looks like code contracts bug, though I couldn't recreate it on a test project.
I am getting the following error:
Error 49 No overload for method 'getData' takes '1' arguments
With this method on the 5th line.
[WebMethod]
public string getVerzekerde(int bsn)
{
ZDFKoppeling koppeling = new ZDFKoppeling();
return koppeling.getData(bsn);
}
The getData method looks like this:
public string getData(int bsn)
{
using (new SessionScope())
{
ZorgVerzekerde verzekerde = PolisModule.GetVerzekerde(bsn);
return "Verzekerde " + verzekerde.Naam;
}
}
I realy don't understand what is going wrong here.. The description of this error on the msdn site didn't help me.. http://msdn.microsoft.com/en-us/library/d9s6x486%28VS.80%29.aspx
Someone who has a solution?
Yeah; somehow you're compiling against a different version of that class. Do a clean build, and double check your references.
Put an error in the GetData() method, then do a full build and confirm that the compiler find the errors. You may be editing the wrong file if you have more then one copy of the source code on your machine, and this will show you if you are.
Also try renaming the ZDFKoppeling class without updating getVerzekerde() and check you get a compiler error. If not you are not picking up the changed class for some reason.
If the above does not give a compiler error, try a rebook, as a process my have the dll locked, and also try a complete rebuild.
These problems normally turn out to be very simple once you have tracked them down. But get take forever to track down.
If another programmer works in the same office, ask for his/her help, as often a 2nd set of eye on the machine can find it quickly.
(I am assuming that GetData() is defined in the ZDFKoppeling class, not some other calss)
This generally indicates that it's not referencing the method you thought it was, but instead a different one. You can generally find out what method that is in Visual Studio by right clicking the method call and selecting "Go to definition". This should help work out why it's calling the one it is and not the one you expect.
Where is the getData method defined? Is it in another assembly? Have you tried rebuilding?
It doesn't look like anything's wrong with your the code.
So I have this code that takes care of command acknowledgment from remote computers, sometimes (like once in 14 days or something) the following line throws a null reference exception:
computer.ProcessCommandAcknowledgment( commandType );
What really bugs me is that I check for a null reference before it, so I have no idea whats going on.
Here's the full method for what its worth:
public static void __CommandAck( PacketReader reader, SocketContext context )
{
string commandAck = reader.ReadString();
Type commandType = Type.GetType( commandAck );
Computer computer = context.Client as Computer;
if (computer == null)
{
Console.WriteLine("Client already disposed. Couldn't complete operation");
}
else
{
computer.ProcessCommandAcknowledgment( commandType );
}
}
Any clues?
Edit: ProcessCommandAcknowledgment:
public void ProcessCommandAcknowledgment( Type ackType )
{
if( m_CurrentCommand.GetType() == ackType )
{
m_CurrentCommand.Finish();
}
}
Based on the information you gave, it certainly appears impossible for a null ref to occur at that location. So the next question is "How do you know that the particular line is creating the NullReferenceException?" Are you using the debugger or stack trace information? Are you checking a retail or debug version of the code?
If it's the debugger, various setting combinations which can essentially cause the debugger to appear to report the NullRef in a different place. The main on that would do that is the Just My Code setting.
In my experience, I've found the most reliable way to determine the line an exception actually occurs on is to ...
Turn off JMC
Compile with Debug
Debugger -> Settings -> Break on Throw CLR exceptions.
Check the StackTrace property in the debugger window
I would bet money that there's a problem with your TCP framing code (if you have any!)
"PacketReader" perhaps suggests that you don't. Because, technically, it would be called "FrameReader" or something similar if you did.
If the two PC's involved are on a local LAN or something then it would probably explain the 14 days interval. If you tried this over the Internet I bet your error frequency would be much more common especially if the WAN bandwidth was contended.
Is it possible that ReadString() is returning null? This would cause GetType to fail. Perhaps you've received an empty packet? Alternatively, the string may not match a type and thus commandType would be null when used later.
EDIT:
Have you checked that m_CurrentCommand is not null when you invoke ProcessCommandAcknowledgment?
What are the other thread(s) doing?
Edit: You mention that the server is single threaded, but another comment suggests that this portion is single threaded. If that's the case, you could still have concurrency issues.
Bottom line here, I think, is that you either have a multi-thread issue or a CLR bug. You can guess which I think is more likely.
If you have optimizations turned on, it's likely pointing you to a very wrong place where it actually happens.
Something similar happened to me a few years back.
Or else a possible thread race somewhere where context gets set to null by another thread. That would also explain the uncommonness of the error.
Okay, ther are really only a few possibilities.
Somehow your computer reference is being tromped by the time you call that routine.
Something under the call is throwing the null pointer dereference error but it's being detected at that line.
Looking at it, I'm very suspicious the stack is getting corrupted, causing your computer automatic to get mangled. Check the subroutine/method/function calls around the one you have trouble with; in particular, check that what you're making into a "Computer" item really is the type you expect.
computer.ProcessCommandAcknowledgment( commandType );
Do you have debugging symbols to be able to step into this?
The null ref exception could be thrown by ProcessCommandAcknowledgement, and bubble up.