对于microsoft .net petshop程序中的购物车和订单处理模块,文中主要分析两种技术的应用:
1. profile技术在petshop程序中用于三处:
1) 购物车shoppingcart -下面的例子围绕购物车流程进行
2) 收藏wishlist
3) 用户信息accountinfo
注册新用户 newuser.aspx :使用的是createuserwizard 控件,基于membership机制,在数据库mspetshop4services的表aspnet_users中创建用户
修改用户注册信息 userprofile.aspx: 基于profile技术,在数据库mspetshop4profile的表profiles和account中创建用户信息
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));
将接收到的消息传送给消息变量以后,通过消息变量m的body属性就可以读出消息了:
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服务开启
处理队列中的批量异步订单,在事务范围内把它们提交到数据库
文章整理:站长天空 网址:http://www.z6688.com/
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!




