/// <summary> /// Private helper method to encapsulate the logic for loading and parsing the datafile. /// </summary> /// <param name="datafile">Location of a data file creating comma-separated pairs of /// old URLs and new URLs for use as redirection targets.</param> /// <returns></returns> private static RedirectionMap LoadMapFromFile(String datafile) { log.Trace("Enter LoadMapFromFile()."); SimpleRedirectorConfigurationSection config = SimpleRedirectorConfigurationSection.Get(); char[] separators = new char[1]; separators[0] = config.DataSource.Separator; RedirectionMap map = new RedirectionMap(); try { if (!File.Exists(datafile)) { log.ErrorFormat("Datafile '{0}' not found.", datafile); throw new FileNotFoundException(datafile); } } catch (Exception ex) { log.ErrorFormat("Error while loading urls from {0}.", ex, datafile); // Swallow the exception. The worst case is we return an empty dictionary // and nothing gets redirected. } String[] listOfUrlPairs = File.ReadAllLines(datafile); foreach (String urlPair in listOfUrlPairs) { String[] urls = urlPair.Trim().Split(separators); if (urls.Length >= 2) { try { map.Add(urls[0], urls[1]); } catch (Exception ex) { log.ErrorFormat("Duplicate URL found in RedirectMap: {0}", ex, urls[0]); } } if (urls.Length != 2) { // We can recover from this problem. No exception needed. log.WarnFormat("Expected only two urls, found {0} in '{1}'.", urls.Length, urlPair); } } return(map); }
/// <summary> /// Private helper to find the redirection URL mapped to a given input URL. /// </summary> /// <param name="url">The URL to examine for a replacement</param> /// <param name="context"></param> /// <returns></returns> private String GetRedirectUrl(String url, HttpContext context) { String redirect = null; string urlWithSlash; if (url.LastIndexOf("/") == url.Length - 1) { urlWithSlash = url; url = url.Substring(0, url.Length - 1); } else { urlWithSlash = url + "/"; } SimpleRedirectorConfigurationSection config = SimpleRedirectorConfigurationSection.Get(); String datafile = HttpContext.Current.Server.MapPath(config.DataSource.DataFile); RedirectionMap urlMap = RedirectionMap.GetMap(datafile, context); if (urlMap.Contains(url)) { if (urlMap.ContainsMultiple(url)) { log.DebugFormat("Url: '{0}' has multiple instances in redirect map.", url); } redirect = urlMap[url]; log.DebugFormat("Url '{0}' found; redirects to '{1}'.", url, redirect); } else if (urlMap.Contains(urlWithSlash)) { if (urlMap.ContainsMultiple(urlWithSlash)) { log.DebugFormat("Url: '{0}' has multiple instances in redirect map.", urlWithSlash); } redirect = urlMap[urlWithSlash]; log.DebugFormat("Url '{0}' found; redirects to '{1}'.", urlWithSlash, redirect); } else { log.DebugFormat("No match found for url '{0}.", url); } return(redirect); }