How to preserve null values in string interpolation C# - c#

I want to keep the null values (insert them to DB) while i pass them over as a string to the sql variable in my C# code.
var valString = new StringBuilder();
//somevalue is null at this point
valString.Append($"({id}, " +$"'{SomeValue}')");
The string interpolation is returning an emptyString for SomeValue => '' instead of null.
I want to preserve that null in the string interpolation and pass it to the query string.
Is it possible?

This will use SomeValue if it isn't null, and use NULL if it is.
var valString = new StringBuilder();
//somevalue is null at this point
valString.Append($"({id}," + (SomeValue == null ? "NULL" : $"'{SomeValue}'"));

you can do this as follows:
var valString = new StringBuilder();
valString.Append($"({id}, " +$"'{SomeValue ?? "null"}')");

Related

error in LINQ while converting IPaddress to String using C# and PostgreSQL database

How to convert IPAddress to String is not that enough to use .ToString()?
I do it in LINQ and I get :
Object reference not set to an instance of an object
here is my code:
var x = (from t in db.v_vpn_gateway.AsEnumerable()
select new TurbineDvce
{
Comments = "VPN Gateway",
Description = string.Empty,
DeviceType = t.device_type,
TurbineId = t.turbine_id.ToString(),
Username = string.Empty
})
TurbineId is string
Because t.turbine_id is null so you can't add .ToString() Do a null check, then add .ToString()
TurbineId = t.turbine_id ?? t.turbine_id.ToString()

Dealing with empty cells when importing Excel file using EPPlus

I want to import data from Excel to DataBase using EPPLUS. From here I took code: https://www.paragon-inc.com/resources/blogs-posts/easy_excel_interaction_pt6
The problem is that sometimes in excel are empty Cells. And if cell is empty then I receive an error: NullReferenceException, and my application stops. I think good solution would be assign null value to specific variable if there is no reference e.g. if(LAST_NAME returns NullReferenceException then LAST_NAME = null) - but I don't know how to do this in code.
var newRecord = new DB_USER
{
ID = Int32.Parse(worksheet.Cells[idColumn + row].Value.ToString()),
FIRST_NAME = worksheet.Cells[firstNameColumn + row].Value.ToString(),
LAST_NAME = worksheet.Cells[lastNameColumn + row].Value.ToString() //If this value has NullReferenceException then assign null or ""
};
I thing its fine to assign a empty string i.e. string.Empty for empty cells .And if you are fine you can put it this way :
var newRecord = new DB_USER
{
ID = Int32.Parse(worksheet.Cells[idColumn + row].Value.ToString()),
FIRST_NAME = worksheet.Cells[firstNameColumn + row].Value.ToString(),
LAST_NAME = worksheet.Cells[lastNameColumn + row].Value ?? string.Empty).ToString() //for a null value assign a empty string else the string value
};
A cleaner approach would be Extension method :
public static string ToNullSafeString(this object obj)
{
return (obj ?? string.Empty).ToString();
}
and use it as :
LAST_NAME = worksheet.Cells[lastNameColumn + row].Value.ToNullSafeString();
still if you wish to return a null instead of string.Empty then a slight modification to ToNullSafeString extension method above will work.
If you are using the latest C# version (6.0) then you can use the null propagation operator:
LAST_NAME = worksheet?.Cells[lastNameColumn + row]?.Value?.ToString()

Streamwriter unresponsive to conditionals

I'm trying to test for null values of two particular fields, and if they're null, replace the whitespace with the amount of 0s appropriate for that field. My code below gives no errors, but isn't doing anything and the normal values are being used.
var replace1 = "00";
var replace2 = "0";
var downpay = _Reader[26].ToString();
var preauth = _Reader[28].ToString();
if(downpay == null || downpay == " ") { downpay = replace1; }
if(preauth == null || preauth == " ") { preauth = replace2; }
writer.WriteLine("{0}{1}{2}{3}{5}{6}{7}{15}{16}{17}{18}{19}{20} 0{21}{22}{23}{24}{25}{26}{27}{28}{29}{30}{31}{32}{33}{34}{35}{36}{37} {38}{39}{40}{41}{42}{43}{44}{45}{46}{47}{48}{49} {50}", _Reader[1], _Reader[2], _Reader[3], _Reader[4], _Reader[5], _Reader[6], _Reader[7], _Reader[8], _Reader[9], _Reader[10], _Reader[11], _Reader[12], _Reader[13], _Reader[14], _Reader[15], _Reader[16], _Reader[17], _Reader[18], _Reader[19], _Reader[20], _Reader[21], _Reader[22], _Reader[23], _Reader[24], _Reader[25], downpay, _Reader[27], preauth, _Reader[29], _Reader[30], _Reader[31], _Reader[32], _Reader[33], _Reader[34], _Reader[35], _Reader[36], _Reader[37], _Reader[38], _Reader[39], _Reader[40], _Reader[41], _Reader[42], _Reader[43], _Reader[44], _Reader[45], _Reader[46], _Reader[47], _Reader[48], _Reader[49], _Reader[50], date3);
Update: Fixed the issue using the debugger. The values were \00 and \0, even though when i copy from the field in sql server it's empty.

is a conditional string.join<object> from DataRow more efficient than a string.replace?

Here's the working code I have:
DataSet myDataSet = new DataSet();
mySqlDataAdapter.Fill(myDataSet);
DataTable positionData = myDataSet.Tables["Table"];
if (siteData.Rows.Count > 0)
{
positionDV = string.Join<object>(", ",
from r in siteData.Rows.OfType<DataRow>() select r[1]);
}
else
{
positionDV = "";
}
The content of positionDV looks like this "14, 47, 5, , 11" etc. where there is a blank space for each NULL value in the database.
What I would like to achieve is that the values which are NULL are actually written to the string as NULL. So the above example would look like "14, 47, 5, null, 11".
positionDV is just one string shown for brevity, in reality there are dozens per dataset, with close to 100,000 values each.
What I am looking for is a way to insert null instead of a space. Would it be more efficient to create a conditional during the string.Join (and if so, how would I do that?), or would it be more efficient to just create the string as is and then create a separate assignment to do that like so:
positionDV += positionDV.replace(", ,", ", null,");
Just use Enumerable.Select, DataRow.Field supports nullable types. Then you can use the conditional operator (?:) to get either the int-value as string or "null" if it's empty/null:
IEnumerable<int?> positionValues = myDataSet.Tables["Table"].AsEnumerable()
.Select(r => r.Field<int?>(1));
IEnumerable<string> positions = positionValues
.Select(v => v.HasValue ? v.Value.ToString() : "null");
string positionDV = string.Join(", ", positions);

Don't have a nullReferenceException on XML Parsing

I have wrote a c# function in order to parse an XML Stream.
My XML can have several nodes.
Example :
<Stream>
<One>nnn</One>
<Two>iii</Two>
<Three>jjj</Three>
</Stream>
But sometimes, it is :
<Stream>
<Two>iii</Two>
</Stream>
Here is my c# code :
var XML = from item in XElement.Parse(strXMLStream).Descendants("Stream") select item;
string strOne = string.Empty;
string strTwo = string.Empty;
string strThree = string.Empty;
if ((item.Element("One").Value != "")
{
strOne = item.Element("One").Value;
}
if ((item.Element("Two").Value != "")
{
strTwo = item.Element("Two").Value;
}
if ((item.Element("Three").Value != "")
{
strThree = item.Element("Three").Value;
}
With this code, if my Stream is full ( Node On, Two and three), there's no problem! But, if my Stream has only the node "Two", I get a NullReferenceException.
Is there a way to avoid this exception (I cannot change my Stream).
Thanks a lot :)
You should check if item.Element("anything") is null before accessing it's Value property.
if (item.Element("Three") != null && item.Element("Three").Value != "")
You need to do:
if (item.Element("One") != null)
{
strOne = item.Element("One").Value;
}
.Element(String) returns null if an element of the name you requested does not exist.
Checking if value != "" is pointless, because all you are preventing is the reassignment of an empty string to the strOne variable, which is already an empty string. Also, if you really needed to do the empty string check, using String.IsNullOrEmpty(String) method is the preferred way.
Instead of accessing Value property (which raises NullReferenceException if element not exist, as you already know) cast elements to strings. You can use ?? to provide default value for non-existing elements:
string strOne = (string)item.Element("One") ?? String.Empty;
string strTwo = (string)item.Element("Two") ?? String.Empty;
string strThree = (string)item.Element("Three") ?? String.Empty;

Categories

Resources