Shining Star Services LLC

Creating a Custom Membership Provider and Membership User utilizing a Data Set Table Adapter - Step 8

by Nannette Thacker

Customizing our MembershipProvider Class.

Following is the source code for the customized methods used within the MembershipProvider class. They demonstrate how to use the custom Remember Me cookie and how to use data sets and table adapters.

I started this article in January, prior to getting swamped with a lengthy consulting contract. As a result, I will include the source code, but will not make detailed comments about what is taking place. I suggest you turn on debugging and run through the code in debug mode to see what is happening, where and how. Meanwhile, here are the customized classes created for the MembershipProvider:

#Region "Response.Redirects and ThreadAbortException"
        ' This is the normal behavior. 
        ' A Response.Redirect or Server.Transfer raises a ThreadAbortException, 
        ' since that is what is actually happening. 
        ' (The server aborts the current thread by calling a HttpResponse.End 
        ' and starts executing the new page in a new thread.) 
        ' http://support.microsoft.com/default.aspx?scid=kb;EN-US;312629
        ' For Response.Redirect, use an overload, 
        ' Response.Redirect(String url, bool endResponse) 
        ' that passes false for the endResponse parameter to suppress the 
        ' internal call to Response.End. For example:
        ' Response.Redirect ("nextpage.aspx", false)
#End Region

#Region "ValidateUser using a TableAdapter."
        ' use a custom Remember Me cookie
        Public Overrides Function ValidateUser(ByVal userName As String, _
        ByVal userPassword As String) As Boolean

            Try
                Dim IAdapter As New SSNetDataSetTableAdapters.UserTableAdapter
                Dim myMember As SSNetDataSet.UserDataTable = Nothing
                myMember = IAdapter.GetUserByLogin(userName, userPassword)
                If myMember.Rows.Count > 0 Then
                    Dim myUser As New SSSMembershipUser("")
                    myUser = GetUserFromDataset(myMember)
                    Dim myCookies As New SSSCookie()
                    myCookies.SetCookies(myUser.UserID, myUser.UserName, _
                    myUser.Password) ' 12/3/07 put in method
                    System.Web.HttpContext.Current.Response.Redirect("~/default.aspx", _
                    False)
                    Return True
                Else
                    Dim myCookies As New AppCookie()
                    myCookies.DeleteCookie("RememberMe")    
                    ' delete the cookie if the log in fails...
                    Return False
                End If

            Catch ex As Exception
                Console.Write(ex.ToString)
                Return False
            End Try

        End Function

#End Region

#Region "MS provided method style, must have a method style for CreateUser"

        Public Overrides Function CreateUser(ByVal username As String, _
        ByVal password As String, _
            ByVal email As String, _
            ByVal passwordQuestion As String, _
            ByVal passwordAnswer As String, _
            ByVal isApproved As Boolean, _
            ByVal providerUserKey As Object, _
            ByRef status As MembershipCreateStatus) As MembershipUser

            Dim myUser As New SSSMembershipUser("")
            Return myUser

        End Function

#End Region

        Public Overloads Overrides Function GetUser(ByVal providerUserKey As Object, _
        ByVal userIsOnline As Boolean) As System.Web.Security.MembershipUser

            Dim myUser As New SSSMembershipUser("")
            Return myUser

        End Function

#Region "GetUser using Table Adapter"

        Public Overloads Overrides Function GetUser(ByVal userName As String, _
        ByVal userIsOnline As Boolean) As System.Web.Security.MembershipUser

            Dim myUser As New SSSMembershipUser(userName)

            Try
                Dim IAdapter As New SSNetDataSetTableAdapters.UserTableAdapter

                Dim myMember As SSNetDataSet.UserDataTable = Nothing
                myMember = IAdapter.GetUserByUserName(userName)
                If Not myMember Is Nothing Then
                    If myMember.Rows.Count > 0 Then
                        myUser = GetUserFromDataset(myMember)
                    End If
                End If
                Return myUser
            Catch ex As Exception
                Console.Write(ex.ToString)
                Return myUser
            End Try

        End Function

#End Region

#Region "GetUserFromDataSet - Helper Function"
        ' A helper function that takes the current row from the tableadapter
        ' and hydrates a MembershipUser from the values. Called by the 
        ' MembershipUser.GetUser implementation.
        Public Function GetUserFromDataset(ByVal myMember _
        As SSNetDataSet.UserDataTable) As MembershipUser

            Dim userID As Decimal = 0
            Dim userName As String = ""
            Dim userEmail As String = ""
            Dim userPassword As String = ""
            Dim createDate As DateTime = New DateTime()
            Dim lastlogindate As DateTime = New DateTime()
            Dim ipAddress As String = ""

            If myMember.Rows.Count > 0 Then

                If Not myMember(0).IsusernameNull Then _
                    userName = myMember(0).username
                If Not myMember(0).userID = Nothing Then _
                    userID = myMember(0).userID
                If Not myMember(0).IsuserpasswordNull Then _
                    userPassword = myMember(0).userpassword
                If Not myMember(0).IsuseremailNull Then _
                    userEmail = myMember(0).useremail
                If Not myMember(0).IscreatedateNull Then _
                    createDate = myMember(0).createdate
                If Not myMember(0).IslastlogindateNull Then _
                    lastlogindate = myMember(0).lastlogindate
                If Not myMember(0).IsIPAddressNull Then _
                    ipAddress = myMember(0).IPAddress

            End If

            Dim myUser As New SSSMembershipUser("SSSMembershipProvider", _
                    userID, userName, userEmail, userPassword, _
                     createDate, lastlogindate, ipAddress)

            Return myUser

        End Function

#End Region

#Region "GetUserNameByEmail using a TableAdapter."

        Public Overrides Function GetUserNameByEmail(ByVal userEmail As String) _
        As String

            Dim userName As String = ""
            Try
                Dim IAdapter As New SSNetDataSetTableAdapters.UserTableAdapter
                Dim myMember As SSNetDataSet.UserDataTable
                myMember = IAdapter.GetUserByUserEmail(userEmail) ' pass in email
                If myMember.Rows.Count > 0 Then
                    If Not myMember(0).IsusernameNull Then
                        userName = myMember(0).username
                    End If
                End If
            Catch ex As Exception
                Console.Write(ex.ToString)
            End Try
            Return userName
        End Function
#End Region

#Region "ChangePassword using TableAdapter"

        Public Overrides Function ChangePassword(ByVal userName As String, _
            ByVal oldPassword As String, _
            ByVal newPassword As String) As Boolean

            Try

                ' make sure valid user....
                If Not ValidateUser(userName, oldPassword) Then _
                  Return False

                Dim args As ValidatePasswordEventArgs = _
                  New ValidatePasswordEventArgs(userName, newPassword, True)

                OnValidatingPassword(args)

                If args.Cancel Then
                    If Not args.FailureInformation Is Nothing Then
                        Throw args.FailureInformation
                    Else
                        Throw New ProviderException("Change password canceled _
                        due to New password validation failure.")
                    End If
                End If

                Dim IAdapter As New SSNetDataSetTableAdapters.UserTableAdapter
                ' retrieve the identity key userID from the insert
                IAdapter.UpdateUserPassword(newPassword, userName)
                Return True

            Catch ex As Exception
                Throw ex
                Return False
            End Try
        End Function

#End Region

    End Class

#Region "Provider Wrapper Class for Overloaded and Unique Custom Member Functions"

    Public Class SSSMembershipProviderWrapper

        Public Overloads Function GetUser(ByVal userID As Decimal) _
        As System.Web.Security.MembershipUser

            Dim myUser As New SSSMembershipUser("")

            Try
                Dim IAdapter As New SSNetDataSetTableAdapters.UserTableAdapter
                Dim myMember As SSNetDataSet.UserDataTable = Nothing
                myMember = IAdapter.GetUserByUserID(userID) ' uid is passed in....
                If Not myMember Is Nothing Then
                    If myMember.Rows.Count > 0 Then
                        Dim myMemberProvider As New SSSMembershipProvider
                        myUser = myMemberProvider.GetUserFromDataset(myMember)
                    End If
                End If
                Return myUser
            Catch ex As Exception
                Console.Write(ex.ToString)
                Return myUser
            End Try

        End Function

#Region "GetPassword Customized to return a MembershipUser"

        Public Overloads Function GetPassword(ByVal userName As String, _
        ByVal userEmail As String) As System.Web.Security.MembershipUser

            Dim myUser As New SSSMembershipUser("")
            Try
                If String.IsNullOrEmpty(userName) And _
                String.IsNullOrEmpty(userEmail) Then
                    Throw New ProviderException("MemberProvider.GetPassword: _
                    User Name and useremail are blank.")
                Else
                    Dim IAdapter As New SSNetDataSetTableAdapters.UserTableAdapter
                    Dim myMember As SSNetDataSet.UserDataTable = Nothing
                    If Not String.IsNullOrEmpty(userName) Then
                        myMember = IAdapter.GetUserByUserName(userName)
                    ElseIf Not String.IsNullOrEmpty(userEmail) Then
                        myMember = IAdapter.GetUserByUserEmail(userEmail)
                    End If
                    If Not myMember Is Nothing Then
                        If myMember.Rows.Count > 0 Then
                            Dim myMemberProvider As New SSSMembershipProvider
                            myUser = myMemberProvider.GetUserFromDataset(myMember)
                        End If
                    End If
                End If
            Catch ex As Exception
                Throw ex
            End Try
            Return myUser
        End Function
#End Region

#Region "Helper methods"

        Public Function GetUserNameByUserName(ByVal dupeUserName As String) As String
            ' used by registration to check for duplicate user name...
            Dim userName As String = ""
            Try
                Dim IAdapter As New SSNetDataSetTableAdapters.UserTableAdapter
                Dim myMember As SSNetDataSet.UserDataTable
                myMember = IAdapter.GetUserByUserName(dupeUserName) ' pass in email
                If myMember.Rows.Count > 0 Then
                    If Not myMember(0).IsusernameNull Then
                        userName = myMember(0).username
                    End If
                End If
            Catch ex As Exception
                Console.Write(ex.ToString)
            End Try
            Return userName
        End Function


        Public Function GetUserNameByUserID(ByVal userID As Decimal) As String

            Dim userName As String = ""
            Try
                Dim IAdapter As New SSNetDataSetTableAdapters.UserTableAdapter
                Dim myMember As SSNetDataSet.UserDataTable
                myMember = IAdapter.GetUserByUserID(userID)
                If myMember.Rows.Count > 0 Then
                    If Not myMember(0).IsusernameNull Then
                        userName = myMember(0).username
                    End If
                End If
            Catch ex As Exception
                Console.Write(ex.ToString)
            End Try
            Return userName
        End Function


#End Region

#Region "CreateUser Customized"

        Public Overloads Function CreateUser(ByVal userName As String, _
            ByVal userPassword As String, _
            ByVal userEmail As String, _
            ByVal firstName As String, _
            ByVal lastName As String, _
            ByVal createdate As Date, _
            ByVal lastlogindate As Date, _
            ByVal IPaddress As String) _
            As System.Web.Security.MembershipUser

            Dim myUser As New SSSMembershipUser("")
            Dim newUserID As Integer = 0
            Try
                Dim IAdapter As New SSNetDataSetTableAdapters.UserTableAdapter
                ' retrieve the identity key userID from the insert
                newUserID = _
                    Convert.ToInt32(IAdapter.InsertUser(userName, _
                        userPassword, userEmail, _
                        firstName, lastName, createdate, _
                        lastlogindate, IPaddress))
                If CStr(newUserID) <> "0" Then
                    myUser = GetUser(newUserID)
                End If
            Catch ex As Exception
                Console.Write(ex.ToString)
            End Try
            Return myUser
        End Function

#End Region
We are now ready to begin Step 9: Step 9: Our Custom RoleProvider Class.

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
© Copyright 1997-2017 Shining Star Services LLC, Nannette Thacker. All Rights Reserved.