Intermittent NullReferenceException Error

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

The following code is running in an asp.net application:

bool bLogin;
try
{
bLogin = Convert.ToBoolean(Session["UserLogin"].ToString());
}
catch
{
bLogin = false;
}

ArrayList _roles;
try
{
_roles = (ArrayList)Session["Role"];
}
catch
{
_roles = new ArrayList();
_roles.Add(0);
}

if(bLogin && _roles.Contains(3))
{
plUnsecure.Visible = false;
plSecure.Visible = true;
}
else
{
plUnsecure.Visible = true;
plSecure.Visible = false;
}

if(!_roles.Contains(3))
{
plLogin.Visible = true;
}
else
{
plLogin.Visible = false;
}

I'm getting intermittent NullReferenceException errors on the line:
if(!_roles.Contains(3))

This is confusing me because the line:
if(bLogin && _roles.Contains(3))

was executed prior to the error line and it did not generate a
NullReferenceException error.

The entire code block runs in the Page_Load method of the asp.net page. I
am unable to reproduce the error in the production or development
environments, but all production errors are logged, so I know it is occurring.

I plan on refactoring the code, but I hope someone could shed some light on
why it is not working as is.

Thanks,
Eric
 
This would make sense if bLogin is false, so _roles.Contains(3) is never
tested, so I'm guessing that the session has dropped, and so Session["Role"]
returns null.

I would make this:
_roles = (ArrayList)Session["Role"];
if(_roles==null) {
_roles = new ArrayList();
_roles.Add(0);
}

I would also investigate a flags enum for the roles.

Marc
 
Back
Top