aspnet/vbnet clear label after response redirect - asp.net

I'm building an asp.net web page with vb.net code behind.
My web page is designed to display an error when the user clicks a button without filling the relevant textbox; the code below shows how this works:
If txtOrderNumber.Text = "" Then
lblStatus.Text = orderNoWarning
lblStatus.CssClass = "error"
ElseIf txtPhaseNumber.Text = "" Then
lblStatus.Text = phaseNoWarning
lblStatus.CssClass = "error"
ElseIf txtOrderNumber.Text.Length > 0 AndAlso txtPhaseNumber.Text.Length > 0 Then
Try
Dim intOrderNumber As Integer = CInt(txtOrderNumber.Text)
Try
Dim intPhaseNumber As Integer = CInt(txtPhaseNumber.Text)
Dim objWIP_Tracking As New wsWIP_Tracking.WIP_TrackingSoapClient
Dim myResults As wsWIP_Tracking.TicketType2 = objWIP_Tracking.GetTicketType2(intOrderNumber, intPhaseNumber)
If myResults = wsWIP_Tracking.TicketType2.AME Or _
myResults = wsWIP_Tracking.TicketType2.Orion Then
lblStatus.Text = ""
Response.Redirect("http://ligrptsvr2/default.aspx?Report=JoinerySummarybyComponent.rpt&username=imservices&FOLDER=Analytics&OrderNo=" & intOrderNumber.ToString & "&PhaseNo=" & intPhaseNumber.ToString & "&ParameterPrompt=yes")
ElseIf myResults = wsWIP_Tracking.TicketType2.GS Then
lblStatus.Text = ""
Response.Redirect("http://ligrptsvr2/default.aspx?Report=JoinerySummary_GreenScreen.rpt&username=wip&FOLDER=Analytics&JobNo=" & intOrderNumber.ToString & "&PhaseNo=" & intPhaseNumber.ToString & "&ParameterPrompt=yes")
ElseIf myResults <> wsWIP_Tracking.TicketType2.AME Or _
myResults <> wsWIP_Tracking.TicketType2.Orion Or _
myResults = wsWIP_Tracking.TicketType2.GS Then
lblStatus.Text = warning
lblStatus.CssClass = "warning"
Else
Response.End()
End If
Catch ex As Exception
End Try
Catch ex As Exception
End Try
Else
lblStatus.Text = ""
End If
However, when a response.redirect (redirects to new page) occurs , I would like to clear the label(lblstatus). The code 'lblstatus.text=""' does not work. When the user gets redirected to a new page then goes back (using browser back button), the label still shows an error. Iv tried disabling and enabling viewstate; doesn't make any difference. What can I do to clear this label?

Please see: What happens when I press browser BACK button?
When you press back button in a browser, most browsers will just display the cached copy of the html page in it's latest state, before the redirect happened. The functionality is totally browser dependent. Hence, your VB code or viewstate can hardly do anything.
One option is to use java-script on page load, to dynamically toggle the error message (which is what I do when I have this kind of a problem).

Related

The code for my aspx signup page does not work

Hello the following code for my signup page does not work. when I execute it, it refreshes and stays in the same page. But it is supposed to redirect to a page called message.aspx. The register command works as follows the person trying to register writes in comboboxs their information and then once they finished, they click the button begin which will save all their information and then use it to personalize the message.aspx page and the person will receive an email.
here is the code:
Private Sub cmdRegister_Click(sender As Object, e As System.EventArgs) Handles cmdRegister.Click
Dim status As MembershipCreateStatus
Dim organization As New Org
Dim employee As New Employee
Dim description As New Description(25)
Dim userMembership As MembershipUser
Dim stringBuilder As New StringBuilder
Try
Membership.CreateUser( _
txtUserName.Text, _
txtPassword.Text, _
txtEmail.Text, _
"question", _
"answer", _
True, _
status)
If status.ToString = "Success" Then
organization.GSTRate = 1
organization.QSTRate = 1
organization.AccountStatus = 2
organization.Name = txtOrg.Text
organization.Active = 1
organization.OrgTypeID = cboType.SelectedValue
organization.Create()
organization = Nothing
organization = New Org(txtOrg.Text)
employee.Username = txtUserName.Text
employee.OrgID = organization.ID
employee.FirstName = txtFName.Text
employee.LastName = txtLName.Text
employee.Title = txtTitle.Text
employee.Username = txtUserName.Text
employee.IsAdmin = True
employee.IsSupervisor = True
employee.IsAccountant = False
employee.IsAdvalorem = True
employee.Email = txtEmail.Text
employee.Phone = ""
employee.Create()
Roles.AddUserToRole(employee.Username, "Admin")
userMembership = Membership.GetUser(txtUserName.Text)
stringBuilder.Append(description.EnglishDescription)
stringBuilder.Replace("(name)", employee.FirstName & " " & employee.LastName)
stringBuilder.Replace("(OrgName)", organization.Name)
stringBuilder.Replace("(username)", employee.Username)
stringBuilder.Replace("you must activate your account", "you must <a href='https://www.advataxes.ca/login.aspx?action=activate&id=" + userMembership.ProviderUserKey.ToString + "&username=" + userMembership.UserName + "'>activate your account</a>")
SendEmail(userMembership.Email, "Advataxes: Account created ", stringBuilder.ToString, Session("language"))
Session("NewUserEmail") = userMembership.Email
Response.Redirect("message.aspx?id=364")
Else
lblInvalidUserName.Visible = True
If status.ToString = "DuplicateUserName" Then lblInvalidUserName.Text = "Username already exists"
End If
Catch ex As MembershipCreateUserException
MsgBox(GetErrorMessage(ex.StatusCode))
Catch ex As HttpException
MsgBox(ex.Message)
Finally
userMembership = Nothing
organization = Nothing
employee = Nothing
description = Nothing
End Try
End Sub
Looking at your code, I suspect the code execution is not successfully reaching the Response.Redirect("message.aspx?id=364") line and due to an exception the flow jumps to catch block/
Two possibilities I can think of:
Exception is thrown inside SendEmail method if smtp is not configured
Membership.CreateUser is failing due to incorrect database connectionstring
I suggest you put a breakpoint inside the cmdRegister_Click method and step through the code.

Error when accessing cookies when a cookies without a name exists

On a few of the Classic ASP websites I manage for the last few days I have been getting some error notifications (with no error number) that always show an error on a line number where a cookie value is being requested.
Looking at the request for each of these errors, they all have unusual cookies, and look like some sort of hack attempt.
The lines that are indicated as causing the error are all like this:
strCookieCart = Request.Cookies("cart")
Here's a couple of samples of the cookies being sent (truncated)... Note the =true (no name, just a value).
HTTP_COOKIE:=true; yuv=u97Yoe-o0UWp7ho_vaB2csT-xxaQ37gMWzhB1MARTSNk1QKpjJTXmZYMRQ095rM96MaNbhx1tEdJ
HTTP_COOKIE:pll_language=en; =true; yandexuid=6536735381437958890; st=6c9838994ffb
Is Classic ASP incapable of handling these? Is there any way to avoid these errors and ignore the bad values? Are these always likely to be hack attempts or could there be legitimate requests without cookie names?
I suppose I could check for these looking at Request.ServerVariables("HTTP_COOKIE") by manually parsing or using a regular expression check of some sort. Does anyone else do this? Any code to share?
A second answer to my own question and the solution I have now implemented is to add the following code to my common include file.
It tests whether Classic ASP can read the cookies and, using error trapping, ends the response if an error is detected.
On Error Resume Next
Request.Cookies("test")
If Err.Number <> 0 Then Response.End
On Error Goto 0
This is a better solution to my other answer as there is no point in generating a page for what is obviously an attack of some sort so ending the script as soon as possible is a better choice.
My proposed answer to my own question is to create a class that extracts all the valid keys and values for the cookies on initialisation, and has a function to return a value for a specified key.
Unfortunately it doesn't work for cookies that contain a collection of multiple values, but I don't generally use these anyway.
Here is the class:
<%
Class MyRequest
Private m_objCookies
Private Sub Class_Initialize()
Dim strCookies, i, strChar, strName, strValue, blnInValue
strCookies = Request.ServerVariables("HTTP_COOKIE")
Set m_objCookies = Server.CreateObject("Scripting.Dictionary")
i = 1
strName = ""
strValue = ""
blnInValue = False
Do
strChar = Mid(strCookies, i, 1)
If strChar = ";" Or i = Len(strCookies) Then
strValue = Trim(strValue)
If strName <> "" And strValue <> "" Then
If m_objCookies.Exists(strName) Then
m_objCookies.Item(strName) = strValue
Else
m_objCookies.Add strName, strValue
End If
End If
If i = Len(strCookies) Then Exit Do
strName = ""
strValue = ""
blnInValue = False
ElseIf strChar = "=" Then
strName = Trim(strName)
blnInValue = True
ElseIf blnInValue Then
strValue = strValue & strChar
Else
strName = strName & strChar
End If
i = i + 1
Loop
End Sub
Public Function Cookies(strKey)
Cookies = m_objCookies.Item(strKey)
End Function
End Class
%>
The changes to my code to use this class are minimal. Where I currently have...
strCookieCart = Request.Cookies("cart")
I will need to change to...
Dim objMyRequest : Set objMyRequest = New MyRequest
strCookieCart = objMyRequest.Cookies("cart")
I have tested the above with many of the bad requests I have logged and it works fine.
Add three line codes for #johna is answer, after this line:
If strChar = ";" Or i = Len(strCookies) Then
add these lines:
If i = Len(strCookies) And strChar <> ";" Then
strValue = strValue & strChar
End If

ASP.NET/VB Reading/Writing Cookies - Object not set to instance of an object

so I have this code:
Try
If Request.Cookies("curUsrId")("id") Is Nothing Then
Dim cke As HttpCookie = New HttpCookie("curUsrId")
cke("id") = CStr(myUser.Id)
cke.Expires = Now.AddDays(35)
Response.Cookies.Add(cke)
Else
If Request.Cookies("curUsrId")("id") = "2" Then
grdIssues.SettingsPager.Mode = DevExpress.Web.ASPxGridView.GridViewPagerMode.ShowAllRecords
chkPaging.Checked = True
Else
grdIssues.SettingsPager.Mode = DevExpress.Web.ASPxGridView.GridViewPagerMode.ShowPager
chkPaging.Checked = False
End If
End If
Catch ex As Exception
lblErrorMsg.Visible = True
txtErrorTxt.Visible = True
txtErrorTxt.Text = ex.Message
End Try
I'm trying to read/write to a cookie, but everytime I run this, I get a "Object not set to an instance of an object" error.
Does anyone know why?
I changed the code slighty, still the same error? Per the comment below, I do check to see if the value is nothing.
Try
If Request.Cookies("curUsrId").Value Is Nothing Then
Dim cke As HttpCookie = New HttpCookie("curUsrId")
cke.Value = CStr(myUser.Id)
cke.Expires = Now.AddDays(35)
Response.Cookies.Add(cke)
Else
If Request.Cookies("curUsrId").Value = "2" Then
grdIssues.SettingsPager.Mode = DevExpress.Web.ASPxGridView.GridViewPagerMode.ShowAllRecords
chkPaging.Checked = True
Else
grdIssues.SettingsPager.Mode = DevExpress.Web.ASPxGridView.GridViewPagerMode.ShowPager
chkPaging.Checked = False
End If
End If
Catch ex As Exception
lblErrorMsg.Visible = True
txtErrorTxt.Visible = True
txtErrorTxt.Text = ex.Message
End Try
ANOTHER EDIT:
I added a breakpoint at the Try line, guess, what it doesn't hit. "No symbol information loaded etc". I tried loading the DLL manually, I've rebuilt the solution etc, no difference?
You are getting this exception because you are trying to read value of
a cookie which does not exist in cookies collection.
If Request.Cookies("curUsrId").Value //Here you are trying to read value from cookie wich is not set yet
Try this for C#
if(Request.Cookies.Get("curUsrId")==null)
{
//Your code to add cookie
}
In VB.Net
If Request.Cookies.Get("curUserId") Is Nothing Then

Session is showing nothing in homepage (asp.net)

I'm trying to set session in asp.net app.
Have set Session("username")=txtusername.text
in click event of login button and on home page after successful login trying to access the Session("username") on page_load but it's getting back to login page as there is nothing in Session("Username").
Can any one help me possible cause as this suddenly started happening.
==========Login page==============
Session("SrNo") = sqlReader.Item(0)
ViewState("Username") = sqlReader.Item(3)
Session("Name") = sqlReader.Item(1) + " " + sqlReader.Item(2)
Session("Mobile") = sqlReader.Item(5)
Session("Email") = sqlReader.Item(6)
Session("UserType") = sqlReader.Item(7)
' Session.Timeout = "600000"
Response.Redirect("welcome.aspx", True)
'Server.Transfer("Welcome.aspx")
End If
End If
=============Welcome page===================
Dim string1 As String
string1 = Session("Username")
If Session("SrNo") = Nothing Then
Response.Redirect("Login.aspx")
Else
//my codes
endif

How to determine if a user is in a security group?

I am using the code below to get the user groups but I am not sure how to code it to say that if the user is in "TestGroup" do something if not redirect the page?
Dim resEnt As SearchResult
Try
For Each resEnt In mySearcher.FindAll()
LabelUser.Text = resEnt.GetDirectoryEntry.Properties.Item("DisplayName").Value
LabelLocation.Text = resEnt.GetDirectoryEntry.Properties.Item("SystemUserLocation").Value
LabelState.Text = resEnt.GetDirectoryEntry.Properties.Item("st").Value
LabelCountry.Text = resEnt.GetDirectoryEntry.Properties.Item("c").Value
Dim result As SearchResult = mySearcher.FindOne()
If (result Is Nothing) Then
Else
Dim groupColl As Object
For Each groupColl In resEnt.Properties("memberof")
Dim GroupArray As Array = groupColl.split(",")
Select Case GroupArray(0).replace("CN=", "")
Case "TestGroup"
'Continue loading page
Case Else
'Prevent page from loading????
End Select
Next groupColl
End If
Next
Catch f As Exception
Console.WriteLine(f.ToString)
End Try

Resources