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!
Related
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.
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();
I'm trying to eliminate a VB.NET button on my aspx page. Trying to use javascript and ajax to execute the same code my vb had.
I put in a script manager, set EnablePageMethods to true, added a static subroutine, and referred to it in my javascript function (BTW -- this seems a lot of work just to execute an existing subroutine). The javascript calls my code-behind and it almost works.
Problem is, now I'm getting a NullReferenceException when SimulatePrintBatchClick tries to do anything with the controls.
Error is 'Object reference not set to an instance of an object', line is 'pnlVars.Controls.Clear'
Here's the code from UW.aspx:
<WebMethod()> _
Public Shared Sub PrintBatchFromJSWM()
Dim UWI As New UW
UWI.SimulatePrintBatchClick()
End Sub
Sub SimulatePrintBatchClick()
Dim Client As New LetterWriterClient
'Run ExStream and get the PDF File
Globals.PDF_Data = Nothing
Globals.PDF_Data = Client.ProcessDatFile(Session("SessionID").ToString)
'Reload the form -- turn off all controls, initialize variables and make the PDF iFrame visible
pnlVars.Controls.Clear() 'Bombs out on THIS line of code
pnlPDF.Visible = True
Me.SendToBach.Visible = False
Session.Contents("LetterVariables") = Nothing
Session.Contents("PolicyInformation") = Nothing
Session.Contents("Submitted") = True
Response.Redirect("UW.aspx")
End Sub
Funny, when I run the above code in PrintBatch_Click it all executes just fine. I really don't understand why it bombs out as a subroutine.
Perhaps this is not the way to do this, but I'm at a loss for finding a different way. Originally this code was handled by an ASP/VB button, but the specs have called for it to be deleted.
Any way I can get the above code to do it's job?
Thanks,
Jason
You cannot use any server controls in WebMethod or AjaxMethod as they are not part of Page life cycle, access these controls in Javascript.
I have an object, say Order where if an error occurs, it raises the ErrorOccurred event. If I'm running some code in say, the codebehind for a .aspx page with an public Order registered as WithEvents and I want to check to see if an error has occurred before I run more code, how do I do this? I can't simply check theOrder.ErrorOccurred. Do I have to create a local boolean flag that switches over in the event handler (OnErrorOccurred)? Or is there a better way to do this?
Thanks!
Example:
Public WithEvents theOrder As New Order
Public Sub DoStuff()
theOrder.DoSomething()
If theOrder.ErrorOccurred Then
do stuff
End If
End Sub
That seems like a reasonable approach. If there is lots of logic going on with an Order object that depends on knowing about errors, having a Status field would allow easy communication to any consumer what the status of the order was, rather than everyone having to subscribe to the event and track it themselves.
Alternately you could track it internally in the Order and just throw exceptions when critical methods were accessed if the Order was in an error state. This has the disadvantage of making you do more error handling, but would have the advantage of making sure that any Order consumer handled them explicitly.
Why not use structured error handling?
Try
'Code that may raise an error.
Catch
'Code to handle the error.
Finally
'Code to do any final clean up.
End Try
http://support.microsoft.com/kb/315965
This is what it is intended for.
Problems may arize if someone calls DoSomething but thay are unaware that they need to check theOrder.ErrorOccurred. based on what DoSomething is doing, allowing one to call a method and letting it fail quietly can be a problem.
If do something is doing logging sure, let it fail. If it is finalizing an order process..
Brian
Use the Try Catch Block
Try
'try your code here
Catch somevariablenamehere As Exception
'use methods from Exception class to get to know the error better and how to deal with it
Finally
'this is optional, If you want to do something finally, like cleaning up etc. You can do here
End Try
'to end the Try block
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).