I am trying to get the list of items inside of a quickbooks database. I have the following snippet of code:
IItemServiceRet itemServiceRet = itemRet.ItemServiceRet;
TestItem item = new TestItem();
item.Name = itemServiceRet.Name.GetValue();
item.Desc = itemServiceRet.ORSalesPurchase.SalesOrPurchase.Desc.GetValue();
item.Rate = itemServiceRet.ORSalesPurchase.SalesOrPurchase.ORPrice.Price.GetValue().ToString();
item.ItemType = "Service";
item.QBID = itemServiceRet.ListID.GetValue();
item.EditSeq = itemServiceRet.EditSequence.GetValue();
The code fails on the line:
item.Desc = itemServiceRet.ORSalesPurchase.SalesOrPurchase.Desc.GetValue();
"Object reference not set to an instance of an object"
Because that particular service item in the QB database does not have a description. I was curious if there was a 'clean' way to check for null values without having to have each line include an if statement checking if GetValue() returns null?
Edit: After trying Andrew Cooper's solution of:
item.Desc = itemServiceRet.ORSalesPurchase.SalesOrPurchase.Desc == null ? null : itemServiceRet.ORSalesPurchase.SalesOrPurchase.Desc.GetValue();
It still throws the exception:
Object reference not set to an instance of an object
Its as if GetValue() returns nothing at all if there is no description, which wouldn't make much sense.
You could use the ternary operator like this:
item.Desc = itemServiceRet.ORSalesPurchase.SalesOrPurchase.Desc == null ? null : itemServiceRet.ORSalesPurchase.SalesOrPurchase.Desc.GetValue();
But that's pretty ugly.
Best bet is to create a helper method that takes whatever type Desc and wraps the above logic.
I don't think there's any better solution, as you can't access the functions of a null object. I typically create a constructor for my items that does the checking so I only have to do that once. So in your example:
TestItem item = new TestItem(itemRet.ItemServiceRet);
The constructor would look like this:
public TestItem(IItemServiceRet i)
{
if(i.Name != null) this.Name = i.Name.GetValue();
if(i.ORSalesPurchase != null)
if(i.ORSalesPurchase.SalesOrPurchase != null)
{
if(i.ORSalesPurchase.SalesOrPurchase.Desc != null) this.Desc = i.ORSalesPurchase.SalesOrPurchase.Desc.GetValue();
if(i.ORSalesPurchase.SalesOrPurchase.ORPrice != null)
if(i.ORSalesPurchase.SalesOrPurchase.ORPrice.Price != null) this.Price = i.ORSalesPurchase.SalesOrPurchase.ORPrice.Price.GetValue();
}
}Keep in mind that this does work well for strings, as an empty string is usually the same as a blank field, but for number fields in QuickBooks this may cause problems. For example, an Invoice line can have a blank quantity field (which is a double). A double will default to the value of 0.0, but a blank quantity field in QuickBooks is treated as a quantity of 1.0. This can also cause problems with dates, as QuickBooks can have null date fields.
Related
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;
I have a method which uses LINQ to look up a company in a local DataSet, using a company id (Guid). The properties from the data set is then stored in a class (CompanyModel), which is created for the occasion. One of the properties is the OrganizationNo, which is of type Long in the DataSet, but String in the CompanyModel.
The issue is, OrganizationNo can be null in the DataSet. This causes the ToString() method to throw an exception. I can tried fixing it (see below), but with no luck.
Isn't there some sort of simple, easy to read solution for this, which does not require multiple lines of code and/or use of try/catch?
UPDATE
The exception is thrown at an earlier point, since query becomes null if the organization number is null. Hence it has nothing to do with ToString() failing. The code never gets that far. I have tried changing the NullValue property of the OrganizationNo in the data table from (Throw Exception) to (Null), but this is not allowed. Is it a bad design we have chosen, using Long for a property which is sometimes null?
public void SelectCompany(Guid companyId)
{
SelectedCompany = new CompanyModel();
SelectedCompany.Id = companyId;
CompanyDataTabel dt = DataSet.Company;
// Look up the company in the company table in the data Set
var query = from company in dt.AsEnumerable()
where company.Id == companyId
select new
{
company.OrganizationNo,
company.Name,
company.PhoneNo,
company.Email,
};
// If the OrganizationNo is null, then the entire query is null.
// Hence the '.Count()' method will fail.
if (query.Count() != 1)
{
// One (and only one) company should match the organisation ID.
throw new ArgumentException("Multiple companies found.");
}
// These properties are never null and causes no issues
SelectedCompany.Name = query.First().Name;
SelectedCompany.PhoneNumber = query.First().PhoneNo;
SelectedCompany.EmailAddress = query.First().Email;
SelectedCompany.OrganisationNumber = query.First().OrganizationNo.ToString()
}
The problem in your query is that you are using a strongly typed DataSet which throws an error if you try to access a property that is null. To handle that case the DataSet automatically adds a bool method that you have to check before you access that nullable-column property. But your query creates an anonymous type that accesses this nullable property without this check. For that reason you will get the exception when the query is executed which is at query.First().
Use this query instead:
var query = from company in dt.AsEnumerable()
where company.Id == companyId
select new
{
OrganizationNo = company.IsOrganizationNoNull()
? string.Empty
: company.OrganizationNo.ToString(),
company.Name,
company.PhoneNo,
company.Email,
};
Side-note:
Instead of if (query.Count() != 1) you should use Single:
var company = query.Single(); // throws a desired exception if there are no or more than two records
SelectedCompany.Name = company.Name;
SelectedCompany.PhoneNumber = company.PhoneNo;
SelectedCompany.EmailAddress = company.Email;
SelectedCompany.OrganisationNumber = company.OrganizationNo;
This handles the case that there is none or more than one and will throw this exception on both cases. It's more efficient because you only need to execute the query once. Btw, all your query.First() calls must execute the whole query again
you can check OrganisationNumber property is must be define Nulable.. Nulable<long> or long? like this public long? OrganisationNumber {get;set;}
SelectedCompany.OrganisationNumber = string.Empty;
if(query.First() != null && query.First().OrganizationNo.HasValue)
{
SelectedCompany.OrganisationNumber =
query.First().OrganizationNo.Value.ToString();
}
or
SelectedCompany.OrganisationNumber = query.First() != null && query.First().OrganizationNo.HasValue ? "" : "";
or
SelectedCompany.OrganisationNumber =
query.First() != null ? query.First().OrganizationNo?.ToString() ?? string.Empty : string.Empty;
long type variable itself can not be null. but Nullable<long> can
The ?. operator works with null, which works for reference types or nullable value types, but not for normal value types like long.
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
}
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.
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();
}