Casting XElement to int? fails when xsi:nil = "true" is specified [duplicate] - c#

This question already has answers here:
LinqToXml does not handle nillable elements as expected
(3 answers)
Closed 6 years ago.
The XElement has explicit support for casting to Nullable<int> but it's not working as I expected. The following unit test demonstrates the problem:
[TestMethod]
public void CastingNullableInt()
{
var xdoc = XDocument.Parse("<root xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><okay>123</okay><boom xsi:nil=\"true\"/></root>");
Assert.AreEqual(123, (int?)xdoc.Root.Element("okay"));
Assert.IsNull((int?)xdoc.Root.Element("boom"));
}
The test should pass the last assert. Instead it gives an FormatException:
Input string was not in a correct format.
Why doesn't it parse to null correctly here?

Linq to XML is not schema aware so it will not convert xsi:nil = "true" to a nullable variable. To test this you would need to do something like:
Assert.IsTrue((bool?)xdoc.Root.Element("boom").Attribute("{http://www.w3.org/2001/XMLSchema-instance}nil") == true);

XElement does not parse <boom xsi:nil=\"true\"/> correctly. It only works if you omit <boom xsi:nil=\"true\"/>, then the value is null and it returns (int?)null.
A workaround could be to first check on the value not being empty:
!string.IsNullOrEmpty((string)xdoc.Root.Element("boom"))
? (int?)xdoc.Root.Element("boom")
: null
;

You can check IsEmpty property:
var value = xdoc.Root.Element("boom").IsEmpty ? null : (int?)xdoc.Root.Element("boom");

Related

How can I convert string to Guid? [duplicate]

This question already has answers here:
Test if string is a guid without throwing exceptions?
(19 answers)
Closed 5 years ago.
I have string type value like "e2ddfa02610e48e983824b23ac955632". I need to add - in this code means convert in Guid.
EntityKey = "e2ddfa02610e48e983824b23ac955632";
Id = (Guid)paymentRecord.EntityKey;
Just a simple creation:
String source = "e2ddfa02610e48e983824b23ac955632";
Guid result = new Guid(source);
You could do :
Guid guid;
if (Guid.TryParse("e2ddfa02610e48e983824b23ac955632", out guid))
{
// succeed...
}
else
{
// failed...
}
Edit : Like #Silvermind said, if you know the format of the input, you can use Guid.TryParseExact with the "N" format in your case.
For parsing the string to a Guid. You can do this:
var guid= "e2ddfa02610e48e983824b23ac955632";
var result= Guid.ParseExact(guid,"N")
Or if you prefer to have it in a try parse. You can also do this:
Guid result;
if(Guid.TryParseExact(guid,"N",out result))
{
//Do something
}
The "N" is a format which indicates that the string will be format with 32 digits without "-"
Reference:
Guid.TryParseExact Method (String, String, Guid)

C# System.NullException convert null to blank or no value [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
When using the following method there are use cases where one of the parameters, for this example RC_2 (datetime) may pass a null value. I need to have that null value converted into either a blank value or a string value so that it can be passed to a stringbuilder below is what I'm currently using,
public static string CHG_FixDatetime(string RC_1, string RC_2, string seperator)
{
var sb = new StringBuilder();
sb.Append(RC_1);
sb.Append(RC_2);
sb.Append(seperator);
DateTime dt;
if (!string.IsNullorWhiteSpace(RC_2))
sb.append(RC_2)
else
{
sb.Append(Convert.ToString(RC_2));
}
return sb.ToString();
}
I've tried multiple configurations and variations, but I'm unable to get past the System.NullException that is thrown when the RC_2 value is Null. Any help is appreciated.
Try the following solution
RC_2 = String.IsNullOrWhiteSpace(RC_2) ? "" : RC_2;

DataRow to bool casting

I have an xml file from which I read data in the unit test : [DataSource]
For the xml line : <DataBool>true</DataBool>, I try to read value by :
bool bData = (bool)TestContext.DataRow[4];
But it throws exception - invalid casting.What is the possible efficient solution?
If there's no schema associated with it, then it's probably just a string. If so, use bool.Parse or bool.TryParse to convert it from a string to a bool.
When you have int-tinyint value in DB :
int.Parse(dataRow["column_name"].ToString()) == 1 ? true : false

Read content as integer of empty XML element

I encountered a problem while parsing XML in C# with XMLReader.
Here is an example:
string text = xNode.ReadElementContentAsString().Length > 0 ? xBonusesNode.ReadElementContentAsString() : null;
int nmb = xNode.ReadElementContentAsInt();
So, where I'm trying to get string value there is simple inline if statement to check if element has data or not.
How can I do something similar with integer? Or how to catch exception correctly and in best way, for this?
You can use int.TryParse like this:
int number;
bool result = Int32.TryParse(xNode.ReadElementContentAsString, out number);
string text = xNode.ReadElementContentAsString().Length > 0 ? xBonusesNode.ReadElementContentAsString() : null;
Int32.TryParse(text,out myInt);
Should work.
I'm not sure whether the xml library supports nullable types (int?) but the above should work anyway - basically I'm reading it as a string then trying to parse it. If TryParse fails myInt will remain as it was before (and tryParse returns 'false')

How can I check whether a string variable is empty or null in C#? [duplicate]

This question already has answers here:
Easier way of writing null or empty?
(7 answers)
Closed 4 years ago.
How can I check whether a C# variable is an empty string "" or null?
I am looking for the simplest way to do this check. I have a variable that can be equal to "" or null. Is there a single function that can check if it's not "" or null?
if (string.IsNullOrEmpty(myString)) {
//
}
Since .NET 2.0 you can use:
// Indicates whether the specified string is null or an Empty string.
string.IsNullOrEmpty(string value);
Additionally, since .NET 4.0 there's a new method that goes a bit farther:
// Indicates whether a specified string is null, empty, or consists only of white-space characters.
string.IsNullOrWhiteSpace(string value);
if the variable is a string
bool result = string.IsNullOrEmpty(variableToTest);
if you only have an object which may or may not contain a string then
bool result = string.IsNullOrEmpty(variableToTest as string);
if (string.IsNullOrEmpty(myString))
{
. . .
. . .
}
string.IsNullOrEmpty is what you want.
Cheap trick:
Convert.ToString((object)stringVar) == ""
This works because Convert.ToString(object) returns an empty string if object is null. Convert.ToString(string) returns null if string is null.
(Or, if you're using .NET 2.0 you could always using String.IsNullOrEmpty.)

Categories