unable to retrieve the role in asp.net with MSSQL Server - asp.net

I am working with asp.net and MSSQL server for development of online application, I like to add roles and Membership in website, membership and roles are stored in SQL Server, I tried and successes for login with SQL Users and while i change the code for restricted access for specific role the role is not listing on page.
my code for page are like below:
For Login
Dim userId As Integer = 0
Dim roles As String = String.Empty
Dim constr As String = ConfigurationManager.ConnectionStrings("InfinitudeConnectionString").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("Validate_User")
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#Username", Username.Text)
cmd.Parameters.AddWithValue("#Password", Password.Text)
cmd.Connection = con
con.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
reader.Read()
userId = Convert.ToInt32(reader("UserId"))
roles = reader("Roles").ToString()
con.Close()
End Using
con.Close()
End Using
Select Case userId
Case -1
errorText.Visible = True
errorText.Text = "Username and/or password is incorrect."
Exit Select
Case Else
Dim ticket As New FormsAuthenticationTicket(1, Username.Text, DateTime.Now, DateTime.Now.AddMinutes(1), True, roles,
FormsAuthentication.FormsCookiePath)
Dim hash As String = FormsAuthentication.Encrypt(ticket)
Dim cookie As New HttpCookie(FormsAuthentication.FormsCookieName, hash)
If ticket.IsPersistent Then
cookie.Expires = ticket.Expiration
End If
Response.Cookies.Add(cookie)
Session("login") = Username.Text
Response.Redirect(FormsAuthentication.GetRedirectUrl(Username.Text, True))
Exit Select
End Select
After that Master Page for Code :
Page Load
If Not Me.Page.User.Identity.IsAuthenticated Then
Response.Redirect(FormsAuthentication.LoginUrl)
ElseIf Session("login") = Nothing Then
FormsAuthentication.SignOut()
Session.Abandon()
Session.RemoveAll()
FormsAuthentication.RedirectToLoginPage("~/default")
Else
Using con As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("InfinitudeConnectionString").ConnectionString)
Using cmd As SqlCommand = New SqlCommand
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = "select hashtable.Username, lastlogin, hashtable.HASHid, hashtable.compID, company_list.Company_Name from hashtable inner join company_list on company_list.CompanyID = hashtable.CompID where hashtable.username = '" + Session("login") + "'"
Dim dt As New DataTable()
con.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
dt.Load(reader)
userID.Text = "Welcome Mr. " + dt.Rows(0).Item("Username").ToString.Trim()
LastLogin.Text = dt.Rows(0).Item("lastlogin").ToString.Trim()
Session("Companydetl") = dt.Rows(0).Item("compID").ToString.Trim()
Session("lastused") = dt.Rows(0).Item("HASHid").ToString.Trim()
con.Close()
End Using
End Using
End If
Global.ASAX
Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
If HttpContext.Current.User IsNot Nothing Then
If HttpContext.Current.User.Identity.IsAuthenticated Then
If TypeOf HttpContext.Current.User.Identity Is FormsIdentity Then
Dim id As FormsIdentity = DirectCast(HttpContext.Current.User.Identity, FormsIdentity)
Dim ticket As FormsAuthenticationTicket = id.Ticket
Dim userData As String = ticket.UserData
Dim roles As String() = userData.Split(",")
HttpContext.Current.User = New GenericPrincipal(id, roles)
End If
End If
End If
End Sub
when I run below code the menu is not visible.
<% if (HttpContext.Current.User.IsInRole("Atul")) Then %>
Update Company Details
<% end if %>
and when I try to know the role of the current user it display blank.
please help

First up, you should always use parameters WHEN dealing with user input. You can get away using string concatenation for internal code, but when input comes from the web page, you REALLY want to use parameters.
So, for example, your code snip should be this:
Also, note that a sql command object has a connection, has a reader.
So LITTLE need to code over and over a seperate conneciton object and a reader - you do NOT need those - they eixst as part of the sqlcommand object.
eg this:
Dim strSQL As String
strSQL = "select hashtable.Username, lastlogin, hashtable.HASHid, hashtable.compID, company_list.Company_Name from hashtable " &
"inner join company_list on company_list.CompanyID = hashtable.CompID " &
"WHERE hashtable.username = #Login"
Using cmd As SqlCommand = New SqlCommand(strSQL,
New SqlConnection(ConfigurationManager.ConnectionStrings("InfinitudeConnectionString").ConnectionString))
cmd.Parameters.Add("#Login", SqlDbType.NVarChar).Value = Session("login")
Dim dt As New DataTable()
cmd.Connection.Open()
dt.Load(cmd.ExecuteReader)
With dt.Rows(0)
userID.Text = "Welcome Mr. " + .Item("Username")
LastLogin.Text = .Item("lastlogin")
Session("Companydetl") = .Item("compID")
Session("lastused") = .Item("HASHid")
End With
End Using
So, note how I don't need a separate connection object, and I don't need a reader (they already exist as part of the sql command object. So, just trying to save your keyboard here!!
Next up:
To test/check for role membership? If you setup security tables correctly, then you should have something like this:
You REALLY want to ensure that your tables follow the standard asp.net security.
Now in above, my main contact table is custom, but the rest of the tables are the standard ones required and generated by running the sql scripts to setup security. The REASON why this is a HUGE deal? Then you can secuire ANY web page by simply dropping in and haveing a web.config file in any sub folder, and thus you can secure any web page AUTOMATIC without code based on the users role.
So, you can say use this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<authorization>
<allow roles="PortalMaster" />
<deny users="*" />
</authorization>
</system.web>
</configuration>
So now, any user to use any page in that sub folder with the above web config? They MUST be a member of PortalMaster - they can't even load that page if they try to - no code required.
And if you done this correct, to test for role membership, then you can and should use this:
If Roles.IsUserInRole("PortalMaster") then
' code goes here for user role = PortalMaster
End if
So you can and should be able to use Roles.IsUserInRole("some role name")
Dim roles As String() = userData.Split(",")
Above is a bad idea - the roles need to come from the Web_usersInRoles table.
If you need to display all roles for a given user, then you can do this:
Say we have a simple button + text box:
<br />
<asp:Button ID="Button1" runat="server" Height="34px" Text="Button" Width="170px" />
<br />
<asp:TextBox ID="TextBox1" runat="server" Height="188px" TextMode="MultiLine" Width="423px"></asp:TextBox>
The button code can be this:
For Each MyRole As String In Roles.GetRolesForUser()
TextBox1.Text &= MyRole & vbCrLf
Next
result:
And with this setup, then in say the master page, you can control/set/hide menu bar items like this:
<li id="mAdmin" runat="server" class="dropdown" ClientIDMode="Static">
so above is a menu bar - master page. With roles, we can now do this:
Me.mAdmin.Visible = Roles.IsUserInRole("SiteAdmin")
So, to run security on that site - you really - but really really really want to use and have the membership role tables setup correctly here.
So to test for membership in a role you can and should be able to use
Roles.IsUserInRole("some role name here") = true/false

Related

Incorrect Password when Password is Correct (ASP.NET VB Web Form)

I am building a login page for a website using ASP.NET and Visual Basic without Razor, as well as T-SQL. When I try to login with an existing account, I get an incorrect password message even if the password is correct.
I've tried to conduct some research on Stack Overflow and Code Project about this problem, but most people use ASP.NET Razor which is not what I am using.
Imports System.Data.SqlClient
Partial Class Login
Inherits System.Web.UI.Page
Public Sub Submit(e As Object, sender As EventArgs) Handles submitButton.Click
Dim conn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("RegistrationConnectionString").ConnectionString)
conn.Open()
Dim checkuser As String = "SELECT count(*) FROM [Table] WHERE Username='" + user.Text + "'"
Dim com As SqlCommand = New SqlCommand(checkuser, conn)
Dim temp As Integer = Convert.ToInt32(com.ExecuteScalar())
conn.Close()
If temp = 1 Then
conn.Open()
Dim checkpasswordquery As String = "SELECT password FROM [Table] WHERE Username='" + user.Text + "'"
Dim passComm As SqlCommand = New SqlCommand(checkpasswordquery, conn)
Dim password As String = passComm.ExecuteScalar().ToString()
MsgBox(password) //I have this here to test if my password matches (and my password does match)
If password = pass.Text Then
MsgBox("Login successful!")
Else
MsgBox("Incorrect password. If you would like to reset your password, please email info#maddenu.com")
End If
Else
MsgBox("Incorrect username")
End If
End Sub
End Class
I expect to get a message box telling me that the login is successful, but instead I get a message box telling me that the password is incorrect and I should email info#maddenu.com if I need a password reset.

How can I make the logged-In name the default option in dropdownlist box?

Experts.
When a user logs into one of our web apps, there is a dropdownlist containing the names of all of our employees.
An employee could log into the system to record his or her entries into the database.
The employee could log the entries for another employee.
So far, an employee has had to select his or her name from the dropdown list and we don't want employees typing their names, just for consistency and to preserve data integrity.
Our problem currently is how to have employee's login name become the default option in the dropdown. The employee can select another name from the list if making the entries for another empployee.
Any ideas how to accomplish this task?
Thanks alot in advance.
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not IsPostBack Then
Dim s As String
Dim reader As OleDbDataReader
txtFullName.Text = Session.Item("assignedTo").ToString
'Initialize Connection
s = "Select login_id, UserName from tblusers ORDER BY UserName"
Dim connStr As String = ConfigurationManager.ConnectionStrings("allstringconstrng").ConnectionString
Dim conn As New OleDbConnection(connStr)
Dim cmd As New OleDbCommand(s, conn)
'Open the connection
conn.Open()
Try
'Execute the Login command
reader = cmd.ExecuteReader()
'Populate the list of Users
txtLoginName.DataSource = reader
txtLoginName.DataValueField = "login_id"
txtLoginName.DataTextField = "UserName"
txtLoginName.DataBind()
'Close the reader
reader.Close()
Finally
'Close Connection
conn.Close()
End Try
End If
End Sub
<--new code -->
Try
'Execute the Login command
reader = cmd.ExecuteReader()
'Populate the list of Users
Dim currentUserName As String = ""
While reader.Read()
If (reader("login_id").ToString().Equals(currentUserName)) Then
currentUserName = reader("UserName").ToString()
End If
End While
txtLoginName.SelectedValue = currentUserName
'Close the reader
reader.Close()
Finally
'Close Connection
conn.Close()
End Try
you can use Page.User property to get the Name and then assign it to the dropdown's selected Value on Page_Load event.
Could you just simply select it by text after you populate the list? I assume you'll know the login_id once the user logs in, so you could find the username from the results of the query, like so:
UNTESTED:
string currentUserName = "";
While reader.Read()
If (reader("login_id").ToString().Equals(currentUserLogin)) Then
currentUserName = reader("UserName").ToString()
End If
End While
And then, once the list is populated via the results, select the correct user by username.
txtLoginName.Items.FindByValue(UserName).Selected = true;
Or even better yet, since you should already know the login_id, you can simply select by value from the populated drop down list, like so:
txtLoginName.SelectedValue = login_id
It's worth noting that this is making a very big assumption that the login_id will exist in the list. You may want to perform the appropriate check first to see if the login_id exists before selecting.
If you are using forms or windows authentication, wouldn't you just use:
txtLoginName.Text = User.Identity.Name
I believe this will select it if the text is in the list and matches exactly. Or, just use Sam's method. But was it the User.Identity.Name that you were looking for?

Using 2 databases for Session information in ASP.NET [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
This post was originally trying to find the problem, which I thought was a web.config issue. I also thought it was something in the code behind of my master page. All the text up here is part of the process of finding out the problem, scroll to the bottom for the most recent updates.
My website allows users to type a code into a textbox. If a recognized code is entered, the page will refresh and display a welcome message to that user, otherwise an error message will come up. I am putting their manually entered code into a session so that their name can be pulled up. I can't get the session to stay between pages. All of my code is on the master page's vb page and I don't know what I am doing wrong.
I have been told to make sure EnableSessionState="true" but that doesn't work on master pages.
I've been told to check IIS settings, but I can't because I don't have permissions to it.
Tried SessionState cookieless="UseUri" and somehow that created a never-ending redirect loop.
I have debugged the functions and they DO return values.
The textbox DOES go away when I enter a code and the welcome message gets displayed with the user's first and last name, so I know that works.
I've checked to make sure there is no Session.Abandon code anywhere in the site.
I added a Watch to every instance of Session("IB") on the page and they are filled correctly when I enter a code into the textbox. Then when I click on a link to move to another page, the debugger stops on the very first line in my Page_Load, Dim ib As String = CType(Session.Item("IB"), String) and all of my watched IB variables immediately turn into Nothing.
Here is the code behind for the master page:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.OleDb
Partial Class MasterPage
Inherits System.Web.UI.MasterPage
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim BAccount As String = CType(Session("BAccount"), String)
If Not IsPostBack Then
If Session("BAccount") Is Nothing Then
'no such value in session state, show textbox for IB to enter code
IBText.Visible = True
IBTextBox.Visible = True
IBTextBoxButton.Visible = True
lbNotIB.Visible = False
Else
'call function
GetSessionValues(BAccount)
End If
End If
End Sub
Protected Function GetSessionValues(ByVal Code As String) As Boolean
Dim FirstName As String = CType(Session("First_Name"), String)
Dim LastName As String = CType(Session("Last_Name"), String)
Dim Name As String = CType(Session("Name"), String)
If GetAccountName(FirstName, LastName) Then
'hide textbox
IBText.Visible = False
IBTextBox.Visible = False
IBTextBoxButton.Visible = False
'show welcome message to user if IB code exists in database
lblIB.Visible = True
lblIB.Text = "Welcome, " + Session("First_Name") + " " + Session("Last_Name") + "."
lbNotIB.Visible = True
lbNotIB.Text = "Not " + Session("First_Name") + " " + Session("Last_Name") + "?"
Return True
ElseIf GetBackUpAccountName(Name) Then
'hide textbox
IBText.Visible = False
IBTextBox.Visible = False
IBTextBoxButton.Visible = False
'show welcome message to user if IB code exists in database
lblIB.Visible = True
lblIB.Text = "Welcome, " + Session("Name") + "."
lbNotIB.Visible = True
lbNotIB.Text = "Not " + Session("Name") + "?"
Return True
Else
'IB code not found
'shows error message in red
lblIB.ForeColor = Drawing.Color.Red
lblIB.Text = "Account not found, please try again."
Return False
End If
End Function
Private Function GetAccountName(ByRef FirstName As String, ByRef LastName As String) As Boolean
'declare variable
Dim BAccount As String = CType(Session("BAccount"), String)
'sql statement for baccount information
Dim sql As String = "SELECT BAccount, First_Name, Last_Name FROM IB INNER JOIN IB_BUISNESS_INFORMATION ON (IB.IB_ID = IB_BUISNESS_INFORMATION.IB_ID) WHERE BAccount = #BAccount"
Using conn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("IBConnectionString").ConnectionString)
Using cmd As New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("#BAccount", SqlDbType.VarChar)
cmd.Parameters("#BAccount").Value = IBTextBox.Text
If IBTextBox.Text Is Nothing Then
cmd.Parameters("#BAccount").Value = DBNull.Value
Else
cmd.Parameters("#BAccount").Value = IBTextBox.Text
End If
conn.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader
If (rdr.Read) Then
FirstName = rdr("First_Name").ToString()
LastName = rdr("Last_Name").ToString()
Return True
Else
Return False
End If
End Using
conn.Close()
End Using
End Using
End Function
Private Function GetBackUpAccountName(ByRef Name As String) As Boolean
'declare variable
Dim BAccount As String = CType(Session("BAccount"), String)
'sql statement for baccount information in case BAccount is not found, search here next
Dim backupsql As String = "SELECT BAccount, Name FROM brokermaster WHERE BAccount = ?"
Using conn As New OleDbConnection(System.Configuration.ConfigurationManager.ConnectionStrings("BackUpConnectionString").ConnectionString)
Using cmd As New OleDbCommand(backupsql, conn)
cmd.Parameters.AddWithValue("?", SqlDbType.VarChar)
cmd.Parameters("?").Value = IBTextBox.Text
If IBTextBox.Text Is Nothing Then
cmd.Parameters("?").Value = DBNull.Value
Else
cmd.Parameters("?").Value = IBTextBox.Text
End If
conn.Open()
Using backuprdr As OleDbDataReader = cmd.ExecuteReader
If (backuprdr.Read) Then
Name = backuprdr("Name").ToString()
Return True
Else
Return False
End If
End Using
conn.Close()
End Using
End Using
End Function
Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
'declare variables
Dim FirstName As String = CType(Session("First_Name"), String)
Dim LastName As String = CType(Session("Last_Name"), String)
Dim Name As String = CType(Session("Name"), String)
If (Not GetSessionValues(args.Value)) Then
args.IsValid = False
Else
args.IsValid = True
End If
If GetAccountName(FirstName, LastName) Then
'set session variables
Session("First_Name") = FirstName
Session("Last_Name") = LastName
'hide textbox
IBText.Visible = False
IBTextBox.Visible = False
IBTextBoxButton.Visible = False
args.IsValid = True
'show welcome message to user if IB code exists in database
lblIB.Visible = True
lblIB.Text = "Welcome, " + Session("First_Name") + " " + Session("Last_Name") + "."
ElseIf GetBackUpAccountName(Name) Then
'set session variables
Session("Name") = Name
'hide textbox
IBText.Visible = False
IBTextBox.Visible = False
IBTextBoxButton.Visible = False
args.IsValid = True
'show welcome message to user if IB code exists in database
lblIB.Visible = True
lblIB.Text = "Welcome, " + Session("Name") + "."
Else
'IB code not found
args.IsValid = False
'shows error message in red
lblIB.ForeColor = Drawing.Color.Red
lblIB.Text = "Account not found, please try again."
End If
End Sub
Protected Sub IBTextBoxButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles IBTextBoxButton.Click
If Page.IsValid Then
'declare variables
Dim LSD As String = CType(Session("LSD"), String)
Dim LSC As String = CType(Session("LSC"), String)
Dim BAccount As String = CType(Session("BAccount"), String)
Session("BAccount") = IBTextBox.Text
'add session variable
If GetCompanyName(LSD) Then
Session("LSD") = LSD
End If
'add session variable
If GetWebsite(LSC) Then
Session("LSC") = LSC
End If
End If
End Sub
Private Function GetCompanyName(ByRef LSD As String) As Boolean
'declare variable
Dim BAccount As String = CType(Session("BAccount"), String)
'sql statement to get company information
Dim sql As String = "SELECT Company_Name, BAccount FROM IB_CONTACT_INFORMATION INNER JOIN IB_BUISNESS_INFORMATION ON (IB_CONTACT_INFORMATION.IB_ID = IB_BUISNESS_INFORMATION.IB_ID) WHERE BAccount = #BAccount"
Using conn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("IBConnectionString").ConnectionString)
Using cmd As New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("#BAccount", SqlDbType.VarChar)
cmd.Parameters("#BAccount").Value = IBTextBox.Text
If IBTextBox.Text Is Nothing Then
cmd.Parameters("#BAccount").Value = DBNull.Value
Else
cmd.Parameters("#BAccount").Value = IBTextBox.Text
End If
conn.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader
If (rdr.Read) Then
LSD = rdr("Company_Name").ToString()
Return True
Else
Return False
End If
End Using
conn.Close()
End Using
End Using
End Function
Private Function GetWebsite(ByRef LSC As String) As Boolean
'declare variable
Dim BAccount As String = CType(Session("BAccount"), String)
'sql statement for website information
Dim sql As String = "SELECT TOP 1 WebSites, BAccount FROM IB_WEBSITES INNER JOIN IB_BUISNESS_INFORMATION ON (IB_WEBSITES.IB_ID = IB_BUISNESS_INFORMATION.IB_ID) WHERE BAccount = #BAccount"
Using conn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("IBConnectionString").ConnectionString)
Using cmd As New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("#BAccount", SqlDbType.VarChar)
cmd.Parameters("#BAccount").Value = IBTextBox.Text
If IBTextBox.Text Is Nothing Then
cmd.Parameters("#BAccount").Value = DBNull.Value
Else
cmd.Parameters("#BAccount").Value = IBTextBox.Text
End If
conn.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader
If (rdr.Read) Then
LSC = rdr("WebSites").ToString()
Return True
Else
Return False
End If
End Using
conn.Close()
End Using
End Using
End Function
Protected Sub lbNotIB_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lbNotIB.Click
'if user is not IB that currently holds session, this will destroy the session and allow them to enter different code
Session.Abandon()
Response.Redirect(Request.RawUrl)
End Sub
End Class
aspx:
<asp:Label ID="IBText" runat="server" Text="Enter your IB code here:"></asp:Label>
<asp:TextBox ID="IBTextBox" runat="server"></asp:TextBox>
<asp:Button ID="IBTextBoxButton" runat="server" Text="Submit" />
<asp:CustomValidator ID="CustomValidator1" runat="server"
ControlToValidate="IBTextBox" ForeColor="Red"
OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
<asp:Label ID="lblIB" runat="server" Text=""></asp:Label>
web.config:
<sessionState mode="InProc" cookieless="false" timeout="20" sqlConnectionString="Data Source=***;Initial Catalog=***;Persist Security Info=True;User ID=***;Password=***">
</sessionState>
UPDATE:
Hah! I finally got it! So there are 2 problems here.
I did not have <httpModules> set in my web.config.
I needed to add:
<httpModules>
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
</httpModules>
Reference
Now the problem is that I have information being pulled from 2 databases for these Sessions but have only 1 database listed in the <sessionState> section of my web.config file. I tried adding a 2nd <sessionState> but it threw an error.
Is there a way to include the 2nd database?
If I don't, half of my sessions will stay throughout the website, and half will disappear. By the way, I didn't have anything to do with the database creation, this was all done way before my time.
I tried this in web.config but it also doesn't work:
<sessionState mode="InProc"
cookieless="false"
timeout="20"
sqlConnectionString="IBConnectionString, BackUpConnectionString">
</sessionState>
Yet another update:
Here's another thing I tried, suggested by a user on the asp.net forums. This generated a 500 internal server error as well, so that makes me think that having 2 instances of <sessionState> is not something that is allowed.
<sessionState mode="SQLServer"
cookieless="false"
timeout="20"
sqlConnectionString="IBConnectionString">
</sessionState>
<sessionState mode="SQLServer"
cookieless="false"
timeout="20"
sqlConnectionString="BackUpConnectionString">
</sessionState>
More:
sessionState has been changed and the site still acts like it has been, the ConnectionString must not have anything to do with the problem with the 2nd database losing it's session. It's gotta be something in the code behind, I can't think of what else could be wrong with the web.config.
<sessionState mode="InProc" timeout="20"></sessionState>
We also found out that the session variable is still there, it just won't display the user's information when it's connected to the back up database connection.
After much deliberation and frustration, I asked my boss how hard it would be to just combine the databases. Although there are more than 2400 records in the Back Up Account database, there is really no other option. I do not foresee a solution coming to me anytime soon and I have already wasted a month on this....thanks everyone for the help.
If I ever do figure something out, I will come back and edit this post!
First off, remove your code in the Init portion of the page. It is unnecssary.
Second, why are you setting the IB values of the session to True in portions of your code? It's overwriting the account number. Change both..
Session("IB") = True
to
Session("IB") = args.Value
Or just don't even mess with the session at that point..it should already be set from the IBTextBoxButton_Click Sub Routine.
Make sure session state enabled in web.config. If it is set to "StateServer" or "SQLServer", change it to "InProc" for testing purposes to rule out external failing dependencies.
<sessionState mode="InProc" />
Also, I have seen exceptions get thrown in the past that seemed to "eat" the session. Look for any try/catch blocks that might be giving you problems.
Single stepping through the code normally shows the problems, but if not, one technique I use that helps sometimes, is to litter your code with "i am here" messages.
The thinking is that sometimes it helps trigger an epiphany when you can see which line (or close to it) appears to be creating the problem.
For example, you could dump a session variable state along with an approximate line number and just output it at several spots to your web page.
You also should try to narrow down the amount of code you are debugging.
If you can isolate the problem to a smaller set of code, often this helps spot problems.
** edit **
Apparently I was just scanning. Upon actually reading your post, i see you have identified the line causing the issue. I don't see anything wrong with the line, but for some reason i want to try using a different session variable name. I don't know if that will help, but it's an easy thing to try. Maybe use a longer session variable name. Without having the debugger open in front of me, I don't know what else to check off the top of my head.

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.

How can I transfer login value to another page?

I am a newbie in using asp.net with code behind of vb.net I just wanna know on how to see the name of the admin on the POS page. it seems that this code doesn't work??
Main.lbl_name.Text = CurName.ToUpper
POS.lbl_cashier.Text = CurName.ToUpper
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cmd1 As New SqlCommand
Dim rdr As SqlDataReader
cmd1.Connection = cn
cmd1.Connection.Open()
cmd1.CommandText = "SELECT * from UserTable WHERE Username ='" & txt_username.Text & "'"
rdr = cmd1.ExecuteReader
If rdr.HasRows = True Then
rdr.Read()
If txt_username.Text = rdr.Item(0) And txt_password.Text = rdr.Item(3) Then
CurPos = rdr.Item("Type")
CurUser = rdr.Item("Username")
CurName = rdr.Item("EmployeeName")
If rdr.Item(4) = "ADMINISTRATOR" Then
MsgBox("WELCOME! " & rdr.Item(4), MsgBoxStyle.Information)
'Main.lbl_name.Text = CurName.ToUpper
'POS.lbl_cashier.Text = CurName.ToUpper
cmd1.Connection.Close()
Response.Redirect("ACESCHOOLSUPPLIES.aspx")
'Me.Dispose()
You can't just access other pages, ASP.NET runtime is ignorant about other pages, you have access to your current page only!
You can use the Session variable to store some data temporarily for current user session, the Session object is available on every ASP.NET Page.
Session("adminname") = CurName
On other page where you want to show it you just reload it from Session
Dim NewName = Session("adminname")
Take some hidden field and use session.add("username") and store your username or which ever you want and the n retrieve that from your second page.
Session.Add("Username",Username);
does essentially the same as
Session["Username"] = Username;
As Alaudo suggested, storing variables in Session state is an option.
For the sake of completeness other options you have are:
Cookies
QueryString
Hidden fields (for POST requests)
The logged on user name is something I personally would not store in Session state or pass around using any of the alternate techniques I mention above.
Looking at your code it seems you are trying to authenticate some credentials (user name/password).
I recommend you look at MemebershipProvider in ASP.NET. Are you familiar with this? You can then easily access the logged in user.

Resources