private static bool SaveToXml(SiteSettings settings) { if (settings == null) return false; HttpContext context = HttpContext.Current; if (context == null) return false; string configPath = context.Server.MapPath(XmlConfigFile); XmlSerializer xml; FileStream fs = null; bool success = false; int numAttempts = 0; while (!success && numAttempts < 2) { try { numAttempts++; xml = new XmlSerializer(typeof(SiteSettings)); fs = new FileStream(configPath, FileMode.Create, FileAccess.ReadWrite, FileShare.None); xml.Serialize(fs, settings); success = true; } catch { // if an exception is thrown, there might have been a sharing violation; // we wait and try again (max: two attempts) success = false; System.Threading.Thread.Sleep(1000); } } if (fs != null) fs.Close(); return success; }
public static SiteSettings LoadFromConfiguration() { SiteSettings s = LoadFromXml(); if (s == null) { s = new SiteSettings(); s.SiteName = "Beefbooster.com"; s.SiteEmailAddress = "*****@*****.**"; s.ReportDataFolder = "~/App_Data/XML/"; SaveToXml(s); } return s; }
public static bool UpdateSettings(SiteSettings newSettings) { // write settings to code or db // update Application-wide settings, only over-writing settings that users should edit lock (BeefboosterHttpApplication.BeefboosterApplicationSettings) { // XML Report Data BeefboosterHttpApplication.BeefboosterApplicationSettings.ReportDataFolder = newSettings.ReportDataFolder; // Site Name BeefboosterHttpApplication.BeefboosterApplicationSettings.SiteName = newSettings.SiteName; // Contact Email Address for Site BeefboosterHttpApplication.BeefboosterApplicationSettings.SiteEmailAddress = newSettings.SiteEmailAddress; // Serialize to Xml Config File return SaveToXml(BeefboosterHttpApplication.BeefboosterApplicationSettings); } }