I'm not really sure if I will be able to explain this behavior but I'll try. I have a program like a dashboard where some graph modules are initialized at startup, each module has a sole purpose to show a graph has a function passed to it which determine the data shown.
The module building (initializing each module type with the corresponding function) is handled in a separate thread using Task. But randomly some of these functions stop working and the List with the data stop being available as if it was never declared.
This is one of the functions, keep in mind it's kind of random which one throws this error, but one of these will always throw an exception. I really can't track down what could cause this behavior I thought about the resources being deleted by other thread but this List is created at startup and only passed and used as a reference. And nowhere in the program I ever reset this list. The same code work in other project and while debugging step by step... I'm really out of tracks to follow
private static IEnumerable<ICompositeValue> GroupEvent(IEnumerable<Event> events, DateTime referenceDate, Month month)
{
List<ICompositeValue> Values= new List<ICompositeValue>();
foreach (Days day in (Giorni[])Enum.GetValues(typeof(Days)))
{
if (day != Giorni.Sunday)
if (events== null) return null; //this was tried to catch the exception
Values.Add(new ICompositeValue()
{
Argument = day.ToString(),
Valore = event.Count(x => (int)x.DDB_APDATA.Value.DayOfWeek == (int)day && (int)x.DDB_APDATA.Value.Month == (int)month && x.DDB_APDATA.Value.Year == referenceDate.Year)
}); ;
}
return valori;
}
As shown in this image Visual Studio can't even evaluate the List value as if it was never declared
Can someone point me in the right direction?
Thanks to everyone!
I just wanted to thank those who tried to help me.
I still didn't get why the debugger acted the way it did since it showed me "x" was null not the inside property, but I managed to track down the problem. I noticed the object mapping from the DataTable was acting strange with the DateTime type variable and indeed something returned null from time to time
As Jeroen Mostert has suggested it seems like some property in your lambda is unexpectedly null. The reason events is not available is because your debugger context is inside the lambda.
x => (int)x.DDB_APDATA.Value.DayOfWeek == (int)day && (int)x.DDB_APDATA.Value.Month == (int)month && x.DDB_APDATA.Value.Year == referenceDate.Year
So one of either x, DDB_APDATA, or Value will likely be null.
Related
while analyzing my code using sonarqube i came across 'variableProducerAgreements' is null on at least one execution path in the following code (the foreach loop):
however, upon looking at it and trying various things, variableProducerAgreements seems to never be null in this foreach loop. during a code review, i'm being told that it can "totally" be null and should add conditional logic to handle it. but i'm not understanding how it can be null and thus not sure how to add a conditional. any ideas?
I can't see a way in which variableProducerAgreements could be null since you have the null guard in place at the top (and assuming you don't have any crazy code in your property getters).
if (userProfile?.ProducerProfile == null)
return result;
The Where and FindAll methods in .NET doesn't return null.
However, it is possible the use of a null-conditional every time you access ProducerProfile is confusing some tools and people. Since you're returning early if it is null, you should remove them:
if (IsActingAsDelegate && userProfile.ProducerProfile.IsInactiveProducer)
{
variableProducerAgreements = userProfile.ProducerProfile.ProducerAgreements.FindAll(ag => ag.IsActive && ag.IsVariableBranchContract);
}
else
{
variableProducerAgreements = userProfile.ProducerProfile.ActiveAgreements.Where(a => a.IsVariableContract);
}
If there was a way for it to be null before the if statement, you would also risk a NullReferenceException when you access the IsInactiveProducer property.
Also, the reviewer should be able to explain his/her reasoning.
I have been having an issue lately with a Foreach statement and it throwing an Collection was modified; enumeration operation may not execute exception when changing a variable that shouldn't impact the items being enumerated upon, but it still does. Here is my code so I can continue my explanation:
private static CEconTradeOffer RemoveUndesirables(CEconTradeOffer offer)
{
try
{
CEconTradeOffer returned = offer;
foreach (CEconAsset cEconAsset in offer.ItemsToReceive)
{
string marketHashName = cEconAsset.GetMarketHashName(_config.ApiKey);
if (marketHashName.ToLower().Contains("case") ||
marketHashName.Contains("gut") ||
marketHashName.Contains("falchion") ||
marketHashName.Contains("bayonet") ||
marketHashName.Contains("huntsman") ||
marketHashName.Contains("karambit") ||
marketHashName.Contains("butterfly"))
{
//somehow changes both "offer" and "returned" at once.
returned.ItemsToReceive.Remove(cEconAsset);
continue;
}
MarketValue value = MarketHandler.GetPriceOverview(Convert.ToUInt32(cEconAsset.AppId),
marketHashName);
if (!value.Success || int.Parse(value.Volume, NumberStyles.AllowThousands) <= 20)
returned.ItemsToReceive.Remove(cEconAsset);
}
return returned;
}
catch (Exception e)
{
Write.Exception(e);
return null;
}
}
This function was designed to do exactly what it says; remove undesired items from a trade offer. As you can see, I set CEconTradeOffer returned equal to the passed argument of the same type named offer. Strangely enough, whenever I change something inside of returned it causes the foreach statement to break even though I technically shouldn't be impacting offer.ItemsToReceive in any way. returned is what should be modified. When I use the debugger, I notice that BOTH returned and offer get changed at the line returned.ItemsToReceive.Remove(cEconAsset);. Through my previous experience with C# and browsing related problems, this should not be happening since I am creating a new variable that should be separate from offer. I have tried include setting returned equal to a new CEconTradeOffer() and then setting it equal to offer but to no avail. In my research of this problem, I can only seem to find problems where people fail to create a new variable and modifying that in the foreach statement rather than the enumerated value.
Is there something blatantly obvious I am missing? I do not quite understand why I am getting this particular issue when I create a separate variable to change inside the foreach statement.
I am not using more than one thread, so it can't be impacted outside of its own thread of execution.
Thanks in advance.
whenever I change something inside of returned it causes the foreach statement to break even though I technically shouldn't be impacting offer.ItemsToReceive in any way.
It seems that CEconTradeOffer is a reference type, so then you assign
CEconTradeOffer returned = offer;
you get another reference to exactly the same thing.
So when the items are removed using returned.ItemsToReceive.Remove(cEconAsset) they are removed from the same collection, just via another reference.
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.
DateTime mydt = new DateTime();
mydt = Convert.ToDateTime(com.Decrypt(Request.QueryString["Time"].ToString(), com.KeyCode.ToString()));
What am I doing wrong ? Its giving NullReferenceException.
Well, it's hard to say exactly what's going on because you've got lots of stuff going on in one statement.
As a simple aid to debugging, break that statement up into several separate ones - it'll make it a lot easier to find out what's going wrong. (Also note that your initial value of mydt is overwritten in the next statement anyway, so there's no point in it.)
Here's how I would rewrite your code:
// This already returns a string... you don't need to call ToString() on it
string encryptedTime = Request.QueryString["Time"];
// We don't know what "com" is here...
string key = com.KeyCode.ToString();
string decryptedTime = com.Decrypt(encryptedTime, key);
DateTime mydt = Convert.ToDateTime(decryptedTime);
(I'd also usually use DateTime.TryParseExact, but that's a different matter.)
A NullReferenceException occurs when you try to access a member of a null reference.
When you have a series of member accesses (using the '.' operator) and any reference is null, this will occur.
Any of these could be null:
com
Request.QueryString["Time"]
com.KeyCode
You can debug this by stopping on this line with a breakpoint (click on the line, press F9), and hover on each item in the above list. One of them is bound to be null.
Here's how you might redo your code in order to make it easier to read and debug issues like these:
DateTime mydt; // You don't need to initialize this with a new DateTime
if (com == null)
{
// Do something else, since nothing below this will work
}
var keyCode = com.KeyCode;
var time = Request.QueryString["Time"];
if (keyCode == null || time == null)
{
// Do something else, since nothing below this will work
}
mydt = Convert.ToDateTime(com.Decrypt(time.ToString(), keyCode.ToString()));
There are many possible null references here, but the most likely one is the Time query string variable. Make sure it exists.
Also, is your com variable set? And the com.KeyCode?
Several things can be null..
com, Request.QueryString["Time"], com.KeyCode
Set a breakpoint and find out ;)
One of your objects is null and when you try to access a property of a object that's null you receive a NullReferenceException.
Break out the code into multiple lines and test as either com, Request.QueryString["Time"] or com.KeyCode is null.
NullReferenceException come when a operation work on a object who have a null value or not have a valid value. you need to check that object have valid value or not null before making a operation on them.
if you parse it from anything that check that it is valid in some case if value not valid then he set the object as null in .net
As its name indicates, NullReferenceException is thrown because you are calling methods or properties on something that is null.
Therefore, you need to debug that expression to see which object is null at runtime, in the page you are testing.
We don't have enough info to answer your question directly. But...
There might not be a "Time" parameter in the query string?
Your variable com might be null? Was it properly instantiated?
As we don't see what page you are calling, we cannot tell.
So fire up visual studio and debug the expressions in there. Anyone of them could be null for any number of reasons.
NullReference essentially means that you are using a reference to an object when that object is null.
Background
I have a DataGridView control which I am using, and I added my handler below to the DataGridView.CellFormatting event so the values in some cells can be made more human-readable. This event handler has been working great, formatting all values without issue.
Recently however, I have discovered a very rare circumstance causes an unusual bug. The column in my DataGridView for the item's due date always has an int value. 0 indicates the event is never due, any other value is a UTC timestamp for the due date. The MySQL db column corresponding doesn't allow nulls. When the user has moved from one DataGridView row with a due date, to another DataGridView row with a due date (at this point everything is still appears fine), and then presses a button which reloads the data from the database (without sending updates, essentially calling DataAdapter.Fill()), the program generates a StackOverflowException**.
No recursion?
What is so unusual to me is that I do not see where the recursion or infinte-looping is. I added int cellFormatCallCount as a class member, and increment it during each call, but at the time the exception is thrown, the debugger shows the value of that int as 1, which I would expect since I wasn't under the impression and recursion was occuring.
Can somebody help me?
How can I view a stack trace? In VS2008 it says:
{Cannot evaluate expression because the current thread is in a stack overflow state.}
Best regards,
Robinson
private int cellFormatCallCount = 0;
private void myDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) {
try {
// to format the cell, we will need to know its value and which column its in
string value = "";
string column = "";
// the event is sometimes called where the value property is null
if (e.Value != null) {
cellFormatCallCount++; // here is my test for recursion, this class member will increment each call
// This is the line that throws the StackOverflowException
/* ********************* */
value = e.Value.ToString();
/* ********************* */
column = actionsDataGridView.Columns[e.ColumnIndex].Name;
} else {
return; // null values cannont be formatted, so return
}
if (column == "id") {
// different code for formatting each column
} else if (column == "title") {
// ...
} else {
// ...
}
} finally {
cellFormatCallCount = 0; // after we are done with the formatting, reset our recursion counter
}
}
Apparently e.Value.ToString() invokes the CellFormatting event again. That seems somewhat logical. It should be easy enough to find out with a debugger.
But the actual recursion could be caused somewhere else, like in the per-column formatting that you omitted.
Your recursion check isn't reliable since Value==null will also reset it, and it appears to be shared by all columns. Make it surround the e.Value.ToString() more tightly:
if (e.Value != null)
{
cellFormatCallCount++;
System.Diagnostics.Debug.Assert(cellFormatCallCount <= 1, "Recursion");
value = e.Value.ToString();
cellFormatCallCount--;
...
}
Totally random guess (with no stack trace it's all I can do)...
Are you attempting to display/format a type which has a potentially recursive ToString()?
public string ToString()
{
return ... this.ToString() ...
// or
return String.Format("The value is {0}", this);
}
A typo/error like that could cause a StackOverflowException...
Given that this is an event, might it be triggering its self?
Try making the cellFormatCallCount variable static so that it shared by all instances of the class. I suspect that somehow the event is triggering itself but you aren't seeing it because cellFormatCallCount is only local to each instance of the class handling the event and thus is never incremented beyond 1. If that's the case, then the actual trigger for the stackoverflow (recursion) could be anywhere in the method and it just happens to run out of stack space at that line.
Once you've made the variable static, you could throw an exception when it exceeds a certain (small) value, like 2. That exception should leave a viewable stack trace around.
#Daniel: If that were the issue, wouldn't it already raise the exception in the line:
if (e.Value != null) {
#gnirts: Could you post the full method and stack trace too?
#BCS (below): I think that might be it, but it might easily be in some of the code that is not shown in the deo posted.
PS. I'm sorry, this should have been a comment, but I have not enough reps :-D
It's unrelated to the problem but you can actually have a StackOverflowException without recursion at all just with:
throw new StackOverflowException();
I Have just had a similar problem of stackoverflow with no trace details.
My problem was due to a instance of an object which should not have been instantiated. I removed the offending new object and all was fine.
In the circumstance above without seeing any more code, ensure multiple events are not fired using the =- to cancel the events accordingly.
I hope this might help someone.