A ConfigurationManager wrapper that allows the developer to store credentials and a like settings in a machine specific config file that takes precedence when loading over web.config
This file contains 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
public class MachineConfigurationManager | |
{ | |
private const string ConfigFileCacheKey = "ConfigFileCacheKey"; | |
private static readonly ILog Logger = LogManager.GetLogger(typeof(MachineConfigurationManager)); | |
public static void Init() | |
{ | |
var _file = GetConfigFile(); | |
if (!_file.Exists) | |
{ | |
if (Logger.IsInfoEnabled) | |
{ | |
Logger.InfoFormat("No machine specific configuration exists. {0} is created.", _file.FullName); | |
} | |
var _appSettings = new Dictionary<string, string>(); | |
foreach (var _key in ConfigurationManager.AppSettings.AllKeys) | |
{ | |
_appSettings.Add(_key, ConfigurationManager.AppSettings[_key]); | |
} | |
File.WriteAllText(_file.FullName, JsonConvert.SerializeObject(_appSettings, Formatting.Indented)); | |
} | |
} | |
public static MachineAppSetting AppSettings | |
{ | |
get | |
{ | |
return new MachineAppSetting(); | |
} | |
} | |
private static FileInfo GetConfigFile() | |
{ | |
return new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "\\machine." + Environment.MachineName.ToLower() + ".config"); | |
} | |
public class MachineAppSetting | |
{ | |
public string this[string key] | |
{ | |
get | |
{ | |
Dictionary<string, string> _appSettings = (Dictionary<string, string>)HttpRuntime.Cache.Get(ConfigFileCacheKey); | |
if (_appSettings == null) | |
{ | |
_appSettings = JsonConvert.DeserializeObject<Dictionary<string,string>>(File.ReadAllText(GetConfigFile().FullName)); | |
HttpRuntime.Cache.Add( | |
ConfigFileCacheKey, | |
_appSettings, | |
new CacheDependency(GetConfigFile().FullName), | |
Cache.NoAbsoluteExpiration, | |
TimeSpan.FromDays(1), | |
CacheItemPriority.AboveNormal, | |
delegate(string s, object value, CacheItemRemovedReason reason) | |
{ | |
if (Logger.IsInfoEnabled) | |
{ | |
Logger.InfoFormat("Machine configuration cache is cleared (Reason: " + reason + ")"); | |
} | |
}); | |
} | |
if (_appSettings.ContainsKey(key)) | |
{ | |
return _appSettings[key]; | |
} | |
return ConfigurationManager.AppSettings[key]; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment