profile实现购物车

 

对于microsoft .net petshop程序中的购物车和订单处理模块,文中主要分析两种技术的应用:

1. profile技术在petshop程序中用于三处:

   1) 购物车shoppingcart    -下面的例子围绕购物车流程进行

    2) 收藏wishlist

    3)  用户信息accountinfo

  注册新用户 newuser.aspx :使用的是createuserwizard 控件,基于membership机制,在数据库mspetshop4services的表aspnet_users中创建用户

  修改用户注册信息 userprofile.aspx 基于profile技术,在数据库mspetshop4profile的表profilesaccount中创建用户信息

2. 异步消息处理技术运用于订单处理

4.1 web.config配置

profile可以利用数据库存储关于用户的个性化信息,有点象session对象,但session对象是有生存期的,在生存期后,session对象自动失效了。而profile不同,除非显式移除它。要实现profile功能,必须先在web.config中进行定义。

web.congfig中,将会定义一些属性/值,分别存贮将要保存的变量和值,比如language属性,定义其值是string类型,如此类推。而<group>标签,则是将一些相同或类似功能的变量值放在一起。

程序中使用方法:profile.language = ddllanguage.selecteditem.value;

 

<profile automaticsaveenabled="false" defaultprovider="shoppingcartprovider">

              <providers>

                   <add name="shoppingcartprovider" connectionstringname="sqlprofileconnstring" type="petshop.profile.petshopprofileprovider" applicationname=".net pet shop 4.0"/>

                   <add name="wishlistprovider" connectionstringname="sqlprofileconnstring" type="petshop.profile.petshopprofileprovider" applicationname=".net pet shop 4.0"/>

                   <add name="accountinfoprovider" connectionstringname="sqlprofileconnstring" type="petshop.profile.petshopprofileprovider" applicationname=".net pet shop 4.0"/>

              </providers>

              <properties>

                   <add name="shoppingcart" type="petshop.bll.cart" allowanonymous="true" provider="shoppingcartprovider"/>

                   <add name="wishlist" type="petshop.bll.cart" allowanonymous="true" provider="wishlistprovider"/>

                   <add name="accountinfo" type="petshop.model.addressinfo" allowanonymous="false" provider="accountinfoprovider"/>

              </properties>

         </profile>

4.2 购物车程序流程-profile技术

1.       点击加入购物车 http://localhost:2327/web/shoppingcart.aspx?additem=est-34

2.     shoppingcart.aspx文件处理:在init方法之前处理

      protected void page_preinit(object sender, eventargs e) {

        if (!ispostback) {

            string itemid = request.querystring["additem"];

            if (!string.isnullorempty(itemid)) {

                profile.shoppingcart.add(itemid); //注意shoppingcart的类型是petshop.bll.cart

                //save 方法将修改后的配置文件属性值写入到数据源,如shoppingcart属性已经改变

                profile.save();    

         

                // redirect to prevent duplictations in the cart if user hits "refresh"

                //防止刷新造成 多次提交

                response.redirect("~/shoppingcart.aspx", true);  //将客户端重定向到新的 url。指定新的 url 并指定当前页的执行是否应终止。

            }

        }

3.     petshop.bll.cart

// dictionary: key/value 

private dictionary<string, cartiteminfo> cartitems = new dictionary<string, cartiteminfo>();

 

/// <summary>

        /// add an item to the cart.

        /// when itemid to be added has already existed, this method will update the quantity instead.

        /// </summary>

        /// <param name="itemid">item id of item to add</param>

        public void add(string itemid) {

cartiteminfo cartitem;

//获取与指定的键相关联的值trygetvalue(tkey key,out tvalue value)

            if (!cartitems.trygetvalue(itemid, out cartitem)) {

                item item = new item();

                iteminfo data = item.getitem(itemid);

                if (data != null) {

                    cartiteminfo newitem = new cartiteminfo(itemid, data.productname, 1, (decimal)data.price, data.name, data.categoryid, data.productid);

                    cartitems.add(itemid, newitem);

                }

            }

            else

                cartitem.quantity++;

        }

 

4.     更新profile

//save 方法将修改后的配置文件属性值写入到数据源,如shoppingcart属性已经改变

                profile.save(); 

如何更新:

    根据配置中的shoppingcartprovider类型 petshop.profile.petshopprofileprovider

 

asp.net 配置文件提供对用户特定属性的持久性存储和检索。配置文件属性值和信息按照由 profileprovider 实现确定的方式存储在数据源中。

每个用户配置文件在数据库的 profiles 表中进行唯一标识。该表包含配置文件信息,如应用程序名称和上次活动日期。

create table profiles

(

  uniqueid autoincrement not null primary key,

  username text (255) not null,

  applicationname text (255) not null,

  isanonymous yesno,

  lastactivitydate datetime,

  lastupdateddate datetime,

  constraint pkprofiles unique (username, applicationname)

)

 

5.     petshop.profile. petshopprofileprovider类, 继承自profileprovider

// 创建 petshop.sqlprofiledal.petshopprofileprovider-数据库操作

         private static readonly ipetshopprofileprovider dal

= dataaccess.createpetshopprofileprovider();

 

/// <summary>

        /// 设置指定的属性设置组的值

        /// </summary>

         public override void setpropertyvalues(settingscontext context, settingspropertyvaluecollection collection) {

              string username = (string)context["username"];

              checkusername(username);                        

              bool isauthenticated = (bool)context["isauthenticated"];

 

              int uniqueid = dal.getuniqueid(username, isauthenticated, false, applicationname);

              if(uniqueid == 0)

                   uniqueid = dal.createprofileforuser(username, isauthenticated, applicationname);

 

              foreach(settingspropertyvalue pv in collection) {

                   if(pv.propertyvalue != null) {

                       switch(pv.property.name) {

                            case profile_shoppingcart:   //shoppingcart

                                 setcartitems(uniqueid, (cart)pv.propertyvalue, true);

                                 break;

                            case profile_wishlist:

                                 setcartitems(uniqueid, (cart)pv.propertyvalue, false);

                                 break;

                            case profile_account:

                                 if(isauthenticated)

                                     setaccountinfo(uniqueid, (addressinfo)pv.propertyvalue);

                                 break;

                            default:

                                 throw new applicationexception(err_invalid_parameter + " name.");

                       }

                   }

              }

 

              updateactivitydates(username, false);

         }

 

// update cart

         private static void setcartitems(int uniqueid, cart cart, bool isshoppingcart) {

              dal.setcartitems(uniqueid, cart.cartitems, isshoppingcart);

         }

 

6.       petshop.sqlprofiledal. petshopprofileprovider

使用事务:包含两个sql动作,先删除,再插入

/// <summary>

        /// update shopping cart for current user

        /// </summary>

        /// <param name="uniqueid">user id</param>

        /// <param name="cartitems">collection of shopping cart items</param>

        /// <param name="isshoppingcart">shopping cart flag</param>

         public void setcartitems(int uniqueid, icollection<cartiteminfo> cartitems, bool isshoppingcart) {

                   string sqldelete = "delete from cart where uniqueid = @uniqueid and isshoppingcart = @isshoppingcart;";

 

              sqlparameter[] parms1 = {                   

                   new sqlparameter("@uniqueid", sqldbtype.int),

                   new sqlparameter("@isshoppingcart", sqldbtype.bit)};

              parms1[0].value = uniqueid;

              parms1[1].value = isshoppingcart;

 

            if (cartitems.count > 0) {

 

                // update cart using sqltransaction

                string sqlinsert = "insert into cart (uniqueid, itemid, name, type, price, categoryid, productid, isshoppingcart, quantity) values (@uniqueid, @itemid, @name, @type, @price, @categoryid, @productid, @isshoppingcart, @quantity);";

 

                sqlparameter[] parms2 = {                 

                   new sqlparameter("@uniqueid", sqldbtype.int), 

                   new sqlparameter("@isshoppingcart", sqldbtype.bit),

                   new sqlparameter("@itemid", sqldbtype.varchar, 10),

                   new sqlparameter("@name", sqldbtype.varchar, 80),

                   new sqlparameter("@type", sqldbtype.varchar, 80),

                   new sqlparameter("@price", sqldbtype.decimal, 8),

                   new sqlparameter("@categoryid", sqldbtype.varchar, 10),

                   new sqlparameter("@productid", sqldbtype.varchar, 10),

                   new sqlparameter("@quantity", sqldbtype.int)};

                parms2[0].value = uniqueid;

                parms2[1].value = isshoppingcart;

 

                sqlconnection conn = new sqlconnection(sqlhelper.connectionstringprofile);

                conn.open();

                sqltransaction trans = conn.begintransaction(isolationlevel.readcommitted);

 

                try {

                    sqlhelper.executenonquery(trans, commandtype.text, sqldelete, parms1);

 

                    foreach (cartiteminfo cartitem in cartitems) {

                        parms2[2].value = cartitem.itemid;

                        parms2[3].value = cartitem.name;

                        parms2[4].value = cartitem.type;

                        parms2[5].value = cartitem.price;

                        parms2[6].value = cartitem.categoryid;

                        parms2[7].value = cartitem.productid;

                        parms2[8].value = cartitem.quantity;

                        sqlhelper.executenonquery(trans, commandtype.text, sqlinsert, parms2);

                    }

                    trans.commit();

                }

                catch (exception e) {

                    trans.rollback();

                    throw new applicationexception(e.message);

                }

                finally {

                    conn.close();

                }

            }

            else

                // delete cart

                sqlhelper.executenonquery(sqlhelper.connectionstringprofile, commandtype.text, sqldelete, parms1);

         }

4.3 订单处理技术

 

订单处理技术:――分布式事务

1  同步:直接在事务中 将订单 插入到数据库中,同时更新库存

2  异步:订单-》消息队列(使用msmq)-》后台处理 

4.3.1 使用wizard组件

4.3.2 分布式事务处理技术

开启msdtc 服务支持分布式事务. to start the msdtc service, open administrative tools | services and start the distributed transaction coordinator service

4.3.3 msmq 消息队列简介

1)引用队列

 

      引用队列有三种方法,通过路径、格式名和标签引用队列,这里我只介绍最简单和最常用的方法:通过路径引用队列。队列路径的形式为 machinename/queuename。指向队列的路径总是唯一的。下表列出用于每种类型的队列的路径信息:

如果是发送到本机上,还可以使用”.”代表本机名称。

 

2)消息的创建

不过要使用msmq开发你的消息处理程序,必须在开发系统和使用程序的主机上安装消息队列。消息队列的安装属于windows组件的安装,和一般的组件安装方法类似。

往系统中添加队列十分的简单,打开[控制面板]中的[计算机管理],展开[服务和应用程序],找到并展开[消息队列](如果找不到,说明你还没有安装消息队列,安装windows组件),右击希望添加的消息队列的类别,选择新建队列即可。

 

消息接收服务位于system.messaging中,在初始化时引用消息队列的代码很简单,如下所示:

messagequeue mq=new messagequeue(“.//private$//jiang”)

 

通过path属性引用消息队列的代码也十分简单:

messagequeue mq=new messagequeue()

mq.path=”.//private$//jiang”;

 

使用create 方法可以在计算机上创建队列:

system.messaging.messagequeue.create(@"./private$/jiang");

 

3) 发送和接收消息

过程:消息的创建-》发送-》接收-》阅读-》关闭

简单消息的发送示例如下:

         mq.send(1000); //发送整型数据

         mq.send(“this is a test message!”); //发送字符串

 

接收消息由两种方式:通过receive方法接收消息同时永久性地从队列中删除消息;通过peek方法从队列中取出消息而不从队列中移除该消息。如果知道消息的标识符(id),还可以通过receivebyid方法和peekbyid方法完成相应的操作。

     接收消息的代码很简单:

         mq.receive(); //mq.receivebyid(id);

         mq.peek();  // mq.peekbyid(id);

 

阅读消息

接收到的消息只有能够读出来才是有用的消息,因此接收到消息以后还必须能读出消息,而读出消息算是最复杂的一部操作了。消息的序列化可以通过visual studio .net framework 附带的三个预定义的格式化程序来完成:xmlmessageformatter 对象( messagequeue 组件的默认格式化程序设置)、binarymessageformatter 对象、activexmessageformatter 对象。由于后两者格式化后的消息通常不能为人阅读,所以我们经常用到的是xmlmessageformatter对象。

使用xmlmessageformatter对象格式化消息的代码如下所示:

       string[] types = { "system.string" };

       ((xmlmessageformatter)mq.formatter).targettypenames = types;

        message m=mq.receive(new timespan(0,0,3));

       将接收到的消息传送给消息变量以后,通过消息变量mbody属性就可以读出消息了:

messagebox.show((string)m.body);

 

关闭消息队列

     消息队列的关闭很简单,和其他对象一样,通过close函数就可以实现了:

mq.close();

 

4.3.4 petshop程序中订单处理-使用同步消息

默认程序使用同步消息 处理,直接操作数据库插入订单,更新库存类

4.3.5 petshop程序中订单处理-使用异步消息

1)    web程序中调用petshop.bll.order类方法:  insert(orderinfo order);

 

2)    petshop.bll.order

//iorderstrategy接口中只有一个插入订单方法:void insert(petshop.model.orderinfo order);

        //得到petshop.bll. orderasynchronous

        private static readonly petshop.ibllstrategy.iorderstrategy orderinsertstrategy = loadinsertstrategy();

 

        //iorder接口中有两种方法:send()receive()  -消息队列

        private static readonly petshop.imessaging.iorder orderqueue

= petshop.messagingfactory.queueaccess.createorder();

 

public void insert(orderinfo order) {

            // call credit card procesor,采用随机化方法设置订单认证数字

            processcreditcard(order);

            // insert the order (a)synchrounously based on configuration

            orderinsertstrategy.insert(order);    //调用petshop.bll.orderasynchronous

        }

 

3)    petshop.bll. orderasynchronous

 

// createorder()方法得到petshop.msmqmessaging .order类的实例

private static readonly petshop.imessaging.iorder asynchorder

 = petshop.messagingfactory.queueaccess.createorder();

 

public void insert(petshop.model.orderinfo order) {

            asynchorder.send(order);    //调用petshop.msmqmessaging.order

        }

 

4)    petshop.msmqmessaging项目 -关键(发送/接收消息)

 

petshopqueue基类:创建消息队列,发送和接收消息

order类:继承自petshopqueue

public new orderinfo receive() {            //从队列中接收消息

            base.transactiontype = messagequeuetransactiontype.automatic;

            return (orderinfo)((message)base.receive()).body;

        }

public void send(orderinfo ordermessage) {  //发送消息到队列

            base.transactiontype = messagequeuetransactiontype.single;

            base.send(ordermessage);

        }

 

5)    petshop.orderprocessor项目-后台处理订单,将它们插入到数据库中

program类:多线程后台订单处理程序,可写成一个控制台程序,作为windows服务开启

处理队列中的批量异步订单,在事务范围内把它们提交到数据库

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

一、ASP.NETProfile属性

  

 

1.提供对配置文件(Web.config)属性值和信息的非类型化访问

2.Web应用程序运行时,ASP.NET创建一个从ProfileBase类动态继承下来的动态生成出来的ProfileCommon类。动态ProfileCommon类包含了你在Web应用程序配置文件中指定的Profile属性所拥有的字段。一个动态ProfileCommon类的实例被设置成了当前HttpContextProfile属性,并可以在应用程序的各个页面中使用。

 

二、Profile作用

1.存储和使用唯一与用户对应的信息

2.展现个人化版本的Web应用程序

3.用户的唯一身份标识在再次访问时识别用户

 

=========常用的Web保存数据的方式=========

1.Session

只要Session不超时,那么保存在Session的数据就不会丢失

优点:

<1>数据私有性

<2>会话结束,释放资源,节省访问器内存

缺点:

<1>易丢失,超时时间很难确定

<2>Asp.Net1.0Session保存到数据库方式,持久保存数据,导致网站性能降低

使用:

Session["Key"]=Value;//存储 (Type)Session["Key"]; //读取(强制转换)

 

2.Cookie

保存到客户端的少量文本数据

优点:

<1>可自定义有效期

<2>不占用服务器磁盘空间

<3>稳定性比较好

缺点:

<1>易丢失

<2>安全性差

<3>只能存储文本数据

使用:

Response.Cookies["Key"].Value=;//Cookie写入数据,String类型 string value = Request.Cookies["Key"];//读取

 

3.Application

4.Cache

5.XML

6.文件

7.数据库

  

 

=========购物车=========

一、特点

1.私有性:每位用户操作自己的购物车

2.安全性:保障用户支付信息的安全

3.稳定性:可以支持高负载

4.持久性:购物车内的物品不能丢失

 

二、抽象

<1> 购物车中的商品类(购物车容器中的实例)

===CartItem类的属性===

ID: 唯一标识 (只读)

Name: 商品名称 (只读)

Price: 商品价格 (只读)

Quantity: 商品数量

===CartItem的方法===

CartItem(int id,string name,decimal Price); CartItem(int id,string name,decimal Price,int Quantity);

 

<2>购物车(存放商品的容器)

===Cart类的属性===

Items :商品集合(Hashtable)

Hashtable Items = new Hashtable(); //返回购物车中商品的集合 public ICollection CartItems {   Get{return Items.Values;} }

CartItems: 获取全部商品

Total: 商品总价格

===Cart类的方法===

public void AddItem(int id,string name,decimal price) //增加项 {   //无商品增加. 有商品更改数量,通过检验Hashtable中键来判断有无商品           CartItem item = (CartItem)Items[id];   if(item ==null)   {     //增加     Items.Add(id,new CartItem(id,name,price));   }   else   {     items.Quantity++;     items[id] = item;   } } public void RemoveItem(int id);//移出项 {   item.Quantity--;   if(item.Quantity ==0)//如果没数量,移除   {     Items.Remove(id);   }   else   {     items[id] =item;   } }

 

 

 

 

  =========Provider提供程序==========

 1.Profile属性

2.配置层:Web.Config

3.提供程序层:SqlProfileProvider

4.数据层:Aspnetdb数据库

 

  

//Web.config <connectionStrings> <add name="profileConnStr" connectionString="server=./sqlexpress;database=test;uid=sa;pwd=123456"/> </connectionStrings> <system.web> <!-- 匿名用户也可访问profile --> <anonymousIdentification enabled="true"/> <profile enabled="true" automaticSaveEnabled="true" defaultProvider="SqlProvide"> <providers> <add name="SqlProvide" connectionStringName="profileConnStr" type="System.Web.Profile.SqlProfileProvider"/> </providers> <properties> <add name="ShoppingCart" type="Cart" allowAnonymous="true" serializeAs="Binary"/> </properties> </profile> ...... <!-- 通过 <authentication> 节可以配置 ASP.NET 用来 识别进入用户的 安全身份验证模式。 --> <authentication mode="Forms" /> </system.web> //采用硬编码方式进行用户认证: string name = txtName.Text.Trim(); string pwd = txtPassword.Text.Trim(); if (name == "niunan" && pwd == "123456") { FormsAuthentication.SetAuthCookie(name, false); Response.Redirect("~/product.aspx"); } //匿名用户的购物车数据向实名用户的购物车数据迁移 //,未登陆时收藏到购物车. 结账时登陆.将匿名用户的购物车转移到登陆账户中 //Global.asax文件中加入如下内容: protected void Profile_MigrateAnonymous(object s, ProfileMigrateEventArgs e) { ProfileCommon anonProfile = Profile.GetProfile(e.AnonymousID); foreach (CartItem ci in anonProfile.ShoppingCart.GetItems()) { Profile.ShoppingCart.AddItem(ci); } ProfileManager.DeleteProfile(e.AnonymousID); // 删除匿名用户的profile AnonymousIdentificationModule.ClearAnonymousIdentifier(); // 清除匿名用户标识 Profile.Save(); } =============Aspnetdb数据库中内容===============

aspnet_Users

基础表

aspnet_Applications

基础表  

aspnet_Profile  

个性化用户配置部分  

aspnet_PersonalizationPerUser  

页面个性化设置部分  

aspnet_Paths  

页面个性化设置部分  

aspnet_PersonalizationAllUsers  

页面个性化配置部分  

aspnet_Roles  

角色管理部分  

aspnet_UserInRoles  

角色管理部分  

aspnet_Membership  

成员资格管理部分

=============Asp.net提供程序基类===============

 

描述

MembershipProvider  

成员资格提供程序的基类,用来管理用户账户信息  

ProfileProvider  

个性化提供程序的基类,用来永久存储和检索用户的配置信息  

RoleProvider  

角色提供程序的基类,用来管理用户角色信息  

SessionStateStoreProviderBase  

会话状态存储器提供程序的基类,这些提供程序用来把会话状态信息保存在持久性存储介质中,或从中检索会话状态信息  

SiteMapProvider  

管理站点地图信息的基类

 

Profile属性的作用

1.存储和使用唯一与用户对应的信息

2.展现个人化版本的Web应用程序

3.用户的唯一身份标识在再次访问时识别用户

 

=============Sql ServerProviderAsp.net提供程序的支持===============

描述

SqlMembershipProvider类  

成员资格  

SqlRoleProvider类  

角色管理  

SqlProfileProvider类  

个性化配置  

SqlPersonalizationProvider类  

Web部件个性化设置  

SqlWebEventProvider类  

Web事件

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值