public string ProcessCcAvenuePostBack(int paymentTypeId,string transId, int userId, int userType, int transactionType,string invoiceIds, string debitNoteIds, string description,double sellingCurrencyAmount, double accountingCurrencyAmount,  string username, string address1, string city,string state, string zip, string country, string telno,string emailaddr, string ccAvenueMerchantId, string ccAvenueWorkingKey, string ccAvenueRedirectUrl)
        {
            var ccAvenuePostForm = new StringBuilder();
            try
            {
                /*int paymentTypeId = Convert.ToInt32(request.QueryString["paymenttypeid"]);
                string transId = request.QueryString["transid"];
                int userId = Convert.ToInt32(request.QueryString["userid"]);
                int userType = Convert.ToInt32(request.QueryString["usertype"]);
                int transactionType = Convert.ToInt32(request.QueryString["transactiontype"]);
                string invoiceIds = request.QueryString["invoiceids"];
                string debitNoteIds = request.QueryString["debitnoteids"];
                string description = request.QueryString["description"];
                double sellingCurrencyAmount = Convert.ToDouble(request.QueryString["sellingcurrencyamount"]);
                double accountingCurrencyAmount = Convert.ToDouble(request.QueryString["accountingcurrencyamount"]);
                string redirectUrl = request.QueryString["redirecturl"];
                string checksum = request.QueryString["checksum"];

                if (transId == null)
                    transId = string.Empty;
                if (invoiceIds == null)
                    invoiceIds = string.Empty;
                if (debitNoteIds == null)
                    debitNoteIds = string.Empty;

                if (Utilities.VerifyChecksum(paymentTypeId.ToString(), transId, userId.ToString(), userType.ToString(), transactionType.ToString(), invoiceIds, debitNoteIds, description, sellingCurrencyAmount.ToString(), accountingCurrencyAmount.ToString(), ccAvenueChecksumSaltKey, checksum))
                {
                    string username = request.QueryString["name"];
                    string emailaddr = request.QueryString["emailaddr"];
                    string address1 = request.QueryString["address1"];
                    string address2 = request.QueryString["address2"];
                    string address3 = request.QueryString["address3"];
                    string city = request.QueryString["city"];
                    string state = request.QueryString["state"];
                    string country = request.QueryString["country"];
                    string zip = request.QueryString["zip"];
                    string telno = request.QueryString["telno"];
                    string faxnocc = request.QueryString["faxNoCc"];

                    // saving transaction into DB
                    var scope = ObjectScopeProvider1.GetNewObjectScope();
                    scope.Transaction.Begin();

                    var user = new User
                                   {
                                       Username = username,
                                       Address = address1 + Environment.NewLine + address2 + Environment.NewLine + address3,
                                       City = city,
                                       Country = country,
                                       Email = emailaddr,
                                       Faxno = faxnocc,
                                       State = state,
                                       Mobileno = telno,
                                       Zip = zip
                                   };

                    var preTransactionDetails = new PreTransactionDetails
                                                    {
                                                        DebitNoteId = debitNoteIds,
                                                        Description = description,
                                                        EntryTime = DateTime.Now,
                                                        InvoiceIds = invoiceIds,
                                                        PaymentTypeId = (PaymentTypes)paymentTypeId,
                                                        RedirectUrl = redirectUrl,
                                                        SellingCurrencyAmount = sellingCurrencyAmount,
                                                        TransactionId = transId,
                                                        TransactionStatus = TransactionStatus.Requested,
                                                        TransactionType = (TransactionTypes)transactionType,
                                                        //User = user
                                                    };

                    scope.Add(preTransactionDetails);
                    scope.Transaction.Commit(); */

                    // Preparing post form for cc avenue
                    string ccavenuechecksum = Utilities.Getchecksum(ccAvenueMerchantId, transId, sellingCurrencyAmount.ToString(), ccAvenueRedirectUrl, ccAvenueWorkingKey);
                    ccAvenuePostForm.Append("<form method='post' name='paymentpage' action='https://www.ccavenue.com/shopzone/cc_details.jsp'>");
                    ccAvenuePostForm.Append("<input type='hidden' name='Order_Id' value='" + transId + "' runat='server' />");
                    ccAvenuePostForm.Append("<input type='hidden' name='Amount' value='" + sellingCurrencyAmount + "' runat='server' />");
                    ccAvenuePostForm.Append("<input type='hidden' name='Merchant_Id' value='" + ccAvenueMerchantId + "' runat='server'  />");
                    ccAvenuePostForm.Append("<input type='hidden' name='Redirect_Url' value='" + ccAvenueRedirectUrl + "' runat='server'  />");
                    ccAvenuePostForm.Append("<input type='hidden' name='Currency' value='USD'  runat='server'  />");
                    ccAvenuePostForm.Append("<input type='hidden' name='TxnType' value='A'  runat='server'  />");
                    ccAvenuePostForm.Append("<input type='hidden' name='ActionID' value='TXN'  runat='server'  />");
                    ccAvenuePostForm.Append("<input type='hidden' name='Checksum' value='" + ccavenuechecksum + "'  runat='server'  />");
                    ccAvenuePostForm.Append("<input type='hidden' name='billing_cust_name' value='" + username + "'  runat='server'  />");
                    ccAvenuePostForm.Append("<input type='hidden' name='billing_middle_name' value=''  runat='server'  />");
                    ccAvenuePostForm.Append("<input type='hidden' name='billing_last_name' value=''  runat='server'  />");
                    ccAvenuePostForm.Append("<input type='hidden' name='billing_cust_address' value='" + address1 + "'  runat='server'  />");
                    ccAvenuePostForm.Append("<input type='hidden' name='billing_cust_city' value='" + city + "'  runat='server'  />");
                    ccAvenuePostForm.Append("<input type='hidden' name='billing_cust_state' value='" + state + "'  runat='server'  />");
                    ccAvenuePostForm.Append("<input type='hidden' name='billing_zip_code' value='" + zip + "'  runat='server'  />");
                    ccAvenuePostForm.Append("<input type='hidden' name='billing_cust_country' value='" + country + "'  runat='server'  />");
                    ccAvenuePostForm.Append("<input type='hidden' name='billing_cust_tel_Ctry' value='" + telno + "'  runat='server'  />");
                    ccAvenuePostForm.Append("<input type='hidden' name='billing_cust_tel' value='" + telno + "'  runat='server'  />");
                    ccAvenuePostForm.Append("<input type='hidden' name='billing_cust_email' value='" + emailaddr + "'  runat='server'  />");
                    ccAvenuePostForm.Append("</form>");
                //}
            }
            catch (Exception exception)
            {
                if (_isErrorMailConfigured)
                {
                    //Mail Sending here
                    var sendmail = new SendMailViaGmail
                                       {
                                           PGmailAccount = _gmailUsername,
                                           PGmailPassword = _gmailPassword
                                       };
                    var messageBody = new StringBuilder();
                    messageBody.Append("The following error has been raised while processing online payment transaction <br />");
                    messageBody.Append("<Br /> Error: ");
                    messageBody.Append(!string.IsNullOrEmpty(exception.StackTrace) ? exception.StackTrace : exception.Message);
                    sendmail.SendMail(_tomails, "CC Avenue Integration Module Error", messageBody.ToString(), null);
                }
                throw;
            }

            return ccAvenuePostForm.ToString();
        }
        public ActionResult Checkout()
        {
            if (User.Identity.IsAuthenticated)
            {
                string transactionID = string.Empty;
                var scope = ObjectScopeProvider1.GetNewObjectScope();
                var mycarts = (from c in scope.GetOqlQuery<User>().ExecuteEnumerable()
                               from d in c.PreTransactionDetailses
                               from e in d.MyCarts
                               where !c.Username.Equals(DBNull.Value) &&
                                   c.Username.ToLower().Equals(User.Identity.Name.ToLower()) &&
                                   d.TransactionStatus == TransactionStatus.Pending && e.Product != null
                               select e).ToList();
                var users = (from c in scope.GetOqlQuery<User>().ExecuteEnumerable()
                             where c.Username.ToLower().Equals(User.Identity.Name.ToLower())
                             select c).ToList();

                if (users.Count > 0)
                {
                    var pretransactions = (from c in scope.GetOqlQuery<User>().ExecuteEnumerable()
                                           from d in c.PreTransactionDetailses
                                           where !c.Username.Equals(DBNull.Value) &&
                                                 c.Username.ToLower().Equals(User.Identity.Name.ToLower()) &&
                                                 d.TransactionStatus == TransactionStatus.Pending
                                           select d).ToList();
                    if (pretransactions.Count > 0)
                        transactionID = pretransactions[0].TransactionId;
                    if (string.IsNullOrEmpty(transactionID))
                    {

                        string productInfo = string.Empty;
                        double totalamount = 0.0;
                        foreach (var mycart in mycarts)
                        {
                            totalamount += mycart.Product.Price*mycart.Quantity;
                            productInfo += "<p><b>Product name        :</b> " + mycart.Product.Name + " <br></p>";
                            productInfo += "<p><b>        Category    :</b> " + mycart.Product.Category + " <br></p>";
                            productInfo += "<p><b>        Price       :</b> " + mycart.Product.Price + " <br></p>";
                            productInfo += "<p><b>Quantity            :</b> " + mycart.Quantity + " <br></p>";
                            productInfo += "<p><br><br></p>";
                        }

                        var sendMailViaGmail = new SendMailViaGmail();
                        sendMailViaGmail.PGmailAccount = Utilities.Gmailid;
                        sendMailViaGmail.PGmailPassword = Utilities.Gmailpassword;
                        // mail sending here to the admin to say that somebody tried to pay online
                        try
                        {
                            var user = users[0];

                            var stringBuilder = new StringBuilder();
                            stringBuilder.Append(
                                @"<table border='0' cellpadding='0' cellspacing='0' width='98%'><tbody><tr><td style='padding: 10px 15px 40px; font-family: Helvetica,Arial,sans-serif; font-size: 16px; line-height: 1.3em; text-align: left;' valign='top'><h1 style='font-family: Helvetica,Arial,sans-serif; color: rgb(34, 34, 34); font-size: 28px; line-height: normal; letter-spacing: -1px;'>Online transaction initiated.</h1><p>Hi <b>Srigreensentei</b>,</p><p>Here is the transaction details.</p>");
                            stringBuilder.Append("<p><b>Transaction ID      :</b> " + transactionID + " <br></p>");
                            stringBuilder.Append("<p><b>Username            :</b> " + user.Username + " <br></p>");
                            stringBuilder.Append("<p><b>Email               :</b> " + user.Email + " <br></p>");
                            stringBuilder.Append("<p><b>Mobile              :</b> " + user.Mobileno + " <br></p>");
                            stringBuilder.Append(productInfo);
                            stringBuilder.Append("<p><b>Total amount        :</b> " + totalamount + " <br></p>");
                            stringBuilder.Append(
                                @"<hr) style='margin-top: 30px; border-right: medium none; border-width: 1px medium medium; border-style: solid none none; border-color: rgb(204, 204, 204) -moz-use-text-color -moz-use-text-color;'><p style='font-size: 13px; line-height: 1.3em;'></p></td></tr></tbody></table>");
                            sendMailViaGmail.SendMail(Utilities.Srigreenmails,
                                                      "A new user registered with us.", stringBuilder.ToString(),
                                                      new List<string>());

                        }
                        catch (Exception)
                        {
                        }

                        var toccavenue = new ToCcAvenue();
                        toccavenue.ConfigureEmail(Utilities.Gmailid, Utilities.Gmailpassword, Utilities.Srigreenmails);
                        ViewData["PostBackData"] = toccavenue.ProcessCcAvenuePostBack(2, transactionID
                                                                                      ,
                                                                                      3, 2, 4,
                                                                                      new Random().NextDouble().ToString
                                                                                          (),
                                                                                      new Random().NextDouble().ToString
                                                                                          (),
                                                                                      "Srigreen product selling online",
                                                                                      totalamount, totalamount,
                                                                                      User.Identity.Name,
                                                                                      users[0].DeliveryAddress,
                                                                                      users[0].DeliveryCity,
                                                                                      users[0].DeliveryState,
                                                                                      users[0].DeliveryPin,
                                                                                      users[0].DeliveryCountry,
                                                                                      users[0].Mobileno, users[0].Email,
                                                                                      "M_domain2h_14761",
                                                                                      "v5n8ti6siksqh5r4hi",
                                                                                      "http://srigreensentei.com/ShoppingCart/Payment");
                        return View();
                    }
                }
                return RedirectToAction("PaymentOptions");
            }
            return Redirect("/Account/LogOn");
        }
        public TransactionStatus ProcessCcAvenueData(NameValueCollection form, string ccAvenueWorkingKey)
        {
            try
            {
                string merchantId = form["Merchant_Id"];
                string orderId = form["Order_Id"];
                string amount = form["Amount"];
                string authDesc = form["AuthDesc"];
                string chksum = form["Checksum"];
                string checksum = Utilities.Verifychecksum(merchantId, orderId, amount, authDesc, ccAvenueWorkingKey, chksum);
                if (checksum == null)
                {
                    return TransactionStatus.Forgery;
                }
                if (checksum == "true")
                {
                    if (authDesc == "Y")
                    {
                        // modify the status and sending mail
                        var scope = ObjectScopeProvider1.GetNewObjectScope();
                        List<PreTransactionDetails> transactionDetailses = (from c in scope.GetOqlQuery<PreTransactionDetails>().ExecuteEnumerable()
                                                                            where c.TransactionId.Equals(orderId)
                                                                            select c).ToList();
                        if (transactionDetailses.Count > 0)
                        {
                            // modifying status here

                            scope.Transaction.Begin();
                            transactionDetailses[0].TransactionStatus = CCAvenueIntegrationDL.TransactionStatus.Completed;
                            scope.Add(transactionDetailses[0]);
                            scope.Transaction.Commit();

                            try
                            {
                                //Mail Sending here
                                var sendmail = new SendMailViaGmail
                                                   {
                                                       PGmailAccount = _gmailUsername,
                                                       PGmailPassword = _gmailPassword
                                                   };
                                var messageBody = new StringBuilder();
                                messageBody.Append("The sales transaction had been processed with the following details <br />");
                                messageBody.Append("Trans-ID : " + orderId + "<br/>");
                                /*messageBody.Append("Username : "******"<br/>");
                                messageBody.Append("Email : " + transactionDetailses[0].User.Email + "<br/>");
                                messageBody.Append("Address: " + transactionDetailses[0].User.Address + "<br/>");
                                messageBody.Append("City: " + transactionDetailses[0].User.City + "<br/>");
                                messageBody.Append("State: " + transactionDetailses[0].User.State + "<br/>");
                                messageBody.Append("Country: " + transactionDetailses[0].User.Country + "<br/>");
                                messageBody.Append("Mobile no: " + transactionDetailses[0].User.Mobileno + "<br/>"); */
                                messageBody.Append("Amount: " + amount + "<br/>");
                                sendmail.SendMail(_tomails, "Transaction Details", messageBody.ToString(), null);
                            }
                            catch (Exception)
                            {
                                return TransactionStatus.Success;
                            }
                        }
                        return TransactionStatus.Success;
                    }
                    if (authDesc == "N")
                    {
                        return TransactionStatus.Declined;
                    }
                    if (authDesc == "B")
                    {
                        return TransactionStatus.PostPoned;
                    }
                    return TransactionStatus.PostPoned;
                }
            }
            catch (Exception exception)
            {
                if (_isErrorMailConfigured)
                {
                    //Mail Sending here
                    var sendmail = new SendMailViaGmail
                    {
                        PGmailAccount = _gmailUsername,
                        PGmailPassword = _gmailPassword
                    };
                    var messageBody = new StringBuilder();
                    messageBody.Append("The following error has been raised while processing online payment transaction <br />");
                    messageBody.Append("<Br /> Error: ");
                    messageBody.Append(!string.IsNullOrEmpty(exception.StackTrace) ? exception.StackTrace : exception.Message);
                    sendmail.SendMail(_tomails, "CC Avenue Integration Module Error", messageBody.ToString(), null);
                }
                throw;
            }
            return TransactionStatus.Forgery;
        }
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);
                if (createStatus == MembershipCreateStatus.Success)
                {
                    var scope = ObjectScopeProvider1.GetNewObjectScope();
                    int count = (from c in scope.GetOqlQuery<User>().ExecuteEnumerable()
                                 where !c.Username.Equals(DBNull.Value) && c.Username.ToLower().Equals(model.UserName.ToLower())
                                 select c).Count();
                    if (count == 0)
                    {
                        scope.Transaction.Begin();
                        var user = new User();
                        user.BillingAddress = model.BillingAddress;
                        user.BillingCity = model.BillingCity;
                        user.BillingCountry = model.BillingCountry;
                        user.BillingFaxno = model.BillingFaxno;
                        user.BillingPin = model.BillingPin;
                        user.BillingState = model.BillingState;

                        if (Request.Form["yes"] == "true" || Request.Form["yes"] == "on")
                        {
                            user.DeliveryAddress = model.BillingState;
                            user.DeliveryCity = model.BillingCity;
                            user.DeliveryCountry = model.BillingCountry;
                            user.DeliveryPin = model.BillingPin;
                            user.DeliveryState = model.BillingState;
                        }
                        else
                        {
                            user.DeliveryAddress = model.DeliveryState;
                            user.DeliveryCity = model.DeliveryCity;
                            user.DeliveryCountry = model.DeliveryCountry;
                            user.DeliveryPin = model.DeliveryPin;
                            user.DeliveryState = model.DeliveryState;
                        }

                        user.Email = model.Email;
                        user.IsheAdmin = false;
                        user.Mobileno = model.Mobile;
                        user.Username = model.UserName;

                        scope.Add(user);
                        scope.Transaction.Commit();
                        FormsService.SignIn(model.UserName, false /* createPersistentCookie */);

                        var sendMailViaGmail = new SendMailViaGmail();
                        sendMailViaGmail.PGmailAccount = Utilities.Gmailid;
                        sendMailViaGmail.PGmailPassword = Utilities.Gmailpassword;

                        // mail sending here to the admin
                        try
                        {
                            var stringBuilder = new StringBuilder();
                            stringBuilder.Append(@"<table border='0' cellpadding='0' cellspacing='0' width='98%'><tbody><tr><td style='padding: 10px 15px 40px; font-family: Helvetica,Arial,sans-serif; font-size: 16px; line-height: 1.3em; text-align: left;' valign='top'><h1 style='font-family: Helvetica,Arial,sans-serif; color: rgb(34, 34, 34); font-size: 28px; line-height: normal; letter-spacing: -1px;'>A new user registered!</h1><p>Hi <b>Srigreensentei</b>,</p><p>Here is the new user registered details.</p>");

                            stringBuilder.Append("<p><b>Username            :</b> " + user.Username + " <br></p>");
                            stringBuilder.Append("<p><b>Email               :</b> " + user.Email + " <br></p>");
                            stringBuilder.Append("<p><b>Mobile              :</b> " + user.Mobileno + " <br></p>");

                            stringBuilder.Append("<p><b>Billing Address     :</b> " + user.BillingAddress + " <br></p>");
                            stringBuilder.Append("<p><b>        City        :</b> " + user.BillingCity + " <br></p>");
                            stringBuilder.Append("<p><b>        State       :</b> " + user.BillingState + " <br></p>");
                            stringBuilder.Append("<p><b>        Country     :</b> " + user.BillingCountry + " <br></p>");
                            stringBuilder.Append("<p><b>        Pin Code    :</b> " + user.BillingPin + " <br></p>");
                            stringBuilder.Append("<p><b>        Fax No      :</b> " + user.BillingFaxno + " <br></p>");

                            stringBuilder.Append("<p><b>Delivery Address    :</b> " + user.BillingAddress + " <br></p>");
                            stringBuilder.Append("<p><b>         City       :</b> " + user.BillingCity + " <br></p>");
                            stringBuilder.Append("<p><b>         State      :</b> " + user.BillingState + " <br></p>");
                            stringBuilder.Append("<p><b>         Country    :</b> " + user.BillingCountry + " <br></p>");
                            stringBuilder.Append("<p><b>         Code       :</b> " + user.BillingPin + " <br></p>");
                            stringBuilder.Append("<p><b>         Fax No     :</b> " + user.BillingFaxno + " <br></p>");

                            stringBuilder.Append(@"<hr) style='margin-top: 30px; border-right: medium none; border-width: 1px medium medium; border-style: solid none none; border-color: rgb(204, 204, 204) -moz-use-text-color -moz-use-text-color;'><p style='font-size: 13px; line-height: 1.3em;'></p></td></tr></tbody></table>");
                            sendMailViaGmail.SendMail(Utilities.Srigreenmails,
                                                      "A new user registered with us.", stringBuilder.ToString(),
                                                      new List<string>());
                        }
                        catch (Exception)
                        {
                        }

                        // mail sending here to the user
                        try
                        {
                            var stringBuilder = new StringBuilder();
                            stringBuilder.Append(@"<table border='0' cellpadding='0' cellspacing='0' width='98%'><tbody><tr><td style='padding: 10px 15px 40px; font-family: Helvetica,Arial,sans-serif; font-size: 16px; line-height: 1.3em; text-align: left;' valign='top'><h1 style='font-family: Helvetica,Arial,sans-serif; color: rgb(34, 34, 34); font-size: 28px; line-height: normal; letter-spacing: -1px;'>You have registered with us!</h1><p>Hi <b>" + user.Username + "</b>,</p><p>Your account has been created with us. Here is your account details.</p>");

                            stringBuilder.Append("<p><b>Username            :</b> " + user.Username + " <br></p>");
                            stringBuilder.Append("<p><b>Email               :</b> " + user.Email + " <br></p>");
                            stringBuilder.Append("<p><b>Mobile              :</b> " + user.Mobileno + " <br></p>");

                            stringBuilder.Append("<p><b>Billing Address     :</b> " + user.BillingAddress + " <br></p>");
                            stringBuilder.Append("<p><b>        City        :</b> " + user.BillingCity + " <br></p>");
                            stringBuilder.Append("<p><b>        State       :</b> " + user.BillingState + " <br></p>");
                            stringBuilder.Append("<p><b>        Country     :</b> " + user.BillingCountry + " <br></p>");
                            stringBuilder.Append("<p><b>        Pin Code    :</b> " + user.BillingPin + " <br></p>");
                            stringBuilder.Append("<p><b>        Fax No      :</b> " + user.BillingFaxno + " <br></p>");

                            stringBuilder.Append("<p><b>Delivery Address    :</b> " + user.BillingAddress + " <br></p>");
                            stringBuilder.Append("<p><b>         City       :</b> " + user.BillingCity + " <br></p>");
                            stringBuilder.Append("<p><b>         State      :</b> " + user.BillingState + " <br></p>");
                            stringBuilder.Append("<p><b>         Country    :</b> " + user.BillingCountry + " <br></p>");
                            stringBuilder.Append("<p><b>         Code       :</b> " + user.BillingPin + " <br></p>");
                            stringBuilder.Append("<p><b>         Fax No     :</b> " + user.BillingFaxno + " <br></p>");

                            stringBuilder.Append(@"<hr) style='margin-top: 30px; border-right: medium none; border-width: 1px medium medium; border-style: solid none none; border-color: rgb(204, 204, 204) -moz-use-text-color -moz-use-text-color;'><p style='font-size: 13px; line-height: 1.3em;'></p></td></tr></tbody></table>");
                            sendMailViaGmail.SendMail(new List<string>() { user.Email },
                                                      "Your account has been created at Srigreensentei", stringBuilder.ToString(),
                                                      new List<string>());
                        }
                        catch (Exception)
                        {
                        }

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

                    ModelState.AddModelError("UserName", "Username already exists.");
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }