ProfileManager 类

定义

管理用户配置文件数据和设置。

public ref class ProfileManager abstract sealed
public static class ProfileManager
type ProfileManager = class
Public Class ProfileManager
继承
ProfileManager

示例

下面的代码示例演示使用 类管理非活动配置文件的 ASP.NET 页 ProfileManager

重要

此示例包含一个接受用户输入的文本框,这是一个潜在的安全威胁。 默认情况下,ASP.NET 网页验证用户输入是否不包含脚本或 HTML 元素。 有关详细信息,请参阅脚本侵入概述

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Profile" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

int pageSize = 5;
int totalProfiles;
int totalPages;
int currentPage = 1;

ProfileAuthenticationOption authOption;
int inactiveDays = 120;
int deletedProfiles = 0;

public void Page_Load()
{
  DeletedMessage.Text = "";

  authOption = GetAuthenticationOption();

  if (!IsPostBack)
  {
    InactiveDaysTextBox.Text = inactiveDays.ToString();

    GetProfiles();
  }
  else
  {
    inactiveDays = Convert.ToInt32(InactiveDaysTextBox.Text);
  }
}

public void ProfileGrid_Delete(object sender, GridViewCommandEventArgs args)
{
  // Retrieve user name selected.

  int index = Convert.ToInt32(args.CommandArgument);

  string username = ProfileGrid.Rows[index].Cells[0].Text;

  ProfileManager.DeleteProfiles(new string[] {username});

  DeletedMessage.Text = "1 profile deleted.";

  // Refresh profile list.

  currentPage = Convert.ToInt32(CurrentPageLabel.Text);
  GetProfiles();
}


private void GetProfiles()
{
  ProfileGrid.DataSource = ProfileManager.GetAllInactiveProfiles(authOption,
                               DateTime.Now.Subtract(new TimeSpan(inactiveDays, 0, 0, 0)),
                               currentPage - 1, pageSize, out totalProfiles);

  TotalProfilesLabel.Text = totalProfiles.ToString();

  totalPages = ((totalProfiles - 1) / pageSize) + 1;

  // Ensure that we do not navigate past the last page of Profiles.

  if (currentPage > totalPages)
  {
    currentPage = totalPages;
    GetProfiles();
    return;
  }

  ProfileGrid.DataBind();
  CurrentPageLabel.Text = currentPage.ToString();
  TotalPagesLabel.Text = totalPages.ToString();

  if (currentPage == totalPages)
    NextButton.Visible = false;
  else
    NextButton.Visible = true;

  if (currentPage == 1)
    PreviousButton.Visible = false;
  else
    PreviousButton.Visible = true;

  if (totalProfiles <= 0)
    NavigationPanel.Visible = false;
  else
    NavigationPanel.Visible = true;
}

public void NextButton_OnClick(object sender, EventArgs args)
{
  currentPage = Convert.ToInt32(CurrentPageLabel.Text);
  currentPage++;
  GetProfiles();
}

public void PreviousButton_OnClick(object sender, EventArgs args)
{
  currentPage = Convert.ToInt32(CurrentPageLabel.Text);
  currentPage--;
  GetProfiles();
}

public void ModifyInactiveDaysButton_OnClick(object sender, EventArgs args)
{
  GetProfiles();
}

public void AuthenticationOptionListBox_OnSelectedIndexChanged(object sender, EventArgs args)
{
  authOption = GetAuthenticationOption();
  GetProfiles();
}

private ProfileAuthenticationOption GetAuthenticationOption()
{
  if (AuthenticationOptionListBox.SelectedItem != null)
  {
    switch (AuthenticationOptionListBox.SelectedItem.Value)
    {
      case "Anonymous":
        return ProfileAuthenticationOption.Anonymous;
        break;
      case "Authenticated":
        return ProfileAuthenticationOption.Authenticated;
        break;
      default:
        return ProfileAuthenticationOption.All;
        break;
    }
  }

  return ProfileAuthenticationOption.All;
}

public void DeleteAllInactiveButton_OnClick(object sender, EventArgs args)
{
  deletedProfiles = ProfileManager.DeleteInactiveProfiles(authOption, 
                        DateTime.Now.Subtract(new TimeSpan(inactiveDays, 0, 0 ,0)));
  DeletedMessage.Text = deletedProfiles.ToString() + " profiles deleted.";
  GetProfiles();
}

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Sample: Find Profiles</title>
</head>
<body>

<form id="form1" runat="server">
  <h3>Profile List</h3>

  <table border="0" cellpadding="3" cellspacing="3">
    <tr>
      <td valign="top">Authentication Option</td>
      <td valign="top"><asp:ListBox id="AuthenticationOptionListBox" rows="3" runat="Server"
                                    AutoPostBack="true"
                                    OnSelectedIndexChanged="AuthenticationOptionListBox_OnSelectedIndexChanged">
                         <asp:ListItem value="All" selected="True">All</asp:ListItem>
                         <asp:ListItem value="Authenticated">Authenticated</asp:ListItem>
                         <asp:ListItem value="Anonymous">Anonymous</asp:ListItem>
                       </asp:ListBox>
      </td>
    </tr>
    <tr>
      <td valign="top" style="width:160">
        Number of Days for Profile to be considered "inactive"</td>
      <td valign="top" style="width:200">
        <asp:TextBox id="InactiveDaysTextBox" runat="Server" MaxLength="3" Columns="3" />
        <asp:Button id="ModifyInactiveDaysButton" runat="server" Text="Refresh Results" 
           OnClick="ModifyInactiveDaysButton_OnClick" /><br />
        <asp:Button id="DeleteAllInactiveButton" runat="Server"
           Text="Delete All Inactive Profiles" OnClick="DeleteAllInactiveButton_OnClick" />
      </td>
      <td valign="top">
        <asp:RequiredFieldValidator id="InactiveDaysRequiredValidator" runat="server"
           ControlToValidate="InactiveDaysTextBox" ForeColor="red"
           Display="Static" ErrorMessage="Required" />
        <asp:RegularExpressionValidator id="InactiveDaysValidator" runat="server"
           ControlToValidate="InactiveDaysTextBox" ForeColor="red"
           Display="Static" ValidationExpression="[0-9]*" 
           ErrorMessage="Inactive Days must be a whole number less than 1000 (e.g. 30, 120)" />
     </td>
    </tr>
    <tr>
      <td><asp:Label id="DeletedMessage" runat="server" /></td>
      <td><asp:Label id="TotalProfilesLabel" runat="server" /> inactive profiles found.</td>
    </tr>
  </table>

    <asp:Panel id="NavigationPanel" Visible="false" runat="server">
    <table border="0" cellpadding="3" cellspacing="3">
      <tr>
        <td style="width:100">Page <asp:Label id="CurrentPageLabel" runat="server" />
            of <asp:Label id="TotalPagesLabel" runat="server" /></td>
        <td style="width:60"><asp:LinkButton id="PreviousButton" Text="< Prev"
                            OnClick="PreviousButton_OnClick" runat="server" /></td>
        <td style="width:60"><asp:LinkButton id="NextButton" Text="Next >"
                            OnClick="NextButton_OnClick" runat="server" /></td>
      </tr>
    </table>
  </asp:Panel>

  <asp:GridView id="ProfileGrid" runat="server" AutoGenerateColumns="false"
                OnRowCommand="ProfileGrid_Delete"
                CellPadding="2" CellSpacing="1" Gridlines="None">
    <HeaderStyle BackColor="darkblue" ForeColor="white" />
    <Columns>
      <asp:BoundField HeaderText="User Name" DataField="Username" />
      <asp:BoundField HeaderText="Is Anonymous" DataField="IsAnonymous" />
      <asp:BoundField HeaderText="Last Updated" DataField="LastUpdatedDate" />
      <asp:BoundField HeaderText="Last Activity" DataField="LastActivityDate" />
      <asp:ButtonField HeaderText="Action" Text="Delete" ButtonType="Link" />
    </Columns>
  </asp:GridView>

</form>

</body>
</html>
<%@ Page Language="VB" %>
<%@ Import Namespace="System.Web.Profile" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

Dim pageSize As Integer = 5
Dim totalProfiles As Integer 
Dim totalPages As Integer
Dim currentPage As Integer = 1

Dim authOption As ProfileAuthenticationOption
Dim inactiveDays As Integer = 120
Dim deletedProfiles As Integer = 0

Public Sub Page_Load()

  DeletedMessage.Text = ""

  authOption = GetAuthenticationOption()

  If Not IsPostBack Then  
    InactiveDaysTextBox.Text = inactiveDays.ToString()

    GetProfiles()
  Else
    inactiveDays = Convert.ToInt32(InactiveDaysTextBox.Text)
  End If
End Sub

Public Sub ProfileGrid_Delete(sender As Object, args As GridViewCommandEventArgs)
  ' Retrieve user name selected.

  Dim index As Integer = Convert.ToInt32(args.CommandArgument)

  Dim username As String = ProfileGrid.Rows(index).Cells(0).Text

  ProfileManager.DeleteProfiles(New string() {username})

  DeletedMessage.Text = "1 profile deleted."

  ' Refresh profile list.

  currentPage = Convert.ToInt32(CurrentPageLabel.Text)
  GetProfiles()
End Sub


Private Sub GetProfiles()
  ProfileGrid.DataSource = ProfileManager.GetAllInactiveProfiles(authOption, _
                               DateTime.Now.Subtract(New TimeSpan(inactiveDays, 0, 0, 0)), _
                               currentPage - 1, pageSize, totalProfiles)

  TotalProfilesLabel.Text = totalProfiles.ToString()

  totalPages = ((totalProfiles - 1) \ pageSize) + 1

  ' Ensure that we do not navigate past the last page of Profiles.

  If currentPage > totalPages Then  
    currentPage = totalPages
    GetProfiles()
    Return
  End If

  ProfileGrid.DataBind()
  CurrentPageLabel.Text = currentPage.ToString()
  TotalPagesLabel.Text = totalPages.ToString()

  If currentPage = totalPages Then
    NextButton.Visible = False
  Else
    NextButton.Visible = True
  End If

  If currentPage = 1 Then
    PreviousButton.Visible = False
  Else
    PreviousButton.Visible = True
  End If

  If totalProfiles <= 0 Then
    NavigationPanel.Visible = False
  Else
    NavigationPanel.Visible = True
  End If
End Sub

Public Sub NextButton_OnClick(sender As Object, args As EventArgs)
  currentPage = Convert.ToInt32(CurrentPageLabel.Text)
  currentPage += 1
  GetProfiles()
End Sub

Public Sub PreviousButton_OnClick(sender As Object, args As EventArgs)
  currentPage = Convert.ToInt32(CurrentPageLabel.Text)
  currentPage -= 1
  GetProfiles()
End Sub

Public Sub ModifyInactiveDaysButton_OnClick(sender As Object, args As EventArgs)
  GetProfiles()
End Sub

Public Sub AuthenticationOptionListBox_OnSelectedIndexChanged(sender As Object, args As EventArgs)
  authOption = GetAuthenticationOption()
  GetProfiles()
End Sub

Private Function GetAuthenticationOption() As ProfileAuthenticationOption 
  If Not AuthenticationOptionListBox.SelectedItem Is Nothing Then  
    Select Case AuthenticationOptionListBox.SelectedItem.Value
      Case "Anonymous"
        Return ProfileAuthenticationOption.Anonymous
      Case "Authenticated"
        return ProfileAuthenticationOption.Authenticated
      Case Else
        Return ProfileAuthenticationOption.All
    End Select
  End If

  Return ProfileAuthenticationOption.All
End Function

Public Sub DeleteAllInactiveButton_OnClick(sender As Object, args As EventArgs)
  deletedProfiles = ProfileManager.DeleteInactiveProfiles(authOption, _
                        DateTime.Now.Subtract(new TimeSpan(inactiveDays, 0, 0 ,0)))
  DeletedMessage.Text = deletedProfiles.ToString() & " profiles deleted."
  GetProfiles()
End SUb

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Sample: Find Profiles</title>
</head>
<body>

<form id="form1" runat="server">
  <h3>Profile List</h3>

  <table border="0" cellpadding="3" cellspacing="3">
    <tr>
      <td valign="top">Authentication Option</td>
      <td valign="top"><asp:ListBox id="AuthenticationOptionListBox" rows="3" runat="Server"
                                    AutoPostBack="True"
                                    OnSelectedIndexChanged="AuthenticationOptionListBox_OnSelectedIndexChanged">
                         <asp:ListItem value="All" selected="True">All</asp:ListItem>
                         <asp:ListItem value="Authenticated">Authenticated</asp:ListItem>
                         <asp:ListItem value="Anonymous">Anonymous</asp:ListItem>
                       </asp:ListBox>
      </td>
    </tr>
    <tr>
      <td valign="top" style="width:160">
        Number of Days for Profile to be considered "inactive"</td>
      <td valign="top" style="width:200">
        <asp:TextBox id="InactiveDaysTextBox" runat="Server" MaxLength="3" Columns="3" />
        <asp:Button id="ModifyInactiveDaysButton" runat="server" Text="Refresh Results" 
           OnClick="ModifyInactiveDaysButton_OnClick" /><br />
        <asp:Button id="DeleteAllInactiveButton" runat="Server"
           Text="Delete All Inactive Profiles" OnClick="DeleteAllInactiveButton_OnClick" />
      </td>
      <td valign="top">
        <asp:RequiredFieldValidator id="InactiveDaysRequiredValidator" runat="server"
           ControlToValidate="InactiveDaysTextBox" ForeColor="red"
           Display="Static" ErrorMessage="Required" />
        <asp:RegularExpressionValidator id="InactiveDaysValidator" runat="server"
           ControlToValidate="InactiveDaysTextBox" ForeColor="red"
           Display="Static" ValidationExpression="[0-9]*" 
           ErrorMessage="Inactive Days must be a whole number less than 1000 (e.g. 30, 120)" />
     </td>
    </tr>
    <tr>
      <td><asp:Label id="DeletedMessage" runat="server" /></td>
      <td><asp:Label id="TotalProfilesLabel" runat="server" /> inactive profiles found.</td>
    </tr>
  </table>

    <asp:Panel id="NavigationPanel" Visible="False" runat="server">
    <table border="0" cellpadding="3" cellspacing="3">
      <tr>
        <td style="width:100">Page <asp:Label id="CurrentPageLabel" runat="server" />
            of <asp:Label id="TotalPagesLabel" runat="server" /></td>
        <td style="width:60"><asp:LinkButton id="PreviousButton" Text="< Prev"
                            OnClick="PreviousButton_OnClick" runat="server" /></td>
        <td style="width:60"><asp:LinkButton id="NextButton" Text="Next >"
                            OnClick="NextButton_OnClick" runat="server" /></td>
      </tr>
    </table>
  </asp:Panel>

  <asp:GridView id="ProfileGrid" runat="server" AutoGenerateColumns="False"
                OnRowCommand="ProfileGrid_Delete"
                CellPadding="2" CellSpacing="1" Gridlines="None">
    <HeaderStyle BackColor="darkblue" ForeColor="white" />
    <Columns>
      <asp:BoundField HeaderText="User Name" DataField="Username" />
      <asp:BoundField HeaderText="Is Anonymous" DataField="IsAnonymous" />
      <asp:BoundField HeaderText="Last Updated" DataField="LastUpdatedDate" />
      <asp:BoundField HeaderText="Last Activity" DataField="LastActivityDate" />
      <asp:ButtonField HeaderText="Action" Text="Delete" ButtonType="Link" />
    </Columns>
  </asp:GridView>

</form>

</body>
</html>

注解

ASP.NET 配置文件用于在数据源(如数据库)中存储和检索用户设置。 使用 Profile 当前 HttpContext的 属性访问用户配置文件。 配置文件信息和属性值使用配置文件提供程序进行管理。

ProfileManager 用于管理配置文件设置、搜索用户配置文件以及删除不再使用的用户配置文件。 类 ProfileManager 提供静态方法和属性,可通过在应用程序代码中引用 ProfileManager 类来访问这些方法和属性。 有关示例,请参阅本主题中的示例部分,以及有关类成员 ProfileManager 的主题中的其他示例。

默认情况下,对所有 ASP.NET 应用程序禁用用户配置文件。 若要启用用户配置文件,请将enabled配置文件配置元素的 属性设置为 true,如以下示例所示。

<configuration>
  <system.web>
    <profile enabled="true" />
  </system.web>
</configuration>

有关用户配置文件的详细信息,请参阅 ASP.NET 配置文件属性概述

配置文件提供程序用于存储和检索用户配置文件中的属性。 .NET Framework包含一个SqlProfileProvider类,该类将用户配置文件属性存储在SQL Server数据库中。 名为 SqlProfileProviderAspNetSqlProvider 实例在计算机配置中指定为默认配置文件提供程序。 实例AspNetSqlProvider连接到本地 Web 服务器上的 SQL Server 数据库。 可以使用提供程序配置元素defaultProvider配置文件配置元素的 属性将SqlProfileProvider连接到另一SQL Server指定为默认配置文件提供程序,如以下示例所示。

<configuration>
  <connectionStrings>
    <add name="SqlServices" connectionString=
      "Data Source=MySqlServer;Integrated Security=SSPI;Initial Catalog=aspnetdb;" />
  </connectionStrings>
  <system.web>
    <profile defaultProvider="SqlProvider">
      <providers>
        <clear />
        <add name="SqlProvider"
          type="System.Web.Profile.SqlProfileProvider"
          connectionStringName="SqlServices"
          applicationName="MyApplication" />
      </providers>
    </profile>
  </system.web>
</configuration>

属性

ApplicationName

获取或设置要存储和检索其配置文件信息的应用程序的名称。

AutomaticSaveEnabled

获取一个值,该值指示是否将在 ASP.NET 页执行结束时自动保存用户配置文件。

Enabled

获取一个值,该值指示是否为应用程序启用用户配置文件。

Provider

获取对应用程序的默认配置文件提供程序的引用。

Providers

获取 ASP.NET 应用程序的配置文件提供程序的集合。

方法

AddDynamicProfileProperty(ProfilePropertySettings)

以编程方式添加配置文件属性。

DeleteInactiveProfiles(ProfileAuthenticationOption, DateTime)

删除上次活动日期和时间出现在指定日期和时间之前的用户配置文件数据。

DeleteProfile(String)

从数据源中删除指定用户名的配置文件。

DeleteProfiles(ProfileInfoCollection)

从数据源中删除提供的一系列配置文件的配置文件属性和信息。

DeleteProfiles(String[])

删除提供的一系列用户名的配置文件属性和信息。

FindInactiveProfilesByUserName(ProfileAuthenticationOption, String, DateTime)

检索所有配置文件的配置文件信息,在这些配置文件中,上次活动日期与指定的日期和时间相同或在其之前,而且配置文件的用户名与指定的名称匹配。

FindInactiveProfilesByUserName(ProfileAuthenticationOption, String, DateTime, Int32, Int32, Int32)

以分页数据的形式检索一些配置文件的配置文件信息,在这些配置文件中,上次活动日期与指定的日期和时间相同或在其之前,而且配置文件的用户名与指定的名称匹配。

FindProfilesByUserName(ProfileAuthenticationOption, String)

检索用户名与指定名称匹配的配置文件的所有配置文件信息。

FindProfilesByUserName(ProfileAuthenticationOption, String, Int32, Int32, Int32)

以分页数据的形式检索用户名与指定名称匹配的配置文件的配置文件信息。

GetAllInactiveProfiles(ProfileAuthenticationOption, DateTime)

对于上次活动日期与指定的日期和时间相同或在其之前的配置文件,检索它们的所有用户配置文件数据。

GetAllInactiveProfiles(ProfileAuthenticationOption, DateTime, Int32, Int32, Int32)

对于上次活动日期与指定的日期和时间相同或在其之前的用户配置文件,检索它们的 ProfileInfo 对象的页面。

GetAllProfiles(ProfileAuthenticationOption)

在数据源中检索配置文件的用户配置文件数据。

GetAllProfiles(ProfileAuthenticationOption, Int32, Int32, Int32)

检索用户配置文件数据的页面。

GetNumberOfInactiveProfiles(ProfileAuthenticationOption, DateTime)

获取上次活动日期与指定日期相同或在其之前的配置文件的数目。

GetNumberOfProfiles(ProfileAuthenticationOption)

获取数据源中的配置文件数量。

适用于

另请参阅