ASP.NET Tutorial/Profile/Introduction
Содержание
- 1 Creating Complex Profile Properties
- 2 Defining default values for personalization properties
- 3 Get / set profile data defined in Web.config
- 4 Get / set user-defined object to profile
- 5 Inheriting a Profile from a Custom Class
- 6 Making Personalization Properties Read-Only
- 7 Using Profiles
- 8 Working with the automaticSaveEnabled attribute
Creating Complex Profile Properties
File: App_Code\ShoppingCart.cs
using System;
using System.Collections.Generic;
using System.Web.Profile;
namespace MyNamespace
{
public class ShoppingCart
{
private List<CartItem> _items = new List<CartItem>();
public List<CartItem> Items
{
get { return _items; }
}
}
public class CartItem
{
private string _name;
private decimal _price;
private string _description;
public string Name
{
get { return _name; }
set { _name = value; }
}
public decimal Price
{
get { return _price; }
set { _price = value; }
}
public string Description
{
get { return _description; }
set { _description = value; }
}
public CartItem() { }
public CartItem(string name, decimal price, string description)
{
_name = name;
_price = price;
_description = description;
}
}
}
File: Web.Config
<configuration>
<system.web>
<profile>
<properties>
<add name="ShoppingCart" type="MyNamespace.ShoppingCart" />
</properties>
</profile>
</system.web>
</configuration>
File: Default.aspx
<%@ Page Language="C#" %>
<%@ Import Namespace="MyNamespace" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void Page_PreRender()
{
grdShoppingCart.DataSource = Profile.ShoppingCart.Items;
grdShoppingCart.DataBind();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
CartItem newItem = new CartItem(txtName.Text, decimal.Parse(txtPrice.Text), txtDescription.Text);
Profile.ShoppingCart.Items.Add(newItem);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Show ShoppingCart</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView
id="grdShoppingCart"
EmptyDataText="There are no items in your shopping cart"
Runat="server" />
<br />
<fieldset>
<legend>Add Product</legend>
<asp:Label
id="lblName"
Text="Name:"
AssociatedControlID="txtName"
Runat="server" />
<br />
<asp:TextBox
id="txtName"
Runat="server" />
<br /><br />
<asp:Label
id="lblPrice"
Text="Price:"
AssociatedControlID="txtPrice"
Runat="server" />
<br />
<asp:TextBox
id="txtPrice"
Runat="server" />
<br /><br />
<asp:Label
id="lblDescription"
Text="Description:"
AssociatedControlID="txtDescription"
Runat="server" />
<br />
<asp:TextBox
id="txtDescription"
Runat="server" />
<br /><br />
<asp:Button
id="btnAdd"
Text="Add To Cart"
Runat="server" OnClick="btnAdd_Click" />
</fieldset>
</div>
</form>
</body>
</html>
Defining default values for personalization properties
<configuration>
<system.web>
<profile>
<properties>
<add name="FirstName" type="System.String" />
<add name="LastName" type="System.String" />
<add name="LastVisited" type="System.DateTime" />
<add name="Age" type="System.Integer" />
<add name="Member" type="System.Boolean" defaultValue="False" />
</properties>
</profile>
<authentication mode="Windows" />
</system.web>
</configuration>
Get / set profile data defined in Web.config
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="SimpleTypes" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
First Name:<asp:TextBox ID="txtFirst" runat="server">Harriet</asp:TextBox>
Last Name:<asp:TextBox ID="txtLast" runat="server">Smythe</asp:TextBox>
Date of Birth:<asp:Calendar ID="Calendar1" runat="server"></asp:Calendar>
<asp:Button ID="cmdShow" runat="server" OnClick="cmdShow_Click" Text="Show Profile Data"/>
<asp:Button ID="cmdSet" runat="server" OnClick="cmdSet_Click" Text="Set Profile Data" />
<asp:Label ID="lbl" runat="server" EnableViewState="False"></asp:Label>
</form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class SimpleTypes : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Calendar1.SelectedDate = DateTime.Now;
}
protected void cmdShow_Click(object sender, EventArgs e)
{
lbl.Text = "First Name: " + Profile.FirstName + "<br />" +
"Last Name: " + Profile.LastName + "<br />" +
"Date of Birth: " + Profile.DateOfBirth.ToString("D");
}
protected void cmdSet_Click(object sender, EventArgs e)
{
Profile.FirstName = txtFirst.Text;
Profile.LastName = txtLast.Text;
Profile.DateOfBirth = Calendar1.SelectedDate;
}
}
File: Web.config
<?xml version="1.0"?>
<configuration>
<system.web>
<profile>
<properties>
<add name="FirstName" type="String" serializeAs="Binary"/>
<add name="LastName" type="String" serializeAs="Xml"/>
<add name="DateOfBirth" type="DateTime" serializeAs="String"/>
</properties>
</profile>
</system.web>
</configuration>
Get / set user-defined object to profile
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="ComplexTypes" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td style="width: 99px">
Name:</td>
<td>
<asp:TextBox ID="txtName" runat="server" ></asp:TextBox></td>
</tr>
<tr>
<td style="width: 99px">
Street:</td>
<td>
<asp:TextBox ID="txtStreet" runat="server" ></asp:TextBox></td>
</tr>
<tr>
<td style="width: 99px">
City:</td>
<td>
<asp:TextBox ID="txtCity" runat="server" ></asp:TextBox></td>
</tr>
<tr>
<td style="width: 99px">
Zip Code:</td>
<td>
<asp:TextBox ID="txtZip" runat="server" ></asp:TextBox></td>
</tr>
<tr>
<td style="width: 99px">
State:</td>
<td>
<asp:TextBox ID="txtState" runat="server" ></asp:TextBox></td>
</tr>
<tr>
<td style="width: 99px">
Country:</td>
<td>
<asp:TextBox ID="txtCountry" runat="server" ></asp:TextBox></td>
</tr>
</table>
</div>
<br />
<asp:Button ID="cmdGet" runat="server" OnClick="cmdGet_Click" Text="Get" />
<asp:Button ID="cmdSave" runat="server" OnClick="cmdSave_Click" Text="Save" />
</form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class ComplexTypes : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
LoadProfile();
}
protected void cmdSave_Click(object sender, EventArgs e)
{
Profile.Address = new Address(txtName.Text, txtStreet.Text, txtCity.Text, txtZip.Text, txtState.Text, txtCountry.Text);
}
protected void cmdGet_Click(object sender, EventArgs e)
{
LoadProfile();
}
private void LoadProfile()
{
txtName.Text = Profile.Address.Name;
txtStreet.Text = Profile.Address.Street;
txtCity.Text = Profile.Address.City;
txtZip.Text = Profile.Address.ZipCode;
txtState.Text = Profile.Address.State;
txtCountry.Text = Profile.Address.Country;
}
}
[Serializable()]
class Address
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private string street;
public string Street
{
get { return street; }
set { street = value; }
}
private string city;
public string City
{
get { return city; }
set { city = value; }
}
private string zipCode;
public string ZipCode
{
get { return zipCode; }
set { zipCode = value; }
}
private string state;
public string State
{
get { return state; }
set { state = value; }
}
private string country;
public string Country
{
get { return country; }
set { country = value; }
}
public Address(string name, string street, string city,
string zipCode, string state, string country)
{
Name = name;
Street = street;
City = city;
ZipCode = zipCode;
State = state;
Country = country;
}
public Address() { }
}
File: Web.config
<?xml version="1.0"?>
<configuration>
<system.web>
<profile>
<properties>
<add name="address" type="Address" serializeAs="Binary"/>
</properties>
</profile>
</system.web>
</configuration>
Inheriting a Profile from a Custom Class
File: App_Code\SiteProfile.cs
using System;
using System.Web.Profile;
public class SiteProfile : ProfileBase
{
private string _firstName = "Your First Name";
private string _lastName = "Your Last Name";
[SettingsAllowAnonymous(true)]
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
[SettingsAllowAnonymous(true)]
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
}
File: Web.Config
<configuration>
<system.web>
<anonymousIdentification enabled="true" />
<profile inherits="SiteProfile" />
</system.web>
</configuration>
Making Personalization Properties Read-Only
<configuration>
<system.web>
<profile>
<properties>
<add name="StartDate" type="System.DateTime" readOnly="True" />
</properties>
</profile>
<authentication mode="Windows" />
</system.web>
</configuration>
Using Profiles
The ASP.NET Framework provides an alternative to using cookies or Session state to store user information: the Profile object.
The Profile object provides you with a strongly typed, persistent form of session state.
You create a Profile by defining a list of Profile properties in your application root web configuration file.
The ASP.NET Framework dynamically compiles a class that contains these properties in the background.
The following web configuration file defines a Profile that contains three properties: firstName, lastName, and numberOfVisits.
File: Web.Config
<configuration>
<system.web>
<profile>
<properties>
<add name="firstName" />
<add name="lastName" />
<add name="numberOfVisits" type="Int32" defaultValue="0" />
<add name="xmlLastName" type="String" serializeAs="Xml"/>
</properties>
</profile>
</system.web>
</configuration>
When you define a Profile property, you can use any of the following attributes:
name sets the name of the property.
type sets the type of the property.
The type can be any custom type, including a custom component that you define in the App_Code folder.
The default type is string.
defaultValue is a default value for the property.
readOnly creates a read-only property.
The default value is false.
serializeAs sets how a property is persisted into a static representation.
Possible values are Binary, ProviderSpecific, String, and Xml.
The default value is ProviderSpecific.
allowAnonymous allows anonymous users to read and set the property.
The default value is false.
provider associates the property with a particular Profile provider.
customProviderData passes custom data to a Profile provider.
File: ShowProfile.aspx
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void Page_PreRender()
{
lblFirstname.Text = Profile.firstName;
lblLastName.Text = Profile.lastName;
Profile.numberOfVisits++;
lblNumberOfVisits.Text = Profile.numberOfVisits.ToString();
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
Profile.firstName = txtNewFirstName.Text;
Profile.lastName = txtNewLastName.Text;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Show Profile</title>
</head>
<body>
<form id="form1" runat="server">
<div>
First Name:
<asp:Label
id="lblFirstname"
Runat="server" />
<br /><br />
Last Name:
<asp:Label
id="lblLastName"
Runat="server" />
<br /><br />
Number of Visits:
<asp:Label
id="lblNumberOfVisits"
Runat="server" />
<hr />
<asp:Label
id="lblNewFirstName"
Text="New First Name:"
AssociatedControlID="txtNewFirstName"
Runat="server" />
<asp:TextBox
id="txtNewFirstName"
Runat="server" />
<br /><br />
<asp:Label
id="lblNewLastName"
Text="New Last Name:"
AssociatedControlID="txtNewLastName"
Runat="server" />
<asp:TextBox
id="txtNewLastName"
Runat="server" />
<br /><br />
<asp:Button
id="btnUpdate"
Text="Update Profile"
OnClick="btnUpdate_Click"
Runat="server" />
</div>
</form>
</body>
</html>
Working with the automaticSaveEnabled attribute
<configuration>
<system.web>
<profile automaticSaveEnabled="False">
<properties>
<add name="FirstName" />
<add name="LastName" />
<add name="LastVisited" />
<add name="Age" />
<add name="Member" />
</properties>
</profile>
<authentication mode="Windows" />
</system.web>
</configuration>