private void AddShipFromAddress(ShipmentType shipment)
        {
            ShipFromType shipFrom        = new ShipFromType();
            AddressType  shipFromAddress = new AddressType();

            //  shipFromAddress.AddressLine = new String[] { txtPShipFromAddress.Text };
            shipFromAddress.City              = "South El Monte";
            shipFromAddress.PostalCode        = "91733";
            shipFromAddress.StateProvinceCode = "CA";
            shipFromAddress.CountryCode       = "US";
            shipFrom.Address  = shipFromAddress;
            shipment.ShipFrom = shipFrom;
        }
Example #2
0
        private void AddShipFromAddress(ShipmentType shipment)
        {
            var shipFrom        = new ShipFromType();
            var shipFromAddress = new ShipAddressType();

            shipFromAddress.AddressLine       = new String[] { ShipFromAddressLine };
            shipFromAddress.City              = ShipFromCity;
            shipFromAddress.PostalCode        = ShipFromPostalCode;
            shipFromAddress.StateProvinceCode = ShipFromStateProvinceCode;
            shipFromAddress.CountryCode       = ShipFromCountryCode;
            shipFrom.Address  = shipFromAddress;
            shipFrom.Name     = ShipFromName;
            shipment.ShipFrom = shipFrom;
        }
        private void AddShipFromAddress(ShipmentType shipment)
        {
            var shipFrom        = new ShipFromType();
            var shipFromAddress = new ShipAddressType();

            shipFromAddress.AddressLine       = new[] { ShipperAddressLine };
            shipFromAddress.City              = ShipperCity;
            shipFromAddress.PostalCode        = ShipperPostalCode;
            shipFromAddress.StateProvinceCode = ShipperStateProvinceCode;
            shipFromAddress.CountryCode       = ShipperCountryCode;
            shipFrom.Address = shipFromAddress;
            shipFrom.Name    = ShipperName;
            shipFrom.CompanyDisplayableName = ShipperCompany;
            shipment.ShipFrom = shipFrom;
        }
        static void Main()
        {
            try
            {
                RateService rate        = new RateService();
                RateRequest rateRequest = new RateRequest();
                UPSSecurity upss        = new UPSSecurity();
                UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken();
                upssSvcAccessToken.AccessLicenseNumber = "Your Access License Number";
                upss.ServiceAccessToken = upssSvcAccessToken;
                UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();
                upssUsrNameToken.Username = "******";
                upssUsrNameToken.Password = "******";
                upss.UsernameToken        = upssUsrNameToken;
                rate.UPSSecurityValue     = upss;
                RequestType request       = new RequestType();
                String[]    requestOption = { "Rate" };
                request.RequestOption = requestOption;
                rateRequest.Request   = request;
                ShipmentType shipment = new ShipmentType();
                ShipperType  shipper  = new ShipperType();
                shipper.ShipperNumber = "Your Shipper Number";
                RateWSSample.RateWebReference.AddressType shipperAddress = new RateWSSample.RateWebReference.AddressType();
                String[] addressLine = { "5555 main", "4 Case Cour", "Apt 3B" };
                shipperAddress.AddressLine       = addressLine;
                shipperAddress.City              = "Roswell";
                shipperAddress.PostalCode        = "30076";
                shipperAddress.StateProvinceCode = "GA";
                shipperAddress.CountryCode       = "US";
                shipperAddress.AddressLine       = addressLine;
                shipper.Address  = shipperAddress;
                shipment.Shipper = shipper;
                ShipFromType shipFrom = new ShipFromType();
                RateWSSample.RateWebReference.AddressType shipFromAddress = new RateWSSample.RateWebReference.AddressType();
                shipFromAddress.AddressLine       = addressLine;
                shipFromAddress.City              = "Roswell";
                shipFromAddress.PostalCode        = "30076";
                shipFromAddress.StateProvinceCode = "GA";
                shipFromAddress.CountryCode       = "US";
                shipFrom.Address  = shipFromAddress;
                shipment.ShipFrom = shipFrom;
                ShipToType        shipTo        = new ShipToType();
                ShipToAddressType shipToAddress = new ShipToAddressType();
                String[]          addressLine1  = { "10 E. Ritchie Way", "2", "Apt 3B" };
                shipToAddress.AddressLine       = addressLine1;
                shipToAddress.City              = "Plam Springs";
                shipToAddress.PostalCode        = "92262";
                shipToAddress.StateProvinceCode = "CA";
                shipToAddress.CountryCode       = "US";
                shipTo.Address  = shipToAddress;
                shipment.ShipTo = shipTo;
                CodeDescriptionType service = new CodeDescriptionType();

                //Below code uses dummy date for reference. Please udpate as required.
                service.Code     = "02";
                shipment.Service = service;
                PackageType       package       = new PackageType();
                PackageWeightType packageWeight = new PackageWeightType();
                packageWeight.Weight = "125";
                CodeDescriptionType uom = new CodeDescriptionType();
                uom.Code        = "LBS";
                uom.Description = "pounds";
                packageWeight.UnitOfMeasurement = uom;
                package.PackageWeight           = packageWeight;
                CodeDescriptionType packType = new CodeDescriptionType();
                packType.Code         = "02";
                package.PackagingType = packType;
                PackageType[] pkgArray = { package };
                shipment.Package     = pkgArray;
                rateRequest.Shipment = shipment;
                System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
                Console.WriteLine(rateRequest);
                RateResponse rateResponse = rate.ProcessRate(rateRequest);
                Console.WriteLine("The transaction was a " + rateResponse.Response.ResponseStatus.Description);
                Console.WriteLine("Total Shipment Charges " + rateResponse.RatedShipment[0].TotalCharges.MonetaryValue + rateResponse.RatedShipment[0].TotalCharges.CurrencyCode);
                Console.ReadKey();
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                Console.WriteLine("");
                Console.WriteLine("---------Rate Web Service returns error----------------");
                Console.WriteLine("---------\"Hard\" is user error \"Transient\" is system error----------------");
                Console.WriteLine("SoapException Message= " + ex.Message);
                Console.WriteLine("");
                Console.WriteLine("SoapException Category:Code:Message= " + ex.Detail.LastChild.InnerText);
                Console.WriteLine("");
                Console.WriteLine("SoapException XML String for all= " + ex.Detail.LastChild.OuterXml);
                Console.WriteLine("");
                Console.WriteLine("SoapException StackTrace= " + ex.StackTrace);
                Console.WriteLine("-------------------------");
                Console.WriteLine("");
            }
            catch (System.ServiceModel.CommunicationException ex)
            {
                Console.WriteLine("");
                Console.WriteLine("--------------------");
                Console.WriteLine("CommunicationException= " + ex.Message);
                Console.WriteLine("CommunicationException-StackTrace= " + ex.StackTrace);
                Console.WriteLine("-------------------------");
                Console.WriteLine("");
            }
            catch (Exception ex)
            {
                Console.WriteLine("");
                Console.WriteLine("-------------------------");
                Console.WriteLine(" Generaal Exception= " + ex.Message);
                Console.WriteLine(" Generaal Exception-StackTrace= " + ex.StackTrace);
                Console.WriteLine("-------------------------");
            }
            finally {
                Console.ReadKey();
            }
        }
Example #5
0
 static void Main()
 {
     try
     {
         ShipService     shpSvc          = new ShipService();
         ShipmentRequest shipmentRequest = new ShipmentRequest();
         UPSSecurity     upss            = new UPSSecurity();
         UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken();
         upssSvcAccessToken.AccessLicenseNumber = "Your Access License";
         upss.ServiceAccessToken = upssSvcAccessToken;
         UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();
         upssUsrNameToken.Username = "******";
         upssUsrNameToken.Password = "******";
         upss.UsernameToken        = upssUsrNameToken;
         shpSvc.UPSSecurityValue   = upss;
         RequestType request       = new RequestType();
         String[]    requestOption = { "nonvalidate" };
         request.RequestOption   = requestOption;
         shipmentRequest.Request = request;
         ShipmentType shipment = new ShipmentType();
         shipment.Description = "Ship webservice example";
         ShipperType shipper = new ShipperType();
         shipper.ShipperNumber = "Your Shipper Number";
         PaymentInfoType    paymentInfo   = new PaymentInfoType();
         ShipmentChargeType shpmentCharge = new ShipmentChargeType();
         BillShipperType    billShipper   = new BillShipperType();
         billShipper.AccountNumber = "Your Account Number";
         shpmentCharge.BillShipper = billShipper;
         shpmentCharge.Type        = "01";
         ShipmentChargeType[] shpmentChargeArray = { shpmentCharge };
         paymentInfo.ShipmentCharge  = shpmentChargeArray;
         shipment.PaymentInformation = paymentInfo;
         ShipWSSample.ShipWebReference.ShipAddressType shipperAddress = new ShipWSSample.ShipWebReference.ShipAddressType();
         String[] addressLine = { "480 Parkton Plaza" };
         shipperAddress.AddressLine       = addressLine;
         shipperAddress.City              = "Timonium";
         shipperAddress.PostalCode        = "21093";
         shipperAddress.StateProvinceCode = "MD";
         shipperAddress.CountryCode       = "US";
         shipperAddress.AddressLine       = addressLine;
         shipper.Address       = shipperAddress;
         shipper.Name          = "ABC Associates";
         shipper.AttentionName = "ABC Associates";
         ShipPhoneType shipperPhone = new ShipPhoneType();
         shipperPhone.Number = "1234567890";
         shipper.Phone       = shipperPhone;
         shipment.Shipper    = shipper;
         ShipFromType shipFrom = new ShipFromType();
         ShipWSSample.ShipWebReference.ShipAddressType shipFromAddress = new ShipWSSample.ShipWebReference.ShipAddressType();
         String[] shipFromAddressLine = { "Ship From Street" };
         shipFromAddress.AddressLine       = addressLine;
         shipFromAddress.City              = "Timonium";
         shipFromAddress.PostalCode        = "21093";
         shipFromAddress.StateProvinceCode = "MD";
         shipFromAddress.CountryCode       = "US";
         shipFrom.Address       = shipFromAddress;
         shipFrom.AttentionName = "Mr.ABC";
         shipFrom.Name          = "ABC Associates";
         shipment.ShipFrom      = shipFrom;
         ShipToType        shipTo        = new ShipToType();
         ShipToAddressType shipToAddress = new ShipToAddressType();
         String[]          addressLine1  = { "Some Street" };
         shipToAddress.AddressLine       = addressLine1;
         shipToAddress.City              = "Roswell";
         shipToAddress.PostalCode        = "30076";
         shipToAddress.StateProvinceCode = "GA";
         shipToAddress.CountryCode       = "US";
         shipTo.Address       = shipToAddress;
         shipTo.AttentionName = "DEF";
         shipTo.Name          = "DEF Associates";
         ShipPhoneType shipToPhone = new ShipPhoneType();
         shipToPhone.Number = "1234567890";
         shipTo.Phone       = shipToPhone;
         shipment.ShipTo    = shipTo;
         ServiceType service = new ServiceType();
         service.Code     = "01";
         shipment.Service = service;
         PackageType       package       = new PackageType();
         PackageWeightType packageWeight = new PackageWeightType();
         packageWeight.Weight = "10";
         ShipUnitOfMeasurementType uom = new ShipUnitOfMeasurementType();
         uom.Code = "LBS";
         packageWeight.UnitOfMeasurement = uom;
         package.PackageWeight           = packageWeight;
         PackagingType packType = new PackagingType();
         packType.Code     = "02";
         package.Packaging = packType;
         PackageType[] pkgArray = { package };
         shipment.Package = pkgArray;
         LabelSpecificationType labelSpec      = new LabelSpecificationType();
         LabelStockSizeType     labelStockSize = new LabelStockSizeType();
         labelStockSize.Height    = "6";
         labelStockSize.Width     = "4";
         labelSpec.LabelStockSize = labelStockSize;
         LabelImageFormatType labelImageFormat = new LabelImageFormatType();
         labelImageFormat.Code              = "SPL";
         labelSpec.LabelImageFormat         = labelImageFormat;
         shipmentRequest.LabelSpecification = labelSpec;
         shipmentRequest.Shipment           = shipment;
         Console.WriteLine(shipmentRequest);
         System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
         ShipmentResponse shipmentResponse = shpSvc.ProcessShipment(shipmentRequest);
         Console.WriteLine("The transaction was a " + shipmentResponse.Response.ResponseStatus.Description);
         Console.WriteLine("The 1Z number of the new shipment is " + shipmentResponse.ShipmentResults.ShipmentIdentificationNumber);
         Console.ReadKey();
     }
     catch (System.Web.Services.Protocols.SoapException ex)
     {
         Console.WriteLine("");
         Console.WriteLine("---------Ship Web Service returns error----------------");
         Console.WriteLine("---------\"Hard\" is user error \"Transient\" is system error----------------");
         Console.WriteLine("SoapException Message= " + ex.Message);
         Console.WriteLine("");
         Console.WriteLine("SoapException Category:Code:Message= " + ex.Detail.LastChild.InnerText);
         Console.WriteLine("");
         Console.WriteLine("SoapException XML String for all= " + ex.Detail.LastChild.OuterXml);
         Console.WriteLine("");
         Console.WriteLine("SoapException StackTrace= " + ex.StackTrace);
         Console.WriteLine("-------------------------");
         Console.WriteLine("");
     }
     catch (System.ServiceModel.CommunicationException ex)
     {
         Console.WriteLine("");
         Console.WriteLine("--------------------");
         Console.WriteLine("CommunicationException= " + ex.Message);
         Console.WriteLine("CommunicationException-StackTrace= " + ex.StackTrace);
         Console.WriteLine("-------------------------");
         Console.WriteLine("");
     }
     catch (Exception ex)
     {
         Console.WriteLine("");
         Console.WriteLine("-------------------------");
         Console.WriteLine(" General Exception= " + ex.Message);
         Console.WriteLine(" General Exception-StackTrace= " + ex.StackTrace);
         Console.WriteLine("-------------------------");
     }
     finally
     {
         Console.ReadKey();
     }
 }
Example #6
0
        private RateRequest CreateRateRequest(RateService rate)
        {
            RateRequest rateRequest = new RateRequest();
            UPSSecurity upss        = new UPSSecurity();
            UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken();

            upssSvcAccessToken.AccessLicenseNumber = AccessKey;
            upss.ServiceAccessToken = upssSvcAccessToken;

            UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();

            upssUsrNameToken.Username = UserName;
            upssUsrNameToken.Password = Password;
            upss.UsernameToken        = upssUsrNameToken;
            rate.UPSSecurityValue     = upss;

            RequestType request = new RequestType();

            String[] requestOption = { "Shop" };
            request.RequestOption = requestOption;
            rateRequest.Request   = request;

            ShipmentType shipment = new ShipmentType();

            ShipperType shipper = new ShipperType();
            //shipper.ShipperNumber = "ISUS01";
            AddressType shipperAddress = new AddressType();

            String[] addressLine = { "Shipper\'s address line" };
            shipperAddress.AddressLine = addressLine;
            shipperAddress.City        = "Shipper\'s city";
            shipperAddress.PostalCode  = PostalCodeFrom;
            //shipperAddress.StateProvinceCode = UpsItem.CountryCode;
            shipperAddress.CountryCode = CountryCodeFrom;
            shipperAddress.AddressLine = addressLine;
            shipper.Address            = shipperAddress;
            shipment.Shipper           = shipper;

            ShipFromType shipFrom        = new ShipFromType();
            AddressType  shipFromAddress = new AddressType();

            shipFromAddress.AddressLine = addressLine;
            shipFromAddress.City        = "ShipFrom city";
            shipFromAddress.PostalCode  = PostalCodeFrom;
            //shipFromAddress.StateProvinceCode = "GA";
            shipFromAddress.CountryCode = CountryCodeFrom;
            shipFrom.Address            = shipFromAddress;
            shipment.ShipFrom           = shipFrom;

            ShipToType        shipTo        = new ShipToType();
            ShipToAddressType shipToAddress = new ShipToAddressType();

            String[] addressLine1 = { AddressTo };
            shipToAddress.AddressLine       = addressLine1;
            shipToAddress.City              = CityTo;
            shipToAddress.PostalCode        = PostalCodeTo;
            shipToAddress.StateProvinceCode = StateTo;
            shipToAddress.CountryCode       = CountryCodeTo;
            shipTo.Address  = shipToAddress;
            shipment.ShipTo = shipTo;

            //CodeDescriptionType service = new CodeDescriptionType();
            //service.Code = "02";
            //shipment.Service = service;
            float weight = MeasureUnits.ConvertWeight(ShoppingCart.TotalShippingWeight, MeasureUnits.WeightUnit.Kilogramm, MeasureUnits.WeightUnit.Pound);

            var data = new List <PackageType>();

            if (!IsPackageTooHeavy(weight))
            {
                PackageType       package       = new PackageType();
                PackageWeightType packageWeight = new PackageWeightType();
                packageWeight.Weight = weight.ToString("F3").Replace(',', '.');

                CodeDescriptionType uom = new CodeDescriptionType();
                uom.Code        = "LBS";
                uom.Description = "Pounds";
                packageWeight.UnitOfMeasurement = uom;
                package.PackageWeight           = packageWeight;

                CodeDescriptionType packType = new CodeDescriptionType();
                packType.Code         = "02";
                package.PackagingType = packType;
                data.Add(package);
            }
            else
            {
                int totalPackages        = 1;
                int totalPackagesWeights = 1;
                if (IsPackageTooHeavy(weight))
                {
                    totalPackagesWeights = SQLDataHelper.GetInt(Math.Ceiling(weight / MaxPackageWeight));
                }

                totalPackages = totalPackagesWeights;
                if (totalPackages == 0)
                {
                    totalPackages = 1;
                }

                float weight2 = weight / totalPackages;

                if (weight2 < 1)
                {
                    weight2 = 1;
                }
                for (int i = 0; i < totalPackages; i++)
                {
                    PackageType       package       = new PackageType();
                    PackageWeightType packageWeight = new PackageWeightType();
                    packageWeight.Weight = weight2.ToString("F3");

                    CodeDescriptionType uom = new CodeDescriptionType();
                    uom.Code        = "LBS";
                    uom.Description = "Pounds";
                    packageWeight.UnitOfMeasurement = uom;
                    package.PackageWeight           = packageWeight;

                    CodeDescriptionType packType = new CodeDescriptionType();
                    packType.Code         = GetPackagingTypeCode(PackagingType);
                    package.PackagingType = packType;
                    data.Add(package);
                }
            }

            PackageType[] pkgArray = data.ToArray();
            shipment.Package     = pkgArray;
            rateRequest.Shipment = shipment;

            CodeDescriptionType pckup = new CodeDescriptionType()
            {
                Code = GetPickupTypeCode(PickupType)
            };

            rateRequest.PickupType = pckup;

            CodeDescriptionType ccustomer = new CodeDescriptionType()
            {
                Code = GetCustomerClassificationCode(CustomerType)
            };

            rateRequest.CustomerClassification = ccustomer;

            System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();

            return(rateRequest);
        }
Example #7
0
        public ActionResult Index()
        {
            UPSSecurity upss = new UPSSecurity();


            UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken();

            upssSvcAccessToken.AccessLicenseNumber = "3D6A1DD5F39023B5";
            upss.ServiceAccessToken = upssSvcAccessToken;
            UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();

            upssUsrNameToken.Username = "******";
            upssUsrNameToken.Password = "******";
            upss.UsernameToken        = upssUsrNameToken;

            RateRequest rateRequest = new RateRequest();

            RequestType request = new RequestType();

            String[] requestOption = { "Shoptimeintransit" };
            request.RequestOption = requestOption;
            rateRequest.Request   = request;


            ShipmentType shipment = new ShipmentType();

            TimeInTransitRequestType Time_Tran = new TimeInTransitRequestType();
            var packbillcode = "03";

            Time_Tran.PackageBillType        = packbillcode;
            shipment.DeliveryTimeInformation = Time_Tran;

            ShipperType shipper = new ShipperType();

            // shipper.ShipperNumber = "Your Shipper Number";

            var shipperAddress = new AddressType();

            // String[] addressLine = { "5555 main", "4 Case Cour", "Apt 3B" };
            //shipperAddress.AddressLine = addressLine;
            shipperAddress.City              = "San Diego";
            shipperAddress.PostalCode        = "92101";
            shipperAddress.StateProvinceCode = "CA";
            shipperAddress.CountryCode       = "US";
            // shipperAddress.AddressLine = addressLine;
            shipper.Address  = shipperAddress;
            shipment.Shipper = shipper;
            ShipFromType shipFrom        = new ShipFromType();
            var          shipFromAddress = new ShipAddressType();

            //shipFromAddress.AddressLine = addressLine;
            shipFromAddress.City              = "San Diego";
            shipFromAddress.PostalCode        = "92101";
            shipFromAddress.StateProvinceCode = "CA";
            shipFromAddress.CountryCode       = "US";
            shipFrom.Address  = shipFromAddress;
            shipment.ShipFrom = shipFrom;


            ShipToType        shipTo        = new ShipToType();
            ShipToAddressType shipToAddress = new ShipToAddressType();

            //String[] addressLine1 = { "10 E. Ritchie Way", "2", "Apt 3B" };
            //shipToAddress.AddressLine = addressLine1;
            shipToAddress.City              = "Canton";
            shipToAddress.PostalCode        = "02021";
            shipToAddress.StateProvinceCode = "MA";
            shipToAddress.CountryCode       = "US";
            shipTo.Address  = shipToAddress;
            shipment.ShipTo = shipTo;

            CodeDescriptionType service = new CodeDescriptionType();

            //Below code uses dummy date for reference. Please udpate as required.
            service.Code     = "02";
            shipment.Service = service;

            PackageType       package       = new PackageType();
            PackageWeightType packageWeight = new PackageWeightType();

            packageWeight.Weight = "1";
            CodeDescriptionType uom = new CodeDescriptionType();

            uom.Code        = "LBS";
            uom.Description = "pounds";
            packageWeight.UnitOfMeasurement = uom;
            package.PackageWeight           = packageWeight;
            CodeDescriptionType packType = new CodeDescriptionType();

            packType.Code         = "02";
            package.PackagingType = packType;
            PackageType[] pkgArray = { package };
            shipment.Package     = pkgArray;
            rateRequest.Shipment = shipment;
            //System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12 | System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11; //This line will ensure the latest security protocol for consuming the web service call.
            // Console.WriteLine(rateRequest);
            var          client       = new RatePortTypeClient();
            RateResponse rateResponse = client.ProcessRate(upss, rateRequest);

            var model = new Rate_Package()
            {
                Response = rateResponse
            };

            return(View(model));
        }
Example #8
0
        public static double UPSEstimatedRate(Person shipto, ProductCollection cart)
        {
            double temp = 0.0;  //return 0.0 if something is wrong

            try
            {
                RateService rate        = new RateService();
                RateRequest rateRequest = new RateRequest();
                UPSSecurity upss        = new UPSSecurity();
                UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken();
                upssSvcAccessToken.AccessLicenseNumber = ConfigurationManager.AppSettings["UPSAccessLicenseNumber"];
                upss.ServiceAccessToken = upssSvcAccessToken;
                UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();
                upssUsrNameToken.Username = ConfigurationManager.AppSettings["UPSUserName"];
                upssUsrNameToken.Password = ConfigurationManager.AppSettings["UPSPassword"];
                upss.UsernameToken        = upssUsrNameToken;
                rate.UPSSecurityValue     = upss;
                RequestType request       = new RequestType();
                String[]    requestOption = { "Rate" };
                request.RequestOption = requestOption;
                rateRequest.Request   = request;
                ShipmentType shipment = new ShipmentType();
                ShipperType  shipper  = new ShipperType();
                shipper.ShipperNumber = "54A177";   //***EAC Intentionally hard-coded.  DO NOT REPLACE WITH ONE IN WEB.CONFIG!

                UPSRateService.AddressType shipperAddress = new UPSRateService.AddressType();
                String[] addressLine = { ConfigurationManager.AppSettings["LMStreet"] };
                shipperAddress.AddressLine       = addressLine;
                shipperAddress.City              = ConfigurationManager.AppSettings["LMCity"];
                shipperAddress.StateProvinceCode = ConfigurationManager.AppSettings["LMState"];
                shipperAddress.PostalCode        = ConfigurationManager.AppSettings["LMZip"];
                shipperAddress.CountryCode       = ConfigurationManager.AppSettings["LMCountry"];
                shipperAddress.AddressLine       = addressLine;
                shipper.Address  = shipperAddress;
                shipment.Shipper = shipper;

                ShipFromType shipFrom = new ShipFromType();
                //UPSRateService.AddressType shipFromAddress = new UPSRateService.AddressType();
                //shipFromAddress.AddressLine = shipperAddress.AddressLine;
                //shipFromAddress.City = shipperAddress.City;
                //shipFromAddress.StateProvinceCode = shipperAddress.StateProvinceCode;
                //shipFromAddress.PostalCode = shipperAddress.PostalCode;
                //shipFromAddress.CountryCode = shipperAddress.CountryCode;
                shipFrom.Address  = shipperAddress;
                shipment.ShipFrom = shipFrom;


                ShipToType        shipTo        = new ShipToType();
                ShipToAddressType shipToAddress = new ShipToAddressType();
                String[]          addressLine1  = { shipto.Addr1 };
                shipToAddress.AddressLine       = addressLine1;
                shipToAddress.City              = shipto.City;
                shipToAddress.StateProvinceCode = shipto.State;
                shipToAddress.PostalCode        = shipto.Zip5;
                shipToAddress.CountryCode       = shipto.Country;
                shipTo.Address  = shipToAddress;
                shipment.ShipTo = shipTo;


                CodeDescriptionType service = new CodeDescriptionType();
                //Below code uses dummy date for reference. Please udpate as required.
                //service.Code = "03"; //01:nextdayair 02;2ndday 03:ground 12:3dayselect
                service.Code     = DAL2.DAL.GetShippingMethodValuebyID(cart.ShipMethod);
                shipment.Service = service;
                PackageType       package       = new PackageType();
                PackageWeightType packageWeight = new PackageWeightType();
                packageWeight.Weight = cart.TotalWeight.ToString();
                CodeDescriptionType uom = new CodeDescriptionType();
                uom.Code        = "LBS";
                uom.Description = "pounds";
                packageWeight.UnitOfMeasurement = uom;
                package.PackageWeight           = packageWeight;
                CodeDescriptionType packType = new CodeDescriptionType();
                packType.Code         = "02"; //02:pkgcustomer
                package.PackagingType = packType;
                PackageType[] pkgArray = { package };
                shipment.Package     = pkgArray;
                rateRequest.Shipment = shipment;
                System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();

                RateResponse rateResponse = rate.ProcessRate(rateRequest);
                UPSNoelWrite("The transaction was a " + rateResponse.Response.ResponseStatus.Description);
                UPSNoelWrite("Total Shipment Charges " + rateResponse.RatedShipment[0].TotalCharges.MonetaryValue + rateResponse.RatedShipment[0].TotalCharges.CurrencyCode);
                temp = Double.Parse(rateResponse.RatedShipment[0].TotalCharges.MonetaryValue);
            }
            catch (Exception ex)
            {
                temp = 0.0;
            }
            return(temp);
            //catch (System.Web.Services.Protocols.SoapException ex)
            //{
            //    UPSNoelWrite("");
            //    UPSNoelWrite("---------Rate Web Service returns error----------------");
            //    UPSNoelWrite("---------\"Hard\" is user error \"Transient\" is system error----------------");
            //    UPSNoelWrite("SoapException Message= " + ex.Message);
            //    UPSNoelWrite("");
            //    UPSNoelWrite("SoapException Category:Code:Message= " + ex.Detail.LastChild.InnerText);
            //    UPSNoelWrite("");
            //    UPSNoelWrite("SoapException XML String for all= " + ex.Detail.LastChild.OuterXml);
            //    UPSNoelWrite("");
            //    UPSNoelWrite("SoapException StackTrace= " + ex.StackTrace);
            //    UPSNoelWrite("-------------------------");
            //    UPSNoelWrite("");
            //}
            //catch (System.ServiceModel.CommunicationException ex)
            //{
            //    UPSNoelWrite("");
            //    UPSNoelWrite("--------------------");
            //    UPSNoelWrite("CommunicationException= " + ex.Message);
            //    UPSNoelWrite("CommunicationException-StackTrace= " + ex.StackTrace);
            //    UPSNoelWrite("-------------------------");
            //    UPSNoelWrite("");

            //}
            //catch (Exception ex)
            //{
            //    UPSNoelWrite("");
            //    UPSNoelWrite("-------------------------");
            //    UPSNoelWrite(" Generaal Exception= " + ex.Message);
            //    UPSNoelWrite(" Generaal Exception-StackTrace= " + ex.StackTrace);
            //    UPSNoelWrite("-------------------------");

            //}
            //finally
            //{
            //    //Console.ReadKey();
            //}
        }
Example #9
0
        private string PrintLabel()
        {
            try
            {
                ShipService     shpSvc          = new ShipService();
                ShipmentRequest shipmentRequest = new ShipmentRequest();
                UPSSecurity     upss            = new UPSSecurity();
                UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken();
                upssSvcAccessToken.AccessLicenseNumber = hfLicense.Value;
                upss.ServiceAccessToken = upssSvcAccessToken;
                UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();
                upssUsrNameToken.Username = hfUserName.Value;
                upssUsrNameToken.Password = hfPassword.Value;
                upss.UsernameToken        = upssUsrNameToken;
                shpSvc.UPSSecurityValue   = upss;
                RequestType request       = new RequestType();
                String[]    requestOption = { lblAddressValidation.Text.Trim() };
                request.RequestOption   = requestOption;
                shipmentRequest.Request = request;
                ShipmentType shipment = new ShipmentType();
                shipment.Description = "CMS Label Printing";
                ShipperType shipper = new ShipperType();
                shipper.ShipperNumber = hfAccountNumber.Value;
                PaymentInfoType    paymentInfo   = new PaymentInfoType();
                ShipmentChargeType shpmentCharge = new ShipmentChargeType();
                BillShipperType    billShipper   = new BillShipperType();
                billShipper.AccountNumber = hfAccountNumber.Value;
                shpmentCharge.BillShipper = billShipper;
                shpmentCharge.Type        = lblChargeType.Text.Trim();
                ShipmentChargeType[] shpmentChargeArray = { shpmentCharge };
                paymentInfo.ShipmentCharge  = shpmentChargeArray;
                shipment.PaymentInformation = paymentInfo;
                UPSShipWebReference.ShipAddressType shipperAddress = new UPSShipWebReference.ShipAddressType();

                String[] addressLine = { lblFromStreet.Text.Trim() };
                shipperAddress.AddressLine       = addressLine;
                shipperAddress.City              = lblFromCity.Text.Trim();
                shipperAddress.PostalCode        = lblFromZip.Text.Trim();
                shipperAddress.StateProvinceCode = hfFromStateUPSCode.Value;
                shipperAddress.CountryCode       = hfFromCountryUPSCode.Value;
                shipperAddress.AddressLine       = addressLine;
                shipper.Address       = shipperAddress;
                shipper.Name          = lblFromName.Text.Trim();
                shipper.AttentionName = lblFromName.Text.Trim();
                ShipPhoneType shipperPhone = new ShipPhoneType();
                shipperPhone.Number = lblFromPhone.Text.Trim();
                shipper.Phone       = shipperPhone;
                shipment.Shipper    = shipper;

                ShipFromType shipFrom = new ShipFromType();
                UPSShipWebReference.ShipAddressType shipFromAddress = new UPSShipWebReference.ShipAddressType();
                String[] shipFromAddressLine = { lblFromStreet.Text.Trim() };
                shipFromAddress.AddressLine       = addressLine;
                shipFromAddress.City              = lblFromCity.Text.Trim();
                shipFromAddress.PostalCode        = lblFromZip.Text.Trim();
                shipFromAddress.StateProvinceCode = hfFromStateUPSCode.Value;
                shipFromAddress.CountryCode       = hfFromCountryUPSCode.Value;
                shipFrom.Address       = shipFromAddress;
                shipFrom.AttentionName = lblFromName.Text.Trim();
                shipFrom.Name          = lblFromName.Text.Trim();
                shipment.ShipFrom      = shipFrom;

                ShipToType        shipTo        = new ShipToType();
                ShipToAddressType shipToAddress = new ShipToAddressType();
                String[]          addressLine1  = { lblToStreet.Text.Trim() };
                shipToAddress.AddressLine       = addressLine1;
                shipToAddress.City              = lblToCity.Text.Trim();
                shipToAddress.PostalCode        = lblToZip.Text.Trim();
                shipToAddress.StateProvinceCode = hfToStateUPSCode.Value;
                shipToAddress.CountryCode       = hfToCountryUPSCode.Value;
                shipTo.Address       = shipToAddress;
                shipTo.AttentionName = lblToName.Text.Trim();
                shipTo.Name          = lblToName.Text.Trim();
                ShipPhoneType shipToPhone = new ShipPhoneType();
                shipToPhone.Number = lblToPhone.Text.Trim();
                shipTo.Phone       = shipToPhone;
                shipment.ShipTo    = shipTo;

                ServiceType service = new ServiceType();
                service.Code     = lblShipService.Text.Trim();
                shipment.Service = service;
                PackageType       package       = new PackageType();
                PackageWeightType packageWeight = new PackageWeightType();
                packageWeight.Weight = lblWeight.Text.Trim();
                ShipUnitOfMeasurementType uom = new ShipUnitOfMeasurementType();
                uom.Code = lblMeasurementType.Text.Trim();
                packageWeight.UnitOfMeasurement = uom;
                package.PackageWeight           = packageWeight;
                PackagingType packType = new PackagingType();
                packType.Code     = lblPackagingType.Text.Trim();
                package.Packaging = packType;
                PackageType[] pkgArray = { package };
                shipment.Package = pkgArray;
                LabelSpecificationType labelSpec      = new LabelSpecificationType();
                LabelStockSizeType     labelStockSize = new LabelStockSizeType();
                labelStockSize.Height    = "6";
                labelStockSize.Width     = "4";
                labelSpec.LabelStockSize = labelStockSize;
                LabelImageFormatType labelImageFormat = new LabelImageFormatType();
                labelImageFormat.Code              = "GIF";
                labelSpec.LabelImageFormat         = labelImageFormat;
                shipmentRequest.LabelSpecification = labelSpec;
                shipmentRequest.Shipment           = shipment;
                System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();

                ShipmentResponse shipmentResponse = shpSvc.ProcessShipment(shipmentRequest);

                iTextSharp.text.Document doc = new iTextSharp.text.Document();
                //Output to File
                string localPath = Server.MapPath("../Labels") + "\\" + shipmentResponse.ShipmentResults.ShipmentIdentificationNumber + ".pdf";
                PdfWriter.GetInstance(doc, new FileStream(localPath, FileMode.Create));
                doc.Open();
                Byte[]       labelBuffer = System.Convert.FromBase64String(shipmentResponse.ShipmentResults.PackageResults[0].ShippingLabel.GraphicImage);
                MemoryStream stream      = new MemoryStream(labelBuffer);

                iTextSharp.text.Image gif = iTextSharp.text.Image.GetInstance(stream);
                gif.RotationDegrees = -90f;
                gif.ScalePercent(50f);
                stream.Close();
                doc.NewPage();
                doc.Add(gif);
                doc.Close();

                MemoryStream output = new MemoryStream();
                doc = new iTextSharp.text.Document();
                PdfWriter.GetInstance(doc, output);
                doc.Open();
                doc.NewPage();
                doc.Add(gif);
                doc.Close();


                (new OrderEntryDAL()).UploadShippingLabel_DAL("Shipping Label", output.ToArray(), "application/pdf", shipmentResponse.ShipmentResults.ShipmentIdentificationNumber + ".pdf", "", labelBuffer.Length, int.Parse(hfOrderId.Value), int.Parse(Session["UserID"].ToString()));

                output.Close();
                return(shipmentResponse.ShipmentResults.ShipmentIdentificationNumber);
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                lblErr.Text = ex.Message;
                MPEPrepare.Show();
                return("");
            }
            catch (Exception ex)
            {
                lblErr.Text = ex.Message;
                MPEPrepare.Show();
                return("");
            }
        }
Example #10
0
        private void RequestRate(UPSSecurity upss, RatePackage rPackage)
        {
            RateRequest rateRequest = new RateRequest();

            UPSRateRef.RequestType request = new UPSRateRef.RequestType();
            String[] requestOption         = { "Shop" };
            request.RequestOption = requestOption;
            rateRequest.Request   = request;

            ShipmentType shipment = new ShipmentType();

            ShipperType shipper        = new ShipperType();
            AddressType shipperAddress = new AddressType();

            shipperAddress.City        = SHIPFROM_CITY;
            shipperAddress.PostalCode  = SHIPFROM_POSTALCODE;
            shipperAddress.CountryCode = SHIPFROM_COUNTRYCODE;
            shipper.Address            = shipperAddress;
            shipment.Shipper           = shipper;

            ShipFromType    shipFrom        = new ShipFromType();
            ShipAddressType shipFromAddress = new ShipAddressType();

            shipFromAddress.City        = SHIPFROM_CITY;
            shipFromAddress.PostalCode  = SHIPFROM_POSTALCODE;
            shipFromAddress.CountryCode = SHIPFROM_COUNTRYCODE;
            shipFrom.Address            = shipFromAddress;
            shipment.ShipFrom           = shipFrom;

            ShipToType        shipTo        = new ShipToType();
            ShipToAddressType shipToAddress = new ShipToAddressType();

            shipToAddress.City        = SHIPTO_CITY;
            shipToAddress.PostalCode  = SHIPTO_POSTALCODE;
            shipToAddress.CountryCode = SHIPTO_COUNTRYCODE;
            shipTo.Address            = shipToAddress;
            shipment.ShipTo           = shipTo;

            PackageType       package       = new PackageType();
            PackageWeightType packageWeight = new PackageWeightType();

            packageWeight.Weight = WEIGHT;
            UPSRateRef.CodeDescriptionType uom = new UPSRateRef.CodeDescriptionType();
            uom.Code = MESUREMENT;
            //uom.Description = MESUREMENT_DISCRIPTION;
            packageWeight.UnitOfMeasurement = uom;
            package.PackageWeight           = packageWeight;
            UPSRateRef.CodeDescriptionType packType = new UPSRateRef.CodeDescriptionType();
            packType.Code         = "02";
            package.PackagingType = packType;
            PackageType[] pkgArray = { package };
            shipment.Package = pkgArray;

            rateRequest.Shipment = shipment;

            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12 | System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11; //This line will ensure the latest security protocol for consuming the web service call.

            RatePortTypeClient client       = new RatePortTypeClient();
            RateResponse       rateResponse = client.ProcessRate(upss, rateRequest);


            foreach (var item in rateResponse.RatedShipment)
            {
                item.Service.Description = ServiceCode.GetName(item.Service.Code);
            }

            rPackage.rateResponse = rateResponse;
        }
Example #11
0
        static void Main()
        {
            try
            {
                FreightShipService freightShipService = new FreightShipService();
                FreightShipRequest freightShipRequest = new FreightShipRequest();
                RequestType        request            = new RequestType();
                String[]           requestOption      = { "1" };
                request.RequestOption      = requestOption;
                freightShipRequest.Request = request;
                ShipmentType shipment = new ShipmentType();

                /** ****************ShipFrom******************************* */
                ShipFromType           shipFrom        = new ShipFromType();
                FreightShipAddressType shipFromAddress = new FreightShipAddressType();
                String[] shipFromAddressLines          = { "ShipFrom address line" };
                shipFromAddress.AddressLine       = shipFromAddressLines;
                shipFromAddress.City              = "Roswell";
                shipFromAddress.StateProvinceCode = "GA";
                shipFromAddress.PostalCode        = "30076";
                shipFromAddress.CountryCode       = "US";
                shipFrom.Address       = shipFromAddress;
                shipFrom.AttentionName = "XYZ Associates";
                shipFrom.Name          = "XYZ Associates";

                FreightShipPhoneType shipFromPhone = new FreightShipPhoneType();
                shipFromPhone.Number    = "123456789";
                shipFromPhone.Extension = "34567";
                shipFrom.Phone          = shipFromPhone;
                shipFrom.EMailAddress   = "*****@*****.**";
                shipment.ShipFrom       = shipFrom;
                /** ****************ShipFrom******************************* */

                shipment.ShipperNumber = "Your shipper number";

                /** ****************ShipTo*************************************** */
                ShipToType             shipTo        = new ShipToType();
                FreightShipAddressType shipToAddress = new FreightShipAddressType();
                String[] shipToAddressLines          = { "ShipTo address line" };
                shipToAddress.AddressLine       = shipToAddressLines;
                shipToAddress.City              = "Roswell";
                shipToAddress.StateProvinceCode = "GA";
                shipToAddress.PostalCode        = "30076";
                shipToAddress.CountryCode       = "US";
                shipTo.Address       = shipFromAddress;
                shipTo.AttentionName = "PQR Associates";
                shipTo.Name          = "PQR";
                FreightShipPhoneType shipToPhone = new FreightShipPhoneType();
                shipToPhone.Number    = "123456789";
                shipToPhone.Extension = "34567";
                shipTo.Phone          = shipToPhone;
                shipTo.EMailAddress   = "*****@*****.**";
                shipment.ShipTo       = shipTo;
                /** ****************ShipTo*************************************** */

                /** ***************PaymentInformationType************************* */
                PaymentInformationType paymentInfo = new PaymentInformationType();
                PayerType payer = new PayerType();
                payer.AttentionName = "Mr. XYZ";
                payer.Name          = "XYZ Associates";
                FreightShipPhoneType payerPhone = new FreightShipPhoneType();
                payerPhone.Number    = "123456789";
                payerPhone.Extension = "3456";
                payer.Phone          = payerPhone;
                payer.ShipperNumber  = "Your Shipper Number";
                payer.EMailAddress   = "*****@*****.**";

                FreightShipAddressType payerAddress = new FreightShipAddressType();
                String[] payerAddressLines          = { "Payer address line" };
                payerAddress.AddressLine       = payerAddressLines;
                payerAddress.City              = "Roswell";
                payerAddress.StateProvinceCode = "GA";
                payerAddress.PostalCode        = "30075";
                payerAddress.CountryCode       = "US";
                payer.Address     = payerAddress;
                paymentInfo.Payer = payer;
                ShipCodeDescriptionType shipBillOption = new ShipCodeDescriptionType();
                shipBillOption.Code               = "10";
                shipBillOption.Description        = "PREPAID";
                paymentInfo.ShipmentBillingOption = shipBillOption;
                shipment.PaymentInformation       = paymentInfo;
                /** ***************PaymentInformationType************************* */

                /** ***************Service************************************** */
                ShipCodeDescriptionType service = new ShipCodeDescriptionType();
                service.Code        = "309";
                service.Description = "UPS Ground Freight";
                shipment.Service    = service;
                /** ***************Service************************************** */

                //Below sample contains dummy data for your reference
                //Please update dummy date as per your requirement
                /** **************Commodity************************************* */
                CommodityType commodity = new CommodityType();
                commodity.NumberOfPieces = "20";
                NMFCCommodityType nmfcCommodity = new NMFCCommodityType();
                nmfcCommodity.PrimeCode = "132680";
                nmfcCommodity.SubCode   = "02";
                commodity.NMFCCommodity = nmfcCommodity;
                commodity.FreightClass  = "77.5";
                ShipCodeDescriptionType packagingType = new ShipCodeDescriptionType();
                packagingType.Code        = "BAG";
                packagingType.Description = "BAG";
                commodity.PackagingType   = packagingType;
                WeightType weight = new WeightType();
                weight.Value = "200";
                FreightShipUnitOfMeasurementType unitOfMeasurement = new FreightShipUnitOfMeasurementType();
                unitOfMeasurement.Code        = "lbs";
                unitOfMeasurement.Description = "pounds";
                weight.UnitOfMeasurement      = unitOfMeasurement;
                commodity.Weight = weight;
                CommodityValueType commodityValue = new CommodityValueType();
                commodityValue.CurrencyCode  = "USD";
                commodityValue.MonetaryValue = "100";
                commodity.CommodityValue     = commodityValue;
                commodity.Description        = "LCD TVS";
                CommodityType[] commodityArray = { commodity };
                shipment.Commodity = commodityArray;
                /** **************Commodity************************************* */

                /** **************HandlingUnitOne************************** */
                HandlingUnitType handlingUnit = new HandlingUnitType();
                handlingUnit.Quantity = "1";
                ShipCodeDescriptionType handlingUnitType = new ShipCodeDescriptionType();
                handlingUnitType.Code        = "SKD";
                handlingUnitType.Description = "SKID";
                handlingUnit.Type            = handlingUnitType;
                shipment.HandlingUnitOne     = handlingUnit;
                /** **************HandlingUnitOne************************** */

                UPSSecurity upss = new UPSSecurity();
                UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken();
                upssSvcAccessToken.AccessLicenseNumber = "Your License";
                upss.ServiceAccessToken = upssSvcAccessToken;
                UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();
                upssUsrNameToken.Username           = "******";
                upssUsrNameToken.Password           = "******";
                upss.UsernameToken                  = upssUsrNameToken;
                freightShipService.UPSSecurityValue = upss;

                freightShipRequest.Shipment = shipment;

                System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
                Console.WriteLine(freightShipRequest);
                FreightShipResponse freightShipResponse = freightShipService.ProcessShipment(freightShipRequest);
                Console.WriteLine("The transaction was a " + freightShipResponse.Response.ResponseStatus.Description);
                Console.WriteLine("The BOLID of the shipment is: " + freightShipResponse.ShipmentResults.BOLID);
                Console.WriteLine("The Shipment number of the shipment is " + freightShipResponse.ShipmentResults.ShipmentNumber);
                Console.ReadKey();
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                Console.WriteLine("");
                Console.WriteLine("---------FreightShip Web Service returns error----------------");
                Console.WriteLine("---------\"Hard\" is user error \"Transient\" is system error----------------");
                Console.WriteLine("SoapException Message= " + ex.Message);
                Console.WriteLine("");
                Console.WriteLine("SoapException Category:Code:Message= " + ex.Detail.LastChild.InnerText);
                Console.WriteLine("");
                Console.WriteLine("SoapException XML String for all= " + ex.Detail.LastChild.OuterXml);
                Console.WriteLine("");
                Console.WriteLine("SoapException StackTrace= " + ex.StackTrace);
                Console.WriteLine("-------------------------");
                Console.WriteLine("");
            }
            catch (System.ServiceModel.CommunicationException ex)
            {
                Console.WriteLine("");
                Console.WriteLine("--------------------");
                Console.WriteLine("CommunicationException= " + ex.Message);
                Console.WriteLine("CommunicationException-StackTrace= " + ex.StackTrace);
                Console.WriteLine("-------------------------");
                Console.WriteLine("");
            }
            catch (Exception ex)
            {
                Console.WriteLine("");
                Console.WriteLine("-------------------------");
                Console.WriteLine(" Generaal Exception= " + ex.Message);
                Console.WriteLine(" Generaal Exception-StackTrace= " + ex.StackTrace);
                Console.WriteLine("-------------------------");
            }
            finally
            {
                Console.ReadKey();
            }
        }
Example #12
0
        static void Main()
        {
            try
            {
                ShipService     shpSvc          = new ShipService();
                ShipmentRequest shipmentRequest = new ShipmentRequest();
                UPSSecurity     upss            = new UPSSecurity();
                UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken();
                upssSvcAccessToken.AccessLicenseNumber = "Your Access License";
                upss.ServiceAccessToken = upssSvcAccessToken;
                UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();
                upssUsrNameToken.Username = "******";
                upssUsrNameToken.Password = "******";
                upss.UsernameToken        = upssUsrNameToken;
                shpSvc.UPSSecurityValue   = upss;
                RequestType request       = new RequestType();
                String[]    requestOption = { "nonvalidate" };
                request.RequestOption   = requestOption;
                shipmentRequest.Request = request;
                ShipmentType shipment = new ShipmentType();
                shipment.Description = "Ship webservice example";
                ShipperType shipper = new ShipperType();
                shipper.ShipperNumber = "Your Shipper Number";
                PaymentInfoType    paymentInfo   = new PaymentInfoType();
                ShipmentChargeType shpmentCharge = new ShipmentChargeType();
                BillShipperType    billShipper   = new BillShipperType();
                billShipper.AccountNumber = "Your Account Number";
                shpmentCharge.BillShipper = billShipper;
                shpmentCharge.Type        = "01";
                ShipmentChargeType[] shpmentChargeArray = { shpmentCharge };
                paymentInfo.ShipmentCharge  = shpmentChargeArray;
                shipment.PaymentInformation = paymentInfo;
                ShipWSSample.ShipWebReference.ShipAddressType shipperAddress = new ShipWSSample.ShipWebReference.ShipAddressType();
                String[] addressLine = { "480 Parkton Plaza" };
                shipperAddress.AddressLine       = addressLine;
                shipperAddress.City              = "Timonium";
                shipperAddress.PostalCode        = "21093";
                shipperAddress.StateProvinceCode = "MD";
                shipperAddress.CountryCode       = "US";
                shipperAddress.AddressLine       = addressLine;
                shipper.Address       = shipperAddress;
                shipper.Name          = "ABC Associates";
                shipper.AttentionName = "ABC Associates";
                ShipPhoneType shipperPhone = new ShipPhoneType();
                shipperPhone.Number = "1234567890";
                shipper.Phone       = shipperPhone;
                shipment.Shipper    = shipper;
                ShipFromType shipFrom = new ShipFromType();
                ShipWSSample.ShipWebReference.ShipAddressType shipFromAddress = new ShipWSSample.ShipWebReference.ShipAddressType();
                String[] shipFromAddressLine = { "Ship From Street" };
                shipFromAddress.AddressLine       = addressLine;
                shipFromAddress.City              = "Timonium";
                shipFromAddress.PostalCode        = "21093";
                shipFromAddress.StateProvinceCode = "MD";
                shipFromAddress.CountryCode       = "US";
                shipFrom.Address       = shipFromAddress;
                shipFrom.AttentionName = "Mr.ABC";
                shipFrom.Name          = "ABC Associates";
                shipment.ShipFrom      = shipFrom;
                ShipToType        shipTo        = new ShipToType();
                ShipToAddressType shipToAddress = new ShipToAddressType();
                String[]          addressLine1  = { "GOERLITZER STR.1" };
                shipToAddress.AddressLine = addressLine1;
                shipToAddress.City        = "Neuss";
                shipToAddress.PostalCode  = "41456";
                shipToAddress.CountryCode = "DE";
                shipTo.Address            = shipToAddress;
                shipTo.AttentionName      = "DEF";
                shipTo.Name = "DEF Associates";
                ShipPhoneType shipToPhone = new ShipPhoneType();
                shipToPhone.Number = "1234567890";
                shipTo.Phone       = shipToPhone;
                shipment.ShipTo    = shipTo;
                ServiceType service = new ServiceType();
                service.Code     = "08";
                shipment.Service = service;

                ShipmentTypeShipmentServiceOptions shpServiceOptions = new ShipmentTypeShipmentServiceOptions();

                /** **** International Forms ***** */
                InternationalFormType internationalForms = new InternationalFormType();

                /** **** Commercial Invoice ***** */
                String[] formTypeList = { "01" };
                internationalForms.FormType = formTypeList;

                /** **** Contacts and Sold To ***** */
                ContactType contacts = new ContactType();

                SoldToType soldTo = new SoldToType();
                soldTo.Option        = "1";
                soldTo.AttentionName = "Sold To Attn Name";
                soldTo.Name          = "Sold To Name";
                PhoneType soldToPhone = new PhoneType();
                soldToPhone.Number    = "1234567890";
                soldToPhone.Extension = "1234";
                soldTo.Phone          = soldToPhone;
                AddressType soldToAddress     = new AddressType();
                String[]    soldToAddressLine = { "34 Queen St" };
                soldToAddress.AddressLine = soldToAddressLine;
                soldToAddress.City        = "Frankfurt";
                soldToAddress.PostalCode  = "60547";
                soldToAddress.CountryCode = "DE";
                soldTo.Address            = soldToAddress;
                contacts.SoldTo           = soldTo;

                internationalForms.Contacts = contacts;

                /** **** Product ***** */
                ProductType product1    = new ProductType();
                String[]    description = { "Product 1" };
                product1.Description       = description;
                product1.CommodityCode     = "111222AA";
                product1.OriginCountryCode = "US";
                UnitType unit = new UnitType();
                unit.Number = "147";
                unit.Value  = "478";
                UnitOfMeasurementType uomProduct = new UnitOfMeasurementType();
                uomProduct.Code        = "BOX";
                uomProduct.Description = "BOX";
                unit.UnitOfMeasurement = uomProduct;
                product1.Unit          = unit;
                ProductWeightType productWeight = new ProductWeightType();
                productWeight.Weight = "10";
                UnitOfMeasurementType uomForWeight = new UnitOfMeasurementType();
                uomForWeight.Code               = "LBS";
                uomForWeight.Description        = "LBS";
                productWeight.UnitOfMeasurement = uomForWeight;
                product1.ProductWeight          = productWeight;
                ProductType[] productList = { product1 };
                internationalForms.Product = productList;

                /** **** InvoiceNumber, InvoiceDate, PurchaseOrderNumber, TermsOfShipment, ReasonForExport, Comments and DeclarationStatement  ***** */
                internationalForms.InvoiceNumber        = "asdf123";
                internationalForms.InvoiceDate          = "20151225";
                internationalForms.PurchaseOrderNumber  = "999jjj777";
                internationalForms.TermsOfShipment      = "CFR";
                internationalForms.ReasonForExport      = "Sale";
                internationalForms.Comments             = "Your Comments";
                internationalForms.DeclarationStatement = "Your Declaration Statement";

                /** **** Discount, FreightCharges, InsuranceCharges, OtherCharges and CurrencyCode  ***** */
                IFChargesType discount = new IFChargesType();
                discount.MonetaryValue      = "100";
                internationalForms.Discount = discount;
                IFChargesType freight = new IFChargesType();
                freight.MonetaryValue             = "50";
                internationalForms.FreightCharges = freight;
                IFChargesType insurance = new IFChargesType();
                insurance.MonetaryValue             = "200";
                internationalForms.InsuranceCharges = insurance;
                OtherChargesType otherCharges = new OtherChargesType();
                otherCharges.MonetaryValue      = "50";
                otherCharges.Description        = "Misc";
                internationalForms.OtherCharges = otherCharges;
                internationalForms.CurrencyCode = "USD";


                shpServiceOptions.InternationalForms = internationalForms;
                shipment.ShipmentServiceOptions      = shpServiceOptions;

                PackageType       package       = new PackageType();
                PackageWeightType packageWeight = new PackageWeightType();
                packageWeight.Weight = "10";
                ShipUnitOfMeasurementType uom = new ShipUnitOfMeasurementType();
                uom.Code = "LBS";
                packageWeight.UnitOfMeasurement = uom;
                package.PackageWeight           = packageWeight;
                PackagingType packType = new PackagingType();
                packType.Code     = "02";
                package.Packaging = packType;
                PackageType[] pkgArray = { package };
                shipment.Package = pkgArray;
                LabelSpecificationType labelSpec      = new LabelSpecificationType();
                LabelStockSizeType     labelStockSize = new LabelStockSizeType();
                labelStockSize.Height    = "6";
                labelStockSize.Width     = "4";
                labelSpec.LabelStockSize = labelStockSize;
                LabelImageFormatType labelImageFormat = new LabelImageFormatType();
                labelImageFormat.Code              = "GIF";
                labelSpec.LabelImageFormat         = labelImageFormat;
                shipmentRequest.LabelSpecification = labelSpec;
                shipmentRequest.Shipment           = shipment;
                Console.WriteLine(shipmentRequest);
                System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
                ShipmentResponse shipmentResponse = shpSvc.ProcessShipment(shipmentRequest);
                Console.WriteLine("The transaction was a " + shipmentResponse.Response.ResponseStatus.Description);
                Console.WriteLine("The 1Z number of the new shipment is " + shipmentResponse.ShipmentResults.ShipmentIdentificationNumber);
                Console.ReadKey();
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                Console.WriteLine("");
                Console.WriteLine("---------Ship Web Service returns error----------------");
                Console.WriteLine("---------\"Hard\" is user error \"Transient\" is system error----------------");
                Console.WriteLine("SoapException Message= " + ex.Message);
                Console.WriteLine("");
                Console.WriteLine("SoapException Category:Code:Message= " + ex.Detail.LastChild.InnerText);
                Console.WriteLine("");
                Console.WriteLine("SoapException XML String for all= " + ex.Detail.LastChild.OuterXml);
                Console.WriteLine("");
                Console.WriteLine("SoapException StackTrace= " + ex.StackTrace);
                Console.WriteLine("-------------------------");
                Console.WriteLine("");
            }
            catch (System.ServiceModel.CommunicationException ex)
            {
                Console.WriteLine("");
                Console.WriteLine("--------------------");
                Console.WriteLine("CommunicationException= " + ex.Message);
                Console.WriteLine("CommunicationException-StackTrace= " + ex.StackTrace);
                Console.WriteLine("-------------------------");
                Console.WriteLine("");
            }
            catch (Exception ex)
            {
                Console.WriteLine("");
                Console.WriteLine("-------------------------");
                Console.WriteLine(" General Exception= " + ex.Message);
                Console.WriteLine(" General Exception-StackTrace= " + ex.StackTrace);
                Console.WriteLine("-------------------------");
            }
            finally
            {
                Console.ReadKey();
            }
        }
Example #13
0
        public void CreateShipmentRequest()
        {
            try
            {
                ShipService     shipService     = new ShipService();
                ShipmentRequest shipmentRequest = new ShipmentRequest();

                // Security
                UPSSecurity upss = new UPSSecurity();
                UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken
                {
                    AccessLicenseNumber = "1CBF3AD5FB29C105"
                };
                upss.ServiceAccessToken = upssSvcAccessToken;
                UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();
                if (radioButton_PLZFT.Checked == true)
                {
                    upssUsrNameToken.Username = "******";
                    upssUsrNameToken.Password = "******";
                }
                else
                {
                    upssUsrNameToken.Username = "******";   // AAC
                    upssUsrNameToken.Password = "******"; // AAC
                }
                upss.UsernameToken           = upssUsrNameToken;
                shipService.UPSSecurityValue = upss;

                // Request
                RequestType request = new RequestType();
                shipmentRequest.Request = request;

                // Request Option
                String[] requestOption = { "nonvalidate" };
                request.RequestOption   = requestOption;
                shipmentRequest.Request = request;

                // Shipment
                ShipmentType shipment = new ShipmentType();
                shipment.Description = "Amazon Gift Card";

                // Shipper
                ShipperType shipper = new ShipperType();
                //shipper.ShipperNumber = "9E6741";
                //if (radioButton_PLZFT.Checked == true)
                shipper.ShipperNumber = "9E6741";     // <- gleich dem im AccessToken !?
                //else
                // 9E6741
                //    shipper.ShipperNumber = "9E6741"; // <- gleich dem im AccessToken !?

                // Payment Info
                PaymentInfoType paymentInfo = new PaymentInfoType();


                ShipmentChargeType shipmentCharge = new ShipmentChargeType();
                shipmentCharge.Type = "01";

                //Payment Info -> BillShipper
                BillShipperType billShipper = new BillShipperType();
                //billShipper.AccountNumber = "9E6741";
                billShipper.AccountNumber  = "587997";
                shipmentCharge.BillShipper = billShipper;


                ShipmentChargeType shipmentCharge2 = new ShipmentChargeType();
                shipmentCharge2.Type = "02";

                // Payment Info -> BillReceiver
                BillReceiverType billReceiver = new BillReceiverType();
                billReceiver.AccountNumber   = "9E6741";
                shipmentCharge2.BillReceiver = billReceiver;

                // Payment Info -> Bill3rdParty
                //BillThirdPartyChargeType bill3rdParty = new BillThirdPartyChargeType();
                //bill3rdParty.AccountNumber = "9E6741";
                //AccountAddressType thirdPartyAddress = new AccountAddressType
                //{
                //    PostalCode = "94032",
                //    CountryCode = "DE"
                //};
                //bill3rdParty.Address = thirdPartyAddress;
                //shipmentCharge2.BillThirdParty = bill3rdParty;



                ShipmentChargeType[] shpmentChargeArray = { shipmentCharge, shipmentCharge2 };
                //ShipmentChargeType[] shpmentChargeArray = { shipmentCharge2 };
                //ShipmentChargeType[] shpmentChargeArray = { shipmentCharge2 };
                paymentInfo.ShipmentCharge = shpmentChargeArray;


                // Shipment -> Payment Information
                shipment.PaymentInformation = paymentInfo;

                // Shipper
                UPS_API.ShipWebReference.ShipAddressType shipperAddress = new UPS_API.ShipWebReference.ShipAddressType();
                String[] addressLine = { textBox_Shipper_AddressLine.Text };
                shipperAddress.AddressLine       = addressLine;
                shipperAddress.City              = textBox_Shipper_City.Text;
                shipperAddress.PostalCode        = textBox_Shipper_PostalCode.Text;
                shipperAddress.StateProvinceCode = textBox_Shipper_StateProvince.Text;
                shipperAddress.CountryCode       = textBox_Shipper_CountryCode.Text;
                shipperAddress.AddressLine       = addressLine;
                shipper.Address       = shipperAddress;
                shipper.Name          = textBox_Shipper_Name.Text;
                shipper.AttentionName = textBox_Shipper_AttentionName.Text;

                ShipPhoneType shipperPhone = new ShipPhoneType();
                shipperPhone.Number = textBox_Shipper_PhoneNumber.Text;
                shipper.Phone       = shipperPhone;

                // Shipment -> Shipper
                shipment.Shipper = shipper;

                // ShipFrom
                ShipFromType shipFrom = new ShipFromType();
                UPS_API.ShipWebReference.ShipAddressType shipFromAddress = new UPS_API.ShipWebReference.ShipAddressType();
                String[] shipFromAddressLine = { textBox_ShipFrom_AddressLine.Text };
                shipFromAddress.AddressLine       = addressLine;
                shipFromAddress.City              = textBox_ShipFrom_City.Text;
                shipFromAddress.PostalCode        = textBox_ShipFrom_PostalCode.Text;
                shipFromAddress.StateProvinceCode = textBox_ShipFrom_StateProvince.Text;
                shipFromAddress.CountryCode       = textBox_ShipFrom_CountryCode.Text;
                shipFrom.Address       = shipFromAddress;
                shipFrom.Name          = textBox_ShipFrom_Name.Text;
                shipFrom.AttentionName = textBox_ShipFrom_AttentionName.Text;
                ShipPhoneType shipFromPhone = new ShipPhoneType();
                shipFromPhone.Number = textBox_ShipFrom_PhoneNumber.Text;
                shipFrom.Phone       = shipFromPhone;

                // Shipment -> ShipFrom
                shipment.ShipFrom = shipFrom;

                // ShipTo
                ShipToType        shipTo        = new ShipToType();
                ShipToAddressType shipToAddress = new ShipToAddressType();
                String[]          addressLine1  = { textBox_ShipTo_AddressLine1.Text };
                shipToAddress.AddressLine       = addressLine1;
                shipToAddress.City              = textBox_ShipTo_City.Text;
                shipToAddress.PostalCode        = textBox_ShipTo_PostalCode.Text;
                shipToAddress.StateProvinceCode = textBox_ShipTo_StateProvince.Text;
                shipToAddress.CountryCode       = textBox_ShiptTo_CountryCode.Text;
                shipTo.Address       = shipToAddress;
                shipTo.Name          = textBox_ShipTo_Name.Text;
                shipTo.AttentionName = textBox_ShipTo_AttentionName.Text;
                ShipPhoneType shipToPhone = new ShipPhoneType();
                shipToPhone.Number = textBox_ShipTo_PhoneNumber.Text;
                shipTo.Phone       = shipToPhone;

                // Shipment -> ShipTo
                shipment.ShipTo = shipTo;

                // Services
                ServiceType service = new ServiceType();
                service.Code = "11";

                //ShipmentServiceOptionsType shipmentServiceOptions = new ShipmentServiceOptionsType();


                // Shipment -> Services
                shipment.Service = service;

                // Package
                PackageType       package       = new PackageType();
                PackageWeightType packageWeight = new PackageWeightType();
                packageWeight.Weight = textBox_Package_Weight.Text;
                ShipUnitOfMeasurementType uom = new ShipUnitOfMeasurementType();
                uom.Code = textBox_Package_MeasurementCode.Text;
                packageWeight.UnitOfMeasurement = uom;
                package.PackageWeight           = packageWeight;
                PackagingType packType = new PackagingType();
                packType.Code     = textBox_Package_TypeCode.Text;
                package.Packaging = packType;
                PackageType[] pkgArray = { package };

                // Shipment -> Package
                shipment.Package = pkgArray;

                // Label
                LabelSpecificationType labelSpec      = new LabelSpecificationType();
                LabelStockSizeType     labelStockSize = new LabelStockSizeType();
                labelStockSize.Height    = "6";
                labelStockSize.Width     = "4";
                labelSpec.LabelStockSize = labelStockSize;
                LabelImageFormatType labelImageFormat = new LabelImageFormatType();
                labelImageFormat.Code      = "PNG";
                labelSpec.LabelImageFormat = labelImageFormat;

                // Shipment Request -> Label
                shipmentRequest.LabelSpecification = labelSpec;

                // Shipment Request -> Shipment
                shipmentRequest.Shipment = shipment;

                // Request -> Execute
                richTextBox1.Text += shipmentRequest + "\r\n";
                System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12 | System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11; //This line will ensure the latest security protocol for consuming the web service call.
                ShipmentResponse shipmentResponse = shipService.ProcessShipment(shipmentRequest);

                string shipmentIdentificationNumber = shipmentResponse.ShipmentResults.ShipmentIdentificationNumber;

                richTextBox1.Text += "The transaction was a " + shipmentResponse.Response.ResponseStatus.Description + "\r\n";
                richTextBox1.Text += "The 1Z number of the new shipment is " + shipmentIdentificationNumber + "\r\n";
                textBox_ShipmentIdentificationNumber.Text = shipmentIdentificationNumber;

                // Save label as PNG
                string base64Label = shipmentResponse.ShipmentResults.PackageResults[0].ShippingLabel.GraphicImage;
                byte[] data        = Convert.FromBase64String(base64Label);
                using (var stream = new MemoryStream(data, 0, data.Length))
                {
                    Image imageLabel = Image.FromStream(stream);
                    pictureBox_Label.Image = imageLabel;
                    pictureBox_Label.Image.RotateFlip(RotateFlipType.Rotate90FlipNone);
                    imageLabel.Save(Path.Combine(@Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "ups_" + shipmentResponse.ShipmentResults.ShipmentIdentificationNumber + ".png"));
                }

                textBox_ErrorLog.ForeColor = Color.LimeGreen;
                textBox_ErrorLog.Text      = "OK";
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                textBox_ErrorLog.ForeColor = Color.Salmon;
                textBox_ErrorLog.Text      = ex.Detail.LastChild.InnerText;

                richTextBox1.Text += "\r\n";
                richTextBox1.Text += "---------Ship Web Service returns error----------------\r\n";
                richTextBox1.Text += "---------\"Hard\" is user error \"Transient\" is system error----------------\r\n";
                richTextBox1.Text += "SoapException Message= " + ex.Message;
                richTextBox1.Text += "\r\n";
                richTextBox1.Text += "SoapException Category:Code:Message= " + ex.Detail.LastChild.InnerText;
                richTextBox1.Text += "\r\n";
                richTextBox1.Text += "SoapException XML String for all= " + ex.Detail.LastChild.OuterXml;
                richTextBox1.Text += "\r\n";
                richTextBox1.Text += "SoapException StackTrace= " + ex.StackTrace;
                richTextBox1.Text += "-------------------------\r\n";
                richTextBox1.Text += "\r\n";
            }
            catch (System.ServiceModel.CommunicationException ex)
            {
                textBox_ErrorLog.ForeColor = Color.Salmon;
                textBox_ErrorLog.Text      = ex.Message;

                richTextBox1.Text += "\r\n";
                richTextBox1.Text += "--------------------\r\n";
                richTextBox1.Text += "CommunicationException= " + ex.Message;
                richTextBox1.Text += "CommunicationException-StackTrace= " + ex.StackTrace;
                richTextBox1.Text += "-------------------------\r\n";
                richTextBox1.Text += "\r\n";
            }
            catch (Exception ex)
            {
                textBox_ErrorLog.ForeColor = Color.Salmon;
                textBox_ErrorLog.Text      = ex.Message;

                richTextBox1.Text += "\r\n";
                richTextBox1.Text += "-------------------------\r\n";
                richTextBox1.Text += " General Exception= " + ex.Message;
                richTextBox1.Text += " General Exception-StackTrace= " + ex.StackTrace;
                richTextBox1.Text += "-------------------------\r\n";
            }
            finally
            {
            }
        }
Example #14
0
        private static void ScheduleShipment()
        {
            try
            {
                ShipService     shpSvc          = new ShipService();
                ShipmentRequest shipmentRequest = new ShipmentRequest();


                // security
                UPSSecurity upss = new UPSSecurity();
                UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken();
                upssSvcAccessToken.AccessLicenseNumber = "4CF6E9703C30E4B6";
                upss.ServiceAccessToken = upssSvcAccessToken;
                UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();
                upssUsrNameToken.Username = "******";
                upssUsrNameToken.Password = "******";
                upss.UsernameToken        = upssUsrNameToken;
                shpSvc.UPSSecurityValue   = upss;

                RequestType request       = new RequestType();
                String[]    requestOption = { "nonvalidate" };
                request.RequestOption   = requestOption;
                shipmentRequest.Request = request;

                ShipmentType shipment = new ShipmentType();
                shipment.Description = "New shipment ...";

                // payment
                PaymentInfoType    paymentInfo   = new PaymentInfoType();
                ShipmentChargeType shpmentCharge = new ShipmentChargeType();
                BillShipperType    billShipper   = new BillShipperType();
                billShipper.AccountNumber = "1YA077";
                shpmentCharge.BillShipper = billShipper;
                shpmentCharge.Type        = "01";
                ShipmentChargeType[] shpmentChargeArray = { shpmentCharge };
                paymentInfo.ShipmentCharge  = shpmentChargeArray;
                shipment.PaymentInformation = paymentInfo;

                // shipper
                ShipperType shipper = new ShipperType();
                shipper.ShipperNumber = "1YA077";
                ShipWSSample.ShipWebReference.ShipAddressType shipperAddress =
                    new ShipWSSample.ShipWebReference.ShipAddressType();
                String[] addressLine = { "88 Foster Crescent" };
                shipperAddress.AddressLine       = addressLine;
                shipperAddress.City              = "Mississauga";
                shipperAddress.PostalCode        = "L5R4A2";
                shipperAddress.StateProvinceCode = "ON";
                shipperAddress.CountryCode       = "CA";
                shipper.Address       = shipperAddress;
                shipper.Name          = "CATO";
                shipper.AttentionName = "Ingram Micro - Mississauga";
                ShipPhoneType shipperPhone = new ShipPhoneType();
                shipperPhone.Number = "1234567890";
                shipper.Phone       = shipperPhone;
                shipment.Shipper    = shipper;

                // ship from
                ShipFromType shipFrom = new ShipFromType();
                ShipWSSample.ShipWebReference.ShipAddressType shipFromAddress =
                    new ShipWSSample.ShipWebReference.ShipAddressType();
                String[] shipFromAddressLine = { "135 Liberty St. Suite 101" };
                shipFromAddress.AddressLine       = addressLine;
                shipFromAddress.City              = "Toronto";
                shipFromAddress.PostalCode        = "M6K1A7";
                shipFromAddress.StateProvinceCode = "ON";
                shipFromAddress.CountryCode       = "CA";
                shipFrom.Address       = shipFromAddress;
                shipFrom.AttentionName = "Mr. Andy Feng";
                shipFrom.Name          = "Kobo Inc.";
                shipment.ShipFrom      = shipFrom;

                // ship to
                ShipToType        shipTo        = new ShipToType();
                ShipToAddressType shipToAddress = new ShipToAddressType();
                String[]          addressLine1  = { "403 Burr Oak Drive" };
                shipToAddress.AddressLine       = addressLine1;
                shipToAddress.City              = "Oswego";
                shipToAddress.PostalCode        = "60543";
                shipToAddress.StateProvinceCode = "IL";
                shipToAddress.CountryCode       = "US";
                shipTo.Address       = shipToAddress;
                shipTo.AttentionName = "Mr. John Smith";
                shipTo.Name          = "DEF Associates";
                ShipPhoneType shipToPhone = new ShipPhoneType();
                shipToPhone.Number = "(905) 123-1234";
                shipTo.Phone       = shipToPhone;
                shipment.ShipTo    = shipTo;

                //service
                ServiceType service = new ServiceType();
                //service.Code = "01"; // next day air
                service.Code     = "11";//ups standard
                shipment.Service = service;


                // package
                PackageType       package       = new PackageType();
                PackageWeightType packageWeight = new PackageWeightType();
                packageWeight.Weight = "10";
                ShipUnitOfMeasurementType uom = new ShipUnitOfMeasurementType();
                uom.Code = "LBS";
                packageWeight.UnitOfMeasurement = uom;
                package.PackageWeight           = packageWeight;
                PackagingType packType = new PackagingType();
                packType.Code     = "02";
                package.Packaging = packType;
                // package 2
                PackageType       package2       = new PackageType();
                PackageWeightType packageWeight2 = new PackageWeightType();
                packageWeight2.Weight = "9";
                ShipUnitOfMeasurementType uom2 = new ShipUnitOfMeasurementType();
                uom2.Code = "LBS";
                packageWeight2.UnitOfMeasurement = uom2;
                package2.PackageWeight           = packageWeight2;
                PackagingType packType2 = new PackagingType();
                packType2.Code     = "02";
                package2.Packaging = packType2;

                PackageType[] pkgArray = { package, package2 };
                shipment.Package = pkgArray;

                // add delivery confirmation for package level
                //PackageServiceOptionsType packageServiceOptions = new PackageServiceOptionsType();
                //package.PackageServiceOptions = packageServiceOptions;
                //package2.PackageServiceOptions = packageServiceOptions;
                //DeliveryConfirmationType deliveryConfirmation = new DeliveryConfirmationType();
                ////Service DCIS Type, The type of confirmation required upon delivery of the package.
                //deliveryConfirmation.DCISType = "2"; //Delivery Confirmation Signature Required
                //// The delivery confirmation control number that confirms the package's delivery.
                ////deliveryConfirmation.DCISNumber = "xxxxxxxx";
                //packageServiceOptions.DeliveryConfirmation = deliveryConfirmation;

                // label
                LabelSpecificationType labelSpec      = new LabelSpecificationType();
                LabelStockSizeType     labelStockSize = new LabelStockSizeType();
                labelStockSize.Height    = "1";
                labelStockSize.Width     = "1";
                labelSpec.LabelStockSize = labelStockSize;
                LabelImageFormatType labelImageFormat = new LabelImageFormatType();
                //// for zpl
                //labelStockSize.Height = "6";
                //labelStockSize.Width = "4";
                //labelImageFormat.Code = "ZPL";
                // for gif
                labelImageFormat.Code              = "GIF";
                labelSpec.LabelImageFormat         = labelImageFormat;
                shipmentRequest.LabelSpecification = labelSpec;

                shipmentRequest.Shipment = shipment;

                // label
                ShipmentTypeShipmentServiceOptions options = new ShipmentTypeShipmentServiceOptions();
                //options.LabelDelivery = new LabelDeliveryType();
                shipment.ShipmentServiceOptions = options;

                // international form for paperless invoice
                InternationalFormType internationalForm = new InternationalFormType();
                internationalForm.AdditionalDocumentIndicator = null;
                internationalForm.ReasonForExport             = "SALE";
                internationalForm.ExportDate       = DateTime.Now.ToString("yyyyMMdd");
                internationalForm.ExportingCarrier = "UPS";
                internationalForm.InvoiceDate      = DateTime.Now.ToString("yyyyMMdd");
                internationalForm.CurrencyCode     = "CAD";
                internationalForm.FormType         = new String[] { "01" };
                internationalForm.Contacts         = new ContactType()
                {
                    SoldTo = new SoldToType()
                    {
                        Name    = "andy",
                        Address = new AddressType()
                        {
                            AddressLine = new String[] { "box 40" }, City = "Tornnn", CountryCode = "US", PostalCode = "M1S2S5", StateProvinceCode = "ON"
                        }
                    }
                };

                internationalForm.Product = new ProductType[]
                {
                    new ProductType()
                    {
                        ProducerInfo = "product1", Description = new String[] { "1233" }, Unit = new UnitType()
                        {
                            Number = "1", UnitOfMeasurement = new UnitOfMeasurementType()
                            {
                                Code = "BG"
                            }, Value = "1"
                        }, OriginCountryCode = "CA", CommodityCode = "123456", NumberOfPackagesPerCommodity = "1", ProductWeight = new ProductWeightType()
                        {
                            UnitOfMeasurement = new UnitOfMeasurementType()
                            {
                                Code = "LBS"
                            }, Weight = "12"
                        }
                    }
                };
                options.InternationalForms = internationalForm;
                // delivery confirmation for shipment level
                DeliveryConfirmationType deliveryConfirmation = new DeliveryConfirmationType();
                deliveryConfirmation.DCISType = "2";
                options.DeliveryConfirmation  = deliveryConfirmation;

                Console.WriteLine(shipmentRequest);
                System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();

                // response
                ShipmentResponse shipmentResponse = shpSvc.ProcessShipment(shipmentRequest);

                Console.WriteLine("The transaction was a " + shipmentResponse.Response.ResponseStatus.Description);

                // output label base64 characters
                string byteFileName = @"c:\Users\afeng\Pictures\label.txt";
                using (FileStream fs = new FileStream(byteFileName, FileMode.Create, FileAccess.ReadWrite))
                {
                    using (BinaryWriter sw = new BinaryWriter(fs))
                    {
                        sw.Write(shipmentResponse.ShipmentResults.PackageResults.FirstOrDefault().ShippingLabel.GraphicImage);
                    }
                }

                // output label image
                string filename = @"c:\Users\afeng\Pictures\label.gif";
                byte[] byteLabel;

                using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite))
                {
                    using (BinaryWriter writer = new BinaryWriter(fs))
                    {
                        byteLabel =
                            Convert.FromBase64String(
                                shipmentResponse.ShipmentResults.PackageResults.FirstOrDefault().ShippingLabel.GraphicImage);
                        writer.Write(byteLabel);
                    }
                }


                // output label html page
                string htmlFilename = @"c:\Users\afeng\Pictures\label.html";
                byte[] htmlByteLabel;

                using (FileStream fs = new FileStream(htmlFilename, FileMode.Create, FileAccess.ReadWrite))
                {
                    using (BinaryWriter writer = new BinaryWriter(fs))
                    {
                        htmlByteLabel =
                            Convert.FromBase64String(
                                shipmentResponse.ShipmentResults.PackageResults.FirstOrDefault().ShippingLabel.HTMLImage);
                        writer.Write(htmlByteLabel);
                    }
                }

                // binary serialize
                Stream          stream     = File.Open(@"c:\Users\afeng\Pictures\data.dat", FileMode.Create);
                BinaryFormatter bformatter = new BinaryFormatter();
                Console.WriteLine("Writing binary serialize Information");
                bformatter.Serialize(stream, shipmentResponse);
                stream.Close();

                // xml serialize
                Stream        requetStream      = File.Open(@"c:\Users\afeng\Pictures\request.xml", FileMode.Create);
                XmlSerializer requestSerializer = new XmlSerializer(shipment.GetType());
                Console.WriteLine("Writing xml serialize Information");
                requestSerializer.Serialize(requetStream, shipment);
                requetStream.Close();
                Stream        responseStream = File.Open(@"c:\Users\afeng\Pictures\response.xml", FileMode.Create);
                XmlSerializer serializer     = new XmlSerializer(shipmentResponse.GetType());
                Console.WriteLine("Writing xml serialize Information");
                serializer.Serialize(responseStream, shipmentResponse);
                responseStream.Close();

                // resize picture
                int width  = (int)(8.25 * 72);
                int height = (int)(4.25 * 72);

                // resize picture 1
                Bitmap imgIn  = new Bitmap(filename);
                double y      = imgIn.Height;
                double x      = imgIn.Width;
                double factor = 1;
                if (width > 0)
                {
                    factor = width / x;
                }
                else if (height > 0)
                {
                    factor = height / y;
                }
                System.IO.MemoryStream outStream = new System.IO.MemoryStream();
                Bitmap imgOut = new Bitmap((int)(x * factor), (int)(y * factor));

                // Set DPI of image (xDpi, yDpi)
                //imgOut.SetResolution(72, 72);
                imgOut.SetResolution(96, 96);

                Graphics g = Graphics.FromImage(imgOut);
                g.Clear(Color.White);
                g.DrawImage(imgIn, new Rectangle(0, 0, (int)(factor * x), (int)(factor * y)),
                            new Rectangle(0, 0, (int)x, (int)y), GraphicsUnit.Pixel);

                imgOut.Save(outStream, ImageFormat.Gif);
                string       filename2 = @"c:\Users\afeng\Pictures\label2.gif";
                FileStream   fs2       = new FileStream(filename2, FileMode.Create, FileAccess.ReadWrite);
                BinaryWriter writer2   = new BinaryWriter(fs2);
                writer2.Write(outStream.ToArray());
                writer2.Close();


                // resize picture 2
                //Creates a new Bitmap as the size of the window
                Bitmap bmp = new Bitmap(width, height);
                //Creates a new graphics to handle the image that is coming from the stream
                Graphics g2 = Graphics.FromImage((Image)bmp);
                g2.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                g2.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                //Resizes the image from the stream to fit our windows
                Bitmap imgIn2 = new Bitmap(filename);
                g2.DrawImage(imgIn2, 0, 0, width, height);
                string                 filename3  = @"c:\Users\afeng\Pictures\label3.gif";
                FileStream             fs3        = new FileStream(filename3, FileMode.Create, FileAccess.ReadWrite);
                BinaryWriter           writer3    = new BinaryWriter(fs3);
                System.IO.MemoryStream outStream2 = new System.IO.MemoryStream();
                bmp.Save(outStream2, ImageFormat.Gif);
                writer3.Write(outStream2.ToArray());
                writer3.Close();

                // resize picture 3
                Bitmap newImage = new Bitmap(width, height);
                using (Graphics gr = Graphics.FromImage(newImage))
                {
                    gr.SmoothingMode = SmoothingMode.HighQuality;
                    //gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    gr.InterpolationMode = InterpolationMode.NearestNeighbor;
                    gr.PixelOffsetMode   = PixelOffsetMode.HighQuality;
                    gr.DrawImage(new Bitmap(filename), new Rectangle(0, 0, width, height));
                    string     filename4 = @"c:\Users\afeng\Pictures\label4.gif";
                    FileStream fs4       = new FileStream(filename4, FileMode.Create, FileAccess.ReadWrite);
                    //newImage.Save(filename4, System.Drawing.Imaging.ImageFormat.Gif);
                    BinaryWriter           writer4    = new BinaryWriter(fs4);
                    System.IO.MemoryStream outStream4 = new System.IO.MemoryStream();
                    newImage.Save(outStream4, ImageFormat.Gif);
                    writer4.Write(outStream4.ToArray());
                    writer4.Close();
                }

                // resize picture 4
                ImageHandler ih        = new ImageHandler();
                string       filename5 = @"c:\Users\afeng\Pictures\label5.jpg";
                MemoryStream stream5   = new MemoryStream();
                stream5.Write(byteLabel, 0, byteLabel.Length);
                //Bitmap b = new Bitmap(filename);
                Bitmap b = new Bitmap(stream5);
                ih.Save(b, width, height, 100, filename5);


                Console.WriteLine("The 1Z number of the new shipment is " +
                                  shipmentResponse.ShipmentResults.ShipmentIdentificationNumber);
                Console.ReadKey();
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                Console.WriteLine("");
                Console.WriteLine("---------Ship Web Service returns error----------------");
                Console.WriteLine("---------\"Hard\" is user error \"Transient\" is system error----------------");
                Console.WriteLine("SoapException Message= " + ex.Message);
                Console.WriteLine("");
                Console.WriteLine("SoapException Category:Code:Message= " + ex.Detail.LastChild.InnerText);
                Console.WriteLine("");
                Console.WriteLine("SoapException XML String for all= " + ex.Detail.LastChild.OuterXml);
                Console.WriteLine("");
                Console.WriteLine("SoapException StackTrace= " + ex.StackTrace);
                Console.WriteLine("-------------------------");
                Console.WriteLine("");
            }
            catch (System.ServiceModel.CommunicationException ex)
            {
                Console.WriteLine("");
                Console.WriteLine("--------------------");
                Console.WriteLine("CommunicationException= " + ex.Message);
                Console.WriteLine("CommunicationException-StackTrace= " + ex.StackTrace);
                Console.WriteLine("-------------------------");
                Console.WriteLine("");
            }
            catch (Exception ex)
            {
                Console.WriteLine("");
                Console.WriteLine("-------------------------");
                Console.WriteLine(" General Exception= " + ex.Message);
                Console.WriteLine(" General Exception-StackTrace= " + ex.StackTrace);
                Console.WriteLine("-------------------------");
            }
            finally
            {
                Console.ReadKey();
            }
        }
Example #15
0
        private FreightRateRequest BuildUPSFreightRateRequestForShipment(IShipment shipment)
        {
            FreightRateRequest freightRateRequest = new FreightRateRequest();
            RequestType        request            = new RequestType();

            String[] requestOption = { "1" }; //Ground
            request.RequestOption      = requestOption;
            freightRateRequest.Request = request;

            /** ****************ShipFrom******************************* */
            ShipFromType shipFrom        = new ShipFromType();
            AddressType  shipFromAddress = new AddressType();

            String[] shipFromAddressLines = { shipment.SourceAddress.Street, shipment.SourceAddress.Street2 };
            shipFromAddress.AddressLine       = shipFromAddressLines;
            shipFromAddress.City              = shipment.SourceAddress.City;
            shipFromAddress.StateProvinceCode = shipment.SourceAddress.RegionBvin;
            shipFromAddress.PostalCode        = shipment.SourceAddress.PostalCode;
            shipFromAddress.CountryCode       = shipment.SourceAddress.CountryData.IsoCode;
            shipFrom.Address = shipFromAddress;

            freightRateRequest.ShipFrom = shipFrom;
            /** ****************ShipFrom******************************* */

            /** ****************ShipTo*************************************** */
            ShipToType  shipTo        = new ShipToType();
            AddressType shipToAddress = new AddressType();

            String[] shipToAddressLines = { shipment.DestinationAddress.Street, shipment.DestinationAddress.Street2 };
            shipToAddress.AddressLine       = shipToAddressLines;
            shipToAddress.City              = shipment.DestinationAddress.City;
            shipToAddress.StateProvinceCode = shipment.DestinationAddress.RegionBvin;
            shipToAddress.PostalCode        = shipment.DestinationAddress.PostalCode;
            shipToAddress.CountryCode       = shipment.DestinationAddress.CountryData.IsoCode;
            shipTo.Address = shipToAddress;


            freightRateRequest.ShipTo = shipTo;
            /** ****************ShipTo*************************************** */

            /** ***************PaymentInformationType************************* */

            PaymentInformationType paymentInfo = new PaymentInformationType();
            PayerType payer = new PayerType();

            payer.AttentionName = Settings.PayerName; //Required PayerName
            payer.Name          = Settings.PayerName;


            AddressType payerAddress = new AddressType();

            String[] payerAddressLines = { shipment.DestinationAddress.Street };
            payerAddress.AddressLine       = payerAddressLines;
            payerAddress.City              = shipment.DestinationAddress.City;
            payerAddress.StateProvinceCode = shipment.DestinationAddress.RegionBvin;
            payerAddress.PostalCode        = shipment.DestinationAddress.PostalCode;
            payerAddress.CountryCode       = shipment.DestinationAddress.CountryData.IsoCode;
            payer.Address     = payerAddress;
            paymentInfo.Payer = payer;

            RateCodeDescriptionType shipBillOption = new RateCodeDescriptionType();

            shipBillOption.Code                   = ((int)GlobalSettings.BillingOption).ToString();
            shipBillOption.Description            = GlobalSettings.BillingOption.ToString();
            paymentInfo.ShipmentBillingOption     = shipBillOption;
            freightRateRequest.PaymentInformation = paymentInfo;

            /** ***************PaymentInformationType************************* */

            /** ***************Service************************************** */
            RateCodeDescriptionType service = new RateCodeDescriptionType();

            service.Code               = Settings.ServiceCodeFilter[0].Code;
            service.Description        = Settings.ServiceCodeFilter[0].DisplayName;
            freightRateRequest.Service = service;
            /** ***************Service************************************** */

            /** **************HandlingUnitOne************************************* */
            HandlingUnitType handUnitType = new HandlingUnitType();

            handUnitType.Quantity = shipment.Items.Count.ToString();
            RateCodeDescriptionType rateCodeDescType = new RateCodeDescriptionType();

            rateCodeDescType.Code              = GlobalSettings.HandleOneUnitType.ToString();
            rateCodeDescType.Description       = GlobalSettings.HandleOneUnitType.ToString();
            handUnitType.Type                  = rateCodeDescType;
            freightRateRequest.HandlingUnitOne = handUnitType;
            /** **************HandlingUnitOne************************************* */

            /** **************Commodity************************************* */
            // Optimize Packages for Weight
            var optimizedPackages = OptimizeSingleGroup(shipment);
            var ignoreDimensions  = GlobalSettings.IgnoreDimensions;

            List <CommodityType> commodityArray = new List <CommodityType>();

            foreach (var pak in optimizedPackages)
            {
                //Prepare Commodity Item
                CommodityType commodity = WriteSingleCommidityPackage(pak, ignoreDimensions);
                commodityArray.Add(commodity);
            }
            freightRateRequest.Commodity = commodityArray.ToArray();

            /** **************Commodity************************************* */

            return(freightRateRequest);
        }
Example #16
0
        static void Main()
        {
            try
            {
                FreightRateService freightRateService = new FreightRateService();
                FreightRateRequest freightRateRequest = new FreightRateRequest();
                RequestType        request            = new RequestType();
                String[]           requestOption      = { "RateChecking Option" };
                request.RequestOption      = requestOption;
                freightRateRequest.Request = request;

                /** ****************ShipFrom******************************* */
                ShipFromType shipFrom             = new ShipFromType();
                AddressType  shipFromAddress      = new AddressType();
                String[]     shipFromAddressLines = { "ShipFrom address" };
                shipFromAddress.AddressLine       = shipFromAddressLines;
                shipFromAddress.City              = "ShipFrom city";
                shipFromAddress.StateProvinceCode = "ShipFrom state province code";
                shipFromAddress.PostalCode        = "ShipFrom postal code";
                shipFromAddress.CountryCode       = "ShipFrom country code";
                shipFrom.Address            = shipFromAddress;
                shipFrom.AttentionName      = "ShipFrom attention name";
                shipFrom.Name               = "ShipFrom Name";
                freightRateRequest.ShipFrom = shipFrom;
                /** ****************ShipFrom******************************* */

                /** ****************ShipTo*************************************** */
                ShipToType  shipTo             = new ShipToType();
                AddressType shipToAddress      = new AddressType();
                String[]    shipToAddressLines = { "ShipTo address line" };
                shipToAddress.AddressLine       = shipToAddressLines;
                shipToAddress.City              = "ShipTo city";
                shipToAddress.StateProvinceCode = "ShipTo state province code";
                shipToAddress.PostalCode        = "ShipTo postal code";
                shipToAddress.CountryCode       = "ShipTo country code";
                shipTo.Address            = shipToAddress;
                shipTo.AttentionName      = "ShipTo attention name";
                shipTo.Name               = "ShipTo Name";
                freightRateRequest.ShipTo = shipTo;
                /** ****************ShipTo*************************************** */

                /** ***************PaymentInformationType************************* */
                PaymentInformationType paymentInfo = new PaymentInformationType();
                PayerType payer = new PayerType();
                payer.AttentionName = "Payer attention name";
                payer.Name          = "Payer name";
                payer.ShipperNumber = "Payer shipper number";
                AddressType payerAddress      = new AddressType();
                String[]    payerAddressLines = { "Payer address line" };
                payerAddress.AddressLine       = payerAddressLines;
                payerAddress.City              = "Payer city";
                payerAddress.StateProvinceCode = "Payer state province code";
                payerAddress.PostalCode        = "Payer postal code";
                payerAddress.CountryCode       = "Payer country code";
                payer.Address     = payerAddress;
                paymentInfo.Payer = payer;
                RateCodeDescriptionType shipBillOption = new RateCodeDescriptionType();
                shipBillOption.Code                   = "Ship bill option";
                shipBillOption.Description            = "Ship bill description";
                paymentInfo.ShipmentBillingOption     = shipBillOption;
                freightRateRequest.PaymentInformation = paymentInfo;
                /** ***************PaymentInformationType************************* */

                //Below code use dummy data for referenced. Please update as required


                /** ***************Service************************************** */
                RateCodeDescriptionType service = new RateCodeDescriptionType();
                service.Code               = "309";
                service.Description        = "UPS Ground Freight";
                freightRateRequest.Service = service;
                /** ***************Service************************************** */


                /** **************Commodity************************************* */
                CommodityType      commodity = new CommodityType();
                CommodityValueType commValue = new CommodityValueType();
                commValue.CurrencyCode   = "USD";
                commValue.MonetaryValue  = "5670";
                commodity.CommodityValue = commValue;
                commodity.NumberOfPieces = "20";

                RateCodeDescriptionType packagingType = new RateCodeDescriptionType();
                packagingType.Code        = "BAG";
                packagingType.Description = "BAG";
                commodity.PackagingType   = packagingType;
                WeightType            weight            = new WeightType();
                UnitOfMeasurementType unitOfMeasurement = new UnitOfMeasurementType();
                unitOfMeasurement.Code        = "LBS";
                unitOfMeasurement.Description = "Pounds";
                weight.UnitOfMeasurement      = unitOfMeasurement;
                weight.Value          = "200";
                commodity.Weight      = weight;
                commodity.Description = "LCD TVS";

                CommodityValueType commodityValue = new CommodityValueType();
                commodityValue.CurrencyCode  = "USD";
                commodityValue.MonetaryValue = "100";
                commodity.CommodityValue     = commodityValue;
                commodity.Description        = "LCD TVS";
                commodity.FreightClass       = "60";
                CommodityType[] commodityArray = { commodity };
                freightRateRequest.Commodity = commodityArray;
                /** **************Commodity************************************* */


                /** **************HandlingUnitOne************************************* */
                HandlingUnitType handUnitType = new HandlingUnitType();
                handUnitType.Quantity = "1";
                RateCodeDescriptionType rateCodeDescType = new RateCodeDescriptionType();
                rateCodeDescType.Code              = "SKD";
                rateCodeDescType.Description       = "SKID";
                handUnitType.Type                  = rateCodeDescType;
                freightRateRequest.HandlingUnitOne = handUnitType;

                /** **************HandlingUnitOne************************************* */


                UPSSecurity upss = new UPSSecurity();
                UPSSecurityServiceAccessToken upsSvcToken = new UPSSecurityServiceAccessToken();
                upsSvcToken.AccessLicenseNumber = "Your License Number";
                upss.ServiceAccessToken         = upsSvcToken;
                UPSSecurityUsernameToken upsSecUsrnameToken = new UPSSecurityUsernameToken();
                upsSecUsrnameToken.Username         = "******";
                upsSecUsrnameToken.Password         = "******";
                upss.UsernameToken                  = upsSecUsrnameToken;
                freightRateService.UPSSecurityValue = upss;

                System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
                Console.WriteLine(freightRateRequest);
                FreightRateResponse freightRateResponse = freightRateService.ProcessFreightRate(freightRateRequest);
                Console.WriteLine("Response code: " + freightRateResponse.Response.ResponseStatus.Code);
                Console.WriteLine("Response description: " + freightRateResponse.Response.ResponseStatus.Description);
                Console.ReadKey();
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                Console.WriteLine("");
                Console.WriteLine("---------Freight Rate Web Service returns error----------------");
                Console.WriteLine("---------\"Hard\" is user error \"Transient\" is system error----------------");
                Console.WriteLine("SoapException Message= " + ex.Message);
                Console.WriteLine("");
                Console.WriteLine("SoapException Category:Code:Message= " + ex.Detail.LastChild.InnerText);
                Console.WriteLine("");
                Console.WriteLine("SoapException XML String for all= " + ex.Detail.LastChild.OuterXml);
                Console.WriteLine("");
                Console.WriteLine("SoapException StackTrace= " + ex.StackTrace);
                Console.WriteLine("-------------------------");
                Console.WriteLine("");
            }
            catch (System.ServiceModel.CommunicationException ex)
            {
                Console.WriteLine("");
                Console.WriteLine("--------------------");
                Console.WriteLine("CommunicationException= " + ex.Message);
                Console.WriteLine("CommunicationException-StackTrace= " + ex.StackTrace);
                Console.WriteLine("-------------------------");
                Console.WriteLine("");
            }
            catch (Exception ex)
            {
                Console.WriteLine("");
                Console.WriteLine("-------------------------");
                Console.WriteLine(" General Exception= " + ex.Message);
                Console.WriteLine(" General Exception-StackTrace= " + ex.StackTrace);
                Console.WriteLine("-------------------------");
            }
            finally
            {
                Console.ReadKey();
            }
        }
Example #17
0
        private RateRequest CreateRateRequest(RateService rate)
        {
            RateRequest rateRequest = new RateRequest();
            UPSSecurity upss = new UPSSecurity();
            UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken();
            upssSvcAccessToken.AccessLicenseNumber = AccessKey;
            upss.ServiceAccessToken = upssSvcAccessToken;

            UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();
            upssUsrNameToken.Username = UserName;
            upssUsrNameToken.Password = Password;
            upss.UsernameToken = upssUsrNameToken;
            rate.UPSSecurityValue = upss;

            RequestType request = new RequestType();
            String[] requestOption = { "Shop" };
            request.RequestOption = requestOption;
            rateRequest.Request = request;

            ShipmentType shipment = new ShipmentType();

            ShipperType shipper = new ShipperType();
            //shipper.ShipperNumber = "ISUS01";
            AddressType shipperAddress = new AddressType();
            String[] addressLine = { "Shipper\'s address line" };
            shipperAddress.AddressLine = addressLine;
            shipperAddress.City = "Shipper\'s city";
            shipperAddress.PostalCode = PostalCodeFrom;
            //shipperAddress.StateProvinceCode = UpsItem.CountryCode;
            shipperAddress.CountryCode = CountryCodeFrom;
            shipperAddress.AddressLine = addressLine;
            shipper.Address = shipperAddress;
            shipment.Shipper = shipper;

            ShipFromType shipFrom = new ShipFromType();
            AddressType shipFromAddress = new AddressType();
            shipFromAddress.AddressLine = addressLine;
            shipFromAddress.City = "ShipFrom city";
            shipFromAddress.PostalCode = PostalCodeFrom;
            //shipFromAddress.StateProvinceCode = "GA";
            shipFromAddress.CountryCode = CountryCodeFrom;
            shipFrom.Address = shipFromAddress;
            shipment.ShipFrom = shipFrom;

            ShipToType shipTo = new ShipToType();
            ShipToAddressType shipToAddress = new ShipToAddressType();
            String[] addressLine1 = { AddressTo };
            shipToAddress.AddressLine = addressLine1;
            shipToAddress.City = CityTo;
            shipToAddress.PostalCode = PostalCodeTo;
            shipToAddress.StateProvinceCode = StateTo;
            shipToAddress.CountryCode = CountryCodeTo;
            shipTo.Address = shipToAddress;
            shipment.ShipTo = shipTo;

            //CodeDescriptionType service = new CodeDescriptionType();
            //service.Code = "02";
            //shipment.Service = service;
            float weight = MeasureUnits.ConvertWeight(ShoppingCart.TotalShippingWeight, MeasureUnits.WeightUnit.Kilogramm, MeasureUnits.WeightUnit.Pound);

            var data = new List<PackageType>();
            if (!IsPackageTooHeavy(weight))
            {

                PackageType package = new PackageType();
                PackageWeightType packageWeight = new PackageWeightType();
                packageWeight.Weight = weight.ToString("F3").Replace(',', '.');

                CodeDescriptionType uom = new CodeDescriptionType();
                uom.Code = "LBS";
                uom.Description = "Pounds";
                packageWeight.UnitOfMeasurement = uom;
                package.PackageWeight = packageWeight;

                CodeDescriptionType packType = new CodeDescriptionType();
                packType.Code = "02";
                package.PackagingType = packType;
                data.Add(package);
            }
            else
            {
                int totalPackages = 1;
                int totalPackagesWeights = 1;
                if (IsPackageTooHeavy(weight))
                {
                    totalPackagesWeights = SQLDataHelper.GetInt(Math.Ceiling(weight / MaxPackageWeight));
                }

                totalPackages = totalPackagesWeights;
                if (totalPackages == 0)
                    totalPackages = 1;

                float weight2 = weight / totalPackages;

                if (weight2 < 1)
                    weight2 = 1;
                for (int i = 0; i < totalPackages; i++)
                {
                    PackageType package = new PackageType();
                    PackageWeightType packageWeight = new PackageWeightType();
                    packageWeight.Weight = weight2.ToString("F3");

                    CodeDescriptionType uom = new CodeDescriptionType();
                    uom.Code = "LBS";
                    uom.Description = "Pounds";
                    packageWeight.UnitOfMeasurement = uom;
                    package.PackageWeight = packageWeight;

                    CodeDescriptionType packType = new CodeDescriptionType();
                    packType.Code = GetPackagingTypeCode(PackagingType);
                    package.PackagingType = packType;
                    data.Add(package);
                }
            }

            PackageType[] pkgArray = data.ToArray();
            shipment.Package = pkgArray;
            rateRequest.Shipment = shipment;

            CodeDescriptionType pckup = new CodeDescriptionType() { Code = GetPickupTypeCode(PickupType) };
            rateRequest.PickupType = pckup;

            CodeDescriptionType ccustomer = new CodeDescriptionType() { Code = GetCustomerClassificationCode(CustomerType) };
            rateRequest.CustomerClassification = ccustomer;

            System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();

            return rateRequest;
        }