protected void UpdateDbCart(Action<Cart, ApplicationContext> action, Guid? userId = null)
 {
     using (ApplicationContext context = new ApplicationContext())
     {
         Cart cart = context
                         .Set<Cart>()
                         .Include("CartItems.Product")
                         .Where(x => x.UserId == (userId ?? UserId))
                         .First();
         action(cart, context);
         context.SaveChanges();
     }
 }
Beispiel #2
0
        static void Main(string[] args)
        {
            Task<string> t = GeteRawString();
            t.Wait();

            File.WriteAllText("nova_poshta.json", t.Result);

            string json = File.ReadAllText("nova_poshta.json");
            List<NpDepartment> departments = ConvertToObjects(json);

            using (ApplicationContext context = new ApplicationContext())
            {
                context.Set<NpDepartment>().RemoveRange(context.Set<NpDepartment>());
                context.Set<NpDepartment>().AddRange(departments);
                context.SaveChanges();
            }
        }
        public async Task<ActionResult> Register(LoginRegisterViewModel model)
        {
            RegisterViewModel registerModel = model.RegisterViewModel;

            if (!ModelState.IsValid)
            {
                return View("LoginRegister", model);
            }
            else if (string.IsNullOrWhiteSpace(registerModel.RegisterEmail) ||
                        string.IsNullOrWhiteSpace(registerModel.RegisterPassword) ||
                        string.IsNullOrWhiteSpace(registerModel.RegisterName))
            {
                if (string.IsNullOrWhiteSpace(registerModel.RegisterEmail))
                {
                    ModelState.AddModelError("RegisterEmail", "Please, enter email.");
                }

                if (string.IsNullOrWhiteSpace(registerModel.RegisterPassword))
                {
                    ModelState.AddModelError("RegisterPassword", "Please, enter password.");
                }

                if (string.IsNullOrWhiteSpace(registerModel.RegisterName))
                {
                    ModelState.AddModelError("RegisterName", "Please, enter user name.");
                }

                return View("LoginRegister", model);
            }

            var user = new ApplicationUser { UserName = registerModel.RegisterName, Email = registerModel.RegisterEmail };
            var result = await UserManager.CreateAsync(user, registerModel.RegisterPassword);
            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                ApplicationUser addedUser = UserManager.FindByEmail(user.Email);
                Guid userId = Guid.Parse(addedUser.Id);

                using (ApplicationContext context = new ApplicationContext())
                {
                    UserDetail detail = new UserDetail();
                    detail.UserId = userId;
                    detail.Name = addedUser.UserName;
                    context.Set<UserDetail>().Add(detail);

                    Cart cart = context
                                .Set<Cart>()
                                .Include("CartItems.Product")
                                .Where(x => x.UserId == userId)
                                .FirstOrDefault();

                    if (null == cart)
                    {
                        context.Set<Cart>().Add(new Cart(userId));
                    }

                    context.SaveChanges();
                }

                if (null != Session["Cart"])
                {
                    Cart sessionCart = (Cart)Session["Cart"];

                    UpdateDbCart((cart, context) =>
                    {
                        foreach (CartItem item in sessionCart.CartItems)
                        {
                            CartItem savedItem = cart.CartItems.Where(x => x.Product.Id == item.Product.Id).FirstOrDefault();
                            if (null == savedItem)
                                cart.CartItems.Add(new CartItem(item.Product, item.Quontity));
                            else
                                savedItem.Quontity += item.Quontity;
                        }
                    }, userId);

                    Session["Cart"] = null;
                }

                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                return RedirectToAction("Index", "Product");
            }
            //    AddErrors(result);
            //}

            //// If we got this far, something failed, redisplay form
            return View("LoginRegister", model);
        }
        public ActionResult SubmitOrder(SubmitViewModel model)
        {
            NpDepartment dep = null;

            using (ApplicationContext context = new ApplicationContext())
            {
                dep = context.Set<NpDepartment>().Where(x => x.Id == model.NpDepartmentId).First();
                Order order = UserCart.GetOrder();
                order.NpDepartment = dep;
                order.Status = OrderStatus.Submitted;

                context.Set<Order>().Add(order);

                context.SaveChanges();
            }

            UpdateDbCart((cart, context) =>
            {
                cart.CartItems.Clear();
            });

            var body = "<p>" +
                            "New Order Submitted" +
                       "</p>" +
                       "<table>" +
                            "<tbody>" +
                                "<tr>" +
                                    "<td>Name:</td><td>{0}</td>" +
                                "</tr>" +
                                "<tr>" +
                                    "<td>Phone:</td><td>{1}</td>" +
                                "</tr>" +
                                "<tr>" +
                                    "<td>City:</td><td>{2}</td>" +
                                "</tr>" +
                                "<tr>" +
                                    "<td>Nova Poshta Address:</td><td>{3}</td>" +
                                "</tr>" +
                            "</tbody>" +
                        "</table>";

            var message = new MailMessage();
            message.To.Add(new MailAddress("*****@*****.**"));  // replace with valid value
            message.From = new MailAddress("*****@*****.**");  // replace with valid value
            message.Subject = "New Order Submitted";
            message.Body = string.Format(body, model.Name, model.Phone, dep.CityRu, dep.AddressRu);
            message.IsBodyHtml = true;

            using (var smtp = new SmtpClient())
            {

                //smtp.UseDefaultCredentials = true;
                //smtp.Credentials = new NetworkCredential("", "");
                //smtp.Host = "smtp.gmail.com";
                //smtp.Port = 587;
                //smtp.EnableSsl = true;
                //await smtp.SendMailAsync(message);

                return Json(OrderStatus.Submitted, JsonRequestBehavior.AllowGet);
            }
        }