public enum PageTrackingMode
{
ByApplication,
BySession,
ByTripTime
}
[
DefaultProperty("TrackingMode")
]
public class PageTracker : WebControl
{
private TimeSpan _tripTime;
[
Category("Appearance"),
DefaultValue("{0}"),
Description("The formatting string used to display the value being tracked.")
]
public virtual string FormatString
{
get
{
string s = (string)ViewState["FormatString"];
return ((s == null) ? "{0}" : s);
}
set
{
ViewState["FormatString"] = value;
}
}
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public int Hits
{
get
{
PageTrackingMode mode = TrackingMode;
object o = null;
if (mode == PageTrackingMode.ByApplication)
{
o = Page.Application[HitsKey];
}
else if (mode == PageTrackingMode.BySession)
{
o = Page.Session[HitsKey];
}
else
{
throw new NotSupportedException("Hits is only supported when TrackingMode is PageTrackingMode.ByApplication or PageTrackingMode.BySession");
}
return ((o == null) ? 0 : (int)o);
}
}
[
Category("Behavior"),
DefaultValue(PageTrackingMode.ByApplication),
Description("The type of tracking to perform.")
]
public virtual PageTrackingMode TrackingMode
{
get
{
object mode = ViewState["TrackingMode"];
return ((mode == null) ? PageTrackingMode.ByApplication : (PageTrackingMode)mode);
}
set
{
if (value < PageTrackingMode.ByApplication || value > PageTrackingMode.ByTripTime)
{
throw new ArgumentOutOfRangeException("value");
}
ViewState["TrackingMode"] = value;
// Perform cleanup of the old storage.
// We have to check that the Page is not null
// because the control could be initialized
// before it is added to the control tree.
// 因为 Application and Session
// 在设计时不可用,所以会出现异常
switch (TrackingMode)
{
case PageTrackingMode.ByApplication:
if (Page != null && Page.Application != null)
{
Page.Application.Remove(HitsKey);
}
break;
case PageTrackingMode.BySession:
if (Page != null && Page.Session != null)
{
Page.Session.Remove(HitsKey);
}
break;
case PageTrackingMode.ByTripTime:
ViewState.Remove("TimeStamp");
break;
}
}
}
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public TimeSpan TripTime
{
get
{
if (TrackingMode != PageTrackingMode.ByTripTime)
{
throw new NotSupportedException("TripTime is only supported when TrackingMode is PageTrackingMode.ByTripTime");
}
return _tripTime;
}
}

protected override HtmlTextWriterTag TagKey
{
get
{
return HtmlTextWriterTag.Div;
}
}

private string HitsKey
{
get
{
// Create a unique HitsKey for the page for keying
// in hits per page in the Application and Session objects.
return Page.GetType().FullName;
}
}

protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
switch (TrackingMode)
{
case PageTrackingMode.ByApplication:
// Update the page hits in the Application
// object. This operation needs a lock because
// multiple users could access a page at the same
// time.来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/12639172/viewspace-332340/ ,如需转载,请注明出处,否则将追究法律责任。