hello to all i have this method
public void insertXmlNode(string XmlParentNodeName, List<string> XmlNodeName, List<string> XmlNodeValue, List<string> XmlAttributeName, List<string> XmlAttributeValue)
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load(_connection);
XmlNode xparent = xdoc.SelectSingleNode("//" + XmlParentNodeName);
if (xparent == null)
{
xparent = xdoc.CreateNode(XmlNodeType.Element, XmlParentNodeName, null);
xdoc.DocumentElement.AppendChild(xparent);
}
for (int i = 0; i <= XmlNodeName.Count; i++)
{
XmlNode xnode = xdoc.CreateNode(XmlNodeType.Element, XmlNodeName[i], null);
xnode.InnerText = XmlNodeValue[i];
if (!string.IsNullOrEmpty(XmlAttributeName.ToString()))
{
XmlAttribute xattribute = xdoc.CreateAttribute(XmlAttributeName[i]);
xattribute.Value = XmlAttributeValue[i];
xnode.Attributes.Append(xattribute);
}
xparent.AppendChild(xnode);
}
xdoc.Save(_connection);
}
and i call this like below:
_db.insertXmlNode("Orders", _orderName, _orderValue, null, null);
"_db is a class instanc and _orderName & _orderValue has list string "
i wanna if XmlAttributeName not null add attribute to xml node but i
get this error
value can't be null
how i can check if XmlAttributeName not null do somthing?
Instead of doing the check this way, as you said in comment :
if (XmlAttributeName != null ||
XmlAttributeName.All(x => string.IsNullOrWhiteSpace(x)))
{
.......
}
Try to do it this way :
if (XmlAttributeName != null &&
XmlAttributeName.All(x => !string.IsNullOrWhiteSpace(x)))
{
.......
}
With && operator 2nd condition will only be checked if the 1st condition met. And code execution will enter if block, only if XmlAttributeis not null and all attributes in the list is not null or empty string.
private bool HasInvalidValues(IEnumerable<string> enumerable)
{
return enumerable == null || enumerable.Any(string.IsNullOrWhiteSpace);
}
The correct way to check for nullity is if(XmlAttributeName != null). This kind of check is ubiquitous for reference types; even Nullable<T> overrides the equality operator to be a more convenient way of expressing nullable.HasValue when checking for nullity.
If you do if(!XmlAttributeName.Equals(null)) then you will get a NullReferenceException if data == null. Which is kind of comical since avoiding this exception was the goal in the first place.
if (XmlAttributeName != null &&
XmlAttributeName.All(x => !string.IsNullOrWhiteSpace(x)))
{
// do here
}
Related
Following is my null operator check
if (vessels?.Vessels?.Count == 0)
{ }
and object is below
private static readonly DataQueueItem _emptyVessel = new DataQueueItem()
{
VesselId = 1,
Vessels = null
};
It is going in else part but it should be in if block.
I am confused why it is happening.
Any help
Please change your code into =>
if ((vessels?.Vessels?.Count ?? 0) == 0)
{
// do something.
}
Explanation: As vessels can be null or vessels.Vessels can be null so, vessels?.Vessels?.Count will return (int?) type. At the same time, in the if condition if (vessels?.Vessels?.Count == 0) in the question, we are trying check a (int?)==(int). Which might not worked as you expected. We can not check null to a value. That's why I have added (vessels?.Vessels?.Count ?? 0). That part will return 0 if vessels?.Vessels?.Count is null. So, value will be checked with a value.
Do this instead:
if (vessels.Vessels == null)
{
// Code
}
The null keyword is a literal that represents a null reference, one that does not refer to any object. null is not the same as 0.
In IEnumerable.First function, how do I handle the case if there are no matches? Currently it just crashes...
MySPListItem firstItem = itemCollection.First(item => !item.isFolder);
if (firstItem != null)
{
TreeNode firstNode = GetNodeByListItem(my_treeview.Nodes, firstItem, ReportObject);
if (firstNode != null)
{
ReportObject.log("Selecting the first PDF");
selectPDF(my_treeview, firstNode, queryStr_param);
}
}
Error Message:
Sequence contains no matching element
Stacktrace: at System.Linq.Enumerable.First[TSource](IEnumerable1 source, Func2
predicate)
Ok, If it is exceptional for there to be no first,
try
{
var first = enumerable.First();
}
catch (InvalidOperationException)
{
// Oops, that was exceptional.
}
If you anticipate that there may be no first in some valid situations,
var first = enumerable.FirstOrDefault();
if (first == default(someType)) // null for reference types.
{
// Ok, I need to deal with that.
}
While you do a null check on the find, you don't in your predicate. The line
foundItem = itemCollection.Find(item => item.item.ID == PDFID);
Might throw an exception it item is null (have you inserted an null item in the collection?) or item.item is null (are you sure it's always there?).
You could do:
foundItem = itemCollection.Find(item => item != null &&
item.item != null &&
item.item.ID == PDFID);
More chatty, but you won't get a NullReferenceException.
Edit Well you changed your question. Now you do First. The First method will throw an exception if nothing is found. Use FirstOrDefault instead which will return null for a class or the default value for a struct.
foundItem = itemCollection.FirstOrDefault(item => item != null &&
item.item != null &&
item.item.ID == PDFID);
Replace First by FirstOrDefault :
MySPListItem firstItem = itemCollection.FirstOrDefault(item => !item.isFolder);
Quoted from the MSDN website you linked to:
The first element that matches the conditions defined by the specified predicate, if found; otherwise, the default value for type T.
This describes the return value. Hence, when no match is found, the default value for type T is returned, which means null for reference types, and things such as 0, false & co. for value types.
So in your calling code, simply check for this default value, and you're fine :-). What you can not do is just use the value that is being returned, as this e.g. might result in a NullReferenceException, if you are using a reference type.
Check if the result is null:
if (result == null)
{
Console.WriteLine("Not found");
}
There is a clear example demonstrating what to do if the item is found/not found here
It shouldn't throw an exception, you need to handle the case where it returns default(T). You might be getting a NullReferenceException because you're not handling the case where it returns null. For example:
IEnumerable<Cars> cars = GetCars();
Car car = cars.Find(c => c.Model == "Astra");
if(car != null)
{
// You found a car!
}
If you were doing the same for a struct, you'd check for it's default instead. Ints for example would be a 0:
int[] ints = new int[] { 1, 4, 7 };
int myInt = ints.Find(i => i > 5);
if(myInt != 0) // 0 is default(int)
{
// You found a number
}
I'm writing a bit of code, and there is a part that gives me hassles.
I'm having the following structure in my code:
foreach (Node node in nodes)
{
try
{
bool n = node.previous == null;
}
catch (Exception e)
{
StreamWriter s = new StreamWriter("error.txt");
s.WriteLine(e.Message);
s.WriteLine("-----------");
s.Close();
}
}
In here Node is a custom type, the node.prev variable is also a custom type (Location). Running this gives the following error-log:
Object reference not set to an instance of an object.
-----------
I'm 100% sure that node isn't null (which should be made impossible by foreach = Not true, sorry!). Also, as you can see in the following listing, the Node.previous is set to null at declaration:
public class Node
{
public Location previous = null;
public Location location;
public int distance;
...
...
}
I have no idea how I can fix these exeptions occuring, and I'm kind of at the end of having any ideas on how to solve this. Can anybody help me with this?
Note that these are all not the final code, but I sifted the parts that didn't matter!
Thanks in advance,
Delpee
EDIT: Ricovox helped me to the solution with this answer, thanks a lot!
So I'm posting another answer in response to your comment:
"I have checked for node being null, it isn't, at any point."
If that IS true, there here are some other options;
Take a look at the node.previous class/struct definition. It COULD implement a CUSTOM == operator that throws an error when compared to null. As an example, think about the Nullable<T> type. It has an overloaded == operator that returns true if the HasValue property is false (obviously, since it is a struct it isn't truly null, but overloading the operator gives the desired behavior.) To fix this, you could test object.ReferenceEquals(node.previous, null) which wouldn't be overloaded. If you have access to change the node.previous definition, perhaps you can find out why the overloaded operator throws an exception when compared to null (which it obviously shouldn't)
nodes could be null, in which case it is the foreach statement that is throwing the error. Test nodes == null before the foreach.
---------------Edit---------------
As Jeppe pointed out, my analogy with Nullable<T> (in option #1, above) could be misleading (in fact it did confuse the discussion, although the point itself was correct). In order to better illustrate the idea of overriding the == operator, I've posted an example below that demonstrates the Container type. This type is a struct, so it can never be null itself, but it contains a single Value object.
(The point of this struct is that you can work with any Container object without worrying whether or not it is null, even though the contained Value object might be null). The main thing to note is that when a Container is compared with == to null, the result will be true if Value is null, which would NOT be true if the == operator weren't overridden (because a struct can never be null).
public struct Container {
public object Value { get; set; }
public bool IsNull { get { return Value == null; } }
public static bool operator ==(Container x, object y) { return x.Equals(y); }
public static bool operator !=(Container x, object y) { return !x.Equals(y); }
public override bool Equals(object obj) {
if (obj is Container)
return Value == ((Container)obj).Value;
return Value == obj;
}
public override int GetHashCode() { return Value == null ? 0 : Value.GetHashCode(); }
}
////---------Test----------
var x = new Container { Value = null };
var y = new Container { Value = "hi" };
var z = new Container { Value = null };
Print(x == null); //true
Print(x == y); //false
Print(x == z); //true
And just in case you are wondering how overriding == would affect a class, I've written another example below that demonstrates a Box class. It's similar to the Container struct, except that we have to deal with the case in which the Box object is null itself. Note that in this case, there is another surprising result of overriding ==. Two reference types can be equal (==) to each other, even if they reference different objects, as long as they have equal Value properties.
public class Box {
public static bool ItemsEqual(object x, object y) {
object xval, yval;
xval = x is Box ? (x as Box).Value : x;
yval = y is Box ? (y as Box).Value : y;
return xval == yval;
}
public object Value { get; set; }
public bool IsNull { get { return Value == null; } }
public static bool operator ==(Box x, object y) { return ItemsEqual(x, y); }
public static bool operator !=(Box x, object y) { return !ItemsEqual(x, y); }
public override bool Equals(object obj) { return ItemsEqual(this, obj); }
public override int GetHashCode() { return Value == null ? 0 : Value.GetHashCode(); }
}
////---------Test----------
object n = null;
Box w = null;
Box x = new Box { Value = null };
Box y = new Box { Value = "hi" };
Box z = new Box { Value = "hi" };
Print(w == null); //true (uses overridden '==' because w is defined as a Box)
Print(w == n); //true
Print(x == w); //true
Print(x == null); //true
Print(x == n); //true
Print(w == y); //false
Print(x == y); //false
Print(y == z); //true (actual ref's differ, but values are ==)
The most likely problem is that node is null!. There is nothing about the foreach statement that would prevent node from being null, because in general an IEnumerable object (e.g. a list or collection) CAN contain null as a valid item.
No error would be thrown if previous is null (unless the node.prev class/struct overrides the == operator).
As others have mentioned, put in a test like this to verify:
foreach (Node node in nodes)
{
bool n;
try
{
if (node == null)
{
n = true; //do something to deal with a null node
}
else
{
n = node.previous == null;
}
}
catch (Exception e)
{
StreamWriter s = new StreamWriter("error.txt");
s.WriteLine(e.Message);
s.WriteLine("-----------");
s.Close();
}
}
If nodes were null the exception would occur before the loop, and the exception wouldn't be caught.
Since the previous member is a simple field, the only possibility I see is that one of the node members of your nodes collection is null. You can do this:
foreach (Node node in nodes)
{
if (node == null)
throw new Exception("I told you so");
}
EDIT: OK, it turned out there was one possibility I didn't see, and that was a broken overload of the == operator. To make sure you call the usual overload, say:
foreach (Node node in nodes)
{
bool n = (object)(node.previous) == (object)null;
}
(actually it will suffice to cast just one side of the == operator to object), or equivalently use ReferenceEquals:
foreach (Node node in nodes)
{
bool n = object.ReferenceEquals(node.previous, null);
}
But you must fix the wrong implementation of the == overload.
If you had posted the stack trace of the exception in your original question, it would have been clear to most users here on SO that the exception came from a call to your == overload. So next time, inspect your stack trace.
set a breakpoint at your line that starts with bool and verify that node is not null and that nodes is not null. My guess is that either nodes is null, or else it contains a null value if it's not a type-safe list.
There's nothing that ensures that node is not null, since Node is not a value type. Mind giving more details?
I'm 100% sure that node isn't null
But I'm 100% sure that an element in nodes is null! try this:
foreach (Node node in nodes)
{
try
{
if(null == node) throw new Exception("This is not expected!");
bool n = node.previous == null;
}
catch (Exception e)
{
if(File.Exists("error.txt")) File.Delete("error.txt");
using(StreamWriter s = new StreamWriter("error.txt")){
s.WriteLine(e.Message);
s.WriteLine("-----------");
s.Close();}
}
}
I have:
An XML with some elements.
A sub-element that may or may not be defined inside this XML.
Need to extract the value of the sub-element when it does exist.
How do I get the value without throwing object-reference errors?
For example:
string sampleXML = "<Root><Tag1>tag1value</Tag1></Root>";
//Pass in <Tag2> and the code works:
//string sampleXML = "<Root><Tag1>tag1value</Tag1><Tag2>tag2Value</Tag2></Root>";
XDocument sampleDoc = XDocument.Parse(sampleXML);
//Below code is in another method, the 'sampleDoc' is passed in. I am hoping to change only this code
XElement sampleEl = sampleDoc.Root;
string tag1 = String.IsNullOrEmpty(sampleEl.Element("Tag1").Value) ? "" : sampleEl.Element("Tag1").Value;
//NullReferenceException:
//Object reference not set to an instance of an object.
string tag2 = String.IsNullOrEmpty(sampleEl.Element("Tag2").Value) ? "" : sampleEl.Element("Tag2").Value;
You can use the null-coalescing-operator for a shortcut:
string tag1= (string)sampleEl.Element("Tag1") ?? string.Empty;
This also uses the fact that LINQ to XML allows the cast operation to get the value of the element (in this case cast to string), but returns null if the element does not exist.
You'll need to check for null in order to prevent them. Given the repeated pattern you're using I would just factor this off into an extension method.
public static string GetElementValue(this XElement parent, string elementName) {
if (parent == null) {
return string.Empty;
}
var element = parent.Element(elementName);
if (element == null || element.Value == null) {
return string.Empty;
}
return element.Value;
}
Now your above code can be replaced with the following
string tag1 = sampleEl.GetElementValue("Tag1");
string tag2 = sampleEl.GetElementValue("Tag2");
The C# ternary operator is pretty good for this:
string tag2 = sampleEl.Element("Tag2") == null ? "" : sampleEl.Element("Tag2").Value;
First you should check if the document is null, remember you are accessing the .Value and this will throw a null reference exception so before you apply .value do a test:
if (sampleEl != null)
//now apply .value
Or ternary:
string tag2 = sampleEl.Element("Tag2") != null ? sampleEL.Element("Tag2").Value : String.Empty
Your code then becomes:
string sampleXML = "<Root><Tag1>tag1value</Tag1></Root>";
//Pass in <Tag2> and the code works:
//string sampleXML = "<Root><Tag1>tag1value</Tag1><Tag2>tag2Value</Tag2></Root>";
XDocument sampleDoc = XDocument.Parse(sampleXML);
//Below code is in another method, the 'sampleDoc' is passed in. I am hoping to change only this code
XElement sampleEl = sampleDoc.Root;
string tag1 = sampleEl.Element("Tag1") != null ? sampleEl.Element("Tag1").Value : String.Empty;
//NullReferenceException:
//Object reference not set to an instance of an object.
string tag2 = sampleEl.Element("Tag2") != null ? sampleEL.Element("Tag2").Value : String.Empty
string tag1 = sampleEl.Element("Tag1") != null ? sampleEl.Element("Tag1").Value : string.Empty;
I came up with this extension method. It requires you to specify the property to access as a lambda, and a default value to use if the actual value or anything up the chain is null:
public static TOut ValueOrDefault<TIn, TOut>(this TIn input, Func<TIn, TOut> projection, TOut defaultValue)
where TOut : class
{
try
{
return projection(input) ?? defaultValue;
}
catch (NullReferenceException)
{
return defaultValue;
}
catch (InvalidOperationException)
{
return defaultValue;
}
}
Usage:
var value = topObject.ValueOrDefault(x=>x.ChildObject.AnotherChild.ChildProperty, String.Empty);
value will be the empty string if topObject, ChildObject, AnotherChild, or ChildProperty are null. If all of those are valid references, the return will be whatever ChildProperty actually is (which could still be the empty string). The catch for the NullReferenceException handles references of child members of a null reference. For nullable types, InvalidOperationException is thrown when accessing the Value property of a null nullable type.
C# 6.0 allows us to make the expression shorter and simpler:
string uniqueIdentifier = myNode.Document?.Element("elem1")?.Element("elem2")?.Attribute("attribute1")?.Value;
Just for the fun of it, here's a solution using LINQ to XML which
requires only one statement and
does not need the ternary operator, so you don't need to specify the name of the tag twice:
string tag1 = sampleEl.Elements("Tag1").Select(x => x.Value).FirstOrDefault();
string tag2 = sampleEl.Elements("Tag2").Select(x => x.Value).FirstOrDefault();
Add ?? "" if you want the empty string instead of null if the tag does not exist.
What is the best way to deal with null values in Linq.
I have this code which retrieves the customer contacts from the db but if the contact details don't exist it creates a new instance
void SetProperty(int _CustomerID)
{
Contacts_GetResult Contact;
if (Global.VariableStore._Contact == null)
{
Contact = Cd.Contacts_Get(_CustomerID).SingleOrDefault();
if (Contact == null)
Contact = new Contacts_GetResult();
Global.VariableStore._Contact = Contact;
}
else
{
Contact = Global.VariableStore._Contact;
}
if (Contact != null)
{
HomeNumber.Value = Contact.HomeNumber.ToString();
MobileNumber.Value = Contact.MobileNumber.ToString();
WorkNumber.Value = Contact.WorkNumber.ToString();
EmailAddress.Value = Contact.EmailAddress.ToString();
}
When it create the new contacts all the values are null which makes the below code fail as the value is null
HomeNumber.Value = Contact.HomeNumber.ToString();
I currently use:
if (Contact.HomeNumber != null)
HomeNumber.Value = Contact.HomeNumber.ToString();
Is there an easier way?
There is a number of ways, all of which include checking for null one way or the other:
if (Contact.HomeNumber != null)
HomeNumber.Value = Contact.HomeNumber.ToString();
HomeNumber.Value = (Contact.HomeNumber ?? string.Empty).ToString();
HomeNumber.Value = Contact.HomeNumber != null
? Contact.HomeNumber.ToString()
: string.Empty;
There is a slight difference in that the last two samples will substitute the null value with an empty string. In the case of the ?? operator, there is nothing much to do about that; that whole code construct is about making sure that the value is not null before operating on it. That code is the most compact of them, but comes with the downside of unnecessary calls to ToString when HomeNumber is null.
In the case of the ?: operator, that sample can easily be altered to return null instead of an empty string:
HomeNumber.Value = Contact.HomeNumber != null
? Contact.HomeNumber.ToString()
: null;
I use the following extension method to (somewhat) simplify guarding against null instances:
public static V ValueOrDefaultIfNull<T, V>(this T #this, Func<T, V> #value, V #default)
{
return #this != null ? #value(#this) : #default;
}
So now I can make calls like this:
HomeNumber.Value = Contact.ValueOrDefaultIfNull(x => x.HomeNumber.ToString(), "N/A");