EKing 十八画生

--》》》 君不见黄河之水天上来,奔流到海不复回...

用户操作
[即时聊天] [发私信] [加为好友]
EKing/王毅ID:wangyihust
287124次访问,排名202好友2人,关注者29
hot
wangyihust的文章
原创 237 篇
翻译 1 篇
转载 82 篇
评论 152 篇
EKing/王毅的公告
王毅 is online?
MSN:wangyihust
   @hotmail.com
巨蟹座
毕业学校: HUST
SCUT
目前位置:中国西安
最近评论
s:美女啊
wowlevel:http://www.wowlevel.net/index.asp
power level
wangyihust:博达的建站系统VSB不知道运用在实际项目中如何?好像要硬加密狗。
EKING:EKING.
csnffdn:是西安 热工院的 王毅吗?
文章分类
收藏
相册
Develop
TEMP
DOTNET
Ajax官方主页
ASP.NET官方网站
C#开源资源大全
Dflying Atlas
dotnetjunkies
Good Ajax Samples
gotdotnet开发网
JSON格式化工具
Kaneboy's Blog
MS.Tech
MSDN
MSDN杂志
scottgu
Win32 Api在DotNet下的封装
天极网微软开发专栏
老猫的理想
JAVA
bea开发文档
CSDN
IBM Developers中国
JavaEye
TSS
WEB开发荟萃
Wiki
中国Linux公社
电力网络
中国电力社区(炉火纯青)
华能集团
电力世界网
粤电集团
西安热工院
锅炉论坛
个人事务
电子报
个人简历
我的相册
IT公司速查手册
Norton病毒库定时更新
万年历
中国代理列表
西安市公交线路
西安电子地图
学术研究
EI Village Indexed
IEEE/IEE
中国ERP知识库
数据挖掘研究院
存档
订阅我的博客
XML聚合  FeedSky
订阅到鲜果
订阅到Google
订阅到抓虾
订阅到BlogLines
订阅到Yahoo
订阅到GouGou
订阅到飞鸽
订阅到Rojo
订阅到newsgator
订阅到netvibes

原创 浅析Microsoft .net PetShop程序中的购物车和订单处理模块(Profile技术,异步MSMQ消息)收藏

新一篇: 在Struts和Hibernate之间搭起桥梁 | 旧一篇: 在安装 Norton AntiVirus 企业版客户端时出现错误“错误 1920:服务 Norton AntiVirus Server...”

    对于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)