Database Storage with the ASP.NET Web Matrix: Simple Login Page

This article covers the creation of a basic login page for your website. With this page, when a registered member returns to your website and logs in, he or she will be able to access restricted or personal areas of your site.

Contributed by
Rating: 4 stars4 stars4 stars4 stars4 stars / 34
September 21, 2005
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

If you read my last article about creating, connecting and writing to a database using the Microsoft Web Matrix, you should have a working registration page that will allow users to enter a username and password into your database, thus registering as a member.  Certain criteria were also enforced, such as unique usernames and a minimum password length of seven characters.

This article will focus on creating a login page to go with the registration page so that when a member returns, they are able to access restricted or personal areas of your site.  The page itself will be very basic, just a simple demonstration of reading data from a database and matching records.

To begin with, you’ll need to create a standard ASP.NET page from the general templates section.  You also need to make sure that the database from the previous example (members) is connected, and if not, connect it by choosing the Add Database Connection button from the Data pane at the far right of the Web Matrix, then by selecting the database in the Connect to SQL or MSDE Database dialog box.

Once that is done, set up the registration page by, in the Design view, dragging a label web control, a textbox web control and another label web control onto one line, then another line featuring the same controls.  Then on a new line, drag a button web control onto the page, and finally, on another new line, drag a final label control onto the page.

Start with the Properties pane

Using the Properties pane at the far right of the Web Matrix (just below the Data pane), set the Text value of the first label to Username: then set the ID value of the textbox to txtUsername.  Set the ID of the label after the textbox to lblUsernameError and clear the Text value.  Now set the Fore color to red.

Move down to the next line and set the Text value of the first label to Password: then set the ID value of the textbox to txtPassword.  Set the ID value of the label following this textbox to lblPasswordError, clear the Text value and again set the Fore color to red.

Move down to the button and set the ID value to btnSubmit and the Text value to Submit.  Finally, move down to the last label control and set the ID value to msgWelcome, set the Fore color to green and clear the Text value.

These are the only visual elements we will need.  Your page should look a little like this:

 

In the previous example, we used an INSERT function to write the information submitted by the user to the database.  In this example, we will use a SELECT function instead to read the contents of the database.  In fact, we will use two SELECT functions, one to read the first column of the database (username) and one to read both the first and second columns (username and password).

Switch to the Code view

Switch to the Code view in the Web Matrix and drag a SELECT function onto the page to launch the Select Code Wizard dialog box.  Make sure the members database is selected and click the Next button.  In the Columns panel of the next window, check the Username tick box, then click the Where button.  The Where Clause Builder will already be set correctly, so just click Ok.  Click the Next button twice and then set a name for the function, such as checkUserName, make sure the DataSet radio is selected, and click Finish.  This will add the first of our SELECT functions to the page. 

To create the second SELECT function, drag another SELECT onto the page; this time, choose both the Username the Password tick boxes and in the Where Clause Builder dialog, select Username in the Left Operand Column panel and click Ok.  Now click the And Clause button and this time, choose Password as the Left Operand and click Ok. Click the Next button twice and then set the function name to checkUserPass.  Again, ensure the DataSet radio is selected.

The following screenshot shows the vast amount of code that the Wen Matrix has just written for you:

To call these functions and check the user’s information, go back to the Design view in the Web Matrix, and double-click the Submit button.  This will add a click event to the Code view.  Go back to the Code view, and in the Sub add the following code:

lblUsernameError.Text = ""
lblPasswordError.Text = ""
lblWelcome.Text = ""

These three lines of code simply reset the messages when the Submit button is clicked so that, if a user enters an incorrect name on the first attempt, whichever error message is displayed gets switched off the next time the submit button is clicked.  Otherwise, if a user submits an incorrect username or password before submitting a correct username and password, the error message will be displayed with the welcome message.

Encrypting the password

Because we chose to encrypt the user’s password on the registration page before it was written to the database, we need to also encrypt the password when it is submitted on the login page, otherwise the values won’t match.  Add the following block of code, which is exactly the same as it was on the register page:

Dim hashMethod as string
hashMethod = "MD5"
Dim encryptPassword as string
encryptPassword =
FormsAuthentication.HashPasswordForStoringInConfigFile
(txtPassword.Text, hashMethod)

We now need to create a method that passes the txtUsername value to the first SELECT statement, and a variable in which to hold the returned dataset:

Dim userDetailsName As New System.Data.DataSet
userDetailsName = checkUserName(txtUsername.Text)

The userDetailsName variable will now hold a dataSet containing the matching values from the database.  We also need to get a dataSet containing both the matching usernames and passwords from the database, so also add the following code to the page:

Dim userDetailsPass As New System.Data.DataSet

userDetailsPass = checkUserPass(txtUsername.Text,
encryptPassword)

So now we have two datasets, one containing the matching Username from the database and one containing the matching Username and the encrypted Password from the database.   You need to use two datasets so that an appropriate error message can be displayed.  The first dataSet is just used to check that the user is defined in the database, while the second dataSet is used to check that the username matches the password.

The data returned in the datasets is automatically formatted into a table by .NET, so to address the data correctly you need to specify which table in the dataSet the row holding the information resides in. There will only be one table in our datasets, and because the tables within a dataSet have zero-based indices, we will be working with table(0).  DataSets don’t have to be created by a dataAdapter reading data from a database; they can also read information from XML files, or be constructed manually.  Additionally, because the database we are using can only hold unique values, only one row will be held in the dataSet -- therefore if the Count method returns anything other than a one, it will return a zero. 

Add the following If statement to the Code page, which checks that both dataSets hold just one record each:

If userDetailsName.Tables(0).Rows.Count <> 1 Then
      lblUsernameError.Text = "* Username not known, please <a
 href='register.aspx'>Register</a> with us"
    Else If userDetailsPass.Tables(0).Rows.Count <> 1 Then
      lblPasswordError.Text = "* Password incorrect"
Else
      lblWelcome.Text = "Welcome back " + txtUsername.Text
End If

This statement first checks that the username entered on the page exists in the dataSet; if it doesn’t, it displays an error message and links to the registration page.  If the username does exist, the statement then moves on and checks that the password entered matches the password associated with the username in the second dataSet. If it doesn’t, it displays a message advising that the password is incorrect.  If both of these conditions are true, a welcome message is displayed.  Test the page to check that it’s working properly.

Do you want to use a template?

  

 The Web Matrix does provide a login page template under the Security templates section, but I thought that creating the page manually may help to promote a fuller learning experience.  If you create a new page from this template, you will see that in the Loginbtn_Click event handler that comes as part of the template, a line of code that reads:

FormsAuthentication.RedirectFromLoginPage(UserName.Text, true)

This line of code would be used instead of the Welcome message we created.  What this does is either redirect the user to the page that the user was on before the login page, or redirect them to their default page.  The second parameter of the method states whether a session persistent cookie should be created or not.  I have left this out of this tutorial because so far, all we have is a registration page and a login page; there is no default page that you could be redirected to!

So far, you have seen how easily and quickly pages can be created with the power to insert and read data to and from a database.  The next articles will describe how the Web Matrix can be put to the task of removing and updating data from  a database, so pretty soon, you should have a good understanding of just what can be achieved with a data-driven ASP.NET site.

blog comments powered by Disqus
DATABASE ARTICLES

- How To Install DotNetNuke with MySQL
- Manage Projects with SQL Server Management S...
- Query Editing and Regular Expressions with S...
- Using SQL Server Management Studio Tools
- SQL Server Management Studio
- Exporting a MySQL Database to Excel Using OD...
- Controlling Databases with SQL Server 2005 D...
- Using Recovery Models with SQL Server 2005 D...
- Handling Database Properties for the SQL Ser...
- Managing Permissions with the SQL Server 200...
- SQL Server 2005 Database Engine Security
- Administering SQL Server 2005 Database Engine
- Building Applications with Anonymous Types
- A Closer Look at Anonymous Types
- Programming with Anonymous Types

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 1 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials