The following example will demonstrate as how to manage registered users, activate or deactivate them assign or remove role(s) in ASP.Net. My assumption is, you already have a page which allows users to register and now you would like to activate the user and assign a role so that they can login to your web site. I have created two page, which resides in Admin area of web site. You will be required to make some changes such as Master Page File, Namespace, Base Page and Content Place Holder ID etc. in order to properly compile and work with you project. The first page will allow you to search and find one or more registered users and second page will allow you to activate and assign a role.
 

Note: My User Profile contains additional fields such as First Name, Last Name, Address and Phone Number, if you are not using in your profile, you can remove it or change it as per your user profile.

 

Users.Aspx

 

<%@ Page Language="VB" MasterPageFile="~/WebSite.master"

    AutoEventWireup="false" CodeFile="Users.aspx.vb" Inherits="Admin_Users"

    title="VishwaMohan.Com | Admin | Manage Users" %>

 

<asp:Content ID="conContentManage" ContentPlaceHolderID="cphMainContent" Runat="Server">

     <div style="text-align:center">

     <table cellpadding="2" cellspacing="0" border="0" width="100%" style="text-align:center">

        <tr>

            <td id="content" width="100%" valign="top" height="100%" class="darkgray_row" style="text-align:center">      

                <table cellpadding="0" cellspacing="0" border="0" width="100%" style="text-align:center" >

                    <tr>

                        <td valign="top" style="text-align:center"><h3 class="lighgray_row" style="text-align:center">Account Management</h3>

                            <br />

                            <b>- Total registered users: <asp:Literal runat="server" ID="lblTotUsers" /><br />

                            - Users online now: <asp:Literal runat="server" ID="lblOnlineUsers" /></b>

                            <p>

                                Click one of the following link to display all users whose name begins with that letter:

                            </p>

                        </td>

                    </tr>

            <tr>

                <td style="text-align:center">

                   <asp:Repeater runat="server" ID="rptAlphabet" OnItemCommand="rptAlphabet_ItemCommand">

                      <ItemTemplate><asp:LinkButton ID="lnbLinkButton" runat="server" Text='<%# Container.DataItem %>'

                         CommandArgument='<%# Container.DataItem %>' />&nbsp;&nbsp;

                      </ItemTemplate>

                   </asp:Repeater>

                </td>

           </tr>

           <tr>

                <td style="text-align:center">

                    <br />

                    Otherwise use the controls below to search users by partial username or e-mail:

                    <br />

                </td>

            </tr>       

            <tr>

            <td height="50px;" style="text-align:center">

                <asp:DropDownList runat="server" ID="ddlSearchTypes">

                  <asp:ListItem Text="UserName" Selected="true" />

                  <asp:ListItem Text="E-mail" />

               </asp:DropDownList>

               Contains

               <asp:TextBox runat="server" ID="txtSearchText" />

               <asp:Button runat="server" ID="btnSearch" Text="Search" CssClass="button" OnClick="btnSearch_Click" />

                <br />

            </td>

            </tr>

            <tr>

                <td style="text-align:center">

               <asp:GridView ID="gvwUsers" runat="server" AutoGenerateColumns="false" DataKeyNames="UserName"

                  OnRowCreated="gvwUsers_RowCreated" Width="100%" PagerSettings-Mode="NumericFirstLast"

                  PageSize="10" >

                  <Columns>    

                     <asp:BoundField HeaderText="UserName" DataField="UserName" />

                     <asp:HyperLinkField HeaderText="E-mail" DataTextField="Email" DataNavigateUrlFormatString="mailto:{0}" DataNavigateUrlFields="Email" />

                     <asp:BoundField HeaderText="Created" DataField="CreationDate" DataFormatString="{0:MM/dd/yy h:mm tt}" />

                     <asp:BoundField HeaderText="Last activity" DataField="LastActivityDate" DataFormatString="{0:MM/dd/yy h:mm tt}" />

                     <asp:CheckBoxField HeaderText="Appr." DataField="IsApproved" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" />

                     <asp:HyperLinkField Text="<img src='../images/edit.gif' border='0' />" DataNavigateUrlFormatString="EditUser.aspx?UserName={0}" DataNavigateUrlFields="UserName" />

                     <asp:ButtonField CommandName="Delete" ButtonType="Image" ImageUrl="~/images/delete.gif" />

                  </Columns>

                  <EmptyDataTemplate><b>No users found for the specified criteria</b></EmptyDataTemplate>

               </asp:GridView>            

                </td>

           </tr>

        </table>

        </td>

      </tr>       

     </table>

 </div>

 </asp:Content>

 

Users.Aspx.vb

Option Explicit On

Option Strict On

Partial Class Admin_Users

    Inherits BasePage

    Private allUsers As MembershipUserCollection = Membership.GetAllUsers

 

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Not Me.IsPostBack Then

            lblTotUsers.Text = allUsers.Count.ToString

            lblOnlineUsers.Text = Membership.GetNumberOfUsersOnline.ToString

            Dim alphabet As String() = _

                "A;B;C;D;E;F;G;H;I;J;K;L;M;N;O;P;Q;R;S;T;U;V;W;X;Y;Z;All".Split(CChar(";"))

            rptAlphabet.DataSource = alphabet

            rptAlphabet.DataBind()

        End If

    End Sub

 

    Private Sub BindUsers(ByVal reloadAllUsers As Boolean)

        If reloadAllUsers Then

            allUsers = Membership.GetAllUsers

        End If

 

        Dim users As MembershipUserCollection = Nothing

 

        Dim searchText As String = ""

        If Not String.IsNullOrEmpty(gvwUsers.Attributes("SearchText")) Then

            searchText = gvwUsers.Attributes("SearchText")

        End If

 

        Dim searchByEmail As Boolean = False

        If Not String.IsNullOrEmpty(gvwUsers.Attributes("SearchByEmail")) Then

            searchByEmail = Boolean.Parse(gvwUsers.Attributes("SearchByEmail"))

        End If

 

        If searchText.Length > 0 Then

            If searchByEmail Then

                users = Membership.FindUsersByEmail(searchText)

            Else

                users = Membership.FindUsersByName(searchText)

            End If

        Else

            users = allUsers

        End If

 

        gvwUsers.DataSource = users

        gvwUsers.DataBind()

    End Sub

 

    Protected Sub rptAlphabet_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.RepeaterCommandEventArgs) Handles rptAlphabet.ItemCommand

        gvwUsers.Attributes.Add("SearchByEmail", Boolean.FalseString)

 

        If e.CommandArgument.ToString.Length = 1 Then

            gvwUsers.Attributes.Add("SearchText", e.CommandArgument.ToString + "%")

            BindUsers(False)

        Else

            gvwUsers.Attributes.Add("SearchText", "")

            BindUsers(False)

        End If

    End Sub

 

    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click

        Dim searchByEmail As Boolean = (ddlSearchTypes.SelectedValue = "E-mail")

        gvwUsers.Attributes.Add("SearchText", "%" + txtSearchText.Text + "%")

        gvwUsers.Attributes.Add("SearchByEmail", searchByEmail.ToString)

        BindUsers(False)

    End Sub

 

    Protected Sub gvwUsers_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvwUsers.RowCreated

        If e.Row.RowType = DataControlRowType.DataRow Then

            Dim btn As ImageButton = CType(e.Row.Cells(6).Controls(0), ImageButton)

            btn.OnClientClick = "if (confirm('Are you sure you want to delete this user account?') == false) return false;"

        End If

    End Sub

    Protected Sub gvwUsers_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles gvwUsers.RowDeleting

        Try

            Dim userName As String = gvwUsers.DataKeys(e.RowIndex).Value.ToString

            ProfileManager.DeleteProfile(userName)

            Membership.DeleteUser(userName)

            BindUsers(True)

            lblTotUsers.Text = allUsers.Count.ToString

        Catch exc As Exception

            lblOnlineUsers.Text = exc.Message

        End Try

    End Sub

End Class

EditUser.Aspx

<%@ Page Language="VB" MasterPageFile="~/WebSite.master"

    AutoEventWireup="false" CodeFile="EditUser.aspx.vb" Inherits="Admin_EditUser"

    title="VishwaMohan.Com | Admin | Edit Users" %>

 

<asp:Content ID="conContentEditUser" ContentPlaceHolderID="cphMainContent" Runat="Server">

      <div style="text-align:center">

        <table cellpadding="2" cellspacing="0" border="0" width="100%" style="text-align:center">

        <tr>           

            <td id="content" width="100%" valign="top" height="100%" class="darkgray_row" align="left">      

                <table cellpadding="0" cellspacing="0" border="0" width="100%" style="text-align:center" >

                    <tr>

                        <td valign="top" colspan="2" style="text-align:center">

                                <h3 class="lighgray_row" style="text-align:center">Edit User Account</h3>

                        </td>

                     </tr>

                     <tr>         

                        <td width="200px" nowrap></td>             

                        <td>                      

                            <table cellpadding="2" border="0" width="100%" visible=false>

                            <tr>

                                <td >User Name:</td>

                                <td >

                                    <asp:Literal ID="lblUserName" runat="server"></asp:Literal></td>

                            </tr>

                            <tr>

                                <td >

                                    First Name:</td>

                                <td>

                                    <asp:Label ID="lblFirstName" runat="server"/></td>

                            </tr>

                            <tr>

                                <td >

                                    Last Name:</td>

                                <td>

                                    <asp:Label ID="lblLastName" runat="server"/></td>

                            </tr>

                            <tr>

                                <td colspan="2"><hr /></td>

                            </tr>

                            <tr>

                                <td >

                                    E-Mail:</td>

                                <td>

                                    <asp:HyperLink ID="lnkEmail" runat="server">[lnkEmail]</asp:HyperLink></td>

                            </tr>

                            <tr>

                                <td >

                                   Address:</td>

                                <td>

                                    <asp:Label ID="lblAddress" runat="server"/></td>

                            </tr>

                            <tr>

                                <td >

                                    Phone:</td>

                                <td>

                                    <asp:Label ID="lblPhone" runat="server"/></td>

                            </tr>

                            <tr>

                                <td colspan="2"><hr /></td>

                            </tr>

                            <tr>

                                <td >

                                    Registered:</td>

                                <td>

                                    <asp:Literal ID="lblRegistered" runat="server"></asp:Literal></td>

                            </tr>

                            <tr>

                                <td >

                                    Last Login:</td>

                                <td>

                                    <asp:Literal ID="lblLastLogin" runat="server"></asp:Literal></td>

                            </tr>

                            <tr>

                                <td >

                                    Last Activity</td>

                                <td>

                                    <asp:Literal ID="lblLastActivity" runat="server"></asp:Literal></td>

                            </tr>

                             <tr>

                                <td colspan="2"><hr /></td>

                            </tr>

                            <tr>

                                <td >

                                    Online Now:</td>

                                <td>

                                    <asp:CheckBox ID="chkOnlineNow" runat="server" Enabled="False" /></td>

                            </tr>

                            <tr>

                                <td >

                                    Approved:</td>

                                <td>

                                    <asp:CheckBox ID="chkApproved" runat="server" AutoPostBack="True" />&nbsp;&nbsp; If approved, make sure a role is assigned.</td>

                            </tr>

                            <tr>

                                <td >

                                    Locked Out:</td>

                                <td>

                                    <asp:CheckBox ID="chkLockedOut" runat="server" AutoPostBack="True" /></td>

                            </tr>

                        </table>

                     </td>

                </tr>

                <tr>

                    <td colspan="2" style="text-align:center">

                        <h4 class="lighgray_row" style="text-align:center">Edit user's roles</h4>

                        <br />  

                        <asp:CheckBoxList ID="chklRoles" runat="server" CellSpacing="4" RepeatColumns="5"/>

                    </td>

                 <tr>

                 <td class="sidebar"></td>                

                 <td>

                    <table cellpadding="2" width="100%" border="0">

                        <tr>

                            <td align="right">

                                <asp:Label ID="lblRolesFeedback" runat="server" Text="Roles updated successfully"

                                    Visible="False"></asp:Label>&nbsp;&nbsp;&nbsp;&nbsp;

                                <asp:Button ID="btnUpdateRoles" runat="server" Text="Update" CssClass="button"/></td>

                        </tr>

                        <tr>

                            <td align="right">

                                Create new role:&nbsp;<asp:TextBox ID="txtNewRole" runat="server"></asp:TextBox>

                                <asp:RequiredFieldValidator ID="rfvRequireNewRole" runat="server" ControlToValidate="txtNewRole"

                                    ErrorMessage="Role name is required." SetFocusOnError="True" ValidationGroup="CreateRole"></asp:RequiredFieldValidator>

                                <asp:Button ID="btnCreateRole" runat="server" Text="Create" ValidationGroup="CreateRole" CssClass="button" /></td>

                        </tr>

                    </table>

                  </td>

                  </tr>

                  </table>  

            </td>

          </tr>           

        </table>

</div>

 

 

</asp:Content>

 

 

 

EditUser.Aspx.vb

Option Explicit On

Option Strict On

Imports System.Collections

Imports System.Collections.Generic

 

 

Partial Class Admin_EditUser

    Inherits BasePage

    Dim userName As String = ""

 

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Try

            userName = Me.Request.QueryString("UserName")

            lblRolesFeedback.Visible = False

 

            If Not Me.IsPostBack Then

                ' show the user's details

                If userName.Length > 0 Then

                    Dim user As MembershipUser = Membership.GetUser(userName)

                    Me.lblUserName.Text = user.UserName

                    Me.lnkEmail.Text = user.Email

                    Me.lnkEmail.NavigateUrl = "mailto:" & user.Email

                    Me.lblRegistered.Text = user.CreationDate.ToString("f")

                    Me.lblLastLogin.Text = user.LastLoginDate.ToString("f")

                    Me.lblLastActivity.Text = user.LastActivityDate.ToString("f")

                    Me.chkOnlineNow.Checked = user.IsOnline

                    Me.chkApproved.Checked = user.IsApproved

                    Me.chkLockedOut.Checked = user.IsLockedOut

                    Me.chkLockedOut.Enabled = user.IsLockedOut

 

                    Dim userProfile As ProfileCommon = Me.Profile

                    userProfile = Me.Profile.GetProfile(userName)

                    Me.lblFirstName.Text = userProfile.FirstName

                    Me.lblLastName.Text = userProfile.LastName

                    Me.lblAddress.Text = userProfile.Address

                    Me.lblPhone.Text = userProfile.Phone

 

                    BindRoles()

                End If

            End If

        Catch exc As Exception

            ' Do nothing

        Finally

        End Try

    End Sub

 

    Private Sub BindRoles()

        Me.chklRoles.DataSource = Roles.GetAllRoles

        Me.chklRoles.DataBind()

        For Each role As String In Roles.GetRolesForUser(userName)

            Me.chklRoles.Items.FindByText(role).Selected = True

        Next

    End Sub

    Protected Sub chkApproved_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkApproved.CheckedChanged

        Try

           

            Dim user As MembershipUser = Membership.GetUser(userName)

            Dim userEmail As String = user.Email.ToString()

            user.IsApproved = chkApproved.Checked

            Membership.UpdateUser(user)

            If chkApproved.Checked Then

                Dim emailMsg As New System.Net.Mail.MailMessage

                Dim smtpClient As New System.Net.Mail.SmtpClient()

 

                emailMsg.From = New System.Net.Mail.MailAddress(ConfigurationManager.AppSettings.Item("AdminUserEmail").ToString())

                emailMsg.Subject = "Your Account has been Approved."

                emailMsg.Body = "Hello " & userName & vbCrLf & Space(15) & "Your Account has been Approved." & vbCrLf & vbCrLf & "See you online!" & vbCrLf & "- Vishwa Mohan"

                emailMsg.To.Add(userEmail)

                smtpClient.Send(emailMsg)

 

            End If

            Me.lblRolesFeedback.Text = "Approval status updated successfully."

        Catch exc As Exception

            Me.lblRolesFeedback.Text = exc.Message

        Finally

            Me.lblRolesFeedback.Visible = True

        End Try

    End Sub

 

    Protected Sub chkLockedOut_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkLockedOut.CheckedChanged

        If Not chkLockedOut.Checked Then

            Dim user As MembershipUser = Membership.GetUser(userName)

            user.UnlockUser()

            Me.chkLockedOut.Enabled = False

        End If

    End Sub

 

    Protected Sub btnUpdateRoles_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdateRoles.Click

        ' first remove the user from all roles...

        Dim currRoles() As String = Roles.GetRolesForUser(userName)

        If currRoles.Length > 0 Then

            Roles.RemoveUserFromRoles(userName, currRoles)

            Me.lblRolesFeedback.Text = "Role removed from the User."

        End If

 

        ' and then add the user to the selected roles

        Dim newRoles As New List(Of String)

        For Each item As ListItem In chklRoles.Items

            If item.Selected Then

                newRoles.Add(item.Text)

                Me.lblRolesFeedback.Text = "New Role Added to the User."

            End If

        Next

        Dim userNames() As String = {userName}

        Roles.AddUsersToRoles(userNames, newRoles.ToArray)

        Me.lblRolesFeedback.Visible = True

    End Sub

 

    Protected Sub btnCreateRole_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCreateRole.Click

        If Not Roles.RoleExists(txtNewRole.Text.Trim) Then

            Roles.CreateRole(txtNewRole.Text.Trim)

            BindRoles()

        End If

    End Sub

End Class

 

Users.Aspx Page at Run Time

 

Signature

Comments

3/16/2007 8:25:00 PM #

Cricket91

Great Code!!

Had A Quick question I've been looking in the forums when I came across your tuturial and my question is this. How do you restrict albums by users and not roles?

Thanks

Cricket91 United States

3/18/2007 5:23:54 PM #

vishwa

I think you can do it two ways. One you can assign each album to a user for view or not to view or you can go up to photo level driven based on user. But either way it will put more work on you to assign each user either all album or photos you want to share with him or her. Another way could be, creating more groups and splitting your albums, and then you can assign one user to one or more role or group.

vishwa United States

9/5/2007 2:58:08 AM #

Osiris

First, I think that your program is great. For my purposes I had to make the slight changes shown below. The problem is that in an asp.net 2.0 environment this line "Roles.AddUsersToRoles(userNames, newRoles.ToArray)" produces this error "Unable to cast object of type 'System.Object[]' to type 'System.String[]'."

Please let me know the best fix. Thanks.

Protected Sub btnUpdateRoles_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdateRoles.Click

        ' first remove the user from all roles...
        Dim currRoles() As String = Roles.GetRolesForUser(userName)

        If currRoles.Length > 0 Then
            Roles.RemoveUserFromRoles(userName, currRoles)
            Me.lblRolesFeedback.Text = "Role removed from the User."
        End If

        ' and then add the user to the selected roles
        Dim newRoles As New ArrayList

        For Each item As ListItem In chklRoles.Items
            If item.Selected Then
                newRoles.Add(item.Text)
                Me.lblRolesFeedback.Text = "New Role Added to the User."
            End If
        Next

        Dim userNames() As String = {userName}
        Roles.AddUsersToRoles(userNames, newRoles.ToArray)
        Me.lblRolesFeedback.Visible = True

    End Sub

Osiris United States

9/5/2007 3:15:18 AM #

Osiris

Ignore my post. The problem was that I had not added this to my web.config file. But while I have your attention, I used asp:createuserwizard to create users and I changed password settings in web.config under providers.
minRequiredNonalphanumericCharacters="0"
minRequiredPasswordLength="6"
These changes have had no effect. What am I doing wrong? Thanks again.

Osiris United States

9/5/2007 3:29:12 AM #

Osiris

Sorry again. By adding defaultProvider="ISKSqlMembershipProvider"  to the membership node in web.config everything worked.

Osiris United States

12/17/2007 4:11:38 AM #

farooq

Hi vishwa,
Above post is very good,
I ve bounded the following to repeater
Dim alphabet As String() = _

"A;B;C;D;E;F;G;H;I;J;K;L;M;N;O;P;Q;R;S;T;U;V;W;X;Y;Z;All".Split(CChar(";"))

and my reuirement is if records are not available with the particular alphabet how can I hide it ,do I need to do coding plz suggest me,

Thanks

farooq India

10/8/2008 12:11:40 PM #

johnjam

Hello Vishwa,
Many thanks for leaving the code on your site, it works very well indeed.  
I am still learning ASP.NET but loved the way you coded this and it integrated
very well with my existing application.
It may be wise to point out to novices developers such as myself the setting required
in the web.config as your Note was a bit vague about FirstName and LastName etc
perhaps you could verify these settings in web.config        

            
                
                
                
                
            

        

Another small note to make, what about Password resetting?.

Once again many thanks for the code
Kind regards
Johnjam

johnjam United Kingdom

4/7/2009 6:06:35 AM #

Ajay Pant

Hello Vishwa, Many thanks for leaving the code on your site, it works very well indeed. I am still learning ASP.NET but loved the way you coded this and it integrated very well with my existing application.

i got some error when i use the editusers.aspx.vb of yours coding "Managing Users and Roles."

the following syntax shows the error in "profile word" says 'Type Expected '
Dim userprofile As Profile = Me.Load
please give me the solution

Thanks

Ajay Pant India

3/1/2010 11:04:42 PM #

Cast Iron Hibachi

Zahvaljujemo se vam za dobro delovno mesto najlep?a hvala

Cast Iron Hibachi United States

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



About Me

Me Hello,my name is Vishwa Mohan Kumar.
I am a Software Architect. This blog is result of my experiments.

Flickr Photos

Calendar

<<  March 2010  >>
MoTuWeThFrSaSu
22232425262728
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar

Recent Comments

Comment RSS

Live Traffic Feed