示例#1
0
        public void ThrowException_CardNameIsEmptyOrNull()
        {
            var paymentProcessor = new PaymentProcessor();

            Assert.ThrowsAny <Exception>(() => paymentProcessor.ChargeCreditCard(""));
        }
        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 }));
            }
        }