/// <summary> /// Perform any updates before the output is rendered. Any changes at this point /// to the state of the control can be saved and the ones in the rendering phase are lost /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_PreRender(object sender, EventArgs e) { using (ShoppingCartEngine usersShoppingCart = new ShoppingCartEngine()) { //format the cart count string cartStr = string.Format("Cart [{0}]", usersShoppingCart.GetCount()); if (cartStr != null && cartCount != null) { try { cartCount.InnerText = cartStr; } catch (Exception ex) { HttpContext.Current.Session["Error"] = ex; HttpContext.Current.Response.Redirect("/UserPages/ErrorPage.aspx"); } } if (usersShoppingCart.GetCount() > 0) { contentCartCounter.Visible = true; } else { contentCartCounter.Visible = false; } } }
protected void Page_Load(object sender, EventArgs e) { string rawId = Request.QueryString["productID"]; Session["productId"] = rawId; //Session["Error"] = rawId; //Response.Redirect("/UserPages/ErrorPage.aspx"); int productId; if (!String.IsNullOrEmpty(rawId) && int.TryParse(rawId, out productId)) { using (ShoppingCartEngine usersShoppingCart = new ShoppingCartEngine()) { usersShoppingCart.AddToCart(Convert.ToInt16(rawId)); //remove 1 unit from inventory // cartEngine.DiminishInventory(); } } else { Debug.Fail("ERROR : accessing AddToCart.aspx without a ProductId."); throw new Exception("ERROR : illegal action accessing AddToCart.aspx without ProductId."); } Response.Redirect("ShoppingCart.aspx"); }
protected void LogIn(object sender, EventArgs e) { if (IsValid) { // Validate the user password var manager = new UserManager(); ApplicationUser user = manager.Find(UserName.Text, Password.Text); if (user != null) { //Migrate shoppint cart. When the shopping cart is migrated, //the GUID used to identify the anonymous shopping cart is //replaced with the user name. //create new instance of shopping cart ShoppingCartEngine usersShoppingCart = new ShoppingCartEngine(); //retrieve GUID String cartId = usersShoppingCart.GetCartId(); //pass cartId and UserName to Migrate cart method usersShoppingCart.MigrateCart(cartId, UserName.Text); IdentityHelper.SignIn(manager, user, RememberMe.Checked); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { FailureText.Text = "Invalid username or password."; ErrorMessage.Visible = true; } } }
/// <summary> /// Update the cart items /// </summary> /// <returns></returns> public List <CartItem> UpdateCartItems() { using (ShoppingCartEngine usersShoppingCart = new ShoppingCartEngine()) { String cartId = usersShoppingCart.GetCartId(); ShoppingCartEngine.ShoppingCartUpdates[] cartUpdates = new ShoppingCartEngine.ShoppingCartUpdates[CartList.Rows.Count]; for (int i = 0; i < CartList.Rows.Count; i++) { IOrderedDictionary rowValues = new OrderedDictionary(); rowValues = GetValues(CartList.Rows[i]); cartUpdates[i].ProductId = Convert.ToInt32(rowValues["ProductID"]); CheckBox cbRemove = new CheckBox(); cbRemove = (CheckBox)CartList.Rows[i].FindControl("Remove"); cartUpdates[i].RemoveItem = cbRemove.Checked; TextBox quantityTextBox = new TextBox(); quantityTextBox = (TextBox)CartList.Rows[i].FindControl("PurchaseQuantity"); cartUpdates[i].PurchaseQuantity = Convert.ToInt16(quantityTextBox.Text.ToString()); } usersShoppingCart.UpdateShoppingCartDatabase(cartId, cartUpdates.ToList()); CartList.DataBind(); lblTotal.Text = String.Format("{0:c}", usersShoppingCart.GetTotal()); return(usersShoppingCart.GetCartItems()); } }
protected void CreateUser_Click(object sender, EventArgs e) { // var userStore = new UserStore<IdentityUser>(); var userManager = new UserManager(); var user = new ApplicationUser() { UserName = UserName.Text }; try { IdentityResult result = userManager.Create(user, Password.Text); RoleManager <IdentityRole> roleManager = new RoleManager <IdentityRole>( new RoleStore <IdentityRole>(new ApplicationDbContext())); if (result.Succeeded) { var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); //create a user role CreateRole("Customer"); var store = new UserStore <ApplicationUser>(new ApplicationDbContext()); store.AutoSaveChanges = false; var currentUserId = User.Identity.GetUserId(); var manager = new UserManager <ApplicationUser>(store); var currentUser = manager.FindById(User.Identity.GetUserId()); //get current user //var currentUser = userManager.FindByName(user.UserName); StatusMessage.Text = string.Format("User {0} was created successfully!", user.UserName); IdentityHelper.SignIn(userManager, user, isPersistent: false); //migrate shopping cart using (ShoppingCartEngine usersShoppingCart = new ShoppingCartEngine()) { //get the GUID and assign to cardId String cartId = usersShoppingCart.GetCartId(); //pass cartId and User id to migrateCart method usersShoppingCart.MigrateCart(cartId, user.Id); } IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); //Add user to role var roleresult = userManager.AddToRole(currentUser.Id, "Customer"); if (!roleManager.RoleExists("Customer")) { Session["Error"] = "Role does not exist"; Response.Redirect("/UserPages/ErrorPage.aspx"); } if (!System.Web.HttpContext.Current.User.IsInRole("Customer")) { Session["Error"] = "user is not in role"; Response.Redirect("/UserPages/ErrorPage.aspx"); } authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity); Response.Redirect("~/Login.aspx"); } else { ErrorMessage.Text = result.Errors.FirstOrDefault(); } } catch (EntityCommandExecutionException ex) { Session["Error"] = ex; Response.Redirect("/UserPages/ErrorPage.aspx"); } }
/// <summary> /// Provide behavior for checkout button /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnCheckOut_Click(object sender, EventArgs e) { EntityMappingContext ctx = new EntityMappingContext(); //instantiate store engine to get cart items ShoppingCartEngine cartEngine = new ShoppingCartEngine(); //create an order status object in order to set it to submitted OrderStatus orderstatus = ctx.OrderStatuses.Create(); //get the cart items List <CartItem> cartItemList = cartEngine.GetCartItems(); // Session["CartItems"] = cartItemList; orderstatus.Status = "Created " + DateTime.Now.ToString(); //Session["Error"] = orderstatus.Status; //Response.Redirect("/UserPages/ErrorPage.aspx"); try { ctx.OrderStatuses.Add(orderstatus); ctx.SaveChanges(); //validate ctx.Configuration.ValidateOnSaveEnabled = true; } catch (DbEntityValidationException ex) { var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Combine the original exception message with the new one. var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage); Session["Error"] = fullErrorMessage; Response.Redirect("ErrorPage.aspx"); // Throw a new DbEntityValidationException with the improved exception message. throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors); } //now deal with registering the user's data. If he / she is not registered //He will be prompted to register, otherwise he will proceed to simply checkout AdminEngine adminEngine = new AdminEngine(); //// && System.Web.HttpContext.Current.User.IsInRole("user") //&& System.Web.HttpContext.Current.User.IsInRole("Customer") string user = System.Web.HttpContext.Current.User.Identity.Name; var store = new UserStore <ApplicationUser>(new ApplicationDbContext()); store.AutoSaveChanges = false; var currentUserId = User.Identity.GetUserId(); var manager = new UserManager <ApplicationUser>(store); var currentUser = manager.FindById(User.Identity.GetUserId()); //if the current user is null he is not authenticated if (!(currentUser == null)) { //If the object to be checked is null create it if (currentUser.MyUserCCardInfo == null) { //creating object currentUser.MyUserCCardInfo = new MyUserCCardInfo(); //go to enter data Response.Redirect("~/UserPages/EnterUserData.aspx"); } else { //If the credit card number is not null the record exists //and just confirmation is required if (!(currentUser.MyUserCCardInfo.CardNumber == null)) { //Create order shoppingCart.CreateOrder(currentUser); //go to confirm Response.Redirect("~/Secure/UserPagesSecured/ConfirmOrder.aspx"); } else { //if not then enter user data Response.Redirect("~/UserPages/EnterUserData.aspx"); } } } //if the user is not authenticated then make sure he is logged out and send him to login else { var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; authenticationManager.SignOut(); HttpContext.Current.Response.Redirect("~/Account/Login.aspx"); } //check if the credit card number is null if not then just confirm if (!(currentUser.MyUserCCardInfo.CardNumber == null)) { //Create order shoppingCart.CreateOrder(currentUser); //go to confirm Response.Redirect("~/Secure/UserPagesSecured/ConfirmOrder.aspx"); } //if the user name is null then login if (user == null) { HttpContext.Current.Response.Redirect("~/Account/Login.aspx"); } }