StateSession NullReference - asp.net

I'm working on a Login session through Visual Basic with asp.net. When the session timeout is complete and I click on another different page it gives me an error, "Object reference not set to an instance of an object." SessionState mode="InProc"
Here is the code that I used for the session:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Session("Username") Is Nothing Then
Label1.Text = "Welcome, " & Session("Username").ToString()
End If
End Sub

If Session("Username") IsNot Nothing Then
Label1.Text = "Welcome, " & Session("Username").ToString()
Else
Response.Redirect("~/Default.aspx")
End If
You need to check for if it's not null before you reference it. You were doing the opposite. You were checking to see if it's null, verifying it was, then referencing it. That's why you get a NullReferenceException. Basically all null reference exceptions are the same, you're trying to perform an operation on an object that is null.

Use a built in function which is exactly what you are looking for :
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsNothing(Session("Username")) Then
Label1.Text = "Welcome, " & Session("Username").ToString()
End If
End Sub
That's all :=)
Cheers

Related

VB.NET persistent cookie exception

I am attempting to add the text that a user types into the textbox 'textMain' to a cookie. I am trying to do this so there is no need to click a 'Save' button. Therefore a user could type a sentence and then close the browser and it would be saved. Here is the VB code; done on the load handler and the unload handler.
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
If Request.Cookies("content") IsNot Nothing Then
textMain.Text = Request.Cookies("content").Value.ToString
End If
End If
End Sub
Protected Sub Page_Unload(sender As Object, e As EventArgs) Handles Me.Unload
'' If Request.Cookies("content") Is Nothing Then
Dim contentCookie As New HttpCookie("content")
contentCookie.Value = textMain.Text
contentCookie.Expires = DateTime.MaxValue
Response.Cookies.Add(contentCookie)
'' End If
End Sub
The exception comes on the Respinse.Cookies.Add(contentCookie) line.
Thanks!

Only IE10 returning Invalid Postback

I swear I have a love hate relationship with Microsoft. This is being thrown only in IE 10.
Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/>
Now,
On the #page I have ValidateRequest = "False"
In the Web.config I have httpRuntime requestValidationMode="2.0"
I am NOT using any Ajax or have a ScriptManager
I am checking for PostBack
Removed combobox code but it does use AutoPostBack
Here is my code
Private Sub Page_Init(sender As Object, e As EventArgs) Handles Me.Init
Try
Dim User As New UserRole(Me.SiteID, Master.UserName)
If User.GetLevel(Permissions.Edit) >= Levels.Page Then
Exit Sub
End If
Catch ex As Exception
End Try
Response.Redirect("/Manage/Errors/Unauthorized.aspx")
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Me.IsPostBack = True Then
Exit Sub
End If
Try
Dim Item As New PageBase(Me.PageID)
Me.txtCode.Text = Item.Code
Catch ex As Exception
Master.ShowError("Flex encountered a problem reading this page.")
End Try
End Sub
Private Sub cmbSnippet_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbSnippet.SelectedIndexChanged
If Me.cmbSnippet.SelectedIndex = 0 Then
Exit Sub
End If
Try
Dim Filename As String = String.Format("/Manage/Editors/Text/Scripts/{0}", Me.cmbSnippet.SelectedValue)
Me.txtCode.Text = My.Computer.FileSystem.ReadAllText(Server.MapPath(Filename))
Exit Sub
Catch ex As Exception
End Try
Master.ShowError("Flex encountered a problem reading the snippet.")
End Sub
Private Sub btnOk_Click(sender As Object, e As EventArgs) Handles btnOk.Click
Try
Dim Item As New PageBase(Me.PageID)
Item.Code = Me.txtCode.Text
If Item.Update = True Then
Me.ShowUpdateTime()
Exit Sub
End If
Catch ex As Exception
End Try
Master.ShowError("Flex encountered a problem modifying this page.")
End Sub
Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
Response.Redirect(String.Format("/Manage/Preview.aspx?PageID={0}", Me.PageID))
End Sub
This may or may not solve the issue.
.NET 4 and earlier don't know what IE 10 is. It's not in the list of browsers .NET knows about, so .NET assumes the browser is something that can't handle...well, anything really. Javascript and cookies, and I suspect more, get screwed over. So:
Download this: http://www.hanselman.com/blog/content/binary/App_BrowsersUpdate.zip, which is taken from here:
http://www.hanselman.com/blog/BugAndFixASPNETFailsToDetectIE10CausingDoPostBackIsUndefinedJavaScriptErrorOrMaintainFF5ScrollbarPosition.aspx,
which is referenced from here: IE10 User-Agent causes ASP.Net to not send back Set-Cookie (IE10 not setting cookies)
Extract the files and put them in your application's App_Browser directory. Rebuild and see if that works.

CheckBoxList.Selected keeps coming back with False value

I have a CheckBoxList on my page that isn't behaving very well.
The idea is that once the submit button on the form is clicked, the app should clear the database table of all rows pertaining to the specific user and then re-insert new ones based on the user's CheckBoxList selections.
The problem is that regardless of whether or not any (or all) items in the CheckBoxList are selected, the app keeps getting Selected = False.
Here's my code:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
loadRegions()
End Sub
Private Sub loadRegions()
Dim db As New Database
Dim sql As String = "select * from regions"
Dim dr As MySqlDataReader = db.execDB(sql, "Text", Nothing, "DataReader", False)
If dr.HasRows Then
cblRegion.DataSource = dr
cblRegion.DataTextField = "regionname"
cblRegion.DataValueField = "regionid"
cblRegion.DataBind()
End If
dr.Close()
End Sub
Protected Sub btnRegister_Click(sender As Object, e As System.EventArgs) Handles btnRegister.Click
' ============================================================
' There's more code in here, but it's irrelevant to this paste
' ============================================================
Dim sql As String = "delete from userregions where userid = " & lblUserID.Text & ";"
For i As Integer = 0 To cblRegion.Items.Count - 1
If cblRegion.Items(i).Selected Then
sql &= "insert into userregions (userid, regionid)" & _
"values(" & UserID & ", " & cblRegion.Items(i).Value & ")"
db.execDB(sql, "Text", Nothing, "None", False)
End If
Next
End Sub
For the record
I'm aware of the potential for SQL Injection here. I'll be going over to using Parameters as soon as I have the loop working.
Thanks for your time.
Any help will be greatly appreciated.
You only need to call loadRegions on the initial load and not on postbacks:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
loadRegions()
End If
End Sub
Otherwise you'll lose changed values and events are not triggered.
Add this line of copde "If IsPostBack Then Return" in Page_Load method.
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If IsPostBack Then Return
loadRegions()
End Sub
In page loaded, write the following:
If Not IsPostBack
loadRegions()
End If

User enters code into TextBox, code gets added to URL (using session)

I'm using ASP.net 4.0 VB :)
I am using a session variable to add a user entered code into the url of each page. I can get the code to show up at the end of the page's URL that my textbox is on, but what do I add to every page to make sure that the session stays at the end of every URL that person visits during their session? This is the code from the page that the user enters their user code.
Protected Sub IBTextBoxButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles IBTextBoxButton.Click
Session("IB") = IBTextBox.Text
Dim IB As String = Session("IB")
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ProductID.Value = Request.QueryString("id")
If Session("IB") Is Nothing Then
tab4.Visible = "False"
Else
tab4.Visible = "True"
End If
End Sub
This is what I have in the page load of one of the other pages. What else do I add to make sure that variable is added to the URL of that page?
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim IB As String
IB = Session("IB")
End Sub
string url = Request.Url.ToString();
string newUrl = url + url.Contains("?") ? "&" : "?" + "ib=" + Server.UrlEncode(IBTextBox.Text);
Response.Redirect(newUrl);
return;
The approach I might use would be to create a base page class that all of your pages can inherit. The base page would then inherit the System.Web.UI.Page.
Within your base page class, create a property for IB and also handle the page load event.
In that event, check if the QueryString has the IB parameter in it. If it does, set the property to the value in the parameter.
Private _IB As String
Public Property IB() As String
Get
Return _IB
End Get
Set(ByVal value As String)
_IB = value
End Set
End Property
Public Function GetIB(ByVal url As String) As String
If Not(_IB = String.Empty) Then
If (url.Contains("?")) Then
Return "&IB=" & _IB
Else
Return url & "?IB=" & _IB
End If
Else
Return url
End If
End Function
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not (String.IsNullOrEmpty(Request.QueryString("IB"))) Then
_IB = Request.QueryString("IB")
End If
End Sub
Finally in your markup you would need to place something like the following at the end of all of your links:
next page
I threw this code into the Master Page to make sure that every page knows whether or not the Session is there. Thanks for all the help everyone!
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
If Session("IB") Is Nothing Then
IBText.Visible = True
IBTextBox.Visible = True
IBTextBoxButton.Visible = True
Else
IBText.Visible = False
IBTextBox.Visible = False
IBTextBoxButton.Visible = False
lblIB.Visible = True
lblIB.Text = "Welcome, " + Session("First_Name") + " " + Session("Last_Name")
End If
End Sub

ASP.Net page methods execution time monitoring

could anybody advice me, are there any approaches to calculate the methods execution time in asp.net page?
ASP.Net Trace doesn't suit me since it ignores ajax partial postbacks though just they are the tight place.
I have the page event which for some unknown reason executes slowly. Since the logic and event execution chain is rather complicated, I still unable to merely determine the culprit in debugger.
I'd like to measure the execution time of each method throughout the page, but I still see no way but insert redundant code lines (like timeBegin = DateTime.Now.... timeEnd=DateTime.Now = timeBegin etc) in the beginning and ending of each method. It seems to be ugly approach, does anybody know how to do it automatically? Are there tools which measure the methods execution time available?
I am not 100% sure the below works in all cases. So far it does though. Note that Context.Session.Item("CURRENT_WEB_USER") is where I store the current user, and is therefore not readily available as part of the asp.net session variables.
The code hereunder is in replacement of Global.aspx that allows both full page timing and timing of developer code.
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Sub Application_AcquireRequestState(sender As Object, e As System.EventArgs)
If HttpContext.Current Is Nothing Then Return
If HttpContext.Current.Session Is Nothing Then Return
If TypeOf HttpContext.Current.CurrentHandler Is Page Then
If Not Context.Items.Contains("Request_Start_Time") Then
Dim MyPage As Page = HttpContext.Current.CurrentHandler
AddHandler MyPage.Init, AddressOf PageInitEncountered
AddHandler MyPage.Unload, AddressOf PageUnloadEncountered
Context.Items.Add("Request_Start_Time", DateTime.Now)
Dim User As String = Context.Session.Item("CURRENT_WEB_USER")
Context.Items.Add("Request_User", User )
End If
End If
End Sub
Sub Application_ReleaseRequestState(sender As Object, e As System.EventArgs)
If HttpContext.Current Is Nothing Then Return
If TypeOf Context.CurrentHandler Is Page Then
Dim Page As Page = Context.CurrentHandler
Dim StartDate As Date = Context.Items("Request_Start_Time") : If StartDate = Nothing Then Return
Dim EndDate As Date = Now
Dim StartProc As Date = Context.Items("Page_Init")
Dim EndProc As Date = Context.Items("Page_Unload")
Dim User As String = Context.Items("Request_User")
LogEntry(StartDate, EndDate, StartProc, EndProc, User, Context.Request.Url.ToString)
End If
End Sub
Public Sub PageInitEncountered(sender As Object, e As System.EventArgs)
Context.Items.Add("Page_Init", DateTime.Now)
End Sub
Public Sub PageUnloadEncountered(sender As Object, e As System.EventArgs)
Context.Items.Add("Page_Unload", DateTime.Now)
End Sub
Public Sub LogEntry(StartDate As Date, EndDate As Date, StartProc As Date, EndProc As Date, User As String, PageURL As String)
System.Diagnostics.Debug.WriteLine(" (" & LogEntry.RequestMs & " - " & LogEntry.DurationMs & ") (" & User & ") " & PageURL)
End Sub
This may not be what you are looking for, but RedGate has a product called Performance Profiler that does exactly that. They do have a 15 day trial so you can even download it and try it out on your current issue. IMHO, it's worth every penny.
You can use asp.net performance counters and other things also. But that will not measure a page speed but they will measure a over all application performance.

Resources