/// <summary> /// Deserialize the json zip/coord mapping file into a dictionary object /// </summary> /// <returns>ZipCodeDictionary zipCodes</returns> private static ZipCodeDictionary LoadDictionary() { // - Get the context object for the current HTTP request and map the physical filepath to the // relative filepath (the relative filepath is specified in the Web.config). // - Read the json file using StreamReader. // - Deserialize the json data into a ZipCodeDictionary object. string locZipFilePath = HttpContext.Current.Server.MapPath(_zipFilePath); try { using (StreamReader r = new StreamReader(locZipFilePath)) { string json = r.ReadToEnd(); ZipCodeDictionary zipCodes = JsonConvert.DeserializeObject <ZipCodeDictionary>(json); return(zipCodes); } } catch (FileNotFoundException ex) { log.ErrorFormat("LoadDictionary(): Path {0} not found.", ex, locZipFilePath); return(null); } catch (Exception ex) { log.ErrorFormat("LoadDictionary(): Failed to read dictionary file on path {0}", ex, locZipFilePath); return(null); } }
/// <summary> /// Static constructor - initializes ZipCodeDictionary object /// A static class constructor is gauranteed to be called first and only once. /// </summary> static ZipCodeGeoLookup() { _zipFilePath = ConfigurationManager.AppSettings["ZipCodesJsonMap"]; log = LogManager.GetLogger(typeof(ZipCodeGeoLookup)); zipCodeDictionary = LoadDictionary(); WatchDictionaryFile(); }
/// <summary> /// Locking method to safely handle file removal after the initial load /// </summary> static void GuaranteeData() { Object lockObject = new Object(); if (zipCodeDictionary == null) { lock (lockObject) { if (zipCodeDictionary == null) { zipCodeDictionary = LoadDictionary(); } } } }
/// <summary> /// Check against the dictionary of zipcodes and return a ZipCodeGeoEntry object /// if a match is found. /// </summary> /// <param name="zipCodeEntry">5-digit zip code string</param> /// <returns>ZipCodeGeoEntry or null if no match</returns> public GeoLocation GetZipCodeGeoEntry(string zipCodeEntry) { GuaranteeData(); // Guarantee we have data before trying to load it. ZipCodeDictionary zipDict = zipCodeDictionary; if (zipDict != null && zipDict.ContainsKey(zipCodeEntry)) { ZipCodeGeoEntry zip = zipDict[zipCodeEntry]; return(new GeoLocation(zip.Latitude, zip.Longitude)); } else { return(null); } }
/// <summary> /// Event handler for .json file in the Configuration\files directory being modified or created. /// Loads the dictionary again upon file update and logs modify/create event. /// </summary> /// <param name="src">event source (not used)</param> /// <param name="e">event arguments (not used)</param> private static void OnChange(object src, FileSystemEventArgs e) { zipCodeDictionary = LoadDictionary(); log.Warn("OnChange(): Dictionary file was updated."); }