DataRow to bool casting - c#

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

Related

Null value causing issue saving to the database

I am trying to convert a text box into a decimal when I try this method it says that inpurt string was not in correct format what is the best way around this.
_record.houseHoldArrearsAmount = Convert.ToDecimal(txtArrearsAmount.Text)
I persume it is because text is "" null and and 0.00 hence it falls over
The compiler run time is causing an exception
The input is blank if the user has not entered a value as of yet
If you know that the text is always going to be a number you can still use Convert but check that the string isn't empty first:
if (!string.IsNullOrWhitespace(txtArrearsAmount.Text))
{
_record.houseHoldArrearsAmount = Convert.ToDecimal(txtArrearsAmount.Text);
}
Obviously this won't update the houseHoldArrearsAmount if it's not a numeric value. What you do in this case depends on your business model. You might want to set it to 0 or you might want to leave it with the old value and report and error.
Alternatively, if the input could be any string, you can use Decimal.TryParse to convert the string to a number.
decimal result;
if (decimal.TryParse(txtArrearsAmount.Text, out result))
{
_record.houseHoldArrearsAmount = result;
}
You can use "TryParse" funtion.
decimal householdArrearsAmount = decimal.Zero;
decimal.TryParse(txtArrearsAmount.Text, out householdArrearsAmount);
_record.householdArrearsAmount = householdArrearsAmount;
You can't use the null coalescing operator (as your suggested in comments), as the string value of the textbox won't be null, it will be an empty string.
You could do the following:
_record.householdArrearsAmount =
(string.IsNullOrWhiteSpace(txtArrearsAmount.Text) ? 0 :
Convert.ToDecimal(txtArrearsAmount.Text));

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

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");

Compare string null or empty in c#

In my table of MySQL Db I have the field Check.
The value memorized on the field Check it could be : null or -1.
When the value memorized on the field Check is null or -1 I need in return the xxx value. and I have tried :
string Check = sdr["Check"] == DBNull.Value || sdr["Check"] == "-1,00" ? "xxx" : sdr["Check"].ToString();
Without success because the output is always -1,00.
How to do resolve this?
Please help me, thank you so much in advance.
The problem is that you are comparing the wrong objects. The values returned from System.Data result sets are wrappers around the actual value. What you want are the typed versions. Basically, the check should look like this:
int checkIndex = sdr.GetOrdinal("Check");
string Check = sdr.IsDBNull(checkIndex) || (sdr.GetString(checkIndex) == "-1,00") ? "xxx" : sdr.GetString(checkIndex);
If you "Check" is actually a number, you may want to use the IntValue("Check") call, just to deal with globalization issues if your app is ever deployed where they use a "." instead of a "," for your decimal point.
See https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx for the full API.
If your MySQL database is not set to use the same locale formatting as your C# application, your assumptions about number formats could be incorrect. To make a more robust version of your check, I would recommend something like this:
int checkIndex = sdr.GetOrdinal("Check");
string Check = "xxx";
double checkValue = sdr.IsDBNull(checkIndex) ? -1 : Convert.ToDouble(sdr[checkIndex]);
if (checkValue != -1)
{
Check = checkValue.ToString(CultureInfo.CurrentCulture);
}
If the data type is decimal 10,2 you need Convert.ToDecimal the value :
string Check = (sdr["Check"] == DBNull.Value || Convert.ToDecimal(sdr["Check"]) == -1) ? "xxx" : sdr["Check"].ToString();
You can compare a string empty or null by below code
string str = Your string
if(String.IsNullOrEmpty(str))
{
if yes, it comes here
}
else
{
if not, it comes here
}
The String.IsNullOrEmpty() is a bool type.

Replace string value with '0' when string is empty

I'm taking a value from a textbox and converting it to decimal. But, the textbox value could be empty. So, how could I handle empty strings from the textbox?
Unfortunately I have around 50 textboxes to deal with, so answers like 'check for null with IF condition' won't help me. My code will look ugly if I use all those IF conditions.
I have this
Convert.ToDecimal(txtSample.Text)
To handle nulls, I did this
Convert.ToDecimal(txtSample.Text = string.IsNullOrEmpty(txtSample.Text) ? "0" : txtSample.Text)
But, the above code is displaying '0' in the textbox. User does not want to see '0'. Another solution is to take text box value into a variable and convert the variable like below.
string variable = txtSample.Text;
Convert.ToDecimal(variable = string.IsNullOrEmpty(variable) ? "0" : variable)
But again, I do not want to define around 50 variables. I am looking for some piece of code that handles null values during conversion without adding the extra line of code.
But, the above code is displaying '0' in the textbox. User does not want to see '0'.
This is because your statement is assigning the new value to txtSample.Text (when you do txtSample.Text = ...). Just remove the assignment:
Convert.ToDecimal(string.IsNullOrEmpty(txtSample.Text) ? "0" : txtSample.Text)
To make things easier if you have many text fields to handle, you can define an extension method :
public static string ZeroIfEmpty(this string s)
{
return string.IsNullOrEmpty(s) ? "0" : s;
}
And use it like this:
Convert.ToDecimal(txtSample.Text.ZeroIfEmpty())
You could make a function to keep from copying the code all over the place.
decimal GetTextboxValue(string textboxText)
{
return Convert.ToDecimal(string.IsNullOrEmpty(textboxText) ? "0" : textboxText);
}
and then use it like this:
GetTextboxValue(txtSample.Text);
You can create an extension method for the string as below
public static decimal ToDecimal(this string strValue)
{
decimal d;
if (decimal.TryParse(strValue, out d))
return d;
return 0;
}
Then you can just txtSample.Text.ToDecimal() in every place.

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')

Categories