public async Task <IActionResult> PutCouponUser([FromRoute] int id, [FromBody] CouponUser couponUser) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != couponUser.Id) { return(BadRequest()); } _context.Entry(couponUser).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CouponUserExists(id)) { return(NotFound()); } else { throw; } } return(Ok(_context.CouponUsers.Find(id))); }
public ActionResult GetPwd(int id, string userID, string cUserID) { userID = UserID == null ? userID : UserID; string couponUserID; if (string.IsNullOrWhiteSpace(cUserID))//如果有分享的用户ID不验证 { if (string.IsNullOrWhiteSpace(userID)) { return(Json(Comm.ToJsonResult("NotLogin", "用户没有登录"), JsonRequestBehavior.AllowGet)); } var user = db.Users.FirstOrDefault(s => s.Id == userID); if (!user.IsActive) { return(Json(Comm.ToJsonResult("NotActive", "用户没有激活"), JsonRequestBehavior.AllowGet)); } couponUserID = Bll.Accounts.GetCouponUserID(userID); if (couponUserID == null) { return(Json(Comm.ToJsonResult("NotReceive", "当前用户没法领取"), JsonRequestBehavior.AllowGet)); } } else { couponUserID = cUserID; } CouponUser cu = db.CouponUsers.Include(s => s.Coupon).FirstOrDefault(s => s.CouponID == id && s.UserID == couponUserID); if (cu == null) { return(Json(Comm.ToJsonResult("Error", "优惠券不存在"), JsonRequestBehavior.AllowGet)); } string pwd = ""; switch (cu.Platform) { case Enums.CouponPlatform.TaoBao: case Enums.CouponPlatform.TMall: { pwd = new Taobao().GetWirelessShareTpwd(cu.Coupon.Image, cu.Link, cu.Coupon.Name, 0); } break; case Enums.CouponPlatform.Jd: case Enums.CouponPlatform.MoGuJie: default: { pwd = cu.Link; } break; } return(Json(Comm.ToJsonResult("Success", "成功", new { Data = pwd }), JsonRequestBehavior.AllowGet)); }
public async Task <IActionResult> PostCouponUser([FromBody] CouponUser couponUser) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } _context.CouponUsers.Add(couponUser); await _context.SaveChangesAsync(); return(CreatedAtAction("GetCouponUser", new { id = couponUser.Id }, couponUser)); }
public bool Insert(CouponUser entity) { try { db.CouponUsers.Add(entity); db.SaveChanges(); return(true); } catch { return(false); } }
public void InsertCouponTest() { CouponUser user = new CouponUser() { LastName = "User", FirstName = "Test", Email = "*****@*****.**", // Guid.NewGuid().ToString("N") + "@fosfor.us", Address1 = "209 E 6th", City = "Austin", State = "TX", PostalCode = "78701", PetType = "DOG", OptIn = false }; User returnUser = _target.RegisterCoupon(user, 52, "PC-AAP-SAMPLING"); Assert.IsNotNull(returnUser, "RegisterCoupon gets valid response"); Assert.IsTrue(returnUser.Email == user.Email, "RegisterCoupon returns updated object"); Assert.IsNotNull(returnUser.Uuid, "RegisterCoupon sets UUID"); Console.WriteLine("Returned Object: UUID = " + returnUser.Uuid); }
/// <summary> /// 用户提交优惠劵的信息 /// </summary> /// <param name="CouponUser">用户信息 现在提交过来的用户信息只有 一个电话号码</param> /// <returns></returns> public JsonResult CouponAdd(CouponUser CouponUser) { if (Session["CouponCode"] != null) { var CouponCode = (CouponLog)Session["CouponCode"]; var Coupon = CouponRepository.Find(Specification<Coupon>.Eval(o => o.CouponID == CouponCode.CouponID)); var ip = Request.UserHostAddress; var dt = DateTime.Now.Date; CouponUser.CouponItemID = Coupon.CouponItems.ToList()[CouponCode.IsAward - 1].CouponItemID; CouponUser.CouponID = CouponCode.CouponID; CouponUser.IP = Request.UserHostAddress; CouponUser.CouponCode = CouponCode.CouponCode; CouponUser.UserId = int.Parse(Session["UserId"].ToString()); CouponUser.AddDate = DateTime.Now; CouponUserRepository.Add(CouponUser); CouponUserRepository.Context.Commit(); return Json(new { message = "提交成功" }); } else { return Json(new { message = "已超时!" }); } }
public async Task <IActionResult> Edit(string id, CouponViewModel viewModel) { #region SelectList var users = await _db.UserRepository.GetAsync(); ViewData["UsersId"] = new SelectList(users, "Id", "UserName"); var products = await _db.ProductRepository.GetAsync(); ViewData["ProductsId"] = new SelectList(products, "Id", "Name"); var categories = await _db.CategoryRepository.GetAsync(); ViewData["CategoriesId"] = new SelectList(categories, "Id", "Name"); #endregion if (ModelState.IsValid) { viewModel.Title = viewModel.Title.Trim(); var couponModel = await _db.CouponRepository.GetAsync(c => c.Title == viewModel.Title.Trim() && c.Id != id, string.Empty); if (couponModel == null) { var coupon = await _db.CouponRepository.GetAsync(id); if (coupon != null) { if (viewModel.EndDateLimit < viewModel.StartDateLimit) { ModelState.AddModelError("EndDateLimit", "تاریخ پایان باید بعد از تاریخ شروع باشد"); return(View(viewModel)); } if (viewModel.HasUserLimit && viewModel.Users.Count == 0) { ModelState.AddModelError("Users", "کاربران را وارد کنید"); return(View(viewModel)); } if (viewModel.HasProductOrCategoryLimit) { if (viewModel.ProductOrCategoryLimit == "product" && viewModel.Products.Count == 0) { ModelState.AddModelError("Products", "محصولات را وارد کنید"); return(View(viewModel)); } if (viewModel.ProductOrCategoryLimit == "category" && viewModel.Categories.Count == 0) { ModelState.AddModelError("Categories", "دسته بندی ها را وارد کنید"); return(View(viewModel)); } } #region Coupon coupon.Title = viewModel.Title.Trim(); coupon.Type = viewModel.Type == "percent" ? true : false; coupon.Value = viewModel.Type == "percent" ? viewModel.PercentDiscount : viewModel.ValueDiscount; coupon.HasCountLimit = viewModel.HasCountLimit; if (viewModel.HasCountLimit) { coupon.CountLimit = viewModel.CountLimit; } coupon.HasDateLimit = viewModel.HasDateLimit; if (viewModel.HasDateLimit) { coupon.StartDateLimit = viewModel.StartDateLimit; coupon.EndDateLimit = viewModel.EndDateLimit; } coupon.HasUserLimit = viewModel.HasUserLimit; if (viewModel.HasProductOrCategoryLimit) { if (viewModel.ProductOrCategoryLimit == "product") { coupon.HasProductLimit = true; coupon.HasCategoryLimit = false; } else { coupon.HasCategoryLimit = true; coupon.HasProductLimit = false; } } else { coupon.HasProductLimit = false; coupon.HasCategoryLimit = false; } #endregion _db.CouponRepository.Update(coupon); await _db.SaveAsync(); if (viewModel.HasUserLimit) { var oldUsers = await _db.CouponUserRepository.GetAsync(c => c.CouponId == coupon.Id, null, string.Empty); foreach (var oldUser in oldUsers) { _db.CouponUserRepository.Delete(oldUser); } foreach (var userId in viewModel.Users) { var couponUser = new CouponUser() { CouponId = coupon.Id, UserId = userId }; await _db.CouponUserRepository.AddAsync(couponUser); } await _db.SaveAsync(); } if (viewModel.HasProductOrCategoryLimit) { if (viewModel.ProductOrCategoryLimit == "product") { var oldProducts = await _db.CouponProductRepository.GetAsync(c => c.CouponId == coupon.Id, null, string.Empty); foreach (var oldProduct in oldProducts) { _db.CouponProductRepository.Delete(oldProduct); } foreach (var productId in viewModel.Products) { var couponProduct = new CouponProduct() { CouponId = coupon.Id, ProductId = productId }; await _db.CouponProductRepository.AddAsync(couponProduct); } await _db.SaveAsync(); } else { var oldCategories = await _db.CouponCategoryRepository.GetAsync(c => c.CouponId == coupon.Id, null, string.Empty); foreach (var oldCategory in oldCategories) { _db.CouponCategoryRepository.Delete(oldCategory); } foreach (var categoryId in viewModel.Categories) { var couponCategory = new CouponCategory() { CouponId = coupon.Id, CategoryId = categoryId }; await _db.CouponCategoryRepository.AddAsync(couponCategory); } await _db.SaveAsync(); } } return(Redirect("/Admin/Coupon")); } else { return(NotFound()); } } else { ModelState.AddModelError("Title", "کد تخفیف با این نام قبلا ثبت شده است"); return(View(viewModel)); } } else { return(View(viewModel)); } }
public ActionResult SendOrder(string shipName, string mobile, string address, string email) { try { UserLogin user = (UserLogin)Session[Common.CommonConstants.USER_SESSION]; var cart = (List <CartItem>)Session[Common.CommonConstants.CART_SESSION]; var itemList = new List <CartItem>(); if (cart != null) { itemList = (List <CartItem>)cart; } var coupon = (List <Coupon>)Session[Common.CommonConstants.COUPON_SESSION]; var couponList = new List <Coupon>(); if (coupon != null) { couponList = (List <Coupon>)coupon; } var productDao = new ProductDao(); decimal originPrice = 0; foreach (var item in itemList) { //check quantity+status của product if (productDao.CheckProduct(item.Product.ID, item.Quantity) == false) { var alertMessage = "Số lượng sản phẩm [" + item.Product.Name + "] đã hết. Xin vui lòng chọn sản phẩm khác."; SetAlert(alertMessage, "error"); return(Redirect("/het-san-pham")); } if (item.Product.PromotionPrice != null) { originPrice += (item.Product.PromotionPrice.GetValueOrDefault(0) * item.Quantity); } else { originPrice += (item.Product.Price.GetValueOrDefault(0) * item.Quantity); } } decimal newPrice = originPrice; foreach (var item in couponList) { if (item.ByPercentage == true) { newPrice = (newPrice * (1 - item.DiscountBy / 100)); } else { newPrice = newPrice - item.DiscountBy; } } if (newPrice < 0) { newPrice = 0; } //Gửi Email //đọc file neworder.html //email mẫu string content = System.IO.File.ReadAllText(Server.MapPath("/assets/client/template/neworder.html")); //replace các key {{}} content = content.Replace("{{CustomerName}}", shipName); //tùy chọn: cần 2 phone+email hoặc ít nhất 1 int infoCount = (mobile != "" ? 1 : 0) + (email != "" ? 1 : 0); if (infoCount > 0) { content = content.Replace("{{Phone}}", mobile != "" ? mobile : "trống"); content = content.Replace("{{Email}}", email != "" ? email : "trống"); } else { return(Redirect("/loi-dat-hang")); } content = content.Replace("{{Address}}", address); decimal ship = 100000; // ship 100k content = content.Replace("{{Ship}}", ship.ToString("N0") + "đ"); if (newPrice == originPrice) //ko có coupon, ko có newPrice { content = content.Replace("{{OriginPrice}}", "Giá: " + originPrice.ToString("N0") + "đ"); content = content.Replace("{{NewPrice}}", ""); } else { content = content.Replace("{{OriginPrice}}", "Giá gốc: " + originPrice.ToString("N0") + "đ"); content = content.Replace("{{NewPrice}}", "Giá mới: " + newPrice.ToString("N0") + "đ"); } content = content.Replace("{{Total}}", (newPrice + ship).ToString("N0") + "đ"); //đọc tham số từ key trong Web.config của project OnlineShop var toEmail = ConfigurationManager.AppSettings["ToEmailAddress"].ToString(); //gửi đi 2 nơi new MailHelper().SendMail(toEmail, "Đơn hàng mới từ OnlineShop đến người cung cấp sản phẩm", content); new MailHelper().SendMail(email, "Đơn hàng mới từ OnlineShop đến người đặt đơn hàng", content); //Gửi thành công // bắt đầu xử lý database //ghi order vào databasse var orderDao = new OrderDao(); var order = new Model.EF.Order(); order.CreatedDate = DateTime.Now; if (user != null) { order.CustomerID = user.UserID; } order.ShipName = shipName; order.ShipMobile = mobile; order.ShipAddress = address; order.ShipEmail = email; order.Status = -1; //đang chờ shipper nhận var orderId = orderDao.Insert(order); //xử lý OrderDetail + Product var detailDao = new OrderDetailDao(); foreach (var item in itemList) { //Xử lý OrderDetail var orderDetail = new OrderDetail(); orderDetail.ProductID = item.Product.ID; orderDetail.OrderID = orderId; orderDetail.Price = item.Product.Price; orderDetail.Quantity = item.Quantity; detailDao.Insert(orderDetail); //Xử lý sản phẩm // cập nhật số lượng sản phẩm productDao.UpdateQuantity(item.Product.ID, item.Quantity); } //xử lý coupon + CouponUser var couponDao = new CouponDao(); var couponUserDao = new CouponUserDao(); foreach (var item in couponList) { //xử lý coupon couponDao.UseCouponDiscountCode(item.Code); //Xử lý CouponUser var couponUser = new CouponUser(); couponUser.CouponID = item.ID; couponUser.UserID = user.UserID; couponUserDao.Insert(couponUser); } //gán cart+coupon null Session[Common.CommonConstants.CART_SESSION] = null; Session[Common.CommonConstants.COUPON_SESSION] = null; } catch (Exception ex) { //ghi log Logger.Log("Error" + ex.Message); return(Redirect("/loi-dat-hang")); } return(Redirect("/hoan-thanh")); }
//Pay=paypal public ActionResult PaymentWithPaypal(string Cancel = null) { UserLogin user = (UserLogin)Session[Common.CommonConstants.USER_SESSION]; var cart = (List <CartItem>)Session[Common.CommonConstants.CART_SESSION]; var itemList = new List <CartItem>(); if (cart != null) { itemList = (List <CartItem>)cart; } var coupon = (List <Coupon>)Session[Common.CommonConstants.COUPON_SESSION]; var couponList = new List <Coupon>(); if (cart != null) { couponList = (List <Coupon>)coupon; } var productDao = new ProductDao(); //check quantity+status của product foreach (var item in cart) { if (productDao.CheckProduct(item.Product.ID, item.Quantity) == false) { var alertMessage = "Số lượng sản phẩm [" + item.Product.Name + "] đã hết. Xin vui lòng chọn sản phẩm khác."; SetAlert(alertMessage, "error"); return(Redirect("/het-san-pham")); } } //getting the apiContext APIContext apiContext = helper.PaypalConfiguration.GetAPIContext(); try { //A resource representing a Payer that funds a payment Payment Method as paypal //Payer Id will be returned when payment proceeds or click to pay string payerId = Request.Params["PayerID"]; if (string.IsNullOrEmpty(payerId)) { //this section will be executed first because PayerID doesn't exist //it is returned by the create function call of the payment class // Creating a payment // baseURL is the url on which paypal sendsback the data. // So we have provided URL of this controller only string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Cart/PaymentWithPaypal?"; //here we are generating guid for storing the paymentID received in session //which will be used in the payment execution. //guid we are generating for storing the paymentID received in session //after calling the create function and it is used in the payment execution var guid = Convert.ToString((new Random()).Next(100000)); //CreatePayment function gives us the payment approval url //on which payer is redirected for paypal account payment var createdPayment = this.CreatePayment(apiContext, baseURI + "guid=" + guid); //get links returned from paypal in response to Create function call var links = createdPayment.links.GetEnumerator(); string paypalRedirectUrl = null; while (links.MoveNext()) { Links lnk = links.Current; if (lnk.rel.ToLower().Trim().Equals("approval_url")) { //saving the payapalredirect URL to which user will be redirected for payment paypalRedirectUrl = lnk.href; } } // saving the paymentID in the key guid Session.Add(guid, createdPayment.id); return(Redirect(paypalRedirectUrl)); } else { // This section is executed when we have received all the payments parameters // from the previous call to the function Create // Executing a payment var guid = Request.Params["guid"]; var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string); //If executed payment failed then we will show payment failure message to user if (executedPayment.state.ToLower() != "approved") { Session.Remove(guid); return(View("FailureView")); } //Tới đây coi như thành công //ghi order vào databasse var orderDetailDao = new Model.Dao.OrderDetailDao(); var orderCounponDao = new Model.Dao.OrderCouponDao(); var order = new Model.EF.Order(); order.CreatedDate = DateTime.Parse(executedPayment.create_time); if (user != null) { order.CustomerID = user.UserID; } order.ShipName = executedPayment.payer.payer_info.shipping_address.recipient_name; order.ShipMobile = executedPayment.payer.payer_info.shipping_address.phone; order.ShipAddress = executedPayment.payer.payer_info.shipping_address.line1 + ", " + executedPayment.payer.payer_info.shipping_address.city + ", " + executedPayment.payer.payer_info.shipping_address.state + ", " + executedPayment.payer.payer_info.shipping_address.country_code + "."; order.ShipEmail = executedPayment.payer.payer_info.email; order.Status = -1; //đang chờ shipper nhận var orderID = new OrderDao().Insert(order); decimal sumProduct = 0; foreach (var item in itemList) { //Xử lý orderDetail var orderDetail = new OrderDetail(); orderDetail.ProductID = item.Product.ID; orderDetail.OrderID = orderID; decimal?tempPrice = item.Product.PromotionPrice != null ? item.Product.PromotionPrice : item.Product.Price; orderDetail.Price = tempPrice; orderDetail.Quantity = item.Quantity; orderDetailDao.Insert(orderDetail); //Xử lý sản phẩm // cập nhật số lượng sản phẩm productDao.UpdateQuantity(item.Product.ID, item.Quantity); // sumProduct += orderDetail.Price.GetValueOrDefault(0) * orderDetail.Quantity.GetValueOrDefault(0); } //xử lý coupon + CouponUser var couponDao = new CouponDao(); var couponUserDao = new CouponUserDao(); if (couponList != null) { foreach (var item in couponList) { //xử lý coupon // giảm quantity của coupon đi 1 couponDao.UseCouponDiscountCode(item.Code); //Xử lý CouponUser var couponUser = new CouponUser(); couponUser.CouponID = item.ID; couponUser.UserID = user.UserID; couponUserDao.Insert(couponUser); //Xử lý orderCoupon var orderCoupon = new OrderCoupon(); orderCoupon.OrderID = orderID; orderCoupon.CouponID = item.ID; decimal tempAmount = 0; if (item.ByPercentage == true) { tempAmount = sumProduct * item.DiscountBy / 100; //discount theo % } else { tempAmount = item.DiscountBy; //discount cố định } orderCoupon.DiscountAmount = tempAmount; orderCounponDao.Insert(orderCoupon); } } //gán cart+coupon null Session[Common.CommonConstants.CART_SESSION] = null; Session[Common.CommonConstants.COUPON_SESSION] = null; } } catch (Exception ex) { Logger.Log("Error" + ex.Message); return(View("FailureView")); } //on successful payment, show success page to user. return(View("SuccessView")); }
public async Task <ActionResult> Complete(FormCollection fc) { try { Order order = null; if (Session["BrochureID"] != null) { ViewBag.BrochureID = Session["BrochureID"].ToString(); } else { return(RedirectPermanent("/")); } if (Session["studentID"] != null) { ViewBag.studentID = Session["studentID"].ToString(); } int orderID = -1; if (Request.Cookies["orderCookie"] != null) { int.TryParse(Request.Cookies["orderCookie"].Value.ToString(), out orderID); } else { return(View("Index", "Customer", new { ID = ViewBag.studentID })); } if (Session["Order"] == null) { return(RedirectToActionPermanent("Index", new { ID = ViewBag.studentID })); } // var cart = ShoppingCart.GetCart(this.HttpContext); order = Session["Order"] as Order; //db.Orders.Add(order); //db.SaveChanges(); if (order != null) { var cart = ShoppingCart.GetCart(this.HttpContext); var total = cart.GetTotal(); if (fc["CardType"] != null) { order.CardType = fc["CardType"].ToString(); } if (fc["CardNumber"] != null) { order.CardNumber = fc["CardNumber"].ToString(); } if (fc["CardName"] != null) { order.CardName = fc["CardName"].ToString(); } if (fc["ExpirationDate"] != null) { order.ExpirationDate = fc["ExpirationDate"].ToString(); } if (fc["ExpirationYear"] != null) { order.ExpirationYear = fc["ExpirationYear"].ToString(); } if (fc["CVVNumber"] != null) { order.CVVNumber = fc["CVVNumber"].ToString(); } OrderItem orderitem; List <OrderItem> orderarr = new List <OrderItem>(); bool shiptoschool = false; //OrderItem[] orderarr = new OrderItem[cart.GetCount()]; //int count = 0; OrderItem shipping = new OrderItem(); var CartItems = cart.GetCartItems(); foreach (Cart c in CartItems) { orderitem = new OrderItem(); //if (c.chargeShipping) //{ //} if (c.ShipToSchool) { shiptoschool = true; } orderitem.Cost = Convert.ToDecimal(c.Price); orderitem.Description = c.Description; orderitem.Quantity = c.Quantity; if (!ShrdMaster.Instance.CheckProductQty(c.productId, c.Quantity)) { string Message = "Product with name " + c.Description + " is out of stock.please wait for availability."; return(RedirectToAction("ErrorView", "Customer", new { message = Message })); } orderarr.Add(orderitem); // orderarr[count] = orderitem; // count++; } var cartTotal = cart.GetTotal(); decimal shippingcharge; double freeShippingAmount = 0; if (!shiptoschool) { //var charges = db.ShippingCharges.Where(x => x.LowerLimit >= cartTotal && x.UpperLimit <= cartTotal).SingleOrDefault(); var charges = db.ShippingCharges.Where(x => cartTotal >= x.LowerLimit && cartTotal <= x.UpperLimit).SingleOrDefault(); if (charges != null) { freeShippingAmount = charges.FreeAmount; if (Session["Organization"] != null) { var org = Session["Organization"] as Organization; if (org.FreeShippingAmount) { if (total >= freeShippingAmount) { shippingcharge = 0; } } else { shipping.Description = "Shipping"; decimal.TryParse(charges.Charge.ToString(), out shippingcharge); shipping.Cost += shippingcharge; shipping.Quantity = 1; orderarr.Add(shipping); } } } } var SalesTax = db.SalesTaxCharges.Where(x => x.Active == true).SingleOrDefault(); if (SalesTax != null) { if (ShrdMaster.Instance.CheckState(order.SState, SalesTax.State)) { shipping = new OrderItem(); decimal amount; decimal.TryParse(SalesTax.TaxAmount.ToString(), out amount); shipping.Cost += amount; shipping.Description = "SalesTax"; shipping.Quantity = 1; orderarr.Add(shipping); } } var chargeRequest = new ChargeRequest() { iTransactApiKey = ConfigurationManager.AppSettings["iTransactApiKey"], iTransactGateway = ConfigurationManager.AppSettings["iTransactTargetGateway"], iTransactUserName = ConfigurationManager.AppSettings["iTransactUsername"], BillingAddress = order.Address1, BillingCity = order.City, BillingState = order.State, BillingCountry = "US", BillingFirstName = order.FirstName, BillingLastName = order.LastName, BillingPhone = order.PhoneNumber, BillingZip = order.PostalCode, Email = order.EmailAddress, // Optional ShippingAddress = order.SAddress1, ShippingCity = order.SCity, ShippingState = order.SState, ShippingCountry = "US", ShippingFirstName = order.FirstName, ShippingLastName = order.LastName, ShippingPhone = order.PhoneNumber, ShippingZip = order.SPostalCode, CreditCardNumber = order.CardNumber, Cvv = order.CVVNumber, ExpirationMonth = order.ExpirationDate, ExpirationYear = order.ExpirationYear, //ExpirationMonth = Convert.ToInt32(order.ExpirationDate) > 10 ? order.ExpirationDate : "0" + order.ExpirationDate, //ExpirationYear = order.ExpirationYear, OrderItems = orderarr.ToArray(), //CustomerId = order.ID.ToString() }; var response = PaymentProcessor.ChargeCreditCard(chargeRequest); if (response.Status == TransactionStatus.Ok) { Logger.Instance.Log("Entered in ok part......1"); db.Orders.Add(order); db.SaveChanges(); Logger.Instance.Log("Entered in ok part......1.1"); cart.createOrder(order); Logger.Instance.Log("Entered in ok part......1.2"); if (Request.Cookies["Coupon"] != null) { string code = ""; code = Request.Cookies["Coupon"].Value; var coupon = db.Coupons.Where(cp => cp.Code == code).SingleOrDefault(); if (coupon.CouponUsage == 2) { coupon.Active = false; db.Entry(coupon).State = EntityState.Modified; db.SaveChanges(); } //Adding values to coupon User tbale CouponUser cpnUser = new CouponUser(); cpnUser.FirstName = order.FirstName; cpnUser.LastName = order.LastName; cpnUser.EmailID = order.EmailAddress; cpnUser.Couponcode = coupon.Code; db.CouponUsers.Add(cpnUser); db.SaveChanges(); } Logger.Instance.Log("Entered in ok part......2"); /// convert to PDF HtmlToPdf Convertor = new HtmlToPdf(); Logger.Instance.Log("Entered in ok part......2.1"); //// create a new pdf document converting an url // string url = "http://localhost:51369/Customer/InvoicePrint?orderID=" + order.ID + "&PDF=1&cartID=" + cart.GetCartId(this.HttpContext); string url = "http://fundraising.infodatixhosting.com/Customer/InvoicePrint?orderID=" + order.ID + "&PDF=1&cartID=" + cart.GetCartId(this.HttpContext); Logger.Instance.Log("Entered in ok part......2.3"); Logger.Instance.Log("Entered in ok part......3"); string htmlCode; using (WebClient client = new WebClient()) { // Download as a string. Logger.Instance.Log("Entered in ok part......3.1"); htmlCode = client.DownloadString(url); Logger.Instance.Log("Entered in ok part......4"); } Logger.Instance.Log("Entered in ok part......5"); // PdfPageSize pdfpagesize = PdfPageSize.B5; // Convertor.Options.PdfPageSize = pdfpagesize; Convertor.Options.MarginTop = 50; Convertor.Options.MarginBottom = 50; // Convertor.Options.WebPageHeight = 1000; PdfDocument doc = Convertor.ConvertHtmlString(htmlCode); string path = Server.MapPath("/PDF//"); path += order.ID + "_Receipt.Pdf"; //HtmlToPdf opt = new HtmlToPdf(); //HtmlToPdfOptions options = new HtmlToPdfOptions(); //options.MarginTop = 2; // PdfMargins margin=new PdfMargins (1.5f); //doc.Margins = margin; doc.Save(path); Logger.Instance.Log("Entered in ok part......1"); // close pdf document doc.Close(); //sending mail var student = db.Students.Where(s => s.StudentID == order.StudentID).SingleOrDefault(); var org = db.Organizations.Find(order.SchoolID); EmailService email = new EmailService(path); IdentityMessage details = new IdentityMessage(); details.Destination = order.EmailAddress; details.Subject = "Receipt! Fundraisingshop.com"; Dictionary <string, string> param = new Dictionary <string, string>(); if (org != null) { param.Add("<%Student%>", student.FirstName + " " + student.LastName); param.Add("<%School%>", org.Name); } else { param.Add("<%Student%>", " "); param.Add("<%School%>", " "); } param.Add("<%customer%>", order.FullName); details.Body = ShrdMaster.Instance.buildEmailBody("InvoiceEmailTemplate.txt", param); string attachment = path; await email.SendAsync(details); Logger.Instance.Log("Entered in ok part......6"); cart.EmptyCart(); return(View("Complete1")); //System.Console.WriteLine("Transaction OK"); //System.Console.WriteLine("Transaction Id: " + response.TransactionId); } else { // db.Orders.Remove(order); // db.SaveChanges(); // ShrdMaster.Instance.RemoverOrderDetails(order.ID); string Message = "<span><h3>Transaction declined.</h3></span> <br/> <b>" + response.ErrorMessage + "</b>"; //"<span><h3>Transaction declined.</h3></span> <br/> <b>In pattern AccountInfo: AccountNumber must be between 13 and 16 digits </b>" return(RedirectToAction("ErrorView", "Customer", new { option = 1, message = Message })); //var cartITems = cart.GetCartItems(); //foreach (Cart c in cartITems) //{ // var product = db.Products.Find(c.productId); // product.InventoryAmount += c.Quantity; // db.Entry(product).State = EntityState.Modified; // db.SaveChanges(); //} //System.Console.WriteLine("ERROR!!!!"); //System.Console.WriteLine("AVS Error: " + response.Avs); //System.Console.WriteLine("Error Message: " + response.ErrorMessage); //System.Console.WriteLine("Xml: " + response.RawXml); } //if (response.IsSuccessStatusCode) //{ //} //else //{ //} ////doc.SelectSingleNode("//AccountInfo//CardAccount//TrackData").InnerText = "TRACK DATA"; ////doc.SelectSingleNode("//AccountInfo//CardAccount//Ksn").InnerText = "12345"; ////doc.SelectSingleNode("//AccountInfo//CardAccount//Pin").InnerText = "1234"; ////XmlTextReader xmlFile = new XmlTextReader(xmlUrl); ////XmlTextWriter write = new XmlTextWriter (xmlUrl,null); ////write.WriteElementString("Email", order.EmailAddress); ////write.WriteElementString("CustId", XmlConvert.ToString(order.ID)); ////write.WriteElementString("Address1", order.Address1); ////write.WriteElementString("Address2", order.Address2); ////string file; ////while(xmlFile.Read()) ////{ //// file+=xmlFile.reade ////} //if (Transaction() % 2 == 0) //{ // //getting cart information to update in orders //} //else //{ //} } return(RedirectToAction("ErrorView", "Customer", new { message = "some error has occured." })); //return RedirectToAction("InvoicePrint", "Customer", new { orderID=orderID,PDF=1}); //return View("Index", "Customer", new { ID=order.StudentID}); } catch (Exception ex) { // ViewBag.Error = ex.Message; return(RedirectToAction("ErrorView", "Customer", new { message = ex.Message })); } }