Object reference error even when object is not null - c#

i have an application wherein i have incorporate a "Remember Me" feature for the login screen.
I do this by creating a cookie when the user logs in for the first time, so next time when the user visits the site i get the cookie and load the user information.
i have written the code for loading user information in a common class in the App_Code folder...and all my pages inherit from this class.
code for loading the user info is as follows:
public static void LoadUserDetails(string emailId)
{
UsersEnt currentUser = UsersBL.LoadUserInfo(emailId);
if (currentUser != null)
HttpContext.Current.Session["CurrentUser"] = currentUser;
}
Now the problem is i get an "Object reference" error when i try to store the currentUser object in the session variable (even though the currentUser object is not null). However the password property in the currentUser object is null.
Am i getting the error because of this...or is there some other reason??
thank you

Assuming it's the final line which is causing the problem, that suggests that either HttpContext.Current or HttpContext.Current.Session is null. I suggest you find out which it is, and then work out why.

HttpContext.Current.Session is probably null.
Code that uses the State has to be placed after the AcquireRequestState Event has called. See the page lifecycle for more information.
Try putting your code after or inside the Page_Load method.

If it is throwing the exception on the line:
HttpContext.Current.Session["CurrentUser"] = currentUser;
Then the only other explanation is that HttpContext.Current.Session is null.

Related

My Session variable is always null

I'm creating a movie ticket reservation project. I want to get username from page1 and display it on page2 (using session variable)
Page1:
string uname = TextBox1.Text;
Session["UName"] = uname;
Session.Timeout = 30;
Page2:
if ((string)Session["UName"] != null)
{
string user = (string)Session["UName"];
}
and I placed a sign out button in page2 to remove session variable value. But the session variable is always null.
I've already used cookies in the page1 and will this be a cause? or what else? Please Help. Thanks in advance.
This usually occurs when doing a Response.Redirect after setting the session variable. You can work around this issue by calling the overload instead:
Response.Redirect("...", false); // false = don't stop execution
//causes ASP.NET to bypass all events and filtering in the HTTP pipeline
//chain of execution and directly execute the EndRequest event
HttpContext.Current.ApplicationInstance.CompleteRequest();
The underlying issue is a ThreadAbortException which is often ignored because it doesn't break the application. This is a known issue, and you can learn more about it here: http://support.microsoft.com/kb/312629.
Side Note
On a side note, you shouldn't be resetting your Session.Timeout value in the code like that. I can't be sure, but that may also have an adverse affect on your logic. Instead, you should specify the session timeout in the web.config under the system.web section:
<sessionState timeout="60" />
See this answer on when the Session can be null:
What should I do if the current ASP.NET session is null?
I personally often ran into this issue when I was using async requests with completion callback. In these callbacks I wanted to set something in the session and it was null.
I also had same problem,
I was toggling between debugging two different sites on localhost and there were two cookies for the session ID.
I deleted the cookies via Chrome's developer tools [Press F12 in Browser]->Application->Storage->Cookies

other user's profile not populating

I've got a weird issue going on. I'm calling the profile for another user (not the currently authenticated user) and trying to access a value.
var profile = System.Web.Profile.ProfileBase.Create(username, true);
if (profile.PropertyValues["x"] != null)
ddlList.SelectedValue = profile.PropertyValues["x"].PropertyValue.ToString();
The value 'x' does exist for the user, but it's returning null. If I step through the code, and actually view the profile values before the if statement, then it works as expected. So I have to explicitly step through the code and view the value for the app to actually acknowledge it.

setting HttpContext.Current.User throws null reference exception

This is a WCF Oneway operation. HttpContext.Current.User is cleared in those operations, that is the reason I added a behavior that saves the User before it is cleared. Later I want to re-set the HttpContext.Current.User with the value I saved but I'm getting an exception:
HttpContext.Current.User = (RolePrincipal)userThatWasSavedBefore;
Object reference not set to an instance of an object.
at System.Web.HttpContext.SetPrincipalNoDemand(IPrincipal principal, Boolean needToSetNativePrincipal)
at System.Web.HttpContext.set_User(IPrincipal value)
at (My Function)
Why can't I set the user? What is the problem?
The reason you can't set it is most likely that the request has finished. Setting the User property results in ASP.NET trying to call back into per-request data structures, and if these data structures have been released then the resulting behavior is undefined.
For one-way operations, WCF invokes application code while simultaneously telling ASP.NET not to wait for the application code to finish and to just complete the request immediately. For this reason is it strongly recommended that you don't access HttpContext from a one-way operation.
Clearly some object in the line throwing the exception is null.
Check whether you have a current HttpContext, that is, I suspect HttpContext.Current is null.
The call stack shows an instance method of HttpContext is executed.
In other words - HttpContext is there, the exception is provoked by something else - a missing NulRef check likely for _notificationContext.
The NotificationContext is internal and unset only by OnRequestNotificationCompletionHelper as I write.
Exception scenario seem to look like:
Some work is to be done async - does not block/prevent a request from being completed
Request processing is finished
Your worker item sets HttpContext.User for the finished request
This looks like a framework bug :(
This problem is either because some object in these classes is null (such as HttpContext.Current)
OR
The user which you are passing there (and you saved before) is actually pointing to null. As you can see from stack trace, this is very likely the case, because the exception is thrown by System.Web.HttpContext.set_User(IPrincipal value)
User is actually not a variable, but a property. And changing it to another value is calling a function, that throws this exception in case new value for user is null.
In order to find out what is causing this problem I recommend you to set a breakpoint to the line which is throwing the exception and check if any part of that line isn't pointing to null
crash proof alternative could be:
if (HttpContext.Current != null && userThatWasSavedBefore != null)
{
HttpContext.Current.User = (RolePrincipal)userThatWasSavedBefore;
}

C# MVC4 windows username and cookie issues

First, I'm sad to say I'm not sure whether this code should be in the _Layout.cshtml or somewhere in the controller. It needs to run on all pages, so I've put it in the _Layout.cshtml page.
This is for an intranet web app. What I'm attempting to do is this: if a cookie (holding the user's userid) is not found, get the windows username, run it through a class that will go into the database and get the corresponding user's username, and - if we get a user id back - make a cookie containing it. Doesn't sound too hard, but one line in particular, and various incarnations of it, is refusing to be supportive. Here's the code as a whole.
if(!Context.Response.Cookies.AllKeys.Contains("userid")){
var winuser = System.Web.HttpContext.Current.User.Identity.Name;
var winuserid = myprojectname.Models.MyIntranetDataContext.getUserId(winuser).UserID();
if (winuserid == null) {
Response.Redirect("/someotherpage");
} else {
HttpCookie cookieuser = new HttpCookie("userid");
DateTime now = DateTime.Now;
cookieuser.Value = winuserid;
cookieuser.Expires = now.AddMonths(1);
Response.Cookies.Add(cookieuser);
}
}
Line 2 - var winuser... - appears to be the problem. In this current incarnation, I'm getting a build error: An object reference is required for the non-static field, method, or property 'myprojectname.Models.MyIntranetDataContext.getUserId(string)'
It doesn't like it when I add a .ToString to it either.
I've tried making winuser this as well:
Page.User.Identity.Name;
That gave no build errors. When I attempt to Start Debugging, she blows up with this beauty of an error: 'Cannot perform runtime binding on a null reference'
Once I get the windows username, all will be well.
Really, this isn't about cookies, or even mvc to much of an extent (except maybe guidance on where to put this code - the _Layout.cshtml?). Really it's about getting the windows username, which I seem unable to do. Thanks in advance for any assistance you are able to provide.
Note, the above names aren't actual - just for example only.
If they are on the domain, couldn't you use something like the following to retrieve that information?
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
WindowsPrincipal principal = (WindowsPrincipal)Thread.CurrentPrincipal;
WindowsIdentity identity = (WindowsIdentity)principal.Identity;
String userName= principal.Identity.Name;

Error retrieving information from user cookie

When I run the project, I get this line highlighted with an error:
string cartID = context.Request.Cookies["Cinemax_CartID"].Value;
The message is as follows:
Object reference not set to an instance of an object.
Thanks for any suggestions!
The problem is that you have to check if the cookie exists, if it does, then you can read its value in a safe way, otherwise you should initialize the cookie value or you would get a null reference exception.
This is actually the same pattern you should apply when reading items from the ViewState, Session, Application, Cookies, etc. basically you cannot rely on an external value, you should check if it actually exists
Try something like this:
if(context.Request.Cookies["Cinemax_CartID"] == null)
{
// initialize the cookie
context.Request.Cookies["Cinemax_CartID"].Value = initial_value;
}
myCookieValue = context.Request.Cookies["Cinemax_CartID"].Value;

Categories