Session is showing nothing in homepage (asp.net) - 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

Related

vb Redirect to new page after 5 sec. delay

Example below is not working to delay a page redirect after 5 sec. - The Header update doesn't seem to work. Is there a pure VB solution for is the header the only way to go? Thought of just running a timer to delay next line of execution?
Tried commented out section as well - still didn't fire the header change.
Dim TF As String = ResetNewPassword(uName, pAnwser, newPassword)
Dim dateUpdated As Boolean = UpdateLastLoginDate(uName)
If TF Then
uEmail = u.Email
Label2.Text = "Users password has been updated"
Training.xMail(uEmail, Label2.Text, "Password Changed")
Response.AppendHeader("REFRESH", "5;URL=Default.aspx")
'Dim meta As New HtmlMeta()
'meta.HttpEquiv = "Refresh"
'meta.Content = "5;url=Page2.aspx"
'Me.Page.Controls.Add(meta)
PassQuestion1.Text = "You will now be redirected in 5 seconds"
Else
Label2.Text = "Users password failed to update please try again!!!"
Training.Mail("mail_user_acct", Label2.Text, "Password Failed - resetPassword")
End If

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.

after logout from users account all page shows error

I have vb.net web application in which if users are logged in than all other pages working fine but the time I log out from account than it gets error in all pages. I know the page getting values from cookies but if cookies is empty then it's getting null & so cause the error page
Error : System.NullReferenceException: Object reference not set to an instance of an object.
VB Code for any pageload
Dim var, Type As String
var = Server.HtmlEncode(Request.Cookies("chkusername").Value)
Type = Server.HtmlEncode(Request.Cookies("User_Type").Value)
Dim LogIn, LogOut, listup As Control
Dim BtnProfile As Button = Page.Master.FindControl("myAccount")
LogIn = Master.FindControl("login")
LogOut = Master.FindControl("logout")
listup = Master.FindControl("list")
'not login
If HttpContext.Current.Request.Cookies("chkusername") Is Nothing Then
listup.Visible = True
LogIn.Visible = True
LogOut.Visible = False
BtnProfile.Visible = False
'login
Else
LogOut.Visible = True
BtnProfile.Visible = True
LogIn.Visible = False
listup.Visible = False
End If
Login Page code
Dim User, Pass As String
If selectbusinesstype.SelectedValue.ToString = "0" Then
Response.Write("<script language='javascript'>alert('Select login type first');</script>")
ElseIf selectbusinesstype.SelectedValue = "Hospitals" Then
Try
If loginId.Text <> "" And password.Text <> "" Then
Dim str As String = "select * from hospitals where username='" + loginId.Text + "' and Password='" + password.Text + "';"
Dim cmd As New MySqlCommand(str, con)
con.Open()
Dim da As New MySqlDataAdapter(cmd)
Dim ds As New DataSet
da.Fill(ds)
con.Close()
User = ds.Tables(0).Rows(0)("username")
Pass = ds.Tables(0).Rows(0)("password")
If ds.Tables(0).Rows.Count > 0 Then
If User = loginId.Text.ToString And Pass = password.Text.ToString Then
Response.Cookies("User_Type").Value = "Hospitals"
Response.Cookies("chkusername").Value = loginId.Text
Response.Redirect("hospital-profile.aspx?user=" + Request.Cookies("chkusername").Value)
Else
Response.Write("<script language='javascript'>alert('User name or password is invalid');</script>")
End If
Else
Response.Write("<script language='javascript'>alert('User name or password is invalid');</script>")
End If
Else
Response.Write("<script language='javascript'>alert('Enter All the Details');</script>")
End If
Catch ex As Exception
Response.Write("<br /><br /><br /><br /><br />")
Response.Write(ex)
con.Close()
End Try
You have below lines,
Dim var, Type As String
var = Server.HtmlEncode(Request.Cookies("chkusername").Value)
Type = Server.HtmlEncode(Request.Cookies("User_Type").Value)
Convert it to,
Dim var, Type As String
If not HttpContext.Current.Request.Cookies("chkusername") Is Nothing Then
var = Server.HtmlEncode(Request.Cookies("chkusername").Value)
End If
If not HttpContext.Current.Request.Cookies("User_Type") Is Nothing Then
Type = Server.HtmlEncode(Request.Cookies("User_Type").Value)
End If

aspnet/vbnet clear label after response redirect

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).

how to allow admin and customer to login in at same place but direct to other page after click button?

i have 2 textbox for name and password and a button
there 2 table, one admin and one customer
after i enter the customer name and password , it verify whether empty or incorrect password , if correct it will go to the customer page
however if i enter admin name and password and after verify it should go to the admin page
i am only able to allow use one table for the login ? so how should i change the code below?
Protected Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
If String.IsNullOrEmpty(txtName.Text) Or String.IsNullOrEmpty(txtPassword.Text) Then
Failure.Text = "Invalid User Name and Password. Try Again."
Exit Sub
End If
Dim connectionString = ConfigurationManager.ConnectionStrings("MYdatabase").ConnectionString
Dim myConn As New SqlConnection(connectionString)
Dim cmd = "Select * From Customer where name = #name"
Dim my As New SqlCommand(cmd, myConn)
my.Parameters.AddWithValue("#name", txtName.Text)
Dim objReader As SqlDataReader
myConn.Open()
objReader = myCmd.ExecuteReader()
FailureText.Text = " "
If objReader.Read() Then
Dim pass As String = objReader.GetString(2)
Dim cusId As Integer = objReader.GetValue(0)
If pass = txtPassword.Text Then
Failure.Text = "Login Successful"
Session("name") = txtName.Text
Session("Password") = txtPassword.Text
Session("customerID") = cusId
my.Dispose()
myConn.Dispose()
Response.Redirect("CustomerHome.aspx")
Else
FailureText.Text = "Invalid Password"
End If
Else
FailureText.Text = "Login Name does not exist"
End If
End Sub
You can repeat the same process that you use to validate if the user is a customer, for validating if it's an administrator.
Where you put: FailureText.Text = "Login Name does not exist" you can repeat the code from above and first validate if the supplied username and password map to an administrator. If so, set the session for an Admin and redirect to the admin page. If not, show the failure text.
To make sure your code stays readable, I would split the validate function into multiple functions that are called from the main function(refactoring). So you would get functions like: IsValidCustomer and IsValidAdministrator that do there checking.

Resources