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.
Related
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
I am trying to send some variables, using a session, to the next page "ProcedureSelectionForm.aspx". As you can see, the sessions have been commented out. The code below will work (without sending the variable of course). However, when you remove the comments the .onclick function reloads the page rather than navigating to "ProcedureSelectionForm.aspx". For this reason, I believe this is where my problem is. The first two columns are "Account" and "Password" in the database. I have not misspelled anything. I am new to VB and ASP.net and would appreciate some explanation as to what is happening and why my desired functionality isn't materializing. Thank you for your help!
If IsValid Then
Try
Dim strSQL = "select * from CreatePatient where Account = #Account and Password = #Password"
Using CCSQL = New SqlConnection(ConfigurationManager.ConnectionStrings("CreatePatientConnectionString").ConnectionString)
Using CCUser = New SqlCommand(strSQL, CCSQL)
CCSQL.Open()
CCUser.Parameters.Add("#Account", Data.SqlDbType.VarChar).Value = PatientAccount.Text
CCUser.Parameters.Add("#Password", Data.SqlDbType.VarChar).Value = PatientPass.Text
CCUser.ExecuteNonQuery()
'Using reader As SqlDataReader = CCUser.ExecuteReader()
'If reader.HasRows Then
'reader.Read()
'Session("user") = reader("Account")
'Session("pass") = reader("Password")
Response.Redirect("ProcedureSelectionForm.aspx")
'End If
'End Using
End Using
End Using
Catch ex As Exception
Label1.Text = ex.Message
End Try
End If
My friend was able to make time to help me out. I am unsure of what he did differently besides closing connections
If IsValid Then
Dim CCSQL As New SqlConnection
Dim CCUser As New SqlCommand
Dim strSQL As String
Dim dtrUser As SqlDataReader
Try
CCSQL.ConnectionString = ConfigurationManager.ConnectionStrings("CreatePatientConnectionString").ConnectionString
strSQL = "Select * from CreatePatient where Account=#user and Password=#pwd"
CCUser.CommandType = Data.CommandType.Text
CCUser.CommandText = strSQL
CCUser.Parameters.Add("#user", Data.SqlDbType.VarChar).Value = PatientAccount.Text
CCUser.Parameters.Add("#pwd", Data.SqlDbType.VarChar).Value = PatientPass.Text
CCSQL.Open()
CCUser.Connection = CCSQL
dtrUser = CCUser.ExecuteReader()
If dtrUser.HasRows Then
dtrUser.Read()
Session("user") = dtrUser("Account")
Session("level") = dtrUser("Password")
Response.Redirect("ProcedureSelectionForm.aspx")
Else
Label1.Text = "Please check your user name and password"
End If
dtrUser.Close()
CCSQL.Close()
Catch ex As Exception
Label1.Text = ex.Message
End Try
End If
I am on a tight deadline but i will get back to those interested with an answer. Thank you for your effort.
You don't want to do .ExecuteNonQuery() when you are actually doing a query (i.e. a SQL "SELECT" statement. You can just do the .ExecuteReader() to read those two values.
Also, I presume you are trying to validate the Account and Password; otherwise you could just set Session("user") = PatientAccount.Text and set Session("pass") = PatientPass.Text.
I am working on a site thath has to also support Danish characters (the supported languages will increase in the future).
I am using a database table - lets call it Strings - where I create a record for each string I display on my site. For example, the greeting message in the login page is entered in the database like this:
ID | Description | Text | Lang_code
1 | login | Log In | en
This is the code that pulls the lang_code from the database:
Public Shared Function GetLanguageCodeFromBrowser()
Dim language_code As String
Dim databaseConnection As New DBConnectionAdapter
Dim DataReader, DataReader1 As MySqlDataReader
Dim serverVar As String = HttpContext.Current.Request.ServerVariables("HTTP_ACCEPT_LANGUAGE")
language_code = LCase(serverVar)
Dim Query As String = "SELECT language_code FROM languages WHERE language_code = '" & LCase(language_code) & "' AND disabled = 0"
Dim Query1 As String = "SELECT language_code FROM languages WHERE language_code = '" & LCase(Left(language_code, 2)) & "' AND disabled = 0"
Dim cmdSelect As New MySqlCommand(Query, databaseConnection.connectionWebServices)
Dim cmdSelect1 As New MySqlCommand(Query1, databaseConnection.connectionWebServices)
Try
databaseConnection.OpenWebServices()
DataReader = cmdSelect.ExecuteReader
If Not DataReader.Read Then
DataReader.Dispose()
DataReader1 = cmdSelect1.ExecuteReader
If Not DataReader1.Read Then
DataReader1.Dispose()
Return language_code = "en"
Else
Return DataReader1("language_code")
End If
DataReader1 = Nothing
DataReader1.Dispose()
Else
Return DataReader("language_code")
End If
DataReader = Nothing
DataReader.Dispose()
Catch ex As Exception
' TODO Error handling
HttpContext.Current.Response.Write(ex.Message)
Finally
databaseConnection.CloseWebServices()
End Try
databaseConnection = Nothing
End Function
And I use it in the MasterPage's Page_Init event like this:
Session("language_code") = Language_from_Browser.GetLanguageCodeFromBrowser
Everything works fine in English, but when it comes to Danish, some characters are mangled.
I have tried changing this in web.config:
<globalization
fileEncoding="ISO-8859-1"
requestEncoding="ISO-8859-1"
responseEncoding="ISO-8859-1"
culture="auto"
/>
Still not working properly.
Please note that I have a default.aspx page in each one of my folders, so I dont have to bother with URL rewriting (that's how I see it a least)
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?
I'm trying to update a record from an Ms-Access table with VB.NET and ASP.NET. I'm getting 2 errors:
On the web page that's opened I'm getting Thread was being aborted
Web Developer 2010 gives me an error says there's an error in the
UPDATE statement
This is the code so far:
Imports System.Data.OleDb
Partial Class ChangePassword
Inherits System.Web.UI.Page
Protected Sub btnChange_Click(sender As Object, e As System.EventArgs) Handles btnChange.Click
Dim tUserID As String = Session("UserID")
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Brian\Documents\Visual Studio 2010\WebSites\WebSite3\db.mdb;")
conn.Open()
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [User] where UserID=?", conn)
Dim cmd2 = New OleDbCommand("UPDATE USER SET [Password] = '" + txtConfPass.Text + "' where UserID = '" + tUserID + "'", conn)
cmd.Parameters.AddWithValue("#UserID", tUserID)
Dim read As OleDbDataReader = cmd.ExecuteReader()
Dim read2 As OleDbDataReader = cmd2.ExecuteReader()
lblUser.Text = tUserID.ToString
lblUser.Visible = True
If read.HasRows Then
While read.Read()
If txtOldPass.Text = read.Item("Password").ToString Then
cmd2.ExecuteNonQuery()
lblPass.Visible = True
End If
End While
Else
lblPass.Text = "Invalid Password."
lblPass.Visible = True
End If
conn.Close()
lblPass.Text = tUserID.ToString
lblPass.Visible = True
Any help would be appreciated.
Thanks !
First, your cmd2 fails because USER is a reserved word. Enclose in
square brackets as you already do in the first OleDbCommand.
Second, to execute a statement like UPDATE, INSERT, DELETE you call
cmd2.ExecuteNonQuery not ExecuteReader. Don't really needed that call
after the first for cmd.
Third, in the first OleDbCommand (cmd) you use a parameter for
UserID, why in the second one you revert to string concatenation for
user and password? This opens the door to any kind of Sql Injection
Attack.
Fourth, the Using statement assure that every Disposable object
used in your code will be CLOSED thus freeing the memory used by
this commands ALSO IN CASE OF EXCEPTIONS. An example of Using
statement here
(1)
Dim read2 As OleDbDataReader = cmd2.ExecuteReader()
and then
(2)
cmd2.ExecuteNonQuery()
Remove (1) - ExecuteNonQuery should do the update.
USER is a keyword in Access, add brackets the same way you have added in the Select statement. Next time, you are faced with a similar problem, print out the statement as Access would see it and try executing it on the database directly - that will point out the errors accurately.
Please use place holders for the update statement similar to the select statement.