ASP.NET Tutorial/Profile/Introduction

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Creating Complex Profile Properties

   <source lang="csharp">

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">
   <asp:GridView
       id="grdShoppingCart"
       EmptyDataText="There are no items in your shopping cart"
       Runat="server" />
   
<fieldset> <legend>Add Product</legend> <asp:Label id="lblName" Text="Name:" AssociatedControlID="txtName" Runat="server" />
<asp:TextBox id="txtName" Runat="server" />

<asp:Label id="lblPrice" Text="Price:" AssociatedControlID="txtPrice" Runat="server" />
<asp:TextBox id="txtPrice" Runat="server" />

<asp:Label id="lblDescription" Text="Description:" AssociatedControlID="txtDescription" Runat="server" />
<asp:TextBox id="txtDescription" Runat="server" />

<asp:Button id="btnAdd" Text="Add To Cart" Runat="server" OnClick="btnAdd_Click" /> </fieldset>
   </form>

</body> </html></source>


Defining default values for personalization properties

   <source lang="csharp">

<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></source>


Get / set profile data defined in Web.config

   <source lang="csharp">

<%@ 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 + "
" + "Last Name: " + Profile.LastName + "
" + "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></source>


Get / set user-defined object to profile

   <source lang="csharp">

<%@ 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">
Name: <asp:TextBox ID="txtName" runat="server" ></asp:TextBox>
Street: <asp:TextBox ID="txtStreet" runat="server" ></asp:TextBox>
City: <asp:TextBox ID="txtCity" runat="server" ></asp:TextBox>
Zip Code: <asp:TextBox ID="txtZip" runat="server" ></asp:TextBox>
State: <asp:TextBox ID="txtState" runat="server" ></asp:TextBox>
Country: <asp:TextBox ID="txtCountry" runat="server" ></asp:TextBox>
       
<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></source>


Inheriting a Profile from a Custom Class

   <source lang="csharp">

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></source>


Making Personalization Properties Read-Only

   <source lang="csharp">

<configuration>

 <system.web>
    <profile>
       <properties>
           <add name="StartDate" type="System.DateTime" readOnly="True" />           
       </properties>
   </profile>
   <authentication mode="Windows" />
 </system.web>

</configuration></source>


Using Profiles

   <source lang="csharp">

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">
   First Name:
   <asp:Label
       id="lblFirstname"
       Runat="server" />
   

Last Name: <asp:Label id="lblLastName" Runat="server" />

Number of Visits: <asp:Label id="lblNumberOfVisits" Runat="server" />

   <asp:Label
       id="lblNewFirstName"
       Text="New First Name:"
       AssociatedControlID="txtNewFirstName"
       Runat="server" />
   <asp:TextBox
       id="txtNewFirstName"
       Runat="server" />
   

<asp:Label id="lblNewLastName" Text="New Last Name:" AssociatedControlID="txtNewLastName" Runat="server" /> <asp:TextBox id="txtNewLastName" Runat="server" />

<asp:Button id="btnUpdate" Text="Update Profile" OnClick="btnUpdate_Click" Runat="server" />
   </form>

</body> </html></source>


Working with the automaticSaveEnabled attribute

   <source lang="csharp">

<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></source>