473,612 Members | 2,127 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

cookie null references in c#

Exception Details: System.NullRefe renceException: 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=str ing.Format("You have to login");
}
}
// variable form session, form, cookies or any other method that you
use.
//string sUserId=sUserId 1;
string sPwd="";
int iRoomId=-2; //room ID -2 will not enter any room, -1 will not
enter any room
try
{
iRoomId=int.Par se(lstRooms.Sel ectedValue);

}
catch(Exception ){}
//

//string UserId = cookie.Values["Name"].ToString();
//string sUserId="odonel ";
string sErr="";int iErr=0;
if(this.UserLog in(Session.Sess ionID,iSiteId,s UserId,sPwd,fal se,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 5211
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.Par se(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
ArgumentNullExc eption, not a NullReferenceEx ception.

this.UserLogin( Session.Session ID,iSiteId,sUse rId,sPwd,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(o bject sender, System.EventArg s e)
{
Session["unused"]=0;//this is a hack to work around the bug with
session state not being initialized

int iSiteId=int.Par se(this.SiteIdG et());
// 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["snitz00use r"];

if(cookie == null)
{
//CookieValue represents a WebForm Label control
//try
lblMsg.Text=str ing.Format("log in first"); //test, sUserId was here
}
//}
// catch
else
{
lblMsg.Text=str ing.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.Par se(lstRooms.Sel ectedValue);
}
catch(Exception ){}

string sErr="";int iErr=0;
if(this.UserLog in(Session.Sess ionID,iSiteId,s UserId,sPwd,fal se,iRoomI
d,ref iErr,ref sErr))
{
lblMsg.Text=str ing.Format("Suc cessfully logged in user {0} into site
{1}, room {2}.",sUserId,i SiteId,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=str ing.Format("Fai led to log in user {0} into site {1},
room {2}. Error ({3}) {4}",sUserId,iS iteId,iRoomId,i Err,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(o bject sender, System.EventArg s e)
{
Session["unused"]=0;//this is a hack to work around the bug with
session state not being initialized

int iSiteId=int.Par se(this.SiteIdG et());
// 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["snitz00use r"];

if(cookie == null)
{
//CookieValue represents a WebForm Label control
//try
lblMsg.Text=str ing.Format("log in first"); //test, sUserId was here
}
//}
// catch
else
{
lblMsg.Text=str ing.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.Par se(lstRooms.Sel ectedValue);
}
catch(Exception ){}

string sErr="";int iErr=0;
if(this.UserLog in(Session.Sess ionID,iSiteId,s UserId,sPwd,fal se,iRoomI
d,ref iErr,ref sErr))
{
lblMsg.Text=str ing.Format("Suc cessfully logged in user {0} into site
{1}, room {2}.",sUserId,i SiteId,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=str ing.Format("Fai led to log in user {0} into site {1},
room {2}. Error ({3}) {4}",sUserId,iS iteId,iRoomId,i Err,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.NullRefe renceException: 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:
[NullReferenceEx ception: 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.ZbCha tPage.UserLogou t(Int32 iSiteId, String sUserName,
Int32& iErr, String& sErr) +78
ChatAPISample.C ustomLogin.Butt on2_Click(Objec t sender, EventArgs e)
System.Web.UI.W ebControls.Butt on.OnClick(Even tArgs e) +108

System.Web.UI.W ebControls.Butt on.System.Web.U I.IPostBackEven tHandler.Rai
sePostBackEvent (String eventArgument) +57
System.Web.UI.P age.RaisePostBa ckEvent(IPostBa ckEventHandler
sourceControl, String eventArgument) +18
System.Web.UI.P age.RaisePostBa ckEvent(NameVal ueCollection postData)
+33
System.Web.UI.P age.ProcessRequ estMain() +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(o bject sender, System.EventArg s e)
{

int iSiteId=int.Par se(this.SiteIdG et());
// 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["snitz00use r"];

if(cookie == null)
{
//CookieValue represents a WebForm Label control
lblMsg.Text=str ing.Format("Fai led to log in user");
}
else
{
//CookieValue represents a WebForm Label control
lblMsg.Text=str ing.Format("wor k");
}
try

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

catch
{
lblMsg.Text=str ing.Format("Fai led to log in user");
}

// string sUserId="user1" ;
string sErr="";int iErr=0;
if(this.UserLog out(iSiteId,sUs erId,ref iErr,ref sErr))
{
lblLogout.Text= string.Format(" Successfully logged out user {0} from
site {1}.",sUserId,i SiteId);
//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,iS iteId,iErr,sErr );

}
RoomListRender( );
lnkChat.Visible =false;
------------------------------------------------------------------------
--------
Version Information: Microsoft .NET Framework Version:1.1.432 2.2300;
ASP.NET Version:1.1.432 2.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*er Id,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["snitz00use r"]*;
if(cookie == null)
{
//CookieValue represents a WebForm Label control
lblMsg.Text=str ing.Format("Fai *led to log in user");
}
else
{
sUserId = cookie.Values.G et("Name");
if (sUserId == null)
{
lblMsg.Text = string.Format(" Failed to log in user");
}
else
{
//CookieValue represents a WebForm Label control
lblMsg.Text=str ing.Format("wor *k");

string sErr="";int iErr=0;
if(this.UserLog out(iSiteId,sUs *erId,ref iErr,ref sErr))
{
lblLogout.Text= string.Format(" *Successfully logged out
user {0} from site {1}.",sUserId,i SiteId);
}
else
{
lblLogout.Text= string.Format(" *Failed to log out user {0}
from site {1}. Error ({2}) {3}",sUserId,iS iteId,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.Valu es.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 (ArgumentOutOfR angeException)

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_COOK IE = "YourCookieName ";
const stringNAME_USER ID = "inpUserIDField ";
const stringNAME_SERV ER = "inpServerField ";

private void Page_Load(objec t sender, System.EventArg s e)
{
// Retrieve settings from last visit
try
{
if (Request.Cookie s != null)
{
inpUserID.Value =
Server.HtmlEnco de(Request.Cook ies[NAME_COOKIE][NAME_USERID]).ToString();
inpServer.Value =
Server.HtmlEnco de(Request.Cook ies[NAME_COOKIE][NAME_SERVER]).ToString();
}
}
catch {}
}

private void Submit_ServerCl ick(object sender, System.EventArg s e)
{
// Save user settings
try
{
Response.Cookie s[NAME_COOKIE][NAME_USERID] = inpUserID.Value ;
Response.Cookie s[NAME_COOKIE][NAME_SERVER] = inpServer.Value ;
Response.Cookie s[NAME_COOKIE].Expires = DateTime.MaxVal ue;
}
catch {}
}
www.VoiceInformation.com - <a href="http://www.VoiceInform ation.com">
Virtual Office, Automated Virtual Phone Assistant, Web VMail </a><br>

www.TekGuard.com - <a href="http://www.TekGuard.co m">
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
1486
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 need to return a reference (as opposed to a copy) because I want to use this operator as an l-value sometimes...
3
1693
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) : MyObj* MyClass::GetObj(const wxString& strObjName ) { ReaderIt it = m_scObjs.find( strObjName );
76
4622
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 pointers are allowed to be null, while references must refer an existing variable of required type. The null is normally used for making optional parameters. But there is no way to pass null reference in C#. Something is missing.
6
1459
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 g_something; const Something & getSomething () { if (condition)
0
8105
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8565
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8246
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8415
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7039
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6076
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4045
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2550
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1695
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.