Exemple #1
0
        static public void Send(Order order, String FromEMailAddress, String MailServer, Customer ViewingCustomer)
        {
            // change in v6.1, the Dispatch_ToPhoneNumber must now be the full cell message address (e.g. [email protected]) or whatever
            // is needed. You can also dispatch to multiple cells by separating them with a comma.
            String SMSTo = AppLogic.AppConfig("Dispatch_ToPhoneNumber");

            if (SMSTo.Length != 0)
            {
                Decimal OrderThreshold = System.Decimal.Zero;
                if (AppLogic.AppConfig("Dispatch_OrderThreshold").Length != 0)
                {
                    try
                    {
                        String s = AppLogic.AppConfig("Dispatch_OrderThreshold").Replace("$", "");                                // strip the $ out if present
                        OrderThreshold = Localization.ParseUSDecimal(s);
                    }
                    catch {}
                }
                if (order.Total(true) >= OrderThreshold)
                {
                    try
                    {
                        SMSTo = SMSTo.Replace(";", ",");
                        String SMSSubject = AppLogic.AppConfig("Dispatch_SiteName");
                        if (SMSSubject.Length != 0)
                        {
                            SMSSubject = AppLogic.GetString("sms.cs.1", 1, Localization.GetDefaultLocale());
                        }
                        String PackageName = AppLogic.AppConfig("XmlPackage.NewOrderAdminSMSNotification");
                        if (PackageName.Length != 0)
                        {
                            String SMSBody = AppLogic.RunXmlPackage(PackageName, null, null, order.SkinID, String.Empty, "OrderNumber=" + order.OrderNumber.ToString(), false, false);
                            if (SMSBody.Length > AppLogic.AppConfigUSInt("Dispatch_MAX_SMS_MSG_LENGTH"))
                            {
                                SMSBody = SMSBody.Substring(0, AppLogic.AppConfigUSInt("Dispatch_MAX_SMS_MSG_LENGTH"));
                            }
                            string   s    = String.Empty;
                            string[] sAry = SMSTo.Split(',');
                            for (int i = 0; i < sAry.Length; i++)
                            {
                                String s2 = sAry[i].Trim();
                                if (s2.Length != 0)
                                {
                                    AppLogic.SendMail(SMSSubject, SMSBody, false, FromEMailAddress, FromEMailAddress, s2, s2, "", MailServer);
                                }
                            }
                        }
                    }
                    catch {}
                }
            }
        }
Exemple #2
0
 /// <summary>
 /// The QueryString of the request
 /// </summary>
 /// <param name="key">QueryString key</param>
 /// <param name="native">Parse native or parse based on culture</param>
 /// <returns>decimal</returns>
 public decimal DecimalValue(string key, ParseType parse)
 {
     if (this[key] == null)
     {
         return(0.0M);
     }
     else
     {
         return(parse == ParseType.Native ?
                Localization.ParseNativeDecimal(this[key].ToString()) :
                Localization.ParseUSDecimal(this[key].ToString()));
     }
 }
Exemple #3
0
        static public void Send(Order order, String FromEMailAddress, String MailServer, Customer ViewingCustomer)
        {
            // change in v6.1, the Dispatch_ToPhoneNumber must now be the full cell message address (e.g. [email protected]) or whatever
            // is needed. You can also dispatch to multiple cells by separating them with a comma.
            String SMSTo = AppLogic.AppConfig("Dispatch_ToPhoneNumber");

            if (SMSTo.Length != 0)
            {
                Decimal OrderThreshold = System.Decimal.Zero;
                if (AppLogic.AppConfig("Dispatch_OrderThreshold").Length != 0)
                {
                    try
                    {
                        String s = AppLogic.AppConfig("Dispatch_OrderThreshold").Replace("$", "");                         // strip the $ out if present
                        OrderThreshold = Localization.ParseUSDecimal(s);
                    }
                    catch { }
                }
                if (order.Total() >= OrderThreshold)
                {
                    try
                    {
                        SMSTo = SMSTo.Replace(";", ",");
                        String SMSSubject = AppLogic.AppConfig("Dispatch_SiteName");
                        if (SMSSubject.Length != 0)
                        {
                            SMSSubject = "NEW ORDER";
                        }
                        String PackageName = "notification.smsneworder.xml.config";
                        if (PackageName.Length != 0)
                        {
                            String SMSBody = AppLogic.RunXmlPackage(PackageName, null, null, order.SkinID, String.Empty, "OrderNumber=" + order.OrderNumber.ToString(), false, false);
                            if (SMSBody.Length > AppLogic.AppConfigUSInt("Dispatch_MAX_SMS_MSG_LENGTH"))
                            {
                                SMSBody = SMSBody.Substring(0, AppLogic.AppConfigUSInt("Dispatch_MAX_SMS_MSG_LENGTH"));
                            }
                            string[] sAry = SMSTo.Split(',');
                            for (int i = 0; i < sAry.Length; i++)
                            {
                                String s2 = sAry[i].Trim();
                                if (s2.Length != 0)
                                {
                                    AppLogic.SendMail(subject: SMSSubject, body: SMSBody, useHtml: false, fromAddress: FromEMailAddress, fromName: FromEMailAddress, toAddress: s2, toName: s2, bccAddresses: "", replyToAddress: FromEMailAddress);
                                }
                            }
                        }
                    }
                    catch { }
                }
            }
        }
        private void CanadaPostGetRates(Shipments AllShipments, out string RTShipRequest, out string RTShipResponse, decimal ExtraFee, Decimal MarkupPercent, decimal ShippingTaxRate, ref ShippingMethodCollection shippingMethods)
        {
            RTShipRequest  = String.Empty;
            RTShipResponse = String.Empty;

            if (!AppConfigProvider.GetAppConfigValue("Localization.StoreCurrency", StoreId, true).Trim().Equals("cad", StringComparison.InvariantCultureIgnoreCase))
            {
                RTShipResponse += "Localization.StoreCurrency == CAD required to use Canada Post as a carrier.";
                return;
            }

            if (!AppConfigProvider.GetAppConfigValue("Localization.WeightUnits", StoreId, true).Equals("kg", StringComparison.InvariantCultureIgnoreCase))
            {
                RTShipResponse += "Localization.WeightUnits == kg required to use Canada Post as a carrier.";
                return;
            }

            foreach (Packages Shipment in AllShipments)
            {
                HasFreeItems    = false;
                PackageQuantity = 1;

                if (Shipment.Weight > AppConfigProvider.GetAppConfigValueUsCulture <decimal>("RTShipping.CanadaPost.MaxWeight", StoreId, true))
                {
                    shippingMethods.ErrorMsg = string.Format("{0} {1}", CanadaPostName, AppConfigProvider.GetAppConfigValue("RTShipping.CallForShippingPrompt", StoreId, true));
                    return;
                }

                // create a rate request
                CanadaPost.ratesAndServicesRequest rateRequest = new CanadaPost.ratesAndServicesRequest();
                rateRequest.merchantCPCID = AppConfigProvider.GetAppConfigValue("RTShipping.CanadaPost.MerchantID", StoreId, true);                  // Canada Post merchant credentials

                // ship-to address
                rateRequest.city        = Shipment.DestinationCity;
                rateRequest.provOrState = Shipment.DestinationStateProvince;
                rateRequest.country     = Shipment.DestinationCountryCode;
                rateRequest.postalCode  = Shipment.DestinationZipPostalCode;

                // create one lineitem request per package in shipment
                rateRequest.lineItems.item = new CanadaPost.item[Shipment.Count];

                int packageIndex = 0;
                foreach (Package p in Shipment)
                {
                    if (p.IsFreeShipping)
                    {
                        HasFreeItems = true;
                    }
                    if (p.IsShipSeparately)
                    {
                        PackageQuantity = p.Quantity;
                    }

                    // shipment details
                    rateRequest.itemsPrice = p.InsuredValue.ToString("#####.00");
                    rateRequest.lineItems.item[packageIndex]        = new CanadaPost.item();
                    rateRequest.lineItems.item[packageIndex].weight = p.Weight.ToString("####.0");

                    // dimensions
                    if (p.Length + p.Width + p.Height == 0)                     // if package has no dimensions, we use default
                    {
                        string dimensions = AppConfigProvider.GetAppConfigValue("RTShipping.CanadaPost.DefaultPackageSize", StoreId, true);
                        p.Width  = Convert.ToDecimal(dimensions.Split('x')[0].Trim());
                        p.Height = Convert.ToDecimal(dimensions.Split('x')[1].Trim());
                        p.Length = Convert.ToDecimal(dimensions.Split('x')[2].Trim());
                    }
                    rateRequest.lineItems.item[packageIndex].length = p.Length.ToString("###.0");
                    rateRequest.lineItems.item[packageIndex].width  = p.Width.ToString("###.0");
                    rateRequest.lineItems.item[packageIndex].height = p.Height.ToString("###.0");

                    packageIndex++;
                }

                // initialize eParcel request
                CanadaPost.eparcel request = new CanadaPost.eparcel();

                // choose language for reply text
                request.language = AppConfigProvider.GetAppConfigValue("RTShipping.CanadaPost.Language", StoreId, true).Trim();
                if (request.language.Equals("auto", StringComparison.InvariantCultureIgnoreCase))                 // set the language based on the customers locale
                {
                    Customer ThisCustomer = System.Web.HttpContext.Current.GetCustomer();
                    if (ThisCustomer.LocaleSetting.Trim().StartsWith("fr", StringComparison.InvariantCultureIgnoreCase))
                    {
                        request.language = "fr";
                    }
                    else
                    {
                        request.language = "en";
                    }
                }

                request.Items    = new CanadaPost.ratesAndServicesRequest[1];
                request.Items[0] = rateRequest;

                // serialize eParcel request class
                XmlSerializer serRequest = new XmlSerializer(typeof(CanadaPost.eparcel));
                StringWriter  swRequest  = new StringWriter();

                serRequest.Serialize(swRequest, request);
                string req = swRequest.ToString().Replace(@" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""", "");

                // open a TCP socket with Canada Post server
                Socket     socCanadaPost = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint remoteEndPoint;

                socCanadaPost.ReceiveTimeout = 10000;                 // milliseconds to wait for a response

                try
                {
                    remoteEndPoint = new IPEndPoint(Dns.GetHostAddresses(AppConfigProvider.GetAppConfigValue("RTShipping.CanadaPost.Server", StoreId, true))[0],
                                                    AppLogic.AppConfigNativeInt("RTShipping.CanadaPost.ServerPort"));
                    socCanadaPost.Connect(remoteEndPoint);
                }
                catch (SocketException e)
                {
                    RTShipResponse += "Tried to reach Canada Post Server (" + AppConfigProvider.GetAppConfigValue("RTShipping.CanadaPost.Server", StoreId, true) +
                                      ":" + AppLogic.AppConfigNativeInt("RTShipping.CanadaPost.ServerPort") + "): " + e.Message;
                    return;
                }


                // send request to Canada Post
                byte[] data = System.Text.Encoding.ASCII.GetBytes(req);
                socCanadaPost.Send(data);

                //receive response from Canada Post
                string resp   = String.Empty;
                byte[] buffer = new byte[8192];
                int    iRx    = 0;

                while (!resp.Contains("<!--END_OF_EPARCEL-->"))
                {
                    try
                    {
                        iRx += socCanadaPost.Receive(buffer, iRx, 8192 - iRx, SocketFlags.None);
                    }
                    catch (SocketException e)
                    {
                        if (e.SocketErrorCode == SocketError.TimedOut)
                        {
                            break;
                        }
                        else
                        {
                            throw e;
                        }
                    }
                    resp = new string((System.Text.Encoding.UTF8.GetChars(buffer, 0, iRx)));                      // decode byte array to string
                }

                // close socket
                socCanadaPost.Close();

                // create an eParcel response class
                CanadaPost.eparcel response = new CanadaPost.eparcel();

                // deserialize the xml response into the eParcel response
                XmlSerializer serResponse = new XmlSerializer(typeof(CanadaPost.eparcel));
                StringReader  srResponse  = new StringReader(resp);

                try
                {
                    response = (CanadaPost.eparcel)serResponse.Deserialize(srResponse);
                }
                catch (InvalidOperationException e)                 // invalid xml, or no reply received from Canada Post
                {
                    RTShipResponse += "Canada Post error: Could not parse response from Canada Post server: " + e.Message
                                      + " Response received: " + resp;
                    return;
                }

                srResponse.Close();

                // Check the response object for Faults
                if (response.Items[0] is CanadaPost.error)
                {
                    CanadaPost.error respError = (CanadaPost.error)response.Items[0];
                    RTShipResponse += respError.statusMessage[0];
                    return;
                }

                // Check the response object for Ratings
                if (!(response.Items[0] is CanadaPost.ratesAndServicesResponse))
                {
                    RTShipResponse += "Canada Post Error: No rating responses returned from Canada Post";
                    return;
                }

                // no faults, so extract rate information
                CanadaPost.ratesAndServicesResponse ratesResp = (CanadaPost.ratesAndServicesResponse)response.Items[0];
                foreach (CanadaPost.product product in ratesResp.product)
                {
                    decimal total = Localization.ParseUSDecimal(product.rate);

                    // ignore zero-cost methods, and methods not allowed
                    if (total != 0 && ShippingMethodIsAllowed(product.name, CanadaPostName))
                    {
                        total = total * PackageQuantity * (1.00M + (MarkupPercent / 100.0M));

                        decimal vat = Decimal.Round(total * ShippingTaxRate);

                        if (!shippingMethods.MethodExists(product.name))
                        {
                            var s_method = new ShippingMethod();
                            s_method.Carrier    = CanadaPostName;
                            s_method.Name       = product.name;
                            s_method.Freight    = total;
                            s_method.VatRate    = vat;
                            s_method.IsRealTime = true;
                            s_method.Id         = Shipping.GetShippingMethodID(s_method.Name);

                            if (HasFreeItems)
                            {
                                s_method.FreeItemsRate = total;
                            }

                            shippingMethods.Add(s_method);
                        }
                        else
                        {
                            int IndexOf  = shippingMethods.GetIndex(product.name);
                            var s_method = shippingMethods[IndexOf];
                            s_method.Freight += total;
                            s_method.VatRate += vat;

                            if (HasFreeItems)
                            {
                                s_method.FreeItemsRate += total;
                            }

                            shippingMethods[IndexOf] = s_method;
                        }
                    }
                }
                RTShipRequest  += req;                // stash request & response for this shipment
                RTShipResponse += resp;
            }

            // Handling fee should only be added per shipping address not per package
            // let's just compute it here after we've gone through all the packages.
            // Also, since we can't be sure about the ordering of the method call here
            // and that the collection SM includes shipping methods from all possible carriers
            // we'll need to filter out the methods per this carrier to avoid side effects on the main collection
            foreach (ShippingMethod shipMethod in shippingMethods.PerCarrier(CanadaPostName))
            {
                if (shipMethod.Freight != System.Decimal.Zero)                //Don't add the fee to free methods.
                {
                    shipMethod.Freight += ExtraFee;
                }
            }
        }
Exemple #5
0
        public static decimal XmlAttributeUSDecimal(XmlNode node, String AttributeName)
        {
            String tmpS = XmlAttribute(node, AttributeName);

            return(Localization.ParseUSDecimal(tmpS));
        }
        public static decimal FormUSDecimal(String paramName)
        {
            String tmpS = FormCanBeDangerousContent(paramName);

            return(Localization.ParseUSDecimal(tmpS));
        }
Exemple #7
0
        public Decimal SessionUSDecimal(String paramName)
        {
            String tmpS = Session(paramName);

            return(Localization.ParseUSDecimal(tmpS));
        }
Exemple #8
0
        /// <summary>
        /// Get shipping rates from DHL for International shipments
        /// </summary>
        private void DHLIntlGetRates(Shipments allShipments, out string rtShipRequest, out string rtShipResponse, decimal ExtraFee, decimal markupPercent, decimal shippingTaxRate, ref ShippingMethodCollection shippingMethods)
        {
            rtShipRequest  = String.Empty;
            rtShipResponse = String.Empty;

            // is weight within shippable limit?
            if (ShipmentWeight > AppLogic.AppConfigUSDecimal("RTShipping.DHLIntl.MaxWeight"))
            {
                shippingMethods.ErrorMsg = "DHL " + AppLogic.AppConfig("RTShipping.CallForShippingPrompt");
                return;
            }

            // retrieve correct DHL Server URL
            string dhlServer;

            if (AppLogic.AppConfigBool("RTShipping.UseTestRates"))
            {
                dhlServer = AppLogic.AppConfig("RTShipping.DHL.TestServer");
            }
            else
            {
                dhlServer = AppLogic.AppConfig("RTShipping.DHL.Server");
            }

            // calculate legal ship date
            DateTime shipDate = DateTime.Now.AddDays(AppLogic.AppConfigUSDouble("RTShipping.DHL.ShipInDays"));

            if (shipDate.DayOfWeek == DayOfWeek.Saturday)
            {
                shipDate = shipDate.AddDays(2);
            }
            if (shipDate.DayOfWeek == DayOfWeek.Sunday)
            {
                shipDate = shipDate.AddDays(1);
            }

            // error 4112 is tripped by asking for a rate quote on a Sunday or a Holiday
            bool error4112 = false;

            do
            {
                if (error4112)
                {
                    error4112 = false;
                    shipDate  = shipDate.AddDays(1);
                }

                foreach (Packages shipment in allShipments)
                {
                    HasFreeItems    = false;
                    PackageQuantity = 1;

                    foreach (Package p in shipment)
                    {
                        if (p.IsFreeShipping)
                        {
                            HasFreeItems = true;
                        }
                        if (p.IsShipSeparately)
                        {
                            PackageQuantity = p.Quantity;
                        }

                        // initialize rate requests
                        dhl.InternationalRateRequest rateRequests = new dhl.InternationalRateRequest();
                        rateRequests.Requestor.ID       = AppLogic.AppConfig("RTShipping.DHL.APISystemID");
                        rateRequests.Requestor.Password = AppLogic.AppConfig("RTShipping.DHL.APISystemPassword");

                        string dhlServices = AppLogic.AppConfig("RTShipping.DHLIntl.Services");

                        // create an array of individual requests, one for each service
                        rateRequests.Shipment = new dhl.InternationalRequest[dhlServices.Split(',').Length];

                        // populate the array
                        int serviceIndex = 0;
                        foreach (string service in dhlServices.Split(','))
                        {
                            rateRequests.Shipment[serviceIndex] = new dhl.InternationalRequest();
                            dhl.InternationalRequest request = rateRequests.Shipment[serviceIndex];

                            // DHL rating API credentials
                            request.ShippingCredentials.ShippingKey = AppLogic.AppConfig("RTShipping.DHLIntl.ShippingKey");
                            request.ShippingCredentials.AccountNbr  = AppLogic.AppConfig("RTShipping.DHL.AccountNumber");

                            // shipment details
                            request.ShipmentDetail.ShipDate          = shipDate.ToString("yyyy-MM-dd");
                            request.ShipmentDetail.ShipmentType.Code = AppLogic.AppConfig("RTShipping.DHLIntl.Packaging").ToUpperInvariant();

                            // used to allow 'O' (Other) packaging types, which are now 'P' types
                            if (request.ShipmentDetail.ShipmentType.Code == "O")
                            {
                                request.ShipmentDetail.ShipmentType.Code = "P";
                            }

                            // package weight
                            if (request.ShipmentDetail.ShipmentType.Code == "L")
                            {
                                request.ShipmentDetail.Weight = p.Weight.ToString("#0.0");
                            }
                            else
                            {
                                request.ShipmentDetail.Weight = Math.Ceiling(p.Weight).ToString("##0");
                            }

                            request.ShipmentDetail.ContentDesc = "ContentDesc";

                            // billing details
                            request.Billing.Party.Code = AppLogic.AppConfig("RTShipping.DHLIntl.BillingParty").ToUpperInvariant();
                            if (request.Billing.Party.Code != "S")
                            {
                                request.Billing.AccountNbr = AppLogic.AppConfig("RTShipping.DHLIntl.BillingAccountNbr").ToUpperInvariant();
                            }

                            request.Billing.DutyPaymentType = AppLogic.AppConfig("RTShipping.DHLIntl.DutyPayment").ToUpperInvariant();
                            if (request.Billing.DutyPaymentType == "3")
                            {
                                request.Billing.DutyPaymentAccountNbr = AppLogic.AppConfig("RTShipping.DHLIntl.DutyPaymentAccountNbr").ToUpperInvariant();
                            }

                            // import duty declaration
                            request.Dutiable.DutiableFlag = AppLogic.AppConfig("RTShipping.DHLIntl.Dutiable").ToUpperInvariant();
                            request.Dutiable.CustomsValue = p.InsuredValue.ToString("######");

                            // overrides
                            string overrideCodes = AppLogic.AppConfig("RTShipping.DHLIntl.Overrides");
                            if (overrideCodes.Length > 0)
                            {
                                request.ShipmentProcessingInstructions.Overrides = new dhl.Override[overrideCodes.Split(',').Length];

                                int overrideIndex = 0;
                                foreach (string overrideCode in overrideCodes.Split(','))
                                {
                                    request.ShipmentProcessingInstructions.Overrides[overrideIndex]      = new dhl.Override();
                                    request.ShipmentProcessingInstructions.Overrides[overrideIndex].Code = overrideCode;

                                    overrideIndex++;
                                }
                            }

                            // ship-to address
                            request.Receiver.Address.Street = "Street";
                            request.Receiver.Address.City   = shipment.DestinationCity;
                            if (shipment.DestinationCountryCode.Equals("ca", StringComparison.OrdinalIgnoreCase) ||
                                shipment.DestinationCountryCode.Equals("us", StringComparison.OrdinalIgnoreCase))
                            {
                                request.Receiver.Address.State = shipment.DestinationStateProvince;
                            }

                            request.Receiver.Address.Country    = shipment.DestinationCountryCode.ToUpperInvariant();
                            request.Receiver.Address.PostalCode = shipment.DestinationZipPostalCode.ToUpperInvariant();

                            // dimensions
                            if (p.Length + p.Width + p.Height != 0)
                            {
                                request.ShipmentDetail.Dimensions        = new dhl.Dimensions();
                                request.ShipmentDetail.Dimensions.Length = p.Length.ToString("###");
                                request.ShipmentDetail.Dimensions.Width  = p.Width.ToString("###");
                                request.ShipmentDetail.Dimensions.Height = p.Height.ToString("###");
                            }

                            // insurance
                            if (p.Insured && p.InsuredValue != 0)
                            {
                                request.ShipmentDetail.AdditionalProtection.Code  = "AP"; // additional protection
                                request.ShipmentDetail.AdditionalProtection.Value = p.InsuredValue.ToString("######");
                            }
                            else
                            {
                                request.ShipmentDetail.AdditionalProtection.Code  = "NR"; // not required
                                request.ShipmentDetail.AdditionalProtection.Value = "0";
                            }

                            // add the service code, and service name to the request
                            request.ShipmentDetail.Service.Code = service.Split(';')[0];
                            request.TransactionTrace            = service.Split(';')[1];

                            // add this individual service request to the rateRequests
                            rateRequests.Shipment[serviceIndex] = request;

                            serviceIndex++;
                        }

                        // serialize rateRequests into an xml string
                        XmlWriterSettings xwSettings = new XmlWriterSettings();
                        xwSettings.OmitXmlDeclaration = true;

                        XmlSerializer serRequest = new XmlSerializer(rateRequests.GetType());
                        StringWriter  swRequest  = new StringWriter();
                        XmlWriter     xwRequest  = XmlWriter.Create(swRequest, xwSettings);
                        serRequest.Serialize(xwRequest, rateRequests);

                        string req = swRequest.ToString();

                        // Send xml rate request to DHL server
                        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(dhlServer);
                        webRequest.Method = "POST";

                        webRequest.ProtocolVersion = HttpVersion.Version11;
                        webRequest.ContentType     = "application/xml; charset=UTF-8";
                        webRequest.Accept          = "application/xml; charset=UTF-8";

                        // Transmit the request to DHL
                        byte[] data = System.Text.Encoding.ASCII.GetBytes(req);
                        webRequest.ContentLength = data.Length;
                        Stream requestStream;

                        try
                        {
                            requestStream = webRequest.GetRequestStream();
                        }
                        catch (WebException e)
                        {
                            // could not connect to DHL endpoint
                            rtShipResponse += "Tried to reach DHL Server (" + dhlServer + "): " + e.Message;
                            return;
                        }

                        requestStream.Write(data, 0, data.Length);
                        requestStream.Close();

                        // get the response from DHL
                        WebResponse webResponse = null;
                        string      resp;
                        try
                        {
                            webResponse = webRequest.GetResponse();
                        }
                        catch (WebException e)
                        {
                            // could not receive a response from DHL endpoint
                            rtShipResponse += "No response from DHL Server (" + dhlServer + "): " + e.Message;
                            return;
                        }

                        using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
                        {
                            resp = sr.ReadToEnd();
                            sr.Close();
                        }

                        webResponse.Close();

                        // deserialize the xml response into an InternationalRateResponse object
                        dhl.InternationalRateResponse response = new dhl.InternationalRateResponse();
                        XmlSerializer serResponse = new XmlSerializer(typeof(dhl.InternationalRateResponse));
                        StringReader  srResponse  = new StringReader(resp);

                        try
                        {
                            response = (dhl.InternationalRateResponse)serResponse.Deserialize(srResponse);
                        }
                        catch (InvalidOperationException e)
                        {
                            // invalid xml, or no reply received from DHL
                            rtShipResponse += "Could not parse response from DHL server: " + e.Message + " Response received: " + resp;
                            return;
                        }

                        srResponse.Close();

                        // Check the response object for Ratings
                        if (response.Shipment == null)
                        {
                            rtShipResponse += "DHL Error: No rating responses returned from DHL.";
                            return;
                        }

                        // Check the response object for Faults
                        if (response.Shipment[0].Faults != null)
                        {
                            if (response.Shipment[0].Faults[0].Code == "4112")
                            {
                                error4112 = true;
                            }
                            else
                            {
                                rtShipResponse += "DHL Error: " + response.Shipment[0].Faults[0].Desc;
                                return;
                            }
                        }

                        // one response for each rate request
                        foreach (dhl.Response rateResponse in response.Shipment)
                        {
                            // check for a rate estimate
                            if (rateResponse.EstimateDetail == null)
                            {
                                break;
                            }

                            // we have a good estimate
                            decimal total = Localization.ParseUSDecimal(rateResponse.EstimateDetail.RateEstimate.TotalChargeEstimate);

                            // ignore zero-cost methods, and methods not allowed
                            if ((total == 0 && AppLogic.AppConfigBool("FilterOutShippingMethodsThatHave0Cost")) ||
                                !ShippingMethodIsAllowed(rateResponse.TransactionTrace, string.Empty))
                            {
                                break;
                            }

                            total = total * PackageQuantity * (1.00M + (markupPercent / 100.0M));
                            decimal vat = Decimal.Round(total * shippingTaxRate);

                            if (!shippingMethods.MethodExists(rateResponse.TransactionTrace))
                            {
                                ShippingMethod s_method = new ShippingMethod();
                                s_method.Carrier    = "DHL";
                                s_method.Name       = rateResponse.TransactionTrace;
                                s_method.Freight    = total;
                                s_method.VatRate    = vat;
                                s_method.IsRealTime = true;
                                s_method.Id         = Shipping.GetShippingMethodID(s_method.Name);

                                if (HasFreeItems)
                                {
                                    s_method.FreeItemsRate = total;
                                }

                                shippingMethods.Add(s_method);
                            }
                            else
                            {
                                int            indexOf  = shippingMethods.GetIndex(rateResponse.TransactionTrace);
                                ShippingMethod s_method = shippingMethods[indexOf];

                                s_method.Freight += total;
                                s_method.VatRate += vat;

                                if (HasFreeItems)
                                {
                                    s_method.FreeItemsRate += total;
                                }

                                shippingMethods[indexOf] = s_method;
                            }
                        }

                        rtShipRequest  += req;
                        rtShipResponse += resp;
                    }
                }
            }while (error4112 == true);

            // Handling fee should only be added per shipping address not per package
            // let's just compute it here after we've gone through all the packages.
            // Also, since we can't be sure about the ordering of the method call here
            // and that the collection SM includes shipping methods from all possible carriers
            // we'll need to filter out the methods per this carrier to avoid side effects on the main collection
            foreach (ShippingMethod shipMethod in shippingMethods.PerCarrier("DHL"))
            {
                if (shipMethod.Freight != System.Decimal.Zero) //Don't add the fee to free methods.
                {
                    shipMethod.Freight += ExtraFee;
                }
            }
        }
Exemple #9
0
        private void FedExGetRates(Packages Shipment, out string RTShipRequest, out string RTShipResponse, decimal ExtraFee, Decimal MarkupPercent, decimal ShipmentValue, decimal ShippingTaxRate)     // Retrieves FedEx rates
        {
            RTShipRequest  = string.Empty;
            RTShipResponse = string.Empty;

            Hashtable   htRates = new Hashtable();
            RateRequest request = CreateRateRequest(Shipment);
            RateService service = new RateService(); // Initialize the service

            service.Url = this.FedexServer;


            try
            {
                // Call the web service passing in a RateRequest and returning a RateReply
                RateReply reply = service.getRates(request);

                if (reply.HighestSeverity == NotificationSeverityType.SUCCESS || reply.HighestSeverity == NotificationSeverityType.NOTE || reply.HighestSeverity == NotificationSeverityType.WARNING) // check if the call was successful
                {
                    //create list of available services

                    for (int i = 0; i < reply.RateReplyDetails.Length; i++)
                    {
                        RateReplyDetail     rateReplyDetail     = reply.RateReplyDetails[i];
                        RatedShipmentDetail ratedShipmentDetail = rateReplyDetail.RatedShipmentDetails[1];

                        decimal totalCharges = ratedShipmentDetail.ShipmentRateDetail.TotalNetCharge.Amount;
                        if (MarkupPercent != System.Decimal.Zero)
                        {
                            totalCharges = Decimal.Round(totalCharges * (1.00M + (MarkupPercent / 100.0M)), 2, MidpointRounding.AwayFromZero);
                        }

                        decimal vat      = Decimal.Round(totalCharges * ShippingTaxRate, 2, MidpointRounding.AwayFromZero);
                        string  rateName = rateReplyDetail.ServiceType.ToString();
                        if (htRates.ContainsKey(rateName))
                        {
                            // Get the sum of the rate(s)
                            decimal myTempCharge = Localization.ParseUSDecimal(htRates[rateName].ToString().Split('|')[0]);
                            totalCharges += myTempCharge;
                            vat          += Localization.ParseUSDecimal(htRates[rateName].ToString().Split('|')[1]);

                            // Remove the old value & add the new
                            htRates.Remove(rateName);
                        }

                        // Temporarily add rate to hash table
                        htRates.Add(rateName, Localization.CurrencyStringForDBWithoutExchangeRate(totalCharges) + "|" + Localization.CurrencyStringForDBWithoutExchangeRate(vat));
                    }
                }
                else
                {
                    ratesText.Add("Error: Call Not Successful");
                    ratesValues.Add("Error: Call Not Successful");
                }

                RTShipRequest  = Serialize(request);
                RTShipResponse = Serialize(reply);
            }
            catch (SoapException e)
            {
                ratesText.Add("Error: " + e.Detail.InnerText);
                ratesValues.Add("Error: " + e.Detail.InnerText);
            }
            catch (Exception e)
            {
                ratesText.Add("Error: " + e.Message);
                ratesValues.Add("Error: " + e.Message);
            }



            // Add rates from hastable into array(s)
            IDictionaryEnumerator myEnumerator = htRates.GetEnumerator();

            while (myEnumerator.MoveNext())
            {
                Decimal tmp_rate = Localization.ParseUSDecimal(myEnumerator.Value.ToString().Substring(0, myEnumerator.Value.ToString().IndexOf("|"))) + ExtraFee;
                Decimal tmp_vat  = Localization.ParseUSDecimal(myEnumerator.Value.ToString().Substring(myEnumerator.Value.ToString().LastIndexOf("|") + 1));
                String  rateText = tmp_rate.ToString() + "|" + tmp_vat.ToString();
                ratesText.Add(myEnumerator.Key.ToString() + " $" + rateText);
                ratesValues.Add(myEnumerator.Key.ToString() + "|" + rateText);
            }
        }