We Recommend

Accelerated C# 2008 Accelerated C# 2008
This book is both a rapid tutorial and a permanent reference. You’ll quickly master C# syntax while learning how the CLR simplifies many programming tasks. You’ll also learn best practices that ensure your code will be efficient, reusable, and robust. Why spend months or years discovering the best ways to design and code C# when this book will show you how to do things the right way, right from the start?


Posted By

abry on 07/10/09


Tagged

database code city postal geographical


Versions (?)


Who likes this?

2 people have marked this snippet as a favorite

paelgr
umang_nine


Postal code


Published in: C# 


URL: http://blog.brynildsen.com

See my blog

  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. }

Report this snippet 

You need to login to post a comment.