/// <summary> /// Compare the settings version with this version and, when different, update and prompt the user for a backup. /// </summary> /// <param name="notifyUser"></param> private static void CheckSettingsVersion(SerializableSettings settings) { #if !DEBUG int revision = Assembly.GetExecutingAssembly().GetName().Version.Revision; if (revision != settings.Revision) { DialogResult backupSettings = MessageBox.Show("The current EVEMon settings file is from a previous version of EVEMon. Backup the current file before proceeding (recommended)?", "EVEMon version changed", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (backupSettings == DialogResult.Yes) { using (SaveFileDialog fileDialog = new SaveFileDialog()) { fileDialog.Title = "Settings file backup"; fileDialog.Filter = "Settings Backup Files (*.bak)|*.bak"; fileDialog.FileName = String.Format(CultureConstants.DefaultCulture, "EVEMon_Settings_{0}.xml.bak", revision.ToString()); fileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal); DialogResult saveFile = fileDialog.ShowDialog(); if (saveFile != DialogResult.OK) { return; } FileHelper.OverwriteOrWarnTheUser(EveClient.SettingsFileNameFullPath, fileDialog.FileName); } } } #endif }
/// <summary> /// Saves settings immediately. /// </summary> public static async Task SaveImmediateAsync() { // Prevents the saving if we are restoring the settings at that time if (IsRestoring) { return; } // Reset flags s_savePending = false; s_nextSaveTime = DateTime.UtcNow.AddSeconds(10); try { SerializableSettings settings = Export(); // Save in settings file await FileHelper.OverwriteOrWarnTheUserAsync(EveMonClient.SettingsFileNameFullPath, async fs => { XmlSerializer xs = new XmlSerializer(typeof(SerializableSettings)); xs.Serialize(fs, settings); await fs.FlushAsync(); return(true); }); } catch (Exception exception) { ExceptionHandler.LogException(exception, true); } }
/// <summary> /// Applies the external calendar settings. /// </summary> /// <param name="settings">The settings.</param> internal void ApplyExternalCalendarSettings(SerializableSettings settings) { settings.Calendar.Provider = rbMSOutlook.Checked ? CalendarProvider.Outlook : CalendarProvider.Google; settings.Calendar.UseOutlookDefaultCalendar = rbDefaultCalendar.Checked; settings.Calendar.OutlookCustomCalendarPath = tbOutlookCalendarPath.Text.Trim(); settings.Calendar.GoogleEventReminder = cbGoogleReminder.SelectedIndex != -1 ? (GoogleCalendarReminder)cbGoogleReminder.SelectedIndex : GoogleCalendarReminder.Email; settings.Calendar.GoogleCalendarName = tbGoogleCalendarName.Text; settings.Calendar.UseReminding = cbSetReminder.Checked; int interval; if (int.TryParse(tbReminder.Text, out interval) && interval > 0) { settings.Calendar.RemindingInterval = interval; } settings.Calendar.UseAlternateReminding = cbUseAlterateReminder.Checked; settings.Calendar.EarlyReminding = dtpEarlyReminder.Value; settings.Calendar.LateReminding = dtpLateReminder.Value; settings.Calendar.LastQueuedSkillOnly = cbLastQueuedSkillOnly.Checked; }
/// <summary> /// Creates a serializable version of the settings. /// </summary> /// <returns></returns> public static SerializableSettings Export() { SerializableSettings serial = new SerializableSettings { SSOClientID = SSOClientID, SSOClientSecret = SSOClientSecret, Revision = Revision, Compatibility = Compatibility, Scheduler = Scheduler.Export(), Calendar = Calendar, CloudStorageServiceProvider = CloudStorageServiceProvider, PortableEveInstallations = PortableEveInstallations, LoadoutsProvider = LoadoutsProvider, MarketPricer = MarketPricer, Notifications = Notifications, Exportation = Exportation, Updates = Updates, Proxy = Proxy, G15 = G15, UI = UI }; serial.Characters.AddRange(EveMonClient.Characters.Export()); serial.ESIKeys.AddRange(EveMonClient.ESIKeys.Export()); serial.Plans.AddRange(EveMonClient.Characters.ExportPlans()); serial.MonitoredCharacters.AddRange(EveMonClient.MonitoredCharacters.Export()); return(serial); }
/// <summary> /// Sets the external calendar. /// </summary> /// <param name="settings">The settings.</param> internal void SetExternalCalendar(SerializableSettings settings) { // Google calendar reminder method cbGoogleReminder.Items.Clear(); cbGoogleReminder.Items.AddRange(GoogleCalendarEvent.ReminderMethods.ToArray()); rbMSOutlook.Checked = settings.Calendar.Provider == CalendarProvider.Outlook && ExternalCalendar.OutlookInstalled; rbGoogle.Checked = !rbMSOutlook.Checked; rbDefaultCalendar.Checked = settings.Calendar.UseOutlookDefaultCalendar; rbCustomCalendar.Checked = !rbDefaultCalendar.Checked; tbOutlookCalendarPath.Text = settings.Calendar.OutlookCustomCalendarPath; tbGoogleCalendarName.Text = settings.Calendar.GoogleCalendarName; cbGoogleReminder.SelectedIndex = (int)settings.Calendar.GoogleEventReminder; cbSetReminder.Checked = settings.Calendar.UseReminding; tbReminder.Text = settings.Calendar.RemindingInterval.ToString(CultureConstants. DefaultCulture); cbUseAlterateReminder.Checked = settings.Calendar.UseAlternateReminding; dtpEarlyReminder.Value = settings.Calendar.EarlyReminding; dtpLateReminder.Value = settings.Calendar.LateReminding; cbLastQueuedSkillOnly.Checked = settings.Calendar.LastQueuedSkillOnly; UpdateControlsVisibility(); }
public void SaveSettings() { try { var settingsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\BleckiTreeWriter"; if (!System.IO.Directory.Exists(settingsDirectory)) { System.IO.Directory.CreateDirectory(settingsDirectory); } var settingsPath = settingsDirectory + "\\settings.txt"; var settingsObject = new SerializableSettings { OpenDocuments = OpenDocuments.Select(d => new SerializableDocument { Path = d.FileName, Project = d.Owner.Path }).ToList(), OpenProjects = OpenProjects.Select(d => d.Path).ToList(), Dictionary = DictionaryBase, CustomDictionaryEntries = CustomDictionaryEntries }; System.IO.File.WriteAllText(settingsPath, JsonConvert.SerializeObject(settingsObject)); } catch (Exception e) { System.Windows.Forms.MessageBox.Show("Error saving settings.", "Alert!", System.Windows.Forms.MessageBoxButtons.OK); } }
/// <summary> /// Creates a seriablizable version of the settings. /// </summary> /// <returns></returns> public static SerializableSettings Export() { SerializableSettings serial = new SerializableSettings(); serial.Revision = Settings.Revision; serial.Compatibility = Settings.Compatibility; // Export characters and such serial.Characters = EveClient.Characters.Export(); serial.Accounts = EveClient.Accounts.Export(); serial.Plans = EveClient.Characters.ExportPlans(); serial.MonitoredCharacters = EveClient.MonitoredCharacters.Export(); // API providers serial.APIProviders = EveClient.APIProviders.Export(); // Scheduler serial.Scheduler = Scheduler.Export(); // User settings serial.Calendar = Settings.Calendar.Clone(); serial.Notifications = Settings.Notifications.Clone(); serial.Exportation = Settings.Exportation.Clone(); serial.Updates = Settings.Updates.Clone(); serial.Proxy = Settings.Proxy.Clone(); serial.IGB = Settings.IGB.Clone(); serial.G15 = Settings.G15.Clone(); serial.UI = Settings.UI.Clone(); return(serial); }
/// <summary> /// Constructor. /// </summary> public SettingsForm() { InitializeComponent(); m_settings = Settings.Export(); m_oldSettings = Settings.Export(); // Platform is Unix ? if (Environment.OSVersion.Platform == PlatformID.Unix) { runAtStartupComboBox.Enabled = false; treeView.Nodes["trayIconNode"].Remove(); } // Run with Mono ? if (Type.GetType("Mono.Runtime") != null) { treeView.Nodes["generalNode"].Nodes["g15Node"].Remove(); } // Fill the overview portraits sizes overviewPortraitSizeComboBox.Items.AddRange( Enum.GetValues(typeof(PortraitSizes)).Cast <PortraitSizes>().Select(x => { // Transforms x64 to 64 by 64 var size = x.ToString().Substring(1); return(String.Format("{0} by {0}", size)); }).ToArray()); // Expands the left panel and selects the first page and node. treeView.ExpandAll(); treeView.SelectedNode = treeView.Nodes[0]; multiPanel.SelectedPage = generalPage; }
public DrawAllIntoVolumeRenderPass(VoxelGIGraphicResources graphicsResources, SerializableSettings settings) { Dispose(); renderPassEvent = RenderPassEvent.BeforeRenderingOpaques; m_IsSetup = true; m_GraphicResources = graphicsResources; m_Settings = settings; }
public static void Serialize(SerializableSettings settings, string savePath) { var serializer = new XmlSerializer(typeof(SerializableSettings)); using (TextWriter writer = new StreamWriter(savePath)) { serializer.Serialize(writer, settings); } }
/// <summary> /// Creates new empty Settings file, overwriting the existing file. /// </summary> public static async Task ResetAsync() { s_settings = new SerializableSettings(); IsRestoring = true; Import(); await ImportDataAsync(); IsRestoring = false; }
public static void UpdateSettings(SerializableSettings s1, IWordCountBatchTaskSettings s2) { s2.CharactersPerLine = s1.CharactersPerLine; s2.Culture = s1.Culture; s2.IncludeSpaces = s1.IncludeSpaces; s2.InvoiceRates = s1.InvoiceRates; s2.ReportLockedSeperately = s1.ReportLockedSeperately; s2.UseLineCount = s1.UseLineCount; s2.UseSource = s1.UseSource; }
public static void Serialize(SerializableSettings settings, string savePath) { Contract.Requires <ArgumentNullException>(settings != null); Contract.Requires <ArgumentNullException>(!string.IsNullOrEmpty(savePath)); XmlSerializer serializer = new XmlSerializer(typeof(SerializableSettings)); using (TextWriter writer = new StreamWriter(savePath)) { serializer.Serialize(writer, settings); } }
public void Set(SerializableSettings ss) { this.Sensitivity = ss.sens; this.Fov = ss.fov; this.ZoomSensitivity = ss.zoomSens; this.ZoomFov = ss.zoomFov; this.Keybinds = new Dictionary <string, KeyCode[]>(); for (int i = 0; i < ss.keys.Length; i++) { this.Keybinds.Add(ss.keys[i], ss.commands[i].Clone() as KeyCode[]); // Note: Clone() is important to make sure the argument is deep copied } }
/// <summary> /// Asynchronously imports the settings. /// </summary> /// <param name="serial">The serial.</param> /// <param name="saveImmediate">if set to <c>true</c> [save immediate].</param> /// <returns></returns> public static async Task ImportAsync(SerializableSettings serial, bool saveImmediate = false) { s_settings = serial; Import(); IsRestoring = true; if (saveImmediate) { await SaveImmediateAsync(); } IsRestoring = false; }
/// <summary> /// Occurs when the user click "Apply". /// We set up the new settings if they have changed. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void applyButton_Click(object sender, EventArgs e) { ApplyToSettings(); if (!SettingsChanged) return; // Import the new settings await Settings.ImportAsync(m_settings, true); // Refresh the old settings m_oldSettings = Settings.Export(); }
public SerializableSettings AsSerializable() { SerializableSettings ss = new SerializableSettings(); ss.sens = this.Sensitivity; ss.fov = this.Fov; ss.zoomSens = this.ZoomSensitivity; ss.zoomFov = this.ZoomFov; ss.keys = this.Keybinds.Keys.ToArray(); ss.commands = this.Keybinds.Values.ToArray(); return(ss); }
/// <summary> /// Constructor. /// </summary> public SettingsForm() { InitializeComponent(); treeView.Font = FontFactory.GetFont("Tahoma", 9.75F); alwaysAskRadioButton.Font = FontFactory.GetFont("Tahoma", 8.25F, FontStyle.Bold); removeAllRadioButton.Font = FontFactory.GetFont("Tahoma", 8.25F, FontStyle.Bold); removeConfirmedRadioButton.Font = FontFactory.GetFont("Tahoma", 8.25F, FontStyle.Bold); settingsFileStorageControl.Font = FontFactory.GetFont("Tahoma", 8.25F); m_settings = Settings.Export(); m_oldSettings = Settings.Export(); }
public static SerializableSettings ConvertToSerializableSettings(IWordCountBatchTaskSettings settings) { var s = new SerializableSettings(); s.CharactersPerLine = settings.CharactersPerLine; s.Culture = settings.Culture; s.IncludeSpaces = settings.IncludeSpaces; s.InvoiceRates = settings.InvoiceRates; s.ReportLockedSeperately = settings.ReportLockedSeperately; s.UseLineCount = settings.UseLineCount; s.UseSource = settings.UseSource; return(s); }
/// <summary> /// Initialization for the EVEMon client. Will automatically load the settings file. /// </summary> /// <param name="applicationForm">The main application form</param> /// <exception cref="InvalidOperationException">The instance has been initialized already</exception> public static void InitializeFromFile() { // Creates the settings from the file SerializableSettings settings = TryDeserializeSettings(); // Loading from file failed, we create settings from scratch if (settings == null) { Reset(); } else { Import(settings, false); } }
/// <summary> /// Constructor. /// </summary> public SettingsForm() { InitializeComponent(); treeView.Font = FontFactory.GetFont("Tahoma", 9.75F); alwaysAskRadioButton.Font = FontFactory.GetFont("Tahoma", 8.25F, FontStyle.Bold); removeAllRadioButton.Font = FontFactory.GetFont("Tahoma", 8.25F, FontStyle.Bold); removeConfirmedRadioButton.Font = FontFactory.GetFont("Tahoma", 8.25F, FontStyle.Bold); settingsFileStorageControl.Font = FontFactory.GetFont("Tahoma", 8.25F); extraInfoComboBox.SelectedIndex = 0; m_settings = Settings.Export(); m_oldSettings = Settings.Export(); m_preSelect = null; }
/// <summary> /// Loads a settings file from a specified filepath and sets m_instance. /// </summary> /// <param name="filename">The fully qualified filename of the settings file to load</param> /// <returns>The Settings object loaded</returns> public static void Restore(string filename) { // Try deserialize string settingsFile = EveClient.SettingsFileNameFullPath; SerializableSettings settings = TryDeserializeBackup(filename, settingsFile, false); // Loading from file failed, we abort and keep our current settings if (settings == null) { MessageBox.Show(String.Format(CultureConstants.DefaultCulture, "Cannot restore the settings from {0}, the file is corrupted.", filename), "Bad settings file.", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } // Updates and save Import(settings, false); }
public SiteUtilBase CloneFreshSiteFromExisting(SiteUtilBase site) { // create new instance of this site with reset settings SerializableSettings s = new SerializableSettings() { Sites = new BindingList <SiteSettings>() }; s.Sites.Add(site.Settings); System.IO.MemoryStream ms = new System.IO.MemoryStream(); s.Serialize(ms); ms.Position = 0; SiteSettings originalSettings = SerializableSettings.Deserialize(new StreamReader(ms))[0]; return(CreateUtilFromShortName(site.Settings.UtilName, originalSettings)); }
public void Setup(VoxelGIGraphicResources graphicResources, SerializableSettings settings) { Dispose(); renderPassEvent = RenderPassEvent.BeforeRenderingPostProcessing; m_GraphicResources = graphicResources; m_Settings = settings; if (m_Settings._DrawFullScreenShader != null) { m_DrawFullScreenMaterial = new Material(m_Settings._DrawFullScreenShader); } else { m_DrawFullScreenMaterial = null; } }
/// <summary> /// Saves settings immediately. /// </summary> public static void SaveImmediate() { SerializableSettings settings = Export(); XmlSerializer xs = new XmlSerializer(typeof(SerializableSettings)); // Save in settings file FileHelper.OverwriteOrWarnTheUser(EveClient.SettingsFileNameFullPath, fs => { xs.Serialize(fs, settings); fs.Flush(); return(true); }); // Reset savePending flag m_lastSaveTime = DateTime.UtcNow; m_savePending = false; }
/// <summary> /// Constructor. /// </summary> public SettingsForm() { InitializeComponent(); treeView.Font = FontFactory.GetFont("Tahoma", 9.75F); alwaysAskRadioButton.Font = FontFactory.GetFont("Tahoma", 8.25F, FontStyle.Bold); removeAllRadioButton.Font = FontFactory.GetFont("Tahoma", 8.25F, FontStyle.Bold); removeConfirmedRadioButton.Font = FontFactory.GetFont("Tahoma", 8.25F, FontStyle.Bold); settingsFileStorageControl.Font = FontFactory.GetFont("Tahoma", 8.25F); m_settings = Settings.Export(); m_oldSettings = Settings.Export(); // Expands the left panel and selects the first page and node treeView.ExpandAll(); treeView.SelectedNode = treeView.Nodes.Cast <TreeNode>().First(); }
/// <summary> /// Asynchronously restores the settings from the specified file. /// </summary> /// <param name="filename">The fully qualified filename of the settings file to load</param> /// <returns>The Settings object loaded</returns> public static async Task RestoreAsync(string filename) { // Try deserialize s_settings = TryDeserializeFromBackupFile(filename, false); // Loading from file failed, we abort and keep our current settings if (s_settings == null) { return; } IsRestoring = true; Import(); await ImportDataAsync(); IsRestoring = false; }
/// <summary> /// loads the settings file, or the backup, prompting the user for errors. /// </summary> /// <returns><c>Null</c> if we have been unable to load anything from files, the generated settings otherwise</returns> private static SerializableSettings TryDeserializeSettings() { SerializableSettings settings = null; string settingsFile = EveClient.SettingsFileNameFullPath; string backupFile = settingsFile + ".bak"; // Check that a settings file or backup exists if (File.Exists(settingsFile)) { EveClient.Trace("Settings.TryDeserializeSettings() - begin"); // Check settings file length FileInfo settingsInfo = new FileInfo(settingsFile); if (settingsInfo.Length > 0) { // Gets the revision number of the assembly which generated this file int revision = Util.GetRevisionNumber(settingsFile); // Try to load from a file if (revision == 0) { // Old format settings = DeserializeOldFormat(settingsFile); } else { // New format settings = Util.DeserializeXML <SerializableSettings>(settingsFile); } // If the settings loaded OK, make a backup as 'last good settings' and return if (settings != null) { CheckSettingsVersion(settings); FileHelper.OverwriteOrWarnTheUser(settingsFile, backupFile); EveClient.Trace("Settings.TryDeserializeSettings() - done"); return(settings); } } } // Try to recover from the backup return(TryDeserializeBackup(backupFile, settingsFile, true)); }
/// <summary> /// Deserializes a settings file from an old format. /// </summary> /// <param name="filename"></param> /// <returns></returns> private static SerializableSettings DeserializeOldFormat(string filename) { var oldSerial = Util.DeserializeXML <OldSettings>(filename, Util.LoadXSLT(Properties.Resources.SettingsAndPlanImport)); var serial = new SerializableSettings(); // Accounts serial.Accounts.AddRange(oldSerial.Accounts); // Characters foreach (var oldCharacter in oldSerial.Characters) { // Adds the char both to the characters list and the monitored characters list. var character = new SerializableCCPCharacter { ID = oldCharacter.ID, Name = oldCharacter.Name, Guid = Guid.NewGuid() }; serial.MonitoredCharacters.Add(new MonitoredCharacterSettings { CharacterGuid = character.Guid }); serial.Characters.Add(character); } // Plans foreach (var oldPlan in oldSerial.Plans) { // Look for the owner by his name var owner = serial.Characters.SingleOrDefault(x => x.Name == oldPlan.Owner); if (owner == null) { continue; } // Imports the plan var plan = new SerializablePlan { Owner = owner.Guid, Name = oldPlan.Name }; plan.Entries.AddRange(oldPlan.Entries); serial.Plans.Add(plan); } return(serial); }
/// <summary> /// Initialization for the EVEMon client settings. /// </summary> /// <remarks> /// Will attempt to fetch and initialize settings from a storage server, if user has specified so. /// Otherwise attempts to initialize from a locally stored file. /// </remarks> public static void Initialize() { // Deserialize the local settings file to determine // which cloud storage service provider should be used s_settings = TryDeserializeFromFile(); // Try to download the settings file from the cloud CloudStorageServiceAPIFile settingsFile = s_settings?.CloudStorageServiceProvider?.Provider?.DownloadSettingsFile(); // If a settings file was downloaded try to deserialize it s_settings = settingsFile != null ? TryDeserializeFromFileContent(settingsFile.FileContent) : s_settings; // Loading settings // If there are none, we create them from scratch IsRestoring = true; Import(); IsRestoring = false; }
public static void Load(string filename) { var ser = new XmlSerializer(typeof(SerializableSettings)); if (File.Exists(filename)) { // check for old version of settings var xDoc = new XmlDocument(); xDoc.Load(filename); // old settings files started with <dictionary>. The new root is <settings>. bool oldVer = xDoc.DocumentElement != null && xDoc.DocumentElement.Name == "dictionary"; using (var fs = new FileStream(filename, FileMode.Open)) { if(oldVer) { // read from old version of settings ser = new XmlSerializer(typeof (SerializableDictionary<string, string>)); settings = SerializableSettings.FromSerializableDictionary( (SerializableDictionary<string, string>) ser.Deserialize(fs)); } else { settings = (SerializableSettings) ser.Deserialize(fs); } } } else { settings = new SerializableSettings(); using (var fs = new FileStream(filename, FileMode.Create)) { ser.Serialize(fs, settings); } } fileName = filename; }
private void btnEditSite_Click(object sender, EventArgs e) { SiteSettings siteSettings = (SiteSettings)bindingSourceSiteSettings.Current; // use a copy of the original settings so anything that is changed can be canceled SerializableSettings s = new SerializableSettings() { Sites = new BindingList<SiteSettings>() }; s.Sites.Add(siteSettings); System.IO.MemoryStream ms = new System.IO.MemoryStream(); s.Serialize(ms); ms.Position = 0; SiteSettings copiedSiteSettings = SerializableSettings.Deserialize(new StreamReader(ms))[0]; CreateEditSite frm = new CreateEditSite(); frm.Text = "Edit " + siteSettings.Name; frm.SiteSettingsBindingSource.DataSource = copiedSiteSettings; if (frm.ShowDialog() == DialogResult.OK) { // make sure the configuration is clean and for the cosen util copiedSiteSettings.AddConfigurationValues(frm.SiteUtil); // replace original settings object with the new one int index = bindingSourceSiteSettings.IndexOf(siteSettings); bindingSourceSiteSettings.RemoveCurrent(); bindingSourceSiteSettings.Insert(index, copiedSiteSettings); bindingSourceSiteSettings.Position = index; } }
public SiteUtilBase CloneFreshSiteFromExisting(SiteUtilBase site) { // create new instance of this site with reset settings SerializableSettings s = new SerializableSettings() { Sites = new BindingList<SiteSettings>() }; s.Sites.Add(site.Settings); System.IO.MemoryStream ms = new System.IO.MemoryStream(); s.Serialize(ms); ms.Position = 0; SiteSettings originalSettings = SerializableSettings.Deserialize(new StreamReader(ms))[0]; return CreateUtilFromShortName(site.Settings.UtilName, originalSettings); }
private void btnPublishSite_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(PluginConfiguration.Instance.email) || string.IsNullOrEmpty(PluginConfiguration.Instance.password)) { if (MessageBox.Show("Do you want to register an Email now?", "Registration required!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { RegisterEmail reFrm = new RegisterEmail(); reFrm.tbxEmail.Text = PluginConfiguration.Instance.email; reFrm.tbxPassword.Text = PluginConfiguration.Instance.password; if (reFrm.ShowDialog() == DialogResult.OK) { PluginConfiguration.Instance.email = reFrm.tbxEmail.Text; PluginConfiguration.Instance.password = reFrm.tbxPassword.Text; } } return; } foreach (SiteSettings site in siteList.SelectedObjects) { // set current Time to last updated in the xml, so it can be compared later DateTime lastUdpBkp = site.LastUpdated; site.LastUpdated = DateTime.Now; SerializableSettings s = new SerializableSettings() { Sites = new BindingList<SiteSettings>() }; s.Sites.Add(site); System.IO.MemoryStream ms = new System.IO.MemoryStream(); s.Serialize(ms); ms.Position = 0; System.Xml.XmlDocument siteDoc = new System.Xml.XmlDocument(); siteDoc.Load(ms); XmlWriterSettings xmlSettings = new XmlWriterSettings(); xmlSettings.Encoding = System.Text.Encoding.UTF8; xmlSettings.Indent = true; xmlSettings.OmitXmlDeclaration = true; StringBuilder sb = new StringBuilder(); XmlWriter writer = XmlWriter.Create(sb, xmlSettings); siteDoc.SelectSingleNode("//Site").WriteTo(writer); writer.Flush(); string siteXmlString = sb.ToString(); byte[] icon = null; string image = Path.Combine(Path.Combine(OnlineVideoSettings.Instance.ThumbsDir, "Icons"), site.Name + ".png"); if (File.Exists(image)) icon = File.ReadAllBytes(image); byte[] banner = null; image = Path.Combine(Path.Combine(OnlineVideoSettings.Instance.ThumbsDir, "Banners"), site.Name + ".png"); if (File.Exists(image)) banner = File.ReadAllBytes(image); bool success = false; try { string dll = Sites.SiteUtilFactory.RequiredDll(site.UtilName); OnlineVideosWebservice.OnlineVideosService ws = new OnlineVideos.OnlineVideosWebservice.OnlineVideosService(); string msg = ""; if (!string.IsNullOrEmpty(dll)) { string location = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "OnlineVideos\\") + dll + ".dll"; if (System.IO.File.Exists(location)) { byte[] data = System.IO.File.ReadAllBytes(location); System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); string md5LocalDll = BitConverter.ToString(md5.ComputeHash(data)).Replace("-", "").ToLower(); // check webservice if we need to submit the dll string md5RemoteDll = null; string owner = ws.GetDllOwner(dll, out md5RemoteDll); bool dllFound = md5RemoteDll != null; bool dllsAreEqual = dllFound ? md5RemoteDll == md5LocalDll : false; bool userIsOwner = dllFound ? owner == PluginConfiguration.Instance.email : true; if (!dllsAreEqual) { bool isAdmin = false; if (!userIsOwner) { if (MessageBox.Show("Only administrators can overwrite a DLL they don't own. I am an Admin. Proceed?", "New DLL - Admin required", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { isAdmin = true; } } if (userIsOwner || isAdmin) { string info = dllFound ? "DLL found on server differs from your local file, do you want to update the existing one?" : "Do you want to upload the required dll?"; if (MessageBox.Show(info, "DLL required", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { if (data == null) data = System.IO.File.ReadAllBytes(location); success = ws.SubmitDll(PluginConfiguration.Instance.email, PluginConfiguration.Instance.password, dll, data, out msg); MessageBox.Show(msg, success ? Translation.Instance.Success : Translation.Instance.Error, MessageBoxButtons.OK, success ? MessageBoxIcon.Information : MessageBoxIcon.Error); } } } } } success = ws.SubmitSite(PluginConfiguration.Instance.email, PluginConfiguration.Instance.password, siteXmlString, icon, banner, dll, out msg); MessageBox.Show(msg, success ? Translation.Instance.Success : Translation.Instance.Error, MessageBoxButtons.OK, success ? MessageBoxIcon.Information : MessageBoxIcon.Error); } catch (Exception ex) { MessageBox.Show(ex.Message, Translation.Instance.Error, MessageBoxButtons.OK, MessageBoxIcon.Error); } // if the site was not submitted, restore old last updated date, so saving won't write the wrong value if (!success) site.LastUpdated = lastUdpBkp; } }
/// <summary> /// Restore a backup /// </summary> /// <param name="settings"></param> public static void RestoreBackup(SerializableSettings settings) { lock (State.GlobalSync) { try { Program.Log("Restoring backup..."); Settings.ApplySettings(settings); Save(); Irc.Init(); Program.Log("Restarting..."); } catch (Exception ex) { Program.Log("Failed to restore backup to '" + ConfigFileName + "': " + ex.Message); } } }
void Publish(object sender) { // set current Time to last updated in the xml, so it can be compared later DateTime lastUdpBkp = Site.LastUpdated; Site.LastUpdated = DateTime.Now; SerializableSettings s = new SerializableSettings() { Sites = new BindingList<SiteSettings>() }; s.Sites.Add(Site); var siteDoc = new XmlDocument(); using (var ms = new MemoryStream()) { s.Serialize(ms); ms.Position = 0; siteDoc.Load(ms); } XmlWriterSettings xmlSettings = new XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true, OmitXmlDeclaration = true }; StringBuilder sb = new StringBuilder(); XmlWriter writer = XmlWriter.Create(sb, xmlSettings); siteDoc.SelectSingleNode("//Site").WriteTo(writer); writer.Flush(); string siteXmlString = sb.ToString(); byte[] icon = null; string image = Path.Combine(Path.Combine(OnlineVideoSettings.Instance.ThumbsDir, "Icons"), Site.Name + ".png"); if (File.Exists(image)) icon = File.ReadAllBytes(image); byte[] banner = null; image = Path.Combine(Path.Combine(OnlineVideoSettings.Instance.ThumbsDir, "Banners"), Site.Name + ".png"); if (File.Exists(image)) banner = File.ReadAllBytes(image); bool success = false; try { string dll = OnlineVideos.Sites.SiteUtilFactory.RequiredDll(Site.UtilName); var ws = new OnlineVideos.OnlineVideosWebservice.OnlineVideosService(); string msg = ""; if (!string.IsNullOrEmpty(dll)) { string location = Path.Combine(OnlineVideoSettings.Instance.DllsDir, dll + ".dll"); if (File.Exists(location)) { byte[] data = File.ReadAllBytes(location); System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); string md5LocalDll = BitConverter.ToString(md5.ComputeHash(data)).Replace("-", "").ToLower(); // check webservice if we need to submit the dll string md5RemoteDll = null; string owner = ws.GetDllOwner(dll, out md5RemoteDll); bool dllFound = md5RemoteDll != null; bool dllsAreEqual = dllFound ? md5RemoteDll == md5LocalDll : false; bool userIsOwner = dllFound ? owner == Email : true; if (!dllsAreEqual) { bool isAdmin = false; if (!userIsOwner) { if (MessageBox.Show("Only administrators can overwrite a DLL they don't own. I am an Admin. Proceed?", "New DLL - Admin required", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) { return; } } if (userIsOwner || isAdmin) { string info = dllFound ? "DLL found on server differs from your local file, do you want to update the existing one?" : "Do you want to upload the required dll?"; if (MessageBox.Show(info, "DLL required", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) { if (data == null) data = File.ReadAllBytes(location); success = ws.SubmitDll(Email, Password, dll, data, out msg); MessageBox.Show(msg, success ? Translation.Instance.Success : Translation.Instance.Error, MessageBoxButton.OK, success ? MessageBoxImage.Information : MessageBoxImage.Error); } } } } } success = ws.SubmitSite(Email, Password, siteXmlString, icon, banner, dll, out msg); MessageBox.Show(msg, success ? Translation.Instance.Success : Translation.Instance.Error, MessageBoxButton.OK, success ? MessageBoxImage.Information : MessageBoxImage.Error); } catch (Exception ex) { MessageBox.Show(ex.Message, Translation.Instance.Error, MessageBoxButton.OK, MessageBoxImage.Error); } // if the site was not submitted, restore old last updated date, so saving won't write the wrong value if (!success) Site.LastUpdated = lastUdpBkp; }