Take for example the following extract from a mongo collection :
{"IsBasedOnProduct" : {
"CodeUV" : "09184",
"Name" : null,
"pricingVersion" : "B"
}
}
I would like to extract the Name field from this collection and put it in a C# object. But i do not know how to manage the null value.
This is what I am doing in my C# application :
if (foo.Contains("IsBasedOnProduct"))
{
fooToExcel.Name = foo["IsBasedOnProduct"].AsBsonDocument.Contains("Name") ? foo["IsBasedOnProduct"]["Name"].AsString : string.Empty;
}
Of course when the Name is null, i throw an System.ArgumentNullException
How can I fix it in order to put string.Empty when the value is null ?
Fix it using the following snapshot of code :
if (foo.Contains("IsBasedOnProduct") && foo["IsBasedOnProduct"].BsonType != BsonType.Null)
{
fooToExcel.Name = foo["IsBasedOnProduct"].AsBsonDocument.Contains("Name")&& foo["IsBasedOnProduct"]["Name"].BsonType != BsonType.Null ?
foo["IsBasedOnProduct"]["Name"].AsString : string.Empty;
}
Before that you have to Convert BJson to JSON, check after the conditions.
#Xavier W answer correct Also there another solution to check was BsonValue is NULL using IsBsonNull property [since MongoDB.Bson version 2.3.0]
Here solution:
if (foo.Contains("IsBasedOnProduct") && !foo["IsBasedOnProduct"].IsBsonNull)
{
fooToExcel.Name = (foo["IsBasedOnProduct"].AsBsonDocument.Contains("Name") && !foo["IsBasedOnProduct"]["Name"].IsBsonNull) ?
foo["IsBasedOnProduct"]["Name"].AsString : string.Empty;
}
Documention for IsBsonNull Property -> https://mongodb.github.io/mongo-csharp-driver/2.3/apidocs/html/P_MongoDB_Bson_BsonValue_IsBsonNull.htm
Related
I'm having an issue changing the value of a JSON property.
I want to check if my JSON property is an empty object and if so change the value to null. I figured out how to check if the property is an empty object but I can't figure out how to change the value.
My JSON:
{
"payload": {}
}
My goal:
{
"payload": null
}
What I have so far:
JToken payloadProperty = data["payload"];
if (payloadProperty != null && payloadProperty.Type == JTokenType.Object && !payloadProperty.HasValues)
{
// WHAT TO PUT HERE TO SET "payload" TO NULL
}
What is the porpouse of all of this? you can just use string function
myJson="{ \"payload\": {} }";
myJson=myJson.Replace("\"payload\": {}", "\"payload\": null");
or if you have only payload, or have the same problems with another properties you can try this
myJson=myJson.Replace("{}", "null");
I figured out the solution. I was able to set the "payload" to null directly. I originally thought it was some method or property on some JSON.NET class.
I just did this
JToken payloadProperty = data["payload"];
if (payloadProperty != null && payloadProperty.Type == JTokenType.Object)
{
data["payload"] = null;
}
This results in not needing to know the exact string contents which could have extra spaces, etc.
I am using gridview's default update method in which it allows me to update row in gridview itself by converting cells into textboxes.
I want to check validations that if a particular textbox (cell) remains empty or blank then it should not update its value.
For that i have written following code:
string.IsNullOrEmpty(e.NewValues[0].ToString())
But it gives an error like object reference not set to an instance of an object. May be it can not convert null value of e.Newvalues[0] to string.
All answers are appreciated in advance.
You could do this:
e.NewValues[0] == null || e.NewValues[0].ToString() == string.Empty
If e.NewValues[0] is already a string, you could just do this:
string.IsNullOrEmpty(e.NewValues[0])
Update as of C# 6, you could also use:
string.IsNullOrEmpty(e.NewValues[0]?.ToString())
Or even:
$"{e.NewValues[0]}" == string.Empty
Another way:
String.IsNullOrEmpty(Convert.ToString(e.NewValues[0]));
A bit of (probably unneeded) explanation:
Convert.ToString() will return null for a (string)null, and an empty string for an (object)null (or any other null).
Either case will give the expected result, because we're checking with String.IsNullOrEmpty().
In any case, its behaviour is the same as someValue.ToString() except it handles the cases where someValue is null.
Another (wasteful) way to do it is with a singleton with an overridden ToString and ?? (overkill but it lets me use ?? :P)
(e.NewValues[0] ?? Empty._).ToString();
The code for the singleton is here:
public sealed class Empty
{
private static readonly Lazy<Empty> lazy =
new Lazy<Empty>(() => new Empty());
public override string ToString()
{
return "";
}
public static object _ { get { return lazy.Value; } }
private Empty()
{
}
}
You can use this piece of code
(e.NewValues[0] == null) ? string.Empty : e.NewValues[0].ToString()
The above code will will return the string equivalent if not null, otherwise it will return empty string.
Otherwise you can use following code. This will handle the null case.
string.IsNullOrEmpty(Convert.ToString( e.NewValues[0] )
You'll need to check that e.NewValues[0] isn't null prior to doing a .ToString() on it.
protected void grd_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = grd.Rows[e.RowIndex];
for (int i = 0; i <= row.Cells.Count; i++)
{
String str = ((TextBox)(row.Cells[i].Controls[0])).Text;
if (!string.IsNullOrEmpty(str))
{
//Your Code goes here ::
}
}
}
I have the following code where I am using a Conditional Operator to look for null values and assign another value if a null is found. My problem is that it isn't detecting the null value correctly for some reason.
sliderQuestion11.Value = Convert.ToDouble(cs.q11 != null ? cs.q11 : "10");
cs is a class populated by a SQLite query and q11 is a string.
I get a "Value cannot be null" error. Thanks.
EDIT
Thanks for the help everyone. All those answers should have worked but what I had to do is instead of just returning
query.FirstOrDefault()
I had to do the following
CustomerSurvey cs = new CustomerSurvey();
cs.q1 = query.FirstOrDefault().q1 ?? "-10";
cs.q2 = query.FirstOrDefault().q2 ?? "-10";
cs.q3 = query.FirstOrDefault().q3 ?? "-10";
cs.srID = query.FirstOrDefault().srID;
Now this works
sliderQuestion11.Value = Convert.ToDouble(cs.q11 != "-10" ? cs.q11 : "10");
(I know you are going to say why not just set it to 10 but I need to detect a null value elsewhere in the code. That is why I'm using -10)
Maybe you need:
!string.IsNullOrEmpty(cs.q11) ? cs.qll : "10";
The reason for using string.IsNullOrEmpty is because the string may just be empty rather than null.
Full snippet:
sliderQuestion11.Value = Convert.ToDouble(!string.IsNullOrEmpty(cs.q11) ? cs.qll : "10");
You could also try this code:
sliderQuestion11.Value = Convert.ToDouble(cs.q11 ?? "10");
Perhaps it should be
sliderQuestion11.Value = (cs != null && (!string.IsNullOrWhitespace(cs.q11)) ? Convert.ToDouble(cs.q11) : 10);
sliderQuestion11.Value = Convert.ToDouble(!string.IsNullOrWhiteSpace(cs.q11) ? cs.q11 : "10");
This would also check that the string does not contain just 1 or more whitespaces, in addition to the null and empty checks.
Yet another answer: :)
sliderQuestion11.Value = string.IsNullOrWhitespace(cs.q11) ? 10.0 : Convert.ToDouble(cs.q11);
I'm trying to check for DBNull.Value but in this case reader["Preferences"] returns {} in the immediate window (why?)
so when (string)reader["Preferences"]; executes I get a type casting error
if (reader["Preferences"] == System.DBNull.Value)
{
preferences = (string)reader["Preferences"];
}
You are trying to cast only when the value is DBNull.Value.
You should invert your if:
if (reader["Preferences"] != System.DBNull.Value)
{
preferences = (string)reader["Preferences"];
}
I’m using Linq to extract values from some XML. Shown below is a simplified example to show the problem I’m having. The following code works fine on the XML shown below. The problem I have is when the groupBy section is missing. Because when it’s missing Data.Element("groupBy").Element("property) fails because Data.Element("groupBy") will be null. Is it possible to modify my Linq statement to allow it to provide a default or should it be approached in a different way?
var e = (from Data in theXML.Descendants("exportFile")
select new Export
{
OutputFileName = Data.Element("outputFileName") != null ? (string)Data.Element("outputFileName") : "",
GroupByProperty = Data.Element("groupBy").Element("property") != null ? (string)Data.Element("groupBy").Element("property") : ""
}).First();
<exportFile>
<outputFileName>output.xml</outputFileName>
<groupBy>
<property>DeviceId</property>
</groupBy>
</exportFile>
You can already make it slightly nicer than it is using the null coalescing operator. However, to cope with the groupby element being missing is harder:
select new Export
{
OutputFileName = (string) Data.Element("outputFileName") ?? "",
GroupByProperty = Data.Element("groupBy") == null ? ""
: (string) Data.Element("groupBy").Element("property") ?? ""
}).First();
The conversion to string just returns null if the element reference is null.
An alternative would be:
GroupByProperty =
(string) Data.Elements("groupBy").Elements("property").FirstOrDefault() ?? ""
That uses the extension method which allows you to call Elements on an IEnumerable<XElement>... so that will (lazily) evaluate a sequence of every property element under a groupBy element under Data, then take the first of them if any exist, then apply the string conversion.
You could simply add an additional check in the statement (and clean things up a bit using the null coalescing operator):
GroupByProperty = Data.Element("groupBy") != null ?
(Data.Element("groupBy").Element("property") ?? "") : "";