private void AddUserNameToken(UPSSecurity upss) { var upssUsrNameToken = new UPSSecurityUsernameToken(); upssUsrNameToken.Username = UserName; upssUsrNameToken.Password = Pasword; upss.UsernameToken = upssUsrNameToken; }
static void Main(string[] args) { try { LBRecovery lb_recovery = new LBRecovery(); LabelRecoveryRequest label_recovery_request = new LabelRecoveryRequest(); 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; lb_recovery.UPSSecurityValue = upss; RequestType request = new RequestType(); label_recovery_request.Request = request; label_recovery_request.TrackingNumber = "Your tracking number"; LabelRecoveryResponse label_recovery_response = lb_recovery.ProcessLabelRecovery(label_recovery_request); LabelImageType image = (LabelImageType)label_recovery_response.Items[0]; Console.WriteLine("Image Base64:\n " + image.GraphicImage); Console.ReadKey(); } catch (System.Web.Services.Protocols.SoapException ex) { Console.WriteLine(""); Console.WriteLine("---------LBRecovery 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 (Exception ex) { Console.WriteLine(""); Console.WriteLine("-------------------------"); Console.WriteLine(" General Exception= " + ex.Message); Console.WriteLine(" General Exception-StackTrace= " + ex.StackTrace); Console.WriteLine("-------------------------"); } finally { Console.ReadKey(); } }
/// <summary> /// Gets all events for a tracking number. /// </summary> /// <param name="trackingNumber">The tracking number to track</param> /// <returns>List of Shipment Events.</returns> public virtual IList <ShipmentStatusEvent> GetShipmentEvents(string trackingNumber) { if (string.IsNullOrEmpty(trackingNumber)) { return(new List <ShipmentStatusEvent>()); } var result = new List <ShipmentStatusEvent>(); try { //use try-catch to ensure exception won't be thrown if web service is not available var track = new TrackService(); var tr = new TrackRequest(); var upss = new UPSSecurity(); var upssSvcAccessToken = new UPSSecurityServiceAccessToken(); upssSvcAccessToken.AccessLicenseNumber = _upsSettings.AccessKey; upss.ServiceAccessToken = upssSvcAccessToken; var upssUsrNameToken = new UPSSecurityUsernameToken(); upssUsrNameToken.Username = _upsSettings.Username; upssUsrNameToken.Password = _upsSettings.Password; upss.UsernameToken = upssUsrNameToken; track.UPSSecurityValue = upss; var request = new RequestType(); string[] requestOption = { "15" }; request.RequestOption = requestOption; tr.Request = request; tr.InquiryNumber = trackingNumber; System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate { return(true); }; var trackResponse = track.ProcessTrack(tr); result.AddRange(trackResponse.Shipment.SelectMany(c => c.Package[0].Activity.Select(ToStatusEvent)).ToList()); } catch (SoapException ex) { var sb = new StringBuilder(); sb.AppendFormat("SoapException Message= {0}.", ex.Message); sb.AppendFormat("SoapException Category:Code:Message= {0}.", ex.Detail.LastChild.InnerText); //sb.AppendFormat("SoapException XML String for all= {0}.", ex.Detail.LastChild.OuterXml); _logger.Error(string.Format("Error while getting UPS shipment tracking info - {0}", trackingNumber), new Exception(sb.ToString())); } catch (Exception exc) { _logger.Error(string.Format("Error while getting UPS shipment tracking info - {0}", trackingNumber), exc); } return(result); }
/// <summary> /// Gets all events for a tracking number. /// </summary> /// <param name="trackingNumber">The tracking number to track</param> /// <returns>List of Shipment Events.</returns> public virtual IList <ShipmentStatusEvent> GetShipmentEvents(string trackingNumber) { if (string.IsNullOrEmpty(trackingNumber)) { return(new List <ShipmentStatusEvent>()); } var result = new List <ShipmentStatusEvent>(); try { //use try-catch to ensure exception won't be thrown is web service is not available var track = new TrackService(); var tr = new TrackRequest(); var upss = new UPSSecurity(); var upssSvcAccessToken = new UPSSecurityServiceAccessToken { AccessLicenseNumber = _upsSettings.AccessKey }; upss.ServiceAccessToken = upssSvcAccessToken; var upssUsrNameToken = new UPSSecurityUsernameToken { Username = _upsSettings.Username, Password = _upsSettings.Password }; upss.UsernameToken = upssUsrNameToken; track.UPSSecurityValue = upss; var request = new RequestType(); string[] requestOption = { "15" }; request.RequestOption = requestOption; tr.Request = request; tr.InquiryNumber = trackingNumber; System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate { return(true); }; var trackResponse = track.ProcessTrack(tr); result.AddRange(trackResponse.Shipment.SelectMany(c => c.Package[0].Activity.Select(ToStatusEvent)).ToList()); } catch (Exception exc) { _logger.Error($"Error while getting UPS shipment tracking info - {trackingNumber}", exc); } return(result); }
public static UPSSecurity CreateUPSSecurity() { var svcAccessToken = new UPSSecurityServiceAccessToken() { AccessLicenseNumber = Environment.GetEnvironmentVariable("UPS_API_LICENSE") }; var userNameToken = new UPSSecurityUsernameToken() { Username = Environment.GetEnvironmentVariable("UPS_API_USER"), Password = Environment.GetEnvironmentVariable("UPS_API_PW") }; var security = new UPSSecurity() { ServiceAccessToken = svcAccessToken, UsernameToken = userNameToken }; return(security); }
static void Main() { try { XAVService xavSvc = new XAVService(); XAVRequest xavRequest = new XAVRequest(); UPSSecurity upss = new UPSSecurity(); UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken(); upssSvcAccessToken.AccessLicenseNumber = ; upss.ServiceAccessToken = upssSvcAccessToken; UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken(); upssUsrNameToken.Username = ; upssUsrNameToken.Password = ; upss.UsernameToken = upssUsrNameToken; xavSvc.UPSSecurityValue = upss; RequestType request = new RequestType(); //Below code contains dummy data for reference. Please update as required. String[] requestOption = { "1" }; request.RequestOption = requestOption; xavRequest.Request = request; AddressKeyFormatType addressKeyFormat = new AddressKeyFormatType(); String[] addressLine = { "3930 KRISTI COURT" }; addressKeyFormat.AddressLine = addressLine; addressKeyFormat.PoliticalDivision2 = "SACRAMENTO"; addressKeyFormat.PoliticalDivision1 = "CA"; addressKeyFormat.PostcodePrimaryLow = "95827"; addressKeyFormat.ConsigneeName = "Some Consignee"; addressKeyFormat.CountryCode = "US"; xavRequest.AddressKeyFormat = addressKeyFormat; System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy(); //serialize object (Debugging) System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(xavRequest.GetType()); Stream stream = File.Open("SerializedXAVRequest.xml", FileMode.Create); x.Serialize(stream, xavRequest); XAVResponse xavResponse = xavSvc.ProcessXAV(xavRequest); Console.WriteLine("Response Status Code " + xavResponse.Response.ResponseStatus.Code); Console.WriteLine("Response Status Description " + xavResponse.Response.ResponseStatus.Description); Console.ReadLine();
//private readonly string MESUREMENT_DISCRIPTION = "pounds"; public ActionResult Index() { UPSSecurity upss = new UPSSecurity(); UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken(); upssSvcAccessToken.AccessLicenseNumber = accessToken; upss.ServiceAccessToken = upssSvcAccessToken; UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken(); upssUsrNameToken.Username = username; upssUsrNameToken.Password = password; upss.UsernameToken = upssUsrNameToken; RatePackage rPackage = new RatePackage(); RequestRate(upss, rPackage); RequestTime(upss, rPackage); return(View(MatchData(rPackage).OrderBy(m => m.estimatedTime_num))); }
public TrackResponse GetTrackingInfo(string TrackingNumber) { //The following code is from the WebAPI example //Construct objects var TrackService = new TrackService(); var TrackRequest = new TrackRequest(); var UPSSecurityObject = new UPSSecurity(); var upssSvcAccessToken = new UPSSecurityServiceAccessToken(); //Assign parameters upssSvcAccessToken.AccessLicenseNumber = AccessLicenseNumber; UPSSecurityObject.ServiceAccessToken = upssSvcAccessToken; var upssUsrNameToken = new UPSSecurityUsernameToken(); upssUsrNameToken.Username = Username; upssUsrNameToken.Password = Password; UPSSecurityObject.UsernameToken = upssUsrNameToken; TrackService.UPSSecurityValue = UPSSecurityObject; RequestType request = new RequestType(); String[] requestOption = { "15" }; request.RequestOption = requestOption; TrackRequest.Request = request; TrackRequest.InquiryNumber = TrackingNumber; System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy(); //Send request and receive results try { TrackResponse Results = TrackService.ProcessTrack(TrackRequest); return(Results); } catch (System.Web.Services.Protocols.SoapException ex) { throw new Exception(ex.Message); } }
/// <summary> /// Gets all events for a tracking number. /// </summary> /// <param name="trackingNumber">The tracking number to track</param> /// <returns>List of Shipment Events.</returns> public virtual IList <ShipmentStatusEvent> GetShipmentEvents(string trackingNumber) { var result = new List <ShipmentStatusEvent>(); try { //use try-catch to ensure exception won't be thrown is web service is not available var track = new TrackService(); var tr = new TrackRequest(); var upss = new UPSSecurity(); var upssSvcAccessToken = new UPSSecurityServiceAccessToken(); upssSvcAccessToken.AccessLicenseNumber = _upsSettings.AccessKey; upss.ServiceAccessToken = upssSvcAccessToken; var upssUsrNameToken = new UPSSecurityUsernameToken(); upssUsrNameToken.Username = _upsSettings.Username; upssUsrNameToken.Password = _upsSettings.Password; upss.UsernameToken = upssUsrNameToken; track.UPSSecurityValue = upss; var request = new RequestType(); string[] requestOption = { "15" }; request.RequestOption = requestOption; tr.Request = request; tr.InquiryNumber = trackingNumber; var trackResponse = track.ProcessTrack(tr); result.AddRange(trackResponse.Shipment.SelectMany(c => c.Package[0].Activity.Select(x => ToStatusEvent(x))).ToList()); } catch (SoapException ex) { _logger.ErrorFormat(ex, "Error while getting UPS shipment tracking info - {0}", trackingNumber); } catch (Exception ex) { _logger.ErrorFormat(ex, "Error while getting UPS shipment tracking info - {0}", trackingNumber); } return(result); }
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(); } }
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); }
static void Main(string[] args) { System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer(); System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12 | System.Net.SecurityProtocolType.Ssl3 | System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11; try { XAVService xavSvc = new XAVService(); XAVRequest xavRequest = new XAVRequest(); UPSSecurity upss = new UPSSecurity(); UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken(); upssSvcAccessToken.AccessLicenseNumber = ""; upss.ServiceAccessToken = upssSvcAccessToken; UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken(); upssUsrNameToken.Username = ""; upssUsrNameToken.Password = ""; upss.UsernameToken = upssUsrNameToken; xavSvc.UPSSecurityValue = upss; RequestType request = new RequestType(); //Below code contains dummy data for reference. Please update as required. String[] requestOption = { "1" }; request.RequestOption = requestOption; xavRequest.Request = request; xavRequest.MaximumCandidateListSize = "10"; AddressKeyFormatType addressKeyFormat = new AddressKeyFormatType(); String[] addressLine = { "3930 KRISTI COURT" }; //addressKeyFormat.ItemsElementName = new ItemsChoiceType[] { ItemsChoiceType.PoliticalDivision1,ItemsChoiceType.PoliticalDivision2,ItemsChoiceType.PostcodePrimaryLow }; String[] addressKeyFormatItems = { "CA", "Cumming", "95827" }; //addressKeyFormat.Items = addressKeyFormatItems; addressKeyFormat.AddressLine = addressLine; addressKeyFormat.Urbanization = "SACRAMENTO CA 95827"; addressKeyFormat.ConsigneeName = "Some Consignee"; addressKeyFormat.CountryCode = "US"; addressKeyFormat.PoliticalDivision1 = "CA"; addressKeyFormat.PoliticalDivision2 = "Cumming"; addressKeyFormat.PostcodePrimaryLow = "95827"; Console.WriteLine($"Original Extended Post:{addressKeyFormat.PostcodeExtendedLow}"); xavRequest.AddressKeyFormat = addressKeyFormat; //System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy(); Console.WriteLine(jss.Serialize(xavRequest)); XAVResponse xavResponse = xavSvc.ProcessXAV(xavRequest); Console.WriteLine("Response Status Code " + xavResponse.Response.ResponseStatus.Code); Console.WriteLine("Response Status Description " + xavResponse.Response.ResponseStatus.Description); Console.WriteLine(xavResponse.Candidate[0].AddressKeyFormat.PostcodeExtendedLow); Console.WriteLine(xavResponse.Candidate[0].AddressKeyFormat.PostcodePrimaryLow); Console.ReadLine(); } catch (System.Web.Services.Protocols.SoapException ex) { Console.WriteLine(""); Console.WriteLine("---------XAV 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("G EX"); Console.WriteLine("-------------------------"); Console.WriteLine(" Generaal Exception= " + ex.Message); Console.WriteLine(" Generaal Exception-StackTrace= " + ex.StackTrace); Console.WriteLine("-------------------------"); } finally { Console.ReadKey(); } //NXAVServices.XAVPortTypeClient xvp = new NXAVServices.XAVPortTypeClient(); //NXAVServices.UPSSecurity upssecu = new NXAVServices.UPSSecurity(); //upssecu.ServiceAccessToken = new NXAVServices.UPSSecurityServiceAccessToken() { AccessLicenseNumber = "******" }; //upssecu.UsernameToken = new NXAVServices.UPSSecurityUsernameToken() { Username = "******", Password = "******" }; //NXAVServices.XAVRequest nRequest = new NXAVServices.XAVRequest(); //NXAVServices.RequestType rt = new NXAVServices.RequestType(); //String[] requestOption1 = { "1" }; //rt.RequestOption = requestOption1; //nRequest.Request = rt; //NXAVServices.AddressKeyFormatType addressKeyFormat1 = new NXAVServices.AddressKeyFormatType(); //String[] addressLine1 = { "3930 KRISTI COURT" }; ////addressKeyFormat.ItemsElementName = new ItemsChoiceType[] { ItemsChoiceType.PoliticalDivision1,ItemsChoiceType.PoliticalDivision2,ItemsChoiceType.PostcodePrimaryLow }; ////String[] addressKeyFormatItems = { "CA", "Cumming", "95827" }; ////addressKeyFormat.Items = addressKeyFormatItems; //addressKeyFormat1.AddressLine = addressLine1; //addressKeyFormat1.Urbanization = "SACRAMENTO CA 95827"; //addressKeyFormat1.ConsigneeName = "Some Consignee"; //addressKeyFormat1.CountryCode = "US"; //nRequest.AddressKeyFormat = addressKeyFormat1; //xvp.ProcessXAV(upssecu, nRequest); }
public ActionResult Index() { TimeInTransitService tntService = new TimeInTransitService(); TimeInTransitRequest tntRequest = new TimeInTransitRequest(); RequestType request = new RequestType(); String[] requestOption = { "TNT" }; request.RequestOption = requestOption; tntRequest.Request = request; RequestShipFromType shipFrom = new RequestShipFromType(); RequestShipFromAddressType addressFrom = new RequestShipFromAddressType(); addressFrom.City = "Toronto"; addressFrom.CountryCode = "CA"; addressFrom.PostalCode = "M1P4P5"; //addressFrom.StateProvinceCode = "ShipFrom state province code"; shipFrom.Address = addressFrom; tntRequest.ShipFrom = shipFrom; RequestShipToType shipTo = new RequestShipToType(); RequestShipToAddressType addressTo = new RequestShipToAddressType(); addressTo.City = "Toronto"; addressTo.CountryCode = "CA"; addressTo.PostalCode = "M1P4P5"; //addressTo.StateProvinceCode = "ShipTo state province code"; shipTo.Address = addressTo; tntRequest.ShipTo = shipTo; PickupType pickup = new PickupType(); pickup.Date = "20190830"; tntRequest.Pickup = pickup; //Below code uses dummy data for reference. Please update as required. ShipmentWeightType shipmentWeight = new ShipmentWeightType(); shipmentWeight.Weight = "10"; CodeDescriptionType unitOfMeasurement = new CodeDescriptionType(); unitOfMeasurement.Code = "KGS"; unitOfMeasurement.Description = "Kilograms"; shipmentWeight.UnitOfMeasurement = unitOfMeasurement; tntRequest.ShipmentWeight = shipmentWeight; tntRequest.TotalPackagesInShipment = "1"; InvoiceLineTotalType invoiceLineTotal = new InvoiceLineTotalType(); invoiceLineTotal.CurrencyCode = "CAD"; invoiceLineTotal.MonetaryValue = "10"; tntRequest.InvoiceLineTotal = invoiceLineTotal; tntRequest.MaximumListSize = "1"; UPSSecurity upss = new UPSSecurity(); UPSSecurityServiceAccessToken upsSvcToken = new UPSSecurityServiceAccessToken(); upsSvcToken.AccessLicenseNumber = "3D6A1DD5F39023B5"; upss.ServiceAccessToken = upsSvcToken; UPSSecurityUsernameToken upsSecUsrnameToken = new UPSSecurityUsernameToken(); upsSecUsrnameToken.Username = "******"; upsSecUsrnameToken.Password = "******"; upss.UsernameToken = upsSecUsrnameToken; tntService.UPSSecurityValue = upss; 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(tntRequest); TimeInTransitResponse tntResponse = tntService.ProcessTimeInTransit(tntRequest); Console.WriteLine("Response code: " + tntResponse.Response.ResponseStatus.Code); Console.WriteLine("Response description: " + tntResponse.Response.ResponseStatus.Description); TransitResponseType responseItem = (TransitResponseType)tntResponse.Item; RatePackage model = new RatePackage() { timeResponse = responseItem }; return(View(model)); }
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(); } }
// Gets all available rates regardless of settings private List <IShippingRate> GetAllShippingRatesForShipment(IShipment shipment) { var rates = new List <IShippingRate>(); var hasErrors = false; try { var sErrorMessage = string.Empty; var sErrorCode = string.Empty; var sURL = string.Concat(UPSLIVESERVER, "FreightRate"); // Build XML var settings = new UPSFreightSettings { UserID = GlobalSettings.Username, Password = GlobalSettings.Password, ServerUrl = UPSLIVESERVER, License = GlobalSettings.LicenseNumber }; var sXML = string.Empty; FreightRateRequest freightRateRequest = BuildUPSFreightRateRequestForShipment(shipment); FreightRateService rateService = new FreightRateService(); //Set Web Service URL rateService.Url = sURL; //Set Security Settings For Web Service UPSSecurity upss = new UPSSecurity(); UPSSecurityServiceAccessToken upsSvcToken = new UPSSecurityServiceAccessToken(); upsSvcToken.AccessLicenseNumber = settings.License; upss.ServiceAccessToken = upsSvcToken; UPSSecurityUsernameToken upsSecUsrnameToken = new UPSSecurityUsernameToken(); upsSecUsrnameToken.Username = settings.UserID; upsSecUsrnameToken.Password = settings.Password; upss.UsernameToken = upsSecUsrnameToken; rateService.UPSSecurityValue = upss; var sStatusCode = "-1"; try { ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12; //Set for SSL Webservice Call FreightRateResponse freightRateResponse = rateService.ProcessFreightRate(freightRateRequest); //Send For Processing if (freightRateResponse.Response.ResponseStatus.Code == "1") //Sucess { sStatusCode = "1"; var r = new ShippingRate { DisplayName = Settings.ServiceCodeFilter[0].DisplayName, EstimatedCost = decimal.Parse(freightRateResponse.TotalShipmentCharge.MonetaryValue, NumberStyles.Currency, CultureInfo.InvariantCulture), ServiceCodes = Settings.ServiceCodeFilter[0].Code, ServiceId = Id }; rates.Add(r); } } catch (SoapException soapex) //Handle SOAP Exception { _Logger.LogException(soapex); var mex = new ShippingServiceMessage(); if (soapex.Detail != null) { mex.SetError("Exception", string.Concat(soapex.Detail.InnerText, " | ", soapex.Source)); } else { mex.SetError("Exception", string.Concat(soapex.Message, " | ", soapex.Source)); } _Messages.Add(mex); return(rates); } catch (Exception Exx) { _Logger.LogException(Exx); var mex = new ShippingServiceMessage(); mex.SetError("Exception", string.Concat(Exx.Message, " | ", Exx.Source)); _Messages.Add(mex); return(rates); } if (sStatusCode != "1") { hasErrors = true; } } catch (Exception ex) { _Logger.LogException(ex); var m = new ShippingServiceMessage(); m.SetError("Exception", string.Concat(ex.Message, " | ", ex.StackTrace)); _Messages.Add(m); } if (hasErrors) { rates = new List <IShippingRate>(); } return(rates); }
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(); } }
static void Main() { try { VoidService voidService = new VoidService(); VoidShipmentRequest voidRequest = new VoidShipmentRequest(); RequestType request = new RequestType(); String[] requestOption = { "1" }; request.RequestOption = requestOption; voidRequest.Request = request; VoidShipmentRequestVoidShipment voidShipment = new VoidShipmentRequestVoidShipment(); voidShipment.ShipmentIdentificationNumber = "1ZISDE016691676846"; voidRequest.VoidShipment = voidShipment; 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; voidService.UPSSecurityValue = upss; System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy(); Console.WriteLine(voidRequest); VoidShipmentResponse voidResponse = voidService.ProcessVoid(voidRequest); Console.WriteLine("The transaction was a " + voidResponse.Response.ResponseStatus.Description); Console.WriteLine("The shipment has been : " + voidResponse.SummaryResult.Status.Description); Console.ReadKey(); } catch (System.Web.Services.Protocols.SoapException ex) { Console.WriteLine(""); Console.WriteLine("---------Void 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(); } }
public bool itemDelivered(string trackingNumb) { bool delivered = false; try { //create the client proxy TrackPortTypeClient track = new TrackPortTypeClient(); //create username token UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken(); //this is my UPS userid upssUsrNameToken.Username = "******"; //this is my UPS password upssUsrNameToken.Password = "******"; UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken(); //this is my UPS access key upssSvcAccessToken.AccessLicenseNumber = "CD6DBC4A27FE8C15"; //create UPS security object UPSSecurity upss = new UPSSecurity(); //set the user name token upss.UsernameToken = upssUsrNameToken; //set the service access token upss.ServiceAccessToken = upssSvcAccessToken; //create the request object RequestType request = new RequestType(); //must be hard coded to 15 String[] requestOption = { "15" }; //set the request option request.RequestOption = requestOption; TrackRequest tr = new TrackRequest(); tr.Request = request; //this is your UPS tracking id (normally 18 digit) tr.InquiryNumber = trackingNumb; //added to handle the intermittent error with SSL/TLS connection ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; //open channel track.Open(); //invoke the service TrackResponse trackResponse = track.ProcessTrack(upss, tr); //close channel track.Close(); //store activities List <string> actList = new List <string>(); List <string> dateList = new List <string>(); List <string> timeList = new List <string>(); foreach (ShipmentType shipment in trackResponse.Shipment) { foreach (PackageType package in shipment.Package) { foreach (ActivityType Act in package.Activity) { //Adds description of last activity to actList actList.Add(Act.Status.Description); //Output testing //testConsole.Text += ("\nStatus: "+ //Act.ActivityLocation.Address.City, //Act.ActivityLocation.Address.StateProvinceCode, Act.Date, Act.Time, //Act.Status.Description); } } } if (String.Equals(actList[0], "Delivered")) { delivered = true; } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.ReadLine(); } return(delivered); }
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(""); } }
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(); } }
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(); } }
static void Main() { try { TrackService track = new TrackService(); TrackRequest tr = new TrackRequest(); 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; track.UPSSecurityValue = upss; RequestType request = new RequestType(); String[] requestOption = { "15" }; request.RequestOption = requestOption; tr.Request = request; tr.InquiryNumber = "1Z12345E0205271688"; //System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy(); TrackResponse trackResponse = track.ProcessTrack(tr); Console.WriteLine("The transaction was a " + trackResponse.Response.ResponseStatus.Description); Console.WriteLine("Shipment Service " + trackResponse.Shipment[0].Service.Description); Console.ReadKey(); } catch (System.Web.Services.Protocols.SoapException ex) { Console.WriteLine(""); Console.WriteLine("---------Track 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(); } }
static void Main() { try { TrackService track = new TrackService(); TrackRequest tr = new TrackRequest(); 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; track.UPSSecurityValue = upss; RequestType request = new RequestType(); String[] requestOption = { "15" }; request.RequestOption = requestOption; tr.Request = request; tr.InquiryNumber = "Your track inquiry number"; 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. TrackResponse trackResponse = track.ProcessTrack(tr); Console.WriteLine("The transaction was a " + trackResponse.Response.ResponseStatus.Description); Console.WriteLine("Shipment Service " + trackResponse.Shipment[0].Service.Description); Console.ReadKey(); } catch (System.Web.Services.Protocols.SoapException ex) { Console.WriteLine(""); Console.WriteLine("---------Track 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(); } }
static void Main() { string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=K:\POS Database\POS Construction_be.mdb"; string strSQL = "SELECT p_TrackingNumber as UPSTracking, p_Reference5 as SNowRef, UPSTran as ActivityCount FROM TRACKING WHERE (((UPSTran) Is Null) AND ((p_Reference5) <> '') AND ((si_VoidIndicator)='N') AND ((si_ReturnServiceOption)='N')) OR (((UPSTran)<>99) AND ((UPSTran)<>999) AND ((si_VoidIndicator)='N') AND ((p_Reference5) <> '') AND ((si_ReturnServiceOption)='N'))"; using (OleDbConnection connection = new OleDbConnection(connectionString)) { OleDbCommand command = new OleDbCommand(strSQL, connection); try { connection.Open(); using (OleDbDataReader reader = command.ExecuteReader()) { if (reader.HasRows) { while (reader.Read()) { DateTime now = DateTime.Now; string strTN = reader.GetString(reader.GetOrdinal("UPSTracking")); Int32 strAC = reader.GetInt32(2); string strSerNowRef = reader.GetString(reader.GetOrdinal("SNowRef")); try { TrackService track = new TrackService(); TrackRequest tr = new TrackRequest(); UPSSecurity upss = new UPSSecurity(); UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken(); upssSvcAccessToken.AccessLicenseNumber = "1D5E2960D39CB1B5"; upss.ServiceAccessToken = upssSvcAccessToken; UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken(); upssUsrNameToken.Username = "******"; upssUsrNameToken.Password = "******"; upss.UsernameToken = upssUsrNameToken; track.UPSSecurityValue = upss; RequestType request = new RequestType(); String[] requestOption = { "15" }; request.RequestOption = requestOption; tr.Request = request; tr.InquiryNumber = strTN; 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. TrackResponse trackResponse = track.ProcessTrack(tr); //Console.WriteLine("The transaction was a " + trackResponse.Response.ResponseStatus.Description); //Console.WriteLine("Shipment Service " + trackResponse.Shipment[0].Service.Description); foreach (ShipmentType shipment in trackResponse.Shipment) { foreach (PackageType package in shipment.Package) { bool del = false; if (package.TrackingNumber == strTN) { int intUPSRecords = package.Activity.Length; int R = intUPSRecords - strAC; int N = intUPSRecords; int i = 0; foreach (ActivityType Act in package.Activity) { string strdatetime = Act.Date + Act.Time; DateTime dt = DateTime.ParseExact(strdatetime, "yyyyMMddHHmmss", CultureInfo.InvariantCulture); string StatusCode = Act.Status.Code; string strAns = Act.Status.Description + " " + dt + " - " + Act.ActivityLocation.Address.City + ", " + Act.ActivityLocation.Address.StateProvinceCode + " " + Act.ActivityLocation.Address.CountryCode; Console.WriteLine(package.TrackingNumber + " " + Act.Status.Description + " " + dt + " - " + Act.ActivityLocation.Address.City + ", " + Act.ActivityLocation.Address.StateProvinceCode + " " + Act.ActivityLocation.Address.CountryCode); if (R > i) { N = intUPSRecords - i; Console.WriteLine("....Writing Record to UPS Track Table...."); string strAnsB = strAns.Replace("'", "`"); strSQL = "INSERT INTO UPSTrack ([UPSTrackNumber], [Status], [RequestNum],[Date],[UPSStatusCode],[Order]) VALUES ('" + strTN + "', '" + strAnsB + "', '" + "RE" + strSerNowRef + "', '" + now + "','" + StatusCode + "','" + N + "')"; command = new OleDbCommand(strSQL, connection); command.ExecuteReader(); i++; strSQL = "UPDATE TRACKING SET UPSTran = " + package.Activity.Length + " WHERE p_TrackingNumber ='" + strTN + "'"; command = new OleDbCommand(strSQL, connection); command.ExecuteReader(); } if (Act.Status.Description == "Delivered") { del = true; } } } if (del == true) { // Update rows with 99 when package was delivered strSQL = "UPDATE TRACKING SET UPSTran = 99 WHERE p_TrackingNumber ='" + package.TrackingNumber + "'"; command = new OleDbCommand(strSQL, connection); command.ExecuteReader(); del = false; } } } } catch (System.Web.Services.Protocols.SoapException ex) { Console.WriteLine(""); Console.WriteLine("---------Track 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(""); Console.WriteLine("Press any Key to Continue"); Console.ReadKey(); } catch (System.ServiceModel.CommunicationException ex) { Console.WriteLine(""); Console.WriteLine("--------------------"); Console.WriteLine("CommunicationException= " + ex.Message); Console.WriteLine("CommunicationException-StackTrace= " + ex.StackTrace); Console.WriteLine("-------------------------"); Console.WriteLine(""); Console.WriteLine("Press any Key to Continue"); Console.ReadKey(); } catch (Exception ex) { Console.WriteLine(""); Console.WriteLine("-------------------------"); Console.WriteLine(" General Exception= " + ex.Message); Console.WriteLine(" General Exception-StackTrace= " + ex.StackTrace); Console.WriteLine("-------------------------"); Console.WriteLine(strSerNowRef); Console.WriteLine("Press any Key to Continue"); Console.ReadKey(); } finally { } } } else { Console.WriteLine("No Records Found"); Console.WriteLine("Press any Key to Continue"); Console.ReadKey(); } } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(" General Exception-StackTrace= " + ex.StackTrace); Console.WriteLine("Press any Key to Continue"); Console.ReadKey(); } // The connection is automatically closed becasuse of using block. //Console.ReadKey(); } }
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)); }
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(); } }
static void Main() { // Connection string and SQL query string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=K:\POS Database\POS Construction_be.mdb"; string strSQL = "SELECT ID, si_SaturdayDeliveryOption, p_TrackingNumber, si_ServiceType, UPSTNTDay, si_ReturnServiceOption, si_PickUpDate, st_City, st_State, st_PostalZipCode, st_Country, RecipientCode FROM TRACKING WHERE((UPSTNTDay) = '' or (isNull(UPSTNTDay) AND ((si_ReturnServiceOption) = 'N') AND ((si_VoidIndicator) = 'N')))"; using (OleDbConnection connection = new OleDbConnection(connectionString)) { // Create a command and set its connection OleDbCommand command = new OleDbCommand(strSQL, connection); try { connection.Open(); using (OleDbDataReader reader = command.ExecuteReader()) { if (reader.HasRows) { while (reader.Read()) { string strTrackID = reader.GetString(reader.GetOrdinal("p_TrackingNumber")); string strSatDelOpt = reader.GetString(reader.GetOrdinal("si_SaturdayDeliveryOption")); string strCity = reader.GetString(reader.GetOrdinal("st_City")); string strState = reader.GetString(reader.GetOrdinal("st_State")); string strZip = reader.GetString(reader.GetOrdinal("st_PostalZipCode")); string strShipdate = reader.GetString(reader.GetOrdinal("si_PickUpDate")); string strCountry = reader.GetString(reader.GetOrdinal("st_Country")); string strServiceType = reader.GetString(reader.GetOrdinal("si_ServiceType")); Int32 strID = reader.GetInt32(reader.GetOrdinal("ID")); try { TimeInTransitService tntService = new TimeInTransitService(); TimeInTransitRequest tntRequest = new TimeInTransitRequest(); RequestType request = new RequestType(); String[] requestOption = { "TNT" }; request.RequestOption = requestOption; tntRequest.Request = request; tntRequest.SaturdayDeliveryInfoRequestIndicator = "N"; RequestShipFromType shipFrom = new RequestShipFromType(); RequestShipFromAddressType addressFrom = new RequestShipFromAddressType(); addressFrom.City = "Edina"; addressFrom.CountryCode = "US"; addressFrom.PostalCode = "55435"; addressFrom.StateProvinceCode = "MN"; shipFrom.Address = addressFrom; tntRequest.ShipFrom = shipFrom; RequestShipToType shipTo = new RequestShipToType(); RequestShipToAddressType addressTo = new RequestShipToAddressType(); addressTo.City = strCity; addressTo.CountryCode = strCountry; addressTo.PostalCode = strZip; addressTo.StateProvinceCode = strState; shipTo.Address = addressTo; tntRequest.ShipTo = shipTo; PickupType pickup = new PickupType(); string left = strShipdate.Substring(0, 8); pickup.Date = left; pickup.Time = "120000"; tntRequest.Pickup = pickup; if (strCountry == "CA") { ShipmentWeightType shipmentWeight = new ShipmentWeightType(); shipmentWeight.Weight = "10"; CodeDescriptionType unitOfMeasurement = new CodeDescriptionType(); unitOfMeasurement.Code = "KGS"; unitOfMeasurement.Description = "Kilograms"; shipmentWeight.UnitOfMeasurement = unitOfMeasurement; tntRequest.ShipmentWeight = shipmentWeight; tntRequest.TotalPackagesInShipment = "1"; InvoiceLineTotalType invoiceLineTotal = new InvoiceLineTotalType(); invoiceLineTotal.CurrencyCode = "CAD"; invoiceLineTotal.MonetaryValue = "10"; tntRequest.InvoiceLineTotal = invoiceLineTotal; tntRequest.MaximumListSize = "1"; } else { ShipmentWeightType shipmentWeight = new ShipmentWeightType(); shipmentWeight.Weight = "10"; CodeDescriptionType unitOfMeasurement = new CodeDescriptionType(); unitOfMeasurement.Code = "LBS"; unitOfMeasurement.Description = "pounds"; shipmentWeight.UnitOfMeasurement = unitOfMeasurement; tntRequest.ShipmentWeight = shipmentWeight; tntRequest.TotalPackagesInShipment = "1"; InvoiceLineTotalType invoiceLineTotal = new InvoiceLineTotalType(); invoiceLineTotal.CurrencyCode = "USD"; invoiceLineTotal.MonetaryValue = "10"; tntRequest.InvoiceLineTotal = invoiceLineTotal; tntRequest.MaximumListSize = "1"; } UPSSecurity upss = new UPSSecurity(); UPSSecurityServiceAccessToken upsSvcToken = new UPSSecurityServiceAccessToken(); upsSvcToken.AccessLicenseNumber = "1D5E2960D39CB1B5 "; upss.ServiceAccessToken = upsSvcToken; UPSSecurityUsernameToken upsSecUsrnameToken = new UPSSecurityUsernameToken(); upsSecUsrnameToken.Username = "******"; upsSecUsrnameToken.Password = "******"; upss.UsernameToken = upsSecUsrnameToken; tntService.UPSSecurityValue = upss; 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. TimeInTransitResponse tntResponse = tntService.ProcessTimeInTransit(tntRequest); if (strServiceType == "WORLDWIDE SAVER") { strServiceType = "Worldwide Saver"; } strServiceType = "UPS " + strServiceType; if (tntResponse.Item != null) { var timeInTransitResponse = (TransitResponseType)tntResponse.Item; foreach (var serviceSummaryType in timeInTransitResponse.ServiceSummary) { string strUPScode = serviceSummaryType.Service.Code; if (serviceSummaryType.Service.Description == strServiceType && strSatDelOpt == "Y" && strUPScode.Substring(strUPScode.Length - 1, 1) == "S" || serviceSummaryType.Service.Description == strServiceType && strSatDelOpt != "Y" && strUPScode.Substring(strUPScode.Length - 1, 1) != "S") { Console.WriteLine(addressTo.City + strState + ", " + strCity + " - " + serviceSummaryType.EstimatedArrival.BusinessDaysInTransit); string intUPSTNT = serviceSummaryType.EstimatedArrival.BusinessDaysInTransit; string strTNTDay = serviceSummaryType.EstimatedArrival.Arrival.Date; DateTime d = DateTime.ParseExact(strTNTDay, "yyyyMMdd", CultureInfo.InvariantCulture); string strTNTtime = serviceSummaryType.EstimatedArrival.Arrival.Time; if (Convert.ToInt32(strTNTtime) >= 230000) { strTNTtime = "End of Day"; } else { IFormatProvider format = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat; DateTime time_24 = DateTime.ParseExact(strTNTtime, "HHmmss", format); strTNTtime = time_24.ToString("h:mm tt"); } strSQL = "UPDATE TRACKING SET UPSTNTDay = '" + d.ToString("MM/dd/yyyy") + "', UPSTNTTime = '" + strTNTtime + "' WHERE p_TrackingNumber ='" + strTrackID + "'"; command = new OleDbCommand(strSQL, connection); command.ExecuteReader(); Console.Write(strTrackID); Console.Write("Business Days in Transit: "); Console.Write(serviceSummaryType.EstimatedArrival.BusinessDaysInTransit); Console.Write(", Arrival Date: "); Console.Write(serviceSummaryType.EstimatedArrival.Arrival.Date); Console.Write(", Service: ("); Console.Write(serviceSummaryType.Service.Code); Console.Write(") "); Console.Write(serviceSummaryType.Service.Description); Console.WriteLine(serviceSummaryType.EstimatedArrival.Arrival.Time); } } } } catch (System.Web.Services.Protocols.SoapException ex) { Console.WriteLine(""); Console.WriteLine("---------Time In Transit 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 { } } } } } catch (System.ServiceModel.CommunicationException ex) { Console.WriteLine(ex.Message); Console.WriteLine(" General Exception-StackTrace= " + ex.StackTrace); } } Console.WriteLine("done"); //Console.ReadKey(); }
public string getLatestUPSupdate(string trackingNumb) { string latestUpdate = ""; try { //create the client proxy TrackPortTypeClient track = new TrackPortTypeClient(); //create username token UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken(); //this is my UPS userid upssUsrNameToken.Username = "******"; //this is my UPS password upssUsrNameToken.Password = "******"; UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken(); //this is my UPS access key upssSvcAccessToken.AccessLicenseNumber = "CD6DBC4A27FE8C15"; //create UPS security object UPSSecurity upss = new UPSSecurity(); //set the user name token upss.UsernameToken = upssUsrNameToken; //set the service access token upss.ServiceAccessToken = upssSvcAccessToken; //create the request object RequestType request = new RequestType(); //must be hard coded to 15 String[] requestOption = { "15" }; //set the request option request.RequestOption = requestOption; TrackRequest tr = new TrackRequest(); tr.Request = request; //this is your UPS tracking id (normally 18 digit) //TODO: Make a list and use the strin.join function to create a comma separated list to pass for tracking numbers*********** tr.InquiryNumber = trackingNumb; //trackingNumListBox.SelectedItem.ToString();//gets tracking # from listbox //tr.InquiryNumber = "1Z5V87A90369535127";//Hardcoded test tracking number /*1Z5V87A90369535127 has a status of : * "In transit * Scheduled Delivery: * Wednesday * 11 / 06 / 2019 * Estimated Time * by End of Day * per UPS tracking website */ //added to handle the intermittent error with SSL/TLS connection ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; //open channel track.Open(); //invoke the service TrackResponse trackResponse = track.ProcessTrack(upss, tr); //close channel track.Close(); //store activities List <string> actList = new List <string>(); List <string> dateList = new List <string>(); List <string> timeList = new List <string>(); foreach (ShipmentType shipment in trackResponse.Shipment) { foreach (PackageType package in shipment.Package) { foreach (ActivityType Act in package.Activity) { //Adds description of last activity to actList actList.Add(Act.Status.Description); //Output testing //testConsole.Text += ("\nStatus: "+ //Act.ActivityLocation.Address.City, //Act.ActivityLocation.Address.StateProvinceCode, Act.Date, Act.Time, //Act.Status.Description); } } } latestUpdate = actList[0]; } catch (Exception ex) { Console.WriteLine(ex.Message); Console.ReadLine(); } return(latestUpdate); }
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 { } }
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(); //} }
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; }