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
Code Snippet
- <%@ 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 %>' />
- </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 OnOption Strict OnPartial Class Admin_Users
Inherits BasePage
Private allUsers As MembershipUserCollection = Membership.GetAllUsersProtected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadIf Not Me.IsPostBack ThenlblTotUsers.Text = allUsers.Count.ToStringlblOnlineUsers.Text = Membership.GetNumberOfUsersOnline.ToStringDim 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 = alphabetrptAlphabet.DataBind()End IfEnd SubPrivate Sub BindUsers(ByVal reloadAllUsers As Boolean)If reloadAllUsers ThenallUsers = Membership.GetAllUsersEnd IfDim users As MembershipUserCollection = NothingDim searchText As String = ""If Not String.IsNullOrEmpty(gvwUsers.Attributes("SearchText")) ThensearchText = gvwUsers.Attributes("SearchText")
End IfDim searchByEmail As Boolean = FalseIf Not String.IsNullOrEmpty(gvwUsers.Attributes("SearchByEmail")) ThensearchByEmail = Boolean.Parse(gvwUsers.Attributes("SearchByEmail"))End IfIf searchText.Length > 0 ThenIf searchByEmail Thenusers = Membership.FindUsersByEmail(searchText)Else
users = Membership.FindUsersByName(searchText)End IfElse
users = allUsersEnd IfgvwUsers.DataSource = usersgvwUsers.DataBind()End SubProtected Sub rptAlphabet_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.RepeaterCommandEventArgs) Handles rptAlphabet.ItemCommandgvwUsers.Attributes.Add("SearchByEmail", Boolean.FalseString)If e.CommandArgument.ToString.Length = 1 ThengvwUsers.Attributes.Add("SearchText", e.CommandArgument.ToString + "%")BindUsers(False)
Else
gvwUsers.Attributes.Add("SearchText", "")BindUsers(False)
End IfEnd SubProtected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.ClickDim searchByEmail As Boolean = (ddlSearchTypes.SelectedValue = "E-mail")gvwUsers.Attributes.Add("SearchText", "%" + txtSearchText.Text + "%")gvwUsers.Attributes.Add("SearchByEmail", searchByEmail.ToString)
BindUsers(False)
End SubProtected Sub gvwUsers_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvwUsers.RowCreatedIf e.Row.RowType = DataControlRowType.DataRow ThenDim 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 IfEnd SubProtected Sub gvwUsers_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles gvwUsers.RowDeletingTry
Dim userName As String = gvwUsers.DataKeys(e.RowIndex).Value.ToStringProfileManager.DeleteProfile(userName)Membership.DeleteUser(userName)BindUsers(True)
lblTotUsers.Text = allUsers.Count.ToStringCatch exc As ExceptionlblOnlineUsers.Text = exc.MessageEnd TryEnd SubEnd Class
EditUser.Aspx
Code Snippet
- <%@ 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" /> 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>
- <asp:Button ID="btnUpdateRoles" runat="server" Text="Update" CssClass="button"/></td>
- </tr>
- <tr>
- <td align="right">
- Create new role: <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 OnOption Strict OnImports 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.LoadTry
userName = Me.Request.QueryString("UserName")lblRolesFeedback.Visible = False
If Not Me.IsPostBack Then' show the user's details
If userName.Length > 0 ThenDim user As MembershipUser = Membership.GetUser(userName)Me.lblUserName.Text = user.UserName
Me.lnkEmail.Text = user.Email
Me.lnkEmail.NavigateUrl = "mailto:" & user.EmailMe.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.ProfileuserProfile = 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 IfEnd IfCatch exc As Exception' Do nothing
Finally
End TryEnd SubPrivate 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 = TrueNext
End SubProtected Sub chkApproved_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkApproved.CheckedChangedTry
Dim user As MembershipUser = Membership.GetUser(userName)Dim userEmail As String = user.Email.ToString()user.IsApproved = chkApproved.CheckedMembership.UpdateUser(user)If chkApproved.Checked ThenDim emailMsg As New System.Net.Mail.MailMessageDim 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)