| | |
Login and retrieve user data from database
Please support our ASP.NET advertiser: $4.95 a Month - ASP.NET Web Hosting – Click Here!
![]() |
•
•
Join Date: Nov 2005
Posts: 4
Reputation:
Solved Threads: 1
Hi, I'm using asp.net together with vb.net. I am trying to develop:
1. a login page in asp.net, once user enter the correct username and password, this will be directed to the User page.
2. In User page, there will be some text fields of the user (eg. name and address), all these suppose to retrieve from SQL Server. In here, if the username is found in the database, his/her data will be displayed in the textboxes ( eg. name and address), if not, the textboxes remain empty. User can choose to edit or enter new data into the textboxes and submit back to the datadase.
3. Once updated, user can click "save and logout" to save the data and logout.
I've done the login part, but only in (2), I can't retrieve the user's data from databases based on User.Identity.Name. Any idea how to retrieve data based on user's username?
Thanks.
1. a login page in asp.net, once user enter the correct username and password, this will be directed to the User page.
2. In User page, there will be some text fields of the user (eg. name and address), all these suppose to retrieve from SQL Server. In here, if the username is found in the database, his/her data will be displayed in the textboxes ( eg. name and address), if not, the textboxes remain empty. User can choose to edit or enter new data into the textboxes and submit back to the datadase.
3. Once updated, user can click "save and logout" to save the data and logout.
I've done the login part, but only in (2), I can't retrieve the user's data from databases based on User.Identity.Name. Any idea how to retrieve data based on user's username?
Thanks.
•
•
Join Date: Nov 2005
Posts: 4
Reputation:
Solved Threads: 1
The scenario:
At Login.aspx, user will enter username and password to login, this works perfectly, authenticating against database in SQL Server.
Here's the code:
Login.aspx
Login.aspx.vb
Once successfully logged in, user will be directed to this page "Success.aspx", and the page should be able to retrieve the user's details from the database, in this case the password of the user is to be displayed. However, my program can't retrieve and display the user's password in the textbox/label. Note: connectionstring is stored in web.config.
Some of the SQL is stored in the stored procedures.
Successful.aspx
Success.aspx.vb
UsersDB.vb
EncryptionUtil.vb
As from above, encryption is not necessary, as I will eventually replace the data to be displayed as normal data, instead of displaying the password.
Need help in retrieving the user's data from database and display on the form, user can edit and update and resubmit back to the database.
At Login.aspx, user will enter username and password to login, this works perfectly, authenticating against database in SQL Server.
Here's the code:
Login.aspx
ASP.NET Syntax (Toggle Plain Text)
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="Login.aspx.vb" Inherits="LoginTest.Login"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <title>Login - Login Test</title> <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0"> <meta name="CODE_LANGUAGE" content="Visual Basic 7.0"> <meta name="vs_defaultClientScript" content="JavaScript"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> </HEAD> <body> <form Runat="Server" ID="Form1"> <h2>Please Login:</h2> <asp:Label ID="lblMessage" ForeColor="Red" Font-Bold="True" Runat="Server" /> <p> <b>Username:</b> <br> <asp:TextBox ID="txtUsername" Runat="Server" /> <asp:RequiredFieldValidator ControlToValidate="txtUsername" Text="Required!" Runat="Server" ID="Requiredfieldvalidator1" /> <p> <b>Password:</b> <br> <asp:TextBox ID="txtPassword" Runat="Server" TextMode="Password" /> <asp:RequiredFieldValidator ControlToValidate="txtPassword" Text="Required!" Runat="Server" ID="Requiredfieldvalidator2" /> <p> <asp:Button Text="Login!" OnClick="Button_Click" Runat="Server" ID="Button1" /> <hr> </form> </body> </HTML>
Login.aspx.vb
ASP.NET Syntax (Toggle Plain Text)
Imports System Imports System.IO Imports System.Web Imports System.Data.SqlClient Imports System.Collections Imports System.Web.Security Public Class Login Inherits System.Web.UI.Page Protected WithEvents lblMessage As System.Web.UI.WebControls.Label Protected WithEvents txtUsername As System.Web.UI.WebControls.TextBox Protected WithEvents Requiredfieldvalidator1 As System.Web.UI.WebControls.RequiredFieldValidator Protected WithEvents txtPassword As System.Web.UI.WebControls.TextBox Protected WithEvents Requiredfieldvalidator2 As System.Web.UI.WebControls.RequiredFieldValidator Protected WithEvents Button1 As System.Web.UI.WebControls.Button #Region " Web Form Designer Generated Code " 'This call is required by the Web Form Designer. <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() End Sub Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init 'CODEGEN: This method call is required by the Web Form Designer 'Do not modify it using the code editor. InitializeComponent() End Sub #End Region Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here Dim strLinkPath As String If Not IsPostBack Then strLinkPath = String.Format("Register.aspx?ReturnUrl={0}", _ Request.Params("ReturnUrl")) 'lnkRegister.NavigateUrl = String.Format(strLinkPath) End If End Sub Sub Button_Click(ByVal s As Object, ByVal e As EventArgs) If IsValid Then If DBAuthenticate(txtUsername.Text, txtPassword.Text) > 0 Then FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, False) Response.Redirect("Success.aspx") End If End If End Sub Function DBAuthenticate(ByVal strUsername As String, ByVal strPassword As String) As Integer Dim conMyData As SqlConnection Dim cmdSelect As SqlCommand Dim parmReturnValue As SqlParameter Dim intResult As Integer conMyData = New SqlConnection(ConfigurationSettings.AppSettings("connectionstring")) cmdSelect = New SqlCommand("DBAuthenticate", conMyData) cmdSelect.CommandType = CommandType.StoredProcedure parmReturnValue = cmdSelect.Parameters.Add("RETURN_VALUE", SqlDbType.Int) parmReturnValue.Direction = ParameterDirection.ReturnValue cmdSelect.Parameters.Add("@username", strUsername) cmdSelect.Parameters.Add("@password", strPassword) conMyData.Open() cmdSelect.ExecuteNonQuery() intResult = cmdSelect.Parameters("RETURN_VALUE").Value conMyData.Close() If intResult < 0 Then If intResult = -1 Then lblMessage.Text = "Username Not Registered!" Else lblMessage.Text = "Invalid Password!" End If End If Return intResult End Function End Class
Once successfully logged in, user will be directed to this page "Success.aspx", and the page should be able to retrieve the user's details from the database, in this case the password of the user is to be displayed. However, my program can't retrieve and display the user's password in the textbox/label. Note: connectionstring is stored in web.config.
Some of the SQL is stored in the stored procedures.
Successful.aspx
ASP.NET Syntax (Toggle Plain Text)
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="Success.aspx.vb" Inherits="LoginTest.Success"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <title>Success</title> <meta content="Microsoft Visual Studio.NET 7.0" name="GENERATOR"> <meta content="Visual Basic 7.0" name="CODE_LANGUAGE"> <meta content="JavaScript" name="vs_defaultClientScript"> <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema"> </HEAD> <body> <asp:label id="NameLabel" Runat="server"></asp:label><asp:label id="FormResponse" Runat="server"></asp:label> <form id="formSuccess" method="post" runat="server"> <h1>Welcome <%=User.Identity.Name%> </h1> <br> You have successfully logged in to the secure page. <br> Username:<%=User.Identity.Name%> <br> <br> Password: <asp:Label id="txtPassword" Runat="server" name="password"></asp:Label><br> <asp:button id="btnSubmit" Runat="server" Text="Submit"></asp:button> <asp:button id="btnLogout" Runat="server" Text="Logout"></asp:button></form> </body> </HTML>
Success.aspx.vb
ASP.NET Syntax (Toggle Plain Text)
Imports System Imports System.IO Imports System.Web Imports System.Data.SqlClient Imports System.Collections Imports System.Web.Security Imports System.Data Imports System.Data.SqlDbType Imports System.Security.Cryptography Imports System.Text Public Class Success Inherits System.Web.UI.Page Protected WithEvents formSuccess As System.Web.UI.HtmlControls.HtmlForm Protected WithEvents txtPassword As System.Web.UI.WebControls.Label Protected WithEvents lblmessage As System.Web.UI.WebControls.Label Protected WithEvents btnSubmit As System.Web.UI.WebControls.Button Protected WithEvents NameLabel As System.Web.UI.WebControls.Label Protected WithEvents FormResponse As System.Web.UI.WebControls.Label Protected WithEvents btnLogout As System.Web.UI.WebControls.Button Protected WithEvents txtUsername As System.Web.UI.WebControls.Label #Region " Web Form Designer Generated Code " 'This call is required by the Web Form Designer. <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() End Sub Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init 'CODEGEN: This method call is required by the Web Form Designer 'Do not modify it using the code editor. InitializeComponent() End Sub #End Region Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here If Not (User.Identity.IsAuthenticated) Then Response.Redirect("Login.aspx") End If 'txtPassword.Text = Profile.password If Not Page.IsPostBack Then Dim db As UsersDB = New UsersDB("connectionstring") txtPassword.Text = db.GetPassword(Page.User.Identity.Name) End If End Sub Public Function GetPassword(ByVal username As String) As String 'Retrieve the connection string from the configuration file. Dim con As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("connectionstring")) Dim htmlStr As New StringBuilder() 'Create a parameterized command with placeholders. Dim SQL As String = "SELECT * FROM tblUser WHERE username = @username" Dim cmd As SqlCommand = New SqlCommand(SQL, con) cmd.Parameters.Add("@username", username) Dim encryptedData() As Byte Try 'Update the record con.Open() Dim reader As SqlDataReader = cmd.ExecuteReader() If reader.Read() Then encryptedData = CType(reader("tblUser"), Byte()) txtPassword.Text = reader.Item("password") End If reader.Close() Catch Return Nothing Finally con.Close() End Try 'Decrypt and return the password. Return EncryptionUtil.DecryptToString(encryptedData, CType(HttpContext.Current.Application("Key"), Rijndael)) End Function Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click Dim conMaster As SqlConnection Dim cmdInsert As SqlCommand Dim intUpdate As Integer Dim paramValue As SqlParameter 'Dim intDate As DateTime = DateTime.Now() conMaster = New SqlConnection(ConfigurationSettings.AppSettings("connectionstring")) cmdInsert = New SqlCommand("AddData", conMaster) cmdInsert.CommandType = CommandType.StoredProcedure 'Make sure return value is taken from stored procedure paramValue = cmdInsert.Parameters.Add("ReturnValue", SqlDbType.Int) paramValue.Direction = ParameterDirection.ReturnValue 'DateAddedLabel.Text = DateTime.Now.ToString 'Parameters built to eliminate sql injection attacks 'cmdInsert.Parameters.Add("@date_added", DateTime.Parse(DateAddedLabel.Text)) 'cmdInsert.Parameters.Add("@username", txtUsername.Text) cmdInsert.Parameters.Add("@password", txtPassword.Text) 'Open database connection conMaster.Open() 'Update database by inserting new parameters cmdInsert.ExecuteNonQuery() If cmdInsert.Parameters("ReturnValue").Value = 1 Then 'Duplicate value found go to error page Response.Redirect("FormError.aspx") End If 'Close database connection conMaster.Close() End Sub Private Sub btnLogout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogout.Click FormsAuthentication.SignOut() Response.Redirect("Logout.aspx") End Sub End Class
UsersDB.vb
ASP.NET Syntax (Toggle Plain Text)
Imports Microsoft.VisualBasic Imports System Imports System.Data.SqlClient Imports System.Data Imports System.Configuration Imports System.Web.Security Imports System.Collections Imports System.Web Imports System.Security.Cryptography Public Class UsersDB Protected WithEvents txtUsername As System.Web.UI.WebControls.TextBox Private connectionSetting As String Public Sub New(ByVal connectionStringSettingName As String) Me.connectionSetting = connectionStringSettingName End Sub Public Function GetPassword(ByVal userName As String) As String ' Retrieve the connection string from the configuration file. Dim con As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings(connectionSetting)) ' Create a parameterized command with placeholders. Dim SQL As String = "SELECT * FROM tblUser " + "WHERE username = @username" Dim cmd As SqlCommand = New SqlCommand(SQL, con) cmd.Parameters.Add("@username", userName) Dim encryptedData As Byte() Try ' Update the record. con.Open() Dim reader As SqlDataReader = cmd.ExecuteReader(CommandBehavior.SingleRow) reader.Read() encryptedData = CType(reader("tblUser"), Byte()) reader.Close() Catch Return Nothing Finally con.Close() End Try ' Decrypt and return the credit card number. Return EncryptionUtil.DecryptToString(encryptedData, CType(HttpContext.Current.Application("Key"), Rijndael)) End Function End Class
EncryptionUtil.vb
ASP.NET Syntax (Toggle Plain Text)
Imports Microsoft.VisualBasic Imports System Imports System.Security.Cryptography Imports System.IO Public Class EncryptionUtil Inherits System.Web.UI.Page Public Shared Function EncryptString(ByVal stringToEncrypt As String, ByVal crypt As SymmetricAlgorithm) As Byte() ' Create a cryptographic stream for encryption. Dim ms As MemoryStream = New MemoryStream() Dim cs As CryptoStream = New CryptoStream(ms, crypt.CreateEncryptor(), CryptoStreamMode.Write) ' Write the string to binary data with the help of a BinaryWriter. Dim w As BinaryWriter = New BinaryWriter(cs) w.Write(stringToEncrypt) w.Flush() ' All the data has been written. Now, make sure the last block ' is properly padded. Failing to do this will cause an error ' when you attempt to decrypt the data. cs.FlushFinalBlock() ' Now move the encrypted data out of the stream, ' and into an array of bytes. Return ms.ToArray() End Function Public Shared Function DecryptToString(ByVal dataToDecrypt As Byte(), ByVal crypt As SymmetricAlgorithm) As String ' Create a cryptographic stream for decryption. Dim ms As MemoryStream = New MemoryStream() Dim cs As CryptoStream = New CryptoStream(ms, crypt.CreateDecryptor(), CryptoStreamMode.Write) ' Write the binary data to the memory stream. cs.Write(dataToDecrypt, 0, dataToDecrypt.Length) cs.FlushFinalBlock() ' Read the unencrypted data from the stream into a string, ' with the help of the BinaryReader. Dim r As BinaryReader = New BinaryReader(ms) ms.Position = 0 Dim decryptedData As String = r.ReadString() r.Close() Return decryptedData End Function End Class
Need help in retrieving the user's data from database and display on the form, user can edit and update and resubmit back to the database.
![]() |
Similar Threads
- retrieving a single cell of data from a MySQL database (PHP)
- Inserting Data into Access Database (Java)
- Forms authorization, only want a few links (ASP.NET)
- please help! this is urgent> how to retrieve data to my tabpage without using data fo (C#)
- cgi (HTML and CSS)
- Posting form data to an Oracle database (JavaScript / DHTML / AJAX)
- dynamic content from database, How? (Database Design)
Other Threads in the ASP.NET Forum
- Previous Thread: Using Assembly Language in .NET?
- Next Thread: making a program using itunes
| Thread Tools | Search this Thread |
.net 2.0 activexcontrol advice ajax alltypeofvideos asp asp.net bc30451 beginner bottomasp.net browser businesslogiclayer c# c#gridviewcolumn cac checkbox commonfunctions compatible confirmationcodegeneration content contenttype courier dataaccesslayer database datagrid datagridview datagridviewcheckbox datalist deployment development dgv dropdownlist dropdownmenu dynamic dynamically edit embeddingactivexcontrol fileuploader fill findcontrol flash flv formatdecimal forms formview gridview gudi homeedition iframe iis javascript jquery listbox menu microsoft mouse mssql multistepregistration news objects opera panelmasterpagebuttoncontrols redirect registration relationaldatabases reportemail rotatepage schoolproject security serializesmo.table sessionvariables silverlight smartcard smoobjects software sql-server sqlserver2005 ssl textbox tracking treeview unauthorized validatedate validation vb.net video videos virtualdirectory vista visual-studio visualstudio web webapplications webarchitecture webdevelopemnt webdevelopment webprogramming webservice youareanotmemberofthedebuggerusers





