Recipe 10.5. Managing User Profiles


Problem

You want to provide a mechanism to periodically remove user profile data that is no longer being used.

Solution

Use the ProfileManager class to find inactive profiles, display them in an ASP.NET page for the manager to review, and then use the ProfileManager to delete the desired profiles.

In the .aspx file:

  1. Add a drop-down list or other control to allow selection of the authentication option.

  2. Add a drop-down list or other control to allow selection of the inactive period.

  3. Add a button to initiate the search for the profile.

  4. Add a GridView to display the profiles matching the search parameters.

  5. Provide the ability to delete one or more profiles.

In the code-behind class for the page, use the .NET language of your choice as follows:

  1. Initialize the authentication option drop-down control with the available options.

  2. Initialize the inactive period drop-down control with the available options.

  3. In the event handler for the Search button click event, use the GetAllInactive-Profiles method of the ProfileManager class to get the profiles matching the search parameters and then bind the profile data to a GridView.

  4. In the event handler for the Delete All button click event, use the DeleteInactiveProfiles method of the ProfileManager class to delete the displayed profiles.

The code we have created to illustrate this solution is shown in Examples 10-11, 10-12 through 10-13. Example 10-11 shows the .aspx file for the page used to manage profiles. The code-behind classes for the page are shown in Examples 10-12 (VB) and 10-13 (C#). The output of the page used to manage profiles is shown in Figures 10-1 (before searching) and 10-2 (after searching).

Discussion

The Profile provider supplied by Microsoft with ASP.NET 2.0 permanently stores the profile data for anonymous and authenticated user profiles. Depending on the number of users of your application and the number of those who are recurring users, a large number of inactive profiles may be stored in your database. To keep the performance of your application at its peak, you should periodically remove unused profiles.

Figure 10-1. Managing profiles page before performing search


Figure 10-2. Managing profiles page after performing search


ASP.NET 2.0 provides the ability to manage profiles with the ProfileManager class. This class gives you the ability to find profiles matching selected criteria and to delete them using the same criteria or by culling them from a list of users.

In the example we have written to illustrate this solution, we have created a page that provides the ability for the user to enter the authentication type and the number of inactive months. When the user clicks the Search button, the last activity date is calculated from the number of inactive months selected in the Search button event handler. The GetAllInactiveProfiles method of the ProfileManager class is then called, passing the authentication type and the last activity date.

The GetAllInactiveProfiles method returns a ProfileInfoCollection that can be bound to a GridView or other grid control as shown in Examples 10-12 (VB) and 10-13 (C#).

The ProfileManager class has an overloaded GetAllInactiveProfiles method that fully supports paginating data. It provides the ability to pass the page size and desired page number to allow retrieving a single page of profiles. In addition, it has a TotalRecords parameter that returns the total number of profiles meeting the search criteria.


We store the search parameters in the ViewState to use when the user clicks the Delete All button. By storing the parameters used to display the data, we ensure the deleted profiles are the ones being displayed. If we used the selections from the dropdowns on the form, the user may have changed the selection, which would result in a different set of profiles being deleted.

When the user clicks the Delete All button, the search parameters stored in the ViewState are retrieved from the ViewState in the Delete All button event handler. The DeleteInactiveProfiles method of the ProfileManager class is then called, passing the search parameters retrieved from the ViewState.

The DeleteInactiveProfiles method returns the number of profiles deleted. Next, we hide the GridView and display a message indicating the number of profiles deleted.

Like the other delete profile methods of the ProfileManager class, the DeleteInactiveProfile method deletes only the user profile data. It does not delete the user data from the database. If you want to delete the user data in addition to the profile data, you will need to use the DeleteUser method of the Membership class.


See Also

Recipe 10.1

Example 10-11. Managing profiles (.aspx)

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master" AutoEventWireup="false" CodeFile="CH10ManagingUserProfilesVB.aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH10ManagingUserProfilesVB" Theme="Blue" Title="Managing User Profiles" %> <asp:Content  runat="server" ContentPlaceHolder> <div align="center" > Managing User Profiles (VB) </div> <div align="center" > Profile Search Parmeters </div> <br /> <table width="60%" align="center" border="0" cellpadding="2"> <tr> <td  align="right">Authentication Option: </td> <td> <asp:DropDownList  runat="server" Css /> </td> </tr> <tr> <td  align="right">Months of Inactivity: </td> <td> <asp:DropDownList  runat="server" Css /> </td> </tr> <tr> <td colspan="2" align="center"> <br /> <asp:Button  runat="server" Text="Search" OnClick="btnSearch_Click" /> </td> </tr> </table> <div  runat="server" align="center"> <br /> <asp:GridView  runat="server" BorderColor="#000080" BorderWidth="2px" AutoGenerateColumns="False" HorizontalAlign="center" Width="90%" CellPadding="2" > <HeaderStyle HorizontalAlign="Center" Css /> <RowStyle css /> <AlternatingRowStyle css /> <Columns> <asp:BoundField DataField="UserName" HeaderText="User Name" /> <asp:BoundField DataField="LastActivityDate" HeaderText="Last Activity" /> <asp:BoundField DataField="LastUpdatedDate" HeaderText="Last Updated" /> <asp:BoundField DataField="Size" HeaderText="Size" /> <asp:BoundField DataField="IsAnonymous" HeaderText="Anonymous" /> </Columns> </asp:GridView> <br /> <asp:Button  runat="server"   Text="Delete All"   OnClick="btnDeleteAll_Click" /> </div> <div  runat="server" align="center" > <br /> <asp:Literal  runat="server" /> </div> </asp:Content> 

Example 10-12. Managing profiles code-behind (.vb)

 Option Explicit On Option Strict On Namespace ASPNetCookbook.VBExamples ''' <summary> ''' This class provides the code behind for ''' CH10ManagingUserProfilesVB.aspx ''' </summary> Partial Class CH10ManagingUserProfilesVB   Inherits System.Web.UI.Page   'the following constants define the name of variables in the ViewState   'used to store the search criteria for the currently displayed   'profile data   Private Const VS_AUTHENTICATION_OPTION As String = "AuthenticationOption"   Private Const VS_LAST_ACTIVITY_DATE As String = "lastActivityDate"   '''***********************************************************************   ''' <summary>   ''' This routine provides the event handler for the page load event. It   ''' is responsible for initializing the controls on the page.   ''' </summary>   '''   ''' <param name="sender">Set to the sender of the event</param>   ''' <param name="e">Set to the event arguments</param>   Private Sub Page_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load Dim item As ListItem If (Not Page.IsPostBack) Then 'add items to the authentication option dropdown ddAuthenticationOptions.Items.Clear() item = New ListItem("All", _   (CInt(ProfileAuthenticationOption.All)).ToString()) ddAuthenticationOptions.Items.Add(item) item = New ListItem("Anonymous", _ (CInt(ProfileAuthenticationOption.Anonymous)).ToString()) ddAuthenticationOptions.Items.Add(item) item = New ListItem("Authenticated", _ (CInt(ProfileAuthenticationOption.Authenticated)).ToString()) ddAuthenticationOptions.Items.Add(item) 'add itesm to the "months of inactivity" dropdown ddInactiveMonths.Items.Clear() item = New ListItem("0", "0") ddInactiveMonths.Items.Add(item) item = New ListItem("3", "3") ddInactiveMonths.Items.Add(item) item = New ListItem("6", "6") ddInactiveMonths.Items.Add(item) item = New ListItem("12", "12") ddInactiveMonths.Items.Add(item) 'select the "12 months" entry ddInactiveMonths.SelectedIndex = ddInactiveMonths.Items.Count - 1 'initially hide the grid and message panels divProfiles.Visible = False divMessage.Visible = False End If End Sub 'Page_Load '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the search button click ''' event. It is responsible for searching for and displaying the ''' profiles matching the selected criteria ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Protected Sub btnSearch_Click(ByVal sender As Object, _  ByVal e As System.EventArgs) Dim inactiveMonths As Integer Dim lastActivityDate As DateTime = DateTime.MinValue Dim profileData As ProfileInfoCollection Dim authenticationOption As ProfileAuthenticationOption authenticationOption = CType(ddAuthenticationOptions.SelectedValue, _  ProfileAuthenticationOption) 'calculate the last activity date inactiveMonths = CInt(ddInactiveMonths.SelectedValue) lastActivityDate = DateTime.Now.AddMonths(-inactiveMonths) 'get profiles matching authentication option and last activity date profileData = _   ProfileManager.GetAllInactiveProfiles(authenticationOption, _     lastActivityDate) 'check to see if any profiles match the selected criteria If (profileData.Count = 0) Then   divProfiles.Visible = False   divMessage.Visible = True   litMessage.Text = "No profiles were found matching the entered criteria" Else   divProfiles.Visible = True   divMessage.Visible = False   gvProfiles.DataSource = profileData   gvProfiles.DataBind() End If 'store the search criteria in the ViewState to support deleting 'profiles when required 'NOTE: The data is stored to ensure it matches the displayed '    profiles to handle the case where the user changes the '    criteria and then clicks the delete all button ViewState(VS_AUTHENTICATION_OPTION) = authenticationOption ViewState(VS_LAST_ACTIVITY_DATE) = lastActivityDate End Sub 'btnSearch_Click '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the delete all button ''' click event. It is responsible for deleting the displayed profiles ''' </summary>  ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Protected Sub btnDeleteAll_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Dim lastActivityDate As DateTime Dim authenticationOption As ProfileAuthenticationOption Dim profilesDeleted As Integer 'get the search criteria used to display the current data lastActivityDate = CDate(ViewState(VS_LAST_ACTIVITY_DATE)) authenticationOption = CType(ViewState(VS_AUTHENTICATION_OPTION), _  ProfileAuthenticationOption) 'delete the profiles profilesDeleted = _   ProfileManager.DeleteInactiveProfiles(authenticationOption, _ lastActivityDate) 'hide the grid and output message indicating the number of 'profiles deleted divProfiles.Visible = False divMessage.Visible = True litMessage.Text = profilesDeleted.ToString() & _   " Profile(s) were deleted" End Sub 'btnDeleteAll_Click   End Class 'CH10ManagingUserProfilesVB End Namespace 

Example 10-13. Managing profiles code-behind (.cs)

 using System; using System.Web.UI.WebControls; using System.Web.Profile; namespace ASPNetCookbook.CSExamples { /// <summary> /// This class provides the code behind for /// CH10ManagingUserProfilesCS.aspx /// </summary> public partial class CH10ManagingUserProfilesCS : System.Web.UI.Page {   // the following constants define the name of variables in the ViewState   // used to store the search criteria for the currently displayed   // profile data   private const String VS_AUTHENTICATION_OPTION = "AuthenticationOption";   private const String VS_LAST_ACTIVITY_DATE = "lastActivityDate";   ///***********************************************************************   /// <summary>   /// This routine provides the event handler for the page load event.   /// It is responsible for initializing the controls on the page.   /// </summary>   ///   /// <param name="sender">Set to the sender of the event</param>   /// <param name="e">Set to the event arguments</param>   protected void Page_Load(object sender, EventArgs e)   {     ListItem item; if (!Page.IsPostBack) {   // add items to the authentication option dropdown   ddAuthenticationOptions.Items.Clear();   item = new ListItem("All", ((int)ProfileAuthenticationOption.All).ToString());   ddAuthenticationOptions.Items.Add(item);   item = new ListItem("Anonymous", ((int)ProfileAuthenticationOption.Anonymous).ToString());   ddAuthenticationOptions.Items.Add(item);   item = new ListItem("Authenticated", ((int)ProfileAuthenticationOption.Authenticated).ToString());   ddAuthenticationOptions.Items.Add(item);   // add itesm to the "months of inactivity" dropdown   ddInactiveMonths.Items.Clear();   item = new ListItem("0", "0");   ddInactiveMonths.Items.Add(item);   item = new ListItem("3", "3");   ddInactiveMonths.Items.Add(item);   item = new ListItem("6", "6");   ddInactiveMonths.Items.Add(item);   item = new ListItem("12", "12");   ddInactiveMonths.Items.Add(item);   // select the "12 months" entry   ddInactiveMonths.SelectedIndex = ddInactiveMonths.Items.Count - 1;   // initially hide the grid and message panels   divProfiles.Visible = false;   divMessage.Visible = false; } } // Page_Load ///*********************************************************************** /// <summary> /// This routine provides the event handler for the search button click /// event. It is responsible for searching for and displaying the /// profiles matching the selected criteria /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void btnSearch_Click(Object sender,   System.EventArgs e) {   int inactiveMonths;   DateTime lastActivityDate = DateTime.MinValue;   ProfileInfoCollection profileData;   ProfileAuthenticationOption authenticationOption;   authenticationOption = (ProfileAuthenticationOption)  (Convert.ToInt32(ddAuthenticationOptions.SelectedValue));  // calculate the last activity date  inactiveMonths = Convert.ToInt32(ddInactiveMonths.SelectedValue);  lastActivityDate = DateTime.Now.AddMonths(-inactiveMonths);  // get profiles matching authentication option and last activity date  profileData =    ProfileManager.GetAllInactiveProfiles(authenticationOption,  lastActivityDate);    // check to see if any profiles match the selected criteria    if (profileData.Count == 0)    {  divProfiles.Visible = false;  divMessage.Visible = true;  litMessage.Text = "No profiles were found matching the entered criteria";    }    else    {  divProfiles.Visible = true;  divMessage.Visible = false;  gvProfiles.DataSource = profileData;  gvProfiles.DataBind();    }    // store the search criteria in the ViewState to support deleting    // profiles when required    // NOTE: The data is stored to ensure it matches the displayed    // profiles to handle the case where the user changes the    // criteria and then clicks the delete all button    ViewState[VS_AUTHENTICATION_OPTION] = authenticationOption;    ViewState[VS_LAST_ACTIVITY_DATE] = lastActivityDate; } // btnSearch_Click ///*********************************************************************** /// <summary> /// This routine provides the event handler for the delete all button /// click event. It is responsible for deleting the displayed profiles /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void btnDeleteAll_Click(Object sender,  System.EventArgs e) {    DateTime lastActivityDate;    ProfileAuthenticationOption authenticationOption;    int profilesDeleted;    // get the search criteria used to display the current data    lastActivityDate = (DateTime)(ViewState[VS_LAST_ACTIVITY_DATE]);    authenticationOption = (ProfileAuthenticationOption)   (ViewState[VS_AUTHENTICATION_OPTION]);    // delete the profiles    profilesDeleted =  ProfileManager.DeleteInactiveProfiles(authenticationOption,    lastActivityDate);    // hide the grid and output message indicating the number of    // profiles deleted    divProfiles.Visible = false;    divMessage.Visible = true;    litMessage.Text = profilesDeleted.ToString() +  " Profile(s) were deleted"; } // btnDeleteAll_Click   } // CH10ManagingUserProfilesCS } 



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net