예제 #1
0
        /// <summary>
        /// Get shipping services for a shipment
        /// </summary>
        /// <param name="mailingScenario">Input parameters</param>
        /// <param name="apiKey">The API key</param>
        /// <param name="isSandbox">Is sandbox (testing environment) used</param>
        /// <param name="errors">Errors</param>
        /// <returns>Shipping services</returns>
        public static pricequotes GetShippingRates(mailingscenario mailingScenario, string apiKey, bool isSandbox, out string errors)
        {
            var parameters = new StringBuilder();
            var xmlWriter  = XmlWriter.Create(parameters);

            xmlWriter.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");
            var serializerRequest = new XmlSerializer(typeof(mailingscenario));

            serializerRequest.Serialize(xmlWriter, mailingScenario);

            var method     = "POST";
            var acceptType = "application/vnd.cpc.ship.rate-v3+xml";
            var url        = string.Format("{0}/rs/ship/price", GetBaseUrl(isSandbox));
            var response   = Request(parameters.ToString(), apiKey, method, acceptType, url, out errors);

            if (response == null)
            {
                return(null);
            }

            try
            {
                using (var streamReader = new StreamReader(response.GetResponseStream()))
                {
                    var serializerResponse = new XmlSerializer(typeof(pricequotes));
                    return((pricequotes)serializerResponse.Deserialize(streamReader));
                }
            }
            catch (Exception e)
            {
                errors = e.Message;
                return(null);
            }
        }
예제 #2
0
        /// <summary>
        /// Get shipping services for a shipment
        /// </summary>
        /// <param name="mailingScenario">Input parameters</param>
        /// <param name="apiKey">The API key</param>
        /// <param name="isSandbox">Is sandbox (testing environment) used</param>
        /// <param name="errors">Errors</param>
        /// <returns>Shipping services</returns>
        public static pricequotes GetShippingRates(mailingscenario mailingScenario, string apiKey, bool isSandbox, out string errors)
        {
            var parameters = new StringBuilder();
            var xmlWriter = XmlWriter.Create(parameters);
            xmlWriter.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");
            var serializerRequest = new XmlSerializer(typeof(mailingscenario));
            serializerRequest.Serialize(xmlWriter, mailingScenario);

            var method = "POST";
            var acceptType = "application/vnd.cpc.ship.rate-v3+xml";
            var url = string.Format("{0}/rs/ship/price", GetBaseUrl(isSandbox));
            var response = Request(parameters.ToString(), apiKey, method, acceptType, url, out errors);
            if (response == null)
                return null;

            try
            {
                using (var streamReader = new StreamReader(response.GetResponseStream()))
                {
                    var serializerResponse = new XmlSerializer(typeof(pricequotes));
                    return (pricequotes)serializerResponse.Deserialize(streamReader);
                }
            }
            catch (Exception e)
            {
                errors = e.Message;
                return null;
            }
        }
예제 #3
0
        public pricequotes GetRate(string mailedBy)
        {
            ServicePointManager.SecurityProtocol = Tls12;

            // as provided in the email
            // we can also use AppConfig with config file and use credentials with that
            var username = "******";
            var password = "******";

            var url = "https://ct.soa-gw.canadapost.ca/rs/ship/price"; // REST URL (developer)

            var    method           = "POST";                          // HTTP Method
            String responseAsString = ".NET Framework " + Environment.Version.ToString() + "\r\n\r\n";

            // Create mailingScenario object to contain xml request
            mailingscenario mailingScenario = new mailingscenario();

            mailingScenario.parcelcharacteristics = new mailingscenarioParcelcharacteristics();
            mailingScenario.destination           = new mailingscenarioDestination();
            mailingscenarioDestinationDomestic destDom = new mailingscenarioDestinationDomestic();

            mailingScenario.destination.Item = destDom;

            // Populate mailingScenario object
            mailingScenario.customernumber = mailedBy;
            mailingScenario.parcelcharacteristics.weight = 1;
            mailingScenario.originpostalcode             = "K2B8J6";
            destDom.postalcode = "J0E1X0";
            try
            {
                // Serialize mailingScenario object to String
                StringBuilder mailingScenarioSb  = new StringBuilder();
                XmlWriter     mailingScenarioXml = XmlWriter.Create(mailingScenarioSb);
                mailingScenarioXml.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");
                XmlSerializer serializerRequest = new XmlSerializer(typeof(mailingscenario));
                serializerRequest.Serialize(mailingScenarioXml, mailingScenario);

                // Create REST Request
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = method;

                // Set Basic Authentication Header using username and password variables
                string auth = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password));
                request.Headers = new WebHeaderCollection();
                request.Headers.Add("Authorization", auth);

                // Write Post Data to Request
                UTF8Encoding encoding = new UTF8Encoding();
                byte[]       buffer   = encoding.GetBytes(mailingScenarioSb.ToString());
                request.ContentLength = buffer.Length;
                request.Headers.Add("Accept-Language", "en-CA");
                request.Accept      = "application/vnd.cpc.ship.rate-v4+xml";
                request.ContentType = "application/vnd.cpc.ship.rate-v4+xml";
                Stream PostData = request.GetRequestStream();
                PostData.Write(buffer, 0, buffer.Length);
                PostData.Close();

                // Execute REST Request
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                // Deserialize response to pricequotes object
                XmlSerializer serializer  = new XmlSerializer(typeof(pricequotes));
                TextReader    reader      = new StreamReader(response.GetResponseStream());
                pricequotes   priceQuotes = (pricequotes)serializer.Deserialize(reader);
                return(priceQuotes);
            }
            catch (WebException webEx)
            {
                // we can apply loggin here
                return(null);
            }
            catch (Exception ex)
            {
                // we can apply loggin here
                return(null);
            }
        }
        /// <summary>
        ///  Gets available shipping options
        /// </summary>
        /// <param name="getShippingOptionRequest">A request for getting shipping options</param>
        /// <returns>Represents a response of getting shipping rate options</returns>
        public GetShippingOptionResponse GetShippingOptions(GetShippingOptionRequest getShippingOptionRequest)
        {
            if (getShippingOptionRequest == null)
            {
                throw new ArgumentNullException("getShippingOptionRequest");
            }

            if (getShippingOptionRequest.Items == null)
            {
                return new GetShippingOptionResponse {
                           Errors = new List <string> {
                               "No shipment items"
                           }
                }
            }
            ;

            if (getShippingOptionRequest.ShippingAddress == null)
            {
                return new GetShippingOptionResponse {
                           Errors = new List <string> {
                               "Shipping address is not set"
                           }
                }
            }
            ;

            if (getShippingOptionRequest.ShippingAddress.Country == null)
            {
                return new GetShippingOptionResponse {
                           Errors = new List <string> {
                               "Shipping country is not set"
                           }
                }
            }
            ;

            if (string.IsNullOrEmpty(getShippingOptionRequest.ZipPostalCodeFrom))
            {
                return new GetShippingOptionResponse {
                           Errors = new List <string> {
                               "Origin postal code is not set"
                           }
                }
            }
            ;

            //get available services
            string errors;
            var    availableServices = CanadaPostHelper.GetServices(getShippingOptionRequest.ShippingAddress.Country.TwoLetterIsoCode,
                                                                    _canadaPostSettings.ApiKey, _canadaPostSettings.UseSandbox, out errors);

            if (availableServices == null)
            {
                return new GetShippingOptionResponse {
                           Errors = new List <string> {
                               errors
                           }
                }
            }
            ;

            //create object for the get rates requests
            var    result = new GetShippingOptionResponse();
            object destinationCountry;

            switch (getShippingOptionRequest.ShippingAddress.Country.TwoLetterIsoCode.ToLowerInvariant())
            {
            case "us":
                destinationCountry = new mailingscenarioDestinationUnitedstates
                {
                    zipcode = getShippingOptionRequest.ShippingAddress.ZipPostalCode
                };

                break;

            case "ca":
                destinationCountry = new mailingscenarioDestinationDomestic
                {
                    postalcode = getShippingOptionRequest.ShippingAddress.ZipPostalCode
                };
                break;

            default:
                destinationCountry = new mailingscenarioDestinationInternational
                {
                    countrycode = getShippingOptionRequest.ShippingAddress.Country.TwoLetterIsoCode
                };
                break;
            }

            var mailingScenario = new mailingscenario
            {
                customernumber   = _canadaPostSettings.CustomerNumber,
                originpostalcode = getShippingOptionRequest.ZipPostalCodeFrom,
                destination      = new mailingscenarioDestination
                {
                    Item = destinationCountry
                }
            };

            //get original parcel characteristics
            decimal originalLength;
            decimal originalWidth;
            decimal originalHeight;
            decimal originalWeight;

            GetWeight(getShippingOptionRequest, out originalWeight);
            GetDimensions(getShippingOptionRequest, out originalLength, out originalWidth, out originalHeight);

            //get rate for all available services
            var errorSummary = new StringBuilder();

            foreach (var service in availableServices.service)
            {
                var currentService = CanadaPostHelper.GetServiceDetails(_canadaPostSettings.ApiKey, service.link.href, service.link.mediatype, out errors);
                if (currentService != null)
                {
                    #region parcels count calculation

                    var totalParcels = 1;

                    //parcels count by weight
                    var maxWeight = currentService.restrictions != null &&
                                    currentService.restrictions.weightrestriction != null &&
                                    currentService.restrictions.weightrestriction.maxSpecified
                        ? currentService.restrictions.weightrestriction.max : int.MaxValue;
                    if (originalWeight * 1000 > maxWeight)
                    {
                        var parcelsOnWeight = Convert.ToInt32(Math.Ceiling(originalWeight * 1000 / maxWeight));
                        if (parcelsOnWeight > totalParcels)
                        {
                            totalParcels = parcelsOnWeight;
                        }
                    }

                    //parcels count by length
                    var maxLength = currentService.restrictions != null &&
                                    currentService.restrictions.dimensionalrestrictions != null &&
                                    currentService.restrictions.dimensionalrestrictions.length != null &&
                                    currentService.restrictions.dimensionalrestrictions.length.maxSpecified
                        ? currentService.restrictions.dimensionalrestrictions.length.max : int.MaxValue;
                    if (originalLength > maxLength)
                    {
                        var parcelsOnLength = Convert.ToInt32(Math.Ceiling(originalLength / maxLength));
                        if (parcelsOnLength > totalParcels)
                        {
                            totalParcels = parcelsOnLength;
                        }
                    }

                    //parcels count by width
                    var maxWidth = currentService.restrictions != null &&
                                   currentService.restrictions.dimensionalrestrictions != null &&
                                   currentService.restrictions.dimensionalrestrictions.width != null &&
                                   currentService.restrictions.dimensionalrestrictions.width.maxSpecified
                        ? currentService.restrictions.dimensionalrestrictions.width.max : int.MaxValue;
                    if (originalWidth > maxWidth)
                    {
                        var parcelsOnWidth = Convert.ToInt32(Math.Ceiling(originalWidth / maxWidth));
                        if (parcelsOnWidth > totalParcels)
                        {
                            totalParcels = parcelsOnWidth;
                        }
                    }

                    //parcels count by height
                    var maxHeight = currentService.restrictions != null &&
                                    currentService.restrictions.dimensionalrestrictions != null &&
                                    currentService.restrictions.dimensionalrestrictions.height != null &&
                                    currentService.restrictions.dimensionalrestrictions.height.maxSpecified
                        ? currentService.restrictions.dimensionalrestrictions.height.max : int.MaxValue;
                    if (originalHeight > maxHeight)
                    {
                        var parcelsOnHeight = Convert.ToInt32(Math.Ceiling(originalHeight / maxHeight));
                        if (parcelsOnHeight > totalParcels)
                        {
                            totalParcels = parcelsOnHeight;
                        }
                    }

                    //parcel count by girth
                    var lengthPlusGirthMax = currentService.restrictions != null &&
                                             currentService.restrictions.dimensionalrestrictions != null &&
                                             currentService.restrictions.dimensionalrestrictions.lengthplusgirthmaxSpecified
                        ? currentService.restrictions.dimensionalrestrictions.lengthplusgirthmax : int.MaxValue;
                    var lengthPlusGirth = 2 * (originalWidth + originalHeight) + originalLength;
                    if (lengthPlusGirth > lengthPlusGirthMax)
                    {
                        var parcelsOnHeight = Convert.ToInt32(Math.Ceiling(lengthPlusGirth / lengthPlusGirthMax));
                        if (parcelsOnHeight > totalParcels)
                        {
                            totalParcels = parcelsOnHeight;
                        }
                    }

                    //parcel count by sum of length, width and height
                    var lengthWidthHeightMax = currentService.restrictions != null &&
                                               currentService.restrictions.dimensionalrestrictions != null &&
                                               currentService.restrictions.dimensionalrestrictions.lengthheightwidthsummaxSpecified
                        ? currentService.restrictions.dimensionalrestrictions.lengthheightwidthsummax : int.MaxValue;
                    var lengthWidthHeight = originalLength + originalWidth + originalHeight;
                    if (lengthWidthHeight > lengthWidthHeightMax)
                    {
                        var parcelsOnHeight = Convert.ToInt32(Math.Ceiling(lengthWidthHeight / lengthWidthHeightMax));
                        if (parcelsOnHeight > totalParcels)
                        {
                            totalParcels = parcelsOnHeight;
                        }
                    }

                    #endregion

                    //set parcel characteristics
                    mailingScenario.services = new[] { currentService.servicecode };
                    mailingScenario.parcelcharacteristics = new mailingscenarioParcelcharacteristics
                    {
                        weight     = Math.Round(originalWeight / totalParcels, 3),
                        dimensions = new mailingscenarioParcelcharacteristicsDimensions
                        {
                            length = Math.Round(originalLength / totalParcels, 1),
                            width  = Math.Round(originalWidth / totalParcels, 1),
                            height = Math.Round(originalHeight / totalParcels, 1)
                        }
                    };

                    //get rate
                    var priceQuotes = CanadaPostHelper.GetShippingRates(mailingScenario, _canadaPostSettings.ApiKey, _canadaPostSettings.UseSandbox, out errors);
                    if (priceQuotes != null)
                    {
                        foreach (var option in priceQuotes.pricequote)
                        {
                            result.ShippingOptions.Add(new ShippingOption
                            {
                                Name        = option.servicename,
                                Rate        = PriceToPrimaryStoreCurrency(option.pricedetails.due * totalParcels),
                                Description = string.Format("Delivery {0}into {1} parcels",
                                                            option.servicestandard != null && !string.IsNullOrEmpty(option.servicestandard.expectedtransittime)
                                    ? string.Format("in {0} days ", option.servicestandard.expectedtransittime) : string.Empty, totalParcels),
                            });
                        }
                    }
                    else
                    {
                        errorSummary.AppendLine(errors);
                    }
                }
                else
                {
                    errorSummary.AppendLine(errors);
                }
            }

            //write errors
            var errorString = errorSummary.ToString();
            if (!string.IsNullOrEmpty(errorString))
            {
                _logger.Error(errorString);
            }
            if (!result.ShippingOptions.Any())
            {
                result.AddError(errorString);
            }

            return(result);
        }
예제 #5
0
        /// <summary>
        ///  Gets available shipping options
        /// </summary>
        /// <param name="getShippingOptionRequest">A request for getting shipping options</param>
        /// <returns>Represents a response of getting shipping rate options</returns>
        public GetShippingOptionResponse GetShippingOptions(GetShippingOptionRequest getShippingOptionRequest)
        {
            if (getShippingOptionRequest == null)
                throw new ArgumentNullException("getShippingOptionRequest");

            if (getShippingOptionRequest.Items == null)
                return new GetShippingOptionResponse { Errors = new List<string> { "No shipment items" } };

            if (getShippingOptionRequest.ShippingAddress == null)
                return new GetShippingOptionResponse { Errors = new List<string> { "Shipping address is not set" } };

            if (getShippingOptionRequest.ShippingAddress.Country == null)
                return new GetShippingOptionResponse { Errors = new List<string> { "Shipping country is not set" } };

            if (string.IsNullOrEmpty(getShippingOptionRequest.ZipPostalCodeFrom))
                return new GetShippingOptionResponse { Errors = new List<string> { "Origin postal code is not set" } };

            //get available services
            string errors;
            var availableServices = CanadaPostHelper.GetServices(getShippingOptionRequest.ShippingAddress.Country.TwoLetterIsoCode,
                _canadaPostSettings.ApiKey, _canadaPostSettings.UseSandbox, out errors);
            if (availableServices == null)
                return new GetShippingOptionResponse { Errors = new List<string> { errors } };

            //create object for the get rates requests
            var result = new GetShippingOptionResponse();
            object destinationCountry;
            switch (getShippingOptionRequest.ShippingAddress.Country.TwoLetterIsoCode.ToLowerInvariant())
            {
                case "us":
                    destinationCountry = new mailingscenarioDestinationUnitedstates
                    {
                        zipcode = getShippingOptionRequest.ShippingAddress.ZipPostalCode
                    };
                    break;
                case "ca":
                    destinationCountry = new mailingscenarioDestinationDomestic
                    {
                        postalcode = getShippingOptionRequest.ShippingAddress.ZipPostalCode
                    };
                    break;
                default:
                    destinationCountry = new mailingscenarioDestinationInternational
                    {
                        countrycode = getShippingOptionRequest.ShippingAddress.Country.TwoLetterIsoCode
                    };
                    break;
            }

            var mailingScenario = new mailingscenario
            {
                customernumber = _canadaPostSettings.CustomerNumber,
                originpostalcode = getShippingOptionRequest.ZipPostalCodeFrom,
                destination = new mailingscenarioDestination
                {
                    Item = destinationCountry
                }
            };

            //get original parcel characteristics
            decimal originalLength;
            decimal originalWidth;
            decimal originalHeight;
            decimal originalWeight;
            GetWeight(getShippingOptionRequest, out originalWeight);
            GetDimensions(getShippingOptionRequest, out originalLength, out originalWidth, out originalHeight);

            //get rate for all available services
            var errorSummary = new StringBuilder();
            foreach (var service in availableServices.service)
            {
                var currentService = CanadaPostHelper.GetServiceDetails(_canadaPostSettings.ApiKey, service.link.href, service.link.mediatype, out errors);
                if (currentService != null)
                {
                    #region parcels count calculation

                    var totalParcels = 1;

                    //parcels count by weight
                    var maxWeight = currentService.restrictions != null
                        && currentService.restrictions.weightrestriction != null
                        && currentService.restrictions.weightrestriction.maxSpecified
                        ? currentService.restrictions.weightrestriction.max : int.MaxValue;
                    if (originalWeight * 1000 > maxWeight)
                    {
                        var parcelsOnWeight = Convert.ToInt32(Math.Ceiling(originalWeight * 1000 / maxWeight));
                        if (parcelsOnWeight > totalParcels)
                            totalParcels = parcelsOnWeight;
                    }

                    //parcels count by length
                    var maxLength = currentService.restrictions != null
                        && currentService.restrictions.dimensionalrestrictions != null
                        && currentService.restrictions.dimensionalrestrictions.length != null
                        && currentService.restrictions.dimensionalrestrictions.length.maxSpecified
                        ? currentService.restrictions.dimensionalrestrictions.length.max : int.MaxValue;
                    if (originalLength > maxLength)
                    {
                        var parcelsOnLength = Convert.ToInt32(Math.Ceiling(originalLength / maxLength));
                        if (parcelsOnLength > totalParcels)
                            totalParcels = parcelsOnLength;
                    }

                    //parcels count by width
                    var maxWidth = currentService.restrictions != null
                        && currentService.restrictions.dimensionalrestrictions != null
                        && currentService.restrictions.dimensionalrestrictions.width != null
                        && currentService.restrictions.dimensionalrestrictions.width.maxSpecified
                        ? currentService.restrictions.dimensionalrestrictions.width.max : int.MaxValue;
                    if (originalWidth > maxWidth)
                    {
                        var parcelsOnWidth = Convert.ToInt32(Math.Ceiling(originalWidth / maxWidth));
                        if (parcelsOnWidth > totalParcels)
                            totalParcels = parcelsOnWidth;
                    }

                    //parcels count by height
                    var maxHeight = currentService.restrictions != null
                        && currentService.restrictions.dimensionalrestrictions != null
                        && currentService.restrictions.dimensionalrestrictions.height != null
                        && currentService.restrictions.dimensionalrestrictions.height.maxSpecified
                        ? currentService.restrictions.dimensionalrestrictions.height.max : int.MaxValue;
                    if (originalHeight > maxHeight)
                    {
                        var parcelsOnHeight = Convert.ToInt32(Math.Ceiling(originalHeight / maxHeight));
                        if (parcelsOnHeight > totalParcels)
                            totalParcels = parcelsOnHeight;
                    }

                    //parcel count by girth
                    var lengthPlusGirthMax = currentService.restrictions != null
                        && currentService.restrictions.dimensionalrestrictions != null
                        && currentService.restrictions.dimensionalrestrictions.lengthplusgirthmaxSpecified
                        ? currentService.restrictions.dimensionalrestrictions.lengthplusgirthmax : int.MaxValue;
                    var lengthPlusGirth = 2 * (originalWidth + originalHeight) + originalLength;
                    if (lengthPlusGirth > lengthPlusGirthMax)
                    {
                        var parcelsOnHeight = Convert.ToInt32(Math.Ceiling(lengthPlusGirth / lengthPlusGirthMax));
                        if (parcelsOnHeight > totalParcels)
                            totalParcels = parcelsOnHeight;
                    }

                    //parcel count by sum of length, width and height
                    var lengthWidthHeightMax = currentService.restrictions != null
                        && currentService.restrictions.dimensionalrestrictions != null
                        && currentService.restrictions.dimensionalrestrictions.lengthheightwidthsummaxSpecified
                        ? currentService.restrictions.dimensionalrestrictions.lengthheightwidthsummax : int.MaxValue;
                    var lengthWidthHeight = originalLength + originalWidth + originalHeight;
                    if (lengthWidthHeight > lengthWidthHeightMax)
                    {
                        var parcelsOnHeight = Convert.ToInt32(Math.Ceiling(lengthWidthHeight / lengthWidthHeightMax));
                        if (parcelsOnHeight > totalParcels)
                            totalParcels = parcelsOnHeight;
                    }

                    #endregion

                    //set parcel characteristics
                    mailingScenario.services = new[] { currentService.servicecode };
                    mailingScenario.parcelcharacteristics = new mailingscenarioParcelcharacteristics
                    {
                        weight = Math.Round(originalWeight / totalParcels, 3),
                        dimensions = new mailingscenarioParcelcharacteristicsDimensions
                        {
                            length = Math.Round(originalLength / totalParcels, 1),
                            width = Math.Round(originalWidth / totalParcels, 1),
                            height = Math.Round(originalHeight / totalParcels, 1)
                        }
                    };

                    //get rate
                    var priceQuotes = CanadaPostHelper.GetShippingRates(mailingScenario, _canadaPostSettings.ApiKey, _canadaPostSettings.UseSandbox, out errors);
                    if (priceQuotes != null)
                        foreach (var option in priceQuotes.pricequote)
                        {
                            result.ShippingOptions.Add(new ShippingOption
                            {
                                Name = option.servicename,
                                Rate = PriceToPrimaryStoreCurrency(option.pricedetails.due * totalParcels),
                                Description = string.Format("Delivery {0}into {1} parcels", 
                                    option.servicestandard != null && !string.IsNullOrEmpty(option.servicestandard.expectedtransittime) 
                                    ? string.Format("in {0} days ", option.servicestandard.expectedtransittime) : string.Empty, totalParcels),
                            });
                        }
                    else
                        errorSummary.AppendLine(errors);
                }
                else
                    errorSummary.AppendLine(errors);
            }

            //write errors
            var errorString = errorSummary.ToString();
            if (!string.IsNullOrEmpty(errorString))
                _logger.Error(errorString);
            if (!result.ShippingOptions.Any())
                result.AddError(errorString);

            return result;

        }
예제 #6
0
        static void Main(string[] args)
        {
            ServicePointManager.SecurityProtocol = Tls12;

            // Your username, password and customer number are imported from the following file
            // CPCWS_Rating_DotNet_Samples\REST\rating\user.xml
            var username = "******";
            var password = "******";
            var mailedBy = "4008838";

            var url = "https://ct.soa-gw.canadapost.ca/rs/ship/price"; // REST URL

            var    method           = "POST";                          // HTTP Method
            String responseAsString = ".NET Framework " + Environment.Version.ToString() + "\r\n\r\n";

            // Create mailingScenario object to contain xml request
            mailingscenario mailingScenario = new mailingscenario();

            mailingScenario.parcelcharacteristics = new mailingscenarioParcelcharacteristics();
            mailingScenario.destination           = new mailingscenarioDestination();
            mailingscenarioDestinationDomestic destDom = new mailingscenarioDestinationDomestic();

            mailingScenario.destination.Item = destDom;

            // Populate mailingScenario object
            mailingScenario.customernumber = mailedBy;
            mailingScenario.parcelcharacteristics.weight = 1;
            mailingScenario.originpostalcode             = "K2B8J6";
            destDom.postalcode = "J0E1X0";

            try
            {
                // Serialize mailingScenario object to String
                StringBuilder mailingScenarioSb  = new StringBuilder();
                XmlWriter     mailingScenarioXml = XmlWriter.Create(mailingScenarioSb);
                mailingScenarioXml.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");
                XmlSerializer serializerRequest = new XmlSerializer(typeof(mailingscenario));
                serializerRequest.Serialize(mailingScenarioXml, mailingScenario);

                // Create REST Request
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = method;

                // Set Basic Authentication Header using username and password variables
                string auth = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password));
                request.Headers = new WebHeaderCollection();
                request.Headers.Add("Authorization", auth);

                // Write Post Data to Request
                UTF8Encoding encoding = new UTF8Encoding();
                byte[]       buffer   = encoding.GetBytes(mailingScenarioSb.ToString());
                request.ContentLength = buffer.Length;
                request.Headers.Add("Accept-Language", "en-CA");
                request.Accept      = "application/vnd.cpc.ship.rate-v4+xml";
                request.ContentType = "application/vnd.cpc.ship.rate-v4+xml";
                Stream PostData = request.GetRequestStream();
                PostData.Write(buffer, 0, buffer.Length);
                PostData.Close();

                // Execute REST Request
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                // Deserialize response to pricequotes object
                XmlSerializer serializer  = new XmlSerializer(typeof(pricequotes));
                TextReader    reader      = new StreamReader(response.GetResponseStream());
                pricequotes   priceQuotes = (pricequotes)serializer.Deserialize(reader);

                // Retrieve values from pricequotes object
                foreach (var priceQuote in priceQuotes.pricequote)
                {
                    responseAsString += "Service Name: " + priceQuote.servicename + "\r\n";
                    responseAsString += "Price Name: $" + priceQuote.pricedetails.due + "\r\n\r\n";
                }
            }
            catch (WebException webEx)
            {
                HttpWebResponse response = (HttpWebResponse)webEx.Response;

                if (response != null)
                {
                    responseAsString += "HTTP  Response Status: " + webEx.Message + "\r\n";

                    // Retrieve errors from messages object
                    try
                    {
                        // Deserialize xml response to messages object
                        XmlSerializer serializer = new XmlSerializer(typeof(messages));
                        TextReader    reader     = new StreamReader(response.GetResponseStream());
                        messages      myMessages = (messages)serializer.Deserialize(reader);


                        if (myMessages.message != null)
                        {
                            foreach (var item in myMessages.message)
                            {
                                responseAsString += "Error Code: " + item.code + "\r\n";
                                responseAsString += "Error Msg: " + item.description + "\r\n";
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        // Misc Exception
                        responseAsString += "ERROR: " + ex.Message;
                    }
                }
                else
                {
                    // Invalid Request
                    responseAsString += "ERROR: " + webEx.Message;
                }
            }
            catch (Exception ex)
            {
                // Misc Exception
                responseAsString += "ERROR: " + ex.Message;
            }

            Console.WriteLine(responseAsString);
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey(true);
        }
        private FinalPrice GetRates(SourceDestination sourceDestination)
        {
            FinalPrice  finalPrice = new FinalPrice();
            List <rate> finalRate  = new List <rate>();

            var url = "https://ct.soa-gw.canadapost.ca/rs/ship/price"; // REST URL

            var    method           = "POST";                          // HTTP Method
            String responseAsString = "";

            // Create mailingScenario object to contain xml request
            mailingscenario mailingScenario = new mailingscenario();

            mailingScenario.parcelcharacteristics = new mailingscenarioParcelcharacteristics();
            mailingScenario.destination           = new mailingscenarioDestination();
            mailingscenarioDestinationDomestic destDom = new mailingscenarioDestinationDomestic();

            mailingScenario.destination.Item = destDom;


            String modifiedOrigin      = Regex.Replace(sourceDestination.originpostalcode, @"\s", "");
            String modifiedDestination = Regex.Replace(sourceDestination.destinationpostalcode, @"\s", "");

            // Populate mailingScenario object
            mailingScenario.customernumber = "2004381";
            mailingScenario.parcelcharacteristics.weight = sourceDestination.parcelweight;
            mailingScenario.originpostalcode             = modifiedOrigin.Trim();
            destDom.postalcode = modifiedDestination.Trim();

            try
            {
                // Serialize mailingScenario object to String
                StringBuilder mailingScenarioSb  = new StringBuilder();
                XmlWriter     mailingScenarioXml = XmlWriter.Create(mailingScenarioSb);
                mailingScenarioXml.WriteProcessingInstruction("xml", "version=\"1.1\" encoding=\"UTF-8\"");
                XmlSerializer serializerRequest = new XmlSerializer(typeof(mailingscenario));
                serializerRequest.Serialize(mailingScenarioXml, mailingScenario);

                // Create REST Request
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = method;

                // Set Basic Authentication Header using username and password variables
                string auth = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("6e93d53968881714" + ":" + "0bfa9fcb9853d1f51ee57a"));
                request.Headers = new WebHeaderCollection();
                request.Headers.Add("Authorization", auth);

                // Write Post Data to Request
                UTF8Encoding encoding = new UTF8Encoding();
                byte[]       buffer   = encoding.GetBytes(mailingScenarioSb.ToString());
                request.ContentLength = buffer.Length;
                request.Headers.Add("Accept-Language", "en-CA");
                request.Accept      = "application/vnd.cpc.ship.rate-v4+xml";
                request.ContentType = "application/vnd.cpc.ship.rate-v4+xml";
                Stream PostData = request.GetRequestStream();
                PostData.Write(buffer, 0, buffer.Length);
                PostData.Close();

                // Execute REST Request
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                if (response.StatusCode.ToString() == "OK")
                {
                    // Deserialize response to pricequotes object
                    XmlSerializer serializer  = new XmlSerializer(typeof(pricequotes));
                    TextReader    reader      = new StreamReader(response.GetResponseStream());
                    pricequotes   priceQuotes = (pricequotes)serializer.Deserialize(reader);

                    // Retrieve values from pricequotes object
                    foreach (var priceQuote in priceQuotes.pricequote)
                    {
                        finalRate.Add(new rate {
                            RegularPrice = priceQuote.pricedetails.due, ServiceType = priceQuote.servicename, TransitDay = Convert.ToInt16(priceQuote.servicestandard.expectedtransittime)
                        });
                    }
                    finalPrice.RatesList             = finalRate;
                    finalPrice.originpostalcode      = sourceDestination.originpostalcode;
                    finalPrice.destinationpostalcode = sourceDestination.destinationpostalcode;
                    finalPrice.parcelweight          = sourceDestination.parcelweight;
                }
                else
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(messages));
                    TextReader    reader     = new StreamReader(response.GetResponseStream());
                    messages      myMessages = (messages)serializer.Deserialize(reader);


                    if (myMessages.message != null)
                    {
                        foreach (var item in myMessages.message)
                        {
                            responseAsString    += "Error Code: " + item.code + "\r\n";
                            responseAsString    += "Error Msg: " + item.description + "\r\n";
                            ViewBag.ErrorMessage = responseAsString;
                        }
                    }
                }
            }
            catch (WebException webEx)
            {
                HttpWebResponse response = (HttpWebResponse)webEx.Response;

                if (response != null)
                {
                    //responseAsString += "HTTP  Response Status: " + webEx.Message + "\r\n";

                    // Retrieve errors from messages object
                    try
                    {
                        // Deserialize xml response to messages object
                        XmlSerializer serializer = new XmlSerializer(typeof(messages));
                        TextReader    reader     = new StreamReader(response.GetResponseStream());
                        messages      myMessages = (messages)serializer.Deserialize(reader);


                        if (myMessages.message != null)
                        {
                            foreach (var item in myMessages.message)
                            {
                                responseAsString    += "Error Code: " + item.code + "\r\n";
                                responseAsString    += "Error Msg: " + item.description + "\r\n";
                                ViewBag.ErrorMessage = responseAsString;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        // Misc Exception
                        responseAsString    += "ERROR: " + ex.Message;
                        ViewBag.ErrorMessage = responseAsString;
                    }
                }
                else
                {
                    // Invalid Request
                    responseAsString    += "ERROR: " + webEx.Message;
                    ViewBag.ErrorMessage = responseAsString;
                }
            }
            catch (Exception ex)
            {
                // Misc Exception
                responseAsString    += "ERROR: " + ex.Message;
                ViewBag.ErrorMessage = responseAsString;
            }

            return(finalPrice);
        }
        public DataTable PostAPI(DataTable dt)
        {
            var username = "******";
            var password = "******";
            var url      = "https://ct.soa-gw.canadapost.ca/rs/ship/price";
            var method   = "POST";

            String errorString = "";

            mailingscenario mailingScenario = new mailingscenario();

            mailingScenario.parcelcharacteristics = new mailingscenarioParcelcharacteristics();
            mailingScenario.destination           = new mailingscenarioDestination();
            mailingscenarioDestinationDomestic destDom = new mailingscenarioDestinationDomestic();

            mailingScenario.destination.domestic = destDom;

            mailingScenario.quotetype = "counter";
            mailingScenario.parcelcharacteristics.weight = 1;
            mailingScenario.originpostalcode             = "K2B8J6";
            destDom.postalcode = "J0E1X0";

            try
            {
                StringBuilder mailingScenarioSb  = new StringBuilder();
                XmlWriter     mailingScenarioXml = XmlWriter.Create(mailingScenarioSb);
                mailingScenarioXml.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");
                XmlSerializer serializerRequest = new XmlSerializer(typeof(mailingscenario));
                serializerRequest.Serialize(mailingScenarioXml, mailingScenario);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = method;

                string auth = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password));
                request.Headers = new WebHeaderCollection();
                request.Headers.Add("Authorization", auth);

                UTF8Encoding encoding = new UTF8Encoding();
                byte[]       buffer   = encoding.GetBytes(mailingScenarioSb.ToString());
                request.ContentLength = buffer.Length;
                request.Headers.Add("Accept-Language", "en-CA");
                request.Accept      = "application/vnd.cpc.ship.rate-v4+xml";
                request.ContentType = "application/vnd.cpc.ship.rate-v4+xml";
                Stream PostData = request.GetRequestStream();
                PostData.Write(buffer, 0, buffer.Length);
                PostData.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                XmlSerializer serializer  = new XmlSerializer(typeof(pricequotes));
                TextReader    reader      = new StreamReader(response.GetResponseStream());
                pricequotes   priceQuotes = (pricequotes)serializer.Deserialize(reader);

                foreach (var priceQuote in priceQuotes.pricequote)
                {
                    dt.Rows.Add(priceQuote.servicename, priceQuote.servicestandard.expectedtransittime, "$" + priceQuote.pricedetails.due);
                }
            }
            catch (WebException webEx)
            {
                HttpWebResponse response = (HttpWebResponse)webEx.Response;

                if (response != null)
                {
                    errorString += "HTTP  Response Status: " + webEx.Message + "\r\n";

                    try
                    {
                        errorString += "ERROR!!!";
                    }
                    catch (Exception ex)
                    {
                        errorString += "ERROR: " + ex.Message;
                    }
                }
                else
                {
                    errorString += "ERROR: " + webEx.Message;
                }
            }
            catch (Exception ex)
            {
                // Misc Exception
                errorString += "ERROR: " + ex.Message;
            }

            errStr.Text = errorString;

            return(dt);
        }
예제 #9
0
        public double GetRates(string postalCode, ShippingType shippingType)
        {
            ServicePointManager.SecurityProtocol = Tls12;

            var username = "******";                                      //ConfigurationSettings.AppSettings["username"];
            var password = "******";                                      //ConfigurationSettings.AppSettings["password"];
            var mailedBy = "0008948796";                                    //ConfigurationSettings.AppSettings["customerNumber"];
            var url      = "https://ct.soa-gw.canadapost.ca/rs/ship/price"; // REST URL
            var method   = "POST";                                          // HTTP Method

            // Create mailingScenario object to contain xml request
            mailingscenario mailingScenario = new mailingscenario
            {
                parcelcharacteristics = new mailingscenarioParcelcharacteristics(),
                destination           = new mailingscenarioDestination()
            };

            // remove dis shit
            string responseAsString = "";

            // Check Shipping Type
            switch (shippingType)
            {
            case ShippingType.Canada:
                mailingScenario.destination.Item = new mailingscenarioDestinationDomestic()
                {
                    postalcode = postalCode
                };
                break;

            case ShippingType.USA:
                mailingScenario.destination.Item = new mailingscenarioDestinationUnitedstates()
                {
                    zipcode = postalCode
                };
                break;

            case ShippingType.International:
                mailingScenario.destination.Item = new mailingscenarioDestinationInternational()
                {
                    postalcode = postalCode
                };
                break;

            default:
                break;
            }

            // Populate mailingScenario object
            mailingScenario.customernumber = mailedBy;
            mailingScenario.parcelcharacteristics.weight     = 1;
            mailingScenario.parcelcharacteristics.dimensions = new mailingscenarioParcelcharacteristicsDimensions
            {
                length = 24,
                width  = 4,
                height = 24
            };
            mailingScenario.originpostalcode = "postal code"; // Shipping Original Postal Code

            try
            {
                // Serialize mailingScenario object to String
                StringBuilder mailingScenarioSb  = new StringBuilder();
                XmlWriter     mailingScenarioXml = XmlWriter.Create(mailingScenarioSb);
                mailingScenarioXml.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");
                XmlSerializer serializerRequest = new XmlSerializer(typeof(mailingscenario));
                serializerRequest.Serialize(mailingScenarioXml, mailingScenario);

                // Create REST Request
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = method;

                // Set Basic Authentication Header using username and password variables
                string auth = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password));
                request.Headers = new WebHeaderCollection();
                request.Headers.Add("Authorization", auth);

                // Write Post Data to Request
                UTF8Encoding encoding = new UTF8Encoding();
                byte[]       buffer   = encoding.GetBytes(mailingScenarioSb.ToString());
                request.ContentLength = buffer.Length;
                request.Headers.Add("Accept-Language", "en-CA");
                request.Accept      = "application/vnd.cpc.ship.rate-v4+xml";
                request.ContentType = "application/vnd.cpc.ship.rate-v4+xml";
                Stream PostData = request.GetRequestStream();
                PostData.Write(buffer, 0, buffer.Length);
                PostData.Close();

                // Execute REST Request
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                // Deserialize response to pricequotes object
                XmlSerializer serializer  = new XmlSerializer(typeof(pricequotes));
                TextReader    reader      = new StreamReader(response.GetResponseStream());
                pricequotes   priceQuotes = (pricequotes)serializer.Deserialize(reader);

                return((double)priceQuotes.pricequote.First().pricedetails.due);

                // Retrieve values from pricequotes object
                foreach (var priceQuote in priceQuotes.pricequote)
                {
                    responseAsString += "Service Name: " + priceQuote.servicename + "\r\n";
                    responseAsString += "Price Name: $" + priceQuote.pricedetails.due + "\r\n\r\n";
                }
            }
            catch (WebException webEx)
            {
                return(0); // 0 = error

                // TODO: Log these errors
                HttpWebResponse response = (HttpWebResponse)webEx.Response;

                if (response != null)
                {
                    responseAsString += "HTTP  Response Status: " + webEx.Message + "\r\n";

                    // Retrieve errors from messages object
                    try
                    {
                        // Deserialize xml response to messages object
                        XmlSerializer serializer = new XmlSerializer(typeof(messages));
                        TextReader    reader     = new StreamReader(response.GetResponseStream());
                        messages      myMessages = (messages)serializer.Deserialize(reader);


                        if (myMessages.message != null)
                        {
                            foreach (var item in myMessages.message)
                            {
                                responseAsString += "Error Code: " + item.code + "\r\n";
                                responseAsString += "Error Msg: " + item.description + "\r\n";
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        // Misc Exception
                        responseAsString += "ERROR: " + ex.Message;
                    }
                }
                else
                {
                    // Invalid Request
                    responseAsString += "ERROR: " + webEx.Message;
                }
            }
            catch (Exception ex)
            {
                return(0); // 0 = error

                // Misc Exception
                responseAsString += "ERROR: " + ex.Message;
            }

            return(0); // TODO: should never get here, fix this
        }