NullReferenceException while getting properties from session object - asp.net

I have created a class with name Examination, in this class I have a method with name Get Question(), in take exam when i am creating object of Examination and Run Application it gives following error.
NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 18: Examination e = (Examination)Session["questions"];
Line 19: // display data
Line 20: lblSubject.Text = e.sname;
Line 21: lblQno.Text = e.curpos + 1 + "/" + e.SIZE;
Line 22: lblCtime.Text = DateTime.Now.ToString();

Most probably Session["questions"] does not contain a value, and returns null. It is perfectly valid to cast null to a reference type, but the exception occurs where you try to access properties of it.
You should test if it's null, for instance:
Examination e = (Examination)Session["questions"];
if (e == null)
{
lblSubject.Text = "Your session has expired";
}
(If I'm wrong, and e actually contains a reference to an Examination object, then it's lblSubject that's null)

Related

GraphQLTestCase: AttributeError: 'HttpResponse' object has no attribute 'COOKIES'

I would want to test my graphql mutation which should set a HTTP only cookie.
I use graphene-django GraphQTestCase
class CookieTest(GraphQLTestCase):
def test_set_cookie(self):
response = self.query(...) # This should return WSGIRequest
cookie = response.COOKIES.get('myCookie') # This line throws an attrib error
self.assertIsNotNone(cookie)
What is the problem?
For some reason response.cookies works, and returns http.cookies.SimpleCookie object:
So the correct way would be:
myCookie = response.cookies.get('myCookie')
myCookie.key # 'myCookie'
myCookie.value # <cookie-value>

Retrieving Data using QueryString with LINQ

how can i use request.querystring in asp.net. I am trying to retrieve data using Linq but I keep getting errors. Please get back to me Asap. Im still a novice in asp.net
Code behind:
BlogDBDataContext db = new BlogDBDataContext();
dynamic q = from b in db.Blogs
where b.BlogId = Request.QueryString("BlogId")
select b;
lv.DataSource = q;
lv.DataBind();
this give me the error that says : Non-invocable member 'System.Web.HttpRequest.QueryString' cannot be used like a method.
Code behind:
even when I try this code : Request.QueryString["BlogId"]
still it gives me an error : Cannot implicitly convert type 'string' to 'int'
QueryString is a NameValueCollection, not a method - you should use the [] operator to access members:
Request.QueryString["BlogId"]
Edit: just read the rest of your question. The value of Request.QueryString["BlogId"] is a string, not an int, as the error message suggests. I assume that b.BlogId is an int, so you need to parse the string to an int first.
BlogDBDataContext db = new BlogDBDataContext();
int blogId;
if (int.TryParse(Request.QueryString["BlogId"], out blogId))
{
dynamic q = from b in db.Blogs
where b.BlogId == blogId
select b;
lv.DataSource = q;
lv.DataBind();
}

In controller part ASP.NET MVC 4 Survey project

In the code below I have a problem:
List<SurveyContext> surveys = (from s in DbContext.Surveys
where s.userName == s.userName
select s.ID).ToList();
if(surveys.Count() > 0)
{
int id = 0;
int.TryParse(Surveys.First(), id);
return id;
}
return 0;
Error : ToList()
Error 1 A local variable named 's' cannot be declared in this scope because it would give a different meaning to 's', which is already used in a 'parent or current' scope to denote something else
and here:
int.TryParse(Surveys.First(), id);
The name 'Surveys' does not exist in the current context
But this name exist in context... Can anyone help me??
Error 1
Use == instead of =
where s.userName == userName
Error 2
Try naming s variable on your linq query in a different way, maybe su or survey. But it seems to me that error is on code that you're not showing.
List<SurveyContext> surveys = (from su in DbContext.Surveys
where su.userName == su.userName
select su.ID).ToList();
Error 3
I think you meant surveys instead of Surveys and you need to use out when passing idparam
int.TryParse(surveys.First(), out id);
And since you're not evaluating parse result I'd say you should use int.Parse
id = int.Parse(surveys.First());
And you have to use a property of survey, you're trying to convert the entire survey instance to int
id = int.Parse(surveys.First().Property);

Linq2XML missing element

How do I modify the query below to properly handle the case where the "Summary" element is missing from one of the articles? Now when that happens I get an "Object reference not set to an instance of an object."
var articles = from article in xmlDoc.Descendants("Article")
select new {
articleId = article.Attribute("ID").Value,
heading = article.Element("Heading").Value,
summary = article.Element("Summary").Value,
contents = article.Element("Contents").Value,
cats = from cat in article.Elements("Categories")
select new {
category = cat.Element("Category").Value
}
};
The problem is that article.Element("Summary") returns null if the element is not found, so you get a NullReferenceException when you try to get the Value property.
To solve this, note that XElement also has an explicit conversion to string. This won't throw if the XElement is null - you will just get a null string reference.
So to solve your problem you can change this:
summary = article.Element("Summary").Value,
to this:
summary = (string)article.Element("Summary")

Error: FormatException was unhandled by user code in Linq how to solve?

Look please below this codes throw me : FormatException was unhandled by user code
Codes:
satis.KDV = Decimal.Parse((from o in genSatisctx.Urun where o.ID == UrunID select o.Kdv).ToString());
How can i rewrite linq query?
You are calling ToString on the query rather than a single result. Even though you may expect only one value to match your query, it will not return just a single value. You have to instruct it to do so using Single, First, Last or the variations of these that also return a default value (SingleOrDefault, FirstOrDefault, LastOrDefault).
In order to avoid an exception, you could change it to use Decimal.TryParse or you could change your code to use a default value if the LINQ query returns something that won't parse properly. I'd recommend the former or a combination.
Note that in the following example, I have added the call to SingleOrDefault. This ensures that only one value is parsed, even if no value is found, and that if there are multiple results, we get an exception (i.e. it enforces that we get exactly zero or one result to the query).
decimal parsedValue;
if (Decimal.TryParse(
genSatisctx
.Urun
.Where(o => o.ID == UrunID)
.Select(o=>o.Kdv)
.SingleOrDefault()
.ToString(), out parsedValue))
{
satis.KDV = parsedValue;
}
You're calling ToString() on an IQueryable<T> - what did you expect the string to be? It's very unlikely to be anything which can be parsed as a decimal number!
My guess is that you want to call First() or Single(), but we can't really tell without more information. What's the type of o.Kdv?
I suspect you either want:
satis.KDV = (from o in genSatisctx.Urun
where o.ID == UrunID
select o.Kdv).First();
or
string kdvString = (from o in genSatisctx.Urun
where o.ID == UrunID
select o.Kdv).First();
decimal kdv;
if (decimal.TryParse(kdvString, out kdv))
{
satis.KDV = kdv;
}
else
{
// What do you want to do if it's not valid?
}
When I use debug mode I see the data is update when over mouse, after end of this method ( it's show this message [input string was not in a correct format]
/* protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
TextBox name = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditName");
SqlDataSource2.UpdateParameters["Name"].DefaultValue = name.ToString();
TextBox age = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditAge");
SqlDataSource2.UpdateParameters["Age"].DefaultValue = age.ToString();
TextBox birthday = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditBirthday");
SqlDataSource2.UpdateParameters["Birthday"].DefaultValue = birthday.ToString();
DropDownList country = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("DropEditCountry");
SqlDataSource2.UpdateParameters["CountryID"].DefaultValue = country.SelectedValue;
TextBox mobile = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditMobile");
SqlDataSource2.UpdateParameters["Mobile_No"].DefaultValue = mobile.ToString();
SqlDataSource2.Update();
}
catch (Exception j)
{
j.Message.ToString();
}
}
/* }

Resources