使用配置文件为购物车提供一个商品放置数据库
.Net Framework 中包含的配置文件提供程序是SqlProfileProvider.这个提供程序把配置文件信息存储在SQL server 数据库中。
创建数据库用aspnet_regsql工具。
配置数据库提供程序:
1 <connectionStrings> 2 <clear/> 3 <add name="LocalSqlServer" connectionString="data source=(local);database=MyDBPractice;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/> 4 </connectionStrings>
有了默认的配置文件提供程序,配置文件信息就可以用system.web元素中的web.config定义。可以为登录到系统中的用户和匿名用户保存配置文件信息。如果用户没有登录,且启动了匿名标识,就创建一个匿名ID。为后面的会话把用户映射到匿名用户上,使用永久的cookie。这样,设置就总是映射到同一个匿名用户上。应为匿名用户存储的所有属性必须用allowAnonymous特性标记。配置文件属性在profile/properties中定义。要添加属性可以用add。配置文件属性用name和type描述。type用于保存属性的值。类型在数据库的串行化方式用serializeAs特性定义。串行化可以处理为一个字符串,使用二进制或XML串行化处理器,或者使用处理串行化过程的自定义类来处理。
配置文件信息:
<system.web> <compilation debug="true" targetFramework="4.5.2"/> <httpRuntime targetFramework="4.5.2"/> <anonymousIdentification enabled="true"/> <profile> <properties> <add allowAnonymous="true" name="Color" type="String" serializeAs="Xml"/> <add allowAnonymous="true" name="ShoppingCart" type="WebApplication.ShoppingCart" serializeAs="Binary"/> <group name="UserInfo"> <add allowAnonymous="true" name="Name" type="String" serializeAs="Binary"/> </group> </properties> </profile>
添加类ShoppingCart:
[Serializable] public class ShoppingCart { private readonly List<Item> _items = new List<Item>(); public IList<Item> Items { get { return _items; } } public decimal TotalCost { get { return _items.Sum(item => item.Cost); } } } [Serializable] public class Item { public string Description { get; set; } public decimal Cost { get; set; } } }
添加web窗体HttpContext定义了返回ProfileBase的Profile属性。有了ProfileBase就可以使用索引器读写配置文件属性了。如果使用Visual Studio站点而不是web项目,Page类定义profile 属性用于返回动态创建的ProfileCommon类,使用dynamic关键字。
读写配置数据库:
protected void Button1_Click(object sender, EventArgs e) { Context.Profile["Color"] = TextBox1.Text; Context.Profile.Save(); } protected void Button2_Click(object sender, EventArgs e) { dynamic p = Context.Profile; p.Color = "Red"; p.UserInfo.Name = "Christain"; var cart = new ShoppingCart(); cart.Items.Add(new Item {Description = "Sample1",Cost = 12.09m}); cart.Items.Add(new Item {Description = "Sample2",Cost = 20.12m}); p.ShoppingCart = cart; p.Save(); }
protected void Page_Load(object sender, EventArgs e) { dynamic profile = Context.Profile; Response.Write(string.Format("Color:{0}", profile.Color)); Response.Write("<br />"); Response.Write(string.Format("Name:{0}", profile.UserInfo.Name)); Response.Write("<br />"); ShoppingCart shoppingCart = profile.ShoppingCart; foreach (var item in shoppingCart.Items) { Response.Write(string.Format("{0} {1}", item.Description, item.Cost)); Response.Write("<br />"); } Response.Write(shoppingCart.TotalCost); Response.Write("<br />"); }
作者:Simen.Net
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。