private string BuildUPSRateRequestForShipment(IShipment shipment, UpsSettings settings)
        {
            var sXML      = string.Empty;
            var strWriter = new StringWriter();
            var xw        = new XmlTextWriter(strWriter);

            try
            {
                xw.Formatting  = Formatting.Indented;
                xw.Indentation = 3;

                //--------------------------------------------
                // Agreement Request
                xw.WriteStartElement("RatingServiceSelectionRequest");

                //--------------------------------------------
                // Request
                xw.WriteStartElement("Request");
                //--------------------------------------------
                // TransactionReference
                xw.WriteStartElement("TransactionReference");
                xw.WriteElementString("CustomerContext", "Rate Request");
                xw.WriteElementString("XpciVersion", "1.0001");
                xw.WriteEndElement();
                // End TransactionReference
                //--------------------------------------------
                xw.WriteElementString("RequestOption", "Shop");
                xw.WriteEndElement();
                // End Request
                //--------------------------------------------

                //--------------------------------------------
                // Pickup Type
                if (GlobalSettings.PickUpType != PickupType.Unknown)
                {
                    var pickupCode = ((int)GlobalSettings.PickUpType).ToString();

                    if (pickupCode.Trim().Length < 2)
                    {
                        pickupCode = "0" + pickupCode;
                    }

                    xw.WriteStartElement("PickupType");
                    xw.WriteElementString("Code", pickupCode);
                    xw.WriteEndElement();
                }
                // End Pickup Type
                //--------------------------------------------

                //--------------------------------------------
                // Shipment
                xw.WriteStartElement("Shipment");

                // Shipper
                xw.WriteStartElement("Shipper");
                xw.WriteStartElement("Address");

                //Use City name for countries that don't have postal codes
                if (shipment.SourceAddress.PostalCode.Trim().Length > 0)
                {
                    xw.WriteElementString("PostalCode",
                                          XmlTools.TrimToLength(shipment.SourceAddress.PostalCode.Trim(), 9));
                }
                else
                {
                    xw.WriteElementString("City", XmlTools.TrimToLength(shipment.SourceAddress.City.Trim(), 30));
                }

                if (shipment.SourceAddress.RegionData != null)
                {
                    xw.WriteElementString("StateProvinceCode", shipment.SourceAddress.RegionData.Abbreviation);
                }

                xw.WriteElementString("CountryCode", shipment.SourceAddress.CountryData.IsoCode);

                xw.WriteElementString("ShipperNumber", settings.License);

                xw.WriteEndElement();
                xw.WriteEndElement();

                // Ship To
                xw.WriteStartElement("ShipTo");
                xw.WriteStartElement("Address");

                if (shipment.DestinationAddress.PostalCode.Length > 0)
                {
                    xw.WriteElementString("PostalCode", shipment.DestinationAddress.PostalCode);
                }
                else
                {
                    if (shipment.DestinationAddress.City.Length > 0)
                    {
                        xw.WriteElementString("City", shipment.DestinationAddress.City);
                    }
                }

                if (shipment.DestinationAddress.RegionData != null)
                {
                    xw.WriteElementString("StateProvinceCode", shipment.DestinationAddress.RegionData.Abbreviation);
                }

                if (shipment.DestinationAddress.CountryData.Bvin.Length > 0)
                {
                    xw.WriteElementString("CountryCode", shipment.DestinationAddress.CountryData.IsoCode);
                }

                if (GlobalSettings.ForceResidential)
                {
                    xw.WriteElementString("ResidentialAddress", string.Empty);
                }

                xw.WriteEndElement();
                xw.WriteEndElement();

                var ignoreDimensions = GlobalSettings.IgnoreDimensions;

                // Optimize Packages for Weight
                var optimizedPackages = OptimizeSingleGroup(shipment);

                foreach (var p in optimizedPackages)
                {
                    WriteSingleUPSPackage(ref xw, p, ignoreDimensions);
                }

                if (Settings.NegotiatedRates)
                {
                    xw.WriteStartElement("RateInformation");
                    xw.WriteElementString("NegotiatedRatesIndicator", string.Empty);
                    xw.WriteEndElement();
                }

                xw.WriteEndElement();
                // End Shipment
                //--------------------------------------------

                xw.WriteEndElement();
                // End Agreement Request
                //--------------------------------------------

                xw.Flush();
                xw.Close();
            }
            catch (Exception ex)
            {
                _Logger.LogException(ex);
            }

            sXML = strWriter.GetStringBuilder().ToString();

            return(sXML);
        }
        // Gets all available rates regardless of settings
        private List <IShippingRate> GetAllShippingRatesForShipment(IShipment shipment)
        {
            var rates     = new List <IShippingRate>();
            var hasErrors = false;

            try
            {
                var sErrorMessage = string.Empty;
                var sErrorCode    = string.Empty;

                var sURL = string.Concat(UPSLIVESERVER, "Rate");

                // Build XML
                var settings = new UpsSettings
                {
                    UserID    = GlobalSettings.Username,
                    Password  = GlobalSettings.Password,
                    ServerUrl = UPSLIVESERVER,
                    License   = GlobalSettings.LicenseNumber
                };

                var sXML = string.Empty;

                sXML  = XmlTools.BuildAccessKey(settings);
                sXML += "\n";

                sXML += BuildUPSRateRequestForShipment(shipment, settings);

                var sResponse = string.Empty;
                sResponse = XmlTools.ReadHtmlPage_POST(sURL, sXML);

                XmlDocument xDoc;
                XmlNodeList NodeList;
                var         sStatusCode = "-1";

                try
                {
                    xDoc = new XmlDocument();
                    xDoc.LoadXml(sResponse);

                    if (xDoc.DocumentElement.Name == "RatingServiceSelectionResponse")
                    {
                        XmlNode n;
                        var     i = 0;
                        XmlNode nTag;

                        NodeList = xDoc.GetElementsByTagName("RatingServiceSelectionResponse");
                        n        = NodeList.Item(0);
                        for (i = 0; i <= n.ChildNodes.Count - 1; i++)
                        {
                            nTag = n.ChildNodes.Item(i);
                            switch (nTag.Name)
                            {
                            case "Response":
                                var     iRes = 0;
                                XmlNode nRes;
                                for (iRes = 0; iRes <= nTag.ChildNodes.Count - 1; iRes++)
                                {
                                    nRes = nTag.ChildNodes[iRes];
                                    switch (nRes.Name)
                                    {
                                    case "ResponseStatusCode":
                                        sStatusCode = nRes.FirstChild.Value;
                                        break;

                                    case "ResponseStatusDescription":
                                        // Not Used
                                        break;

                                    case "Error":
                                        var     iErr = 0;
                                        XmlNode nErr;
                                        for (iErr = 0; iErr <= nRes.ChildNodes.Count - 1; iErr++)
                                        {
                                            nErr = nRes.ChildNodes[iErr];
                                            switch (nErr.Name)
                                            {
                                            case "ErrorCode":
                                                sErrorCode = nErr.FirstChild.Value;
                                                break;

                                            case "ErrorDescription":
                                                sErrorMessage = nErr.FirstChild.Value;
                                                break;

                                            case "ErrorSeverity":
                                                // Not Used
                                                break;
                                            }
                                        }
                                        break;
                                    }
                                }
                                break;

                            case "RatedShipment":

                                var     iRated = 0;
                                XmlNode nRated;

                                var sPostage      = string.Empty;
                                var sCurrencyCode = string.Empty;
                                var sCode         = string.Empty;
                                var sDescription  = string.Empty;

                                for (iRated = 0; iRated <= nTag.ChildNodes.Count - 1; iRated++)
                                {
                                    nRated = nTag.ChildNodes[iRated];
                                    switch (nRated.Name)
                                    {
                                    case "Service":
                                        var     iServices = 0;
                                        XmlNode nServices;
                                        for (iServices = 0;
                                             iServices <= nRated.ChildNodes.Count - 1;
                                             iServices++)
                                        {
                                            nServices = nRated.ChildNodes[iServices];
                                            switch (nServices.Name)
                                            {
                                            case "Code":
                                                sCode        = nServices.FirstChild.Value;
                                                sDescription = DecodeUpsServiceCode(sCode);
                                                break;

                                            case "Description":
                                                sDescription = nServices.FirstChild.Value;
                                                break;
                                            }
                                        }
                                        break;

                                    case "TotalCharges":
                                        var     iCharges = 0;
                                        XmlNode nCharges;
                                        for (iCharges = 0; iCharges <= nRated.ChildNodes.Count - 1; iCharges++)
                                        {
                                            nCharges = nRated.ChildNodes[iCharges];
                                            switch (nCharges.Name)
                                            {
                                            case "MonetaryValue":
                                                sPostage = nCharges.FirstChild.Value;
                                                break;

                                            case "CurrencyCode":
                                                sCurrencyCode = nCharges.FirstChild.Value;
                                                break;
                                            }
                                        }
                                        break;
                                    }
                                }

                                var dRate = -1m;

                                if (sPostage.Length > 0)
                                {
                                    dRate = decimal.Parse(sPostage, NumberStyles.Currency,
                                                          CultureInfo.InvariantCulture);
                                }
                                else
                                {
                                    var nop = new ShippingServiceMessage();
                                    nop.SetInfo(string.Empty, "No UPS Postage Found");
                                    _Messages.Add(nop);
                                    hasErrors = true;
                                }

                                if (dRate >= 0)
                                {
                                    var r = new ShippingRate
                                    {
                                        DisplayName   = sDescription,
                                        EstimatedCost = dRate,
                                        ServiceCodes  = sCode,
                                        ServiceId     = Id
                                    };
                                    rates.Add(r);
                                }

                                if (GlobalSettings.DiagnosticsMode)
                                {
                                    var msg = new ShippingServiceMessage();

                                    msg.SetDiagnostics("UPS Rates Found",
                                                       string.Concat("StatusCode = ", sStatusCode, ", Postage = ", sPostage,
                                                                     ", Errors = ", sErrorMessage, ", Rate = ", dRate));

                                    _Messages.Add(msg);
                                }

                                break;
                            }
                        }
                    }
                    else
                    {
                        hasErrors     = true;
                        sErrorMessage = "Couldn't find valid XML response from server.";
                    }
                }
                catch (Exception Exx)
                {
                    _Logger.LogException(Exx);

                    var mex = new ShippingServiceMessage();

                    mex.SetError("Exception", string.Concat(Exx.Message, " | ", Exx.Source));

                    _Messages.Add(mex);

                    return(rates);
                }

                if (sStatusCode != "1")
                {
                    hasErrors = true;
                }
            }

            catch (Exception ex)
            {
                _Logger.LogException(ex);

                var m = new ShippingServiceMessage();

                m.SetError("Exception", string.Concat(ex.Message, " | ", ex.StackTrace));

                _Messages.Add(m);
            }

            if (hasErrors)
            {
                rates = new List <IShippingRate>();
            }

            return(rates);
        }