ITrackingPersonalizable 接口

定义

允许 Web 部件控件跟踪个性化加载和保存过程的特定阶段。

public interface class ITrackingPersonalizable
public interface ITrackingPersonalizable
type ITrackingPersonalizable = interface
Public Interface ITrackingPersonalizable
派生

示例

下面的代码示例演示如何使用 ITrackingPersonalizable 方法和属性来跟踪个性化信息的加载和保存。 该示例由两个部分组成:一个.aspx页和一个应放置在App_Code子目录中的文件。

下面的代码示例创建一个 Web 部件控件,该控件允许用户输入 URL 信息并为用户保存此信息。

namespace PersTest
{

    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Drawing;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;

    public class UrlListWebPart : WebPart, IPersonalizable
    {

        private ArrayList _sharedUrls;
        private ArrayList _userUrls;
        private bool _listDirty;

        private TextBox _nameTextBox;
        private TextBox _urlTextBox;
        private Button _addButton;
        private BulletedList _list;

        public override string Subtitle
        {
            get
            {
                return Text;
            }
        }

        [Personalizable, WebBrowsable]
        public virtual string Text
        {
            get
            {
                object o = ViewState["Text"];
                return (o != null) ? (String)o : "My Links";
            }
            set
            {
                ViewState["Text"] = value;
            }
        }

        protected override void CreateChildControls()
        {
            Label nameLabel = new Label();
            Label urlLabel = new Label();
            LiteralControl breakLiteral1 = new LiteralControl("<br />");
            LiteralControl breakLiteral2 = new LiteralControl("<br />");
            LiteralControl breakLiteral3 = new LiteralControl("<br />");

            _nameTextBox = new TextBox();
            _urlTextBox = new TextBox();
            _addButton = new Button();
            _list = new BulletedList();

            nameLabel.Text = "Name: ";
            urlLabel.Text = "URL: ";
            _nameTextBox.ID = "nameTextBox";
            _urlTextBox.ID = "urlTextBox";
            _addButton.Text = "Add";
            _addButton.ID = "addButton";
            _addButton.Click += new EventHandler(this.OnClickAddButton);
            _list.DisplayMode = BulletedListDisplayMode.HyperLink;
            _list.ID = "list";

            Controls.Add(nameLabel);
            Controls.Add(_nameTextBox);
            Controls.Add(breakLiteral1);

            Controls.Add(urlLabel);
            Controls.Add(_urlTextBox);
            Controls.Add(breakLiteral2);

            Controls.Add(_addButton);
            Controls.Add(breakLiteral3);

            Controls.Add(_list);
        }

        private void OnClickAddButton(object sender, EventArgs e)
        {
            string name = _nameTextBox.Text.Trim();
            string url = _urlTextBox.Text.Trim();

            Pair p = new Pair(name, url);
            if (WebPartManager.Personalization.Scope == PersonalizationScope.Shared)
            {
                _sharedUrls ??= new ArrayList();
                _sharedUrls.Add(p);
            }
            else
            {
                _userUrls ??= new ArrayList();
                _userUrls.Add(p);
            }

            OnUrlAdded();
        }

        protected virtual void OnUrlAdded()
        {
            _listDirty = true;
            ChildControlsCreated = false;
        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            if (_sharedUrls != null)
            {
                foreach (Pair p in _sharedUrls)
                {
                    _list.Items.Add(new ListItem((string)p.First, (string)p.Second));
                }
            }
            if (_userUrls != null)
            {
                foreach (Pair p in _userUrls)
                {
                    _list.Items.Add(new ListItem((string)p.First, (string)p.Second));
                }
            }

            base.RenderContents(writer);
        }

        public virtual bool IsDirty
        {
            get
            {
                return _listDirty;
            }
        }
        public new virtual void Load(PersonalizationDictionary state)
        {
            if (state != null)
            {
                PersonalizationEntry sharedUrlsEntry = state["sharedUrls"];
                if (sharedUrlsEntry != null)
                {
                    _sharedUrls = (ArrayList)sharedUrlsEntry.Value;
                }

                PersonalizationEntry userUrlsEntry = state["userUrls"];
                if (userUrlsEntry != null)
                {
                    _userUrls = (ArrayList)userUrlsEntry.Value;
                }
            }
        }

        public virtual void Save(PersonalizationDictionary state)
        {
            if ((_sharedUrls != null) && (_sharedUrls.Count != 0))
            {
                state["sharedUrls"] = new PersonalizationEntry(_sharedUrls, PersonalizationScope.Shared);
            }
            if ((_userUrls != null) && (_userUrls.Count != 0))
            {
                state["userUrls"] = new PersonalizationEntry(_userUrls, PersonalizationScope.User);
            }
        }
    }

    public class UrlListExWebPart : UrlListWebPart, ITrackingPersonalizable
    {

        private string _trackingLog = String.Empty;
        private bool _loading;
        private bool _saving;

        public override string Text
        {
            get
            {
                return base.Text;
            }
            set
            {
                if (base.Text.Equals(value) == false)
                {
                    base.Text = value;
                    SetPersonalizationDirty();
                }
            }
        }
        protected override void OnUrlAdded()
        {
            base.OnUrlAdded();
            SetPersonalizationDirty();
        }
        protected override void RenderContents(HtmlTextWriter writer)
        {
            base.RenderContents(writer);

            writer.Write("<br />");
            writer.Write("<pre id=\"" + ClientID + "$log" + "\">");
            writer.Write(_trackingLog);
            writer.Write("</pre>");
        }

        public override void Load(PersonalizationDictionary state)
        {
            if (_loading == false)
            {
                throw new InvalidOperationException();
            }
        }

        public override void Save(PersonalizationDictionary state)
        {
            if (_saving == false)
            {
                throw new InvalidOperationException();
            }
            base.Save(state);
        }
        bool ITrackingPersonalizable.TracksChanges
        {
            get
            {
                return true;
            }
        }
        void ITrackingPersonalizable.BeginLoad()
        {
            _loading = true;
            _trackingLog = "1. BeginLoad\r\n";
        }
        void ITrackingPersonalizable.BeginSave()
        {
            _saving = true;
            _trackingLog += "3. BeginSave\r\n";
        }
        void ITrackingPersonalizable.EndLoad()
        {
            _loading = false;
            _trackingLog += "2. EndLoad\r\n";
        }
        void ITrackingPersonalizable.EndSave()
        {
            _saving = false;
            _trackingLog += "4. EndSave";
        }
    }
}



Imports System.Collections
Imports System.ComponentModel
Imports System.Diagnostics
Imports System.Drawing
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts


Namespace PersTest
    Public Class UrlListWebPart
        Inherits WebPart
        Implements IPersonalizable

        Private _sharedUrls As ArrayList
        Private _userUrls As ArrayList
        Private _listDirty As Boolean

        Private _nameTextBox As TextBox
        Private _urlTextBox As TextBox
        Private _addButton As Button
        Private _list As BulletedList


        Public Overrides ReadOnly Property Subtitle() As String
            Get
                Return [Text]
            End Get
        End Property


        <Personalizable(), WebBrowsable()> _
        Public Overridable Property [Text]() As String
            Get
                Dim o As Object = ViewState("Text")
                If o Is Nothing Then
                    Return "My Links"
                Else
                    Return CType(o, String)
                End If

            End Get
            Set(ByVal value As String)
                ViewState("Text") = value
            End Set
        End Property


        Protected Overrides Sub CreateChildControls()
            Dim nameLabel As New Label()
            Dim urlLabel As New Label()
            Dim breakLiteral1 As New LiteralControl("<br />")
            Dim breakLiteral2 As New LiteralControl("<br />")
            Dim breakLiteral3 As New LiteralControl("<br />")

            _nameTextBox = New TextBox()
            _urlTextBox = New TextBox()
            _addButton = New Button()
            _list = New BulletedList()

            nameLabel.Text = "Name: "
            urlLabel.Text = "URL: "
            _nameTextBox.ID = "nameTextBox"
            _urlTextBox.ID = "urlTextBox"
            _addButton.Text = "Add"
            _addButton.ID = "addButton"
            AddHandler _addButton.Click, AddressOf Me.OnClickAddButton
            _list.DisplayMode = BulletedListDisplayMode.HyperLink
            _list.ID = "list"

            Controls.Add(nameLabel)
            Controls.Add(_nameTextBox)
            Controls.Add(breakLiteral1)

            Controls.Add(urlLabel)
            Controls.Add(_urlTextBox)
            Controls.Add(breakLiteral2)

            Controls.Add(_addButton)
            Controls.Add(breakLiteral3)

            Controls.Add(_list)

        End Sub


        Private Sub OnClickAddButton(ByVal sender As Object, ByVal e As EventArgs)
            Dim name As String = _nameTextBox.Text.Trim()
            Dim url As String = _urlTextBox.Text.Trim()

            Dim p As New Pair(name, url)
            If WebPartManager.Personalization.Scope = PersonalizationScope.Shared Then
                If _sharedUrls Is Nothing Then
                    _sharedUrls = New ArrayList()
                End If
                _sharedUrls.Add(p)
            Else
                If _userUrls Is Nothing Then
                    _userUrls = New ArrayList()
                End If
                _userUrls.Add(p)
            End If

            OnUrlAdded()

        End Sub


        Protected Overridable Sub OnUrlAdded()
            _listDirty = True
            ChildControlsCreated = False

        End Sub


        Protected Overrides Sub RenderContents(ByVal writer As HtmlTextWriter)
            If Not (_sharedUrls Is Nothing) Then
                Dim p As Pair
                For Each p In _sharedUrls
                    _list.Items.Add(New ListItem(CStr(p.First), CStr(p.Second)))
                Next p
            End If
            If Not (_userUrls Is Nothing) Then
                Dim p As Pair
                For Each p In _userUrls
                    _list.Items.Add(New ListItem(CStr(p.First), CStr(p.Second)))
                Next p
            End If

            MyBase.RenderContents(writer)

        End Sub


        Public Overridable ReadOnly Property IsDirty() As Boolean _
            Implements IPersonalizable.IsDirty
            Get
                Return _listDirty
            End Get
        End Property

        Public Overridable Shadows Sub Load(ByVal state As PersonalizationDictionary) Implements IPersonalizable.Load
            If Not (state Is Nothing) Then
                Dim sharedUrlsEntry As PersonalizationEntry = state("sharedUrls")
                If Not (sharedUrlsEntry Is Nothing) Then
                    _sharedUrls = CType(sharedUrlsEntry.Value, ArrayList)
                End If

                Dim userUrlsEntry As PersonalizationEntry = state("userUrls")
                If Not (userUrlsEntry Is Nothing) Then
                    _userUrls = CType(userUrlsEntry.Value, ArrayList)
                End If
            End If
            '       Return False

        End Sub

        Public Overridable Sub Save(ByVal state As PersonalizationDictionary) Implements IPersonalizable.Save
            If Not (_sharedUrls Is Nothing) AndAlso _sharedUrls.Count <> 0 Then
                state("sharedUrls") = New PersonalizationEntry(_sharedUrls, PersonalizationScope.Shared)
            End If
            If Not (_userUrls Is Nothing) AndAlso _userUrls.Count <> 0 Then
                state("userUrls") = New PersonalizationEntry(_userUrls, PersonalizationScope.User)
            End If

        End Sub
    End Class


    Public Class UrlListExWebPart
        Inherits UrlListWebPart
        Implements ITrackingPersonalizable

        Private _trackingLog As String = String.Empty
        Private _loading As Boolean
        Private _saving As Boolean


        Public Overrides Property [Text]() As String
            Get
                Return MyBase.Text
            End Get
            Set(ByVal value As String)
                If MyBase.Text.Equals(value) = False Then
                    MyBase.Text = value
                    SetPersonalizationDirty()
                End If
            End Set
        End Property

        Protected Overrides Sub OnUrlAdded()
            MyBase.OnUrlAdded()
            SetPersonalizationDirty()

        End Sub

        Protected Overrides Sub RenderContents(ByVal writer As HtmlTextWriter)
            MyBase.RenderContents(writer)

            writer.Write("<br />")
            writer.Write("<pre id=""" + ClientID + "$log" + """>")
            writer.Write(_trackingLog)
            writer.Write("</pre>")

        End Sub


        Public Overrides Sub Load(ByVal state As PersonalizationDictionary)
            If _loading = False Then
                Throw New InvalidOperationException()
            End If
            MyBase.Load(state)

        End Sub


        Public Overrides Sub Save(ByVal state As PersonalizationDictionary)
            If _saving = False Then
                Throw New InvalidOperationException()
            End If
            MyBase.Save(state)

        End Sub

        ReadOnly Property TracksChanges() As Boolean Implements ITrackingPersonalizable.TracksChanges
            Get
                Return True
            End Get
        End Property

        Sub BeginLoad() Implements ITrackingPersonalizable.BeginLoad
            _loading = True
            _trackingLog = "1. BeginLoad" + vbCr + vbLf

        End Sub

        Sub BeginSave() Implements ITrackingPersonalizable.BeginSave
            _saving = True
            _trackingLog += "3. BeginSave" + vbCr + vbLf

        End Sub

        Sub EndLoad() Implements ITrackingPersonalizable.EndLoad
            _loading = False
            _trackingLog += "2. EndLoad" + vbCr + vbLf

        End Sub

        Sub EndSave() Implements ITrackingPersonalizable.EndSave
            _saving = False
            _trackingLog += "4. EndSave"

        End Sub
    End Class

以下.aspx页创建 Web 部件区域并将控件添加到该区域。 该页还引用了登录控件,应使用该控件登录单个用户,以便可以应用个性化设置。

<%@ Page Language="C#"  %>
<%@ Register TagPrefix="dict" namespace="PersTest" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:WebPartManager ID="WebPartManager1" runat="server"></asp:WebPartManager>
     <asp:LoginName ID="LoginName1" runat="server" />
         
        <asp:LoginStatus ID="LoginStatus1" runat="server" LogoutAction="RedirectToLoginPage" />
            <br />
    <div>
    <asp:WebPartZone ID="WebPartZone1" runat="server">
                 <ZoneTemplate>
        <dict:UrlListWebPart id="PersDict" title="Personalization Dictionary" runat="server" />
       
        </ZoneTemplate>
        </asp:WebPartZone>
    </div>
    </form>
</body>
</html>
<%@ Page Language="VB" %>
<%@ Register TagPrefix="dict" namespace="PersTest" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:WebPartManager ID="WebPartManager1" runat="server"></asp:WebPartManager>
     <asp:LoginName ID="LoginName1" runat="server" />
         
        <asp:LoginStatus ID="LoginStatus1" runat="server" LogoutAction="RedirectToLoginPage" />
            <br />
    <div>
    <asp:WebPartZone ID="WebPartZone1" runat="server">
                 <ZoneTemplate>
        <dict:UrlListWebPart id="PersDict" title="Personalization Dictionary" runat="server" />
       
        </ZoneTemplate>
        </asp:WebPartZone>
    </div>
    </form>
</body>
</html>

注解

此接口允许控件开发人员跟踪个性化生命周期的不同阶段,包括加载和保存个性化数据。 在大多数情况下,若要使用此接口,需要创建自定义 WebPart 或 并 WebPartManager 实现此接口。 此外,需要管理自己的更改 (“脏”) 跟踪的控件应实现此接口。 管理自己的更改跟踪的控件应从 TracksChanges 属性返回true

如果 false 返回 ,则 ASP.NET 负责通过将加载的属性信息与保存的属性信息进行比较来确定更改。

属性

TracksChanges

指示控件是否跟踪其更改的状态。

方法

BeginLoad()

表示个性化信息加载阶段开始。

BeginSave()

表示从控件提取个性化数据之前的阶段。

EndLoad()

表示已经将个性化数据应用于控件之后的阶段。

EndSave()

表示已经从控件提取个性化数据之后的阶段。

适用于

另请参阅