|
|
|
|
|
|
Creating a Custom Membership Provider and Membership User utilizing
a Data Set Table Adapter - Step 13
by Nannette Thacker
Our Register Page
On our Registration page, we'll look at a few Regular Expressions. We'll use client side validation using the RequiredFieldValidator and also the RegularExpressionValidator.
On server side, we'll again check our validations using our FormUtility class and some Regex regular expressions defined there.
Register page code in front
<%@ Page Language="VB" MasterPageFile="~/SSS.Master" AutoEventWireup="false"
CodeFile="Register.aspx.vb" Inherits="Register" Title="Registration - ShiningStar.net and Nannette Thacker" %>
<%@ MasterType VirtualPath="~/SSS.Master" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1"
runat="Server">
<div>
<asp:Panel runat="server" ID="RegisterContainer" DefaultButton="RegisterButton">
<table border="0" cellpadding="0">
<tr>
<td align="center" colspan="2">
Shining Star Registration</td>
</tr>
<%--
http://msdn2.microsoft.com/en-us/library/ms998267.aspx
Regular Expressions
Enclosing the expression in the caret (^) and dollar sign ($)markers
ensures that the expression consists of the desired content and nothing
else. A ^ matches the position at the beginning of the input string
and a $ matches the position at the end of the input string.
If you omit these markers, an attacker could affix malicious input
to the beginning or end of valid content and bypass your filter.
^ # anchor at the start
[a-zA-Z] # may contain upper and lowercase chars
{1,20} # From 1 to 20 characters in length
\s # allows a space
$ # anchor at the end
' http://www.regular-expressions.info/charclass.html
' see shorthand characters
' \w stands for "word character", usually [A-Za-z0-9_].
' \s stands for "whitespace character". Again, which
' characters this actually includes, depends on the regex flavor. In all
' flavors discussed in this tutorial, it includes [ \t\r\n]. That is: \s will match a space, a tab or a line break.
--%>
<tr>
<td align="center" colspan="2">
<asp:Label ID="ResponseMsgTop" runat="server" Text=""></asp:Label>
</td>
</tr>
<tr>
<td align="right" valign="baseline">
<asp:Label ID="UserNameLabel" runat="server"
AssociatedControlID="UserName">Log In User Name:</asp:Label></td>
<td align="left">
<asp:TextBox ID="UserName" runat="server" MaxLength="20"></asp:TextBox>
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server"
Display="Dynamic" ControlToValidate="UserName" ForeColor="DarkRed"
ErrorMessage="*User Name is required."
ToolTip="User Name is required." ValidationGroup="RegisterGroup1"></asp:RequiredFieldValidator>
</tr>
<tr>
<td align="center" colspan="2">
<asp:RegularExpressionValidator ID="RegularExpressionValidator4"
Display="Dynamic" runat="server" ControlToValidate="UserName"
ErrorMessage="Your Log In User Name may contain up to 20 characters, numbers, /_- and spaces.<br>"
ValidationExpression="^[\w/\-\s]{1,20}$" ForeColor="DarkRed"
ValidationGroup="RegisterGroup1"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td align="right" valign="baseline">
<asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label></td>
<td align="left">
<asp:TextBox ID="Password" runat="server" MaxLength="10" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="PasswordRequired" runat="server"
Display="Dynamic" ControlToValidate="Password" ForeColor="DarkRed"
ErrorMessage="*Password is required."
ToolTip="Password is required." ValidationGroup="RegisterGroup1"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right" valign="baseline">
<asp:Label ID="ConfirmPasswordLabel" runat="server" AssociatedControlID="ConfirmPassword">Confirm Password:</asp:Label></td>
<td align="left">
<asp:TextBox ID="ConfirmPassword" runat="server" MaxLength="10"
TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="ConfirmPasswordRequired" runat="server"
Display="Dynamic" ControlToValidate="ConfirmPassword" ForeColor="DarkRed"
ErrorMessage="*Confirm Password is required."
ToolTip="Confirm Password is required." ValidationGroup="RegisterGroup1"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="center" colspan="2">
<asp:CompareValidator ID="PasswordCompare" runat="server" ControlToCompare="Password"
Display="Dynamic" ControlToValidate="ConfirmPassword" ErrorMessage="The Password and Confirmation Password do not match."
ForeColor="DarkRed" ValidationGroup="RegisterGroup1"></asp:CompareValidator>
</td>
</tr>
<tr>
<td align="right" valign="baseline">
<asp:Label ID="EmailLabel" runat="server" AssociatedControlID="UserEmail">E-mail:</asp:Label></td>
<td align="left">
<asp:TextBox ID="UserEmail" runat="server" MaxLength="50"></asp:TextBox>
<asp:RequiredFieldValidator ID="EmailRequired" runat="server"
Display="Dynamic" ControlToValidate="UserEmail" ForeColor="DarkRed"
ErrorMessage="*E-mail is required."
ToolTip="E-mail is required." ValidationGroup="RegisterGroup1"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="center" colspan="2">
<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
runat="server" ControlToValidate="UserEmail"
ErrorMessage="Please enter a valid Email address.<br>" ValidationExpression="^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"
Display="Dynamic" ForeColor="DarkRed" ValidationGroup="RegisterGroup1"></asp:RegularExpressionValidator>
<asp:Label ID="FailureEmail" runat="server" Text=""></asp:Label>
</td>
</tr>
<tr>
<td align="right" valign="baseline">
<asp:Label ID="FirstNameLabel" runat="server" AssociatedControlID="FirstName">First Name:</asp:Label></td>
<td align="left">
<asp:TextBox ID="FirstName" runat="server" MaxLength="20"></asp:TextBox>
<asp:RequiredFieldValidator ID="FirstNameRequired" runat="server"
Display="Dynamic" ControlToValidate="FirstName" ForeColor="DarkRed"
ErrorMessage="*First Name is required."
ToolTip="First Name is required." ValidationGroup="RegisterGroup1"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right" valign="baseline">
<asp:Label ID="LastNameLabel" runat="server" AssociatedControlID="LastName">Last Name:</asp:Label></td>
<td align="left">
<asp:TextBox ID="LastName" runat="server" MaxLength="20"></asp:TextBox>
<asp:RequiredFieldValidator ID="LastNameRequired" runat="server"
Display="Dynamic" ControlToValidate="LastName" ForeColor="DarkRed"
ErrorMessage="*Last Name is required."
ToolTip="Last Name is required." ValidationGroup="RegisterGroup1"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="center" colspan="2">
<asp:Button ID="RegisterButton" runat="server" Text="Register"
ValidationGroup="RegisterGroup1" /><br />
<asp:Label ID="ResponseMsgBottom" runat="server" Text="" ></asp:Label>
<br />
<asp:ValidationSummary ID="ValidationSummary1" ValidationGroup="RegisterGroup1"
runat="server" ForeColor="DarkRed"
DisplayMode="SingleParagraph" />
</td>
</tr>
</table>
</asp:Panel>
<asp:Panel runat="server" ID="SuccessContainer" Visible="False">
<table border="0" cellpadding="0">
<tr>
<td align="center">
Thank you!</td>
</tr>
<tr>
<td align="left">
<ul>
<li>Your account has been registered.</li>
</ul>
</td>
</tr>
</table>
</asp:Panel>
</div>
</asp:Content>
Registration page Code Behind
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.HttpContext
Partial Class Register
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.UserName.Focus() ' set focus....
End Sub
Protected Sub RegisterButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles RegisterButton.Click
Try
Me.ResponseMsgBottom.Text = ""
Me.FailureEmail.Text = ""
Me.ResponseMsgTop.Text = ""
Dim username As String = Me.UserName.Text
Dim password As String = Me.Password.Text
Dim confirmpassword As String = Me.ConfirmPassword.Text
Dim useremail As String = Me.UserEmail.Text
Dim firstname As String = Me.FirstName.Text
Dim lastname As String = Me.LastName.Text
' server side validation...
If String.IsNullOrEmpty(username) Or String.IsNullOrEmpty(password) _
Or String.IsNullOrEmpty(confirmpassword) Or String.IsNullOrEmpty(useremail) _
Or String.IsNullOrEmpty(firstname) Or String.IsNullOrEmpty(lastname) Then
Me.ResponseMsgBottom.Text = "You must enter a User Name, Password, Email Address, First and Last Name."
ElseIf Not FormUtility.IsValidName(username) Then
Me.ResponseMsgBottom.Text = "Your Log In User Name may contain up to 20 characters, numbers, /_- and spaces."
ElseIf CStr(password) <> CStr(confirmpassword) Then
Me.ResponseMsgBottom.Text = "The Password and Confirmation Password must match."
ElseIf Len(username) > 20 Then
Me.ResponseMsgBottom.Text = "Your Log In User Name may contain up to 20 characters."
ElseIf Len(password) > 10 Then
Me.ResponseMsgBottom.Text = "Your Password may contain up to 10 characters."
ElseIf Not FormUtility.IsValidEmail(useremail) Then
Me.ResponseMsgBottom.Text = "You must enter a valid Email Address in username@domain.com format. You will not be able to post until your e-mail is verified."
ElseIf Len(firstname) > 20 Then
Me.ResponseMsgBottom.Text = "Your First Name may contain up to 20 characters."
ElseIf Len(lastname) > 20 Then
Me.ResponseMsgBottom.Text = "Your Last Name may contain up to 20 characters."
Else
Dim logintext As String = "Please enter another, or " & _
"<a href=""" & ResolveClientUrl("~/login/login.aspx") & """>Log In</a> to your existing account or " & _
"<a href=""" & ResolveClientUrl("~/login/PasswordRecover.aspx") & """>Recover</a> your Log In Name and Password."
' check for duplicates
Dim dupeCheck As String = ""
dupeCheck = Membership.GetUserNameByEmail(useremail)
If Not String.IsNullOrEmpty(dupeCheck) Then
Me.ResponseMsgBottom.Text = "The Email entered is already in use. " & logintext
Me.FailureEmail.Text = Me.ResponseMsgBottom.Text
Me.ResponseMsgTop.Text = Me.ResponseMsgBottom.Text
Return
End If
Dim myMemberW As New ShiningStar.SSSMembershipProviderWrapper
dupeCheck = myMemberW.GetUserNameByUserName(username)
If Not String.IsNullOrEmpty(dupeCheck) Then
Me.ResponseMsgBottom.Text = "The User Name entered is already in use. " & logintext
Me.ResponseMsgTop.Text = Me.ResponseMsgBottom.Text
Return
End If
Dim createdate, lastactivitydate As Date
createdate = Now()
lastactivitydate = Now()
Dim IPaddress As String = Current.Request.ServerVariables("Remote_Addr")
Dim myUser As New ShiningStar.SSSMembershipUser("")
myUser = myMemberW.CreateUser(username, password, useremail, firstname, _
lastname, createdate, lastactivitydate, IPaddress)
Me.RegisterContainer.Visible = False
Me.SuccessContainer.Visible = True
Return
End If
Me.ResponseMsgTop.Text = Me.ResponseMsgBottom.Text ' copy to top message as well
Return
Catch ex As Exception
Me.ResponseMsgBottom.Text = ex.ToString
End Try
End Sub
End Class
FormUtility Class and RegEx
Imports Microsoft.VisualBasic
Public Class FormUtility
' put Functions that handle forms in here and Import on only pages that use these functions...
#Region "Javascript Built Functions"
#Region "SetFocus"
' http://ryanfarley.com/blog/archive/2004/12/21/1325.aspx
' setfocus in C#
' nkt: used on form pages in the Page_Load function to set the focus
' of a form field when using masterpages and contentplaceholders
' it writes a javascript function
Public Shared Sub SetFocusControl(ByVal control As Control)
Dim sb As StringBuilder = New StringBuilder
With sb
.Append("" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "<script language='JavaScript'>" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
.Append("<!--" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
.Append("function SetFocus()" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
.Append("{" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
.Append("" & Microsoft.VisualBasic.Chr(9) & "document.")
Dim p As Control = control.Parent
While Not (TypeOf p Is System.Web.UI.HtmlControls.HtmlForm)
p = p.Parent
End While
.Append(p.ClientID)
.Append("['")
.Append(control.UniqueID)
.Append("'].focus();" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
.Append("}" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
.Append("window.onload = SetFocus;" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
.Append("// -->" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
.Append("<" & "/script>")
End With
control.Page.ClientScript.RegisterClientScriptBlock(control.GetType, "SetFocus", sb.ToString)
End Sub
#End Region
#Region "WindowOpen for Popups"
' nkt: used to pop open windows...
Public Shared Function WindowOpen() As String
Dim sb As StringBuilder = New StringBuilder
With sb
.Append("" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "<script language='JavaScript'>" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
.Append("<!--" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
.Append("function winopen(url,stuff,morestuff)" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
.Append("{" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
.Append(" " & Microsoft.VisualBasic.Chr(9) & "window.open(url,stuff,morestuff);")
.Append("" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
.Append("}" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
.Append("// -->" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
.Append("<" & "/script>")
End With
WindowOpen = sb.ToString
End Function
#End Region
#End Region
Public Shared Function IsValidEmail(ByVal strIn As String) As Boolean
' Return true if strIn is in valid e-mail format.
Return Regex.IsMatch(strIn, ("^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"))
End Function
Public Shared Function IsValidName(ByVal strIn As String) As Boolean
Return Regex.IsMatch(strIn, ("^[\w/\-\s]{1,20}$"))
End Function
End Class
We are now ready to begin
Step 14.
Steps for Creating a Custom Membership Provider and Membership
User utilizing a DataSet Table Adapter:
Introduction: Creating a Custom Membership Provider and Membership User utilizing
a DataSet Table Adapter.
Step 1: Creating the Project and Folders.
Step 2: Table Data Structure and Web.config for this Tutorial.
Step 3: Creating The DataSet.
Step 4: Creating the Table Adapter Methods for GetUserByLogin, GetUserByUserName, and InsertUser.
Step 5: Creating our Custom MembershipProvider Class.
Step 6: Adding Properties to Our Custom MembershipProvider Class.
Step 7: Creating Our Custom MembershipUser Class.
Step 8: Customizing our MembershipProvider Class.
Step 9: Our Custom RoleProvider Class.
Step 10: Our Master page.
Step 11: Our Cookie Handler class.
Step 12: Our Log In page.
Step 13: Our Register page.
Step 14: Our Log Out page.
Step 15: Our Change Password page.
Step 16: Our Administration page.
Step 17: Loading a Menu Programmatically based on Roles.
Step 18: Our Default page.
Download the ZIP files:
VB: ShiningStarCustomMemberProviderTutorial.zip
|
|
|
|
|
|
|
|

|