DBnull issue when converting empty string to number - asp.net

Hello I am trying to connect with Oracle and sending parameters as part of store procedure. Two of my parameters are coming as empty string so I need to pass null values but the datatype is set as number in the db end. When ever I run the script it gives me error that "Object cannot be cast from DBNull to other types".
Here is my code snippet remember string Case, string SRE_Pricing are coming in as "" .So I need to convert to number if there is anyting in text like "52" and if "" then assign DB null.
OracleParameter CaseParam = new OracleParameter("arg_CASE_NUMBER", OracleType.Number);
CaseParam.Direction = ParameterDirection.Input;
if (Case != null || Case!="")
{
CaseParam.Value = Convert.ToInt32((Case.Equals(string.Empty)) ? (object)DBNull.Value : Case);
}
else
{
CaseParam.Value = DBNull.Value;
}
//CaseParam.Value =Convert.ToInt32(Case);
cmd.Parameters.Add(CaseParam);
OracleParameter SRE_pricingParam = new OracleParameter("arg_SRE_PRICING_ELEMENT", OracleType.Number);
SRE_pricingParam.Direction = ParameterDirection.Input;
if (SRE_Pricing != null || SRE_Pricing != "")
{
SRE_pricingParam.Value = Convert.ToInt32((SRE_Pricing.Equals(string.Empty)) ? (object)DBNull.Value : SRE_Pricing);
}
else
{
SRE_pricingParam.Value = DBNull.Value;
}
//SRE_pricingParam.Value = Convert.ToInt32(SRE_Pricing);
cmd.Parameters.Add(SRE_pricingParam);
enter image description here

You need to use && operator instead of || in the if condition
if (SRE_Pricing != null && SRE_Pricing != "")
{
SRE_pricingParam.Value = Convert.ToInt32(SRE_Pricing);
}
else
{
SRE_pricingParam.Value = DBNull.Value;
}
Better to use Int32.TryParse()
int price;
if (Int32.TryParse(SRE_Pricing, out price))
{
SRE_pricingParam.Value = price;
}
else
{
SRE_pricingParam.Value = DBNull.Value;
}

Related

Attaching the DbEntityEntry to Context

i am trying to implement a log system to the entitiy framework context.
i want to get the deleted element primary key when its state is deleted.
this is my code:
if (item.State == EntityState.Added || item.State == EntityState.Deleted) {
log = new dt_islemLog();
log.eskiDeger = null;
log.islem = (item.State == EntityState.Added) ? Enums.GetDBValue(Enums.islemDurum.EKLENDI) : Enums.GetDBValue(Enums.islemDurum.SILINDI);
log.islemYapanKullanici_id = kullaniciID;
log.nesneAd = item.Entity.GetType().Name;
log.oturum_id = oturumID;
log.zaman = DateTime.Now;
base.SaveChanges();
var ID = GetPrimaryKeyValue(item);
log.nesneID = ID != null ? ID.ToString() : null;
this.dt_islemLog.Add(log);
}
And this is the method that i get the primary key
object GetPrimaryKeyValue(DbEntityEntry entry) {
try {
if (entry.State == EntityState.Detached)
((IObjectContextAdapter)this).ObjectContext.Attach((System.Data.Entity.Core.Objects.DataClasses.IEntityWithKey)entry.Entity);
var objectStateEntry = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity);
return objectStateEntry.EntityKey.EntityKeyValues[0].Value;
}
catch(Exception ex) {
return null;
}
}
But i can't attach the (entry.Entitiy) to context because the cast operation is invalid. How can i get the primary key ?
If someone needs i have found the solution. i have updated the primary key method to like this
object GetPrimaryKeyValue(DbEntityEntry entry)
{
try
{
if (entry.State == EntityState.Detached)
this.Set(entry.Entity.GetType()).Attach(entry.Entity);
var objectStateEntry = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity);
return objectStateEntry.EntityKey.EntityKeyValues[0].Value;
}
catch
{
return null;
}
}

Object reference not set in asp.net

if (Session["admin_uname"].ToString() == "")
{
Response.Redirect("login.aspx");
}
else
{
string userid = Session["admin_uname"].ToString();
}
i have wrote above code for sessions...
but problem is if there is any session variable it was working properly
if session is not there it was not redirecting to login page and giving an error like
OBJECT REFERENCE NOT SET.
If there is no session exits then u will not able to compare anything. So check its Null or Not. This is how u check the session.
if (Session["admin_uname"] == null)
{
Response.Redirect("login.aspx");
}
else
{
string userid = Session["admin_uname"].ToString();
}
When you call ToString() on that null, you get the exception. So check for Null value too. You can try this:-
if (Session["admin_uname"].ToString() == "" || Session["admin_uname"].ToString() == Null)
Check for nullity before you reference the object, like
if (Session["admin_uname"] != null)
// do something
I would do like this:
if (Session["admin_uname"] != null || Session["admin_uname"].ToString() == "")
Response.Redirect("login.aspx");
string userid = Session["admin_uname"].ToString();
One more entry:
string userid = Session["admin_uname"] ?? "";
if (string.IsNullOrEmpty(userid))
{
Response.Redirect("login.aspx");
}
You could use this:
if (String.IsNullOrEmpty(Session["admin_uname"].ToString()))
{
Response.Redirect("login.aspx");
}
else
{
string userid = Session["admin_uname"].ToString();
}

Creating a new cookie (overwriting the old one) keeps a list of old values?

Edit: Sorry! I forgot to include details. I'm using C# within a MVC4 project.
so I have some code here that is supposed to
1. Create a new cookie if the UserID parameter is set and one hasn't been set already
2. if a cookie has not been set and no UserID parameter is specified, set the UserID to 1
3. if a new UserID parameter is there then update the cookie with the new UserID.
Problem is that ,If UserID is first set to Jake, then to Joe, then to Bob, I get a Cookie Value that looks like this "Bob, Joe, Jake". Is this normal? It seems like it'd be best to clear this list. Thanks in advance for your time.
public static void StoreID()
{
if ((HttpContext.Current.Request.Cookies["UserID"] == null) && (System.Web.HttpContext.Current.Request.Params["UserID"] != null))
{
HttpContext.Current.Response.Cookies["UserID"].Value = System.Web.HttpContext.Current.Request.Params["UserID"];
HttpContext.Current.Response.Cookies["UserID"].Expires = DateTime.Now.AddDays(1);
}
else if ((HttpContext.Current.Request.Cookies["UserID"] == null) && (System.Web.HttpContext.Current.Request.Params["UserID"] == null))
{
HttpContext.Current.Response.Cookies["UserID"].Value = "1";
HttpContext.Current.Response.Cookies["UserID"].Expires = DateTime.Now.AddDays(1);
}
else if ((HttpContext.Current.Request.Cookies["UserID"] != null) && (System.Web.HttpContext.Current.Request.Params["UserID"] == null))
{
}
else
{
HttpContext.Current.Response.Cookies["UserID"].Value = System.Web.HttpContext.Current.Request.Params["UserID"];
HttpContext.Current.Response.Cookies["UserID"].Expires = DateTime.Now.AddDays(1);
}
}
Ok, so introducing subkeys fixed the problem. Not sure why this works the way it does - if someone has any input on why that'd be great! Here's the working code:
if ((HttpContext.Current.Request.Cookies["UserInfo"]== null) && (System.Web.HttpContext.Current.Request.Params["UserID"] != null))
{
HttpContext.Current.Response.Cookies["UserInfo"]["UserID"] = System.Web.HttpContext.Current.Request.Params["UserID"];
}
else if ((HttpContext.Current.Request.Cookies["UserInfo"] == null) && (System.Web.HttpContext.Current.Request.Params["UserID"] == null))
{
HttpContext.Current.Response.Cookies["UserInfo"]["UserID"] = "1";
}
else if ((HttpContext.Current.Request.Cookies["UserInfo"] != null) && (System.Web.HttpContext.Current.Request.Params["UserID"] == null))
{
}
else
{
HttpContext.Current.Response.Cookies["UserInfo"]["UserID"] = System.Web.HttpContext.Current.Request.Params["UserID"];
}

How to parse this XML using linq to xml?

i am trying to parse following xml but no sucess any one guide me what mistake am i doing here
string feedURL = "http://www.bbc.co.uk/arabic/index.xml";
XDocument feedSource;
feedSource = XDocument.Load(feedURL);
var another = (from myFeed in feedSource.Descendants("entry")
select new
{
feedTitle = myFeed.Element("title").Value,
//feedDescription = myFeed.Element("description").Value,
//feedLink = myFeed.Element("link").Value,
feedpubDate = myFeed.Element("published") != null ? myFeed.Element("published").Value : null
//feedcategory = myFeed.Element("category") != null ? myFeed.Element("category").Value : null,
//feedItems = myFeed.Descendants("entry")
}
);
if (another != null && another.Count() > 0)
{
}
else
{
Response.Write("No Record Found");
}
it is showing me no record found.
any help would be appreciated.
This worked in LINQPad:
XNamespace xns = "http://www.w3.org/2005/Atom";
var xdoc = XDocument.Load("http://www.bbc.co.uk/arabic/index.xml");
xdoc.Element(xns + "feed").Elements(xns + "entry");
Problem was the lacking namespace.

Filtering LINQ query

I have problem that is bothering me last couple of days.
I need to filter LINQ query using comboboxes and textboxes. The problem is I can't manage to get the result and I always get the empty gridview (used for showing filtered data).
Can anyone help me why am I getting no results at all? I've checked the debugger and the data sent to query is valid, although, I'm not sure about "string.Empty" value.
Here is the code:
string naziv, nazivEn, adresa, tel, fax, mob, email, web, oib, tip, mjesto;
if (chkMjesto.Checked == true)
{
mjesto = cbMjesto.SelectedItem.Text;
}
else
{
mjesto = string.Empty;
}
if (chkTip.Checked == true)
{
tip = cbTip.SelectedItem.Text;
}
else
{
tip = string.Empty;
}
string tema;
if (chkTema.Checked == true)
{
tema = cbTema.SelectedItem.Text;
}
else
{
tema = string.Empty;
}
if (chkAdresa.Checked == true)
{
adresa = txtAdresa.Text;
}
else
{
adresa = string.Empty;
}
if (chkTelefon.Checked == true)
{
tel = txtTelefon.Text;
}
else
{
tel = string.Empty;
}
if (chkMobitel.Checked == true)
{
mob = txtMobitel.Text;
}
else
{
mob = string.Empty;
}
if (chkEmail.Checked == true)
{
email = txtEmail.Text;
}
else
{
email = string.Empty;
}
if (chkWeb.Checked == true)
{
web = txtWeb.Text;
}
else
{
web = string.Empty;
}
if (chkOIB.Checked == true)
{
oib = txtOIB.Text;
}
else
{
oib = string.Empty;
}
if (chkNaziv.Checked == true)
{
naziv = txtNaziv.Text;
}
else
{
naziv = string.Empty;
}
if (chkNazivEn.Checked == true)
{
nazivEn = txtNazivEn.Text;
}
else
{
nazivEn = string.Empty;
}
if (chkFax.Checked == true)
{
fax = txtFax.Text;
}
else
{
fax = string.Empty;
}
if (rblOrganizator.SelectedItem.Value == "Nije")
{
var pretraga = from t in db.tijeloes
where t.tijelo_naziv.Contains(naziv) && t.tijelo_adresa.Contains(adresa) && t.tip_tijela.tip_tijela_naziv.Contains(tip) && t.mjesto.mjesto_naziv.Contains(mjesto)
where t.tijelo_telefon.Contains(tel) && t.tijelo_fax.Contains(fax) && t.tijelo_email.Contains(email) && t.tijelo_mob.Contains(mob) && t.tijelo_web.Contains(web) && t.tijelo_oib.Contains(oib) && t.tijelo_naziv_en.Contains(nazivEn)
select new { t.tijelo_naziv, t.tijelo_oib,t.tip_tijela.tip_tijela_naziv,t.tijelo_adresa,t.mjesto.mjesto_naziv, t.mjesto.zupanija_drzava.zupanija_naziv};
gvTijelo.DataSource = pretraga;
gvTijelo.DataBind();
if (pretraga.Count() != 0)
{
gvTijelo.HeaderRow.Cells[0].Text = "Naziv";
gvTijelo.HeaderRow.Cells[1].Text = "OIB";
gvTijelo.HeaderRow.Cells[2].Text = "Tip tijela";
gvTijelo.HeaderRow.Cells[3].Text = "Adresa";
gvTijelo.HeaderRow.Cells[4].Text = "Mjesto";
gvTijelo.HeaderRow.Cells[5].Text = "Regionalni centar";
}
}
The string.Empty seems to the culprit. I would bet the SQL being generated is checking if a field contains '', which just won't likely work with data in that field.
Your best bet is to start the query before your conditionals, then append a where to it if the corresponding check box is checked.
var pretraga = db.tijeloes;
if (chkMjesto.Checked == true)
{
pretraga = pretraga.Where(t => t.tijelo_naziv.Contains(cbMjesto.SelectedItem.Text));
}
if (chkTip.Checked == true)
{
pretraga = pretraga.Where(t => t.tip_tijela.tip_tijela_naziv.Contains(cbTip.SelectedItem.Text));
}
...
pretraga = pretraga.Select(t => new { t.tijelo_naziv, t.tijelo_oib,t.tip_tijela.tip_tijela_naziv,t.tijelo_adresa,t.mjesto.mjesto_naziv, t.mjesto.zupanija_drzava.zupanija_naziv });
// Bind to pretraga.
...
If I were you I would declare all the variables at the top seperately like
string naziv = string.empty;
string whatever = string.empty; etc
Doing this will make your code smaller because you can get rid of the else statements as the variables are already set.
Sorry not a solution but might thin down the code for you a little :)

Resources