473,382 Members | 1,375 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

cookie null references in c#

Exception Details: System.NullReferenceException: Object reference not
set to an instance of an object.

Source Error:
here is my code:

HttpCookie cookie = Request.Cookies["forumuser"];

if(cookie != null)

{
string sUserId = cookie.Values["Name"].ToString();
}
else
{
lblMsg.Text=string.Format("You have to login");
}
}
// variable form session, form, cookies or any other method that you
use.
//string sUserId=sUserId1;
string sPwd="";
int iRoomId=-2; //room ID -2 will not enter any room, -1 will not
enter any room
try
{
iRoomId=int.Parse(lstRooms.SelectedValue);

}
catch(Exception){}
//

//string UserId = cookie.Values["Name"].ToString();
//string sUserId="odonel";
string sErr="";int iErr=0;
if(this.UserLogin(Session.SessionID,iSiteId,sUserI d,sPwd,false,iRoomId,ref
iErr,ref sErr))
{

can you guys explain to me what i did wrong here for this null error, i
know we get errors if cookies are not found. i just need to set the
cookie value to sUserId if found, and redirect if not found. please
help with any tip

Nov 17 '05 #1
7 5187
Without knowing anything about cookies, I can see the following places
in your code that could cause a null reference exception.

cookie.Values["Name"].ToString*();

What if there is no value called "Name" in your cookie? You will try to
call ToString() on null. Doesn't work.

iRoomId=int.Parse(lstRooms.Sel*ectedValue);

What if nothing is selected in your list? SelectedValue will be null,
and the Parse method will barf... although it should barf with an
ArgumentNullException, not a NullReferenceException.

this.UserLogin(Session.SessionID,iSiteId,sUserId,s Pwd,fal*se,iRoomId,ref
iErr,ref sErr)

OK... this isn't the actual code, is it? I say that because sUserId is
declared inside the "then" part of an "if", up above, but you're using
it down here, so this wouldn't compile.

Could you post the actual code that is failing, and indicate where the
exception is happening?

Nov 17 '05 #2
here is the code, sorry wrong code pasted, thanx for the reply

private void Button1_Click(object sender, System.EventArgs e)
{
Session["unused"]=0;//this is a hack to work around the bug with
session state not being initialized

int iSiteId=int.Parse(this.SiteIdGet());
// This is just a sample. In real application you would take those
// variable form session, form, cookies or any other method that you
use.

HttpCookie cookie = Request.Cookies["snitz00user"];

if(cookie == null)
{
//CookieValue represents a WebForm Label control
//try
lblMsg.Text=string.Format("login first"); //test, sUserId was here
}
//}
// catch
else
{
lblMsg.Text=string.Format("You have to login before you can chat");
}

string sUserId = cookie.Values["Name"].ToString();

// string sUserId="user1";
string sPwd="";
int iRoomId=-2; //room ID -2 will not enter any room, -1 will not
enter any room
try
{
iRoomId=int.Parse(lstRooms.SelectedValue);
}
catch(Exception){}

string sErr="";int iErr=0;
if(this.UserLogin(Session.SessionID,iSiteId,sUserI d,sPwd,false,iRoomI
d,ref iErr,ref sErr))
{
lblMsg.Text=string.Format("Successfully logged in user {0} into site
{1}, room {2}.",sUserId,iSiteId,iRoomId);
//instead you can just put all this code in your page_load event and
use redirect to chat page here.
lnkChat.Visible=true;

RoomListRender();
}
else
{
//depending on error code you may take different action here
lblMsg.Text=string.Format("Failed to log in user {0} into site {1},
room {2}. Error ({3}) {4}",sUserId,iSiteId,iRoomId,iErr,sErr);
lnkChat.Visible=false;
}
}

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #3
here is the code, sorry wrong code pasted, thanx for the reply

private void Button1_Click(object sender, System.EventArgs e)
{
Session["unused"]=0;//this is a hack to work around the bug with
session state not being initialized

int iSiteId=int.Parse(this.SiteIdGet());
// This is just a sample. In real application you would take those
// variable form session, form, cookies or any other method that you
use.

HttpCookie cookie = Request.Cookies["snitz00user"];

if(cookie == null)
{
//CookieValue represents a WebForm Label control
//try
lblMsg.Text=string.Format("login first"); //test, sUserId was here
}
//}
// catch
else
{
lblMsg.Text=string.Format("You have to login before you can chat");
}

string sUserId = cookie.Values["Name"].ToString();

// string sUserId="user1";
string sPwd="";
int iRoomId=-2; //room ID -2 will not enter any room, -1 will not
enter any room
try
{
iRoomId=int.Parse(lstRooms.SelectedValue);
}
catch(Exception){}

string sErr="";int iErr=0;
if(this.UserLogin(Session.SessionID,iSiteId,sUserI d,sPwd,false,iRoomI
d,ref iErr,ref sErr))
{
lblMsg.Text=string.Format("Successfully logged in user {0} into site
{1}, room {2}.",sUserId,iSiteId,iRoomId);
//instead you can just put all this code in your page_load event and
use redirect to chat page here.
lnkChat.Visible=true;

RoomListRender();
}
else
{
//depending on error code you may take different action here
lblMsg.Text=string.Format("Failed to log in user {0} into site {1},
room {2}. Error ({3}) {4}",sUserId,iSiteId,iRoomId,iErr,sErr);
lnkChat.Visible=false;
}
}

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #4
What's the actual text of the exception, and which line in your posted
code is it happening on?

Nov 17 '05 #5
here is the error:

Server Error in '/CHAT' Application.
------------------------------------------------------------------------
--------

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the
current web request. Please review the stack trace for more information
about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not
set to an instance of an object.

Source Error:

An unhandled exception was generated during the execution of the current
web request. Information regarding the origin and location of the
exception can be identified using the exception stack trace below.

Stack Trace:
[NullReferenceException: Object reference not set to an instance of an
object.]
av.a(String A_0) +32
bw.a(String A_0) +15
a3.a(Int32 A_0, String A_1) +78
chat_net3.ZbChatPage.UserLogout(Int32 iSiteId, String sUserName,
Int32& iErr, String& sErr) +78
ChatAPISample.CustomLogin.Button2_Click(Object sender, EventArgs e)
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +108

System.Web.UI.WebControls.Button.System.Web.UI.IPo stBackEventHandler.Rai
sePostBackEvent(String eventArgument) +57
System.Web.UI.Page.RaisePostBackEvent(IPostBackEve ntHandler
sourceControl, String eventArgument) +18
System.Web.UI.Page.RaisePostBackEvent(NameValueCol lection postData)
+33
System.Web.UI.Page.ProcessRequestMain() +1292

it happens when there is no cookie in the machine accessing the page
and this is the button2_click code:

private void Button2_Click(object sender, System.EventArgs e)
{

int iSiteId=int.Parse(this.SiteIdGet());
// This is just a sample. In real application you would take those
// variable form session, form, cookies or any other method that you
use.
//string sUserId="user1";
HttpCookie cookie = Request.Cookies["snitz00user"];

if(cookie == null)
{
//CookieValue represents a WebForm Label control
lblMsg.Text=string.Format("Failed to log in user");
}
else
{
//CookieValue represents a WebForm Label control
lblMsg.Text=string.Format("work");
}
try

{
sUserId = cookie.Values["Name"].ToString();
}

catch
{
lblMsg.Text=string.Format("Failed to log in user");
}

// string sUserId="user1";
string sErr="";int iErr=0;
if(this.UserLogout(iSiteId,sUserId,ref iErr,ref sErr))
{
lblLogout.Text=string.Format("Successfully logged out user {0} from
site {1}.",sUserId,iSiteId);
//instead you can just put all this code in your page_load event and
use redirect to chat page here.
//lnkChat.Visible=true;

}
else
{
//depending on error code you may take different action here

lblLogout.Text=string.Format("Failed to log out user {0} from site
{1}. Error ({2}) {3}",sUserId,iSiteId,iErr,sErr);

}
RoomListRender();
lnkChat.Visible=false;
------------------------------------------------------------------------
--------
Version Information: Microsoft .NET Framework Version:1.1.4322.2300;
ASP.NET Version:1.1.4322.2300

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #6
So the problem seems to be that sUserId is set only when there is a
cookie. That is, inside the try...catch you have

sUserId = cookie.Values["Name"].ToString*();

However, if that fails, what should sUserId contain? Obviously it
contains a null reference in the current implementation.

Or, perhaps that's the wrong question. A better question would be: If
the attempt to fetch the cookie fails, what do you want to do? Do you
really want to log the user out? Calling

this.UserLogout(iSiteId,sUs*erId,ref iErr,ref sErr)

with a null sUserId appears to make it blow up. If the user has no
cookie, or the "Name" value isn't in the cookie, doesn't that mean that
they're not logged in? Or, at the very least, that you can't determine
who it is, so you can't log them out? Perhaps you want this:

HttpCookie cookie = Request.Cookies["snitz00user"]*;
if(cookie == null)
{
//CookieValue represents a WebForm Label control
lblMsg.Text=string.Format("Fai*led to log in user");
}
else
{
sUserId = cookie.Values.Get("Name");
if (sUserId == null)
{
lblMsg.Text = string.Format("Failed to log in user");
}
else
{
//CookieValue represents a WebForm Label control
lblMsg.Text=string.Format("wor*k");

string sErr="";int iErr=0;
if(this.UserLogout(iSiteId,sUs*erId,ref iErr,ref sErr))
{
lblLogout.Text=string.Format("*Successfully logged out
user {0} from site {1}.",sUserId,iSiteId);
}
else
{
lblLogout.Text=string.Format("*Failed to log out user {0}
from site {1}. Error ({2}) {3}",sUserId,iSiteId,iErr,sErr*);
}
}
}

This way, the code will do the UserLogout only if the attempt to fetch
the cookie succeeds, and the attempt to fetch the "Name" value from the
cookie succeeds. By using the HttpCookie.Values.Get method, you also
avoid the overhead of an exception, making the code run a little faster
(trivially so) and making it clearer what's going on (more important).

Lastly, if you do use exceptions, you don't want to use a blanket
"catch" or "catch (Exception)" unless you have no documentation telling
you what the exceptions are. In your case, if you were to use an
exception, you would want:

catch (ArgumentOutOfRangeException)

because this is the exception that is thrown if the "Name" value isn't
in the cookie. Other exceptions should be allowed to crash the
application, since they indicate something horrible and unanticipated
happened.

Nov 17 '05 #7
Be sure to wrap your references in a try block:
try {string sUserId = cookie.Values["Name"].ToString*();}

Sample C# Code:
const stringNAME_COOKIE = "YourCookieName";
const stringNAME_USERID = "inpUserIDField";
const stringNAME_SERVER = "inpServerField";

private void Page_Load(object sender, System.EventArgs e)
{
// Retrieve settings from last visit
try
{
if (Request.Cookies != null)
{
inpUserID.Value =
Server.HtmlEncode(Request.Cookies[NAME_COOKIE][NAME_USERID]).ToString();
inpServer.Value =
Server.HtmlEncode(Request.Cookies[NAME_COOKIE][NAME_SERVER]).ToString();
}
}
catch {}
}

private void Submit_ServerClick(object sender, System.EventArgs e)
{
// Save user settings
try
{
Response.Cookies[NAME_COOKIE][NAME_USERID] = inpUserID.Value;
Response.Cookies[NAME_COOKIE][NAME_SERVER] = inpServer.Value;
Response.Cookies[NAME_COOKIE].Expires = DateTime.MaxValue;
}
catch {}
}
www.VoiceInformation.com - <a href="http://www.VoiceInformation.com">
Virtual Office, Automated Virtual Phone Assistant, Web VMail </a><br>

www.TekGuard.com - <a href="http://www.TekGuard.com">
Free Mail Server, AntiSpam, PlugIn, WebMail, Free Source Code </a>

Nov 17 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Tony Di Croce | last post by:
Given: T& operator ( int index ); // T is a parameterized type What should be returned when index is out of range? This same question comes up virtually everywhere I return a reference. I...
3
by: Vincent RICHOMME | last post by:
Hi, I would like to know how I can return a NULL reference. usually when I need to return an object and to know if the object is valid I use a pointer (if the object is nto valid I return NULL)...
76
by: valentin tihomirov | last post by:
As explained in "Using pointers vs. references" http://groups.google.ee/group/borland.public.delphi.objectpascal/browse_thread/thread/683c30f161fc1e9c/ab294c7b02e8faca#ab294c7b02e8faca , the...
6
by: jason.cipriani | last post by:
Is it OK to dereference NULL pointers if the only thing you are doing is storing them in a reference then comparing addresses to NULL again later, as in: === BEGIN EXAMPLE === Something...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.