コード例 #1
0
        public async Task <IActionResult> Leasing()
        {
            List <ShoppingCart> cart = SessionHelper.GetObjectFromJson <List <ShoppingCart> >(HttpContext.Session, "cart");

            var id = _userManager.GetUserId(User);

            try
            {
                Leasing l = new Leasing
                {
                    LeasingStart = DateTime.Now,
                    Id           = id
                };
                _context.Add(l);

                LeasingDetail ld;

                foreach (var item in cart)
                {
                    ld = new LeasingDetail
                    {
                        LeasingId           = l.LeasingId,
                        LeasingDetailAmount = item.Quantity,
                        LeasingDetailExtend = true,
                        LeasingDetailEnd    = DateTime.Now.AddYears(1),
                        ProductId           = item.Product.ProductId
                    };
                    var product = _context.Products.Where(p => p.ProductId == item.Product.ProductId).ToList();
                    foreach (var prod in product)
                    {
                        prod.ProductAvailability -= item.Quantity;
                    }

                    _context.Add(ld);
                }

                SmtpClient client = new SmtpClient();
                client.Host                  = "smtp.gmail.com";
                client.Port                  = 587;
                client.EnableSsl             = true;
                client.UseDefaultCredentials = false;
                client.Credentials           = new NetworkCredential("*****@*****.**", "dup@1234");

                var user = await _userManager.GetUserAsync(User);

                var email = user.Email;

                MailMessage mailMessage = new MailMessage();
                mailMessage.From = new MailAddress("*****@*****.**");
                mailMessage.To.Add(email);
                mailMessage.Body    = "Order no. " + l.LeasingId;
                mailMessage.Subject = "Your order is completed. Please pay your bill.";
                mailMessage.Attachments.Add(new Attachment(@"C:\PDF\Leasing.pdf"));
                client.Send(mailMessage);

                _context.SaveChanges();
            }
            catch
            {
                ViewBag.ErrorMessage = "Your cart can't be empty";
                return(RedirectToAction("Index", "Leasings", new { id = _context.Leasings.Last().LeasingId }));
            }

            cart = null;
            SessionHelper.SetObjectAsJson(HttpContext.Session, "cart", cart);

            return(RedirectToAction("Index", "Leasings"));
        }