Blue Theme Orange Theme Green Theme Red Theme
 
DevExpress Free UI Controls
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » ASP.NET and Web » User management, roles and personalization system in ASP.NET 2.0

User management, roles and personalization system in ASP.NET 2.0

Scott Gu, had a cool CreateUserWizard control sample that I have expanded upon to build-up a sample that demonstrates how to build a fairly common user management, roles and personalization system in ASP.NET 2.0 that does this. I was pleasantly surprised to find it only took about 25 lines of C# code in the entire app :)

Page Views : 19143
Downloads : 0
Rating :
 Rate it
Level : Advanced
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Mindcracker MVP Summit 2012
Become a Sponsor
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Scott Gu, had a cool CreateUserWizard control sample that I have expanded upon to build-up a sample that demonstrates how to build a fairly common user management, roles and personalization system in ASP.NET 2.0 that does this.  I was pleasantly surprised to find it only took about 25 lines of C# code in the entire app. J

The sample comes with 6 pages:

Specifically it supports:

  1. Login support to enable registered users to login to the web app using forms auth and the new membership system (login.aspx)
  2. Registration support to enable visitors to create and register new users in the membership system (CreateNewWizard.aspx)
  3. Profile support that enables the site to gather information about the user on registration, and for the users to see that information on a profile page (MyProfile.aspx).  
  4. Change Password support to enable registered users to change their password in the membership system (ChangePassword.aspx)
  5. Password Recovery support to enable users to reset their password if they forgot them (RecoverPassword.aspx)

Implementation Notes on CreateNewWizard.aspx and MyProfile.aspx:

Only two of the above pages (CreateNewWizard.aspx and MyProfile.aspx) have code in them.  The others use the built-in Login controls in V2 to-do everything (asp:login, asp:passwordrecovery, asp:changepassword). 

CreateNewWizard.aspx is the most interesting page.  It uses the built-in <asp:createuserwizard> server control to-do most of the heavy lifting and has two templated wizard steps defined within the wizard:

<asp:createuserwizard> wizard step 1: gathering user-account data

The <asp:createuserwizard> control handles gathering up the user-account, email, password, and password recovery/answer data and then calling into the ASP.NET 2.0 membership system to register the new user.  You simply have to override the control's <createuserwizardstep> template and customize the control layout to have things look how you want. 

The sample is using the ASP.NET validation controls to perform client-side validation on the inputs as well within the template (example: making sure passwords match, the age is a valid integer, etc).  One added benefit in ASP.NET 2.0 is that these validation controls now support client-side validation for FireFox and other modern browsers (note: all screenshots were done using FireFox).

There are then three additional properties (their country, gender and age) that I wanted to gather up about the new user as part of the registration process.  Doing this was pretty easy using the new ASP.NET 2.0 Profile system - simply add their definitions within the <profile> tag of the web.config file to register them and store their values in the new profile system:

<profile enabled="true">

    <properties>

            <add name="Country" type="string"/>

            <add name="Gender" type="string"/>

            <add name="Age" type="Int32"/>

    </properties>

</profile>

I then handled the "CreatedUser" event on the CreateUserWizard control within my CreateNewWizard.aspx.cs code-behind file to retrieve the values from the controls within the CreateUserWizard control template and set them in the profile store:

// CreatedUser event is called when a new user is successfully created

public void CreateUserWizard1_CreatedUser(object sender, EventArgs e) {

 

   // Create an empty Profile for the newly created user

   ProfileCommon p = (ProfileCommon) ProfileCommon.Create(CreateUserWizard1.UserName, true);

 

   // Populate some Profile properties off of the create user wizard

   p.Country = ((DropDownList)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Country")).SelectedValue;

   p.Gender = ((DropDownList)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Gender")).SelectedValue;

   p.Age = Int32.Parse(((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Age")).Text);

 

   // Save profile - must be done since we explicitly created it

   p.Save();

}

Because the user is being created as part of this step, I explicitly choose to create a new Profile object in code (note that I was passing in the CreatedUserWizard1.UserName property as the username - since the user isn't logged into the system yet).  I then accessed the controls within the template of the <asp:createuserwizard> control, pulled out their values, and stuck them within the newly created profile.  Calling p.save at the end registered this profile with the new username.  (note: I'll walk through how we use this profile data later in a page below).

<asp:createuserwizard> wizard step 2: picking roles

After the user fills out the first step of registration information and clicks the next button, the user is created, the CreatedUser event fires, and we fill in the appropriate information about the user into the profile store. 

The <asp:createuserwizard> control then displays the second step template we've defined.  This template lists all of the roles currently created in the ASP.NET Role Management system, and allows the user to select which roles they belong to:

Note that you'd typically never assign roles to an end-user this way (instead you'd add your own logic to somehow calculate which role they belong in), but I thought this scenario was cool nonetheless which is why it works like the sample above.

I think it is cool because of the way we populate and access these roles in the template of the <asp:createuserwizard>.  Basically, we have a template definition to the .aspx like this:

<asp:WizardStep runat="server" AllowReturn="False"

                OnActivate="AssignUserToRoles_Activate"              

                OnDeactivate="AssignUserToRoles_Deactivate">

    <table>

        <tr>

           <td>

              Select one or more roles for the user:

           </td>

        </tr>

        <tr>

            <td>

               <asp:ListBox ID="AvailableRoles" runat="server"

                            SelectionMode="Multiple" >

               </asp:ListBox>

            </td>

        </tr>

    </table>

</asp:WizardStep>

It simply contains a <asp:listbox> control named "AvailableRoles".  When this wizard step is loaded (after the user hits the next button on the first step in the wizard), it will fire the "OnActivate" event.  We can use this to databind the list of all roles in the system to the above listbox.  When the user hits next again, the wizard will fire the "OnDeactivate" event.  We can then use this to determine which roles were selected in the above listbox, and use them to update the role-manager system.

The code to-do both of these actions looks like this:

// Activate event fires when user hits "next" in the CreateUserWizard

public void AssignUserToRoles_Activate(object sender, EventArgs e) {

 

    // Databind list of roles in the role manager system to listbox

    AvailableRoles.DataSource = Roles.GetAllRoles(); ;

    AvailableRoles.DataBind();

}

 

// Deactivate event fires when user hits "next" in the CreateUserWizard

public void AssignUserToRoles_Deactivate(object sender, EventArgs e) {

 

    // Add user to all selected roles from the roles listbox

    for (int i = 0; i < AvailableRoles.Items.Count; i++) {

        if (AvailableRoles.Items[i].Selected == true)

           Roles.AddUserToRole(CreateUserWizard1.UserName, AvailableRoles.Items[i].Value);

    }

}

That is all of the code for the CreateNewWizard.aspx.cs file - 17 lines total if you omit comments and whitespace (if my count is right). 

Next Step: Displaying User Profile Data

The only other page in this scenario that required me to add code was the MyProfile.aspx page.  This page looks like this:

The page itself was pretty simple to implement.  I simply added a few asp:label controls on the page, as well a listbox for the roles.  Populating these controls with the profile and role information involved added a Page_Load event with 7 lines of code like so:

protected void Page_Load(object sender, EventArgs e) {

 

   Country.Text = Profile.Country;

   Gender.Text = Profile.Gender;

   Age.Text = Profile.Age.ToString();

 

   RoleList.DataSource = Roles.GetRolesForUser(User.Identity.Name);

   RoleList.DataBind();

}

Note that the profile object is strongly typed - which means profile properties will get statement completion and compilation checking in VS 2005 with it.  I can also then query the role management system to retrieve an array of all the roles the current user belongs to and then databind this to the listbox control. 

Since the MyProfile.aspx page requires a user to be logged in (otherwise retrieving profile information about them doesn't make a lot of sense), I also added a <location> based authorization control tag in my web.config file:

<location path="MyProfile.aspx">         

   <system.web>

          <authorization>

                   <deny users="?"/>

                   <allow users="*"/>

          </authorization>

   </system.web> 

</location>

This is the same configuration I would have added in ASP.NET V1.1 - and basically tells the system to deny all users who aren't logged in (the ? = anonymous), and then allow all users who are logged in (the * = all). 

Those who aren't logged in will get automatically re-directed to the login.aspx page.  The <asp:login> control can be used there to allow users who have already registered to log-in without the developer having to write any custom code.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Ravikumar Raja
Simple guy working in CTS for past a year, almost worked in most Microsoft Technology... thriving for More Knowledge
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
User registration with multiple tables by awlad_h On April 26, 2007
Say I have a user registration with multiple Wizard steps and want to store the data from each step into seperate table and then add all the information entered in all the steps into the user profile, is this possible? if so how? and thanks for this brilliant article, looking forward to more articles from you.
Reply | Email | Modify 
Re: User registration with multiple tables by Johnny On September 12, 2007

Sub SiteCreateUserWizard_CreatedUser(ByVal sender As Object, ByVal e As System.EventArgs) Handles SiteCreateUserWizard.CreatedUser

Dim UserProfile As ProfileCommon = Profile.GetProfile(SiteCreateUserWizard.UserName)

If Not Roles.IsUserInRole(SiteCreateUserWizard.UserName.ToString, "Members") Then

Roles.AddUserToRole(SiteCreateUserWizard.UserName.ToString, "Members")

End If

With UserProfile

.FirstName = FirstNameTextBox.Text

.LastName = LastNameTextBox.Text

.Nationality = txtNationality.Text

.Gender = cmbGender.Text

.Telephone = txtTelephone.Text

.Mobile = txtMobile.Text

.Address = txtAdress.Text

.City = txtCity.Text

.Postcode = txtPostcode.Text

.Country = txtCountry.Text

.ReceiveEmail = chkReceiveEmail.Checked

.ProfileVersion = Microsoft.SqlTableProfileProvider.ProfileVersion

.Save()

End With

End Sub

 

Powered by myweb.gr

Reply | Email | Modify 
link to the code by tzan1999 On September 14, 2007
can't find the link to the sample code
Reply | Email | Modify 
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.