This is a continuation of the Updated: ASP.NET Login Page Tutorial.
This tutorial will demonstrate how to create a registration page for new users to your site. This registration page will utilize the same principles used in the Login Page Tutorial, so this should be no more difficult to do than the login page. I am using the SQL Server 2000, and programmed this part of the application in Visual Studio .NET 2003. I choose VB because it is more natural language to me, but there is no reason you can't use the same concepts I use here to code this in any other language in the .NET framework.
1. Create the basic HTML layout for the registration page. REGISTER.ASPX
- This page will require all entries to be filled in for a successful registration
- UserName, Password, FirstName and LastName
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="Register.aspx.vb" Inherits="NorthLogin3.Register"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Register</title>
<meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" content="Visual Basic .NET 7.1">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</head>
<body ms_positioning="GridLayout">
<h1>Welcome to the Norwthwind DB Registration Page</h1>
<form id="frmRegister" method="post" runat="server">
<table id="tblRegister" border="1" cellpadding="2" cellspacing="1">
<tr>
<td style="WIDTH: 108px">User Name:</td>
<td><asp:textbox id="txtUserName" runat="server"></asp:textbox><font color="#ff3300" size="4"><strong>*</strong></font></td>
<td><asp:requiredfieldvalidator id="rvUserName" runat="server" errormessage="<-- Required" controltovalidate="txtUserName"></asp:requiredfieldvalidator></td>
</tr>
<tr>
<td style="WIDTH: 108px; HEIGHT: 23px">Password:</td>
<td style="HEIGHT: 23px"><asp:textbox id="txtPassword" runat="server" textmode="Password"></asp:textbox><font color="#ff3300" size="4"><strong>*</strong></font></td>
<td><asp:requiredfieldvalidator id="rvPassword" runat="server" errormessage="<-- Required" controltovalidate="txtPassword"></asp:requiredfieldvalidator></td>
</tr>
<tr>
<td style="WIDTH: 108px">First Name:</td>
<td><asp:textbox id="txtFirst" runat="server"></asp:textbox><font color="#ff3300" size="4"><strong>*</strong></font></td>
<td><asp:requiredfieldvalidator id="rvFirstName" runat="server" errormessage="<-- Required" controltovalidate="txtFirst"></asp:requiredfieldvalidator></td>
</tr>
<tr>
<td style="WIDTH: 108px">Last Name:</td>
<td><asp:textbox id="txtLast" runat="server"></asp:textbox><font color="#ff3300" size="4"><strong>*</strong></font></td>
<td><asp:requiredfieldvalidator id="rvLastName" runat="server" errormessage="<-- Required" controltovalidate="txtLast"></asp:requiredfieldvalidator></td>
</tr>
<tr>
<td colspan="2" align="center"><asp:button id="cmdSubmit" text="Submit" runat="server"></asp:button>
</td>
</tr>
</table>
</form>
<p><font color="#ff3300" size="4">*</font> Required Field
<asp:label id="lblError" style="Z-INDEX: 101; LEFT: 656px; POSITION: absolute; TOP: 264px"
runat="server" width="216px"></asp:label></p>
<p> </p>
<p> </p>
<asp:label id="lblResult" runat="server" width="424px"></asp:label>
</body>
</html>
2. Create the Store Procedures you will need to add a new user
- You will need to handle duplicates
- You will need to handle the adding of a new user.
a. Check for Duplicates. SP_CHECKFORDUPLICATES
CREATE PROCEDURE sp_CheckForDuplicates
(
@UserName VARCHAR(50) = NULL,
@FirstName VARCHAR(50) = NULL,
@LastName VARCHAR(50) = NULL,
@Duplicates INT = 0
)
AS
SET @Duplicates =(SELECT COUNT(*) FROM NorthWindUsers
WHERE UserName = @UserName
OR FirstName = @FirstName AND LastName = @LastName)
RETURN @Duplicates
b. Add New User. SP_REGISTERNEWUSER
CREATE PROCEDURE sp_RegisterNewUser
(
@UserName VARCHAR(50) = NULL,
@Password VARCHAR(50) = NULL,
@FirstName VARCHAR(50) = NULL,
@LastName VARCHAR(50) = NULL
)
AS
IF @UserName IS NULL OR
@Password IS NULL OR
@FirstName IS NULL OR
@LastName IS NULL
RAISERROR('Please fill in all fields', 16, 1)
ELSE
BEGIN
INSERT INTO NorthWindUsers
(UserName, Password, FirstName, LastName)
VALUES (@UserName, @Password, @FirstName, @LastName)
IF @@error <> 0
RAISERROR('User was not added', 16, 1)
ELSE
BEGIN
DECLARE @ID int
SELECT @ID = @@IDENTITY
SELECT Count(*)
FROM NorthWindUsers
WHERE UserID = @ID
END
END
RETURN
4. Create the code behind to provide functionality to your registration page. REGISTER.ASPX.VB
- This code behind will do several things; Validate the entries for completeness, duplication, and add the new user.
- I test for duplicates in UserName, as well as First & Last Name.
Imports System.Web.Security ' |||||| Required Class for Authentication
Imports System.Data ' |||||| DB Accessing Import
Imports System.Data.SqlClient ' |||||| SQL Server Import
Imports System.Configuration ' |||||| Required for Web.Config appSettings |||||
Public Class Register
Inherits System.Web.UI.Page
...
...
Imports System.Web.Security ' |||||| Required Class for Authentication
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
End Sub
Private Sub cmdSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSubmit.Click
If Page.IsValid Then ' ||||| Meaning the Control Validation was successful!
' ||||| All fields have been filled in!
If ValidateNewUser(txtUserName.Text.Trim(), txtFirst.Text.Trim(), txtLast.Text.Trim()) Then
AddNewUser(txtUserName.Text.Trim(), txtFirst.Text.Trim(), txtLast.Text.Trim(), txtPassword.Text.Trim())
Response.Redirect("login.aspx")
End If
End If
End Sub
Function ValidateNewUser(ByVal strAlias As String, ByVal strFirst As String, ByVal strLast As String) As Boolean
' <summary>
' ||||| This function simply verifies that there is no existing match on
' ||||| username (alias), and that the user has not already registered!
' </sumary>
' ||||| Set up a Connection Object to the SQL DB
Dim MyConn As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("strConn"))
' ||||| Pass in the StoreProcedure or Command String, as well as the Connection object
Dim MyCmd As New SqlCommand("sp_CheckForDuplicates", MyConn)
' ||||| Set the Command Type (Stored Procedure, Text, etc)
MyCmd.CommandType = CommandType.StoredProcedure
' ||||| Create Parameter Objects for values passed in
Dim objParam1, objParam2, objParam3 As SqlParameter
' ||||| Create a parameter to store your Return Value from the Stored Procedure
Dim objReturnParam As SqlParameter
' ||||| Add your parameters to the parameters Collection
objParam1 = MyCmd.Parameters.Add("@UserName", SqlDbType.VarChar)
objParam2 = MyCmd.Parameters.Add("@FirstName", SqlDbType.VarChar)
objParam3 = MyCmd.Parameters.Add("@LastName", SqlDbType.VarChar)
objReturnParam = MyCmd.Parameters.Add("@Duplicates", SqlDbType.Int)
objReturnParam.Direction = ParameterDirection.ReturnValue
' ||||| Set the Parameter values to the passed in values
objParam1.Value = strAlias
objParam2.Value = strFirst
objParam3.Value = strLast
Try
' ||||| Check if Connection to DB is already open, if not, then open a connection
If MyConn.State = ConnectionState.Closed Then
' ||||| DB not already Open...so open it
MyConn.Open()
MyCmd.ExecuteNonQuery()
End If
' ||||| Was the return value greater than 0 ???
If objReturnParam.Value > 0 Then
lblResult.Text = "UserName already exists or you are already a registered user!"
Return False
Else
Return True
End If
' ||||| Close the Connection Closes with it
MyConn.Close()
Catch ex As Exception
lblError.Text = "Error Connecting to Database!"
End Try
End Function
Sub AddNewUser(ByVal strUser As String, ByVal strFirst As String, ByVal strLast As String, ByVal strPass As String)
' ||||| Set up a Connection Object to the SQL DB
Dim MyConn As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("strConn"))
' ||||| Pass in the StoreProcedure or Command String, as well as the Connection object
Dim MyCmd As New SqlCommand("sp_RegisterNewUser", MyConn)
' ||||| Set the Command Type (Stored Procedure, Text, etc)
MyCmd.CommandType = CommandType.StoredProcedure
' ||||| Create Parameter Objects for values passed in
Dim objParam1, objParam2, objParam3, objParam4 As SqlParameter
' ||||| Create a parameter to store your Return Value from the Stored Procedure
Dim objReturnParam As SqlParameter
' ||||| Add your parameters to the parameters Collection
objParam1 = MyCmd.Parameters.Add("@UserName", SqlDbType.VarChar)
objParam2 = MyCmd.Parameters.Add("@FirstName", SqlDbType.VarChar)
objParam3 = MyCmd.Parameters.Add("@LastName", SqlDbType.VarChar)
objParam4 = MyCmd.Parameters.Add("@Password", SqlDbType.VarChar)
' ||||| Set the Parameter values to the passed in values
objParam1.Value = strUser
objParam2.Value = strFirst
objParam3.Value = strLast
objParam4.Value = strPass
Try
' ||||| Check if Connection to DB is already open, if not, then open a connection
' ||||| DB not already Open...so open it
MyConn.Open()
MyCmd.ExecuteNonQuery()
' ||||| Close the Connection Closes with it
MyConn.Close()
Catch ex As Exception
lblError.Text = "Error Connecting to Database!"
End Try
End Sub
End Class
5. Final thing to do: Link the Registration Page to the Login Page
- I used a Hyperlink on the login page to do this, but you could use anything. It is just a simple <a href="Register.aspx" ...> line of code to use for this. On that note I also send the user right back to the login page on successful registration. This is not the ideal thing to do. It would be better to direct them to a page that said "You are now registered! Would you like to return to the login page?" and a means of allowing them to return to the login page. But you specific use of this may be different, so the choice is yours.
6. Compile and run.....
Happy coding :cool: