Object reference not set to an instance of an object (int) - c#

This error keeps popping up and I can't seem to figure out where it's coming from.
if (!IsPostBack)
{
DataTable LocalCart = new DataTable();
LocalCart = (DataTable)Session["cart"];
int LocalCartItemCount = (int) Session["CartItemCount"];
Decimal LocalCartAmount = (Decimal)Session["CartAmount"];
if (LocalCart.Rows.Count == 0)
{
titleLabel.Text = "Your shopping cart is empty!";
GridCart.Visible = false;
updateButton.Enabled = false;
checkoutButton.Enabled = false;
totalAmountLabel.Text = String.Format("{0:c}", 0);
}
else
{
GridCart.DataSource = LocalCart;
GridCart.DataBind();
titleLabel.Text = "These are the products in your shopping cart:";
GridCart.Visible = true;
updateButton.Enabled = true;
checkoutButton.Enabled = true;
totalAmountLabel.Text = String.Format("{0:c}", LocalCartAmount);
}
It's saying the error is here -> int LocalCartItemCount = (int) Session["CartItemCount"];

You are not checking to see if the key "CartItemCount" exists in Session. If it does not exist, then the result of Session["CartItemCount"] will return null and create that error when trying to cast null to an (int).

If the session object doesn't exist it will return null which will break the cast. You should look into using int.tryparse. If successful it will update the integer, if not it won't bomb out.
try the following code
int LocalCartItemCount;
int.TryParse(Session["CartItemCount"].ToString(), out LocalCartItemCount);
plan b
int LocalCartItemCount = (int)(Session["CartItemCount"] ?? 0);

Well, the first issue is that Session["CartItemCount"] is most likely null. Since you are attempting to use this null value in your cast, you are receiving an object reference error.
This could be corrected with C#'s ?? operator:
int LocalCartItemCount = (int)(Session["CartItemCount"] ?? 0);
That line is basically shorthand for this:
int LocalCartItemCount;
if(Session["CartItemCount"] != null)
LocalCartItemCount = Session["CartItemCount"];
else
LocalCartItemCount = 0;
That should work, so long as Session["CartItemCount"] is always an integer. If it is not an integer, however, you might receive one of the following errors:
Specified cast is not valid
Cannot unbox 'Session["CartItemCount"]' as 'int'
If there is a risk of these errors above, then you may have to expand it to something like this:
int LocalCartItemCount = 0;
if (Session["CartItemCount"] != null)
{
Int32.TryParse(Session["CartItemCount"].ToString(), out LocalCartItemCount);
}
Usually, though, I prefer not to use TryParse outside of a boolean expression, but it still can.
Keep in mind that you will need to similar null checks for any of your objects coming in from session. So, for the LocalCart.Rows.Count == 0 check mentioned in the comments, for example, I would change the if to read:
if(LocalCart != null && LocalCart.Rows.Count == 0)
{
// do stuff here
}
Alternatively, you can use the ?? operator as described above.

Related

Error: Unable to cast object of type 'System.Int32' to type 'System.String'

I have finish perfectly coding Register Page, Login and now the UpdateCustomer page has errors - Background info : I'm using Microsoft Access as data source
LabelState.Text = (string)Session["sState"];
LabelPostalCode.Text = (string)Session["sPostalCode"];
LabelContactNumber.Text = (string)Session["sContactNumber"];
LabelEmail.Text = (string)Session["sEmail"];
LabelPassword.Text = (string)Session["sPassword"];
Everything here is fine except LabelContactNumber.Text = (string)Session["sContactNumber"].
I believe it is because only ContactNumber in Access is set as Int the rest is Text therefore there's no error when I use (string).
Problem : it is failing because you are assigning the Integer type into String.
here you need to use explicit conversion to convert the Integer type into String type.
Solution : if you want to check wether contact number can be parsed to int or not before assigning it into TextBox use TryParse method
int contact;
if(int.TryParse(Session["sContactNumber"],out contact))
LabelContactNumber.Text = contact.ToString();
else
LabelContactNumber.Text = "Invalid Contact!";
LabelContactNumber.Text = (Session["sContactNumber"] != null)
? Session["sContactNumber"].ToString()
: string.Empty //or whatever default value your want;
int contactNumber = -1;
if( int.TryParse( Session[ "sContactNumber" ], out contactNumber ) == false )
{
LastContactNumber = "N/A";
}
else
{
LastContactNumber = contactNumber.ToString( );
}

Getting errors with SqlParameter and ExecuteScalar

public TransImport()
{
ConnString = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
conn_new = new SqlConnection(ConnString);
command_serial_new = conn_new.CreateCommand();
command_serial_new.CommandText = "SELECT 1 FROM YSL00 WHERE SERLNMBR = #slnr";
var p = new SqlParameter("#slnr", SqlDbType.NVarChar, 50);
command_serial_new.Parameters.Add(p);
//Here you will start reading flat file to get serialnumber.
//Here I have shown a simple call using one value 12345 but it will be 1000's of
//lines from flatfile.
if (CheckSerialNumber('12345'))
DisplayMessage("Good serialnumber"); //this function is not copied here.
}
private Boolean CheckSerialNumber(string SerialNumber)
{
command_serial_new.Parameters["#slnr"].Value = SerialNumber;
try
{
var itExists = (Int32)command_serial_new.ExecuteScalar() > 0;
if (itExists)
{
return true;
}
}
catch (Exception ex)
{
LogException(ex, "Error in CheckSerialNumber =>"+ command_serial_new.CommandText.ToString());
}
return false;
}
I get error in the above catch. It mentions
object reference not set to an instance of object
It is failing with the line that has ExecuteScalar.
I guess I am doing something wrong here, but unable to figure out so far.
Update 1: I have modified this question. Basically I created another question with an issue I am facing.. Also I have marked it as answered.
Here is the NEW question I have posted just now.
Getting timeout errors with SqlTransaction on same table
This happens if the ExecuteScalar() returns null. (eg, because no rows matched)
Since int is a value type, it cannot be null; therefore, you get an error.
Instead, you can cast it to int?, which is nullable.
#SLaks answer is correct.
Here is one more way to avoid the error. No need of null checking etc, Convert.ToInt32 takes care of everything.
var itExists = Convert.ToInt32(command_serial_new.ExecuteScalar()) > 0;
try:
int i;
object o = command_serial_new.ExecuteScalar();
if(o != null && Convert.ToInt32(o.ToString()) > 0)
{
//....
}
to verify that your query returned something

Error for Null value when opening a registry key in C#

I'm having an issue for C# (I'm new to it), when trying to fix a Null value.
Therefore I have a variable "verif" (String verif = String.Empty;), which I used it to read some key from Windows Registry. My code works if the key exists, but when it doesn't I got the error"NullReferanceException was unhandled".
I tried several ways, to catch the exception, to put an "If" statement but I failed miserable.
My code is something like this:
RegistryKey key_user;
RegistryKey key_pwd;
String code = String.Empty;
String tara = String.Empty;
String tot = String.Empty;
String pwd_mdw = String.Empty;
String user_mdw = String.Empty;
String user_uca = String.Empty;
String pwd_uca = String.Empty;
String verif = String.Empty;
private void button1_Click(object sender, EventArgs e)
{tot = listBox1.SelectedValue.ToString();
//MessageBox.Show(tot);
tara = tot.Substring(tot.Length - 2, 2);
//MessageBox.Show(tara);
code = listBox1.SelectedValue.ToString().Substring(0, 2);
user_mdw = textBox1.Text;
//MessageBox.Show(user_mdw);
pwd_mdw = textBox2.Text;
//MessageBox.Show(pwd_mdw);
if (code == "CC")
{
verif = Registry.CurrentUser.OpenSubKey(#"Software\TDCredentials").GetValue("user_mdw_" + tara + "_CC").ToString();
MessageBox.Show("Verif",verif);
MessageBox.Show(user_mdw, "user_mdw");
if (verif==null)
{
key_user = Registry.CurrentUser.CreateSubKey("Software\\TDCredentials");
key_user.SetValue("user_mdw_" + tara + "_CC", user_mdw);
key_user.Close();
key_pwd = Registry.CurrentUser.CreateSubKey("Software\\TDCredentials");
key_pwd.SetValue("pass_mdw_" + tara + "_CC", pwd_mdw);
key_pwd.Close();
MessageBox.Show("User and Password inserted successfully!");
textBox1.Clear();
textBox2.Clear();
}
else
{...
Any hints?
Many thanks in advance, Bogdan.
Looking at what you're trying to do, this line is most likely (one of) your problems;
verif = Registry.CurrentUser.OpenSubKey(#"Software\TDCredentials")
.GetValue("user_mdw_" + tara + "_CC").ToString();
If the key does not exist, OpenSubKey will return null, and you call GetValue() on it without checking.
You can change the line to add a check, something like;
var key = Registry.CurrentUser.OpenSubKey(#"Software\TDCredentials");
var value = key != null ? key.GetValue("user_mdw_" + tara + "_CC") : null;
verif = value != null ? value.ToString() : null;
if(verif == null) {
...
First of all you need to check
Registry.CurrentUser.OpenSubKey(#"Software\TDCredentials")
that this is not null. Then call the getvalue method. Beause if the above key is null then the following getvalue will throw exception.
Try the following check to test if Registry.CurrentUser.OpenSubKey(#"Software\TDCredentials") is not null else it will bomb:
if (code == "CC")
{
if (Registry.CurrentUser.OpenSubKey(#"Software\TDCredentials") != null)
{
verif =
Registry.CurrentUser.OpenSubKey(#"Software\TDCredentials").GetValue("user_mdw_" + "Test" + "_CC").
ToString();
}
Try checking for NULL on OpenSubKey() & GetValue() methods prior to using ToString() method.
You're trying to do too much in one line, without checking the results as you go.
First of all, as others have already said, you need to check that OpenSubKey doesn't return null. You also need to make sure that the key is closed when you're finished, with a using statement:
using (var key = Registry.CurrentUser.OpenSubKey(#"Software\TDCredentials"))
{
if (key == null)
{
// Couldn't open the key, now what?
// You need to make a decision here.
// If you read the documentation for CreateSubKey,
// you'll see that it can *also* return null, so don't rely on it.
}
else
{
// OK, opened the key, and the using statement will close it.
// Now we can try reading values. See the next part of the answer.
}
}
If you successfully open the key, you can try to read the value. Even if you successfully open the key, the value might not exist, or it might not be a string (it could be a DWORD, for instance, or a binary value).
If the value doesn't exist, GetValue returns null, so calling ToString without checking will throw NullReferenceException.
Even if the value exists, calling ToString on it is the wrong thing to do, because it might not be a string value in the registry. If it's a binary value, for example, calling ToString on it will give you the string System.Byte[]. You need to check that it is actually a string.
else
{
// OK, opened the key, and the using statement will close it.
// Now we can try reading values.
string verif = key.GetValue("user_mdw_" + tara + "_CC") as string;
if (verif == null)
{
// The value does not exist, or is not the type you expected it to be (string).
// Now what? You need to make a decision here.
}
else
{
// OK, do something with verif.
}
}
Make sure to read the documentation for these methods, and handle the special cases they mention, especially the circumstances under which they return null:
CreateSubKey
OpenSubKey
GetValue

Linq to SQL for EntityFramework.Extensions Update() method with ?? operator

I have a method with several optional parameters that then updates the database using a LINQ query. I would like to update the record such that the optional fields are only saved if they were supplied in the method, otherwise the values should persist their old value. E.g.,
If I supply optional field "errorMessage" to my method, the database's corresponding record field should update with that value. If the method value is not supplied then I would like the database's record field to persist its existing content (filled or not). However, when using the ?? operator in my query to apply this logic I get the following error;
The parameterized query '(#p__linq__0 int,#p__update__0 nvarchar(198),#p__update__1 nvarc' expects the parameter '#p__update__1', which was not supplied.
I know enough LINQ to know that this basically means that it's having trouble converting the LINQ to SQL. Likewise, I could get around this by first loading the item, applying the method values to the retrieved object and then saving them but this turns a one-step operation into a 3 step operation. I'm hoping there's a concise elegant solution to this that I'm not aware of. Any ideas?
My code;
public void UpdateInvoiceExport(int quickBooksExportID, bool successful, string failureMessage = null,
int? failureRequestID = null, int? failureStatusCode = null,
string failureSeverity = null)
{
// only update certain details if the export was successful
DateTime? exportDateTime = null;
if (successful)
{
exportDateTime = DateTime.Now;
}
// update the export item
_context.QuickBooksExports.Update(item => item.QuickBooksExportID == quickBooksExportID,
qb => new QuickBooksExport
{
DateTimeExported = exportDateTime,
// the addition of the ?? operators here seems to cause the error
LastFailureMessage = failureMessage ?? qb.LastFailureMessage,
FailureRequestID = failureRequestID ?? qb.FailureRequestID,
FailureStatusCode = failureStatusCode ?? qb.FailureStatusCode,
FailureSeverity = failureSeverity ?? qb.FailureSeverity
});
_context.SaveChanges();
}
I have had this issue before, I had to pull the object out, build it first and then pass it in. This prevents the ?? operator from being in the Linq statement.
public void UpdateInvoiceExport(int quickBooksExportID,
bool successful,
string failureMessage = null,
int? failureRequestID = null,
int? failureStatusCode = null,
string failureSeverity = null)
{
// only update certain details if the export was successful
DateTime? exportDateTime = null;
if (successful)
{
exportDateTime = DateTime.Now;
}
// update the export item
var quickBooksExport = new QuickBooksExport;
{
DateTimeExported = exportDateTime
};
quickBooksExport.LastFailureMessage = failureMessage ?? qb.LastFailureMessage;
quickBooksExport.FailureRequestID = failureRequestID ?? qb.FailureRequestID;
quickBooksExport.FailureStatusCode = failureStatusCode ?? qb.FailureStatusCode;
quickBooksExport.FailureSeverity = failureSeverity ?? qb.FailureSeverity;
_context.QuickBooksExports.Update(item => item.QuickBooksExportID == quickBooksExportID,
qb => quickBooksExport);
_context.SaveChanges();
}

Using strings instead of enums?

Is it common place to use a string for comparison as opposed to an enum?
I am aware about your context, but as a first step you can just refactor this way:
Step 1
if (typeOfObject == "UAV")
{
DoSomeWork(_stkObjectRootToIsolateForUavs);
}
else if (typeOfObject == "Entity")
{
DoSomeWork(_stkObjectRootToIsolateForEntities);
}
private void DoSomeWork(IAgStkObject agStkObject)
{
IAgStkObject stkObject = agStkObject.CurrentScenario.Children[stkObjectName];
IAgDataProviderGroup group = (IAgDataProviderGroup)stkUavObject.DataProviders["Heading"];
IAgDataProvider provider = (IAgDataProvider)group.Group["Fixed"];
IAgDrResult result = ((IAgDataPrvTimeVar)provider).ExecSingle(_stkObjectRootToIsolateForUavs.CurrentTime);
stkObjectHeadingAndVelocity[0] = (double)result.DataSets[1].GetValues().GetValue(0);
stkObjectHeadingAndVelocity[1] = (double)result.DataSets[4].GetValues().GetValue(0);
}
Then consider replasing if's with switch:
Step 2
switch (typeOfObject)
{
case "UAV":
DoSomeWork(_stkObjectRootToIsolateForUavs);
break;
case "Entity":
DoSomeWork(_stkObjectRootToIsolateForEntities);
break;
default:
throw new NotImplementedException():
}
This can be even better when using enums.
At the very least, the strings should be declared as constants (or perhaps readonly fields) somewhere, instead of spread out through the code. However, this looks like the schoolbook example for when to use an enum.
public enum ObjectType
{
UAV,
Entity,
// and so on
}
To add to #Restuta's answer, I'd use a
IDictionary<MyEnumifiedString, Action<IAgStkObject>>
to get rid of that if.
I'd agree with #Frederik that this seems a perfect case for using enums, but it could be that the only thing you can get out of the application is a string. In which case your example is perfectly OK.
Oh yes - and make sure you have the string constants defined in one place, preferably a config file so that if they change the other application you don't have to recompile yours.
Regarding your first question I will always use a defined type to store the strings simply to have one location for change if needed.
So for your example i would have the following
public sealed class RootTypes
{
public const string Entity = "entity";
public const string UAV = "uav";
}
Your code then updates to this
typeOfObject = typeOfObject.ToLower();
if (typeOfObject == RootTypes.UAV)
{
stkUavObject = _stkObjectRootToIsolateForUavs.CurrentScenario.Children[stkObjectName];
var group = (IAgDataProviderGroup) stkUavObject.DataProviders["Heading"];
var provider = (IAgDataProvider) group.Group["Fixed"];
IAgDrResult result = ((IAgDataPrvTimeVar) provider).ExecSingle(_stkObjectRootToIsolateForUavs.CurrentTime);
stkObjectHeadingAndVelocity[0] = (double) result.DataSets[1].GetValues().GetValue(0);
stkObjectHeadingAndVelocity[1] = (double) result.DataSets[4].GetValues().GetValue(0);
}
else if (typeOfObject == RootTypes.Entity)
{
IAgStkObject stkEntityObject = _stkObjectRootToIsolateForEntities.CurrentScenario.Children[stkObjectName];
var group = (IAgDataProviderGroup) stkEntityObject.DataProviders["Heading"];
var provider = (IAgDataProvider) group.Group["Fixed"];
IAgDrResult result = ((IAgDataPrvTimeVar) provider).ExecSingle(_stkObjectRootToIsolateForEntities.CurrentTime);
stkObjectHeadingAndVelocity[0] = (double) result.DataSets[1].GetValues().GetValue(0);
stkObjectHeadingAndVelocity[1] = (double) result.DataSets[4].GetValues().GetValue(0);
}
The issue of code redundancy has been anserwed by Restuta
Use enums with bit flags:
[Flags]
public enum MyFlags
{
SomeFlag = 0x1, // 001
OtherFlag = 0x2,// 010
ThirdFlag = 0x4 // 100
}
var firstObject = MyFlags.SomeFlag;
var secondObject = MyFlags.SomeFlag | MyFlags.OtherFlag;
if(((int)secondObject & MyFlags.SomeFlag) != 0)
{
// true
}
if(((int)secondObject & MyFlags.OtherFlag) != 0)
{
// true
}
if(((int)firstObject & MyFlags.SomeFlag) != 0)
{
// true
}
if(((int)firstObject & MyFlags.OtherFlag) != 0)
{
// false
}
This article would be helpful.

Categories