Lightswitch NullReferenceException for String in C# - c#

I am sure this is a case of basic ignorance, but I'm trying to test a database value using code behind in a Lightswitch project.
I'm checking if a varchar(MAX) value is null
if (Order.OrderNotes.Equals(null))
{
do.something...
}
However, I get a NullReferenceException if the value is null. If a value is there I get no error. I've tried using .contains(null), .Length = 0, .ToString() = "" etc without luck. It seems that ints and dates work fine using Equals(null), but not it seems for a string.
Help!!

Assuming you're calling this from a details screen where Order != null as #DeeMac pointed out.
You can check that Order isn't null using the same code below :
if (Order.OrderNotes == null)
{
// do.something...
}

if OrderNotes is null, you can't call any method, properties or whatever using that instance
you should call
if (Order.OrderNotes == null)
of course I assume that the var Order is not itself null,
if you want to be absolutely sure you could change your test in this way
if (Order != null && Order.OrderNotes == null)

In LightSwitch, to test if a nullable property has a value or not, you can use HasValue, so:
"if Order.OrderNotes.HasValue"
If you want the value if there is one, or the default value for the property type, you can use GetValueOrDefault:
"var value = Order.OrderNotes.GetValueOrDefault"
I agree wholeheartedly with Steve that you should be doing null checking on objects (such as Order) before trying to get a value from any of that object's properties.

Related

Check if child object value exists NullReferenceException

I'm pretty new to C#. While attempting to set a local variable value, I'm running into a NullReferenceException.
It appears that the Buyer object is null, which I'm assuming is why it can't figure out the Buyer.Username value. What I'm not sure about is how to check if Buyer is not null AND that the Buyer.Username has a non-null value (in the most simple way possible). Unfortunately, I'm using C# 7.3 which doesn't appear to have support for the ?? operator.
BuyerUserName = string.IsNullOrEmpty(model.Transactions[i].Buyer.Username) ? "" : model.Transactions[i].Buyer.Username
Both ?? and ?. were introduced in C# 6, so you can use them:
BuyerUserName = model.Transactions[i].Buyer?.Username ?? string.Empty;
But even without that, there is nothing wrong with taking more than one line to do something, and you could just use an if statement:
var buyer = model.Transactions[i].Buyer;
if (buyer != null && buyer.Username != null)
BuyerUserName = buyer.Username;
else
BuyerUserName = string.Empty;

How to check if session value is null or session key does not exist in asp.net mvc - 5

I have one ASP.Net MVC - 5 application and I want to check if the session value is null before accessing it. But I am not able to do so.
//Set
System.Web.HttpContext.Current.Session["TenantSessionId"] = user.SessionID;
// Access
int TenantSessionId = (int)System.Web.HttpContext.Current.Session["TenantSessionId"];
I tried many solutions from SO
Attempt
if (!string.IsNullOrEmpty(Session["TenantSessionId"] as string))
{
//The code
}
Kindly guide me.
Error: NULL Reference
if(Session["TenantSessionId"] != null)
{
// cast it and use it
// The code
}
The NullReferenceException comes from trying to cast a null value. In general, you're usually better off using as instead of a direct cast:
var tenantSessionId = Session["TenantSessionId"] as int?;
That will never raise an exception. The value of tenantSessionId will simply be null if the session variable is not set. If you have a default value, you can use the null coalesce operator to ensure there's always some value:
var tenantSessionId = Session["TenantSessionId"] as int? ?? defaultValue;
Then, it will either be the value from the session or the default value, i.e. never null.
You can also just check if the session variable is null directly:
if (Session["TenantSessionId"] != null)
{
// do something with session variable
}
However, you would need to confine all your work with the session variable to be inside this conditional.
[] acts as an indexer (like a method on the class) and in this case, session is null and you cannot perform indexing on it.
Try this..
if(Session != null && Session["TenantSessionId"] != null)
{
// code
}
Check if the session is empty/Null or not in C# MVC Version Lower than 5.
if (!string.IsNullOrEmpty(Session["TenantSessionId"] as string))
{
//cast it and use it
//business logic
}
Check if the session is empty/Null or not in C# MVC Version Above 5.
if(Session["TenantSessionId"] != null)
{
//cast it and use it
//business logic
}
There is a case when you want to check only for existence of the key itself but not the content. Above method fails when you Session key value is null also.
Eg:
Session["myKey"] = null;
if(Session["myKey"]!=null){}
In above code, I want to check if only the key (not value) exists, I will get false. But the key does exists.
So the only way I could separate this existence check, is by basically checking each key.
static bool check_for_session_key(string SessionKey)
{
foreach (var key in HttpContext.Current.Session.Keys)
{
if (key.ToString() == SessionKey) return true;
}
return false;
}
if(check_for_session_key("myKey")){} //checks for the key only
Let me know if you know better way.
Check if the session is empty/Null or not
if (!string.IsNullOrEmpty(Session["TenantSessionId"] as string))
{
//here write code for logic
}

Checking for null HttpContext.Current.Cache value

In the below snippet, I am trying to assign the cache value if the cache value does not already exist. I get an Object_reference_not_set_to_an_instance_of_an_object error when running the following. What am I missing?
if (string.IsNullOrEmpty(HttpContext.Current.Cache[Key].ToString()))
HttpContext.Current.Cache[Key] = data;
I looked around on SO but couldnt find something similar. Maybe I am just not wording my problem correctly.
HttpContext.Current could be null.
HttpContext.Current.Cache[Key] could be null.
If either of those are null, it would result in the error you are getting.
You should check for null on HttpContext.Current and on HttpContext.Current.Cache[Key], both of which could be null. Here's a possible solution, as long as you're okay with not setting the cache key if HttpContext.Current is null.
if (HttpContext.Current != null &&
(HttpContext.Current.Cache[Key] == null || string.IsNullOrEmpty(HttpContext.Current.Cache[Key].ToString()))
{
HttpContext.Current.Cache[Key] = data;
}
You are getting the NullReferenceException because you are trying to call ToString() on a null instance.
You have to check if HttpContext.Current.Cache[Key] is null before calling ToString()
if (HttpContext.Current.Cache[Key] == null)
{
HttpContext.Current.Cache[Key] = data;
}
I just changed the 'get value, convert to string, compare' logic to just get the value and see if it's null right up front. Silly me.
if (HttpContext.Current.Cache[Key] == null)
HttpContext.Current.Cache[Key] = data;
The "Object_reference_not_set_to_an_instance_of_an_object error" is actually essentially the 'null' value I was looking for...
If they key isn't present, then this would return null:
HttpContext.Current.Cache[Key]
You're then blindly calling ToString() on the value from the cache, causing the exception.
You need to assign the value from the cache to a temporary variable and test it for null before calling ToString().

How to cater for an object which can be both null or empty

I've got an object, specifically the following:
table.ExtendedProperties["MS_Description"].Value
If there is not property, the Value is null. If there is a property, but it is empty, the Value.toString() is "".
I would thus like to create an if-statement which caters for both eventualities. This is what I've done so far:
if (table.ExtendedProperties["MS_Description"] == null ||
table.ExtendedProperties["MS_Description"].Value.ToString().Equals(""))
The problem is that if it is null, it is still checking the condition on the right-hand-side.
Any ideas?
You can do:
if (table.ExtendedProperties["MS_Description"] == null || string.IsNullOrEmpty(table.ExtendedProperties["MS_Description"].Value))
The reason your code errors is because you don't check if table.ExtendedProperties["MS_Description"].Value is null.
Thus Value is not a string, then you have to deal with all conditions:
var description = table.ExtendedProperties["MS_Description"];
if (description == null ||
description.Value == null ||
description.Value.ToString().Equals(""))
// no value
BTW your code is not quite correct
if (table.ExtendedProperties["MS_Description"] == null ||
table.ExtendedProperties["MS_Description"].Value.ToString().Equals(""))
Instead of checking Value for null, you are checking if table.ExtendedProperties["MS_Description"] is not null. Thats true. You go further, but if table.ExtendedProperties["MS_Description"].Value is null (you didn't check that, remember?), you will get NullReferenceException on applying ToString().
I'm not sure if you are referring to the DataTable.ExtendedProperties property or something else, but if you are, the property returns a System.Data.PropertyCollection, which inherits from System.Collections.HashTable.
Most of the methods and properties, including the indexer ("Item") being discussed here, are directly inherited from HashTable, so in general, table.ExtendedProperties[key] can return any object, including null.
Note that you can also call DataTable.ExtendedProperties.ContainsKey(object key) to determine if the PropertyCollection contains a specific key or not.
Do you know what type of object you are retrieving when you call table.ExtendedProperties["MS_Description"].Value ?
If so, there might be other properties you can use to determine whether the property has been set, etc.
Depending on what type of object table.ExtendedProperties["MS_Description"] is, you might even be able to do something like this:
if ((table.ExtendedProperties["MS_Description"] ?? "").ToString().Length == 0) {
.....
}
That would take into account all of the possibilities:
the key doesn't exist
the key exists, but the value is null
the key exists and the value is empty
as long as the table.ExtendedProperties["MS_Decription"] object returns "" when its Value property is either null or empty.
So a little more information on the object that is returned could go a long way!
string.IsNullOrEmpty(table.ExtendedProperties["MS_Description"].Value)
It looks like table.ExtendedProperties["MS_Description"] is never null, you should be null checking the Value property instead
string value = table.ExtendedProperties["MS_Description"].Value;
if (value == null || value.ToString().Equals(""))
// OR
if (String.IsNullOrEmpty(value))
If table.ExtendedProperties["MS_Description"] can return null, then you need
if (table.ExtendedProperties["MS_Description"] == null ||
String.IsNullOrEmpty(table.ExtendedProperties["MS_Description"].Value.ToString() )
And since table.ExtendedProperties["MS_Description"].Value may return null, then you need
if (table.ExtendedProperties["MS_Description"] == null ||
table.ExtendedProperties["MS_Description"].Value == null ||
String.IsNullOrEmpty(table.ExtendedProperties["MS_Description"].Value.ToString() )

insert null value when no selected value from ddl

I had ddl which determine gender and user can donot choose any value from ddl so i tried to check if user didnot select any value from ddl inser null value or any value in database i made that but error apear(Procedure or Function 'InsertRegisteration' expects parameter '#Gender_Id', which was not supplied).any one help me
(My Code)
if (DDLGender.SelectedItem.Value[0]!= null )
{
command.Parameters.Add("#Gender_Id",SqlDbType.Int).Value=null;
}
else
{
command.Parameters.Add(Parameter.NewInt("#Gender_Id", DDLGender.SelectedValue));
}
Try this:
if (DDLGender.SelectedItem.Value[0]!= null )
{
command.Parameters.Add("#Gender_Id",SqlDbType.Int).Value= DBNull.Value;
}
else
{
command.Parameters.Add(Parameter.NewInt("#Gender_Id", DDLGender.SelectedValue));
}
Added : Difference between null and System.DbNull.Value
Well, null is not an instance of any type. Rather, it is an invalid reference.
However, System.DbNull.Value, is a valid reference to an instance of System.DbNull (System.DbNull is a singleton and System.DbNull.Value gives you a reference to the single instance of that class) that represents nonexistent* values in the database.
*We would normally say null, but I don't want to confound the issue.
So, there's a big conceptual difference between the two. The keyword null represents an invalid reference. The class System.DbNull represents a nonexistent value in a database field. In general, we should try avoid using the same thing (in this case null) to represent two very different concepts (in this case an invalid reference versus a nonexistent value in a database field).
Keep in mind, this is why a lot of people advocate using the null object pattern in general, which is exactly what System.DbNull is an example of.
Try this:
if (DDLGender.SelectedIndex == 0 )
{
command.Parameters.Add("#Gender_Id", DBNull.Value);
}
else
{
command.Parameters.Add("#Gender_Id", (int)DDLGender.SelectedValue);
}
You don't have to specify the data type for parameters.
Assuming you are using stored procedure for updating,
I think you can make the change in stored procedure to have default value to this INT column as NULL which will make this parameter optional. Then you can execute only the ELSE part here from code.
You can combine the above lines of code to :
cmd.Parameters.Add(new SqlParameter { SqlDbType = SqlDbType.Int, Value = DDLGender.SelectedIndex!=0 ? (int)DDLGender.SelectedValue : null });
The use of Null coalescing operator will do the null check. If the selectedItem is not null then that will be passed in as value otherwise null will be passed.

Categories