1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Working with User Profiles in ASP.NET

Discussion in 'ASP.NET' started by MinalS, Feb 24, 2015.

  1. MinalS

    MinalS New Member

    Joined:
    Jul 8, 2014
    Messages:
    138
    Likes Received:
    30
    Trophy Points:
    0
    The user profiles can be used in any application. To enable the user profiles, user needs to modify the Web.config configuration file in the ASP.NET application. The following code snippet demonstrates the profiles in the configuration file.

    Code:
    <profile>
        <properties>
            <group name = "Employee">
            <add name = "Harry" type="string" />
            <add name ="EmpID" type="Integer" />
            <add name = "Links" type="System.Collection.Specialized.StringCollection" serializesAs="Xml" />
            </group name>
        </properties>
    </profile>
    
    In the above code, the profile using properties is defined in the Web.Config file. The <add> element is used for defining the element in the profile. The <group> element helps user to combine multiple properties in a common container. The serializeAs attribute accepts values for serialization. The ASP.NET dynamically creates a profile object.

    The advantage of using the user profile is that the information is saved permanently. The user log out does not effect the saved information. All the saved data can be viewed again by the user when he logins the system.

    The System.Web.Profile namespace contains classes used for implementing the user profiles. Some of the classes used in the namespace are as mentioned below:
    1. ProfileBase: It provides an untyped access of values and information of the profile property.
    2. CustomProviderDataAttribute: It sets the provider of the profile property with the string of custom data.
    3. ProfileEventArgs: It ensures the availability of the data for the Personalize event.
    4. ProfileModule: It controls the creation of user profile and events
    5. SqlProfileProvider: It manages the user profile information stored in SQL Server database
    ProfileProvider Class

    The ProfileProvider class stores the values and information in a data source so that it can be easily accessed by the ProfileProvider implementation. The class is available in System.Web.Profile namespace present in the System.Web assembly.

    Some of the methods of the ProfileProvide class are as listed below:
    1. GetAllProfiles(): It retrieves all the user profile data for the profiles stored in the data source.
    2. FindProfilesByUserName(): It obtains the information for profiles when the user name is matched with the provided user name
    3. DeleteInactiveProfiles(): It removes all the user profiles data for profiles in which the last activity data is before the date specified.
    4. GetNumberOfInActiveProfiles(): It returns the number of profiles where the last activity data was before the mentioned date.
    The following code snippet demonstrates the providers in the web.config file.
    Code:
    <profile>
        <providers>
            <add name="AspNetSqlProfileProvider"
            connecitonStringName="LocalServer"
            applicationName="/"
            type="System.Web.Profile.SqlProfileProvider, System.Web.Version=2.0.0.0, Culture=neutral"
            />
        </providers>
    </profile>
    
    Anonymous Profiles

    When the user accesses the portal without logging in, the user is called as anonymous user. The user profile for anonymous user stores information about Internet Protocol of the system. For creation of an anonymous user, add the following code in the web.config file.
    Code:
    <anonymousIdentification enabled="true"/>
    
    It creates a unique identification number for the anonymous user visiting the web site. The cookie consists of the unique identification number for the user. The cookie name for the anonymous identification can be modified in the configuration file.
    Code:
    <configuration>
        <system.web>
            <anonymousIdentification enabled="true" cookieName="ck1" />
        </system.web>
    </configuration>
    
    If the cookies are blocked, the identification number stored in the Uniform Resource Locator ( URL ) is useful for sending the request to the web site of the server. The following code snippet demonstrates the storage of the identification number using the configuration file.
    Code:
    <configuration>
        <system.web>
        <anonymousIdentification enabled="true" cookieless="UseUri" />
        </system.web>
    </configuration>
    
    The identification number is lost when user closes the browser on which the website is executing.

    ASP.NET provides the anonymous identification feature. The <anonymousIdentification> element is used for enabling the feature. It is defined in the <system.web> element.

    The following code demonstrates the <anonymousIdentification> element.
    Code:
    <anonymousIdentication
        enabled =" [ true | false ] "
        cookieless = " [ UserUri | UseCookies | AutoDetect | UseDeviceProfile ] "
        cookieName=" "
        cookiePath=" " 
        cookieProtection = " [ None | Validation | Encryption | All ] "
        cookieRequireSSL = "[ true | false ] "
        cookieSlidingExpiration = " [ true | false ] "
        cookieTimeout = " [ DD: HH : SS ] "
        domain = "cookie domain" 
    />
    
    Here,

    Cookieless is used to state the storage of user information of the anonymous user in a cookie. The following values can be used as parameters.
    1. UseUri : It saves the information of the identification number of the user in the URL using the anonymous user request for the web site.
    2. UseCookies: It saves the information of the identification number of the anonymous user in the cookie
    3. AutoDetect: It determines the browser of the anonymous user with the computer supporting the cookie. If the browser supports the cookies, the identification number for the cookie is stored.
    4. UseDeviceProfile: It saves the identification number of the user in a cookie or the URL.
    cookieName: It specifies the cookie name used for saving the information of the anonymous user.

    cookiePath: It states the location of the cookie saving the information of the anonymous user. The default directory is states using the ‘/’.

    cookieProtection: It saves the user information stored in the cookie. The following values can be specified.
    1. None: It states that no encryption or validation is applied to the anonymous user
    2. Encryption: It encrypts the anonymous user information saves in cookie
    3. All: It encrypts and validates the user information stored in the cookie
    4. Validation: It ensures that the information is not modified during the data transmission.
    cookiesRequireSSL: It checks whether a Secure Socket Layer ( SSL ) connection is needed.

    cookieSlidingExpiration: It specifies the time after which the expiration of the cookies is refreshed.

    cookieTimeout: It specifies the expiration time of the cookie. The value is specified in minutes

    Domain: It states the name of the cookie domain.

    Authenticated Profiles



    Once the user registers itself it becomes an authenticated user. The authenticated user can access or view the information by logging in the web site. When the anonymous user logins the web site, it cannot access the account specific information. The web site shows the account specific information when user logs in.

    User can provide various attributes using the <add> element in the configuration file. The allowAnonymous attribute is set to true for storing the information of the anonymous user.

    User Profile Creation



    User can create user profiles for personalizing the web site using the following steps.
    1. Create a web site in Visual Studio application.
    2. In the Web.config file, add the properties of the profile
      Code:
      <configuration>
          <system.web>
              <authentication mode="Forms" />
              <anonymousIdentification enabled="true" />
              <profile>
              <properties>
                  <add name="RollNo" allowAnonymous="true"  defaultValue="10" />
                  <add name="Subject" allowAnonymous="true" defualtValue="ASP.NET" />
                  <add name="Name" allowAnonymous="true" />
              </properties>
              </profile>
          </system.web>
      </configuration>
      
    3. Add the mentioned code in the Defualt.aspx file.
      Code:
      <body>
      <form id="form1" runat="server">
      <div>
      <b>Welcome</b><%=Profile.Name%>
      <br/>
      <b>RollName</b><%=Profile.RollNo%>
      <br/>
      <b>Subject</b><%=Profile.Subject%>
      <br/>
      <b>Name:</b>
      <asp:TextBox ID="txt1" runat="server" />
      <br/>
      <b>RollNo: </b>
      <asp:TextBox ID="txt2" runat="server" />
      <br/>
      <b>Course:</b>
      <asp:TextBox ID="txt3" runat="server" />
          <br/>
      <asp:Button ID="btn1" runat="server" Text="show" OnClick ="btn1_click()" />
          </div>
      </form>
      </body>
      
    4. In the code behind file, add the following code.
      Code:
      using System;
      using System.Text;
      
      protected void btn1_Click ( object sender, EventArgs e)
      {
          Profile.Name=txt1.Text;
          Profile.RollNo = txt2.Text;
          Profile.Subject = txt3.Text;
      }
      
    5. Execute the application and the following output is displayed.

      [​IMG]
    6. Add the values for Name, RollNo and subject. Click on the show button and the new values are displayed.

      [​IMG]
    7. Once the user closes the web page, visits the page next time, the following information is displayed.

      [​IMG]

    Complex Data Types



    User can use the complex data types for defining the profile information. The following steps are used for demonstrating the complex types.
    1. Create a web site in visual studio, add the following information in the Web.config file.
      Code:
      <configuration>
          <system.web>
          <authentication mode="Forms" />
          <anonymousIdentification enabled="true" />
          <profile>
              <properties>
              <add name="Name" allowAnonymous="true" />
              <add name="DOJ" type="JoiningDetails" allowAnonymous="true" />
              </properties>
          </profile>
          <compilation debug="true" targetFrameowrk="4.0" />
          </system.web>
      </configuration>
      
    2. Add the following code in the Defualt.aspx page.
      Code:
      <form>
          <div>
          <b>Welcome</b><%=Profile.Name%>
          <br/>
          <b>DOJ</b><%=Profile.DOJ.Day%><%=Profile.DOJ.Month%><%=Profile.DOJ.Year%>
          <br/>
          EmpName: 
          <asp:TextBox ID="txt1" runat="server"></asp:TextBox>
          <br/>
      
          <b>Day:</b>
          <asp:TextBox ID="txt2" runat="server"></asp:TextBox>
          <br/>
      
          <b>Month:</b>
          <asp:TextBox ID="txt3" runat="server"></asp:TextBox>
          <br/>
          
          <b>Year:</b>
          <asp:TextBox ID="txt4" runat="server"></asp:TextBox>
          <br/>
      
          <asp:Button ID="btn1" runat="server" Text="Display" OnClick = "btn1_click" />
          </div>
      </form>
      
    3. In the code behind file, add the following code.
      Code:
      protected void btn1_click ( object sender, EventArgs e)
      {
          Profile.Name = txt1.Text;
          Profile.DOJ.Day = txt2.Text;
          Profile.DOJ.Month = txt3.Text;
          Profile.DOJ.Year = txt4.Text;
      }
      
    4. Add a class as JoiningDetails.cs and add the code in it.
      Code:
      using System;
      using System.Colleciton.Generic;
      using System.Linq;
      
      public class JoiningDetails
      {
          private string day;
          private string month;
          private string year;
          
          public string Day
          {
              get
              {
                  return day;
              }
              set
              {
                  day = value;
              }
          }
      
          public string Month
          {
              get
              {
                  return month;
              }
              set
              {
                  month = value;
              }
          }
      
          public string Year
          {
              get
              {
                  return year;
              }
              set
              {
                  year = value;
              }
          }
      
      }
      
    5. Execute application by pressing F5 key. Enter the values in the textboxes and click the Display button.

      [​IMG]
    6. When user closes the website and visits it again, the web page shows the personalized information entered by the user.

      [​IMG]

    Profile Migration



    There are is situation when anonymous user visits a web site and changes the profile information according to user requirements. Once the user starts using the web site, he becomes the authenticated user. The profile is saved on the basis of the identification number; it is lost when the anonymous user becomes an authenticated user.

    User can handle the situations by moving the information of the anonymous profile to the authenticated profile. User can perform the profile settings when he log into the web site.

    The steps for migrating information from the anonymous profile to the authenticated profile are as mentioned below:
    1. Create an ASP.NET website and add the following code.
      Code:
      <configuration>
          <system.web>
              <authorization>
                  <deny users=?" />
              </authorization>
              <anonymousIdentification enabled="true" />
              <profile>
                  <properties>
                  <add name ="University" allowAnonymous="true" defaultValue="Harward" />
                  <add name="Courses" allowAnonymous="true" defualtValue="Management" />
                  </properties>
              </profile>
              <authentication mode="Forms" />
          </system.web>
      </configuration>
      
    2. Create two web pages as StudentLogin.aspx and NewUser.aspx.
    3. In the StudentLogin.aspx page, add the following code.
      Code:
      <form id="form1" runat="server" >
      <div>
          <asp:Login ID="login1" runat="server" BorderPadding="4" BorderStyle="Dashed" Height="120px" Width="200px" DestinationPageUrl="~/NewUser.aspx" >
          </asp:Login>
          <br/>
          University:<b><%=Profile.University%></b>
          <br/>
          Courses:<b><%=Profile.Courses%></b>
      </div>
      </form>
      
    4. In the NewUser.aspx page, add the following code.
      Code:
      <div>
      <asp:Label ID="lbl1" runat="server" Text="Welcome" />
          <asp:LoginName ID="login1" runat="server" />
          <br/>
          <asp:LoginStatus ID="lgnstat1" runat="server" LogoutPageUrl="~/StudentLogin.aspx" />
          <br/>
          University:<b><%=Profile.University%></b>
          <br/>
          Courses:<b><%=Profile.Courses%></b>
      </div>
      
    5. In the Global.asax file, add the following code
      Code:
      <%@Application Language="C#" %>
      <script runat="server">
      void Profile_Migrate( object s, ProfileMigrateEventArgs e )
      {
          ProfileCommon prf1 = Profile.GetProfile(e.AnonymousID);
          Profile.University = prf1.University;
          Profile.Courses = prf1.Courses;
      }
      
     

Share This Page