I cant get this to work. The State field is empty on certain occassions, I am trying to get the result to return "--" if it is empty, or doesn't exist.
var CusipFields = from c in xml.Descendants("LISTARRAY")
orderby c.Element("ASKYIELD").Value descending
select new BondData()
{
CUSIP = c.Element("CUSIP").Value,
Description = (string)c.Element("ISSUER").Value,
Maturity= c.Element("MATURITYDT").Value,
AskYield = float.Parse(c.Element("ASKYIELD").Value),
State = (string)c.Element("STATE").Value ?? "--"
}
;
This just doesn't want to work. The error I am getting is:
NullReferenceException was unhandled. {"Object reference not set to an instance of an object."}
I KNOW that it does not exist. I thought that putting ?? "--" will return "--" if c.Element("STATE").Value is null.
I can resort to modifying the statement to:
var CusipFields = from c in xml.Descendants("LISTARRAY")
orderby c.Element("ASKYIELD").Value descending
select c;
foreach(var t in CusipFields)
{
switch(t.name)
{
}
}
But I think that it is slower. And its not what I want.
Use this:
State = (string)c.Element("STATE") ?? "--"
instead of
State = (string)c.Element("STATE").Value ?? "--"
My answer assumes, that your problem is, that the STATE element is missing, not empty. Please tell me, whether or not that fixed your problem.
I think it's because c.Element("STATE") is null, not it's Value property.
try:
(string)c.Element("STATE") != null? (string)c.Element("STATE").Value : "--";
You're getting this error not because the Value property is null, but because c.Element(...) is null. You'll need to check for nulls in all of your Element() calls and take appropriate action in order to avoid this error.
Related
I'm basically trying to iterate over a lot of data and transform a returned data query to a more limited object within a View Model.
Rather than do a huge section of code, I'm calling .ForEach() on a list, then adding a new entry to the view model's list.
This works great, but, there is one property (Address) that is optional.
When I reach the optional item, I get NullReferenceException if the item from the DB doesn't have an entry.
A code example is:
var tmp = _context.Person.Include(x => x.Address).ToList();
tmp.ForEach(x => vm.List.Add(new IndexListItem()
{
Name = x.Name,
Address = x.Address.FirstLine + " " + x.Address.SecondLine,
ID = x.ID
}));
I have since found out from a different answer on this site that if I change the address line so that it reads:
Address = x.Address?.FirstLine + " " + x.Address?.SecondLine,
The code now works when I hit a null entry in tmp.
I do not understand this as the Address property on tmp was already allowing nulls, and the Address property on the view model allows nulls, so, why does changing the line suddenly not return an error?
In addition, is the reason for me not having to do x.Address?.FirstLine? because that's a string and strings are already nullable?
A null reference exception in this particular case is caused when you are trying to access a property where the parent object is null itself.
x.Address.FirstLine
i.e. in your case Address is null.
It is not in regard to what you are trying to set (i.e. the destination view model).
The reason that this works:
x.Address?.FirstLine
..is because 'in the background' it's checking first to see if Address is null. If it isn't, then it returns FirstLine and if it is, then null is returned. It's semantically equivalent to:
if (x.Address == null)
{
return null;
}
else
{
return x.Address.FirstLine;
}
Here's a blog post about the introduction of the ?. operator in C# for some background reading: https://blogs.msdn.microsoft.com/jerrynixon/2014/02/26/at-last-c-is-getting-sometimes-called-the-safe-navigation-operator/
I do not understand this as the Address property on tmp was already allowing nulls, and the Address property on the view model allows nulls, so, why does changing the line suddenly not return an error?
You are mixing up saving data with loading data. When you save the data to the database, null is acceptable, but when you try to use the data, null is not.
The null conditional operator (?.) allows you to "shorten" an if statement, and it would be something similar to:
Address = x.Address?.FirstLine + " " + x.Address?.SecondLine,
string Address = "";
if (x.Address != null)
{
Address += x.Address.FirstLine;
}
// ....
Also, while not relevant to your problem, the code you are using is extremely ineffective, you are loading 2 tables to get just a few properties when you could get those properties directly from the database:
var vm = _context.Person
.Select(x => new IndexListItem
{
Name = x.Name,
Address = x.Address?.FirstLine + " " + x.Address?.SecondLine,
ID = x.ID
})
.ToList();
x.Address?.FirstLine where ? is null propogation operator this means if x.Address is null set null for the FirstLine.
null propogation equivalent code
if (x.Address == null)
return null
else
return x.Address.FirstLine
All reference type variables are nullable. hence, assigning null to reference types are always valid.
string is a reference-type in your example. therefore you do not get error because string x = null is valid
Your issue isn't that Address is null and you're trying to assign it to another property that allows null, it's that you're trying to access .FirstLine in something that's null.
If Address is null, then what you're trying to do with .FirstLine is the equivalent of null.FirstLine which doesn't work. Nothing can't hold something.
The ? notation you're using that works is only effecting Address, basically saying if Address is NOT null give me the value of .FirstLine, if it is null, then give me null.
I have the following string list:
List<string> Emails = new List<string>();
Trying to see if it has any values, or return an empty string:
string Email = Emails[0] ?? "";
The above code throws an exception:
Index was out of range. Must be non-negative and less than the size of
the collection. Parameter name: index
But changing the ?? operator to a simple if statement, it works fine:
if (Emails.Count > 0)
Email = Emails[0];
else
Email = "";
What am I missing here?
When the list is empty, should Emails[0] not be null ?
Thanks.
I suggest to change it to:
string Email = Emails.FirstOrDefault() ?? "";
If your list is empty, Emails[0] is not null, it just doesn't exist.
Edit: that works for strings and ref types, if you do have a value type, for example int, you will get default(int) that is 0 as result of FirstOrDefault of empty collection
Emails[0] will try access first item of the list - that is why it throws exception.
You can use "readable" DefaultIfEmpty method for declaring "default" value if collection is empty
string Email = Emails.DefaultIfEmpty("").First();
string Email = Emails[0]
That is the problem. ?? only checks if whats on its left is null and acts accordingly.
You seem to have the misconception that an empty list has null stored at index 0. That is most definitely not the case. These two lists are semantically very different:
var emptyList = new List<string>();
var someList = new List<string>() { null };
In your code you are trying to access the item at position zero of an empty list. This is an index out of range exception because there is no such item. The exception is thrown before the ?? operator is even evaluated.
Using Emails[0] will throw exception as you access element 0 that is not exist
as Maksim suggested Emails.FirstOrDefault() will return null if the list is empty which you check by ?? coalesce operator
I have a linq WHERE statment where I'm wanting to use a cookie value string (aspxauth) to match up to a string in a table, however I'm getting an "Object reference not set to an instance of an object." error.
The code is:
HttpCookie authCookie = Request.Cookies[".aspxauth"];
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
string cookieUser = authCookie.Value;
if (User.Identity.IsAuthenticated)
{
if (Request.Cookies[".aspxauth"] != null)
{
var loginStatus = new UsersDataContext();
var loginstatus = from s in loginStatus.sessions
where s.aspxauth == cookieUser
select s;
var x = loginstatus.FirstOrDefault().UserId.ToString();
If I remove the where statement I dont get the error.
Any ideas on where I'm going wrong here??
Any help is appreciated, thanks.
My guess would be that none of the elements in the loginStatus.sessions sequence match the condition of the where clause, causing loginstatus.FirstOrDefault() to return null, so when you try to access .UserId, you get the null reference exception.
You should check for null yourself and handle the case:
var firstLoginStatusMatch = loginstatus.FirstOrDefault();
if (firstLoginStatusMatch == null)
{
// Handle no match
}
var userId = firstLoginStatusMatch.UserId.ToString()
I would also suggest naming your variables to be more descriptive. You have two variables of the same name but with different casing, making the code very hard to scan.
It's telling you that at least one of the sessions items is null, or that your where statement filtered the collection down to zero items.
You will get this error if no elements match, that is where where s.aspxauth == cookieUser is false for every element in loginStatus.sessions. FirstOrDefault() will return the default value for an object, which is null.
I'm using C# to write a simple program to read Active Directory and display the value held in a AD field on a Windows form program.
If a property doesn't exist then the program crashes, below is my code, how can I catch this and move on to the next field without doing a try/catch for each and every attribute?
DirectoryEntry usr = new DirectoryEntry("LDAP://" + domain, username, password);
DirectorySearcher searcher = new DirectorySearcher(usr);
searcher.Filter = "(sAMAccountName=" + GlobalClass.strUserName + ")";
searcher.CacheResults = false;
searcher.SearchScope = SearchScope.Subtree;
searcher.PropertiesToLoad.Add("givenName");
searcher.PropertiesToLoad.Add("telephoneNumber");
//program crashes here if telephoneNumber attribute doesn't exist.
textBoxFirstName.Text = usr.Properties["telephoneNumber"].Value.ToString();
Just checking usr.Properties["telephoneNumber"] will not work. You must check the actual value. The reason the error is occuring is because you're calling ToString() on Value which is null.
user.Properties will always return a PropertyValueCollection, regardless of the property name entered into the collections indexer.
I.e.
var pony = usr.Properties["OMG_PONIES"]; // Will return a PropertyValueCollection
var value = pony.Value; // Will return null and not error
You need to check the value itself, the best way through the null coalescing operator:
textBoxFirstName.Text = (usr.Properties["telephoneNumber"].Value
?? "Not found").ToString();
Store the contents of usr.Properties["telephoneNumber"]; in a variable and check for null:
PropertyValueCollection tel = usr.Properties["telephoneNumber"];
textBoxFirstName.Text = (tel != null && tel.Value != null)
? tel.Value.ToString()
: "";
Use the null-coalescing operator (??) operator.
textBoxFirstName.Text = (usr.Properties["telephoneNumber"].Value
?? String.Empty).ToString();
This way the value is replaced with an empty string if null. You could also just return null instead of String.Empty, the reason your code is crashing is because you're trying to call ToString() on a null value.
Something like this should work. If telephoneNumber is not null, it will convert the value to a string, otherwise it will use an empty string.
textBoxFirstName.Text = usr.Properties["telephoneNumber"].Value != null
? usr.Properties["telephoneNumber"].Value.ToString()
: "";
A couple of things will help this be more graceful:
Test usr.Properties["telephoneNumber"] for null before calling child properties like Value. I haven't worked with AD myself, but most string-keyed indexers are designed to gracefully handle non-existent keys. the CLR, on the other hand, will happily throw a NullReferenceException any time you try to reference a member of anything that evaluates to null.
On the off chance that AD DOES blow up on a nonexistent column, enclose the assignment in a Try-Catch block that will show an error on the screen and gracefully continue processing (or not).
Use this code
SearchResult.Properties.Contains("property")
To check if the object actually has the prop loaded from the search result
if (usr.Properties["telephoneNumber"] != null)
textBoxFirstName.Text = usr.Properties["telephoneNumber"].Value.ToString();
I have the following LINQ query which always results in an error when my "Remark" column in dtblDetail is null, even though I test if it is NULL.
var varActiveAndUsedElementsWithDetails =
from e in dtblElements
join d in dtblDetails on e.PK equals d.FK into set
from d in set.DefaultIfEmpty()
where (e.ElementActive == true)
select new
{
ElementPK = e.PK,
Remark = d.IsRemarkNull() ? null : d.Remark
};
The error message was:
"The value for column 'Remark' in table 'dtblDetails' is DBNull."
After adding the test for d.IsRemarkNull() a null reference exception is thrown.
Can you help me with this?
I've already checked the following websites but didn't find anything useful other than that I have to test for DBNULL. But as said this doesn't solve my problem.
http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/3d124f45-62ec-4006-a5b1-ddbb578c4e4d
http://blogs.msdn.com/adonet/archive/2007/02/13/nulls-linq-to-datasets-part-3.aspx
http://www.vbforums.com/showthread.php?t=506645
The problem was that the whole 'd' item was empty.
So calling 'd.IsRemarkNull()' resulted in the null reference exception.
The following code fixed the problem:
var varActiveAndUsedElementsWithDetails =
from e in dtblElements
join d in dtblDetails on e.PK equals d.FK into set
from d in set.DefaultIfEmpty()
where (e.ElementActive == true)
select new
{
ElementPK = e.PK,
Remark = d == null? null : (d.IsRemarkNull() ? null : d.Remark)
};
Where is the error coming from? Is it possible that it is the d.IsRemarkNull() that is causing it? What does that method look like?
Perhaps:
DBNull.Value.Equals(d.Remark)
maybe this field doesn't allow null in db, get a default value for it, and avoid handling null values