private RateRequest CreateRateRequest(ShipmentPackage ShipmentPackage)
        {
            // Build the RateRequest
            RateRequest request = new RateRequest();
            //
            request.WebAuthenticationDetail = new WebAuthenticationDetail();
            request.WebAuthenticationDetail.UserCredential = new WebAuthenticationCredential();
            request.WebAuthenticationDetail.UserCredential.Key = SettingManager.GetSettingValue("ShippingRateComputationMethod.FedEx.Key"); // Replace "XXX" with the Key
            request.WebAuthenticationDetail.UserCredential.Password = SettingManager.GetSettingValue("ShippingRateComputationMethod.FedEx.Password"); // Replace "XXX" with the Password
            //
            request.ClientDetail = new ClientDetail();
            request.ClientDetail.AccountNumber = SettingManager.GetSettingValue("ShippingRateComputationMethod.FedEx.AccountNumber"); // Replace "XXX" with client's account number
            request.ClientDetail.MeterNumber = SettingManager.GetSettingValue("ShippingRateComputationMethod.FedEx.MeterNumber"); // Replace "XXX" with client's meter number
            //
            request.TransactionDetail = new TransactionDetail();
            request.TransactionDetail.CustomerTransactionId = "***Rate Available Services v7 Request - nopCommerce***"; // This is a reference field for the customer.  Any value can be used and will be provided in the response.

            request.Version = new VersionId(); // WSDL version information, value is automatically set from wsdl            

            request.ReturnTransitAndCommit = true;
            request.ReturnTransitAndCommitSpecified = true;
            request.CarrierCodes = new CarrierCodeType[2];
            // Insert the Carriers you would like to see the rates for
            request.CarrierCodes[0] = CarrierCodeType.FDXE;
            request.CarrierCodes[1] = CarrierCodeType.FDXG;

            decimal orderSubTotal = ShoppingCartManager.GetShoppingCartSubTotal(ShipmentPackage.Items, ShipmentPackage.Customer);
            SetShipmentDetails(request, ShipmentPackage, orderSubTotal);
            SetOrigin(request);
            SetDestination(request, ShipmentPackage);
            SetPayment(request, ShipmentPackage);
            SetIndividualPackageLineItems(request, ShipmentPackage, orderSubTotal);

            return request;
        }
        /// <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;
            }

            string url = SettingManager.GetSettingValue("ShippingRateComputationMethod.USPS.URL");
            string username = SettingManager.GetSettingValue("ShippingRateComputationMethod.USPS.Username");
            string password = SettingManager.GetSettingValue("ShippingRateComputationMethod.USPS.Password");
            decimal additionalHandlingCharge = SettingManager.GetSettingValueDecimalNative("ShippingRateComputationMethod.USPS.AdditionalHandlingCharge");
            shipmentPackage.ZipPostalCodeFrom = SettingManager.GetSettingValue("ShippingRateComputationMethod.USPS.DefaultShippedFromZipPostalCode");

            bool isDomestic = IsDomesticRequest(shipmentPackage);
            string requestString = CreateRequest(username, password, shipmentPackage);
            string responseXML = DoRequest(url, requestString);
            shippingOptions = ParseResponse(responseXML, isDomestic, ref error);
            foreach (var shippingOption in shippingOptions)
            {
                if (!shippingOption.Name.ToLower().StartsWith("usps"))
                    shippingOption.Name = string.Format("USPS {0}", shippingOption.Name);
                shippingOption.Rate += additionalHandlingCharge;
            }

            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;
        }
        /// <summary>
        ///  Gets available shipping options
        /// </summary>
        /// <param name="Cart">Shopping cart</param>
        /// <param name="customer">Customer</param>
        /// <param name="ShippingAddress">Shipping address</param>
        /// <param name="Error">Error</param>
        /// <returns>Shipping options</returns>
        public static ShippingOptionCollection GetShippingOptions(ShoppingCart Cart, Customer customer, Address ShippingAddress, ref string Error)
        {
            if (Cart == null)
            {
                throw new ArgumentNullException("Cart");
            }

            bool isFreeShipping = IsFreeShipping(Cart, customer);

            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;

            ShippingOptionCollection shippingOptions = iShippingRateComputationMethod.GetShippingOptions(ShipmentPackage, ref Error);

            decimal additionalShippingCharge = GetShoppingCartAdditionalShippingCharge(Cart, customer);

            shippingOptions.ForEach(so => so.Rate += additionalShippingCharge);

            if (isFreeShipping)
            {
                shippingOptions.ForEach(so => so.Rate = Decimal.Zero);
            }

            shippingOptions.ForEach(so => so.Rate = Math.Round(so.Rate, 2));

            return(shippingOptions);
        }
        /// <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");

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

            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, shippingMethod.ShippingMethodID);
                shippingOptions.Add(shippingOption);
            }

            return shippingOptions;
        }
 private void SetShipmentDetails(RateRequest request, ShipmentPackage ShipmentPackage, decimal orderSubTotal)
 {
     request.RequestedShipment = new RequestedShipment();
     request.RequestedShipment.DropoffType = DropoffType.REGULAR_PICKUP; //Drop off types are BUSINESS_SERVICE_CENTER, DROP_BOX, REGULAR_PICKUP, REQUEST_COURIER, STATION
     request.RequestedShipment.TotalInsuredValue = new Money();
     request.RequestedShipment.TotalInsuredValue.Amount = orderSubTotal;
     request.RequestedShipment.TotalInsuredValue.Currency = CurrencyManager.PrimaryStoreCurrency.CurrencyCode.ToString();
     request.RequestedShipment.ShipTimestamp = DateTime.Now; // Shipping date and time
     request.RequestedShipment.ShipTimestampSpecified = true;
     request.RequestedShipment.RateRequestTypes = new RateRequestType[2];
     request.RequestedShipment.RateRequestTypes[0] = RateRequestType.ACCOUNT;
     request.RequestedShipment.RateRequestTypes[1] = RateRequestType.LIST;
     request.RequestedShipment.PackageDetail = RequestedPackageDetailType.INDIVIDUAL_PACKAGES;
     request.RequestedShipment.PackageDetailSpecified = true;
 }
        /// <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;
            }

            string url = IoC.Resolve<ISettingManager>().GetSettingValue("ShippingRateComputationMethod.UPS.URL");
            string accessKey = IoC.Resolve<ISettingManager>().GetSettingValue("ShippingRateComputationMethod.UPS.AccessKey");
            string username = IoC.Resolve<ISettingManager>().GetSettingValue("ShippingRateComputationMethod.UPS.Username");
            string password = IoC.Resolve<ISettingManager>().GetSettingValue("ShippingRateComputationMethod.UPS.Password");
            var customerClassification = (UPSCustomerClassification)Enum.Parse(typeof(UPSCustomerClassification), IoC.Resolve<ISettingManager>().GetSettingValue("ShippingRateComputationMethod.UPS.CustomerClassification"));
            var pickupType = (UPSPickupType)Enum.Parse(typeof(UPSPickupType), IoC.Resolve<ISettingManager>().GetSettingValue("ShippingRateComputationMethod.UPS.PickupType"));
            var packagingType = (UPSPackagingType)Enum.Parse(typeof(UPSPackagingType), IoC.Resolve<ISettingManager>().GetSettingValue("ShippingRateComputationMethod.UPS.PackagingType"));
            decimal additionalHandlingCharge = IoC.Resolve<ISettingManager>().GetSettingValueDecimalNative("ShippingRateComputationMethod.UPS.AdditionalHandlingCharge");
            if (shipmentPackage.CountryFrom == null)
            {
                int defaultShippedFromCountryID = IoC.Resolve<ISettingManager>().GetSettingValueInteger("ShippingRateComputationMethod.UPS.DefaultShippedFromCountryID");
                shipmentPackage.CountryFrom = IoC.Resolve<ICountryService>().GetCountryById(defaultShippedFromCountryID);
            }
            if (String.IsNullOrEmpty(shipmentPackage.ZipPostalCodeFrom))
                shipmentPackage.ZipPostalCodeFrom = IoC.Resolve<ISettingManager>().GetSettingValue("ShippingRateComputationMethod.UPS.DefaultShippedFromZipPostalCode");

            string requestString = CreateRequest(accessKey, username, password, shipmentPackage,
                customerClassification, pickupType, packagingType);
            string responseXML = DoRequest(url, requestString);
            shippingOptions = ParseResponse(responseXML, ref error);
            foreach (var shippingOption in shippingOptions)
            {
                if (!shippingOption.Name.ToLower().StartsWith("ups"))
                    shippingOption.Name = string.Format("UPS {0}", shippingOption.Name);
                shippingOption.Rate += additionalHandlingCharge;
            }

            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;
            }

            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;
        }
        /// <summary>
        /// Create shipment package from shopping cart
        /// </summary>
        /// <param name="Cart">Shopping cart</param>
        /// <param name="customer">Customer</param>
        /// <param name="ShippingAddress">Shipping address</param>
        /// <returns>Shipment package</returns>
        protected static ShipmentPackage CreateShipmentPackage(ShoppingCart Cart, Customer customer, Address ShippingAddress)
        {
            ShipmentPackage shipmentPackage = new ShipmentPackage();

            shipmentPackage.Customer = customer;
            shipmentPackage.Items    = new ShoppingCart();
            foreach (ShoppingCartItem sc in Cart)
            {
                if (sc.IsShipEnabled)
                {
                    shipmentPackage.Items.Add(sc);
                }
            }
            shipmentPackage.ShippingAddress = ShippingAddress;
            //TODO set values from warehouses or shipping origin
            shipmentPackage.CountryFrom       = null;
            shipmentPackage.StateProvinceFrom = null;
            shipmentPackage.ZipPostalCodeFrom = String.Empty;
            return(shipmentPackage);
        }
        /// <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 SetDestination(RateRequest request, ShipmentPackage ShipmentPackage)
 {
     request.RequestedShipment.Recipient = new Party();
     request.RequestedShipment.Recipient.Address = new Address();
     if (IoC.Resolve<ISettingManager>().GetSettingValueBoolean("ShippingRateComputationMethod.FedEx.UseResidentialRates", false))
     {
         request.RequestedShipment.Recipient.Address.Residential = true;
         request.RequestedShipment.Recipient.Address.ResidentialSpecified = true;
     }
     request.RequestedShipment.Recipient.Address.StreetLines = new string[1] { "Recipient Address Line 1" };
     request.RequestedShipment.Recipient.Address.City = ShipmentPackage.ShippingAddress.City;
     if (ShipmentPackage.ShippingAddress.StateProvince != null)
     {
         request.RequestedShipment.Recipient.Address.StateOrProvinceCode = ShipmentPackage.ShippingAddress.StateProvince.Abbreviation;
     }
     else
     {
         request.RequestedShipment.Recipient.Address.StateOrProvinceCode = string.Empty;
     }
     request.RequestedShipment.Recipient.Address.PostalCode = ShipmentPackage.ShippingAddress.ZipPostalCode;
     request.RequestedShipment.Recipient.Address.CountryCode = ShipmentPackage.ShippingAddress.Country.TwoLetterIsoCode;
 }
        private void SetIndividualPackageLineItems(RateRequest request, ShipmentPackage ShipmentPackage, decimal orderSubTotal)
        {
            // ------------------------------------------
            // Passing individual pieces rate request
            // ------------------------------------------

            var usedMeasureWeight = IoC.Resolve<IMeasureService>().GetMeasureWeightBySystemKeyword(MEASUREWEIGHTSYSTEMKEYWORD);
            if (usedMeasureWeight == null)
                throw new NopException(string.Format("FedEx shipping service. Could not load \"{0}\" measure weight", MEASUREWEIGHTSYSTEMKEYWORD));

            var usedMeasureDimension = IoC.Resolve<IMeasureService>().GetMeasureDimensionBySystemKeyword(MEASUREDIMENSIONSYSTEMKEYWORD);
            if (usedMeasureDimension == null)
                throw new NopException(string.Format("FedEx shipping service. Could not load \"{0}\" measure dimension", MEASUREDIMENSIONSYSTEMKEYWORD));

            int length = Convert.ToInt32(Math.Ceiling(IoC.Resolve<IMeasureService>().ConvertDimension(ShipmentPackage.GetTotalLength(), IoC.Resolve<IMeasureService>().BaseDimensionIn, usedMeasureDimension)));
            int height = Convert.ToInt32(Math.Ceiling(IoC.Resolve<IMeasureService>().ConvertDimension(ShipmentPackage.GetTotalHeight(), IoC.Resolve<IMeasureService>().BaseDimensionIn, usedMeasureDimension)));
            int width = Convert.ToInt32(Math.Ceiling(IoC.Resolve<IMeasureService>().ConvertDimension(ShipmentPackage.GetTotalWidth(), IoC.Resolve<IMeasureService>().BaseDimensionIn, usedMeasureDimension)));
            int weight = Convert.ToInt32(Math.Ceiling(IoC.Resolve<IMeasureService>().ConvertWeight(IoC.Resolve<IShippingService>().GetShoppingCartTotalWeight(ShipmentPackage.Items, ShipmentPackage.Customer), IoC.Resolve<IMeasureService>().BaseWeightIn, usedMeasureWeight)));
            if (length < 1)
                length = 1;
            if (height < 1)
                height = 1;
            if (width < 1)
                width = 1;
            if (weight < 1)
                weight = 1;

            if ((!IsPackageTooHeavy(weight)) && (!IsPackageTooLarge(length, height, width)))
            {
                request.RequestedShipment.PackageCount = "1";

                request.RequestedShipment.RequestedPackageLineItems = new RequestedPackageLineItem[1];
                request.RequestedShipment.RequestedPackageLineItems[0] = new RequestedPackageLineItem();
                request.RequestedShipment.RequestedPackageLineItems[0].SequenceNumber = "1"; // package sequence number
                request.RequestedShipment.RequestedPackageLineItems[0].Weight = new Weight(); // package weight
                request.RequestedShipment.RequestedPackageLineItems[0].Weight.Units = WeightUnits.LB;
                request.RequestedShipment.RequestedPackageLineItems[0].Weight.Value = weight;
                request.RequestedShipment.RequestedPackageLineItems[0].Dimensions = new Dimensions(); // package dimensions

                //it's better to don't pass dims now
                request.RequestedShipment.RequestedPackageLineItems[0].Dimensions.Length = "0";
                request.RequestedShipment.RequestedPackageLineItems[0].Dimensions.Width = "0";
                request.RequestedShipment.RequestedPackageLineItems[0].Dimensions.Height = "0";
                request.RequestedShipment.RequestedPackageLineItems[0].Dimensions.Units = LinearUnits.IN;
                request.RequestedShipment.RequestedPackageLineItems[0].InsuredValue = new Money(); // insured value
                request.RequestedShipment.RequestedPackageLineItems[0].InsuredValue.Amount = orderSubTotal;
                request.RequestedShipment.RequestedPackageLineItems[0].InsuredValue.Currency = IoC.Resolve<ICurrencyService>().PrimaryStoreCurrency.CurrencyCode.ToString();

            }
            else
            {
                int totalPackages = 1;
                int totalPackagesDims = 1;
                int totalPackagesWeights = 1;
                if (IsPackageTooHeavy(weight))
                {
                    totalPackagesWeights = Convert.ToInt32(Math.Ceiling((decimal)weight / (decimal)MAXPACKAGEWEIGHT));
                }
                if (IsPackageTooLarge(length, height, width))
                {
                    totalPackagesDims = Convert.ToInt32(Math.Ceiling((decimal)TotalPackageSize(length, height, width) / (decimal)108));
                }
                totalPackages = totalPackagesDims > totalPackagesWeights ? totalPackagesDims : totalPackagesWeights;
                if (totalPackages == 0)
                    totalPackages = 1;

                int weight2 = weight / totalPackages;
                int height2 = height / totalPackages;
                int width2 = width / totalPackages;
                int length2 = length / totalPackages;
                if (weight2 < 1)
                    weight2 = 1;
                if (height2 < 1)
                    height2 = 1;
                if (width2 < 1)
                    width2 = 1;
                if (length2 < 1)
                    length2 = 1;

                decimal orderSubTotal2 = orderSubTotal / totalPackages;

                request.RequestedShipment.PackageCount = totalPackages.ToString();
                request.RequestedShipment.RequestedPackageLineItems = new RequestedPackageLineItem[totalPackages];

                for (int i = 0; i < totalPackages; i++)
                {
                    request.RequestedShipment.RequestedPackageLineItems[i] = new RequestedPackageLineItem();
                    request.RequestedShipment.RequestedPackageLineItems[i].SequenceNumber = (i + 1).ToString(); // package sequence number
                    request.RequestedShipment.RequestedPackageLineItems[i].Weight = new Weight(); // package weight
                    request.RequestedShipment.RequestedPackageLineItems[i].Weight.Units = WeightUnits.LB;
                    request.RequestedShipment.RequestedPackageLineItems[i].Weight.Value = (decimal)weight2;
                    request.RequestedShipment.RequestedPackageLineItems[i].Dimensions = new Dimensions(); // package dimensions

                    //it's better to don't pass dims now
                    request.RequestedShipment.RequestedPackageLineItems[i].Dimensions.Length = "0";
                    request.RequestedShipment.RequestedPackageLineItems[i].Dimensions.Width = "0";
                    request.RequestedShipment.RequestedPackageLineItems[i].Dimensions.Height = "0";
                    request.RequestedShipment.RequestedPackageLineItems[i].Dimensions.Units = LinearUnits.IN;
                    request.RequestedShipment.RequestedPackageLineItems[i].InsuredValue = new Money(); // insured value
                    request.RequestedShipment.RequestedPackageLineItems[i].InsuredValue.Amount = orderSubTotal2;
                    request.RequestedShipment.RequestedPackageLineItems[i].InsuredValue.Currency = IoC.Resolve<ICurrencyService>().PrimaryStoreCurrency.CurrencyCode.ToString();
                }
            }
        }
 private static int GetWidth(ShipmentPackage shipmentPackage)
 {
     int value = Convert.ToInt32(Math.Ceiling(MeasureManager.ConvertDimension(shipmentPackage.GetTotalWidth(), MeasureManager.BaseDimensionIn, AustraliaPostSettings.MeasureDimension)));
     return (value < MIN_LENGTH ? MIN_LENGTH : value);
 }
        /// <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;
            }

            shipmentPackage.ZipPostalCodeFrom = AustraliaPostSettings.ShippedFromZipPostalCode;
            string zipPostalCodeFrom = shipmentPackage.ZipPostalCodeFrom;
            string zipPostalCodeTo = shipmentPackage.ShippingAddress.ZipPostalCode;
            int weight = GetWeight(shipmentPackage);
            int length = GetLength(shipmentPackage);
            int width = GetWidth(shipmentPackage);
            int height = GetHeight(shipmentPackage);

            Country country = shipmentPackage.ShippingAddress.Country;

            //estimate packaging
            int totalPackages = 1;
            int totalPackagesDims = 1;
            int totalPackagesWeights = 1;
            if (length > MAX_LENGTH || width > MAX_LENGTH || height > MAX_LENGTH)
            {
                totalPackagesDims = Convert.ToInt32(Math.Ceiling((decimal)Math.Max(Math.Max(length, width), height) / MAX_LENGTH));
            }
            if (weight > MAX_WEIGHT)
            {
                totalPackagesWeights = Convert.ToInt32(Math.Ceiling((decimal)weight / (decimal)MAX_WEIGHT));
            }
            totalPackages = totalPackagesDims > totalPackagesWeights ? totalPackagesDims : totalPackagesWeights;
            if (totalPackages == 0)
                totalPackages = 1;
            if (totalPackages > 1)
            {
                //recalculate dims, weight
                weight = weight / totalPackages;
                height = height / totalPackages;
                width = width / totalPackages;
                length = length / totalPackages;
                if (weight < MIN_WEIGHT)
                    weight = MIN_WEIGHT;
                if (height < MIN_LENGTH)
                    height = MIN_LENGTH;
                if (width < MIN_LENGTH)
                    width = MIN_LENGTH;
                if (length < MIN_LENGTH)
                    length = MIN_LENGTH;
            }

            int girth = height + height + width + width;
            if (girth < MIN_GIRTH)
            {
                height = MIN_LENGTH;
                width = MIN_LENGTH;
            }
            if (girth > MAX_GIRTH)
            {
                height = MAX_LENGTH / 4;
                width = MAX_LENGTH / 4;
            }
            try
            {
                switch (country.ThreeLetterIsoCode)
                {
                    case "AUS":
                        shippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, country.TwoLetterIsoCode, "Standard", weight, length, width, height, totalPackages));
                        shippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, country.TwoLetterIsoCode, "Express", weight, length, width, height, totalPackages));
                        shippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, country.TwoLetterIsoCode, "EXP_PLT", weight, length, width, height, totalPackages));
                        break;
                    default:
                        shippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, country.TwoLetterIsoCode, "Air", weight, length, width, height, totalPackages));
                        shippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, country.TwoLetterIsoCode, "Sea", weight, length, width, height, totalPackages));
                        shippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, country.TwoLetterIsoCode, "ECI_D", weight, length, width, height, totalPackages));
                        shippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, country.TwoLetterIsoCode, "ECI_M", weight, length, width, height, totalPackages));
                        shippingOptions.Add(RequestShippingOption(zipPostalCodeFrom, zipPostalCodeTo, country.TwoLetterIsoCode, "EPI", weight, length, width, height, totalPackages));
                        break;
                }

                foreach (ShippingOption shippingOption in shippingOptions)
                {
                    shippingOption.Rate += AustraliaPostSettings.AdditionalHandlingCharge;
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }
            return shippingOptions;
        }
 /// <summary>
 /// Is a request domestic
 /// </summary>
 /// <param name="shipmentPackage">Shipment package</param>
 /// <returns>Rsult</returns>
 protected bool IsDomesticRequest(ShipmentPackage shipmentPackage)
 {
     //Origin Country must be USA, Collect USA from list of countries
     bool result = true;
     if (shipmentPackage != null &&
         shipmentPackage.ShippingAddress != null &&
         shipmentPackage.ShippingAddress.Country != null)
     {
         result = shipmentPackage.ShippingAddress.Country.ThreeLetterIsoCode == "USA";
     }
     return result;
 }
        /// <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;
            }

            string url = SettingManager.GetSettingValue("ShippingRateComputationMethod.UPS.URL");
            string accessKey = SettingManager.GetSettingValue("ShippingRateComputationMethod.UPS.AccessKey");
            string username = SettingManager.GetSettingValue("ShippingRateComputationMethod.UPS.Username");
            string password = SettingManager.GetSettingValue("ShippingRateComputationMethod.UPS.Password");
            UPSCustomerClassification customerClassification = (UPSCustomerClassification)Enum.Parse(typeof(UPSCustomerClassification), SettingManager.GetSettingValue("ShippingRateComputationMethod.UPS.CustomerClassification"));
            UPSPickupType pickupType = (UPSPickupType)Enum.Parse(typeof(UPSPickupType), SettingManager.GetSettingValue("ShippingRateComputationMethod.UPS.PickupType"));
            UPSPackagingType packagingType = (UPSPackagingType)Enum.Parse(typeof(UPSPackagingType), SettingManager.GetSettingValue("ShippingRateComputationMethod.UPS.PackagingType"));
            decimal additionalHandlingCharge = SettingManager.GetSettingValueDecimalNative("ShippingRateComputationMethod.UPS.AdditionalHandlingCharge");
            if (ShipmentPackage.CountryFrom == null)
            {
                int defaultShippedFromCountryID = SettingManager.GetSettingValueInteger("ShippingRateComputationMethod.UPS.DefaultShippedFromCountryID");
                ShipmentPackage.CountryFrom = CountryManager.GetCountryByID(defaultShippedFromCountryID);
            }
            if (String.IsNullOrEmpty(ShipmentPackage.ZipPostalCodeFrom))
                ShipmentPackage.ZipPostalCodeFrom = SettingManager.GetSettingValue("ShippingRateComputationMethod.UPS.DefaultShippedFromZipPostalCode");
            
            string requestString = CreateRequest(accessKey, username, password, ShipmentPackage,
                customerClassification, pickupType, packagingType);
            string responseXML = DoRequest(url, requestString);
            shippingOptions = ParseResponse(responseXML, ref Error);
            foreach (ShippingOption shippingOption in shippingOptions)
                shippingOption.Rate += additionalHandlingCharge;
           
            if (String.IsNullOrEmpty(Error) && shippingOptions.Count == 0)
                Error = "Shipping options could not be loaded";
            return shippingOptions;
        }
 /// <summary>
 /// Gets fixed shipping rate (if shipping rate computation method allows it and the rate can be calculated before checkout).
 /// </summary>
 /// <param name="shipmentPackage">Shipment package</param>
 /// <returns>Fixed shipping rate; or null if shipping rate could not be calculated before checkout</returns>
 public decimal? GetFixedRate(ShipmentPackage shipmentPackage)
 {
     return null;
 }
        /// <summary>
        ///  Gets available shipping options
        /// </summary>
        /// <param name="ShipmentPackage">Shipment option</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 NopSolutions.NopCommerce.Common.NopException("No shipment items");
            if (ShipmentPackage.ShippingAddress == null)
            {
                Error = "Shipping address is not set";
                return shippingOptions;
            }

            string url = SettingManager.GetSettingValue("ShippingRateComputationMethod.USPS.URL");
            string username = SettingManager.GetSettingValue("ShippingRateComputationMethod.USPS.Username");
            string password = SettingManager.GetSettingValue("ShippingRateComputationMethod.USPS.Password");
            decimal additionalHandlingCharge = SettingManager.GetSettingValueDecimalNative("ShippingRateComputationMethod.USPS.AdditionalHandlingCharge");
            ShipmentPackage.ZipPostalCodeFrom = SettingManager.GetSettingValue("ShippingRateComputationMethod.USPS.DefaultShippedFromZipPostalCode");
            string requestString = CreateRequest(username, password, ShipmentPackage);
            string responseXML = DoRequest(url, requestString);
            shippingOptions = ParseResponse(responseXML, ref Error);
            foreach (ShippingOption shippingOption in shippingOptions)
                shippingOption.Rate += additionalHandlingCharge;

            if (String.IsNullOrEmpty(Error) && shippingOptions.Count == 0)
                Error = "Shipping options could not be loaded";
            return shippingOptions;
        }
 private static int GetLength(ShipmentPackage shipmentPackage)
 {
     int value = Convert.ToInt32(Math.Ceiling(IoC.Resolve<IMeasureService>().ConvertDimension(shipmentPackage.GetTotalLength(), IoC.Resolve<IMeasureService>().BaseDimensionIn, AustraliaPostSettings.MeasureDimension)));
     return (value < MIN_LENGTH ? MIN_LENGTH : value);
 }
        /// <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;
            }

            MeasureWeight baseWeightIn = MeasureManager.BaseWeightIn;
            if (baseWeightIn.SystemKeyword != "lb")
                throw new NopException("USPS shipping service. Base weight should be set to lb(s)");

            MeasureDimension baseDimensionIn = MeasureManager.BaseDimensionIn;
            if (baseDimensionIn.SystemKeyword != "inches")
                throw new NopException("USPS shipping service. Base dimension should be set to inch(es)");



            RateRequest request = CreateRateRequest(ShipmentPackage);
            RateService service = new RateService(); // Initialize the service
            service.Url = SettingManager.GetSettingValue("ShippingRateComputationMethod.FedEx.URL");
            try
            {
                // This is the call to the web service passing in a RateRequest and returning a RateReply
                RateReply reply = service.getRates(request); // Service call
                //
                if (reply.HighestSeverity == NotificationSeverityType.SUCCESS || reply.HighestSeverity == NotificationSeverityType.NOTE || reply.HighestSeverity == NotificationSeverityType.WARNING) // check if the call was successful
                {
                    if (reply != null && reply.RateReplyDetails != null)
                    {
                        shippingOptions = ParseResponse(reply);
                    }
                    else
                    {
                        Error = "Could not get reply from shipping server";
                    }
                }
                else
                {
                    Debug.WriteLine(reply.Notifications[0].Message);
                    Error = reply.Notifications[0].Message;
                }
            }
            catch (SoapException e)
            {
                Debug.WriteLine(e.Detail.InnerText);
                Error = e.Detail.InnerText;
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                Error = e.Message;
            }



            if (String.IsNullOrEmpty(Error) && shippingOptions.Count == 0)
                Error = "Shipping options could not be loaded";
            return shippingOptions;
        }
 private static int GetWeight(ShipmentPackage shipmentPackage)
 {
     int value = Convert.ToInt32(Math.Ceiling(IoC.Resolve<IMeasureService>().ConvertWeight(IoC.Resolve<IShippingService>().GetShoppingCartTotalWeight(shipmentPackage.Items, shipmentPackage.Customer), IoC.Resolve<IMeasureService>().BaseWeightIn, AustraliaPostSettings.MeasureWeight)));
     return (value < MIN_WEIGHT ? MIN_WEIGHT : value);
 }
        private string CreateRequest(string AccessKey, string Username, string Password,
            ShipmentPackage ShipmentPackage, UPSCustomerClassification customerClassification,
            UPSPickupType pickupType, UPSPackagingType packagingType)
        {
            var usedMeasureWeight = IoC.Resolve<IMeasureService>().GetMeasureWeightBySystemKeyword(MEASUREWEIGHTSYSTEMKEYWORD);
            if (usedMeasureWeight == null)
                throw new NopException(string.Format("UPS shipping service. Could not load \"{0}\" measure weight", MEASUREWEIGHTSYSTEMKEYWORD));

            var usedMeasureDimension = IoC.Resolve<IMeasureService>().GetMeasureDimensionBySystemKeyword(MEASUREDIMENSIONSYSTEMKEYWORD);
            if (usedMeasureDimension == null)
                throw new NopException(string.Format("UPS shipping service. Could not load \"{0}\" measure dimension", MEASUREDIMENSIONSYSTEMKEYWORD));

            int length = Convert.ToInt32(Math.Ceiling(IoC.Resolve<IMeasureService>().ConvertDimension(ShipmentPackage.GetTotalLength(), IoC.Resolve<IMeasureService>().BaseDimensionIn, usedMeasureDimension)));
            int height = Convert.ToInt32(Math.Ceiling(IoC.Resolve<IMeasureService>().ConvertDimension(ShipmentPackage.GetTotalHeight(), IoC.Resolve<IMeasureService>().BaseDimensionIn, usedMeasureDimension)));
            int width = Convert.ToInt32(Math.Ceiling(IoC.Resolve<IMeasureService>().ConvertDimension(ShipmentPackage.GetTotalWidth(), IoC.Resolve<IMeasureService>().BaseDimensionIn, usedMeasureDimension)));
            int weight = Convert.ToInt32(Math.Ceiling(IoC.Resolve<IMeasureService>().ConvertWeight(IoC.Resolve<IShippingService>().GetShoppingCartTotalWeight(ShipmentPackage.Items, ShipmentPackage.Customer), IoC.Resolve<IMeasureService>().BaseWeightIn, usedMeasureWeight)));
            if (length < 1)
                length = 1;
            if (height < 1)
                height = 1;
            if (width < 1)
                width = 1;
            if (weight < 1)
                weight = 1;

            string zipPostalCodeFrom = ShipmentPackage.ZipPostalCodeFrom;
            string zipPostalCodeTo = ShipmentPackage.ShippingAddress.ZipPostalCode;
            string countryCodeFrom = ShipmentPackage.CountryFrom.TwoLetterIsoCode;
            string countryCodeTo = ShipmentPackage.ShippingAddress.Country.TwoLetterIsoCode;

            var sb = new StringBuilder();
            sb.Append("<?xml version='1.0'?>");
            sb.Append("<AccessRequest xml:lang='en-US'>");
            sb.AppendFormat("<AccessLicenseNumber>{0}</AccessLicenseNumber>", AccessKey);
            sb.AppendFormat("<UserId>{0}</UserId>", Username);
            sb.AppendFormat("<Password>{0}</Password>", Password);
            sb.Append("</AccessRequest>");
            sb.Append("<?xml version='1.0'?>");
            sb.Append("<RatingServiceSelectionRequest xml:lang='en-US'>");
            sb.Append("<Request>");
            sb.Append("<TransactionReference>");
            sb.Append("<CustomerContext>Bare Bones Rate Request</CustomerContext>");
            sb.Append("<XpciVersion>1.0001</XpciVersion>");
            sb.Append("</TransactionReference>");
            sb.Append("<RequestAction>Rate</RequestAction>");
            sb.Append("<RequestOption>Shop</RequestOption>");
            sb.Append("</Request>");
            if (String.Equals(countryCodeFrom, "US", StringComparison.InvariantCultureIgnoreCase) == true)
            {
                sb.Append("<PickupType>");
                sb.AppendFormat("<Code>{0}</Code>", GetPickupTypeCode(pickupType));
                sb.Append("</PickupType>");
                sb.Append("<CustomerClassification>");
                sb.AppendFormat("<Code>{0}</Code>", GetCustomerClassificationCode(customerClassification));
                sb.Append("</CustomerClassification>");
            }
            sb.Append("<Shipment>");
            sb.Append("<Shipper>");
            sb.Append("<Address>");
            sb.AppendFormat("<PostalCode>{0}</PostalCode>", zipPostalCodeFrom);
            sb.AppendFormat("<CountryCode>{0}</CountryCode>", countryCodeFrom);
            sb.Append("</Address>");
            sb.Append("</Shipper>");
            sb.Append("<ShipTo>");
            sb.Append("<Address>");
            sb.Append("<ResidentialAddressIndicator/>");
            sb.AppendFormat("<PostalCode>{0}</PostalCode>", zipPostalCodeTo);
            sb.AppendFormat("<CountryCode>{0}</CountryCode>", countryCodeTo);
            sb.Append("</Address>");
            sb.Append("</ShipTo>");
            sb.Append("<ShipFrom>");
            sb.Append("<Address>");
            sb.AppendFormat("<PostalCode>{0}</PostalCode>", zipPostalCodeFrom);
            sb.AppendFormat("<CountryCode>{0}</CountryCode>", countryCodeFrom);
            sb.Append("</Address>");
            sb.Append("</ShipFrom>");
            sb.Append("<Service>");
            sb.Append("<Code>03</Code>");
            sb.Append("</Service>");

            if ((!IsPackageTooHeavy(weight)) && (!IsPackageTooLarge(length, height, width)))
            {
                sb.Append("<Package>");
                sb.Append("<PackagingType>");
                sb.AppendFormat("<Code>{0}</Code>", GetPackagingTypeCode(packagingType));
                sb.Append("</PackagingType>");
                sb.Append("<Dimensions>");
                sb.AppendFormat("<Length>{0}</Length>", length);
                sb.AppendFormat("<Width>{0}</Width>", width);
                sb.AppendFormat("<Height>{0}</Height>", height);
                sb.Append("</Dimensions>");
                sb.Append("<PackageWeight>");
                sb.AppendFormat("<Weight>{0}</Weight>", weight);
                sb.Append("</PackageWeight>");
                sb.Append("</Package>");
            }
            else
            {
                int totalPackages = 1;
                int totalPackagesDims = 1;
                int totalPackagesWeights = 1;
                if (IsPackageTooHeavy(weight))
                {
                    totalPackagesWeights = Convert.ToInt32(Math.Ceiling((decimal)weight / (decimal)MAXPACKAGEWEIGHT));
                }
                if (IsPackageTooLarge(length, height, width))
                {
                    totalPackagesDims = Convert.ToInt32(Math.Ceiling((decimal)TotalPackageSize(length, height, width) / (decimal)108));
                }
                totalPackages = totalPackagesDims > totalPackagesWeights ? totalPackagesDims : totalPackagesWeights;
                if (totalPackages == 0)
                    totalPackages = 1;

                int weight2 = weight / totalPackages;
                int height2 = height / totalPackages;
                int width2 = width / totalPackages;
                int length2 = length / totalPackages;
                if (weight2 < 1)
                    weight2 = 1;
                if (height2 < 1)
                    height2 = 1;
                if (width2 < 1)
                    width2 = 1;
                if (length2 < 1)
                    length2 = 1;

                for (int i = 0; i < totalPackages; i++)
                {
                    sb.Append("<Package>");
                    sb.Append("<PackagingType>");
                    sb.AppendFormat("<Code>{0}</Code>", GetPackagingTypeCode(packagingType));
                    sb.Append("</PackagingType>");
                    sb.Append("<Dimensions>");
                    sb.AppendFormat("<Length>{0}</Length>", length2);
                    sb.AppendFormat("<Width>{0}</Width>", width2);
                    sb.AppendFormat("<Height>{0}</Height>", height2);
                    sb.Append("</Dimensions>");
                    sb.Append("<PackageWeight>");
                    sb.AppendFormat("<Weight>{0}</Weight>", weight2);
                    sb.Append("</PackageWeight>");
                    sb.Append("</Package>");
                }
            }

            sb.Append("</Shipment>");
            sb.Append("</RatingServiceSelectionRequest>");
            string requestString = sb.ToString();
            return requestString;
        }
        /// <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 void SetPayment(RateRequest request, ShipmentPackage ShipmentPackage)
 {
     request.RequestedShipment.ShippingChargesPayment = new Payment(); // Payment Information
     request.RequestedShipment.ShippingChargesPayment.PaymentType = PaymentType.SENDER; // Payment options are RECIPIENT, SENDER, THIRD_PARTY
     request.RequestedShipment.ShippingChargesPayment.PaymentTypeSpecified = true;
     request.RequestedShipment.ShippingChargesPayment.Payor = new Payor();
     request.RequestedShipment.ShippingChargesPayment.Payor.AccountNumber = IoC.Resolve<ISettingManager>().GetSettingValue("ShippingRateComputationMethod.FedEx.AccountNumber"); // Replace "XXX" with client's account number
 }
        private List<Item> CreateItems(ShipmentPackage ShipmentPackage)
        {
            var  result = new List<Item>();

            var usedMeasureWeight = MeasureManager.GetMeasureWeightBySystemKeyword("kg");
            if (usedMeasureWeight == null)
                throw new NopException("CanadaPost shipping service. Could not load \"kg\" measure weight");

            var usedMeasureDimension = MeasureManager.GetMeasureDimensionBySystemKeyword("meters");
            if (usedMeasureDimension == null)
                throw new NopException("CanadaPost shipping service. Could not load \"meter(s)\" measure dimension");

            foreach (var sci in ShipmentPackage.Items)
            {
                var pv = sci.ProductVariant;

                var item = new Item();
                item.Quantity = sci.Quantity;
                //Canada Post uses kg(s)
                decimal unitWeight = sci.TotalWeight / sci.Quantity;
                item.Weight = MeasureManager.ConvertWeight(unitWeight, MeasureManager.BaseWeightIn, usedMeasureWeight);
                item.Weight = Math.Round(item.Weight, 2);
                if (item.Weight == decimal.Zero)
                    item.Weight = 0.01M;

                //Canada Post uses centimeters
                item.Length = Convert.ToInt32(Math.Ceiling(MeasureManager.ConvertDimension(pv.Length, MeasureManager.BaseDimensionIn, usedMeasureDimension) * 100));
                if (item.Length == decimal.Zero)
                    item.Length = 1;
                item.Width = Convert.ToInt32(Math.Ceiling(MeasureManager.ConvertDimension(pv.Width, MeasureManager.BaseDimensionIn, usedMeasureDimension) * 100));
                if (item.Width == decimal.Zero)
                    item.Width = 1;
                item.Height = Convert.ToInt32(Math.Ceiling(MeasureManager.ConvertDimension(pv.Height, MeasureManager.BaseDimensionIn, usedMeasureDimension) * 100));
                if (item.Height == decimal.Zero)
                    item.Height = 1;
                result.Add(item);
            }

            return result;
        }
        /// <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;
            }

            RateRequest request = CreateRateRequest(shipmentPackage);
            RateService service = new RateService(); // Initialize the service
            service.Url = IoC.Resolve<ISettingManager>().GetSettingValue("ShippingRateComputationMethod.FedEx.URL");
            try
            {
                // This is the call to the web service passing in a RateRequest and returning a RateReply
                var reply = service.getRates(request); // Service call

                if (reply.HighestSeverity == NotificationSeverityType.SUCCESS || reply.HighestSeverity == NotificationSeverityType.NOTE || reply.HighestSeverity == NotificationSeverityType.WARNING) // check if the call was successful
                {
                    if (reply != null && reply.RateReplyDetails != null)
                    {
                        shippingOptions = ParseResponse(reply);
                    }
                    else
                    {
                        if (reply!=null &&
                            reply.Notifications != null &&
                            reply.Notifications.Length > 0 &&
                            !String.IsNullOrEmpty(reply.Notifications[0].Message))
                        {
                            error = string.Format("{0} (code: {1})", reply.Notifications[0].Message, reply.Notifications[0].Code);
                        }
                        else
                        {
                            error = "Could not get reply from shipping server";
                        }
                    }
                }
                else
                {
                    Debug.WriteLine(reply.Notifications[0].Message);
                    error = reply.Notifications[0].Message;
                }
            }
            catch (SoapException e)
            {
                Debug.WriteLine(e.Detail.InnerText);
                error = e.Detail.InnerText;
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                error = e.Message;
            }

            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 string CreateRequest(string Username, string Password, ShipmentPackage ShipmentPackage)
        {
            int length = Convert.ToInt32(Math.Ceiling(ShipmentPackage.GetTotalLength()));
            int height = Convert.ToInt32(Math.Ceiling(ShipmentPackage.GetTotalHeight()));
            int width = Convert.ToInt32(Math.Ceiling(ShipmentPackage.GetTotalWidth()));
            decimal weight = ShippingManager.GetShoppingCartTotalWeigth(ShipmentPackage.Items);
            string zipPostalCodeFrom = ShipmentPackage.ZipPostalCodeFrom;
            string zipPostalCodeTo = ShipmentPackage.ShippingAddress.ZipPostalCode;

            //valid values for testing. http://testing.shippingapis.com/ShippingAPITest.dll
            //Zip to = "20008"; Zip from ="10022"; weight = 2;

            //TODO convert measure weight
            MeasureWeight baseWeightIn = MeasureManager.BaseWeightIn;
            if (baseWeightIn.SystemKeyword != "lb")
                throw new NopException("USPS shipping service. Base weight should be set to lb(s)");

            //TODO convert measure dimension
            MeasureDimension baseDimensionIn = MeasureManager.BaseDimensionIn;
            if (baseDimensionIn.SystemKeyword != "inches")
                throw new NopException("USPS shipping service. Base dimension should be set to inch(es)");

            int pounds = Convert.ToInt32(Math.Truncate(weight));
            //int ounces = Convert.ToInt32((weight - pounds) * 16.0M);
            int ounces = 0;

            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("<RateV3Request USERID=\"{0}\" PASSWORD=\"{1}\">", Username, Password);

            USPSStrings xmlStrings = new USPSStrings(); // Create new instance with string array


            if ((!IsPackageTooHeavy(pounds)) && (!IsPackageTooLarge(length, height, width)))
            {
                USPSPackageSize packageSize = GetPackageSize(length, height, width);
                // RJH get all XML strings not commented out for USPSStrings. 
                // RJH V3 USPS Service must be Express, Express SH, Express Commercial, Express SH Commercial, First Class, Priority, Priority Commercial, Parcel, Library, BPM, Media, ALL or ONLINE;
                foreach (string element in xmlStrings.Elements) // Loop over elements with property
                {
                    sb.Append("<Package ID=\"0\">");

                    // sb.AppendFormat("<Service>{0}</Service>", USPSService.All);
                    sb.AppendFormat("<Service>{0}</Service>", element);
                    sb.AppendFormat("<ZipOrigination>{0}</ZipOrigination>", zipPostalCodeFrom);
                    sb.AppendFormat("<ZipDestination>{0}</ZipDestination>", zipPostalCodeTo);
                    sb.AppendFormat("<Pounds>{0}</Pounds>", pounds);
                    sb.AppendFormat("<Ounces>{0}</Ounces>", ounces);
                    sb.AppendFormat("<Size>{0}</Size>", packageSize);
                    sb.Append("<Machinable>FALSE</Machinable>");

                    sb.Append("</Package>");
                }
            }
            else
            {
                int totalPackages = 1;
                int totalPackagesDims = 1;
                int totalPackagesWeights = 1;
                if (IsPackageTooHeavy(pounds))
                {
                    totalPackagesWeights = Convert.ToInt32(Math.Ceiling((decimal)pounds / (decimal)MAXPACKAGEWEIGHT));
                }
                if (IsPackageTooLarge(length, height, width))
                {
                    totalPackagesDims = TotalPackageSize(length, height, width)/108;
                }
                totalPackages = totalPackagesDims > totalPackagesWeights ? totalPackagesDims : totalPackagesWeights;
                if (totalPackages == 0)
                    totalPackages = 1;

                int pounds2 = pounds / totalPackages;
                int ounces2 = ounces / totalPackages;
                int height2 = height / totalPackages;
                int width2 = width / totalPackages;
                USPSPackageSize packageSize = GetPackageSize(length, height2, width2);
                
                for (int i = 0; i < totalPackages; i++)
                {
                    foreach (string element in xmlStrings.Elements)
                    {
                        sb.AppendFormat("<Package ID=\"{0}\">", i.ToString());
                        // sb.AppendFormat("<Service>{0}</Service>", USPSService.All);
                        sb.AppendFormat("<Service>{0}</Service>", element);
                        sb.AppendFormat("<ZipOrigination>{0}</ZipOrigination>", zipPostalCodeFrom);
                        sb.AppendFormat("<ZipDestination>{0}</ZipDestination>", zipPostalCodeTo);
                        sb.AppendFormat("<Pounds>{0}</Pounds>", pounds2);
                        sb.AppendFormat("<Ounces>{0}</Ounces>", ounces2);
                        sb.AppendFormat("<Size>{0}</Size>", packageSize);
                        sb.Append("<Machinable>FALSE</Machinable>");
                        sb.Append("</Package>");
                    }
                }
            }

            sb.Append("</RateV3Request>");

            string requestString = "API=RateV3&XML=" + sb.ToString();

            return requestString;
        }
 private static int GetWeight(ShipmentPackage shipmentPackage)
 {
     int value = Convert.ToInt32(Math.Ceiling(MeasureManager.ConvertWeight(ShippingManager.GetShoppingCartTotalWeight(shipmentPackage.Items, shipmentPackage.Customer), MeasureManager.BaseWeightIn, AustraliaPostSettings.MeasureWeight)));
     return (value < MIN_WEIGHT ? MIN_WEIGHT : value);
 }
        private string CreateRequest(string username, string password, ShipmentPackage shipmentPackage)
        {
            var usedMeasureWeight = MeasureManager.GetMeasureWeightBySystemKeyword(MEASUREWEIGHTSYSTEMKEYWORD);
            if (usedMeasureWeight == null)
                throw new NopException(string.Format("USPS shipping service. Could not load \"{0}\" measure weight", MEASUREWEIGHTSYSTEMKEYWORD));

            var usedMeasureDimension = MeasureManager.GetMeasureDimensionBySystemKeyword(MEASUREDIMENSIONSYSTEMKEYWORD);
            if (usedMeasureDimension == null)
                throw new NopException(string.Format("USPS shipping service. Could not load \"{0}\" measure dimension", MEASUREDIMENSIONSYSTEMKEYWORD));

            int length = Convert.ToInt32(Math.Ceiling(MeasureManager.ConvertDimension(shipmentPackage.GetTotalLength(), MeasureManager.BaseDimensionIn, usedMeasureDimension)));
            int height = Convert.ToInt32(Math.Ceiling(MeasureManager.ConvertDimension(shipmentPackage.GetTotalHeight(), MeasureManager.BaseDimensionIn, usedMeasureDimension)));
            int width = Convert.ToInt32(Math.Ceiling(MeasureManager.ConvertDimension(shipmentPackage.GetTotalWidth(), MeasureManager.BaseDimensionIn, usedMeasureDimension)));
            int weight = Convert.ToInt32(Math.Ceiling(MeasureManager.ConvertWeight(ShippingManager.GetShoppingCartTotalWeight(shipmentPackage.Items, shipmentPackage.Customer), MeasureManager.BaseWeightIn, usedMeasureWeight)));
            if (length < 1)
                length = 1;
            if (height < 1)
                height = 1;
            if (width < 1)
                width = 1;
            if (weight < 1)
                weight = 1;

            string zipPostalCodeFrom = shipmentPackage.ZipPostalCodeFrom;
            string zipPostalCodeTo = shipmentPackage.ShippingAddress.ZipPostalCode;

            //valid values for testing. http://testing.shippingapis.com/ShippingAPITest.dll
            //Zip to = "20008"; Zip from ="10022"; weight = 2;

            int pounds = weight;
            //we don't use ounce
            //int ounces = Convert.ToInt32((weight - pounds) * 16.0M);
            int ounces = 0;
            if (pounds < 1)
                pounds = 1;

            string requestString = string.Empty;

            bool isDomestic = IsDomesticRequest(shipmentPackage);
            if (isDomestic)
            {
                #region domestic request
                var sb = new StringBuilder();
                sb.AppendFormat("<RateV3Request USERID=\"{0}\" PASSWORD=\"{1}\">", username, password);

                var xmlStrings = new USPSStrings(); // Create new instance with string array

                if ((!IsPackageTooHeavy(pounds)) && (!IsPackageTooLarge(length, height, width)))
                {
                    var packageSize = GetPackageSize(length, height, width);
                    // RJH get all XML strings not commented out for USPSStrings.
                    // RJH V3 USPS Service must be Express, Express SH, Express Commercial, Express SH Commercial, First Class, Priority, Priority Commercial, Parcel, Library, BPM, Media, ALL or ONLINE;
                    foreach (string element in xmlStrings.Elements) // Loop over elements with property
                    {
                        sb.Append("<Package ID=\"0\">");

                        // sb.AppendFormat("<Service>{0}</Service>", USPSService.All);
                        sb.AppendFormat("<Service>{0}</Service>", element);
                        sb.AppendFormat("<ZipOrigination>{0}</ZipOrigination>", zipPostalCodeFrom);
                        sb.AppendFormat("<ZipDestination>{0}</ZipDestination>", zipPostalCodeTo);
                        sb.AppendFormat("<Pounds>{0}</Pounds>", pounds);
                        sb.AppendFormat("<Ounces>{0}</Ounces>", ounces);
                        sb.AppendFormat("<Size>{0}</Size>", packageSize);
                        sb.Append("<Machinable>FALSE</Machinable>");

                        sb.Append("</Package>");
                    }
                }
                else
                {
                    int totalPackages = 1;
                    int totalPackagesDims = 1;
                    int totalPackagesWeights = 1;
                    if (IsPackageTooHeavy(pounds))
                    {
                        totalPackagesWeights = Convert.ToInt32(Math.Ceiling((decimal)pounds / (decimal)MAXPACKAGEWEIGHT));
                    }
                    if (IsPackageTooLarge(length, height, width))
                    {
                        totalPackagesDims = Convert.ToInt32(Math.Ceiling((decimal)TotalPackageSize(length, height, width) / (decimal)108));
                    }
                    totalPackages = totalPackagesDims > totalPackagesWeights ? totalPackagesDims : totalPackagesWeights;
                    if (totalPackages == 0)
                        totalPackages = 1;

                    int pounds2 = pounds / totalPackages;
                    //we don't use ounces
                    int ounces2 = ounces / totalPackages;
                    int height2 = height / totalPackages;
                    int width2 = width / totalPackages;
                    int length2 = length / totalPackages;
                    if (pounds2 < 1)
                        pounds2 = 1;
                    if (height2 < 1)
                        height2 = 1;
                    if (width2 < 1)
                        width2 = 1;
                    if (length2 < 1)
                        length2 = 1;

                    var packageSize = GetPackageSize(length2, height2, width2);

                    for (int i = 0; i < totalPackages; i++)
                    {
                        foreach (string element in xmlStrings.Elements)
                        {
                            sb.AppendFormat("<Package ID=\"{0}\">", i.ToString());
                            // sb.AppendFormat("<Service>{0}</Service>", USPSService.All);
                            sb.AppendFormat("<Service>{0}</Service>", element);
                            sb.AppendFormat("<ZipOrigination>{0}</ZipOrigination>", zipPostalCodeFrom);
                            sb.AppendFormat("<ZipDestination>{0}</ZipDestination>", zipPostalCodeTo);
                            sb.AppendFormat("<Pounds>{0}</Pounds>", pounds2);
                            sb.AppendFormat("<Ounces>{0}</Ounces>", ounces2);
                            sb.AppendFormat("<Size>{0}</Size>", packageSize);
                            sb.Append("<Machinable>FALSE</Machinable>");
                            sb.Append("</Package>");
                        }
                    }
                }

                sb.Append("</RateV3Request>");

                requestString = "API=RateV3&XML=" + sb.ToString();
                #endregion
            }
            else
            {
                #region international request
                var sb = new StringBuilder();
                sb.AppendFormat("<IntlRateRequest USERID=\"{0}\" PASSWORD=\"{1}\">", username, password);

                if ((!IsPackageTooHeavy(pounds)) && (!IsPackageTooLarge(length, height, width)))
                {
                    //little hack here for international requests
                    length = 12;
                    width = 12;
                    height = 12;

                    string mailType = "Package"; //Package, Envelope
                    sb.Append("<Package ID=\"0\">");
                    // No use of pounds in this classes
                    sb.Append("<Pounds>0</Pounds>");
                    ounces = PoundsToOunces(pounds);
                    sb.AppendFormat("<Ounces>{0}</Ounces>", ounces);
                    sb.Append("<Machinable>FALSE</Machinable>");
                    sb.AppendFormat("<MailType>{0}</MailType>", mailType);
                    sb.Append("<GXG>");
                    sb.AppendFormat("<Length>{0}</Length>", length);
                    sb.AppendFormat("<Width>{0}</Width>", width);
                    sb.AppendFormat("<Height>{0}</Height>", height);
                    sb.Append("<POBoxFlag>N</POBoxFlag>");
                    sb.Append("<GiftFlag>N</GiftFlag>");
                    sb.Append("</GXG>");
                    sb.AppendFormat("<Country>{0}</Country>", shipmentPackage.ShippingAddress.Country.Name);

                    sb.Append("</Package>");
                }
                else
                {
                    int totalPackages = 1;
                    int totalPackagesDims = 1;
                    int totalPackagesWeights = 1;
                    if (IsPackageTooHeavy(pounds))
                    {
                        totalPackagesWeights = Convert.ToInt32(Math.Ceiling((decimal)pounds / (decimal)MAXPACKAGEWEIGHT));
                    }
                    if (IsPackageTooLarge(length, height, width))
                    {
                        totalPackagesDims = Convert.ToInt32(Math.Ceiling((decimal)TotalPackageSize(length, height, width) / (decimal)108));
                    }
                    totalPackages = totalPackagesDims > totalPackagesWeights ? totalPackagesDims : totalPackagesWeights;
                    if (totalPackages == 0)
                        totalPackages = 1;

                    int pounds2 = pounds / totalPackages;
                    //we don't use ounces
                    int ounces2 = ounces / totalPackages;
                    int height2 = height / totalPackages;
                    int width2 = width / totalPackages;
                    int length2 = length / totalPackages;
                    if (pounds2 < 1)
                        pounds2 = 1;
                    if (height2 < 1)
                        height2 = 1;
                    if (width2 < 1)
                        width2 = 1;
                    if (length2 < 1)
                        length2 = 1;

                    //little hack here for international requests
                    length2 = 12;
                    width2 = 12;
                    height2 = 12;

                    for (int i = 0; i < totalPackages; i++)
                    {
                        string mailType = "Package"; //Package, Envelope

                        sb.AppendFormat("<Package ID=\"{0}\">", i.ToString());
                        // No use of pounds in this classes
                        sb.Append("<Pounds>0</Pounds>");
                        ounces2 = PoundsToOunces(pounds2);
                        sb.AppendFormat("<Ounces>{0}</Ounces>", ounces2);
                        sb.Append("<Machinable>FALSE</Machinable>");
                        sb.AppendFormat("<MailType>{0}</MailType>", mailType);
                        sb.Append("<GXG>");
                        sb.AppendFormat("<Length>{0}</Length>", length2);
                        sb.AppendFormat("<Width>{0}</Width>", width2);
                        sb.AppendFormat("<Height>{0}</Height>", height2);
                        sb.Append("<POBoxFlag>N</POBoxFlag>");
                        sb.Append("<GiftFlag>N</GiftFlag>");
                        sb.Append("</GXG>");
                        sb.AppendFormat("<Country>{0}</Country>", shipmentPackage.ShippingAddress.Country.Name);

                        sb.Append("</Package>");
                    }
                }

                sb.Append("</IntlRateRequest>");

                requestString = "API=IntlRate&XML=" + sb.ToString();
                #endregion
            }

            return requestString;
        }
        private string CreateRequest(string AccessKey, string Username, string Password,
            ShipmentPackage ShipmentPackage, UPSCustomerClassification customerClassification,
            UPSPickupType pickupType, UPSPackagingType packagingType)
        {
            int length = Convert.ToInt32(Math.Ceiling(ShipmentPackage.GetTotalLength()));
            int height = Convert.ToInt32(Math.Ceiling(ShipmentPackage.GetTotalHeight()));
            int width = Convert.ToInt32(Math.Ceiling(ShipmentPackage.GetTotalWidth()));
            int weight = Convert.ToInt32(Math.Ceiling(ShippingManager.GetShoppingCartTotalWeigth(ShipmentPackage.Items)));
            string zipPostalCodeFrom = ShipmentPackage.ZipPostalCodeFrom;
            string zipPostalCodeTo = ShipmentPackage.ShippingAddress.ZipPostalCode;
            string countryCodeFrom = ShipmentPackage.CountryFrom.TwoLetterISOCode;
            string countryCodeTo = ShipmentPackage.ShippingAddress.Country.TwoLetterISOCode;

            //TODO convert measure weight
            MeasureWeight baseWeightIn = MeasureManager.BaseWeightIn;
            if (baseWeightIn.SystemKeyword != "lb")
                throw new NopException("UPS shipping service. Base weight should be set to lb(s)");

            //TODO convert measure dimension
            MeasureDimension baseDimensionIn = MeasureManager.BaseDimensionIn;
            if (baseDimensionIn.SystemKeyword != "inches")
                throw new NopException("UPS shipping service. Base dimension should be set to inch(es)");

            StringBuilder sb = new StringBuilder();
            sb.Append("<?xml version='1.0'?>");
            sb.Append("<AccessRequest xml:lang='en-US'>");
            sb.AppendFormat("<AccessLicenseNumber>{0}</AccessLicenseNumber>", AccessKey);
            sb.AppendFormat("<UserId>{0}</UserId>", Username);
            sb.AppendFormat("<Password>{0}</Password>", Password);
            sb.Append("</AccessRequest>");
            sb.Append("<?xml version='1.0'?>");
            sb.Append("<RatingServiceSelectionRequest xml:lang='en-US'>");
            sb.Append("<Request>");
            sb.Append("<TransactionReference>");
            sb.Append("<CustomerContext>Bare Bones Rate Request</CustomerContext>");
            sb.Append("<XpciVersion>1.0001</XpciVersion>");
            sb.Append("</TransactionReference>");
            sb.Append("<RequestAction>Rate</RequestAction>");
            sb.Append("<RequestOption>Shop</RequestOption>");
            sb.Append("</Request>");
            sb.Append("<PickupType>");
            sb.AppendFormat("<Code>{0}</Code>", GetPickupTypeCode(pickupType));
            sb.Append("</PickupType>");
            sb.Append("<CustomerClassification>");
            sb.AppendFormat("<Code>{0}</Code>", GetCustomerClassificationCode(customerClassification));
            sb.Append("</CustomerClassification>");
            sb.Append("<Shipment>");
            sb.Append("<Shipper>");
            sb.Append("<Address>");
            sb.AppendFormat("<PostalCode>{0}</PostalCode>", zipPostalCodeFrom);
            sb.AppendFormat("<CountryCode>{0}</CountryCode>", countryCodeFrom);
            sb.Append("</Address>");
            sb.Append("</Shipper>");
            sb.Append("<ShipTo>");
            sb.Append("<Address>");
            sb.Append("<ResidentialAddressIndicator/>");
            sb.AppendFormat("<PostalCode>{0}</PostalCode>", zipPostalCodeTo);
            sb.AppendFormat("<CountryCode>{0}</CountryCode>", countryCodeTo);
            sb.Append("</Address>");
            sb.Append("</ShipTo>");
            sb.Append("<ShipFrom>");
            sb.Append("<Address>");
            sb.AppendFormat("<PostalCode>{0}</PostalCode>", zipPostalCodeFrom);
            sb.AppendFormat("<CountryCode>{0}</CountryCode>", countryCodeFrom);
            sb.Append("</Address>");
            sb.Append("</ShipFrom>");
            sb.Append("<Service>");
            //UNDONE set correct service code
            sb.Append("<Code>03</Code>");
            sb.Append("</Service>");


            if ((!IsPackageTooHeavy(weight)) && (!IsPackageTooLarge(length, height, width)))
            {
                sb.Append("<Package>");
                sb.Append("<PackagingType>");
                sb.AppendFormat("<Code>{0}</Code>", GetPackagingTypeCode(packagingType));
                sb.Append("</PackagingType>");
                sb.Append("<Dimensions>");
                sb.AppendFormat("<Length>{0}</Length>", length);
                sb.AppendFormat("<Width>{0}</Width>", width);
                sb.AppendFormat("<Height>{0}</Height>", height);
                sb.Append("</Dimensions>");
                sb.Append("<PackageWeight>");
                sb.AppendFormat("<Weight>{0}</Weight>", weight);
                sb.Append("</PackageWeight>");
                sb.Append("</Package>");
            }
            else
            {
                int totalPackages = 1;
                int totalPackagesDims = 1;
                int totalPackagesWeights = 1;
                if (IsPackageTooHeavy(weight))
                {
                    totalPackagesWeights = Convert.ToInt32(Math.Ceiling((decimal)weight / (decimal)MAXPACKAGEWEIGHT));
                }
                if (IsPackageTooLarge(length, height, width))
                {
                    totalPackagesDims = TotalPackageSize(length, height, width)/108;
                }
                totalPackages = totalPackagesDims > totalPackagesWeights ? totalPackagesDims : totalPackagesWeights;
                if (totalPackages == 0)
                    totalPackages = 1;

                int weight2 = weight/totalPackages;
                int height2 = height/totalPackages;
                int width2 = width/totalPackages;

                for (int i = 0; i < totalPackages; i++)
                {
                    sb.Append("<Package>");
                    sb.Append("<PackagingType>");
                    sb.AppendFormat("<Code>{0}</Code>", GetPackagingTypeCode(packagingType));
                    sb.Append("</PackagingType>");
                    sb.Append("<Dimensions>");
                    sb.AppendFormat("<Length>{0}</Length>", length);
                    sb.AppendFormat("<Width>{0}</Width>", width2);
                    sb.AppendFormat("<Height>{0}</Height>", height2);
                    sb.Append("</Dimensions>");
                    sb.Append("<PackageWeight>");
                    sb.AppendFormat("<Weight>{0}</Weight>", weight2);
                    sb.Append("</PackageWeight>");
                    sb.Append("</Package>");
                }
            }


            sb.Append("</Shipment>");
            sb.Append("</RatingServiceSelectionRequest>");
            string requestString = sb.ToString();
            return requestString;
        }
 /// <summary>
 /// Create shipment package from shopping cart
 /// </summary>
 /// <param name="cart">Shopping cart</param>
 /// <param name="customer">Customer</param>
 /// <param name="shippingAddress">Shipping address</param>
 /// <returns>Shipment package</returns>
 protected static ShipmentPackage CreateShipmentPackage(ShoppingCart cart, 
     Customer customer, Address shippingAddress)
 {
     var shipmentPackage = new ShipmentPackage();
     shipmentPackage.Customer = customer;
     shipmentPackage.Items = new ShoppingCart();
     foreach (var sc in cart)
         if (sc.IsShipEnabled)
             shipmentPackage.Items.Add(sc);
     shipmentPackage.ShippingAddress = shippingAddress;
     //TODO set values from warehouses or shipping origin
     shipmentPackage.CountryFrom = null;
     shipmentPackage.StateProvinceFrom = null;
     shipmentPackage.ZipPostalCodeFrom = string.Empty;
     return shipmentPackage;
 }
 /// <summary>
 /// Gets fixed shipping rate (if shipping rate computation method allows it and the rate can be calculated before checkout).
 /// </summary>
 /// <param name="ShipmentPackage">Shipment package</param>
 /// <returns>Fixed shipping rate; or null if shipping rate could not be calculated before checkout</returns>
 public decimal? GetFixedRate(ShipmentPackage ShipmentPackage)
 {
     return GetRate();
 }