protected string FormatShippingOption(ShippingOption shippingOption)
 {
     decimal rateBase = TaxManager.GetShippingPrice(shippingOption.Rate, NopContext.Current.User);
     decimal rate = CurrencyManager.ConvertCurrency(rateBase, CurrencyManager.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency);
     string rateStr = PriceHelper.FormatShippingPrice(rate, true);
     return string.Format("({0})", rateStr);
 }
        protected string FormatShippingOption(ShippingOption shippingOption)
        {
            //calculate discounted and taxed rate
            Discount appliedDiscount = null;
            decimal shippingTotalWithoutDiscount = shippingOption.Rate;
            decimal discountAmount = ShippingManager.GetShippingDiscount(NopContext.Current.User, 
                shippingTotalWithoutDiscount, out appliedDiscount);
            decimal shippingTotalWithDiscount = shippingTotalWithoutDiscount - discountAmount;
            if (shippingTotalWithDiscount < decimal.Zero)
                shippingTotalWithDiscount = decimal.Zero;
            shippingTotalWithDiscount = Math.Round(shippingTotalWithDiscount, 2);

            decimal rateBase = TaxManager.GetShippingPrice(shippingTotalWithDiscount, NopContext.Current.User);
            decimal rate = CurrencyManager.ConvertCurrency(rateBase, CurrencyManager.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency);
            string rateStr = PriceHelper.FormatShippingPrice(rate, true);
            return string.Format("({0})", rateStr);
        }
        /// <summary>
        ///  Gets available shipping options
        /// </summary>
        /// <param name="ShipmentPackage">Shipment package</param>
        /// <param name="Error">Error</param>
        /// <returns>Shipping options</returns>
        public ShippingOptionCollection GetShippingOptions(ShipmentPackage ShipmentPackage, ref string Error)
        {
            ShippingOptionCollection shippingOptions = new ShippingOptionCollection();

            if (ShipmentPackage == null)
                throw new ArgumentNullException("ShipmentPackage");
            if (ShipmentPackage.Items == null)
                throw new NopException("No shipment items");

            

            ShippingMethodCollection shippingMethods = ShippingMethodManager.GetAllShippingMethods();
            foreach (ShippingMethod shippingMethod in shippingMethods)
            {
                ShippingOption shippingOption = new ShippingOption();
                shippingOption.Name = shippingMethod.Name;
                shippingOption.Description = shippingMethod.Description;
                shippingOption.Rate = GetRate();
                shippingOptions.Add(shippingOption);
            }

            return shippingOptions;
        }
        private void processNewOrderNotification(string xmlData)
        {
            try
            {
                NewOrderNotification newOrderNotification = (NewOrderNotification)EncodeHelper.Deserialize(xmlData, typeof(NewOrderNotification));
                string googleOrderNumber = newOrderNotification.googleordernumber;

                XmlNode CustomerInfo = newOrderNotification.shoppingcart.merchantprivatedata.Any[0];
                int CustomerID = Convert.ToInt32(CustomerInfo.Attributes["CustomerID"].Value);
                int CustomerLanguageID = Convert.ToInt32(CustomerInfo.Attributes["CustomerLanguageID"].Value);
                int CustomerCurrencyID = Convert.ToInt32(CustomerInfo.Attributes["CustomerCurrencyID"].Value);
                Customer customer = CustomerManager.GetCustomerByID(CustomerID);

                NopSolutions.NopCommerce.BusinessLogic.Orders.ShoppingCart Cart = ShoppingCartManager.GetCustomerShoppingCart(customer.CustomerID, ShoppingCartTypeEnum.ShoppingCart);

                if (customer == null)
                {
                    logMessage("Could not load a customer");
                    return;
                }

                NopContext.Current.User = customer;

                if (Cart.Count == 0)
                {
                    logMessage("Cart is empty");
                    return;
                }

                //validate cart
                foreach (NopSolutions.NopCommerce.BusinessLogic.Orders.ShoppingCartItem sci in Cart)
                {
                    bool ok = false;
                    foreach (Item item in newOrderNotification.shoppingcart.items)
                    {
                        if (!String.IsNullOrEmpty(item.merchantitemid))
                        {
                            if ((Convert.ToInt32(item.merchantitemid) == sci.ShoppingCartItemID) && (item.quantity == sci.Quantity))
                            {
                                ok = true;
                                break;
                            }
                        }
                    }

                    if (!ok)
                    {
                        logMessage(string.Format("Shopping Cart item has been changed. {0}. {1}", sci.ShoppingCartItemID, sci.Quantity));
                        return;
                    }
                }


                string[] billingFullname = newOrderNotification.buyerbillingaddress.contactname.Trim().Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries);
                string billingFirstName = billingFullname[0];
                string billingLastName = string.Empty;
                if (billingFullname.Length > 1)
                    billingLastName = billingFullname[1];
                string billingEmail = newOrderNotification.buyerbillingaddress.email.Trim();
                string billingAddress1 = newOrderNotification.buyerbillingaddress.address1.Trim();
                string billingAddress2 = newOrderNotification.buyerbillingaddress.address2.Trim();
                string billingPhoneNumber = newOrderNotification.buyerbillingaddress.phone.Trim();
                string billingCity = newOrderNotification.buyerbillingaddress.city.Trim();
                int billingStateProvinceID = 0;
                StateProvince billingStateProvince = StateProvinceManager.GetStateProvinceByAbbreviation(newOrderNotification.buyerbillingaddress.region.Trim());
                if (billingStateProvince != null)
                    billingStateProvinceID = billingStateProvince.StateProvinceID;
                string billingZipPostalCode = newOrderNotification.buyerbillingaddress.postalcode.Trim();
                int billingCountryID = 0;
                Country billingCountry = CountryManager.GetCountryByTwoLetterISOCode(newOrderNotification.buyerbillingaddress.countrycode.Trim());
                if (billingCountry != null)
                    billingCountryID = billingCountry.CountryID;

                NopSolutions.NopCommerce.BusinessLogic.CustomerManagement.Address BillingAddress = customer.BillingAddresses.FindAddress(
                    billingFirstName, billingLastName, billingPhoneNumber,
                    billingEmail, string.Empty, string.Empty, billingAddress1, billingAddress2, billingCity,
                    billingStateProvinceID, billingZipPostalCode, billingCountryID);

                if (BillingAddress == null)
                {
                    BillingAddress = CustomerManager.InsertAddress(CustomerID, true,
                        billingFirstName, billingLastName, billingPhoneNumber, billingEmail,
                        string.Empty, string.Empty, billingAddress1,
                        billingAddress2, billingCity,
                        billingStateProvinceID, billingZipPostalCode,
                        billingCountryID, DateTime.Now, DateTime.Now);
                }
                customer = CustomerManager.SetDefaultBillingAddress(customer.CustomerID, BillingAddress.AddressID);

                NopSolutions.NopCommerce.BusinessLogic.CustomerManagement.Address ShippingAddress = null;
                customer.LastShippingOption = null;
                bool shoppingCartRequiresShipping = ShippingManager.ShoppingCartRequiresShipping(Cart);
                if (shoppingCartRequiresShipping)
                {
                    string[] shippingFullname = newOrderNotification.buyershippingaddress.contactname.Trim().Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries);
                    string shippingFirstName = shippingFullname[0];
                    string shippingLastName = string.Empty;
                    if (shippingFullname.Length > 1)
                        shippingLastName = shippingFullname[1];
                    string shippingEmail = newOrderNotification.buyershippingaddress.email.Trim();
                    string shippingAddress1 = newOrderNotification.buyershippingaddress.address1.Trim();
                    string shippingAddress2 = newOrderNotification.buyershippingaddress.address2.Trim();
                    string shippingPhoneNumber = newOrderNotification.buyershippingaddress.phone.Trim();
                    string shippingCity = newOrderNotification.buyershippingaddress.city.Trim();
                    int shippingStateProvinceID = 0;
                    StateProvince shippingStateProvince = StateProvinceManager.GetStateProvinceByAbbreviation(newOrderNotification.buyershippingaddress.region.Trim());
                    if (shippingStateProvince != null)
                        shippingStateProvinceID = shippingStateProvince.StateProvinceID;
                    int shippingCountryID = 0;
                    string shippingZipPostalCode = newOrderNotification.buyershippingaddress.postalcode.Trim();
                    Country shippingCountry = CountryManager.GetCountryByTwoLetterISOCode(newOrderNotification.buyershippingaddress.countrycode.Trim());
                    if (shippingCountry != null)
                        shippingCountryID = shippingCountry.CountryID;

                    ShippingAddress = customer.ShippingAddresses.FindAddress(
                        shippingFirstName, shippingLastName, shippingPhoneNumber,
                        shippingEmail, string.Empty, string.Empty, 
                        shippingAddress1, shippingAddress2, shippingCity,
                        shippingStateProvinceID, shippingZipPostalCode, shippingCountryID);
                    if (ShippingAddress == null)
                    {
                        ShippingAddress = CustomerManager.InsertAddress(CustomerID, false,
                             shippingFirstName, shippingLastName, shippingPhoneNumber, shippingEmail,
                             string.Empty, string.Empty, shippingAddress1,
                             shippingAddress2, shippingCity, shippingStateProvinceID,
                             shippingZipPostalCode, shippingCountryID,
                             DateTime.Now, DateTime.Now);
                    }

                    customer = CustomerManager.SetDefaultShippingAddress(customer.CustomerID, ShippingAddress.AddressID);

                    string shippingMethod = string.Empty;
                    decimal shippingCost = decimal.Zero;
                    if (newOrderNotification.orderadjustment != null &&
                        newOrderNotification.orderadjustment.shipping != null &&
                        newOrderNotification.orderadjustment.shipping.Item != null)
                    {
                        FlatRateShippingAdjustment ShippingMethod = (FlatRateShippingAdjustment)newOrderNotification.orderadjustment.shipping.Item;
                        shippingMethod = ShippingMethod.shippingname;
                        shippingCost = ShippingMethod.shippingcost.Value;


                        ShippingOption shippingOption = new ShippingOption();
                        shippingOption.Name = shippingMethod;
                        shippingOption.Rate = shippingCost;
                        customer.LastShippingOption = shippingOption;
                    }
                }

                //customer.LastCalculatedTax = decimal.Zero;

                PaymentMethod googleCheckoutPaymentMethod = PaymentMethodManager.GetPaymentMethodBySystemKeyword("GoogleCheckout");

                PaymentInfo paymentInfo = new PaymentInfo();
                paymentInfo.PaymentMethodID = googleCheckoutPaymentMethod.PaymentMethodID;
                paymentInfo.BillingAddress = BillingAddress;
                paymentInfo.ShippingAddress = ShippingAddress;
                paymentInfo.CustomerLanguage = LanguageManager.GetLanguageByID(CustomerLanguageID);
                paymentInfo.CustomerCurrency = CurrencyManager.GetCurrencyByID(CustomerCurrencyID);
                paymentInfo.GoogleOrderNumber = googleOrderNumber;
                int orderID = 0;
                string result = OrderManager.PlaceOrder(paymentInfo, customer, out orderID);
                if (!String.IsNullOrEmpty(result))
                {
                    logMessage("new-order-notification received. CreateOrder() error: Order Number " + orderID + ". " + result);
                    return;
                }

                Order order = OrderManager.GetOrderByID(orderID);
                logMessage("new-order-notification received and saved: Order Number " + orderID);

            }
            catch (Exception exc)
            {
                logMessage("processNewOrderNotification Exception: " + exc.Message + ": " + exc.StackTrace);
            }
        }
        private List<ShippingOption> ParseResponse(RateReply reply)
        {
            var additionalFee = IoC.Resolve<ISettingManager>().GetSettingValueDecimalNative("ShippingRateComputationMethod.FedEx.AdditionalFee", 0);
            string carrierServicesOffered = IoC.Resolve<ISettingManager>().GetSettingValue("ShippingRateComputationMethod.FedEx.CarrierServicesOffered");
            bool applyDiscount = IoC.Resolve<ISettingManager>().GetSettingValueBoolean("ShippingRateComputationMethod.FedEx.ApplyDiscounts", false);

            var result = new List<ShippingOption>();

            Debug.WriteLine("RateReply details:");
            Debug.WriteLine("**********************************************************");
            foreach (var rateDetail in reply.RateReplyDetails)
            {
                var shippingOption = new ShippingOption();
                string serviceName = FedExServices.GetServiceName(rateDetail.ServiceType.ToString());

                // Skip the current service if services are selected and this service hasn't been selected
                if (!String.IsNullOrEmpty(carrierServicesOffered) && !carrierServicesOffered.Contains(rateDetail.ServiceType.ToString()))
                {
                    continue;
                }

                Debug.WriteLine("ServiceType: " + rateDetail.ServiceType);
                if (!serviceName.Equals("UNKNOWN"))
                {
                    shippingOption.Name = serviceName;

                    Debug.WriteLine("ServiceType: " + rateDetail.ServiceType);
                    foreach (RatedShipmentDetail shipmentDetail in rateDetail.RatedShipmentDetails)
                    {
                        Debug.WriteLine("RateType : " + shipmentDetail.ShipmentRateDetail.RateType);
                        Debug.WriteLine("Total Billing Weight : " + shipmentDetail.ShipmentRateDetail.TotalBillingWeight.Value);
                        Debug.WriteLine("Total Base Charge : " + shipmentDetail.ShipmentRateDetail.TotalBaseCharge.Amount);
                        Debug.WriteLine("Total Discount : " + shipmentDetail.ShipmentRateDetail.TotalFreightDiscounts.Amount);
                        Debug.WriteLine("Total Surcharges : " + shipmentDetail.ShipmentRateDetail.TotalSurcharges.Amount);
                        Debug.WriteLine("Net Charge : " + shipmentDetail.ShipmentRateDetail.TotalNetCharge.Amount);
                        Debug.WriteLine("*********");

                        // Get discounted rates if option is selected
                        if (applyDiscount == true & shipmentDetail.ShipmentRateDetail.RateType == ReturnedRateType.PAYOR_ACCOUNT)
                        {
                            shippingOption.Rate = shipmentDetail.ShipmentRateDetail.TotalNetCharge.Amount + additionalFee;
                            break;
                        }
                        else if (shipmentDetail.ShipmentRateDetail.RateType == ReturnedRateType.PAYOR_LIST) // Get List Rates (not discount rates)
                        {
                            shippingOption.Rate = shipmentDetail.ShipmentRateDetail.TotalNetCharge.Amount + additionalFee;
                            break;
                        }
                        else // Skip the rate (RATED_ACCOUNT, PAYOR_MULTIWEIGHT, or RATED_LIST)
                        {
                            continue;
                        }
                    }
                    result.Add(shippingOption);
                }
                Debug.WriteLine("**********************************************************");
            }

            return result;
        }
        private static ShippingOption RequestShippingOption(string zipPostalCodeFrom, 
            string zipPostalCodeTo, string countryCode, string serviceType, 
            int weight, int length, int width, int height, int quantity)
        {
            ShippingOption shippingOption = new ShippingOption();
            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("Pickup_Postcode={0}&", zipPostalCodeFrom);
            sb.AppendFormat("Destination_Postcode={0}&", zipPostalCodeTo);
            sb.AppendFormat("Country={0}&", countryCode);
            sb.AppendFormat("Service_Type={0}&", serviceType);
            sb.AppendFormat("Weight={0}&", weight);
            sb.AppendFormat("Length={0}&", length);
            sb.AppendFormat("Width={0}&", width);
            sb.AppendFormat("Height={0}&", height);
            sb.AppendFormat("Quantity={0}&", quantity);

            HttpWebRequest request = WebRequest.Create(AustraliaPostSettings.GatewayUrl) as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            byte[] reqContent = Encoding.ASCII.GetBytes(sb.ToString());
            request.ContentLength = reqContent.Length;
            using (Stream newStream = request.GetRequestStream())
            {
                newStream.Write(reqContent, 0, reqContent.Length);
            }

            WebResponse response = request.GetResponse();
            string rspContent;
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                rspContent = reader.ReadToEnd();
            }

            string[] tmp = rspContent.Split(new char[] { '\n' }, 3);
            if (tmp.Length != 3)
            {
                throw new NopException("Response is not valid.");
            }

            NameValueCollection rspParams = new NameValueCollection();
            foreach (string s in tmp)
            {
                string[] tmp2 = s.Split(new char[] { '=' });
                if (tmp2.Length != 2)
                {
                    throw new NopException("Response is not valid.");
                }
                rspParams.Add(tmp2[0].Trim(), tmp2[1].Trim());
            }

            string err_msg = rspParams["err_msg"];
            if (!err_msg.ToUpperInvariant().StartsWith("OK"))
            {
                throw new NopException(err_msg);
            }

            shippingOption.Name = serviceType;
            shippingOption.Description = String.Format("{0} Days", rspParams["days"]);
            shippingOption.Rate = Decimal.Parse(rspParams["charge"]);

            return shippingOption;
        }
        /// <summary>
        ///  Gets available shipping options
        /// </summary>
        /// <param name="shipmentPackage">Shipment package</param>
        /// <param name="error">Error</param>
        /// <returns>Shipping options</returns>
        public List<ShippingOption> GetShippingOptions(ShipmentPackage shipmentPackage, ref string error)
        {
            var shippingOptions = new List<ShippingOption>();

            if (shipmentPackage == null)
                throw new ArgumentNullException("shipmentPackage");
            if (shipmentPackage.Items == null)
                throw new NopException("No shipment items");
            if (shipmentPackage.ShippingAddress == null)
            {
                error = "Shipping address is not set";
                return shippingOptions;
            }
            if (shipmentPackage.ShippingAddress.Country == null)
            {
                error = "Shipping country is not set";
                return shippingOptions;
            }

            decimal subTotal = decimal.Zero;
            foreach (var shoppingCartItem in shipmentPackage.Items)
            {
                if (shoppingCartItem.IsFreeShipping)
                    continue;
                subTotal += PriceHelper.GetSubTotal(shoppingCartItem, shipmentPackage.Customer, true);
            }

            decimal weight = IoC.Resolve<IShippingService>().GetShoppingCartTotalWeight(shipmentPackage.Items, shipmentPackage.Customer);

            var shippingMethods = IoC.Resolve<IShippingService>().GetAllShippingMethods(shipmentPackage.ShippingAddress.CountryId);
            foreach (var shippingMethod in shippingMethods)
            {
                decimal? rate = GetRate(subTotal, weight, shippingMethod.ShippingMethodId);
                if (rate.HasValue)
                {
                    var shippingOption = new ShippingOption();
                    shippingOption.Name = shippingMethod.Name;
                    shippingOption.Description = shippingMethod.Description;
                    shippingOption.Rate = rate.Value;
                    shippingOptions.Add(shippingOption);
                }
            }

            return shippingOptions;
        }
        private ShippingOptionCollection ParseResponse(RateReply reply)
        {
            ShippingOptionCollection result = new ShippingOptionCollection();

            Debug.WriteLine("RateReply details:");
            Debug.WriteLine("**********************************************************");
            foreach (RateReplyDetail rateDetail in reply.RateReplyDetails)
            {
                Debug.WriteLine("ServiceType: " + rateDetail.ServiceType);
                for (int i = 0; i < rateDetail.RatedShipmentDetails.Length; i++)
                {
                    RatedShipmentDetail shipmentDetail = rateDetail.RatedShipmentDetails[i];
                    Debug.WriteLine("RateType : " + shipmentDetail.ShipmentRateDetail.RateType);
                    Debug.WriteLine("Total Billing Weight : " + shipmentDetail.ShipmentRateDetail.TotalBillingWeight.Value);
                    Debug.WriteLine("Total Base Charge : " + shipmentDetail.ShipmentRateDetail.TotalBaseCharge.Amount);
                    Debug.WriteLine("Total Discount : " + shipmentDetail.ShipmentRateDetail.TotalFreightDiscounts.Amount);
                    Debug.WriteLine("Total Surcharges : " + shipmentDetail.ShipmentRateDetail.TotalSurcharges.Amount);
                    Debug.WriteLine("Net Charge : " + shipmentDetail.ShipmentRateDetail.TotalNetCharge.Amount);
                    Debug.WriteLine("*********");

                    //take first one
                    if (i == 0)
                    {
                        ShippingOption shippingOption = new ShippingOption();
                        string userFriendlyServiceType = GetUserFriendlyEnum(rateDetail.ServiceType.ToString());
                        shippingOption.Name = userFriendlyServiceType;
                        shippingOption.Rate = shipmentDetail.ShipmentRateDetail.TotalNetCharge.Amount;
                        result.Add(shippingOption);
                    }
                }
                Debug.WriteLine("**********************************************************");
            }

            return result;
        }
        public void BindData()
        {
            bool shoppingCartRequiresShipping = this.ShippingService.ShoppingCartRequiresShipping(Cart);
            if (!shoppingCartRequiresShipping)
            {
                NopContext.Current.User.LastShippingOption = null;
                var args1 = new CheckoutStepEventArgs() { ShippingMethodSelected = true };
                OnCheckoutStepChanged(args1);
                if (!this.OnePageCheckout)
                    Response.Redirect("~/checkoutpaymentmethod.aspx");
            }
            else
            {
                string error = string.Empty;
                Address address = NopContext.Current.User.ShippingAddress;
                var shippingOptions = this.ShippingService.GetShippingOptions(Cart, NopContext.Current.User, address, ref error);
                if (!String.IsNullOrEmpty(error))
                {
                    this.LogService.InsertLog(LogTypeEnum.ShippingError, error, error);
                    phSelectShippingMethod.Visible = false;
                    lShippingMethodsError.Text = Server.HtmlEncode(error);
                }
                else
                {
                    if (shippingOptions.Count > 0)
                    {
                        phSelectShippingMethod.Visible = true;
                        dlShippingOptions.DataSource = shippingOptions;
                        dlShippingOptions.DataBind();

                        //select a default shipping option
                        if (dlShippingOptions.Items.Count > 0)
                        {
                            if (NopContext.Current.User != null &&
                                NopContext.Current.User.LastShippingOption != null)
                            {
                                //already selected shipping option
                                this.SelectedShippingOption = NopContext.Current.User.LastShippingOption;
                            }
                            else
                            {
                                //otherwise, the first shipping option
                                var tmp1 = dlShippingOptions.Items[0];
                                var rdShippingOption = tmp1.FindControl("rdShippingOption") as RadioButton;
                                if (rdShippingOption != null)
                                {
                                    rdShippingOption.Checked = true;
                                }
                            }
                        }
                    }
                    else
                    {
                        phSelectShippingMethod.Visible = false;
                        lShippingMethodsError.Text = GetLocaleResourceString("Checkout.ShippingIsNotAllowed");
                    }
                }
            }
        }
        private ShippingOptionCollection ParseResponse(string response, ref string error)
        {
            ShippingOptionCollection shippingOptions = new ShippingOptionCollection();

            using (StringReader sr = new StringReader(response))
            using (XmlTextReader tr = new XmlTextReader(sr))
                while (tr.Read())
                {
                    if ((tr.Name == "Error") && (tr.NodeType == XmlNodeType.Element))
                    {
                        string errorText = "";
                        while (tr.Read())
                        {
                            if ((tr.Name == "ErrorCode") && (tr.NodeType == XmlNodeType.Element))
                            {
                                errorText += "UPS Rating Error, Error Code: " + tr.ReadString() + ", ";
                            }
                            if ((tr.Name == "ErrorDescription") && (tr.NodeType == XmlNodeType.Element))
                            {
                                errorText += "Error Desc: " + tr.ReadString();
                            }
                        }
                        error = "UPS Error returned: " + errorText;
                    }
                    if ((tr.Name == "RatedShipment") && (tr.NodeType == XmlNodeType.Element))
                    {
                        string serviceCode = "";
                        string monetaryValue = "";
                        while (tr.Read())
                        {
                            if ((tr.Name == "Service") && (tr.NodeType == XmlNodeType.Element))
                            {
                                while (tr.Read())
                                {
                                    if ((tr.Name == "Code") && (tr.NodeType == XmlNodeType.Element))
                                    {
                                        serviceCode = tr.ReadString();
                                        tr.ReadEndElement();
                                    }
                                    if ((tr.Name == "Service") && (tr.NodeType == XmlNodeType.EndElement))
                                    {
                                        break;
                                    }
                                }
                            }
                            if (((tr.Name == "RatedShipment") && (tr.NodeType == XmlNodeType.EndElement)) || ((tr.Name == "RatedPackage") && (tr.NodeType == XmlNodeType.Element)))
                            {
                                break;
                            }
                            if ((tr.Name == "TotalCharges") && (tr.NodeType == XmlNodeType.Element))
                            {
                                while (tr.Read())
                                {
                                    if ((tr.Name == "MonetaryValue") && (tr.NodeType == XmlNodeType.Element))
                                    {
                                        monetaryValue = tr.ReadString();
                                        tr.ReadEndElement();
                                    }
                                    if ((tr.Name == "TotalCharges") && (tr.NodeType == XmlNodeType.EndElement))
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                        string service = GetServiceName(serviceCode);

                        //Weed out unwanted or unkown service rates
                        if (service.ToUpper() != "UNKNOWN")
                        {
                            ShippingOption shippingOption = new ShippingOption();
                            shippingOption.Rate = Convert.ToDecimal(monetaryValue, new CultureInfo("en-US"));
                            shippingOption.Name = service;
                            shippingOptions.Add(shippingOption);
                        }

                    }
                }

            return shippingOptions;
        }
        private List<ShippingOption> ParseResponse(string response, ref string error)
        {
            var shippingOptions = new List<ShippingOption>();

            string carrierServicesOffered = IoC.Resolve<ISettingManager>().GetSettingValue("ShippingRateComputationMethod.UPS.CarrierServicesOffered", string.Empty);

            using (var sr = new StringReader(response))
            using (var tr = new XmlTextReader(sr))
                while (tr.Read())
                {
                    if ((tr.Name == "Error") && (tr.NodeType == XmlNodeType.Element))
                    {
                        string errorText = "";
                        while (tr.Read())
                        {
                            if ((tr.Name == "ErrorCode") && (tr.NodeType == XmlNodeType.Element))
                            {
                                errorText += "UPS Rating Error, Error Code: " + tr.ReadString() + ", ";
                            }
                            if ((tr.Name == "ErrorDescription") && (tr.NodeType == XmlNodeType.Element))
                            {
                                errorText += "Error Desc: " + tr.ReadString();
                            }
                        }
                        error = "UPS Error returned: " + errorText;
                    }
                    if ((tr.Name == "RatedShipment") && (tr.NodeType == XmlNodeType.Element))
                    {
                        string serviceCode = "";
                        string monetaryValue = "";
                        while (tr.Read())
                        {
                            if ((tr.Name == "Service") && (tr.NodeType == XmlNodeType.Element))
                            {
                                while (tr.Read())
                                {
                                    if ((tr.Name == "Code") && (tr.NodeType == XmlNodeType.Element))
                                    {
                                        serviceCode = tr.ReadString();
                                        tr.ReadEndElement();
                                    }
                                    if ((tr.Name == "Service") && (tr.NodeType == XmlNodeType.EndElement))
                                    {
                                        break;
                                    }
                                }
                            }
                            if (((tr.Name == "RatedShipment") && (tr.NodeType == XmlNodeType.EndElement)) || ((tr.Name == "RatedPackage") && (tr.NodeType == XmlNodeType.Element)))
                            {
                                break;
                            }
                            if ((tr.Name == "TotalCharges") && (tr.NodeType == XmlNodeType.Element))
                            {
                                while (tr.Read())
                                {
                                    if ((tr.Name == "MonetaryValue") && (tr.NodeType == XmlNodeType.Element))
                                    {
                                        monetaryValue = tr.ReadString();
                                        tr.ReadEndElement();
                                    }
                                    if ((tr.Name == "TotalCharges") && (tr.NodeType == XmlNodeType.EndElement))
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                        string service = GetServiceName(serviceCode);
                        string serviceId = String.Format("[{0}]", serviceCode);

                        // Go to the next rate if the service ID is not in the list of services to offer
                        if (!String.IsNullOrEmpty(carrierServicesOffered) && !carrierServicesOffered.Contains(serviceId))
                        {
                            continue;
                        }

                        //Weed out unwanted or unkown service rates
                        if (service.ToUpper() != "UNKNOWN")
                        {
                            var shippingOption = new ShippingOption();
                            shippingOption.Rate = Convert.ToDecimal(monetaryValue, new CultureInfo("en-US"));
                            shippingOption.Name = service;
                            shippingOptions.Add(shippingOption);
                        }

                    }
                }

            return shippingOptions;
        }
        private List<ShippingOption> ParseResponse(string response, bool isDomestic, ref string error)
        {
            var shippingOptions = new List<ShippingOption>();

            string postageStr = isDomestic ? "Postage" : "Service";
            string mailServiceStr = isDomestic ? "MailService" : "SvcDescription";
            string rateStr = isDomestic ? "Rate" : "Postage";
            string classStr = isDomestic ? "CLASSID" : "ID";
            string carrierServicesOffered = String.Empty;

            if (isDomestic)
            {
                carrierServicesOffered = IoC.Resolve<ISettingManager>().GetSettingValue("ShippingRateComputationMethod.USPS.CarrierServicesOfferedDomestic", string.Empty);
            }
            else
            {
                carrierServicesOffered = IoC.Resolve<ISettingManager>().GetSettingValue("ShippingRateComputationMethod.USPS.CarrierServicesOfferedInternational", string.Empty);
            }

            using (var sr = new StringReader(response))
            using (var tr = new XmlTextReader(sr))
            {
                do
                {
                    tr.Read();

                    if ((tr.Name == "Error") && (tr.NodeType == XmlNodeType.Element))
                    {
                        string errorText = "";
                        while (tr.Read())
                        {
                            if ((tr.Name == "Description") && (tr.NodeType == XmlNodeType.Element))
                                errorText += "Error Desc: " + tr.ReadString();
                            if ((tr.Name == "HelpContext") && (tr.NodeType == XmlNodeType.Element))
                                errorText += "USPS Help Context: " + tr.ReadString() + ". ";
                        }
                        error = "USPS Error returned: " + errorText;
                    }

                    if ((tr.Name == postageStr) && (tr.NodeType == XmlNodeType.Element))
                    {
                        string serviceId = string.Empty;

                        // Find the ID for the service
                        if (tr.HasAttributes)
                        {
                            for (int i = 0; i < tr.AttributeCount; i++)
                            {
                                tr.MoveToAttribute(i);
                                if (tr.Name.Equals(classStr))
                                {
                                    // Add delimiters [] so that single digit IDs aren't found in mutli-digit IDs
                                    serviceId = String.Format("[{0}]", tr.Value);
                                    break;
                                }
                            }
                        }

                        // Go to the next rate if the service ID is not in the list of services to offer
                        if (!String.IsNullOrEmpty(serviceId) &&
                            !String.IsNullOrEmpty(carrierServicesOffered) &&
                            !carrierServicesOffered.Contains(serviceId))
                        {
                            continue;
                        }

                        string serviceCode = string.Empty;
                        string postalRate = string.Empty;

                        do
                        {

                            tr.Read();

                            if ((tr.Name == mailServiceStr) && (tr.NodeType == XmlNodeType.Element))
                            {
                                serviceCode = tr.ReadString();

                                tr.ReadEndElement();
                                if ((tr.Name == mailServiceStr) && (tr.NodeType == XmlNodeType.EndElement))
                                    break;
                            }

                            if ((tr.Name == rateStr) && (tr.NodeType == XmlNodeType.Element))
                            {
                                postalRate = tr.ReadString();
                                tr.ReadEndElement();
                                if ((tr.Name == rateStr) && (tr.NodeType == XmlNodeType.EndElement))
                                    break;
                            }

                        }
                        while (!((tr.Name == postageStr) && (tr.NodeType == XmlNodeType.EndElement)));

                        if (shippingOptions.Find((s) => s.Name == serviceCode) == null)
                        {
                            var shippingOption = new ShippingOption();
                            //TODO check whether we need to multiply rate by package quantity
                            shippingOption.Rate = Convert.ToDecimal(postalRate, new CultureInfo("en-US"));
                            shippingOption.Name = serviceCode;
                            shippingOptions.Add(shippingOption);
                        }
                    }
                }
                while (!tr.EOF);
            }
            return shippingOptions;
        }
        /// <summary>
        ///  Gets available shipping options
        /// </summary>
        /// <param name="shipmentPackage">Shipment package</param>
        /// <param name="error">Error</param>
        /// <returns>Shipping options</returns>
        public List<ShippingOption> GetShippingOptions(ShipmentPackage shipmentPackage, ref string error)
        {
            var shippingOptions = new List<ShippingOption>();
            if (shipmentPackage == null)
                throw new ArgumentNullException("shipmentPackage");
            if (shipmentPackage.Items == null)
                throw new NopException("No shipment items");
            if (shipmentPackage.ShippingAddress == null)
            {
                error = "Shipping address is not set";
                return shippingOptions;
            }
            if (shipmentPackage.ShippingAddress.Country == null)
            {
                error = "Shipping country is not set";
                return shippingOptions;
            }
            if (shipmentPackage.ShippingAddress.StateProvince == null)
            {
                error = "Shipping state is not set";
                return shippingOptions;
            }

            try
            {
                var profile = new Profile();
                //use "CPC_DEMO_XML" merchant ID for testing
                profile.MerchantId = SettingManager.GetSettingValue("ShippingRateComputationMethod.CanadaPost.CustomerID");

                var destination = new Destination();
                destination.City = shipmentPackage.ShippingAddress.City;
                destination.StateOrProvince = shipmentPackage.ShippingAddress.StateProvince.Abbreviation;
                destination.Country = shipmentPackage.ShippingAddress.Country.TwoLetterIsoCode;
                destination.PostalCode = shipmentPackage.ShippingAddress.ZipPostalCode;

                var items = CreateItems(shipmentPackage);

                var lang = CanadaPostLanguageEnum.English;
                if (NopContext.Current.WorkingLanguage.LanguageCulture.ToLowerInvariant().StartsWith("fr"))
                    lang = CanadaPostLanguageEnum.French;

                var requestResult = GetShippingOptionsInternal(profile, destination, items, lang);
                if (requestResult.IsError)
                {
                    error = requestResult.StatusMessage;
                }
                else
                {
                    foreach (var dr in requestResult.AvailableRates)
                    {
                        var so = new ShippingOption();
                        so.Name = dr.Name;
                        if (!string.IsNullOrEmpty(dr.DeliveryDate))
                            so.Name += string.Format(" - {0}", dr.DeliveryDate);
                        so.Rate = dr.Amount;
                        shippingOptions.Add(so);
                    }
                }

                foreach (var shippingOption in shippingOptions)
                {
                    if (!shippingOption.Name.ToLower().StartsWith("canada post"))
                        shippingOption.Name = string.Format("Canada Post {0}", shippingOption.Name);
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                error = e.Message;
            }

            return shippingOptions;
        }
        private ShippingOptionCollection ParseResponse(string response, ref string error)
        {
            ShippingOptionCollection shippingOptions = new ShippingOptionCollection();

            using (StringReader sr = new StringReader(response))
            using (XmlTextReader tr = new XmlTextReader(sr))


                do
                // while (tr.Read())
                {
                    // Read the next XML record
                    tr.Read();

                    if ((tr.Name == "Error") && (tr.NodeType == XmlNodeType.Element))
                    {
                        string errorText = "";
                        while (tr.Read())
                        {
                            if ((tr.Name == "Description") && (tr.NodeType == XmlNodeType.Element))
                                errorText += "Error Desc: " + tr.ReadString();
                            if ((tr.Name == "HelpContext") && (tr.NodeType == XmlNodeType.Element))
                                errorText += "USPS Help Context: " + tr.ReadString() + ". ";
                        }
                        error = "USPS Error returned: " + errorText;
                    }

                    // Process the inner postage XML
                    if ((tr.Name == "Postage") && (tr.NodeType == XmlNodeType.Element))
                    {
                        string serviceCode = "";
                        string postalRate = "";

                        // while (tr.Read())
                        do
                        {

                            tr.Read();

                            if ((tr.Name == "MailService") && (tr.NodeType == XmlNodeType.Element))
                            {
                                serviceCode = tr.ReadString();

                                tr.ReadEndElement();
                                if ((tr.Name == "MailService") && (tr.NodeType == XmlNodeType.EndElement))
                                    break;
                            }
                            // if (((tr.Name == "Postage") && (tr.NodeType == XmlNodeType.EndElement)) || ((tr.Name == "Postage") && (tr.NodeType == XmlNodeType.Element)))
                            //   break;

                            if ((tr.Name == "Rate") && (tr.NodeType == XmlNodeType.Element))
                            {
                                postalRate = tr.ReadString();
                                tr.ReadEndElement();
                                if ((tr.Name == "Rate") && (tr.NodeType == XmlNodeType.EndElement))
                                    break;
                            }

                        } while (!((tr.Name == "Postage") && (tr.NodeType == XmlNodeType.EndElement)));

                        if (shippingOptions.Find((s) => s.Name == serviceCode) == null)
                        {
                            ShippingOption shippingOption = new ShippingOption();
                            //TODO check whether we need to multiply rate by package quantity
                            shippingOption.Rate = Convert.ToDecimal(postalRate, new CultureInfo("en-US"));
                            shippingOption.Name = serviceCode;
                            shippingOptions.Add(shippingOption);
                        }
                    }
                } while (!tr.EOF);
            return shippingOptions;
        }
        /// <summary>
        /// Gets shopping cart shipping total
        /// </summary>
        /// <param name="cart">Cart</param>
        /// <param name="customer">Customer</param>
        /// <param name="includingTax">A value indicating whether calculated price should include tax</param>
        /// <param name="taxRate">Applied tax rate</param>
        /// <param name="appliedDiscount">Applied discount</param>
        /// <param name="error">Error</param>
        /// <returns>Shipping total</returns>
        public decimal?GetShoppingCartShippingTotal(ShoppingCart cart,
                                                    Customer customer, bool includingTax, out decimal taxRate,
                                                    out Discount appliedDiscount, ref string error)
        {
            decimal?shippingTotalWithoutDiscount   = null;
            decimal?shippingTotalWithDiscount      = null;
            decimal?shippingTotalWithDiscountTaxed = null;

            appliedDiscount = null;
            taxRate         = decimal.Zero;

            bool isFreeShipping = IsFreeShipping(cart, customer);

            if (isFreeShipping)
            {
                return(decimal.Zero);
            }

            ShippingOption lastShippingOption = null;

            if (customer != null)
            {
                lastShippingOption = customer.LastShippingOption;
            }

            if (lastShippingOption != null)
            {
                //use last shipping option (get from cache)
                //we have already discounted cache value
                shippingTotalWithoutDiscount = lastShippingOption.Rate;

                //discount
                decimal discountAmount = GetShippingDiscount(customer,
                                                             shippingTotalWithoutDiscount.Value, out appliedDiscount);
                shippingTotalWithDiscount = shippingTotalWithoutDiscount - discountAmount;
                if (shippingTotalWithDiscount < decimal.Zero)
                {
                    shippingTotalWithDiscount = decimal.Zero;
                }
                shippingTotalWithDiscount = Math.Round(shippingTotalWithDiscount.Value, 2);
            }
            else
            {
                //use fixed rate (if possible)
                Address shippingAddress = null;
                if (customer != null)
                {
                    shippingAddress = customer.ShippingAddress;
                }
                var ShipmentPackage = CreateShipmentPackage(cart, customer, shippingAddress);
                var shippingRateComputationMethods = GetAllShippingRateComputationMethods(false);
                if (shippingRateComputationMethods.Count == 0)
                {
                    throw new NopException("Shipping rate computation method could not be loaded");
                }

                if (shippingRateComputationMethods.Count == 1)
                {
                    var shippingRateComputationMethod  = shippingRateComputationMethods[0];
                    var iShippingRateComputationMethod = Activator.CreateInstance(Type.GetType(shippingRateComputationMethod.ClassName)) as IShippingRateComputationMethod;

                    decimal?fixedRate = iShippingRateComputationMethod.GetFixedRate(ShipmentPackage);
                    if (fixedRate.HasValue)
                    {
                        decimal additionalShippingCharge = GetShoppingCartAdditionalShippingCharge(cart, customer);
                        shippingTotalWithoutDiscount = fixedRate.Value + additionalShippingCharge;
                        shippingTotalWithoutDiscount = Math.Round(shippingTotalWithoutDiscount.Value, 2);
                        decimal shippingTotalDiscount = GetShippingDiscount(customer, shippingTotalWithoutDiscount.Value, out appliedDiscount);
                        shippingTotalWithDiscount = shippingTotalWithoutDiscount.Value - shippingTotalDiscount;
                        if (shippingTotalWithDiscount.Value < decimal.Zero)
                        {
                            shippingTotalWithDiscount = decimal.Zero;
                        }
                    }
                }
            }

            if (!shippingTotalWithDiscount.HasValue)
            {
                error = "Shipping total could not be calculated";
            }
            else
            {
                shippingTotalWithDiscountTaxed = IoC.Resolve <ITaxService>().GetShippingPrice(shippingTotalWithDiscount.Value,
                                                                                              includingTax,
                                                                                              customer,
                                                                                              out taxRate,
                                                                                              ref error);

                shippingTotalWithDiscountTaxed = Math.Round(shippingTotalWithDiscountTaxed.Value, 2);
            }

            return(shippingTotalWithDiscountTaxed);
        }
        /// <summary>
        ///  Gets available shipping options
        /// </summary>
        /// <param name="ShipmentPackage">Shipment package</param>
        /// <param name="Error">Error</param>
        /// <returns>Shipping options</returns>
        public ShippingOptionCollection GetShippingOptions(ShipmentPackage ShipmentPackage, ref string Error)
        {
            ShippingOptionCollection shippingOptions = new ShippingOptionCollection();

            if (ShipmentPackage == null)
                throw new ArgumentNullException("ShipmentPackage");
            if (ShipmentPackage.Items == null)
                throw new NopException("No shipment items");
            if (ShipmentPackage.ShippingAddress == null)
            {
                Error = "Shipping address is not set";
                return shippingOptions;
            }
            if (ShipmentPackage.ShippingAddress.Country == null)
            {
                Error = "Shipping country is not set";
                return shippingOptions;
            }

            decimal subTotal = decimal.Zero;
            foreach (ShoppingCartItem shoppingCartItem in ShipmentPackage.Items)
            {
                if (shoppingCartItem.IsFreeShipping)
                    continue;
                subTotal += PriceHelper.GetSubTotal(shoppingCartItem, ShipmentPackage.Customer, true);
            }
            decimal weight = ShippingManager.GetShoppingCartTotalWeigth(ShipmentPackage.Items);

            ShippingMethodCollection shippingMethods = ShippingMethodManager.GetAllShippingMethods();
            foreach (ShippingMethod shippingMethod in shippingMethods)
            {
                ShippingOption shippingOption = new ShippingOption();
                shippingOption.Name = shippingMethod.Name;
                shippingOption.Description = shippingMethod.Description;
                shippingOption.Rate = GetRate(subTotal, weight, shippingMethod.ShippingMethodID, ShipmentPackage.ShippingAddress.Country.CountryID);
                shippingOptions.Add(shippingOption);
            }

            return shippingOptions;
        }
        /// <summary>
        /// Gets shopping cart shipping total
        /// </summary>
        /// <param name="Cart">Cart</param>
        /// <param name="customer">Customer</param>
        /// <param name="includingTax">A value indicating whether calculated price should include tax</param>
        /// <param name="Error">Error</param>
        /// <returns>Shipping total</returns>
        public static decimal?GetShoppingCartShippingTotal(ShoppingCart Cart,
                                                           Customer customer, bool includingTax, ref string Error)
        {
            decimal?shippingTotal = null;

            bool isFreeShipping = IsFreeShipping(Cart, customer);

            if (isFreeShipping)
            {
                return(Decimal.Zero);
            }

            ShippingOption lastShippingOption = null;

            if (customer != null)
            {
                lastShippingOption = customer.LastShippingOption;
            }

            if (lastShippingOption != null)
            {
                //use last shipping option (get from cache)
                shippingTotal = TaxManager.GetShippingPrice(lastShippingOption.Rate,
                                                            includingTax,
                                                            customer,
                                                            ref Error);
            }
            else
            {
                //use fixed rate (if possible)
                Address shippingAddress = null;
                if (customer != null)
                {
                    shippingAddress = customer.ShippingAddress;
                }
                ShipmentPackage ShipmentPackage = CreateShipmentPackage(Cart, customer, shippingAddress);
                ShippingRateComputationMethod activeShippingRateComputationMethod = ActiveShippingRateComputationMethod;
                if (activeShippingRateComputationMethod == null)
                {
                    throw new NopException("Shipping rate computation method could not be loaded");
                }
                IShippingRateComputationMethod iShippingRateComputationMethod = Activator.CreateInstance(Type.GetType(activeShippingRateComputationMethod.ClassName)) as IShippingRateComputationMethod;

                decimal?fixedRate = iShippingRateComputationMethod.GetFixedRate(ShipmentPackage);
                if (fixedRate.HasValue)
                {
                    decimal additionalShippingCharge = GetShoppingCartAdditionalShippingCharge(Cart, customer);

                    shippingTotal = TaxManager.GetShippingPrice(fixedRate.Value + additionalShippingCharge,
                                                                includingTax,
                                                                customer,
                                                                ref Error);
                }
            }

            if (!shippingTotal.HasValue)
            {
                Error = "Shipping total could not be calculated";
            }
            else
            {
                if (HttpContext.Current.Request.Cookies["Currency"] != null && HttpContext.Current.Request.Cookies["Currency"].Value == "USD")
                {
                    shippingTotal = Math.Round(PriceConverter.ToUsd(shippingTotal.Value));
                }
                else
                {
                    shippingTotal = Math.Round(shippingTotal.Value, 2);
                }
            }
            return(shippingTotal);
        }
        private List<ShippingOption> ParseResponse(string response, bool isDomestic, ref string error)
        {
            var shippingOptions = new List<ShippingOption>();

            string postageStr = isDomestic ? "Postage" : "Service";
            string mailServiceStr = isDomestic ? "MailService" : "SvcDescription";
            string rateStr = isDomestic ? "Rate" : "Postage";

            using (var sr = new StringReader(response))
            using (var tr = new XmlTextReader(sr))
            {
                do
                {
                    tr.Read();

                    if ((tr.Name == "Error") && (tr.NodeType == XmlNodeType.Element))
                    {
                        string errorText = "";
                        while (tr.Read())
                        {
                            if ((tr.Name == "Description") && (tr.NodeType == XmlNodeType.Element))
                                errorText += "Error Desc: " + tr.ReadString();
                            if ((tr.Name == "HelpContext") && (tr.NodeType == XmlNodeType.Element))
                                errorText += "USPS Help Context: " + tr.ReadString() + ". ";
                        }
                        error = "USPS Error returned: " + errorText;
                    }

                    if ((tr.Name == postageStr) && (tr.NodeType == XmlNodeType.Element))
                    {
                        string serviceCode = string.Empty;
                        string postalRate = string.Empty;

                        do
                        {

                            tr.Read();

                            if ((tr.Name == mailServiceStr) && (tr.NodeType == XmlNodeType.Element))
                            {
                                serviceCode = tr.ReadString();

                                tr.ReadEndElement();
                                if ((tr.Name == mailServiceStr) && (tr.NodeType == XmlNodeType.EndElement))
                                    break;
                            }

                            if ((tr.Name == rateStr) && (tr.NodeType == XmlNodeType.Element))
                            {
                                postalRate = tr.ReadString();
                                tr.ReadEndElement();
                                if ((tr.Name == rateStr) && (tr.NodeType == XmlNodeType.EndElement))
                                    break;
                            }

                        }
                        while (!((tr.Name == postageStr) && (tr.NodeType == XmlNodeType.EndElement)));

                        if (shippingOptions.Find((s) => s.Name == serviceCode) == null)
                        {
                            var shippingOption = new ShippingOption();
                            //TODO check whether we need to multiply rate by package quantity
                            shippingOption.Rate = Convert.ToDecimal(postalRate, new CultureInfo("en-US"));
                            shippingOption.Name = serviceCode;
                            shippingOptions.Add(shippingOption);
                        }
                    }
                }
                while (!tr.EOF);
            }
            return shippingOptions;
        }
        /// <summary>
        ///  Gets available shipping options
        /// </summary>
        /// <param name="shipmentPackage">Shipment package</param>
        /// <param name="error">Error</param>
        /// <returns>Shipping options</returns>
        public List<ShippingOption> GetShippingOptions(ShipmentPackage shipmentPackage, ref string error)
        {
            var shippingOptions = new List<ShippingOption>();

            if (shipmentPackage == null)
                throw new ArgumentNullException("shipmentPackage");
            if (shipmentPackage.Items == null)
                throw new NopException("No shipment items");
            if (shipmentPackage.ShippingAddress == null)
            {
                error = "Shipping address is not set";
                return shippingOptions;
            }
            if (shipmentPackage.ShippingAddress.Country == null)
            {
                error = "Shipping country is not set";
                return shippingOptions;
            }

            var shippingMethods = ShippingMethodManager.GetAllShippingMethods(shipmentPackage.ShippingAddress.CountryId);
            foreach (var shippingMethod in shippingMethods)
            {
                var shippingOption = new ShippingOption();
                shippingOption.Name = shippingMethod.Name;
                shippingOption.Description = shippingMethod.Description;
                shippingOption.Rate = decimal.Zero;
                shippingOptions.Add(shippingOption);
            }

            return shippingOptions;
        }