Skip to content

Instantly share code, notes, and snippets.

@restlessmedia
Created May 11, 2016 09:01
Show Gist options
  • Save restlessmedia/b1da84a9bf8fec751ea7e250edfc6f15 to your computer and use it in GitHub Desktop.
Save restlessmedia/b1da84a9bf8fec751ea7e250edfc6f15 to your computer and use it in GitHub Desktop.
public class WebConfiguration
{
public WebConfiguration(string path = "~", bool autoSave = true, bool autoRefresh = true)
{
if (string.IsNullOrWhiteSpace(path))
throw new ArgumentNullException("path");
_autoSave = autoSave;
_autoRefresh = autoRefresh;
_configuration = Open(path);
}
public void Compilation(bool debug = false)
{
const string sectionName = "system.web/compilation";
CompilationSection section = GetSection<CompilationSection>(sectionName);
section.Debug = debug;
OnUpdated(section, sectionName);
}
public void Trace(bool enabled = true, bool localOnly = true, bool mostRecent = false, bool pageOutput = false, int requestLimit = 10, TraceDisplayMode traceDisplayMode = TraceDisplayMode.SortByTime, bool writeToDiagnosticsTrace = false)
{
const string sectionName = "system.web/trace";
TraceSection section = GetSection<TraceSection>(sectionName);
section.Enabled = enabled;
section.LocalOnly = localOnly;
section.MostRecent = mostRecent;
section.PageOutput = pageOutput;
section.RequestLimit = requestLimit;
section.TraceMode = traceDisplayMode;
section.WriteToDiagnosticsTrace = writeToDiagnosticsTrace;
OnUpdated(section, sectionName);
}
public void Save()
{
_configuration.Save();
}
public void Restart()
{
System.Web.HttpRuntime.UnloadAppDomain();
}
private T GetSection<T>(string sectionName)
where T : ConfigurationSection
{
ConfigurationSection section = _configuration.GetSection(sectionName);
if (section == null)
throw new ConfigurationErrorsException(string.Format("Section '{0}' not found in config file.", sectionName));
if (section is T)
return (T)section;
throw new ConfigurationErrorsException(string.Format("Section '{0}' is not type '{1}'.", sectionName, typeof(T)));
}
private void OnUpdated(ConfigurationSection section, string sectionName)
{
if (_autoSave)
Save();
if (_autoRefresh)
ConfigurationManager.RefreshSection(sectionName);
}
private static Configuration Open(string path = "~")
{
return WebConfigurationManager.OpenWebConfiguration(path);
}
private readonly Configuration _configuration;
private readonly bool _autoSave;
private readonly bool _autoRefresh;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment