Change value of property - c#

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.

Related

C# bool value as string is always null

I'm attempting to dump variable property information to a simple string but when it gets to my nullable bools, the as string always returns null --even if the actual value is true | false!
StringBuilder propertyDump = new StringBuilder();
foreach(PropertyInfo property in typeof(MyClass).GetProperties())
{
propertyDump.Append(property.Name)
.Append(":")
.Append(property.GetValue(myClassInstance, null) as string);
}
return propertyDump.ToString();
No exceptions are thrown; quick and the output is exactly what I want except any properties that are bool? are always false. If I quick watch and do .ToString() it works! But I can't guarantee other properties are not, in fact, null.
Can anyone explain why this is? and even better, a workaround?
A bool is not a string, so the as operator returns null when you pass it a boxed boolean.
In your case, you could use something like:
object value = property.GetValue(myClassInstance, null);
propertyDump.Append(property.Name)
.Append(":")
.Append(value == null ? "null" : value.ToString());
If you want to have null values just not append any text, you can just use Append(Object) directly:
propertyDump.Append(property.Name)
.Append(":")
.Append(property.GetValue(myClassInstance, null));
This will work, but leave null properties in your "propertyDump" output as missing entries.
The as operator returns a casted value if the instance is of that exact type, or null otherwise.
Instead, you just should .Append(property.GetValue(...)); Append() will automatically handle nulls and conversions.
The nicest solution would be, in my opinion:
.Append(property.GetValue(myClassInstance, null) ?? "null");
If the value is null, it will append "null", and if not - it will call the value's ToString and append that.
Combining that with Linq instead of a foreach loop, you can have a nice little something:
var propertyDump =
string.Join(Environment.NewLine,
typeof(myClass).GetProperties().Select(
pi => string.Format("{0}: {1}",
pi.Name,
pi.GetValue(myClassInstance, null) ?? "null")));
(Looks nicer in the wide screen of VS).
If you compare speeds, by the way, it turns out the string.Join is faster than Appending to a StringBuilder, so I thought you might want to see this solution.
That's because the type of the property is not string. Change it to:
Convert.ToString(property.GetValue(myClassInstance, null))
If it's null, it will retrieve null and that's ok. For non-null values it will return the string representation of the value of the property.
You cannot cast a bool to a string. You must use ToString()
Use the null coalesing operator to handle the Null situations:
void Main()
{
TestIt tbTrue = new TestIt() { BValue = true }; // Comment out assignment to see null
var result =
tbTrue.GetType()
.GetProperties()
.FirstOrDefault( prp => prp.Name == "BValue" )
.GetValue( tb, null ) ?? false.ToString();
Console.WriteLine ( result ); // True
}
public class TestIt
{
public bool? BValue { get; set; }
}

is there a sort of isset() on .NET/C#?

I need to check if there is a param on the uri request.
So I need to check if that param is set. Is there a function on .NET/C#?
An unset value will be null or empty:
value = Request["param"];
if (String.IsNullOrEmpty(value))
{
// param is not set
}
If the param name is in the query string but the value is not, it will be empty. If the name is not in the query string, the value will be null. For example.
&param1=&param2=value
// Request["param1"] is String.Empty
// Request["param3"] is null
Yes, you can use HttpUtility.ParseQueryString() utility method which returns NameValueCollection and then cust call Get():
bool contains = HttpUtility.ParseQueryString(uri.Query)
.Get("ParameterName") != null;
Get() method
Returns A String that contains a comma-separated list of the values associated
with the specified key from the NameValueCollection, if found;
otherwise, null
EDIT:
If you have an instance of the HttpRequest then just use built in indexer like below:
bool contains = Request["ParamName"] != null;
In c# not implemented object is NULL. But if you try to acces to this object you will get the exception. You cat try to catch it or just add # before your variable.
So C# isset looks like this (for array of strings)
// Isset
internal static bool isset(String[] m, int index)
{
return (#m[index] == null) ? false : true;
}
Use it like this: if (App.isset(parts, 1)) cat = parts[1];
Or just "in plase" solution
if (#parts[1] != null) cat = parts[1];
I hope this ansver will help you.
You could use try and catch to wrap your uri request?
catch for NullReferenceException or just exception?

How to i return the value of a property if i dont know the propertyname at run-time?

And let's assume for simplicity that the value of the property needs to always be returned as a string.
public string GetTheValueOfTheProperty(PropertyInfo propertyInfo,Object myObject){
string propname = propertyInfo.Name;
if (propName == "IsSelected"){
return myObject.IsSelected.ToString();
}
//...
}
This works, but it doesn't work if I don't know the name of the property. How would I do that in that scenario ?
http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getvalue.aspx
You can call propertyInfo.GetValue(myObject, null);.
You can convert to a string with ToString(), but you should check for null values first - otherwise you'll get a NullReferenceException.
The PropertyInfo object lets you invoke the property on the object:
object value = propertyInfo.GetGetMethod().Invoke(myObject, new object[] { });

how can I check whether the session is exist or with empty value or null in .net c#

Does anyone know how can I check whether a session is empty or null in .net c# web-applications?
Example:
I have the following code:
ixCardType.SelectedValue = Session["ixCardType"].ToString();
It's always display me error for Session["ixCardType"] (error message: Object reference not set to an instance of an object). Anyway I can check the session before go to the .ToString() ??
Something as simple as an 'if' should work.
if(Session["ixCardType"] != null)
ixCardType.SelectedValue = Session["ixCardType"].ToString();
Or something like this if you want the empty string when the session value is null:
ixCardType.SelectedValue = Session["ixCardType"] == null? "" : Session["ixCardType"].ToString();
Cast the object using the as operator, which returns null if the value fails to cast to the desired class type, or if it's null itself.
string value = Session["ixCardType"] as string;
if (String.IsNullOrEmpty(value))
{
// null or empty
}
You can assign the result to a variable, and test it for null/empty prior to calling ToString():
var cardType = Session["ixCardType"];
if (cardType != null)
{
ixCardType.SelectedValue = cardType.ToString();
}

How to set the value of a property if it is null?

I am trying to write my first WCF Service. Right now I just want to take a bunch of properties of an object and write them to SQL Server.
Not all the property values will always be set so I would like to receive the object on the service side, loop through all the properties on the object and if there are any of a string datatype that are not set, set the value to "?".
All the properties of object are defined of type string
I am trying the following code found here but get the error "Object does not match target type." on the line indicated below
foreach (PropertyInfo pInfo in typeof(item).GetProperties())
{
if (pInfo.PropertyType == typeof(String))
{
if (pInfo.GetValue(this, null) == "")
//The above line results in "Object does not match target type."
{
pInfo.SetValue(this, "?", null);
}
}
}
How should I be checking if a property of string type on an object has not been set?
The value returned from PropertyInfo.GetValue is object. However, since you know the value is a string (because you checked in the line above) you can tell the compiler "I know this is a string" by doing a cast:
if (pInfo.PropertyType == typeof(String))
{
string value = (string) pInfo.GetValue(this, null);
if (value == "")
{
Also, I would add an extra null check in there, just in case the value is null or empty. Luckily, there's the string.IsNullOrEmpty method for that:
if (pInfo.PropertyType == typeof(String))
{
string value = (string) pInfo.GetValue(this, null);
if (string.IsNullOrEmpty(value))
{

Categories