Visual Basic.NET
  Home arrow Visual Basic.NET arrow Page 3 - Adding Roles to ASP.NET Accounts
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Dedicated Servers 
Actuate Whitepapers 
VeriSign Whitepapers 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
VISUAL BASIC.NET

Adding Roles to ASP.NET Accounts
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 3 stars3 stars3 stars3 stars3 stars / 9
    2006-11-22

    Table of Contents:
  • Adding Roles to ASP.NET Accounts
  • Restricting Access to Pages Based on Roles
  • Create Personalized Web Sites
  • Exploring the Pro

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    Adding Roles to ASP.NET Accounts - Create Personalized Web Sites


    (Page 3 of 4 )

     

    Now that you have forms-based security working, you know who your user is and can store the user’s preferences and, if appropriate, previous choices (e.g., “You have 3 items in your shopping cart”).

    To get started, you’ll want a new project that duplicates the work you accomplished in the previous example. Create a new web site called SitePersonalization and use the CopyWebSite pattern described previously to make a copy of ASPSecurityRoles into the new site (copying over all the files and folders from the old site to the new.) Set Welcome.aspx as the Start page, and run the program to make sure you have a working duplicate.

    Recording Personalization Information

    The simplest form of personalization is to record information about the user, then make that information available whenever the user logs on. This requires a kind of persistence that goes beyond session state. To create true personalization, you’ll want to store the user’s choices and information in a database that associates the saved information with a particular user, and that persists indefinitely.

    ASP.NET 2.0 provides all of the plumbing required. You do not have to design, edit, or manage the database tables; all of that is done for you.

    Setting up profile handling

    ASP.NET 2.0 has decoupled the Profile API (how you programmatically interact with profile data) from the underlying data provider (how you store the data). This allows you to use the default provider (SqlServerExpress), one of the other providers
    supplied (SQL server), or even write your own provider (e.g., for an existing Customer Relationship Management system) without changing the way you interact with the profile in the rest of your code.

    If you wish to have the SQLExpress database handle the profile information, there are no additional steps; profile tables have already been created for you. To add data to the user’s profile, alert the system about the data you wish to store by making an entry in Web.config. Add a profile section to the<system.web>element, as shown in Example 12-10.

    Example 12-10. Adding a profile section to Web.config

    <?xml version="1.0"?>
    <configuration>
     
    <connectionStrings>
       
    <remove name="LocalSqlServer"/>
       
    <add name="LocalSqlServer" connectionString="data source=.\sqlExpress;Integrated Security=SSPI;Initial Catalog=aspnetdb"/>
     
    </connectionStrings>
     
    <system.web>
       
    <authentication mode="Forms"/>
       
    <membership defaultProvider="AspNetSqlMembershipProvider"/>
       
    <roleManager enabled="True" defaultProvider="AspNetSqlRoleProvider"/>
       
    <compilation debug="true"/>
       
    <profile enabled="True" defaultProvider="AspNetSqlProfileProvider">
         <properties>
          
    <add name="lastName" />
          
    <add name="firstName" />
          
    <add name="phoneNumber" />
          
    <add name="birthDate" type="System.DateTime"/>
         </properties>
       </profile> 
      
    </system.web>
    </configuration>

    Your Web.config file may look somewhat different depending on your machine configuration and the databases you have installed (SQL Server, SQL Express, etc.)

    The configuration shown in Example 12-10 causes the Profile API to create storage for four pieces of information: first and last name, phone number, and birth date. The default storage type isString. Notice, however, that you are storing the birth date as aDateTimeobject.

    You can gather this personalization information any way you like. For this example, return to Welcome.aspx and click on the smart tag to chooseEditTemplatesand then choose theLoggedIn Template. Set the text toAdd Profile Infoand the NavigateURL property toProfileInfo.aspx(which you will create shortly). Don’t forget to clickEndTemplateEditingwhen you are done.

    Create the new page: ProfileInfo.aspx. Add a table, and within the table, labels and checkboxes, as well as a Save button, as shown in Figure 12-30.

    The HTML code for the Profile Table is shown in Example 12-11.

     


    Figure 12-30.  Profile Table

    Example 12-11. HTML for profile table

    <%@ Page Language="VB" AutoEventWireup="false" CodeFile="ProfileInfo.aspx.vb" Inherits="ProfileInfo" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/ xhtml11.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head id="Head1" runat="server">  
        <title>ProfileInfo</title></head>
    <body>
        <form id="form1" runat="server">
        <div>
               <table>
               <tr>
                   <td>First Name: </td>
                   <td style="width: 193px">

                     <asp:TextBox ID="firstName" Runat="server" />
                  
    </td>
               </tr>
               <tr>
                  
    <td>Last Name: </td>
                   <td style="width: 193px">
                    <asp:TextBox ID="lastName" Runat="server" /></td>
               </tr>
               <tr>
                  
    <td>Phone number: </td>
                   <td style="width: 193px">
                      <asp:TextBox ID="phone" Runat="server" />
                  
    </td>
               </tr>
               <tr>
                   <td>BirthDate</td>
                   <td style="width: 193px">
                      <asp:TextBox ID="birthDate" Runat="server" />
                   </td>
               </tr>
                <tr>
                  <td>
                     <asp:Button ID="save" Text="Save" Runat="server"

                       OnClick="save_Click" />
                 </td>
                <td style="width: 193px"></td>
             </tr>
          </table>

        </div>
        
    </form>
    </body>
    </html>

    All that remains to be done is to add an event handler for the Save button:

      Protected Sub save_Click( _
      ByVal sender As Object, _
      ByVal e As System.EventArgs) Handles save.Click
       
    If Profile.IsAnonymous = False Then
            Profile.lastName = Me.lastName.Text
            Profile.firstName = Me.firstName.Text
            Profile.phoneNumber = Me.phone.Text
            Profile.birthDate = CType(Me.birthDate.Text, System.DateTime)
       
    End If
        Response.Redirect("Welcome.aspx")
      End Sub

    TheProfile.IsAnonymousproperty is explained in detail below

    The Profile object has properties that correspond to the properties you added in Web.config. To test that the Profile object has, in fact, stored this date, you’ll add a panel to the bottom of the Welcome page, as shown in Figure 12-31.


    Figure 12-31.  Welcome page panel

    The panel has a table with three rows, and each row has a label that is initialized to say that the value is unknown (this is not normally needed, but is included here to ensure that the data you see is retrieved from theProfileobject). When the page is loaded, you check to see if you haveProfiledata for this user and, if so, you assign that data to the appropriate controls.

    Example 12-12 shows the source for the panel.

    Example 12-12. Adding a panel to the Welcome page

    <asp:Panel ID="pnlInfo" Runat="server" Visible="False" Width="422px" Height="63px">
      <br />
      <table width="100%">
       
    <tr>
          <td>
            <asp:Label ID="lblFullName" Runat="server"
             Text="Full name unknown">
            </asp:Label></td>
          </tr>
        <tr>
          <td>
            <asp:Label ID="lblPhone" Runat="server"
              Text="Phone number unknown">
            </asp:Label>
         
    </td>
        </tr>
        <tr>
         
    <td>
            <asp:Label ID="lblBirthDate" Runat="server"
                Text="Birthdate unknown">
            </asp:Label>
          </td>
        </tr>
      </table>
    </asp:Panel>

    You’ll need to add a bit of code to the Welcome.aspx.vb page, so that when the page loads it will check to see if you have a profile, and if so, it will make the panel visible, as shown in Example 12-13.

    Example 12-13. Welcome page Page_Load method

    Protected Sub Page_Load(_
    ByVal sender As Object, _
    ByVal e As System.EventArgs) Handles Me.Load
       
    If Not IsPostBack And Profile.UserName IsNot Nothing Then
            Me.pnlInfo.Visible = True
            If Profile.IsAnonymous = False Then
               Me.lblFullName.Text = Profile.firstName & " " & Profile.lastName
               Me.lblPhone.Text = Profile.phoneNumber
               Me.lblBirthDate.Text = Profile.birthDate.ToShortDateString()
           
    End If
        Else
            Me.pnlInfo.Visible = False
        End If
    End Sub

    When you start the application, you are asked to log in. Once logged in, a new hyperlink appears: Add Profile Info. This was created by the hyperlink you added to theLoggedInTemplateearlier. Clicking on that link brings you to your new profile page, as shown in Figure 12-32.


    Figure 12-32.  Profile information page

    When you click Save and return to the Welcome page, thePage_Loadevent fires. The Page_Load begins with anIf statement:

      If Profile.UserName IsNot Nothing And _
         Profile.IsAnonymous = False Then

    Both parts of theIfstatement evaluateTrue: theUserNamevalue in the profile is notNothing, and the user is logged in, and thus not anonymous.

    Your profile information is displayed, as shown in Figure 12-33.


    Figure 12-33.  Profile information displayed 

    More Visual Basic.NET Articles
    More By O'Reilly Media


       · This article is an excerpt from the book "Programming Visual Basic 2005," published...
       · This code has helped a lot! Only thing is I'm getting an error that some of the...
       · I read this article because I was looking for a way to add membership to my website....
       · This excerpted article should explain the term "WAT." I don't know WAT that means. ...
     

    Buy this book now. This article is excerpted from chapter 12 of the book Programming Visual Basic 2005, written by Jesse Liberty (O'Reilly, 2005; ISBN: 0596009496). Check it out today at your favorite bookstore. Buy this book now.

    VISUAL BASIC.NET ARTICLES

    - Working with Classes and Properties for Game...
    - Working with Loops, Arrays, and Collections ...
    - Learning Loops in VB.NET for Game Development
    - Learning VB.NET: Working with Variables, Con...
    - The Basics of VB.NET Through Text Game Devel...
    - Learning VB.NET Through Text Game Development
    - Types of Operators in Visual Basic
    - Operators
    - Understanding Custom Events using Visual Bas...
    - Polymorphism using Abstract Classes in Visua...
    - Shadowing using Shadows in Visual Basic.NET ...
    - Overloading and Overriding in Visual Basic.N...
    - More on Controlling Windows Fax Services Usi...
    - Programmatically Controlling Windows Fax Ser...
    - Focusing on Forms and Menus in Visual Basic





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway