ASP.NET Session bool variable is set to null in page load - asp.net

I am receiving this error message when I debug my program.
Object reference not set to an instance of an object.
That error happens on this line:
protected void Page_Load(object sender, EventArgs e)
{
bool x = (bool)Session["IsConnectionInfoSet"];--> error here
if (IsPostBack && x)
//do something with the bool x variable
}
Postback is invoked by:
protected void btnDo_Click(object sender, EventArgs e)
{
//do something
Session["IsConnectionInfoSet"] = true;
//do something
}
This error happened in Visual Studio 2008, .NET Framework 3.5.
Can someone give me advice on how this?

The Page_Load method is always run before any event handlers. As a result, the page_load will run, find null and throw an error, all before you click handler has a chance to set this session value.
Here's a safer way to access this session value
bool x = Session["IsConnectionInfoSet"] == null ? false :
(bool)Session["IsConnectionInfoSet"];

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//this is the first time page load.
}
else
{
if (Session["IsConnectionInfoSet"] != null)
{
bool x = (bool)Session["IsConnectionInfoSet"];
if (x)
{
//do something with the bool x variable
}
}
}
}
Hope this helps

Related

ViewState equal null asp.net

I have the next code.
protected void Page_PreRender(object sender, EventArgs e)
{
bool isDelayWarning = proxy.MerchantPaySystemSetting_IsHoldPaymentsAllow(clientID, PaySystem.Type));
ViewState.Add("IsDelayWarning", isDelayWarning);
}
protected void btnSend_Click(object sender, EventArgs e)
{
if ((bool)ViewState["IsDelayWarning"] && !cbxDelayConfirm.Checked)
{
this.CustomErrorMessage = Yandex_Term_Error;
return;
}
}
In btnSend_Click method ViewState["IsDelayWarning"] = null.
How can I resolve this trouble?
Thanks! :)
I'm not sure about the logic you're going for, but a button push happens during post-back, before the page is rendered. Put breakpoints in your two methods to see their relative order.
Pay attention to the yellow marked items, control event processing is one of them and it happens strictly before PreRender.
You can always check for null reference by doing something like this
if (something != null)
code ------
or another way if you will sometimes have null is to use. For example if user address is null
if (thisuser.Address == null)
{
thisuser.Address = new Address();
}
thisuser.Address = user.Address.City;

The object reference error in asp.net

i am using the following code on page_load event in asp.net
protected void Page_Load(object sender, EventArgs e)
{
lblDate.Text = System.DateTime.Now.ToLongDateString();
if(!IsPostBack)
{
setImageUrl();
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
setImageUrl();
}
private void setImageUrl()
{
Random rnd = new Random();
int i = rnd.Next(1, 7);
Image1.ImageUrl ="~/SlideImages/"+ i.ToString() + ".gif";
}
code is working well at page-load event but when i click any other menu item it gives me the following error message
Object reference not set to an instance of an object.
Well I am 95% sure that i is null because when you ToString() and object if it is null it will throw a fatal exception. What I would do is set a break point on the line throwing the error and run this project in debug mode and see what I is returning. If it is null then there is your problem. So you would have to find out why your Random Method isn't instantiating properly.
Also a recommendation would be to do a String.Format on that line as well
Image1.ImageUrl = String.Format("~/SlideImages/{0}.gif", i);
This will give you the same result set as long as i is valid and String.Format will format null as an empty string. So you will have a graceful fail and your image just won't show up which means you know your problem.

asp.net tracking user info

How is the best way to track user information, sesssion Id, cookies? once for user session.
In Default.aspx:
protected void Page_Load(object sender, EventArgs e)
{
IF (!isPostPack)
{
var sessionValue= System.Web.HttpContext.Current.Request.Cookies["ASP.NET_SessionId"] != null ? System.Web.HttpContext.Current.Request.Cookies["ASP.NET_SessionId"].Value : string.Empty;
cONSOLE.WRITELINE(sessionValue);
}
}
This is not optimize. is there anyway to get only once the session iD,per user?
var sessionValue = System.Web.HttpContext.Current.Request.Cookies["ASP.NET_SessionId"]
!= null ?
System.Web.HttpContext.Current.Request.Cookies["ASP.NET_SessionId"].Value : string.Empty;
All that will give you is the identifier that ASP.Net uses to track the session. This is rarely something you need to directly access in code.
But assuming that is what you want, it will be extremely fast. To make it cleaner, you can:
Access Request directly (no need for HttpContext inside a Page)
Store the value in a class-level variable that will live for the lifecycle of the page.
private string _sessionId;
protected void Page_Load(object sender, EventArgs e)
{
_sessionId = Request.Cookies["ASP.NET_SessionId"] != null
Request.Cookies["ASP.NET_SessionId"].Value : string.Empty;
}
If you want to do this only once per session (per the comments):
protected void Session_Start( object sender, EventArgs e )
{
using( var writer = File.CreateText( #"c:\temp\session-id.txt" ) )
{
writer.WriteLine( Session.SessionID );
}
}

Set session variable in Application_BeginRequest

I'm using ASP.NET MVC and I need to set a session variable at Application_BeginRequest. The problem is that at this point the object HttpContext.Current.Session is always null.
protected void Application_BeginRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.Session != null)
{
//this code is never executed, current session is always null
HttpContext.Current.Session.Add("__MySessionVariable", new object());
}
}
Try AcquireRequestState in Global.asax. Session is available in this event which fires for each request:
void Application_AcquireRequestState(object sender, EventArgs e)
{
// Session is Available here
HttpContext context = HttpContext.Current;
context.Session["foo"] = "foo";
}
Valamas - Suggested Edit:
Used this with MVC 3 successfully and avoids session error.
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
if (context != null && context.Session != null)
{
context.Session["foo"] = "foo";
}
}
Maybe you could change the paradigm... Perhaps you can use another property of the HttpContext class, more specifically HttpContext.Current.Items as shown below:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
HttpContext.Current.Items["__MySessionVariable"] = new object();
}
It won't store it on the session, but it will be stored on the Items dictionary of the HttpContext class and will be available for the duration of that specific request. Since you're setting it at every request, it would really make more sense to store it into a "per session" dictionary which, incidentally, is exactly what the Items is all about. :-)
Sorry to try to infer your requirements instead of answering your question directly, but I've faced this same problem before and noticed that what I needed was not the Session at all, but the Items property instead.
You can use the session items in Application_BeginRequest this way:
protected void Application_BeginRequest(object sender, EventArgs e)
{
//Note everything hardcoded, for simplicity!
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("LanguagePref");
if (cookie == null)
return;
string language = cookie["LanguagePref"];
if (language.Length<2)
return;
language = language.Substring(0, 2).ToLower();
HttpContext.Current.Items["__SessionLang"] = language;
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(language);
}
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
if (context != null && context.Session != null)
{
context.Session["Lang"] = HttpContext.Current.Items["__SessionLang"];
}
}

asp.net ObjectDataSource error handling

I have objectdatasource and I am trying to find a way to capture the error that is thrown by the SELECT method.
anyone idea how it can be done?
Page level error handling is preferred, not capturing error at the application_error in global.asax
thanks,
Like this:
protected void Page_Load(object sender, EventArgs e)
{
ds.Selected += new ObjectDataSourceStatusEventHandler(ds_Selected);
}
void ds_Selected(object sender, ObjectDataSourceStatusEventArgs e)
{
if (e.Exception != null)
{
}
}

Resources