MrMistreater

Postal code lookup using webservice

May 20th, 2012
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.88 KB | None | 0 0
  1. public static class PostalLookup
  2.     {
  3.         public static Postal Find(string countryCode, string postalCode)
  4.         {
  5.            
  6.             // remove letters from postal code
  7.             postalCode = Regex.Replace(postalCode, "[^0-9]", "");
  8.  
  9.             if (string.IsNullOrEmpty(postalCode) || postalCode.Length != 4)
  10.                 return null;
  11.  
  12.             if (string.IsNullOrEmpty(countryCode))
  13.                 return null;
  14.  
  15.  
  16.             // create the web request to the GeoNames interface
  17.             const string geoNamesUrl = "http://ws.geonames.org/postalCodeLookupJSON?postalcode={0}&country={1}";
  18.             WebRequest geoNamesRequest = WebRequest.Create(String.Format(geoNamesUrl, postalCode, countryCode));
  19.  
  20.             // make the call
  21.             WebResponse geoNamesResponse = geoNamesRequest.GetResponse();
  22.  
  23.             // grab the response stream
  24.             var geoNamesReader = new StreamReader(geoNamesResponse.GetResponseStream());
  25.  
  26.             // put the whole response in a string
  27.             string geoNamesContent = geoNamesReader.ReadToEnd();
  28.  
  29.             try
  30.             {
  31.  
  32.                 JObject o = JObject.Parse(geoNamesContent);
  33.                 var postal = new Postal
  34.                                      {
  35.                                          Code = (string)o["postalcodes"][0]["postalcode"],
  36.                                          PlaceName = (string)o["postalcodes"][0]["placeName"],
  37.                                          County = (string)o["postalcodes"][0]["adminName1"]
  38.                                      };
  39.                 return postal;
  40.             }
  41.             catch
  42.             {
  43.                 return null;
  44.             }
  45.         }
  46.     }
  47.  
  48.     public class Postal
  49.     {
  50.         public string Code { get; set; }
  51.         public string PlaceName { get; set; }
  52.         public string County { get; set; }
  53.     }
Advertisement
Add Comment
Please, Sign In to add comment