public static AddressValidateResponse VerifyAddress(string firmName,string address1,string address2,string city,string state,string zip5,string zip4) { // AddressValidateResponse response = new AddressValidateResponse(); USPSWebToolsClient client = new USPSWebToolsClient(); try { DataSet ds = client.VerifyAddress(firmName,address1,address2,city,state,zip5,zip4); if (ds != null) response.Merge(ds); client.Close(); } catch (TimeoutException te) { client.Abort(); throw new ApplicationException(te.Message); } catch (FaultException<USPSFault> cfe) { client.Abort(); throw new ApplicationException(cfe.Detail.Message); } catch (FaultException fe) { client.Abort(); throw new ApplicationException(fe.Message); } catch (CommunicationException ce) { client.Abort(); throw new ApplicationException(ce.Message); } return response; }
public AddressValidateResponse VerifyAddress(string firmName, string address1, string address2, string city, string state, string zip5, string zip4) { // AddressValidateResponse response = new AddressValidateResponse(); USPSServiceClient client = new USPSServiceClient(); try { DataSet ds = client.VerifyAddress(firmName, address1, address2, city, state, zip5, zip4); if (ds != null) { response.Merge(ds); } client.Close(); } catch (TimeoutException te) { client.Abort(); throw new ApplicationException(te.Message); } catch (FaultException <EnterpriseFault> cfe) { client.Abort(); throw new ApplicationException(cfe.Detail.Message); } catch (FaultException fe) { client.Abort(); throw new ApplicationException(fe.Message); } catch (CommunicationException ce) { client.Abort(); throw new ApplicationException(ce.Message); } return(response); }
internal static async Task <List <Address> > ValidateAsync(List <Address> input) { // limit is 5 addresses per request string requestGuid = Guid.NewGuid().ToString(); Log.Information("{area}: New request for {packageTotal} packages. {requestGuid}", "Validate()", input.Count, requestGuid); List <Address> output = new(); AddressValidateRequest request; int index = 0; while (index < input.Count) { request = new AddressValidateRequest { Address = input.Skip(index).Take(5).ToList(), USERID = UspsApiUsername, }; Log.Information("{area}: Fetching rates for {packageCount} package(s). {requestGuid}", "Validate()", input.Count, requestGuid); XmlSerializer xsSubmit = new(typeof(AddressValidateRequest)); var xml = ""; using (StringWriter sww = new()) { using XmlWriter writer = XmlWriter.Create(sww); xsSubmit.Serialize(writer, request); xml = sww.ToString(); } string uspsUrl = "https://secure.shippingapis.com/ShippingAPI.dll"; FormUrlEncodedContent formData = new(new[] { new KeyValuePair <string, string>("API", "Verify"), new KeyValuePair <string, string>("XML", xml) }); HttpClient httpClient = new() { Timeout = TimeSpan.FromSeconds(50) }; HttpResponseMessage response = null; int retryCount = 0; DateTime responseTimer = DateTime.Now; while (response == null || response.StatusCode != System.Net.HttpStatusCode.OK) { if (retryCount > 0) { Log.Warning("{area}: USPS Failed to Respond after " + retryCount + " seconds. Attempt {retryCount}. {requestGuid}", "Validate()", retryCount, requestGuid); } response = await httpClient.PostAsync(uspsUrl, formData).ConfigureAwait(false); Thread.Sleep(1000 * retryCount); httpClient.CancelPendingRequests(); retryCount++; if (retryCount > 50) { Log.Error("{area}: USPS Failed to Respond after 50 attempts. {requestGuid}", "Validate()", retryCount, requestGuid); throw new UspsApiException("408: After many attempts, the request to the USPS API did not recieve a response. Please try again later."); } } TimeSpan responseTime = DateTime.Now.TimeOfDay.Subtract(responseTimer.TimeOfDay); var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); Log.Information("{area}: USPS response received in {responseTime} ms. {requestGuid}", "Validate()", responseTime.Milliseconds, requestGuid); try { XmlSerializer deserializer = new(typeof(AddressValidateResponse)); var ms = new MemoryStream(Encoding.UTF8.GetBytes(content)); AddressValidateResponse responseJson = (AddressValidateResponse)deserializer.Deserialize(ms); index += 5; if (responseJson.Error != null) { Log.Warning("{area}: USPS Returned Error: {uspsErrorNumber} {uspsErrorDescription} {requestGuid}", "Validate()", responseJson.Error.Number, responseJson.Error.Description, requestGuid); } foreach (Address validatedAddress in responseJson.Address) { Address orig = input.First(i => i.AddressDetailId == validatedAddress.AddressDetailId); if (validatedAddress.Error != null) { Log.Warning("{area}: USPS Returned Error: {uspsErrorNumber} {uspsErrorDescription} {requestGuid}", "Validate()", validatedAddress.Error.Number, validatedAddress.Error.Description, requestGuid); orig.Error = validatedAddress.Error; } orig.Business = validatedAddress.Business; orig.CarrierRoute = validatedAddress.CarrierRoute; orig.CentralDeliveryPoint = validatedAddress.CentralDeliveryPoint; orig.CityAbbreviation = validatedAddress.CityAbbreviation; orig.DeliveryPoint = validatedAddress.DeliveryPoint; orig.DPVCMRA = validatedAddress.DPVCMRA; orig.DPVConfirmation = validatedAddress.DPVConfirmation; orig.DPVFootnotes = validatedAddress.DPVFootnotes; orig.Footnotes = validatedAddress.Footnotes; orig.Vacant = validatedAddress.Vacant; // backup origingal address and overwrite with validated orig.OriginalAddress1 = orig.Address1; orig.Address1 = validatedAddress.Address1; orig.OriginalAddress2 = orig.Address2; orig.Address2 = validatedAddress.Address2; orig.OriginalCity = orig.City; orig.City = validatedAddress.City; orig.OriginalState = orig.State; orig.State = validatedAddress.State; orig.OriginalZip = orig.Zip5; orig.Zip5 = validatedAddress.Zip5 + "-" + validatedAddress.Zip4; output.Add(orig); } } catch (Exception ex) { Log.Error("{area}: Exception: {ex} {requestGuid}", "Validate()", ex.ToString(), requestGuid); throw new UspsApiException(ex); } } if (output.Count != input.Count) { // something went wrong because counts should always match Console.WriteLine("Counts did not match between input and output"); Log.Error("{area}: Counts did not match between input and output. {requestGuid}", "Validate()", requestGuid); throw new UspsApiException("Counts did not match between input and output"); } return(output); }
public bool VerifyAddress(string firmName, string addressLine1, string addressLine2, string city, string state, string zip5, string zip4) { //Set user services bool verified = false; try { // AddressValidateResponse avr = EnterpriseUSPSGateway.VerifyAddress(firmName, addressLine1, addressLine2, city, state, zip5, zip4); if (avr.Error.Rows.Count > 0) { //Bad address or syntax string error = (!avr.Error[0].IsNumberNull() ? avr.Error[0].Number : "") + " " + (!avr.Error[0].IsSourceNull() ? avr.Error[0].Source : "") + "\r\n" + (!avr.Error[0].IsDescriptionNull() ? avr.Error[0].Description : ""); MessageBox.Show(error, App.Title, MessageBoxButtons.OK, MessageBoxIcon.Error); } else if (avr.Address.Rows.Count > 0) { //Does it match the request? string srcAddress = addressLine2.Trim().ToLower() + addressLine1.Trim().ToLower(); string uspsAddress = (!avr.Address[0].IsAddress1Null() ? avr.Address[0].Address1.Trim().ToLower() : "") + (!avr.Address[0].IsAddress2Null() ? avr.Address[0].Address2.Trim().ToLower() : ""); bool match = (srcAddress == uspsAddress) && (city.Trim().ToLower() == (!avr.Address[0].IsCityNull() ? avr.Address[0].City.Trim().ToLower() : "")) && (state.Trim().ToLower() == (!avr.Address[0].IsStateNull() ? avr.Address[0].State.Trim().ToLower() : "")) && (zip5.Trim().ToLower() == (!avr.Address[0].IsZip5Null() ? avr.Address[0].Zip5.Trim().ToLower() : "")); if (match && avr.Address[0].IsReturnTextNull()) { //Use scrubbed USPS address this.mFirmName = firmName; this.mAddressLine1 = !avr.Address[0].IsAddress2Null() ? avr.Address[0].Address2 : ""; this.mAddressLine2 = !avr.Address[0].IsAddress1Null() ? avr.Address[0].Address1 : ""; this.mCity = !avr.Address[0].IsCityNull() ? avr.Address[0].City : ""; this.mState = !avr.Address[0].IsStateNull() ? avr.Address[0].State : ""; this.mZip5 = !avr.Address[0].IsZip5Null() ? avr.Address[0].Zip5 : ""; this.mZip4 = !avr.Address[0].IsZip4Null() ? avr.Address[0].Zip4 : ""; } else { //Let user choose this.txtName.Text = firmName; this.txtAddressLine1.Text = addressLine1; this.txtAddressLine2.Text = addressLine2; this.txtCity.Text = city; this.txtState.Text = state; this.txtZip5.Text = zip5; this.txtZip4.Text = zip4; this.txtUSPSName.Text = firmName; this.txtUSPSAddressLine1.Text = !avr.Address[0].IsAddress2Null() ? avr.Address[0].Address2 : ""; this.txtUSPSAddressLine2.Text = !avr.Address[0].IsAddress1Null() ? avr.Address[0].Address1 : ""; this.txtUSPSCity.Text = !avr.Address[0].IsCityNull() ? avr.Address[0].City : ""; this.txtUSPSState.Text = !avr.Address[0].IsStateNull() ? avr.Address[0].State : ""; this.txtUSPSZip5.Text = !avr.Address[0].IsZip5Null() ? avr.Address[0].Zip5 : ""; this.txtUSPSZip4.Text = !avr.Address[0].IsZip4Null() ? avr.Address[0].Zip4 : ""; this.lblMessage.Text = !avr.Address[0].IsReturnTextNull() ? avr.Address[0].ReturnText : ""; this.ShowDialog(); } verified = true; } else { //Not verified MessageBox.Show("The adddress could not be verified by the US Postal Service.", App.Title, MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception ex) { App.ReportError(ex, true); } return(verified); }
public async Task <IActionResult> GetAsync(Address model) { var webRootPath = _hostingEnvironment.ContentRootPath; Address address = new Address { Address1 = model.Address1 ?? "", Address2 = model.Address2 ?? "", State = model.State ?? "", City = model.City ?? "", Zip5 = model.Zip5 ?? "", Zip4 = model.Zip4 ?? "", FirmName = model.FirmName ?? "", Urbanization = model.Urbanization ?? "" }; string userId = _configuration["USPS:UserId"]; AddressValidateRequest request = new AddressValidateRequest { Address = address, UserId = userId, }; XmlSerializer xsSubmit = new XmlSerializer(typeof(AddressValidateRequest)); var xml = ""; using (var sww = new StringWriter()) { using (XmlWriter writer = XmlWriter.Create(sww)) { xsSubmit.Serialize(writer, request); xml = sww.ToString(); } } var requestXmlFile = Path.Combine(webRootPath, "request.xml"); System.IO.File.WriteAllText(requestXmlFile, xml); //string uspsUrl = "http://production.shippingapis.com/ShippingAPI.dll"; string uspsUrl = "https://secure.shippingapis.com/ShippingAPI.dll"; var formData = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("API", "Verify"), new KeyValuePair <string, string>("XML", xml) }); HttpClient httpClient = new HttpClient(); var response = await httpClient.PostAsync(uspsUrl, formData); var content = await response.Content.ReadAsStringAsync(); var responseXmlFile = Path.Combine(webRootPath, "response.xml"); System.IO.File.WriteAllText(responseXmlFile, content); try { XmlSerializer deserializer = new XmlSerializer(typeof(AddressValidateResponse)); var ms = new MemoryStream(Encoding.UTF8.GetBytes(content)); AddressValidateResponse responseJson = (AddressValidateResponse)deserializer.Deserialize(ms); return(Ok(responseJson)); } catch (Exception ex) { Console.WriteLine(ex.Message); //XmlSerializer serializer = new XmlSerializer(typeof(Error)); //var ms = new MemoryStream(Encoding.UTF8.GetBytes(content)); //Error error = (Error)serializer.Deserialize(ms); return(NotFound(ex.Message)); } }
/// <summary> /// Build USPS AddressValidateRequest XML from Excel Source data matrix /// Deserialize each USPS Response /// Parse response to format and store Address and Carrier Route /// </summary> public void USPSAddressValidateRequest() { XmlSerializer x = new XmlSerializer(typeof(AddressValidateResponse)); AddressValidateResponseAddress[] addressResponse; //Clear lists when new file loaded _parsedResponse.AddressPlusCarrier.Clear(); _parsedResponse.CarrierPlusTally.Clear(); #region Builder pattern for building each XML request for (int k = 0; k < _excel.wsRowCount; ++k) { _director.Construct(_builder, _excel, k); _bproduct = _builder.Retrieve(); string xData = _webTool.AddressValidateReq(_bproduct); AddressValidateResponse myResponse = (AddressValidateResponse)x.Deserialize(new StringReader(xData)); addressResponse = myResponse.Items; #region Debug //===================== DEBUG - PRINT OUT RESPONSE PARSED ================================= Debug.WriteLine($"Address: {addressResponse[0].Address2}"); Debug.WriteLine($"City: {addressResponse[0].City} | State: {addressResponse[0].State} | Zip: {addressResponse[0].Zip5}"); Debug.WriteLine($"Carrier: {addressResponse[0].CarrierRoute}"); #endregion //Store the response address and carrier route (Prepare for report 1) _parsedResponse.AddressPlusCarrier.Add(new string[2] { $"{addressResponse[0].Address2} {addressResponse[0].City} {addressResponse[0].State} {addressResponse[0].Zip5}", $"{addressResponse[0].CarrierRoute}" }); //Store the carrier route and tally any repeats (Prepare for report 2) try { if (_parsedResponse.CarrierPlusTally.ContainsKey(addressResponse[0].CarrierRoute)) { _parsedResponse.CarrierPlusTally[addressResponse[0].CarrierRoute]++; } else { _parsedResponse.CarrierPlusTally.Add(addressResponse[0].CarrierRoute, 1); } } catch (ArgumentNullException) { if (_parsedResponse.CarrierPlusTally.ContainsKey("N/A")) { _parsedResponse.CarrierPlusTally["N/A"]++; } else { _parsedResponse.CarrierPlusTally.Add("N/A", 1); } } } #endregion #region Validate req v1 /* * //Call AddressValidateRequest however many times there are # of rows in Excel Source * for (int p = 0; p<_excel.wsRowCount; ++p) * { * //string xData = _webTool.AddressValidateRequest("Address1", "Address2", "City", "State", "Zip5", "Zip4"); * string xData = _webTool.AddressValidateRequest( * "", * $"{_excel.dataMatrix[p, 0]} {_excel.dataMatrix[p, 1]} {_excel.dataMatrix[p, 2]}", * $"{ _excel.dataMatrix[p, 3]}", * $"{ _excel.dataMatrix[p, 4]}", * $"{ _excel.dataMatrix[p, 5]}", * ""); * * AddressValidateResponse myResponse = (AddressValidateResponse)x.Deserialize(new StringReader(xData)); * addressResponse = myResponse.Items; * * //===================== DEBUG - PRINT OUT RESPONSE PARSED ================================= * Debug.WriteLine($"Loop iteration: {p}"); * Debug.WriteLine($"Address: {addressResponse[0].Address2}"); * Debug.WriteLine($"City: {addressResponse[0].City} | State: {addressResponse[0].State} | Zip: {addressResponse[0].Zip5}"); * Debug.WriteLine($"Carrier: {addressResponse[0].CarrierRoute}"); * * //Store the response address and carrier route (Prepare for report 1) * _parsedResponse.AddressPlusCarrier.Add(new string[2] { $"{addressResponse[0].Address2} {addressResponse[0].City} {addressResponse[0].State} {addressResponse[0].Zip5}", $"{addressResponse[0].CarrierRoute}" }); * * //Store the carrier route and tally any repeats (Prepare for report 2) * if (_parsedResponse.CarrierPlusTally.ContainsKey(addressResponse[0].CarrierRoute)) * { * _parsedResponse.CarrierPlusTally[addressResponse[0].CarrierRoute]++; * } * else * { * _parsedResponse.CarrierPlusTally.Add(addressResponse[0].CarrierRoute, 1); * } * } */ #endregion Debug.WriteLine("AddressValidationComplete"); }