Getting errors with SqlParameter and ExecuteScalar - c#

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

Related

unable to get data from database by passing string value in entity frame work asp.net MVC

i am trying to get data from database passing a string value. but get null value instead of the data.
i have tried the following code
order getCustomerOrder(string or_n)
{
using (foodorderingEntities db = new foodorderingEntities ())
{
var result = db.orders.Where(or => or.order_no == or_n).FirstOrDefault();
return result;
}
}
please some one guide me to solve this problem.
Please paste your order object, so we know if its reference object/primitive etc, you can use this to understand the two ways to retrieve orders.
I would recommend you read this answer & this MSDN string compare, if your default culture is causing an issue in the comparison, it will help you understand whats going on
Options 1:
// Query syntax
IEnumerable<CustomerOrder> queryResultsCustomerOrder =
from order in orders
where order.number == myOrderNumber
select order;
Options 2:
// Method-based syntax
IEnumerable<CustomerOrder> queryResultsCustomerOrder2 = orders.Where(order => order.Number == myOrderNumber);
using the above, now you can get however many orders the customer has. I am assuming your order is a number, but you can change it to whatever like a string.
Int based order comparison sample
IEnumerable<CustomerOrder> getCustomerOrder(int myOrderNumber)
{
if(myOrderNumber <1) return null;
using (foodorderingEntities dbContextOrderSet = new foodorderingEntities())
{
IEnumerable<CustomerOrder> resultsOneOrManyOrders = orders.Where(order => order.Number == myOrderNumber);
return resultsOneOrManyOrders ;
}
}
string based order comparison
IEnumerable<CustomerOrder> getCustomerOrder(string myOrderNumber)
{
//no orders
if(String.IsNullOrEmpty(myOrderNumber)) return null;
using (foodorderingEntities dbContextOrderSet = new foodorderingEntities())
{
IEnumerable<CustomerOrder> resultsOneOrManyOrders = orders.Where(order => order.Number == myOrderNumber);
// you can replace the *** comparison with .string.Compare and try inside the block
return resultsOneOrManyOrders ;
}
}

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

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

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.

LINQ C# Null exception

Can anyone explain why I'm sometimes gets a NULL exception on this insert method?
As said is only sometimes, which for me is just even more confusing.
The table OrderLine has a referemce to the table Product in the datacontext (.dbml file)
public void insertNewOrder(string accountNumber, int orderId)
{
var order = orderRep.GetOrderById(orderId);
var orderlineData = orderLineRep.GetOrderLines(order.OrderID);
foreach (var orderLine in orderlineData)
{
int currentStatus = dlvRep.getAxOrderStatusNumber(orderLine.ItemNumber, 0);
string levering = "";
string status = dlvRep.getAxOrderStatus(orderLine.ItemNumber, currentStatus, out levering);
WebsiteOrderStatus insertNew = new WebsiteOrderStatus
{
AccountNumber = accountNumber,
OrderID = orderId,
ItemNumber = orderLine.ItemNumber,
ItemName = orderLine.Product.Name,
FormatName = orderLine.Product.ProductFormatName,
Quantity = orderLine.Quantity,
Price = orderLine.Price,
Status = status,
Levering = levering,
LastUpdatedStatus = currentStatus,
CreatedDate = DateTime.Now
};
db.WebsiteOrderStatus.InsertOnSubmit(insertNew);
db.SubmitChanges();
}
}
Exception message:
Cannot insert the value NULL into column 'FormatName', table 'GWportal.dbo.WebsiteOrderStatus'; column does not allow nulls. INSERT fails.
The statement has been terminated.
When I look up the products which this code is having trouble finding the ProductFormatName for. The value of ProductFormatName is not NULL and it's having the value as I expected ex: "PS3".
Another strange thing is, why aren't it complaining about:
ItemName = orderLine.Product.Name,
This coulmn does not allow nulls either.
It's probably a bug in the code fororderLineRep.GetOrderLines(order.OrderID) that causes orderLine.Product.ProductFormatName to be set to null.
Try adding some debug code:
foreach (var orderLine in orderlineData)
{
if (orderLine.Product.ProductFormatName == null) {
throw new Exception("ProductFormatName == null");
}
// ...
Another strange thing is, why aren't it complaining about:
ItemName = orderLine.Product.Name,
This coulmn does not allow nulls either.
I can think of two explanations:
orderLine.Product.Name isn't null. The bug mentioned above may affect only ProductFormatName.
orderLine.Product.Name is null, but one error is enough to terminate the statement immediately. Only one error will be reported. Other errors that are also present won't be reported until the first error is fixed.

Help with EntityQuery working Silverlight C#

I have the following code:
var data = (sender as Button).DataContext as Web.Booking;
EntityQuery<Web.Ticket> ticketQuery =
from t in _ticketContext.GetTicketsQuery()
where t.ticketId == data.ticketId
select t;
LoadOperation<Web.Ticket> loadTicket = this._ticketContext.Load(ticketQuery);
loadTicket.Completed += (s, args) => { MessageBox.Show("Loaded Tickets!"); };
ticketDomainDataSource.DataContext = loadTicket.AllEntities;
var ticketData = ticketDomainDataSource.DataContext as Web.Ticket;
string ticketName = ticketData.ticketName;
The main code that I'm having trouble with is the:
var ticketData = ticketDomainDataSource.DataContext as Web.Ticket;
string ticketName = ticketData.ticketName;
It returns an error:
Object reference not set to an
instance of an object.
Can anyone help me out on what I'm doing wrong here, I can't figure out what's null and how I can return proper data.
Thanks
Your issue is likely that DataContext cannot be cast to Web.Ticket. If you look at the documentation for C# -- as returns a null on a conversion failure. See - http://msdn.microsoft.com/en-us/library/cscsdfbt%28v=vs.71%29.aspx
If you change your line of code to
var ticketData = (Web.Ticket) ticketDomainDataSource.DataContext;
you should get a better cast error.

Categories