/// <summary>
 /// Handles the Click event of the btnSave control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
 protected void btnSave_Click(object sender, EventArgs e)
 {
     if(!string.IsNullOrEmpty(txtShippingTrackingNumber.Text)) {
     try {
       Order order = new Order(orderId);
       order.ShippingTrackingNumber = txtShippingTrackingNumber.Text;
       order.Save(WebUtility.GetUserName());
       MessageService messageService = new MessageService();
       messageService.SendShippingNotificationToCustomer(order);
       base.MasterPage.MessageCenter.DisplaySuccessMessage(LocalizationUtility.GetText("lblShippingSaved"));
     }
     catch(Exception ex) {
       Logger.Error(typeof(shipping).Name + ".btnSave_Click", ex);
       base.MasterPage.MessageCenter.DisplayCriticalMessage(ex.Message);
     }
       }
 }
Example #2
0
        /// <summary>
        /// Handles the Click event of the btnOrderStatus control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        protected void btnOrderStatus_Click(object sender, EventArgs e)
        {
            try {
            Order order = new Order(orderId);
            int orderStatusDescriptorId = order.OrderStatusDescriptorId;
            bool isParsed = int.TryParse(ddlOrderStatus.SelectedValue, out orderStatusDescriptorId);
            if(!isParsed) {
              orderStatusDescriptorId = order.OrderStatusDescriptorId;
            }
            order.OrderStatusDescriptorId = orderStatusDescriptorId;
            order.Save(WebUtility.GetUserName());
            base.MasterPage.MessageCenter.DisplaySuccessMessage(LocalizationUtility.GetText("lblOrderStatusChanged"));

              }
              catch(Exception ex) {
            Logger.Error(typeof(actions).Name + ".btnOrderStatus_Click", ex);
            base.MasterPage.MessageCenter.DisplayCriticalMessage(ex.Message);
              }
        }
Example #3
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init"></see> event to initialize the page.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            if (Master.SiteSettings.LoginRequirement == LoginRequirement.Checkout) {
            if (!User.Identity.IsAuthenticated) {
              Response.Redirect("login.aspx?ReturnUrl=/checkout.aspx", true);
            }
              }

              PaymentService paymentService = new PaymentService();
              if (paymentService.PaymentServiceSettings.DefaultProvider == "PayPalStandardPaymentProvider") {
            Response.Redirect("~/paypalcheckout.aspx", true);
              }

              //Keep these here - the Accordion ViewState is funky and requires things to be set early
              Label lblBillingInformation = acCheckout.Panes[0].FindControl("lblBillingInformation") as Label;
              Label lblShippingInformation = acCheckout.Panes[1].FindControl("lblShippingInformation") as Label;
              Label lblShippingMethod = acCheckout.Panes[2].FindControl("lblShippingMethod") as Label;
              Label lblCouponInformation = acCheckout.Panes[3].FindControl("lblCouponInformation") as Label;
              Label lblPaymentInformation = acCheckout.Panes[4].FindControl("lblPaymentInformation") as Label;
              Label lblOrderReview = acCheckout.Panes[5].FindControl("lblOrderReview") as Label;

              //See if there are any coupons in the system
              //If not, then don't display the coupon stuff
              couponCollection = new CouponController().FetchAll();
              if (couponCollection.Count == 0) {
            hasCoupons = false;
            acpCoupon.Visible = false;
            pnlCouponInformationDisplayTitle.Visible = false;
            pnlCouponInformationDisplay.Visible = false;
              }

              shippingService = new ShippingService();
              if (!shippingService.ShippingServiceSettings.UseShipping) {
            acCheckout.Panes[1].Visible = false;
            acCheckout.Panes[2].Visible = false;
            pnlShippingAddressDisplayTitle.Visible = false;
            pnlShippingAddressDisplay.Visible = false;
            pnlShippingMethodDisplayTitle.Visible = false;
            pnlShippingMethodDisplay.Visible = false;
              }

              //Keep these here - the Accordion ViewState is funky and requires things to be set early
              order = new OrderController().FetchOrder(WebUtility.GetUserName());

              #region PayPal Express Checkout Logic

              if (!string.IsNullOrEmpty(order.PaymentMethod)) {
            if (order.PaymentMethod == "PayPal") {
              string token = Utility.GetParameter("token");
              if (!string.IsNullOrEmpty(token)) {
            pnlCreditCardInformation.Visible = false;
            pnlCreditCardInfo.Visible = false;
            lblCreditCardType.Text = order.PaymentMethod;
            ddlCreditCardType.SelectedValue = "4";
            ddlCreditCardType.Enabled = false;
            PayPalPayer payPalPayer = OrderController.GetExpressCheckout(token);
            if (order.BillingAddress == null) {//Then they are coming in from the cart.aspx ExpressCheckout button
              //copy the PayPalPayer ShippingAddress and then flag it as a BillingAddress
              Address billingAddress = new Address(payPalPayer.ShippingAddress);
              billingAddress.AddressType = AddressType.BillingAddress;
              Address duplicateBillingAddress = WebProfile.Current.AddressCollection.Find(
                addressToFind =>
                addressToFind.ToString() == billingAddress.ToString() &&
                addressToFind.AddressType == AddressType.BillingAddress);
              if (duplicateBillingAddress == null) {
                WebProfile.Current.AddressCollection.Add(billingAddress);
                WebProfile.Current.Save();
              }
              order.BillToAddress = payPalPayer.ShippingAddress.ToXml();
            }
            if (!payPalPayer.ShippingAddress.Equals(order.ShippingAddress)) {
              Address shippingAddress = new Address(payPalPayer.ShippingAddress);
              shippingAddress.AddressType = AddressType.ShippingAddress;
              Address duplicateShippingAddress = WebProfile.Current.AddressCollection.Find(
                  addressToFind =>
                  addressToFind.ToString() == shippingAddress.ToString() &&
                  addressToFind.AddressType == AddressType.ShippingAddress);
              if (duplicateShippingAddress == null) {
                WebProfile.Current.AddressCollection.Add(shippingAddress);
                WebProfile.Current.Save();
              }
              order.ShipToAddress = payPalPayer.ShippingAddress.ToXml();
            }
            if (order.ExtendedProperties.ContainsKey(PAYPAL_PAYER_ID)) {
              order.ExtendedProperties.Remove(PAYPAL_PAYER_ID);
            }
            if (order.ExtendedProperties.ContainsKey(PAYPAL_TOKEN)) {
              order.ExtendedProperties.Remove(PAYPAL_TOKEN);
            }
            order.ExtendedProperties.Add(PAYPAL_PAYER_ID, payPalPayer.PayPalPayerId);
            order.ExtendedProperties.Add(PAYPAL_TOKEN, payPalPayer.PayPalToken);
            order.AdditionalProperties = order.ExtendedProperties.ToXml();
            order.Save(WebUtility.GetUserName());
            OrderController.CalculateTax(WebUtility.GetUserName());
            order = new OrderController().FetchOrder(WebUtility.GetUserName());
              }
            }
              }

              #endregion

              if (!Page.IsPostBack) {
            SetBillingAddressDisplay();

            SetShippingAddressDisplay();

            SetShippingMethodDisplay();

            SetCouponDisplay();

            SetPaymentMethodDisplay(-1, order.CreditCardNumber, DateTime.MinValue);
              }
              base.OnInit(e);
        }
        public void Insert(Guid OrderGuid,string OrderNumber,int OrderTypeId,int OrderParentId,int OrderStatusDescriptorId,string UserName,decimal ShippingAmount,string ShippingMethod,decimal HandlingAmount,string BillToAddress,string ShipToAddress,string IPAddress,string PaymentMethod,string ShippingTrackingNumber,string AdditionalProperties,string CreatedBy,DateTime CreatedOn,string ModifiedBy,DateTime ModifiedOn)
        {
            Order item = new Order();

            item.OrderGuid = OrderGuid;

            item.OrderNumber = OrderNumber;

            item.OrderTypeId = OrderTypeId;

            item.OrderParentId = OrderParentId;

            item.OrderStatusDescriptorId = OrderStatusDescriptorId;

            item.UserName = UserName;

            item.ShippingAmount = ShippingAmount;

            item.ShippingMethod = ShippingMethod;

            item.HandlingAmount = HandlingAmount;

            item.BillToAddress = BillToAddress;

            item.ShipToAddress = ShipToAddress;

            item.IPAddress = IPAddress;

            item.PaymentMethod = PaymentMethod;

            item.ShippingTrackingNumber = ShippingTrackingNumber;

            item.AdditionalProperties = AdditionalProperties;

            item.CreatedBy = CreatedBy;

            item.CreatedOn = CreatedOn;

            item.ModifiedBy = ModifiedBy;

            item.ModifiedOn = ModifiedOn;

            item.Save(UserName);
        }
        /// <summary>
        /// Charges the specified order.
        /// </summary>
        /// <param name="order">The order.</param>
        /// <returns></returns>
        internal Transaction Charge(Order order)
        {
            /*
               * Minimum Requirements
               * x_version
               * x_login
               * x_tran_key
               * x_type
               * x_amount
               * x_card_num
               * x_exp_date
               * x_trans_id**
               * x_auth_code**
               */

              StringBuilder sb = new StringBuilder();
              string postData = string.Empty;
              Currency currency = new Currency();

              #region Order Info

              #region Best Practice Fields

              GetBestPracticeFields(sb, AuthorizeNetTransactionType.AUTH_CAPTURE);

              #endregion

              sb.AppendFormat("&x_customer_ip={0}", HttpUtility.UrlEncode(order.IPAddress));
              sb.AppendFormat("&x_invoice_num={0}", HttpUtility.UrlEncode(order.OrderNumber));
              sb.AppendFormat("&x_amount={0}", HttpUtility.UrlEncode(GetFormattedAmount(currency, order.Total).ToString()));
              sb.AppendFormat("&x_freight={0}", HttpUtility.UrlEncode(GetFormattedAmount(currency, order.ShippingAmount).ToString()));
              sb.AppendFormat("&x_tax={0}", HttpUtility.UrlEncode(GetFormattedAmount(currency, order.TaxTotal).ToString()));

              #endregion

              #region Billing Info
              if (order.BillingAddress != null) {
            sb.AppendFormat("&x_email={0}", HttpUtility.UrlEncode(order.BillingAddress.Email));
            sb.AppendFormat("&x_phone={0}", HttpUtility.UrlEncode(order.BillingAddress.Phone));
            sb.AppendFormat("&x_first_name={0}", HttpUtility.UrlEncode(order.BillingAddress.FirstName));
            sb.AppendFormat("&x_last_name={0}", HttpUtility.UrlEncode(order.BillingAddress.LastName));
            sb.AppendFormat("&x_address={0}", HttpUtility.UrlEncode(order.BillingAddress.Address1));
            sb.AppendFormat("&x_city={0}", HttpUtility.UrlEncode(order.BillingAddress.City));
            sb.AppendFormat("&x_state={0}", HttpUtility.UrlEncode(order.BillingAddress.StateOrRegion));
            sb.AppendFormat("&x_zip={0}", HttpUtility.UrlEncode(order.BillingAddress.PostalCode));
            sb.AppendFormat("&x_country={0}", HttpUtility.UrlEncode(order.BillingAddress.Country));
              }

              #endregion

              #region Shipping Info

              if (order.ShippingAddress != null) {
            sb.AppendFormat("&x_ship_to_first_name={0}", HttpUtility.UrlEncode(order.ShippingAddress.FirstName));
            sb.AppendFormat("&x_ship_to_last_name={0}", HttpUtility.UrlEncode(order.ShippingAddress.LastName));
            sb.AppendFormat("&x_ship_to_address={0}", HttpUtility.UrlEncode(order.ShippingAddress.Address1));
            sb.AppendFormat("&x_ship_to_city={0}", HttpUtility.UrlEncode(order.ShippingAddress.City));
            sb.AppendFormat("&x_ship_to_state={0}", HttpUtility.UrlEncode(order.ShippingAddress.StateOrRegion));
            sb.AppendFormat("&x_ship_to_zip={0}", HttpUtility.UrlEncode(order.ShippingAddress.PostalCode));
            sb.AppendFormat("&x_ship_to_country={0}", HttpUtility.UrlEncode(order.ShippingAddress.Country));
              }

              #endregion

              #region Line Items

              AppendLineItems(order, sb, currency);

              #endregion

              #region Credit Card Info

              //x_exp_date
              //x_card_num
              //x_card_code

              string expDate = string.Empty;
              if (order.CreditCardExpirationMonth < 10) {
            expDate = "0" + order.CreditCardExpirationMonth.ToString();
              }
              else {
            expDate = order.CreditCardExpirationMonth.ToString();
              }
              if (order.CreditCardExpirationYear > 99) {
            expDate += order.CreditCardExpirationYear.ToString().Substring(2, 2);
              }
              else {
            expDate += order.CreditCardExpirationYear.ToString();
              }
              sb.AppendFormat("&x_exp_date={0}", HttpUtility.UrlEncode(expDate));
              sb.AppendFormat("&x_card_num={0}", HttpUtility.UrlEncode(order.CreditCardNumber));
              sb.AppendFormat("&x_card_code={0}", HttpUtility.UrlEncode(order.CreditCardSecurityNumber));
              //If the charge fails the first time thru, then we will have some data populated, so we need to try to remove it first
              if (order.ExtendedProperties.Contains("Validator")) {
            order.ExtendedProperties.Remove("Validator");
              }
              if (order.ExtendedProperties.Contains("ExpDate")) {
            order.ExtendedProperties.Remove("ExpDate");
              }
              //now, add them back in
              order.ExtendedProperties.Add("Validator", order.CreditCardNumber.ToString().Substring((order.CreditCardNumber.Length-4)));
              order.ExtendedProperties.Add("ExpDate", expDate);
              order.AdditionalProperties = order.ExtendedProperties.ToXml();
              order.Save("System");

              #endregion

              #region Charge It

              //postData = HttpUtility.UrlEncode(sb.ToString());
              postData = sb.ToString();
              string response = CoreUtility.SendRequestByPost(AuthorizeServiceUtility.GetAuthorizeServiceEndpoint(this.IsLive), postData);

              #endregion

              #region Check it and Build up the Transaction

              string[] output = response.Split('|');

              int counter = 1;//Start @ 1 to keep in sync with docs
              System.Collections.Hashtable vars = new System.Collections.Hashtable();

              foreach (string var in output) {
            vars.Add(counter, var);
            counter += 1;
              }

              Transaction transaction = null;
              string responseCode = vars[1].ToString();
              if ((responseCode == "2") || (responseCode == "3")) {
            throw new AuthorizeNetServiceException(vars[4].ToString());
              }
              else {
            transaction = new Transaction();
            transaction.OrderId = order.OrderId;
            transaction.TransactionTypeDescriptorId = (int)TransactionType.Charge;
            transaction.PaymentMethod = order.CreditCardType.ToString();
            transaction.GatewayName = AUTHORIZENET;
            transaction.GatewayResponse = vars[1].ToString();
            transaction.GatewayTransactionId = vars[7].ToString();
            transaction.AVSCode = vars[6].ToString();
            transaction.CVV2Code = vars[39].ToString();
            decimal grossAmount = 0.00M;
            bool isParsed = decimal.TryParse(vars[10].ToString(), out grossAmount);
            transaction.GrossAmount = grossAmount;
            transaction.TransactionDate = DateTime.Now;
            transaction.Save("System");
              }

              #endregion
              return transaction;
        }
        /// <summary>
        /// Charges the specified order.
        /// </summary>
        /// <param name="order">The order.</param>
        /// <param name="userName">Name of the user.</param>
        /// <returns></returns>
        public static Transaction Charge(Order order, string userName)
        {
            //update the order with IP
              order.IPAddress = HttpContext.Current.Request.UserHostAddress;
              PaymentService paymentService = new PaymentService();
              Transaction transaction = paymentService.Charge(order);
              order.OrderStatusDescriptorId = (int)OrderStatus.ReceivedPaymentProcessingOrder;
              order.OrderTypeId = (int)OrderType.Purchase;
              order.Save(userName);
              Guid userGuid = new Guid(Membership.GetUser(userName).ProviderUserKey.ToString());
              try {
            //Add an OrderNote
            OrderNote orderNote = new OrderNote();
            orderNote.OrderId = order.OrderId;
            orderNote.Note = Strings.ResourceManager.GetString(ORDER_CHARGED);
            orderNote.Save(userName);
            Sku sku;
            DownloadCollection downloadCollection;
            DownloadAccessControlCollection downloadAccessControlCollection;
            DownloadAccessControl downloadAccessControl;
            foreach (OrderItem orderItem in order.OrderItemCollection) {
              //Adjust the Inventory
              sku = new Sku(SKU, orderItem.Sku);
              sku.Inventory = sku.Inventory - orderItem.Quantity;
              sku.Save(SYSTEM);
              ProductCache.RemoveSKUFromCache(orderItem.Sku);
              //Add access control for orderitems
              downloadCollection = new ProductController().FetchAssociatedDownloadsByProductIdAndForPurchase(orderItem.ProductId);
              if (downloadCollection.Count > 0) {
            foreach (Download download in downloadCollection) {
              Query query = new Query(DownloadAccessControl.Schema).
                AddWhere(DownloadAccessControl.Columns.UserId, Comparison.Equals, userGuid).
                AddWhere(DownloadAccessControl.Columns.DownloadId, Comparison.Equals, download.DownloadId);
              downloadAccessControlCollection = new DownloadAccessControlController().FetchByQuery(query);
              if (downloadAccessControlCollection.Count == 0) {
                downloadAccessControl = new DownloadAccessControl();
                downloadAccessControl.DownloadId = download.DownloadId;
                downloadAccessControl.UserId = userGuid;
                downloadAccessControl.Save(SYSTEM);
              }
            }
              }
            }

            //Send out the messages
            //Send these last in case something happens with the email
            MessageService messageService = new MessageService();
            messageService.SendOrderReceivedNotificationToCustomer(order);
            messageService.SendOrderReceivedNotificationToMerchant(order);
              }
              catch (Exception ex) {
            //swallow the exception here because the transaction is saved
            //and, while this is an inconvenience, it's not critical
            Logger.Error(typeof(OrderController).Name + ".Charge", ex);
              }
              return transaction;
        }
 /// <summary>
 /// Provisions the order.
 /// </summary>
 /// <param name="userName">Name of the user.</param>
 /// <returns></returns>
 private int ProvisionOrder(string userName)
 {
     int orderId = GetOrderId(userName);
       if(orderId == 0) {
     Order order = new Order();
     order.OrderGuid = Guid.NewGuid();
     //order.OrderNumber = CoreUtility.GenerateRandomString(ORDER_NUMBER_LENGTH);
     order.OrderNumber = CoreUtility.Generate4By4MaskedString();
     order.OrderStatusDescriptorId = (int)OrderStatus.NotProcessed;
     order.UserName = userName;
     order.IPAddress = HttpContext.Current.Request.UserHostAddress;
     order.Save(userName);
     orderId = order.OrderId;
       }
       return orderId;
 }
 /// <summary>
 /// Resets the shipping and tax and discount.
 /// </summary>
 /// <param name="orderId">The order id.</param>
 /// <param name="userName">Name of the user.</param>
 private static void ResetShippingAndTaxAndDiscount(int orderId, string userName)
 {
     //Clear Shipping and Tax and Discount if in there
       Order order = new Order(orderId);
       if(order.OrderId > 0) {
     order.ShippingAmount = 0;
     order.ShippingMethod = string.Empty;
     foreach(OrderItem orderItem in order.OrderItemCollection) {
       orderItem.ItemTax = 0;
       orderItem.DiscountAmount = 0;
       orderItem.Save(userName);
     }
     order.Save(userName);
       }
 }
        /// <summary>
        /// Refunds the specified transaction.
        /// </summary>
        /// <param name="transaction">The transaction.</param>
        /// <param name="refundedOrder">The refunded order.</param>
        /// <param name="userName">Name of the user.</param>
        public static void RefundStandard(Transaction transaction, Order refundedOrder, string userName)
        {
            Order order = new Order(transaction.OrderId);
              Transaction refundTransaction = new Transaction();
              //refundTransaction.OrderId = transaction.OrderId;
              refundTransaction.TransactionTypeDescriptorId = (int)TransactionType.Refund;
              refundTransaction.PaymentMethod = PAYPAL;
              refundTransaction.GatewayName = PAYPAL_STANDARD;
              refundTransaction.GatewayResponse = SUCCESS;
              refundTransaction.GatewayTransactionId = CoreUtility.GenerateRandomString(16);
              refundTransaction.GrossAmount = refundedOrder.Total;
              refundTransaction.NetAmount = 0.00M;
              refundTransaction.FeeAmount = 0.00M;
              refundTransaction.TransactionDate = DateTime.Now;
              //refundTransaction.Save(userName);
              refundedOrder.Save(userName);

              //set the orderid for the refund
              foreach(OrderItem orderItem in refundedOrder.OrderItemCollection) {
            orderItem.OrderId = refundedOrder.OrderId;
              }
              refundedOrder.OrderItemCollection.SaveAll(userName);
              //set the orderId to the refunded orderId
              refundTransaction.OrderId = refundedOrder.OrderId;
              refundTransaction.Save(userName);
              Guid userGuid = new Guid(Membership.GetUser(order.UserName).ProviderUserKey.ToString());
              DownloadCollection downloadCollection;
              foreach(OrderItem orderItem in refundedOrder.OrderItemCollection) {
            //put the stock back
            Sku sku = new Sku(Sku.Columns.SkuX, orderItem.Sku);
            sku.Inventory = sku.Inventory + orderItem.Quantity;
            sku.Save(userName);
            ProductCache.RemoveSKUFromCache(orderItem.Sku);
            //remove the access control
            downloadCollection = new ProductController().FetchAssociatedDownloadsByProductIdAndForPurchase(orderItem.ProductId);
            if (downloadCollection.Count > 0) {
              foreach (Download download in downloadCollection) {
            new DownloadAccessControlController().Delete(userGuid, download.DownloadId);
              }
            }

              }
              if(refundedOrder.Total == order.Total) {
            order.OrderStatusDescriptorId = (int)OrderStatus.OrderFullyRefunded;
              }
              else {
            order.OrderStatusDescriptorId = (int)OrderStatus.OrderPartiallyRefunded;
              }
              order.Save(userName);
              //Add an OrderNote
              OrderNote orderNote = new OrderNote();
              orderNote.OrderId = order.OrderId;
              orderNote.Note = Strings.ResourceManager.GetString(ORDER_REFUNDED);
              orderNote.Save(userName);
              //send off the notifications
              MessageService messageService = new MessageService();
              messageService.SendOrderRefundToCustomer(refundedOrder);
        }
 /// <summary>
 /// Refunds the specified transaction.
 /// </summary>
 /// <param name="transaction">The transaction.</param>
 /// <param name="refundedOrder">The order the refund should be applied to.</param>
 /// <param name="userName">Name of the user.</param>
 public static void Refund(Transaction transaction, Order refundedOrder, string userName)
 {
     Order order = new Order(transaction.OrderId);
       PaymentService paymentService = new PaymentService();
       Transaction refundTransaction = paymentService.Refund(transaction, refundedOrder);
       refundedOrder.Save(userName);
       //set the orderid for the refund
       foreach(OrderItem orderItem in refundedOrder.OrderItemCollection) {
     orderItem.OrderId = refundedOrder.OrderId;
       }
       refundedOrder.OrderItemCollection.SaveAll(userName);
       //set the orderId to the refunded orderId
       refundTransaction.OrderId = refundedOrder.OrderId;
       refundTransaction.Save(userName);
       Guid userGuid = new Guid(Membership.GetUser(order.UserName).ProviderUserKey.ToString());
       foreach(OrderItem orderItem in refundedOrder.OrderItemCollection) {
     new Product(orderItem.ProductId);
     //put the stock back
     Sku sku = new Sku(Sku.Columns.SkuX, orderItem.Sku);
     sku.Inventory = sku.Inventory + orderItem.Quantity;
     sku.Save(userName);
     ProductCache.RemoveSKUFromCache(orderItem.Sku);
     //remove the access control
     DownloadCollection downloadCollection = new ProductController().FetchAssociatedDownloadsByProductIdAndForPurchase(orderItem.ProductId);
     if (downloadCollection.Count > 0) {
       foreach (Download download in downloadCollection) {
     new DownloadAccessControlController().Delete(userGuid, download.DownloadId);
       }
     }
       }
       if(refundedOrder.Total == order.Total) {
     order.OrderStatusDescriptorId = (int)OrderStatus.OrderFullyRefunded;
       }
       else {
     order.OrderStatusDescriptorId = (int)OrderStatus.OrderPartiallyRefunded;
       }
       order.Save(userName);
       //Add an OrderNote
       OrderNote orderNote = new OrderNote();
       orderNote.OrderId = order.OrderId;
       orderNote.Note = Strings.ResourceManager.GetString(ORDER_REFUNDED);
       orderNote.Save(userName);
       //send off the notifications
       MessageService messageService = new MessageService();
       messageService.SendOrderRefundToCustomer(refundedOrder);
 }
        /// <summary>
        /// Does the express checkout.
        /// </summary>
        /// <param name="order">The order.</param>
        /// <param name="authorizeOnly">if set to <c>true</c> [authorize only].</param>
        /// <param name="userName">Name of the user.</param>
        /// <returns></returns>
        public static Transaction DoExpressCheckout(Order order, bool authorizeOnly, string userName)
        {
            PaymentService paymentService = new PaymentService();
              Transaction transaction = paymentService.DoExpressCheckout(order, authorizeOnly);
              order.OrderStatusDescriptorId = (int)OrderStatus.ReceivedPaymentProcessingOrder;
              order.Save(userName);

              try {
            //Adjust the Inventory
            Sku sku;
            foreach (OrderItem orderItem in order.OrderItemCollection) {
              sku = new Sku(SKU, orderItem.Sku);
              sku.Inventory = sku.Inventory - orderItem.Quantity;
              sku.Save(SYSTEM);
              ProductCache.RemoveSKUFromCache(orderItem.Sku);
            }
            //Send out the messages
            MessageService messageService = new MessageService();
            messageService.SendOrderReceivedNotificationToCustomer(order);
            messageService.SendOrderReceivedNotificationToMerchant(order);
              }
              catch (Exception ex) {
            //swallow the exception here because the transaction is saved
            //and, while this is an inconvenience, it's not critical
            Logger.Error(typeof(OrderController).Name + ".DoExpressCheckout", ex);
              }
              return transaction;
        }
        /// <summary>
        /// Commits the standard transaction.
        /// </summary>
        /// <param name="order">The order.</param>
        /// <param name="transactionId">The transaction id.</param>
        /// <param name="grossAmount">The gross amount.</param>
        /// <returns></returns>
        public static Transaction CommitStandardTransaction(Order order, string transactionId, decimal grossAmount)
        {
            order.OrderStatusDescriptorId = (int)OrderStatus.ReceivedPaymentProcessingOrder;
              order.Save(SYSTEM);
              Transaction transaction = new Transaction();
              transaction.OrderId = order.OrderId;
              transaction.TransactionTypeDescriptorId = (int)TransactionType.Charge;
              transaction.PaymentMethod = PAYPAL;
              transaction.GatewayName = PAYPAL_STANDARD;
              transaction.GatewayResponse = SUCCESS;
              transaction.GatewayTransactionId = transactionId;
              transaction.GrossAmount = grossAmount;
              transaction.TransactionDate = DateTime.UtcNow;
              transaction.Save(SYSTEM);

              try {
            //Adjust the Inventory
            Sku sku;
            foreach (OrderItem orderItem in order.OrderItemCollection) {
              sku = new Sku("Sku", orderItem.Sku);
              sku.Inventory = sku.Inventory - orderItem.Quantity;
              sku.Save("System");
              ProductCache.RemoveSKUFromCache(orderItem.Sku);
            }
            //Send out the messages
            MessageService messageService = new MessageService();
            messageService.SendOrderReceivedNotificationToCustomer(order);
            messageService.SendOrderReceivedNotificationToMerchant(order);
              }
              catch (Exception ex) {
            //swallow the exception here because the transaction is saved
            //and, while this is an inconvenience, it's not critical
            Logger.Error(typeof(OrderController).Name + ".CommitStandardTransaction", ex);
              }
              return transaction;
        }
        /// <summary>
        /// Charges the specified order.
        /// </summary>
        /// <param name="order">The order.</param>
        /// <param name="userName">Name of the user.</param>
        /// <returns></returns>
        public static Transaction Charge(Order order, string userName)
        {
            //update the order with IP
            order.IPAddress = HttpContext.Current.Request.UserHostAddress == "::1" || HttpContext.Current.Request.UserHostAddress == "127.0.0.1" ? "127.0.0.1" : HttpContext.Current.Request.UserHostAddress;
            PaymentService paymentService = new PaymentService();
            Transaction    transaction    = paymentService.Charge(order);

            order.OrderStatusDescriptorId = (int)OrderStatus.ReceivedPaymentProcessingOrder;
            order.OrderTypeId             = (int)OrderType.Purchase;
            order.Save(userName);
            Guid userGuid = new Guid(Membership.GetUser(userName).ProviderUserKey.ToString());

            try {
                //Add an OrderNote
                OrderNote orderNote = new OrderNote();
                orderNote.OrderId = order.OrderId;
                orderNote.Note    = Strings.ResourceManager.GetString(ORDER_CHARGED);
                orderNote.Save(userName);
                Sku sku;
                DownloadCollection downloadCollection;
                DownloadAccessControlCollection downloadAccessControlCollection;
                DownloadAccessControl           downloadAccessControl;
                foreach (OrderItem orderItem in order.OrderItemCollection)
                {
                    //Adjust the Inventory
                    sku           = new Sku(SKU, orderItem.Sku);
                    sku.Inventory = sku.Inventory - orderItem.Quantity;
                    sku.Save(SYSTEM);
                    ProductCache.RemoveSKUFromCache(orderItem.Sku);
                    //Add access control for orderitems
                    downloadCollection = new ProductController().FetchAssociatedDownloadsByProductIdAndForPurchase(orderItem.ProductId);
                    if (downloadCollection.Count > 0)
                    {
                        foreach (Download download in downloadCollection)
                        {
                            Query query = new Query(DownloadAccessControl.Schema).
                                          AddWhere(DownloadAccessControl.Columns.UserId, Comparison.Equals, userGuid).
                                          AddWhere(DownloadAccessControl.Columns.DownloadId, Comparison.Equals, download.DownloadId);
                            downloadAccessControlCollection = new DownloadAccessControlController().FetchByQuery(query);
                            if (downloadAccessControlCollection.Count == 0)
                            {
                                downloadAccessControl            = new DownloadAccessControl();
                                downloadAccessControl.DownloadId = download.DownloadId;
                                downloadAccessControl.UserId     = userGuid;
                                downloadAccessControl.Save(SYSTEM);
                            }
                        }
                    }
                }

                //Send out the messages
                //Send these last in case something happens with the email
                MessageService messageService = new MessageService();
                messageService.SendOrderReceivedNotificationToCustomer(order);
                messageService.SendOrderReceivedNotificationToMerchant(order);
            }
            catch (Exception ex) {
                //swallow the exception here because the transaction is saved
                //and, while this is an inconvenience, it's not critical
                Logger.Error(typeof(OrderController).Name + ".Charge", ex);
            }
            return(transaction);
        }
        /// <summary>
        /// Refunds the specified transaction.
        /// </summary>
        /// <param name="transaction">The transaction.</param>
        /// <param name="refundedOrder">The refunded order.</param>
        /// <param name="userName">Name of the user.</param>
        public static void RefundStandard(Transaction transaction, Order refundedOrder, string userName)
        {
            Order       order             = new Order(transaction.OrderId);
            Transaction refundTransaction = new Transaction();

            //refundTransaction.OrderId = transaction.OrderId;
            refundTransaction.TransactionTypeDescriptorId = (int)TransactionType.Refund;
            refundTransaction.PaymentMethod        = PAYPAL;
            refundTransaction.GatewayName          = PAYPAL_STANDARD;
            refundTransaction.GatewayResponse      = SUCCESS;
            refundTransaction.GatewayTransactionId = CoreUtility.GenerateRandomString(16);
            refundTransaction.GrossAmount          = refundedOrder.Total;
            refundTransaction.NetAmount            = 0.00M;
            refundTransaction.FeeAmount            = 0.00M;
            refundTransaction.TransactionDate      = DateTime.Now;
            //refundTransaction.Save(userName);
            refundedOrder.Save(userName);

            //set the orderid for the refund
            foreach (OrderItem orderItem in refundedOrder.OrderItemCollection)
            {
                orderItem.OrderId = refundedOrder.OrderId;
            }
            refundedOrder.OrderItemCollection.SaveAll(userName);
            //set the orderId to the refunded orderId
            refundTransaction.OrderId = refundedOrder.OrderId;
            refundTransaction.Save(userName);
            Guid userGuid = new Guid(Membership.GetUser(order.UserName).ProviderUserKey.ToString());
            DownloadCollection downloadCollection;

            foreach (OrderItem orderItem in refundedOrder.OrderItemCollection)
            {
                //put the stock back
                Sku sku = new Sku(Sku.Columns.SkuX, orderItem.Sku);
                sku.Inventory = sku.Inventory + orderItem.Quantity;
                sku.Save(userName);
                ProductCache.RemoveSKUFromCache(orderItem.Sku);
                //remove the access control
                downloadCollection = new ProductController().FetchAssociatedDownloadsByProductIdAndForPurchase(orderItem.ProductId);
                if (downloadCollection.Count > 0)
                {
                    foreach (Download download in downloadCollection)
                    {
                        new DownloadAccessControlController().Delete(userGuid, download.DownloadId);
                    }
                }
            }
            if (refundedOrder.Total == order.Total)
            {
                order.OrderStatusDescriptorId = (int)OrderStatus.OrderFullyRefunded;
            }
            else
            {
                order.OrderStatusDescriptorId = (int)OrderStatus.OrderPartiallyRefunded;
            }
            order.Save(userName);
            //Add an OrderNote
            OrderNote orderNote = new OrderNote();

            orderNote.OrderId = order.OrderId;
            orderNote.Note    = Strings.ResourceManager.GetString(ORDER_REFUNDED);
            orderNote.Save(userName);
            //send off the notifications
            MessageService messageService = new MessageService();

            messageService.SendOrderRefundToCustomer(refundedOrder);
        }