ASP.NET Session Object reference not set to instance of an object - asp.net

Hey Just wondering how the following can happen
Object reference not set to an instance of an object.
customerName.Text = Session("userName").ToString()
If (Session("userId") Is Nothing) Then
Response.Redirect(ConfigurationManager.AppSettings("site_base_url").ToString & "login/", False)
End If
customerName.Text = Session("userName").ToString()
Now I currently have no session set on this page. So the session is NULL but i am just wondering why my if statement is taking care of this problem, why does it even try to get to the next part i.e. Response.Write ?

From your code snippet it looks like the line Response.Write(Session("UID").ToString) will always be executed regardless of what happens with the if statement above it.
I wonder if the weird indentation isn't confusing you. Try looking at it like this:
If (Session("userName") IsNot Nothing) Then
customerName.Text = Session("userName").ToString()
End If
Response.Write(Session("UID").ToString)
Notice that I aligned the End If with the corresponding If above and the Response.Write... as well. The Response.Write... line clearly sits outside of the If block and since there is not return or break or continue in the If block it will always get executed.
And btw, it's probably not the Session object that is null. You are calling ToString on an item you assume to be contained in the Session object. It's more likely that the Session does not contain a "UID" entry.

Response.Write() is outside of the IF statement, so whether or not the Session Is Nothing, the Response.Write() method will be ran.
Alternatively, perhaps youre trying to assign a value to the Session if it doesnt already have one? In this case, I think you have your code in reverse:
customerName.Text = Session("userName").ToString()
Should be:
Session("userName") = customerName.Text

Your
customerName.Text = Session("userName").ToString();
will be executed no matter what the value of the session is. In the if condition, you are checking for the (Session("userId") and not Session("userName"). Both of them are different session variables. If for some reason Session("userName") value is not assigned prior, you will get the "Object reference not set to an instance of an object" exception.
I would do a session null check first before assigning the value to customerName.Text
if(Session("userName") IsNot Nothing) Then
customerName.Text = Session("userName").ToString();

Related

if then logic failing to execute code block

I have the following code logic in my vb.net(.net 4.7) page that is supposed to check the value of a session object.
If that object is not nothing and that object does not equal a specific string, then the code block between the if and end if statements is supposed to be executed.
But no matter what I do, it never gets executed.
I even tried setting a breakpoint in Visual Studio to see what the value of Session("buildingID") is, and even if it's something like this:
Session("buildingID") = "991c"
The code block is never hit.
Here is the logic:
If Session("buildingID") IsNot Nothing AndAlso Not Session("buildingID").ToString = "543a" Then
'Do Stuff
End If
The Session object is of type
System.Web.SessionState.HttpSessionState
What could be causing this?
Thanks!

Dealing with a NullReferenceException after user is idle for over a certain amount of time

I have the sub routine below that is used by my game managing web app to refresh the game list.
It works fine except when the user has been idle for more than 20 minutes.
After the user is idle for over 20 minutes, and the user tries to refresh the webpage or navigate within it, this error is always thrown:
[NullReferenceException: Object reference not set to an instance of an object.]
line 15 in refreshGameList() // * line 15 is the "Throw ex" line in the "Catch" statement below *\
How can I prevent this? Either by navigating the user back to the login screen or just "waking up" the app so it doesn't timeout like this?
Thanks
Public Sub refreshGameList(ByVal activePlanetID As Guid)
Dim dbu As New gameUtils.DatabaseUtils
With (Web.HttpContext.Current.Application)
.Lock()
Try
Dim enviromentDataSet As DataSet = CType(Web.HttpContext.Current.Application("enviromentDataSet"), DataSet)
If Not enviromentDataSet Is Nothing And enviromentDataSet.Tables.Contains("gameList") Then
enviromentDataSet.Tables.Remove("gameList")
Dim gameListParams As New ArrayList
gameListParams.Add(New SqlParameter("#planetID", activePlanetID))
dbu.fillDataSet(enviromentDataSet, "gamer_GetGameList", gameListParams, "gameList")
.Item("enviromentDataSet") = enviromentDataSet
End If
Catch ex As Exception
Throw ex
Finally
.UnLock()
End Try
End With
End Sub
In your code, if the cache is empty, the second part of the If statement will still run. Change And with AndAlso
If Not enviromentDataSet Is Nothing AndAlso enviromentDataSet.Tables.Contains("gameList") Then
Caching in asp.net is a bit different than windows form. By default, a web server instance gets removed from memory if there's no activity for a specific amount of time. You need to have steps to rebuild the cache. You can to it in the global.asxa or when you fetch the data, something like.
Public ReadOnly Property EnviromentDataSet As DataSet
Get
If Web.HttpContext.Current.Application("enviromentDataSet") Is Nothing Then
' Load the information
End IF
Return CType(Web.HttpContext.Current.Application("enviromentDataSet"), DataSet)
End Get
End Property

What triggers an System.InvalidCastException in ASP.NET?

I have an issue on my ASP.NET 4.0 application. The error appears when I call one of my subroutines in the App_Code folder. I call the subroutine when a button is clicked on the page.
Protected Sub imgBtnEmailReg_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles imgBtnEmailReg.Click
Dim functions As New Functions
Dim pidm As Integer = Convert.ToInt32(Session("BannerPidm").ToString)
functions.sendStudentAccomLetter(pidm)
End Sub
After the button click the id number is sent to the App_Code/Functions.vb where my subroutine is:
Public Sub sendStudentAccomLetter(ByVal stuPidm As Integer)
...
End Sub
The error I get when calling the above function is:
"System.InvalidCastException: Specified cast is not valid. at Functions.sendStudentAccomLetter(Int32 stuPidm) in D:\www-sec-docs\DisabilityServices\App_Code\Functions.vb:line 259"
Line 259 is the sub signature. I'm not even sure if there is a cast occurring here. Can someone please explain what might be causing this. Thank you.
Your Session("BannerPidm") value may be a different type - the method declaration is not the cause of the cast error. Try implementing some kind of check on the Session("BannerPidm") value such as:
If IsNumeric(Session("BannerPidm")) Then
'Proceed
This link shows a few examples where you would get and error when trying to convert: http://bytes.com/topic/visual-basic-net/answers/514682-difference-between-cint-convert-toint32
Try using CInt() instead and see if you still have problems. If you do, then you may want to start checking what the session variable is and see if there is a better, more standardized way you can store it.
It is most likely the conversion to Int32. Set a breakpoint at that line, and see what value Session("BannerPidm")
is returning. There is definitely a cast occurring, because you are retrieving from Session, casting it to string (.ToString()), then converting that to Int32.

InsertOnSubmit not triggering a database insert on SubmitChanges

I'm experiencing an odd scenario and I'm looking for ways to figure out what's going wrong. I've got a piece of code that inserts a row into a table - the kind of thing I've done in dozens of other apps - but the end result is nothing happens on the database end, and no errors are generated. How do I find out what's going wrong?
Here's my code:
Partial Class MyDatabaseDataContext
Public Sub CreateEnrollee(subId, depId)
dim newEnrollee = New enrolee With {.subId = subId, .depId = depId}
Me.enrollees.InsertOnSubmit(newEnrollee)
Me.SubmitChanges()
dim test = NewEnrollee.id '<-- auto-incrementing key'
End Sub
End Class
After SubmitChanges is called, no new row is created, and "test" is zero. No errors are generated. I have no idea why it's not trying to insert the row. Any ideas on how to debug this?
You could enable logging:
Me.Log = Console.Out;
You could check the ChangeSet for your object.
FOUND IT! Part of the debugging I did for some other issues included adding some logging to some of the extensibility methods:
Partial Private Sub InsertEnrollee(instance As Enrollee)
End Sub
I thought "InsertEnrollee" existed so I could perform actions after the Enrollee was inserted, so I added logging code here and that's when the trouble started. Now I'm guessing this is how you would override the Enrollee insert and do it yourself if you so desired. Since I was essentially overriding with logging code, that's why nothing was happening (from a database perspective).

Why is my asp.net caching throwing an exception?

I have a bunch of simple lookup tables cached in my asp.net application since the source data is on a seperate server from our main web architecture and it changes infrequently. I've been following answers here and various documentation and I have my initial load function call the following:
HttpContext.Current.Cache.Insert("CheckLocations", GetAllCheckLocations(), _
Nothing, DateAdd(DateInterval.Day, 1, Now()), _
System.Web.Caching.Cache.NoSlidingExpiration, _
CacheItemPriority.Normal, _
New CacheItemRemovedCallback(AddressOf CheckLocationsExpired))
For my cache expired callback, I have the following code.
Public Shared Sub CheckLocationsExpired(ByVal key As String, ByVal value As Object, ByVal reason As CacheItemRemovedReason)
Dim dtCheckLocation As New ReferenceSchema.CheckLocationDataTable
dtCheckLocation = GetAllCheckLocations()
HttpContext.Current.Cache.Insert("CheckLocations", dtCheckLocation, Nothing, _
DateAdd(DateInterval.Day, 1, Now()), _
System.Web.Caching.Cache.NoSlidingExpiration, _
CacheItemPriority.Normal, _
New CacheItemRemovedCallback(AddressOf CheckLocationsExpired))
End Sub
For the record, the GetAllCheckLocations method simply calls a web service and parses the results into the data table being stored.
Now when I recompile the application for local testing, everything still functions fine, but I find the following exception message in my log file:
System.NullReferenceException: Object reference not set to an instance of an
object. at EAF.CacheMethods.CheckLocationsExpired(String key, Object value,
CacheItemRemovedReason reason) in
C:\Projects\HR\EAF 2.0\DAL\CacheMethods.vb:line 434 at
System.Web.Caching.CacheEntry.CallCacheItemRemovedCallback(CacheItemRemovedCallback
callback, CacheItemRemovedReason reason)
I verify that the data is indeed there and up to date, and nothing in the command arguments seems out of place when I step through the debugger.
Does anybody know what I'm missing here? Is this another one of those "nuances" like the Reponse.Redirect issue where terminating the processing technically throws a thread abort exception?
You may want to use HttpRuntime.Cache instead. It's possible that HttpContext.Current is null if you are calling it from a unit test or such.
Does it still exception out when you don't give it a callback function? Seems more like the delegated function is having issues with null objects.
My initial thought is that GetAllCheckLocations is throwing the exception or returning null.
Maybe you call the Method with AJAXPro or something.

Resources