public ActionResult Index()
        {
            using (ApplicationContext context = new ApplicationContext())
            {
                Guid userId = Guid.Parse(User.Identity.GetUserId());

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

                UserDetail userDetails = context
                                .Set<UserDetail>()
                                .Where(x => x.UserId == userId)
                                .FirstOrDefault() ?? new UserDetail();

                List<string> npCities = context
                               .Set<NpDepartment>()
                               .GroupBy(x => x.CityRu)
                               .Select(g => g.Key)
                               .ToList();

                dynamic result = new ExpandoObject();
                result.Cart = cart;
                result.UserDetails = userDetails;
                result.NpCities = npCities;

                return View(result);
            }
        }
        public ActionResult GetDetailsInitialData()
        {
            using (ApplicationContext context = new ApplicationContext())
            {
                dynamic result = new ExpandoObject();

                result.Colors = context.Set<Color>().ToList();
                result.Sizes = context.Set<Size>().ToList();
                result.ImagePatterns = context.Set<ImagePattern>().ToList();

                return Json(result, JsonRequestBehavior.AllowGet);
            }
        }
        public ActionResult GenerateImage(int productId, int patternId)
        {
            using (ApplicationContext context = new ApplicationContext())
            {
                string patternFileName = context.Set<ImagePattern>().Where(x => x.Id == patternId).First().FileName;
                string logoFileName = context.Set<Product>().Where(x => x.Id == productId).First().Logo;

                string patterPath = Path.Combine(Server.MapPath(ImageHelper.PatternBaseUrl), patternFileName);
                string redSquarePath = Path.Combine(Server.MapPath(ImageHelper.LogoBaseUrl), logoFileName);

                byte[] result = ImageHelper.GetTestImage(patterPath, redSquarePath);
                return File(result, "image/jpeg");
            }
        }
        public ActionResult AddToCart(int id, int quontity)
        {
            if (UserId.HasValue)
            {
                UpdateDbCart((cart, context) =>
                {
                    Product product = context.Set<Product>().Where(x => x.Id == id).First();
                    CartItem item = cart.CartItems.Where(x => x.Product.Id == id).FirstOrDefault();
                    if (null == item)
                        cart.CartItems.Add(new CartItem(product, quontity));
                    else
                        item.Quontity += quontity;
                });
            }
            else
            {
                Product product;
                using (ApplicationContext context = new ApplicationContext())
                {
                    product = context.Set<Product>().Where(x => x.Id == id).First();
                }

                CartItem item = UserCart.CartItems.Where(x => x.Product.Id == id).FirstOrDefault();
                if (null == item)
                    UserCart.CartItems.Add(new CartItem(product, quontity));
                else
                    item.Quontity += quontity;
            }

            return Json(UserCart, JsonRequestBehavior.AllowGet);
        }
        public ActionResult Index(string tag = null, int page = 1)
        {
            const int pageSize = 9;

            using (ApplicationContext context = new ApplicationContext())
            {
                IQueryable<Product> query = context.Set<Product>().Select(x => x);

                if (!string.IsNullOrWhiteSpace(tag))
                {
                    query = query.Where(x => x.Tags.Any(t => t.Name == tag));
                }

                Product[] shirts = query.OrderBy(x => x.Id).Skip((page - 1) * pageSize).Take(pageSize).ToArray();

                dynamic result = new ExpandoObject();
                result.Shirts = shirts;
                result.PageCount = Math.Ceiling((double)query.Count() / pageSize);
                result.CurrentPage = page;
                result.TagName = tag;

                result.SportwearTags = context.Set<Tag>().Where(x => x.Groups.Any(y => y.Name == "Sportwear")).ToList();
                result.MensTags = context.Set<Tag>().Where(x => x.Groups.Any(y => y.Name == "Mens")).ToList();
                result.WomensTags = context.Set<Tag>().Where(x => x.Groups.Any(y => y.Name == "Womens")).ToList();

                result.TagsWithoutGroups = context.Set<Tag>().Where(x => x.Groups.Count == 0).ToList();

                return View(result);
            }
        }
        // GET: Admin/Admin
        public ActionResult Index()
        {
            using (ApplicationContext context = new ApplicationContext())
            {
                var shirts = context.Set<Product>().Select(x => new
                {
                    Id = x.Id,
                    Name = x.Name,
                    Size = x.Size.Name,
                    Color = x.Color.Name,
                    Price = x.Price,
                    Image = x.Image,
                    Tags = x.Tags.ToList()
                }).ToList().Select(i =>
                {
                    dynamic temp = new ExpandoObject();

                    temp.Id = i.Id;
                    temp.Name = i.Name;
                    temp.Size = i.Size;
                    temp.Color = i.Color;
                    temp.Price = i.Price;
                    temp.Tags = i.Tags;
                    temp.Image = i.Image;

                    return temp;
                });

                return View(shirts);
            }
        }
        public ActionResult Details(int id)
        {
            using (ApplicationContext context = new ApplicationContext())
            {
                Product shirt = context.Set<Product>().Where(x => x.Id == id).FirstOrDefault();
                List<Color> colors = context.Set<Color>().ToList();
                List<Size> sizes = context.Set<Size>().ToList();

                dynamic result = new ExpandoObject();

                result.Shirt = shirt;
                result.Colors = colors;
                result.Sizes = sizes;

                return View(result);
            }
        }
        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 ActionResult GetNpDepartments(string name)
        {
            using (ApplicationContext context = new ApplicationContext())
            {
                List<NpDepartment> departments = context
                               .Set<NpDepartment>()
                               .Where(x => x.CityRu == name)
                               .ToList();

                return Json(departments, JsonRequestBehavior.AllowGet);
            }
        }
 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();
     }
 }
        public ActionResult GetNpCities()
        {
            using (ApplicationContext context = new ApplicationContext())
            {
                List<string> npCities = context
                               .Set<NpDepartment>()
                               .GroupBy(x => x.CityRu)
                               .Select(g => g.Key)
                               .ToList();

                return Json(npCities, JsonRequestBehavior.AllowGet);
            }
        }
 public ActionResult UserDetails()
 {
     using (ApplicationContext context = new ApplicationContext())
     {
         UserDetail detail = context.Set<UserDetail>().Where(x => x.UserId == UserId).First();
         return View(detail);
     }
 }
        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);
            }
        }