Created
June 12, 2021 14:10
-
-
Save hubert17/ee32f12e330ae1fa701895f1d19b27dc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Net; | |
using System.Threading.Tasks; | |
using System.Xml.Linq; | |
public class USPSAddress | |
{ | |
public string Id { get; set; } | |
public string City { get; set; } | |
public string State { get; set; } | |
public string Zip5 { get; set; } | |
} | |
public static class USPSHelper | |
{ | |
public static USPSAddress CityStateLookup(string USPS_UserID, string zip5) | |
{ | |
if (zip5.Length < 5) | |
return null; | |
XDocument requestDoc = new XDocument( | |
new XElement("CityStateLookupRequest", | |
new XAttribute("USERID", USPS_UserID), | |
new XElement("Revision", "1"), | |
new XElement("ZipCode", new XAttribute("ID", "0"), new XElement("Zip5", zip5.Substring(0, 5))) | |
) | |
); | |
try | |
{ | |
var url = "http://production.shippingapis.com/ShippingAPI.dll?API=CityStateLookup&XML=" + requestDoc; | |
Console.WriteLine(url); | |
var client = new WebClient(); | |
var response = client.DownloadString(url); | |
var xdoc = XDocument.Parse(response.ToString()); | |
Console.WriteLine(xdoc.ToString()); | |
USPSAddress uspsAddress = xdoc.Descendants("ZipCode").Select(s => new USPSAddress | |
{ | |
Id = GetXMLAttribute(s, "ID"), | |
City = GetXMLElement(s, "City"), | |
State = GetXMLElement(s, "State"), | |
Zip5 = GetXMLElement(s, "Zip5") | |
}).Where(x => !string.IsNullOrEmpty(x.Zip5)).FirstOrDefault(); | |
return uspsAddress; | |
} | |
catch | |
{ | |
return null; | |
} | |
} | |
public static string GetXMLElement(XElement element, string name) | |
{ | |
var el = element.Element(name); | |
if (el != null) | |
{ | |
return el.Value; | |
} | |
return ""; | |
} | |
public static string GetXMLAttribute(XElement element, string name) | |
{ | |
var el = element.Attribute(name); | |
if (el != null) | |
{ | |
return el.Value; | |
} | |
return ""; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment