Server stack trace:
at
Tavisca.TravelNxt.Hotel.Core.Controllers.HotelSuppliersController.b__33(PassengerTypeQuantity
passengerInfo)
at System.Linq.Enumerable.Any[TSource](IEnumerable1 source, Func2
predicate)
code:
if (passengers == null || passengers.Count == 0)
{
_serviceStatus.MissingItems.Add(Utility.GetXmlElementORAttributeName(type, property));
return false;
}
if (passengers.Any(passengerInfo => passengerInfo.Quantity == 0))
{
_serviceStatus.InvalidItems.Add(Utility.GetXmlElementORAttributeName(type, property));
return false;
}
Please try this
if (passengers == null || (passengers != null && passengers.Count == 0))
{
_serviceStatus.MissingItems.Add(Utility.GetXmlElementORAttributeName(type, property));
return false;
}
if (passengers.Any(passengerInfo => (passengerInfo == null) || (passengerInfo != null && passengerInfo.Quantity == 0)))
{
_serviceStatus.InvalidItems.Add(Utility.GetXmlElementORAttributeName(type, property));
return false;
}
Since the error is in linq, this means the problems is occurring on the line
if (passengers.Any(passengerInfo => passengerInfo.Quantity == 0))
and it is because one or more of the elements in passengers is null, thus the passengerInfo.Quantity part results in the object not set to an instance exception.
Try changing the line to the following to see if it resolves the error:
if (passengers.Any(passengerInfo => passengerInfo == null || passengerInfo.Quantity == 0))
(though of course, this change might in reality be masking the real problem of you having a null passengerInfo object)
Object reference not set to an instance of an object. means that you have an object that is null, hence it's not instantiated. You solve this by ensuring that the object is in-fact instantiated.
There are multiple ways to go by this, it all depends on what you want your application to do in a case of unexpected behavior (a null!).
Example of a null object
If you were to write the following:
Person filip = null;
Console.WriteLine(filip.Name);
Then the second line would give us a Object reference not set to an instance of an object. exception, because we in fact now know that filip is null.
So how do we solve this?
Either we can check if it is null before we print it:
Person filip = null;
if(filip != null)
{
Console.WriteLine(filip.Name);
}
Or if we are getting the Person from another metod, we can use ?? to ensure that it is not null and if it is, we just create a new one like this:
Person filip = GetFilip() ?? new Person();
It all depends on what you want to do in case of a null in your application.
As others have mentioned, you need to set a breakpoint and find where the error are occuring, when you find that, look for what object is null and make sure that it is handled properly.
You have good information in your stack trace that leads us to the LINQ statement.
In your case, you check if (passengers == null || passengers.Count == 0) but at the next line you have if (passengers.Any....) this means that even if passengers is null, it will still try to Any() on it which will throw an exception.
Maybe you are just looking for an else if?
The solution is to make check for all.
if (passengers == null || (passengers != null && passengers.Count == 0))
{
_serviceStatus.MissingItems.Add(Utility.GetXmlElementORAttributeName(type, property));
return false;
}
if (passengers.Any(passengerInfo => (passengerInfo == null) || (passengerInfo != null && passengerInfo.Quantity == 0)))
{
_serviceStatus.InvalidItems.Add(Utility.GetXmlElementORAttributeName(type, property));
return false;
}
Related
I am working on WPF application. In which I am trying to fetch records from list as per required condition. But when there is no any record found then it's giving me object reference not found error.
var recordList = _outputVariables.ToList().Where(X => X.symbolName == _symbolName).ToList();
if (recordList != null)
{
//more coding...
}
so as shown in code when _outputVariables have no any record match as per _symbolName then it's giving error of Object reference not set to an instance of an object.' and X was null.. So how can I handle this issue ? please help for it.
Use the null-conditional operator that was introduced in C#6 (and don't call ToList() more than once):
var recordList = _outputVariables?.Where(X => X?.symbolName == _symbolName).ToList();
if (recordList != null)
{
//more coding...
}
var recordList = _outputVariables.ToList().Where(X => X.symbolName == _symbolName).ToList();
You currently loop through _outputVariables, but if it's null this will give an error, because null does not have a .ToList(). So you should add a ? after your _outputVariables, so it will return null instead of an exception when it's null.
Same goes for X. If X is null and you try to get the property symbolName, you will get an error, because null doesn't have a property called symbolName. So you want to add a ? here too. So it will return null instead of an exception.
Leaving you with: var recordList = _outputVariables?.ToList().Where(X => X?.symbolName == _symbolName).ToList();
You can use like below as well
if (_outputVariables != null && _outputVariables.Count > 0)
{
var recordList = _outputVariables.Where(X => X != null && !string.IsNullOrEmpty(X.symbolName) && X.symbolName == _symbolName);
}
You can try this
if(_outputVariables!=null)
{
var recordList = _outputVariables.Where(X => X.symbolName ==_symbolName).ToList();
}
if (recordList != null)
{
//more coding...
}
I have a List of objects in variable SanityResults with only one object whose values are null,I am trying to validate this condition as if (SanityResults != null) but fails?how to check for this case?
if (SanityResults != null)
{
//code
}
The condition that you are using will check whether SanityResults is null or not. But you wanted to check for the properties of all objects inside the list. So the better option is the use of Any() if you wanted to check check for any object inside the list is null means you have to use like the following:
if(SanityResults.Any(x => x == null))
{
// This will execute if any one of the object in the list is null
}
Now try this, if you wanted to check for properties of each object inside the list:
if(SanityResults.Any(x => x.failCount==null || x.htmllist ==null))
{
// include conditions like this for all required properties
// this statement will execute if any of the property of any of the objects in the list is null
}
Creating a separate method for is contain null
public bool IsContainNull(List<SanityResults> myList)
{
foreach(var myObject in myList)
{
if(myObject==null)
{return false;}
else{
foreach(PropertyInfo pi in myObject.GetType().GetProperties())
{
if(pi.PropertyType == typeof(string))
{
string stringValue = (string)pi.GetValue(myObject);
if(string.IsNullOrEmpty(stringValue ))
{
return true;
}
}
else if(pi.PropertyType == typeof(int))
{
int intValue = (int)pi.GetValue(myObject);
if(intValue==null)
{
return true;
}
}
}
}
return false;
}
}
Ok, just to throw another similar answer into the ring...
if (SanityResults == null || SanityResults.Any(sr => sr == null) ||
SanityResults.Any(sr => sr.failcount == null && sr.htmllist == null &&
sr.passcount == null && sr.testsuitename == null))
{
// Do something if the List is null, if any items in the list are null,
// or all of the properties of any item in the list are null
}
The problem is that the SanityResults is actually not null, and consists of one element with properties, that are null.
What elements are allowed to be null, and what aren't?
If none of the properties are allowed to be null, then go with this:
if(SanityResults.Any(x => x.failCount == null || x.passcount == null || x.testsuitename == null || x.htmllist == null))
{
// Code goes here
}
An element in the list, having nothing but null values in it, but having a semantic value in the code, smells a bit though.
I am somewhat of a beginner programmer. What I am trying to do here is to check that if there is a time, if it is selected, and if that time is equivalent to the other. If that is all true then I want to skip the block of code under it. Here is the code example:
if (currentGVR.Round_Start_Time)
{
if (tr.StartLunchDateTime != null && currentGVR.Round_Start_Lunch && roundedStart == roundedStartL)
// skip
else
{
key = tr.TransactionID;
TransactionRecords[key]["Start_DateTime"] = roundedStart;
}
}
I thought about using an OR operator, but I can see where an error would occur if there was no time to compare to. Using the AND operator avoids this dilemma here.
So the overall question is, is it proper coding to negate all of the conditions to get the correct result, e.g. if (!( cond's )), and also, would this be the best way to check if there is a value to compare with before actually comparing it in C# and otherwise? The times can be null (or do not exist) in some records. Any recommendations?
I'd negate all those conditions and switch the && to || so it's more quickly evident under what conditions the code will (or will not) execute.
Plus (in my experience), you don't typically see an empty if block with all the code under the else.
if (tr.StartLunchDateTime == null || !currentGVR.Round_Start_Lunch || roundedStart != roundedStartL)
{
key = tr.TransactionID;
TransactionRecords[key]["Start_DateTime"] = roundedStart;
}
The statement
if (tr.StartLunchDateTime != null && currentGVR.Round_Start_Lunch && roundedStart == roundedStartL){
// skip
}
else
{
key = tr.TransactionID;
TransactionRecords[key]["Start_DateTime"] = roundedStart;
}
is equivalent to
if (!(tr.StartLunchDateTime != null && currentGVR.Round_Start_Lunch && roundedStart == roundedStartL))
{
key = tr.TransactionID;
TransactionRecords[key]["Start_DateTime"] = roundedStart;
}
else {
// skip
}
This can be further simplified because
!(tr.StartLunchDateTime != null &&
currentGVR.Round_Start_Lunch &&
roundedStart == roundedStartL)
Is the same as
(!(tr.StartLunchDateTime != null) ||
!(currentGVR.Round_Start_Lunch) ||
!(roundedStart == roundedStartL))
or
(tr.StartLunchDateTime == null ||
!currentGVR.Round_Start_Lunch ||
roundedStart != roundedStartL)
See DeMorgan's Laws.
if (someLongCondition)
{ }
else
{
doStuff();
}
is equivalent to this:
if (!someLongCondition)
{
doStuff();
}
So yeah, you can just negate your whole condition:
if (!(tr.StartLunchDateTime != null && currentGVR.Round_Start_Lunch && roundedStart == roundedStartL))
{ … }
But you can also pull the negation in (applying De Morgan's laws) and write it like this:
if (tr.StartLunchDateTime == null || !currentGVR.Round_Start_Lunch || roundedStart != roundedStartL)
{ … }
All these are equivalent so choose whatever makes the condition more clear (actually, consider storing it in a separate variable which you give a descriptive name).
I run this query And if The Query is return with empty values the programme is crashed.
var cust = db.Customers.FirstOrDefault(x => x.telephone == txtTel.Text);
if (cust.BlackList == 1)
{
MessageBox.Show("This customer is blacklisted, Do you wish to continue with this job?");
}
Please Suggest me Some Efficient solution
Thanks.
You are getting a null pointer because FirstOrDefault returns the default value of the object if the result is not found (in this case it is null):
var cust = db.Customers.FirstOrDefault(x => x.telephone == txtTel.Text);
if (cust != null && cust.BlackList == 1)
{
MessageBox.Show("This customer is blacklisted, Do you wish to continue with this job?");
}
You need to check for null because that's what FirstOrDefault returns if there is no record that satisfies your condition:
if(cust != null && cust.BlackList == 1)
FirstOrDefault will return a default value if there is no element in the list which satisfy the condition, in this case it will be null. As you call a property on the null value it will naturally cause an exception.
You should check if cust is null, like:
if(cust != null && cust.BlackList == 1)
Of course you can display another message if the user doesn't exist based on the logic of your application.
I am using the following:
if (Model.Notes.Length == null || Model.Notes.Length < 170) {
But there is an error when the Notes value is null. I thought this would allow it to work but I still get the error. Can someone tell me how I can make this work even if Model.Notes is null?
Add a null check before accessing any properties.
if (Model.Notes!=null)
{
if(Model.Notes.Length == null || Model.Notes.Length < 170)
{
//do the same awesome thing..
}
}
You gotta do:
if ((Model.Notes != null && (Model.Notes.Length == null || Model.Notes.Length < 170))
So it'll check for notes being null first.
What about:
if (Model.Notes != null && (Model.Notes.Length == null || Model.Notes.Length < 170)) {