/// <summary> /// Server Constructor /// </summary> /// <remarks>Defaults to using a config file in the same location as the executing assembly.</remarks> public EMMServer() { mSettings = new Config(this); mMinecraftSettings = new MCServerProperties(this); mMinecraftWhitelist = new SettingsFile(this, Path.Combine(mSettings.MinecraftRoot, "white-list.txt"), ' '); mParser = new CommandParser(this); mScheduler = new Scheduler.SchedulerManager(this); mPowerManager = new PowerManager(this); mUserManager = new UserManager(this); mServerSaving = false; ServerStatus = Status.Stopped; mSavedUsers = new ArrayList(); mOnlineUsers = new ArrayList(); mAutoSaveBlocks = 0; mAutoSaveEnabled = true; // See if we need to swap in a new config file, and load current config. mMinecraftSettings.LookForNewSettings(); mMinecraftWhitelist.LookForNewSettings(); mScheduler.LoadSchedule(Path.Combine(mSettings.ServerManagerRoot, "scheduler.xml")); mScheduler.Start(); mUserManager.UpdateAllPositionsFromFile(); mUserManager.MonitorUserFiles(); }
public void LoadAccounts() { storedAccounts.Clear(); string[] fileNames = Directory.GetFiles( Paths.DataDirectory, "*.account" ); foreach( string fileName in fileNames ) { try { SettingsFile sf = new SettingsFile(); sf.Load( fileName ); SignInAccount newAccount = new SignInAccount { SignInUsername = sf.GetString( "SignInUsername", "" ), PlayerName = sf.GetString( "PlayerName", "" ), Password = sf.GetString( "Password", "" ), LastUrl = sf.GetString( "LastUrl", "" ) }; if( newAccount.Password.Length > 0 ) { newAccount.Password = PasswordSecurity.DecryptPassword( newAccount.Password ); } string tickString = sf.GetString( "SignInDate", "0" ); long ticks; if( Int64.TryParse( tickString, out ticks ) && ticks > DateTime.MinValue.Ticks && ticks <= DateTime.MaxValue.Ticks ) { newAccount.SignInDate = new DateTime( ticks ); } else { newAccount.SignInDate = DateTime.MinValue; } AddAccount( newAccount ); } catch( Exception ex ) { MainForm.Log( "AccountManager.LoadAccounts: " + ex ); } } SaveAllAccounts(); }
public void Test_SettingsFile_With_Copyright() { string path = Path.Combine(TestBase.TestFilePath, "SettingsFile", "Copyright.StyleCop"); SettingsFile target = new SettingsFile(path); Assert.IsNull(target.CompanyName); Assert.AreEqual("Bar", target.Copyright); }
public void Save() { SettingsFile sf = new SettingsFile(); sf.Set( "SignInUsername", SignInUsername ); sf.Set( "PlayerName", PlayerName ); sf.Set( "Password", PasswordSecurity.EncryptPassword( Password ) ); sf.Set( "LastUrl", LastUrl ); sf.Set( "SignInDate", SignInDate.Ticks ); sf.Save( FileName ); }
public GARITS() { InitializeComponent(); permissions = new Permissions(); try { settingsFile = new SettingsFile(); db = new Database(settingsFile.getSetting("dbserver"), settingsFile.getSetting("dbname"), settingsFile.getSetting("dbuser"), settingsFile.getSetting("dbpassword")); db.Connect(); permissions.readPermissions(db); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(1); } permissions.AddComponent(administrationToolStripMenuItem, "Administration Menu Item"); }
public KeybindForm(DS4 InputDevice, SettingsFile BindFile) { InitializeComponent(); kb = BindFile; device = InputDevice; labelBindHow.Text = Properties.Resources.STRING_BIND_HOW; labelTouchMode.Text = Properties.Resources.STRING_BIND_TOUCH_MODE; comboTouchMode.Items[0] = Properties.Resources.STRING_BIND_TOUCH_MOUSE; comboTouchMode.Items[1] = Properties.Resources.STRING_BIND_TOUCH_EXTRA; comboTouchMode.Items[2] = Properties.Resources.STRING_BIND_TOUCH_EMULATE; labelMovement.Text = Properties.Resources.STRING_BIND_MOVEMENT; labelCamera.Text = Properties.Resources.STRING_BIND_CAMERA; labelRightDead.Text = Properties.Resources.STRING_BIND_MOUSE_DEADZONE; labelRightSpeed.Text = Properties.Resources.STRING_BIND_MOUSE_SPEED; labelRightCurve.Text = Properties.Resources.STRING_BIND_MOUSE_CURVE; float rSpeed, rCurve, rDead; int touchMode; kb.Settings.Read("RightDead", out rDead); kb.Settings.Read("RightCurve", out rCurve); kb.Settings.Read("RightSpeed", out rSpeed); kb.Settings.Read("TouchMode", out touchMode); numRCurve.Value = (int)rCurve; numRSpeed.Value = (int)rSpeed; numRDeadzone.Value = (int)rDead; comboTouchMode.SelectedIndex = touchMode; // Set right stick panel to double buffered typeof(Panel).InvokeMember("DoubleBuffered", BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.NonPublic, null, panelRStickAxis, new object[] { true }); kb.Load(); RefreshKeyBindings(); }
public void AuthorItem_Update_UpdatesRemovingTheLastCertificate_Throws() { // Arrange var config = @" <configuration> <SectionName> <author name=""authorName""> <certificate fingerprint=""abcdefg"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""true"" /> </author> </SectionName> </configuration>"; var nugetConfigPath = "NuGet.Config"; using (var mockBaseDirectory = TestDirectory.Create()) { SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config); // Act and Assert var settingsFile = new SettingsFile(mockBaseDirectory); settingsFile.TryGetSection("SectionName", out var section).Should().BeTrue(); section.Should().NotBeNull(); section.Items.Count.Should().Be(1); var item = section.Items.First() as AuthorItem; var updatedItem = item.Clone() as AuthorItem; updatedItem.Certificates.Clear(); // Act and Assert var ex = Record.Exception(() => item.Update(updatedItem)); ex.Should().NotBeNull(); ex.Should().BeOfType <InvalidOperationException>(); ex.Message.Should().Be("A trusted signer entry must have at least one certificate entry."); } }
public void SettingSection_AddOrUpdate_AddsAnElementCorrectly() { // Arrange var nugetConfigPath = "NuGet.Config"; var config = @" <configuration> <Section> <add key='key0' value='value0' /> <add key='key1' value='value1' meta1='data1' meta2='data2'/> </Section> </configuration>"; using (var mockBaseDirectory = TestDirectory.Create()) { SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config); var configFileHash = SettingsTestUtils.GetFileHash(Path.Combine(mockBaseDirectory, nugetConfigPath)); var settingsFile = new SettingsFile(mockBaseDirectory); // Act var section = settingsFile.GetSection("Section"); section.Should().NotBeNull(); section.Items.Count.Should().Be(2); settingsFile.AddOrUpdate("Section", new AddItem("key2", "value2")); section = settingsFile.GetSection("Section"); section.Should().NotBeNull(); section.Items.Count.Should().Be(3); settingsFile.SaveToDisk(); var updatedFileHash = SettingsTestUtils.GetFileHash(Path.Combine(mockBaseDirectory, nugetConfigPath)); updatedFileHash.Should().NotBeEquivalentTo(configFileHash); } }
private static ActionOnDevice laterConfigure() { // Read the entire file before connecting to the device. String filename = nextArgument(); List <String> warnings = new List <string>(); SmcSettings settings = SettingsFile.load(filename, warnings, 0); Smc.fixSettings(settings, warnings, 0); // Handle any warnings. if (warnings.Count != 0) { Console.WriteLine("There were problems with the settings file:"); foreach (String warning in warnings) { Console.WriteLine(" " + warning); } if (forceOption) { Console.WriteLine("The -f option is selected, so the settings will be applied anyway."); } else { throw new Exception("Aborted because of problems with settings file.\nUse the -f option to override and apply settings anyway."); } } // Return a delegate function that will get executed later after all // the command line arguments have been processed. return(delegate(Smc device) { // This is the line that actually applies the settings to the device. device.setSmcSettings(settings); }); }
public KeybindForm(Controller InputDevice, SettingsFile BindFile) { InitializeComponent(); kb = BindFile; device = InputDevice; float rSpeed, rCurve, rDead, touchMode; kb.Settings.Read("RightDead", out rDead); kb.Settings.Read("RightCurve", out rCurve); kb.Settings.Read("RightSpeed", out rSpeed); kb.Settings.Read("TouchMode", out touchMode); numRCurve.Value = (int)rCurve; numRSpeed.Value = (int)rSpeed; numRDeadzone.Value = (int)rDead; // Set right stick panel to double buffered typeof(Panel).InvokeMember("DoubleBuffered", BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.NonPublic, null, panelRStickAxis, new object[] { true }); kb.Load(); RefreshKeyBindings(); }
public RadarrSettings Provide() { dynamic settings = SettingsFile.Read(); return(new RadarrSettings { Hostname = settings.DownloadClients.Radarr.Hostname, BaseUrl = settings.DownloadClients.Radarr.BaseUrl, Port = (int)settings.DownloadClients.Radarr.Port, ApiKey = settings.DownloadClients.Radarr.ApiKey, MovieProfileId = (int)settings.DownloadClients.Radarr.MovieProfileId, MovieRootFolder = settings.DownloadClients.Radarr.MovieRootFolder, MovieMinimumAvailability = settings.DownloadClients.Radarr.MovieMinimumAvailability, MovieTags = settings.DownloadClients.Radarr.MovieTags.ToObject <int[]>(), AnimeProfileId = (int)settings.DownloadClients.Radarr.AnimeProfileId, AnimeRootFolder = settings.DownloadClients.Radarr.AnimeRootFolder, AnimeMinimumAvailability = settings.DownloadClients.Radarr.AnimeMinimumAvailability, AnimeTags = settings.DownloadClients.Radarr.AnimeTags.ToObject <int[]>(), SearchNewRequests = settings.DownloadClients.Radarr.SearchNewRequests, MonitorNewRequests = settings.DownloadClients.Radarr.MonitorNewRequests, UseSSL = (bool)settings.DownloadClients.Radarr.UseSSL, Version = settings.DownloadClients.Radarr.Version, }); }
public void UnknownItem_Update_UpdatesExistingAttributes() { // Arrange var nugetConfigPath = "NuGet.Config"; var config = @" <configuration> <Section> <Unknown old=""attr"" /> </Section> </configuration>"; var updateSetting = new UnknownItem("Unknown", attributes: new Dictionary <string, string>() { { "old", "newAttr" } }, children: null); using (var mockBaseDirectory = TestDirectory.Create()) { SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config); var settingsFile = new SettingsFile(mockBaseDirectory); // Act var section = settingsFile.GetSection("Section"); section.Should().NotBeNull(); var element = section.Items.FirstOrDefault() as UnknownItem; element.Should().NotBeNull(); element.Update(updateSetting); // Assert element.Attributes["old"].Should().Be("newAttr"); } }
private void SelectSettingsFile(string file) { Contract.Requires(settingsDirectory != null); Contract.Requires(file != null); lock (gate) { selectedSettingsFile = settingsFiles.FindByFullName(file); if (selectedSettingsFile == null) { LoadSettingsFiles(); selectedSettingsFile = settingsFiles.FindByFullName(file); } if (selectedSettingsFile != null) { selectedSettingsFile.Accessed(); } } RefreshCommands(); }
public void StoreClientCert_FindBy_ParsedCorrectly(string stringValue, X509FindType value) { // Arrange var config = $@" <configuration> <SectionName> <storeCert packageSource=""Contoso1"" findValue = ""42"" findBy = ""{stringValue}"" /> <storeCert packageSource=""Contoso2"" findValue = ""42"" findBy = ""{stringValue.ToLower()}"" /> <storeCert packageSource=""Contoso3"" findValue = ""42"" findBy = ""{stringValue.ToUpper()}"" /> </SectionName> </configuration>"; var nugetConfigPath = "NuGet.Config"; using (var mockBaseDirectory = TestDirectory.Create()) { SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config); // Act and Assert var settingsFile = new SettingsFile(mockBaseDirectory); var section = settingsFile.GetSection("SectionName"); section.Should().NotBeNull(); var items = section.Items.ToList(); items.Count.Should().Be(3); var storeClientCertItem = (StoreClientCertItem)items[0]; storeClientCertItem.FindType.Should().Be(value); var storeClientCertItemLowerCase = (StoreClientCertItem)items[1]; storeClientCertItemLowerCase.FindType.Should().Be(value); var storeClientCertItemUpperCase = (StoreClientCertItem)items[2]; storeClientCertItemUpperCase.FindType.Should().Be(value); } }
void tabs_SelectedIndexChanged( object sender, EventArgs e ) { if( !tabs.Visible ) { return; } if( tabs.SelectedTab == tabSignIn ) { AcceptButton = bSignIn; if( cSignInUsername.Text.Length == 0 ) { cSignInUsername.Focus(); } else if( tSignInPassword.Text.Length == 0 ) { tSignInPassword.Focus(); } else { tSignInUrl.Focus(); } } else if( tabs.SelectedTab == tabResume ) { AcceptButton = bResume; bResume.Focus(); } else if( tabs.SelectedTab == tabDirect ) { AcceptButton = bDirectConnect; tDirectUrl.Focus(); } else if( tabs.SelectedTab == tabOptions ) { AcceptButton = null; SettingsFile sf = new SettingsFile(); if( File.Exists( Paths.GameSettingsFile ) ) { sf.Load( Paths.GameSettingsFile ); } xFailSafe.Checked = sf.GetBool( "mc.failsafe", false ); } else { AcceptButton = null; } }
public void UpdateSettings(SettingsFile settingsFile) { ValidateSettings(settingsFile); settingsRepo.Update(settingsFile); ReloadSettings(); }
private void SaveSettings_Click(object sender, RoutedEventArgs e) { Console.WriteLine("Saving changes to settings file..."); SettingsFile.SaveToFile(Program.SettingsFilePath); Console.WriteLine(" Changes saved."); }
/// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { Contract.Ensures(initialized); Debug.WriteLine("Entering Initialize() of: {0}", this); Debug.WriteLine("Default selected settings file: " + Settings.Default.SelectedSettingsFile); base.Initialize(); AddOptionKey(SettingsOptionKey); ReadSettingsDirectory(); if (settingsDirectory != null) { var events = Dte.Events; Contract.Assume(events != null); // A reference to solutionEvents must be stored in a field so that event handlers aren't collected by the GC. solutionEvents = events.SolutionEvents; dteEvents = events.DTEEvents; Contract.Assume(solutionEvents != null); Contract.Assume(dteEvents != null); solutionEvents.Opened += SolutionOpened; solutionEvents.Renamed += SolutionRenamed; solutionEvents.BeforeClosing += SolutionClosing; dteEvents.OnBeginShutdown += BeginShutdown; settingFilesWatcher.Path = settingsDirectory.LocalPath; settingFilesWatcher.EnableRaisingEvents = true; lock (gate) { LoadSettingsFiles(); if (selectedSettingsFile == null) { var defaultFile = Settings.Default.SelectedSettingsFile; if (string.IsNullOrWhiteSpace(defaultFile) || !File.Exists(defaultFile) || !settingsDirectory.IsBaseOf(new Uri(defaultFile, UriKind.Absolute))) { if (File.Exists(originalSettingsFile.LocalPath)) { Debug.WriteLine("Importing original settings file: " + originalSettingsFile.LocalPath); ImportSettings(originalSettingsFile.LocalPath); } else { Debug.WriteLine("Exporting original settings file: " + originalSettingsFile.LocalPath); ExportCurrentSettings(originalSettingsFile.LocalPath); } } else { Debug.WriteLine("Default settings file found: " + defaultFile); selectedSettingsFile = settingsFiles.FindByFullName(defaultFile); } } } } var menus = GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (menus != null) { foreach (var command in InitializeCommands()) { menus.AddCommand(command); } } InitializePriorityCommands(); InitializeToolBar(); Contract.Assert(settingsDirectory == null || settingsDirectory.IsAbsoluteUri); Contract.Assert(settingsDirectory == null || settingsDirectory.IsFile); Contract.Assert(autoSettingsFile == null || autoSettingsFile.IsAbsoluteUri); Contract.Assert(autoSettingsFile == null || autoSettingsFile.IsFile); Contract.Assert(oldAutoSettingsFile == null || oldAutoSettingsFile.IsAbsoluteUri); Contract.Assert(oldAutoSettingsFile == null || oldAutoSettingsFile.IsFile); Contract.Assert(originalSettingsFile == null || originalSettingsFile.IsAbsoluteUri); Contract.Assert(originalSettingsFile == null || originalSettingsFile.IsFile); initialized = true; }
public void can_pass_filename_via_ctor() { file = new SettingsFile<AppSettings>("testfile", store); Assert.Equal("testfile" + FileExtension, file.FileName); }
private static UserSettings LoadUserSettings() { var store = new XmlFileStore(); var file = new SettingsFile<UserSettings>("User", store); return file.Load(); }
public async Task UpdateSettings(List <string> settingsFileNames) { foreach (string settingsFileName in settingsFileNames) { if (string.IsNullOrEmpty(settingsFileName)) { continue; } bool add = true; ISettingsPage existingPage = null; foreach (ISettingsPage setting in SettingsPages) { //Edge case for Settings without file if (setting.SettingsFile == null) { continue; } if (settingsFileName.Equals(setting.SettingsFile.FileInfo.FullName)) { add = false; existingPage = setting; break; } } if (add) { SettingsFile settingsFile = new SettingsFile(new FileInfo(settingsFileName)); switch (settingsFile.Type) { case SettingsFile.SettingsType.Vanilla: Application.Current.Dispatcher?.Invoke(() => SettingsPages.Add(new VanillaSettingsPage(this, settingsFile))); break; case SettingsFile.SettingsType.Bungee: if (EntityViewModel is NetworkViewModel) { Application.Current.Dispatcher?.Invoke(() => SettingsPages.Add(new ProxySettingsPage(this, settingsFile))); break; } goto default; default: Application.Current.Dispatcher?.Invoke(() => SettingsPages.Add(new DefaultSettingsPage(settingsFile))); break; } } bool remove = true; int removeIndex = 0; foreach (ISettingsPage setting in SettingsPages) { //Edge case for Settings without file if (setting.SettingsFile == null) { continue; } if (settingsFileName.Equals(setting.SettingsFile.FileInfo.FullName)) { remove = false; removeIndex = SettingsPages.IndexOf(setting); } } if (remove) { Application.Current.Dispatcher?.Invoke(() => SettingsPages.RemoveAt(removeIndex)); } if (!add && !remove) { await existingPage.SettingsFile.ReadText(); } } SortSettingsPages(); }
public void Awake() { Debug.LogWarningFormat("TLMRv" + TLMSingleton.majorVersion + " LOADING TLM "); SettingsFile tlmSettings = new SettingsFile { fileName = TLMConfigWarehouse.CONFIG_FILENAME }; Debug.LogWarningFormat("TLMRv" + TLMSingleton.majorVersion + " SETTING FILES"); try { GameSettings.AddSettingsFile(tlmSettings); } catch (Exception e) { SettingsFile tryLoad = GameSettings.FindSettingsFileByName(TLMConfigWarehouse.CONFIG_FILENAME); if (tryLoad == null) { Debug.LogErrorFormat("TLMRv" + majorVersion + " SETTING FILES FAIL!!! "); Debug.LogError(e.Message); Debug.LogError(e.StackTrace); } else { tlmSettings = tryLoad; } } Debug.LogWarningFormat("TLMRv" + TLMSingleton.majorVersion + " LOADING VARS "); m_savedShowNearLinesInCityServicesWorldInfoPanel = new SavedBool("showNearLinesInCityServicesWorldInfoPanel", Settings.gameSettingsFile, true, true); m_savedShowNearLinesInZonedBuildingWorldInfoPanel = new SavedBool("showNearLinesInZonedBuildingWorldInfoPanel", Settings.gameSettingsFile, false, true); m_savedOverrideDefaultLineInfoPanel = new SavedBool("TLMOverrideDefaultLineInfoPanel", Settings.gameSettingsFile, true, true); m_debugMode = new SavedBool("TLMdebugMode", Settings.gameSettingsFile, false, true); m_betaMapGen = new SavedBool("TLMbetaMapGen", Settings.gameSettingsFile, false, true); m_showDistanceInLinearMap = new SavedBool("TLMshowDistanceInLinearMap", Settings.gameSettingsFile, true, true); if (m_debugMode.value) { TLMUtils.doLog("currentSaveVersion.value = {0}, fullVersion = {1}", currentSaveVersion.value, fullVersion); } if (currentSaveVersion.value != fullVersion) { needShowPopup = true; } toggleOverrideDefaultLineInfoPanel(m_savedOverrideDefaultLineInfoPanel.value); LocaleManager.eventLocaleChanged += new LocaleManager.LocaleChangedHandler(this.autoLoadTLMLocale); if (instance != null) { GameObject.Destroy(instance); } loadTLMLocale(false); var fipalette = TLMUtils.EnsureFolderCreation(palettesFolder); if (Directory.GetFiles(TLMSingleton.palettesFolder, "*" + TLMAutoColorPalettes.EXT_PALETTE).Length == 0) { SavedString savedPalettes = new SavedString("savedPalettesTLM", Settings.gameSettingsFile, "", false); TLMAutoColorPalettes.ConvertLegacyPalettes(savedPalettes); //savedPalettes.Delete(); } onAwake?.Invoke(); }
private void OnClose(object sender, FormClosingEventArgs e) { SettingsFile.Save(ActivateKey); }
void LoadLauncherSettings() { Log( "LoadLauncherSettings" ); SettingsFile settings = new SettingsFile(); if( File.Exists( Paths.LauncherSettingsFile ) ) { settings.Load( Paths.LauncherSettingsFile ); } bool saveUsername = settings.GetBool( "rememberUsername", true ); bool multiUser = settings.GetBool( "multiUser", false ); bool savePassword = settings.GetBool( "rememberPassword", false ); bool saveUrl = settings.GetBool( "rememberServer", true ); GameUpdateMode gameUpdateMode = settings.GetEnum( "gameUpdateMode", GameUpdateMode.Ask ); StartingTab startingTab = settings.GetEnum( "startingTab", StartingTab.SignIn ); xRememberUsername.Checked = saveUsername; xMultiUser.Checked = multiUser; xRememberPassword.Checked = savePassword; xRememberServer.Checked = saveUrl; cGameUpdates.SelectedIndex = (int)gameUpdateMode; cStartingTab.SelectedIndex = (int)startingTab; settingsLoaded = true; }
// ==== Options tab ==== void SaveLauncherSettings( object sender, EventArgs e ) { if( !settingsLoaded ) return; Log( "SaveLauncherSettings" ); // confirm erasing accounts if( sender == xRememberUsername && !xRememberUsername.Checked && !ConfirmDialog.Show( "Forget all usernames?", "When you uncheck \"remember usernames\", all currently-stored account " + "information will be forgotten. Continue?" ) ) { xRememberUsername.Checked = true; lOptionsStatus.Text = ""; return; } // confirm forgetting accounts if( sender == xMultiUser && !xMultiUser.Checked && accounts.Count > 1 && !ConfirmDialog.Show( "Forget all other accounts?", "When you uncheck \"multiple accounts\", all account information other than " + "the currently-selected user will be forgotten. Continue?" ) ) { xMultiUser.Checked = true; lOptionsStatus.Text = ""; return; } SettingsFile settings = new SettingsFile(); settings.Set( "rememberUsername", xRememberUsername.Checked ); settings.Set( "multiUser", xMultiUser.Checked ); settings.Set( "rememberPassword", xRememberPassword.Checked ); settings.Set( "rememberServer", xRememberServer.Checked ); settings.Set( "gameUpdateMode", (GameUpdateMode)cGameUpdates.SelectedIndex ); settings.Set( "startingTab", (StartingTab)cStartingTab.SelectedIndex ); settings.Save( Paths.LauncherSettingsFile ); if( sender == xRememberUsername ) { if( xRememberUsername.Checked ) { xRememberPassword.Enabled = true; lOptionsStatus.Text = "Usernames will now be remembered."; xMultiUser.Enabled = true; } else { xRememberPassword.Checked = false; xRememberPassword.Enabled = false; xMultiUser.Checked = false; xMultiUser.Enabled = false; accounts.RemoveAllAccounts(); LoadAccounts(); lOptionsStatus.Text = "Usernames will no longer be remembered."; } SignInFieldChanged( null, EventArgs.Empty ); } else if( sender == xRememberPassword ) { if( xRememberPassword.Checked ) { lOptionsStatus.Text = "Passwords will now be remembered."; } else { lOptionsStatus.Text = "Passwords will no longer be remembered."; } SignInFieldChanged( null, EventArgs.Empty ); } else if( sender == xRememberServer ) { if( xRememberServer.Checked ) { lOptionsStatus.Text = "Last-joined server will now be remembered."; } else { lOptionsStatus.Text = "Last-joined server will no longer be remembered."; } } else if( sender == xMultiUser ) { if( xMultiUser.Checked ) { lOptionsStatus.Text = "All users will now be remembered."; } else { lOptionsStatus.Text = "Only most-recent user will now be remembered."; } LoadAccounts(); } else if( sender == cGameUpdates ) { lOptionsStatus.Text = "\"Game updates\" preference saved."; } else if( sender == cStartingTab ) { lOptionsStatus.Text = "\"Starting tab\" preference saved."; } else { lOptionsStatus.Text = "Preferences saved."; } }
public void Copyright_Should_Be_Empty_String_With_Default_Ctor() { SettingsFile target = new SettingsFile(); Assert.AreEqual(string.Empty, target.Copyright); }
public static InstallerConfig Load() { return(new InstallerConfig { InstallerState = SettingsFile.Load <Dictionary <string, IDictionary <string, string> > >(nameof(InstallerState)), }); }
public void Test_Empty_SettingsFile() { string path = Path.Combine(TestBase.TestFilePath, "SettingsFile", "Empty.StyleCop"); SettingsFile target = new SettingsFile(path); }
public void passing_null_filename_to_ctor_throws_argex() { Assert.Throws<ArgumentException>( () => file = new SettingsFile<AppSettings>(null, store)); }
public UserSettingsTest() { settings = new UserSettings(); store = MockRepository.GenerateMock<IXmlFileStore>(); file = new SettingsFile<UserSettings>(store); }
public PrimeWindowVM(SettingsFile settingsFile, Window primeWindow) { settingsFile?.FileStorages?.ForEach(x => _AllResources.Add(x)); _primeWindow = primeWindow; _settingsFile = settingsFile; }
public static PrimeWindowVM Create(SettingsFile settingsFile, Window primeWindow) { return(new PrimeWindowVM(settingsFile, primeWindow)); }
private void ValidateSettings(SettingsFile settingsFile) { }
static int Main(string[] args) { //1. Logger initialization Logger logger = LogManager.GetCurrentClassLogger(); int TimePart = 0; decimal PercentagePart = 0M; bool? RunSettingsPart = null; bool? HDDCheckSettingsPart = null; if (args.Length > 0) { if (args.Where(x => x.ToLower() == "-help").ToList().Count > 0) { logger.Info("-----------------------------------------------------------------------------"); logger.Info("-t for Time setting in mins"); logger.Info("-p for Percentage setting"); logger.Info("-r for Run setting (True/False)"); logger.Info("-h for HDD Check (True/False)"); logger.Info("Example : >N3PS.File.Compare.exe -hFalse"); logger.Info("Meaning program will be running 30 mins, 100% random record picked up and New table to be created for processing or not."); logger.Info("-----------------------------------------------------------------------------"); return(0); } try { var timePart = args.Where(x => x.ToLower().Contains("-t")).ToList(); if (timePart.Count > 0) { TimePart = Convert.ToInt32(timePart[0].ToLower().Replace("-t", "")); logger.Info($"TimePart Argument Value : {TimePart}"); } var percentagePart = args.Where(x => x.ToLower().Contains("-p")).ToList(); if (percentagePart.Count > 0) { PercentagePart = Convert.ToDecimal(percentagePart[0].ToLower().Replace("-p", "")); logger.Info($"PercentagePart Argument Value : {PercentagePart}"); } var runSettingsPart = args.Where(x => x.ToLower().Contains("-r")).ToList(); if (runSettingsPart.Count > 0) { RunSettingsPart = Convert.ToBoolean(runSettingsPart[0].ToLower().Replace("-r", "")); logger.Info($"RunSettingsPart Argument Value : {RunSettingsPart}"); } var runHddCheckPart = args.Where(x => x.ToLower().Contains("-h")).ToList(); if (runHddCheckPart.Count > 0) { HDDCheckSettingsPart = Convert.ToBoolean(runHddCheckPart[0].ToLower().Replace("-h", "")); logger.Info($"HDDCheckSettingsPart Argument Value : {HDDCheckSettingsPart}"); } } catch (Exception excp) { logger.Error("Error in processing the command level arguments. " + excp.ToString() + " --- " + excp.StackTrace); } } //2. XML File Initialization string FlatFileXmlName = @".\XMLFiles\FileFormat.xml"; string SettingsXmlName = @".\XMLFiles\Settings.xml"; //string ValidationRuleXmlName = @".\XMLFiles\ValidationRule.xml"; //3. Convert FlatFile to C# objects FlatFile flatFile = new FlatFile(); FlatFile fetchedFlatFileObj = flatFile.GetInstance(FlatFileXmlName, logger); if (fetchedFlatFileObj == null) { logger.Error($"Error while loading the Flat File XML : {FlatFileXmlName}"); return(0); } //4.Convert Settings File to C# objects SettingsFile settingsFile = new SettingsFile(); SettingsFile fetchedSettingsObj = settingsFile.GetInstance(SettingsXmlName, logger); if (fetchedSettingsObj == null) { logger.Error($"Error while loading the Settings File XML : {SettingsXmlName}"); return(0); } if (TimePart != 0) { logger.Info($"Overidden Time Part from Settings.xml: {TimePart}"); fetchedSettingsObj.Time = TimePart; } if (PercentagePart != 0M) { logger.Info($"Overidden Percentage from Settings.xml: {PercentagePart}"); fetchedSettingsObj.Percentage = PercentagePart; } if (RunSettingsPart != null) { logger.Info($"Overidden Run Settings from Settings.xml: {RunSettingsPart}"); fetchedSettingsObj.NewRun = RunSettingsPart.Value; } logger.Info("Settings : Start ----------------------"); logger.Info($"Time : {fetchedSettingsObj.Time}"); logger.Info($"Percentage : {fetchedSettingsObj.Percentage}"); logger.Info($"NewRun : {fetchedSettingsObj.NewRun}"); logger.Info("Settings : END ----------------------"); ////5. Convert ValidationRule to C# objects //ValidationRuleFile validationRuleFile = new ValidationRuleFile(); //ValidationRuleFile fetchedValidationRuleObj = validationRuleFile.GetInstance(ValidationRuleXmlName, logger); //if (fetchedValidationRuleObj == null) //{ // logger.Error($"Error while loading the Validation Rule File XML : {ValidationRuleXmlName}"); // return 0; //} //var dllsDetails = fetchedValidationRuleObj.ValidationRules.Where(x => x.DLLInfo != null && !string.IsNullOrEmpty(x.DLLInfo.DLLName) ).ToList(); //Hashtable assemblyDetails = new Hashtable(); //if (dllsDetails.Count() > 0) //{ // foreach (ValidationsRule rule in dllsDetails) // { // FileInfo f = new FileInfo(@".\ExternalDLLs\" + rule.DLLInfo.DLLName); // logger.Info($"Full File Name : {f.FullName}"); // if (!System.IO.File.Exists(f.FullName)) // { // logger.Error($"External DLL is not exist {rule.DLLInfo.DLLName} in ExternalDLLs folder."); // return 0; // } // else // { // Assembly assembly = Assembly.LoadFile(f.FullName); // assemblyDetails.Add(rule.ColumnNumber, assembly); // } // } //} //6. HDD Size Check if (HDDCheckSettingsPart == null) { HDDCheckSettingsPart = true; } //Check for free space if (HDDCheckSettingsPart.Value) { HDDCheck check = new HDDCheck(); bool isFreeSpaceAvailable = check.IsEnoughSpaceAvailable(fetchedFlatFileObj.FlatFilePath1, logger); if (!isFreeSpaceAvailable) { return(0); } } else { logger.Info("HDD Check is Skipped."); } //logger.Info($"Flat file Path : {fetchedFlatFileObj.FlatFilePath}"); string DBName = "ICA"; SQLiteHelper sqlManipulation = new SQLiteHelper(); bool isDBExist = sqlManipulation.IsDBExist(DBName); if (!isDBExist) { sqlManipulation.CreateDB(DBName, logger); } //SQLiteHelper sqlLite = new SQLiteHelper(); System.Data.SQLite.SQLiteConnection m_dbConnection = sqlManipulation.OpenDBConnection1(DBName); string tableName1 = "ICATable1"; string tableName2 = "ICATable2"; string tableNameDeleted1 = "ICADeletedTable1"; string tableNameInserted2 = "ICAInsertedTable2"; string CreateDeletedTableSQLQuery1 = flatFile.GetFlatFileDeletedTableScript(tableNameDeleted1, fetchedFlatFileObj); string CreateInsertedTableSQLQuery2 = flatFile.GetFlatFileInsertTableScript(tableNameInserted2, fetchedFlatFileObj); string processedtableName1 = "ProcessedICATable1"; string processedtableName2 = "ProcessedICATable2"; FileHelper helper = new FileHelper(); if (fetchedSettingsObj.NewRun) { string CreateTableSQLQuery1 = flatFile.GetFlatFileTableScript(tableName1, fetchedFlatFileObj); string CreateTableSQLQuery2 = flatFile.GetFlatFileTableScript(tableName2, fetchedFlatFileObj); string CreateProcessedTableSQLQuery1 = flatFile.CreateFlatFileTableScript(processedtableName1); string CreateProcessedTableSQLQuery2 = flatFile.CreateFlatFileTableScript(processedtableName2); bool isExist = sqlManipulation.CheckTableExists(m_dbConnection, tableName1, logger); if (isExist) { sqlManipulation.DeleteTable(m_dbConnection, DBName, tableName1, logger); } sqlManipulation.CreateTable(m_dbConnection, DBName, CreateTableSQLQuery1, logger); isExist = sqlManipulation.CheckTableExists(m_dbConnection, tableName2, logger); if (isExist) { sqlManipulation.DeleteTable(m_dbConnection, DBName, tableName2, logger); } sqlManipulation.CreateTable(m_dbConnection, DBName, CreateTableSQLQuery2, logger); //sqlManipulation.DeleteTable(DBName, processedtableName1, logger); //sqlManipulation.DeleteTable(DBName, processedtableName2, logger); //sqlManipulation.CreateTable(DBName, CreateTableSQLQuery1, logger); //sqlManipulation.CreateTable(DBName, CreateTableSQLQuery2, logger); isExist = sqlManipulation.CheckTableExists(m_dbConnection, processedtableName1, logger); if (isExist) { sqlManipulation.DeleteTable(m_dbConnection, DBName, processedtableName1, logger); } sqlManipulation.CreateTable(m_dbConnection, DBName, CreateProcessedTableSQLQuery1, logger); isExist = sqlManipulation.CheckTableExists(m_dbConnection, processedtableName2, logger); if (isExist) { sqlManipulation.DeleteTable(m_dbConnection, DBName, processedtableName2, logger); } sqlManipulation.CreateTable(m_dbConnection, DBName, CreateProcessedTableSQLQuery2, logger); isExist = sqlManipulation.CheckTableExists(m_dbConnection, tableNameDeleted1, logger); if (isExist) { sqlManipulation.DeleteTable(m_dbConnection, DBName, tableNameDeleted1, logger); } sqlManipulation.CreateTable(m_dbConnection, DBName, CreateDeletedTableSQLQuery1, logger); isExist = sqlManipulation.CheckTableExists(m_dbConnection, tableNameInserted2, logger); if (isExist) { sqlManipulation.DeleteTable(m_dbConnection, DBName, tableNameInserted2, logger); } sqlManipulation.CreateTable(m_dbConnection, DBName, CreateInsertedTableSQLQuery2, logger); //sqlManipulation.CreateTable(DBName, CreateProcessedTableSQLQuery1, logger); //sqlManipulation.CreateTable(DBName, CreateProcessedTableSQLQuery2, logger); //sqlManipulation.CloseDBConnection(m_dbConnection); //var conn = new SQLiteConnection( "foofoo"); List <DynamicClass1> objList = new List <DynamicClass1>(); //SQLiteConnection m_dbConnection1 = sqlManipulation.OpenDBConnection(DBName); // m_dbConnection1.CreateTable<DynamicClass1>(); helper.InsertInto(sqlManipulation, fetchedFlatFileObj, fetchedSettingsObj, m_dbConnection, DBName, tableName1, processedtableName1, fetchedFlatFileObj.FlatFilePath1, logger, objList, true); List <DynamicClass2> objList1 = new List <DynamicClass2>(); helper.InsertInto(sqlManipulation, fetchedFlatFileObj, fetchedSettingsObj, m_dbConnection, DBName, tableName2, processedtableName2, fetchedFlatFileObj.FlatFilePath2, logger, objList1, false); } int table1Records = sqlManipulation.GetTotalRecordsInTable1(m_dbConnection, tableName1, logger); //set logger.Info("Comaprison is started."); int table2Records = sqlManipulation.GetTotalRecordsInTable1(m_dbConnection, tableName2, logger); //List< ProcessedDetails1> list1 = m_dbConnection.Query<ProcessedDetails1>($"SELECT IsError, Count(1) AS TotalRecords FROM {processedtableName1} GROUP BY IsError"); m_dbConnection.Close(); Thread.Sleep(1000); m_dbConnection = null; GC.Collect(); GC.WaitForPendingFinalizers(); System.Data.SQLite.SQLiteConnection m_dbConnection1 = sqlManipulation.OpenDBConnection1(DBName); //m_dbConnection1.Open(); var list1 = sqlManipulation.GetTotalRecordsInTable(m_dbConnection1, $"SELECT IsError, Count(1) AS TotalRecords FROM {processedtableName1} GROUP BY IsError", logger); //m_dbConnection1.Open(); helper.Compare(fetchedFlatFileObj, fetchedSettingsObj, sqlManipulation, m_dbConnection1, DBName, tableName1, tableName2, processedtableName1, processedtableName2, tableNameDeleted1, tableNameInserted2, table1Records, list1, logger); int tab1 = sqlManipulation.GetTotalRecordsInTable1(m_dbConnection1, tableName1, logger); int tab2 = sqlManipulation.GetTotalRecordsInTable1(m_dbConnection1, tableName2, logger); int insTab = sqlManipulation.GetTotalRecordsInTable1(m_dbConnection1, tableNameInserted2, logger); int delTab = sqlManipulation.GetTotalRecordsInTable1(m_dbConnection1, tableNameDeleted1, logger); int fetchedTab1 = sqlManipulation.GetTotalRecordsInTable1(m_dbConnection1, processedtableName1, logger); int fetchedTab2 = sqlManipulation.GetTotalRecordsInTable1(m_dbConnection1, processedtableName2, logger); logger.Info("-----------------------Report--------------------------------"); logger.Info($"{tableName1} : {tab1}"); logger.Info($"{tableName2} : {tab2}"); logger.Info($"{tableNameInserted2} : {insTab}"); logger.Info($"{tableNameDeleted1} : {delTab}"); logger.Info($"{processedtableName1} : {fetchedTab1}"); logger.Info($"{processedtableName2} : {fetchedTab2}"); logger.Info("-------------------------------------------------------"); helper.WriteToFile(sqlManipulation, fetchedFlatFileObj, m_dbConnection1, DBName, tableNameInserted2, logger, insTab); helper.WriteToFile(sqlManipulation, fetchedFlatFileObj, m_dbConnection1, DBName, tableNameDeleted1, logger, delTab); sqlManipulation.CloseDBConnection(m_dbConnection1); /*DataSet dsTotalRecords = sqlManipulation.GetTotalRecords(m_dbConnection, tableName, logger); * FileHelper helper = new FileHelper(); * ProcessedDetails processedDetails = helper.ValidateFile(fetchedFlatFileObj, fetchedSettingsObj, fetchedValidationRuleObj, sqlManipulation, m_dbConnection, DBName, tableName, assemblyDetails, dsTotalRecords, logger); * * DataSet dsTotalRecords1 = sqlManipulation.GetTotalRecords(m_dbConnection, tableName, logger); * int totalRecords = 0; * int totalError = 0; * int totalSuccessProcessed = 0; * if (dsTotalRecords1 != null) * { * DataTable dt = dsTotalRecords1.Tables[0]; * foreach(DataRow dr in dt.Rows) * { * int tr = 0; * if(dr["TotalRecords"] != DBNull.Value) * { * tr = Convert.ToInt32(dr["TotalRecords"].ToString()); * if (dr["IsError"] != DBNull.Value && Convert.ToBoolean(dr["IsError"].ToString())) * { * totalError = totalError + tr; * } * else * { * * totalSuccessProcessed = totalSuccessProcessed + tr; * * } * * totalRecords = totalRecords + tr; * } * } * } * logger.Info("------------------------------------------------------------"); * logger.Info($"Total Records: " + processedDetails.TotalRecords); * logger.Info($"Total Records Processed: " + totalRecords);//(processedDetails.TotalErrorRecords + processedDetails.TotalSeccessfullyProcessedRecords)); * logger.Info($"Total Error Records: " + totalError);// processedDetails.TotalErrorRecords); * logger.Info($"Total Successfully Processed Records: " + totalSuccessProcessed);// processedDetails.TotalSeccessfullyProcessedRecords); * logger.Info("------------------------------------------------------------"); * sqlManipulation.CloseDBConnection(m_dbConnection); * * //sqlLite.CreateTable(DBName, CreateTableSQLQuery, logger); * //sqlLite.InsertRecord(DBName, tableName, 1, "Nothing", logger); * //DataSet dt = sqlLite.RetrieveRecord(DBName, tableName, 1, logger); * //FileHelper f = new FileHelper(); * //f.ValidateFile(@"C:\Users\vishal.chilka\Desktop\ZSB120OM.OUT"); * * return 0;*/ // sqlManipulation.CloseDBConnection(m_dbConnection); return(0); }
// Use this for initialization public override void Start() { // Initialize InitAll(); Logger.debug = true; // Set up input listeners Inputs.SetKeyListeners(_keyListeners); // Beats logo TestLogo.Init(); TestLogo logo = TestLogo.Instantiate(); logo.position = new Vector3(Screens.xmid, Screens.ymid, Screens.zmin); // Arrow in each corner TestArrow.Init(); for (int x = 0; x < 3; x++) { for (int y = 0; y < 3; y++) { float posX = (x == 0) ? Screens.xmin : (x == 1) ? Screens.xmid : Screens.xmax; float posY = (y == 0) ? Screens.ymin : (y == 1) ? Screens.ymid : Screens.ymax; float posZ = Screens.zmin; TestArrow arrow = TestArrow.Instantiate(); arrow.name = String.Format("_arrow({0}, {1})", x, y); arrow.position = new Vector3(posX, posY, posZ); } } _randomArrow = TestArrow.Instantiate(); _randomArrow.name = "_randomArrow"; _randomArrow.position = new Vector3(Screens.xmax - 75f, Screens.ymax - 50f, Screens.zmin); // Two random holds TestHold.Init(); _hold1 = TestHold.Instantiate(Screens.height - _randomArrow.height); _hold1.name = "_hold1"; _hold1.position = new Vector3(Screens.xmax - (_hold1.width / 2), Screens.ymid, Screens.zmid); _hold2 = TestHold.Instantiate(_randomArrow.height * 4); _hold2.name = "_hold2"; _hold2.position = new Vector3(_hold1.x - _hold1.width * 2, Screens.ymid, Screens.zmid); // Background image TestBackground background = TestBackground.Instantiate(); background.name = "_background2"; background.position = new Vector3(Screens.xmid, Screens.ymid, Screens.zmax); background.color = new Color(background.color.r, background.color.g, background.color.b, 0.75f); // Generated arrows _arrows = new List <TestArrow>(); _addTimer = ADD_INTERVAL; _arrowCount = 0; // Text label FontMeshData squareTextData = new FontMeshData( "_SquareFont", SysInfo.GetPath("Sandbox/Square.png"), SysInfo.GetPath("Sandbox/Square.fnt") ); float textWidth = squareTextData.width * (_randomArrow.height / 2) / squareTextData.height; float textHeight = (_randomArrow.height / 2); _sysInfo = TestText.Instantiate( squareTextData, "_SysInfo", textWidth * 0.7f, textHeight * 0.7f, TextAnchor.UpperLeft ); _sysInfo.position = new Vector3(Screens.xmin, Screens.ymax, Screens.zdebug); _sysInfo.color = new Color(1f, 1f, 1f, 0.5f); // Semi-transparent Gray _sysInfo.text = SysInfo.InfoString(); _audioTime = TestText.Instantiate( squareTextData, "_AudioTime", textWidth, textHeight, TextAnchor.LowerLeft ); _audioTime.position = new Vector3(Screens.xmin, Screens.ymin + (_randomArrow.height / 2), Screens.zdebug); _touchLog = TestText.Instantiate( squareTextData, "_Touch Log", textWidth, textHeight, TextAnchor.LowerLeft ); _touchLog.position = new Vector3(Screens.xmin, Screens.ymin, Screens.zdebug); _touchLog.color = new Color(255f / 255f, 204f / 255f, 0f); // Tangerine _collisionLog = TestText.Instantiate( squareTextData, "_Collision Log", textWidth, textHeight, TextAnchor.LowerRight ); _collisionLog.position = new Vector3(Screens.xmax, Screens.ymin, Screens.zdebug); _collisionLog.color = Color.red; // FPS Counter _fpsCounter = FpsCounter.Instantiate(squareTextData, textHeight); _fpsCounter.position = new Vector3(Screens.xmax, Screens.ymax, Screens.zdebug); // Load music _audioPlayer = AudioPlayer.Instantiate(); _audioPlayer.Set(AudioClips.SANDBOX_SONG); _audioPlayer.loop = true; _audioPlayer.Play(); TestMine.Init(); _mine = TestMine.Instantiate(); _mine.gameObject.transform.position = new Vector3(Screens.xmid, (Screens.ymin + Screens.ymid) / 2, Screens.zmin - 10); SettingsFile testIniFile = new SettingsFile(SysInfo.GetPath("Sandbox/Test.ini")); testIniFile.Set("Beats", "Version", "MODIFIED"); testIniFile.Write(SysInfo.GetPath("Sandbox/Test2.ini")); }
public static void SaveSettings(SettingsFile settingsFile) { WriteSettings(settingsFile); }
private void Activate(PluginInstance instance) { Log.Debug(Tag, $"Attempting to load {instance.Name}"); if (IsAlreadyLoaded(instance.Assembly.GetName())) { return; } // Check that it references some form of the Plugin API assembly AssemblyName pluginApiName; if ( (pluginApiName = instance.Assembly.GetReferencedAssemblies() .FirstOrDefault(name => name.Name == PluginApiAssemblyName.Name)) != null) { if (pluginApiName.FullName != PluginApiAssemblyName.FullName) { throw new PluginIncompatibleException($"Wrong version of Athame.PluginAPI referenced: expected {PluginApiAssemblyName}, found {pluginApiName}"); } } else { throw new PluginLoadException("Plugin does not reference Athame.PluginAPI.", instance.AssemblyDirectory); } var types = instance.Assembly.GetExportedTypes(); // Only filter for types which can be instantiated and implement IPlugin somehow. var implementingType = types.FirstOrDefault( type => !type.IsInterface && !type.IsAbstract && type.GetInterface(nameof(IPlugin)) != null); if (implementingType == null) { throw new PluginLoadException("No exported types found implementing IPlugin.", instance.AssemblyDirectory); } // Activate base plugin var plugin = (IPlugin)Activator.CreateInstance(implementingType); if (plugin.ApiVersion != ApiVersion) { throw new PluginIncompatibleException($"Plugin declares incompatible API version: expected {ApiVersion}, found {plugin.ApiVersion}."); } instance.Info = plugin.Info; instance.Plugin = plugin; var servicePlugin = plugin as MusicService; var context = new PluginContext { PluginDirectory = instance.AssemblyDirectory }; instance.Context = context; if (servicePlugin != null) { var settingsPath = Program.DefaultApp.UserDataPathOf(Path.Combine(SettingsDir, String.Format(SettingsFileFormat, plugin.Info.Name))); var settingsFile = new SettingsFile(settingsPath, servicePlugin.Settings.GetType(), servicePlugin.Settings); instance.SettingsFile = settingsFile; } else { throw new PluginLoadException("IPlugin type does not implement MusicService.", instance.AssemblyDirectory); } }
public override void PreRender() { base.PreRender(); this._settingsFile = SettingsSchemaFactory.Create<SettingsFile>(base.ProjectItem); }
void xFailSafe_CheckedChanged( object sender, EventArgs e ) { SettingsFile sf = new SettingsFile(); if( File.Exists( Paths.GameSettingsFile ) ) { sf.Load( Paths.GameSettingsFile ); } bool failSafeEnabled = sf.GetBool( "mc.failsafe", false ); if( failSafeEnabled != xFailSafe.Checked ) { sf.Set( "mc.failsafe", xFailSafe.Checked ); sf.Save( Paths.GameSettingsFile ); } lOptionsStatus.Text = "Fail-safe mode " + (xFailSafe.Checked ? "enabled" : "disabled") + "."; }
public void UpdateAvailableUsers() { lock (AvailableUsersSyncRoot) { var defaultSectionName = SettingsFile.DefaultSectionName; var userLogins = SettingsFile.GetSections() .Where(userLogin => userLogin != defaultSectionName) .OrderBy( login => login, StringComparer.Ordinal) .ToArray(); var users = new Dictionary <string, User>(userLogins.Length); foreach (var login in userLogins) { try { var token = GetUserToken(login); string rocketPassword = string.Empty; Task.Run(async() => { try { rocketPassword = GetUserRocketPassword(login); if (string.IsNullOrEmpty(rocketPassword)) { var result = await UserApi.GetRocketPassword( token) .ConfigureAwait(false); if (!result.IsError && result.Data != null) { rocketPassword = result.Data.Password; SetUserRocketPassword(login, rocketPassword); } else { rocketPassword = string.Empty; SetUserRocketPassword(login, rocketPassword); } } } catch (CryptographicException) { rocketPassword = string.Empty; SetUserRocketPassword(login, rocketPassword); } catch (FormatException) { rocketPassword = string.Empty; SetUserRocketPassword(login, rocketPassword); } }); users.Add( login, new User( login, token, GetUserId(login), rocketPassword, UserStoreType.Permanent)); } catch (CryptographicException) { RemoveUser(login, false); } catch (FormatException) { RemoveUser(login, false); } } var oldAvailableUsers = AvailableUsers; AvailableUsers = new ReadOnlyDictionary <string, User>(users); AvailableUsersChanged?.Invoke(this, new AvailableUsersChangedEventArgs(oldAvailableUsers, AvailableUsers)); } }
void LoadResumeInfo() { if( File.Exists( Paths.GameSettingsFile ) ) { SettingsFile gameSettings = new SettingsFile(); gameSettings.Load( Paths.GameSettingsFile ); string resumeUri = gameSettings.GetString( "mc.lastMcUrl", "" ); if( resumeUri.Length > 0 ) { Match match = PlayLinkDirect.Match( resumeUri ); if( match.Success ) { tResumeUri.Text = resumeUri; tResumeServerIP.Text = match.Groups[1].Value; tResumeUsername.Text = match.Groups[7].Value; string resumeServerName = gameSettings.GetString( "mc.lastClassicServer", "" ); if( resumeServerName.Length > 0 ) { tResumeServerName.Text = resumeServerName; } else { tResumeServerName.Text = "?"; } bResume.Enabled = true; return; } } } ResetResumeInfo(); }
protected void RefreshSettings() { store.Expect(x => x.LoadXml(Arg<string>.Is.Anything)).Return(Xml()); var file = new SettingsFile<AppSettings>(store); settings = file.Load(); }
private static AppSettings LoadAppSettings() { var store = new XmlFileStore(); var file = new SettingsFile<AppSettings>("App", store); return file.Load(); }
/// <summary> /// Loads all app settings /// </summary> private void LoadSettings() { //ToDo: set parking zone current light settings newSettingsState = (SettingsFile)loadState.LoadNewState(StateType.SETTINGS); }
private void testROMToolStripMenuItem_Click(object sender, EventArgs e) { LaunchROM.OpenEmulator(); SettingsFile.SaveGlobalSettings("default"); }
private static void SaveSettings() { var settings = Settings(); SettingsFile.Save("appsettings.json", settings.ToJson()); }
public void Save() { SettingsFile.Save(InstallerState, nameof(InstallerState)); }
private static string GetSettingsFileLocation() { return(SettingsFile.GetLocation("appsettings.json")); }
public SettingsFileTest() { store = MockRepository.GenerateMock<IXmlFileStore>(); file = new SettingsFile<AppSettings>("TestFile", store); settings = new AppSettings(); }
private Session(SingleInstanceMainForm singleInstanceMainForm, ISettingsProvider settingsProvider, Localizer defaultLocalizer, Dictionary <LocalizedStringKey, string> defaultLocalizerDictionary, Icon applicationIcon) { if (settingsProvider == null) { throw new ArgumentNullException(nameof(settingsProvider)); } if (singleInstanceMainForm == null) { throw new ArgumentNullException(nameof(singleInstanceMainForm)); } if (!singleInstanceMainForm.IsHandleCreated || singleInstanceMainForm.Disposing || singleInstanceMainForm.IsDisposed) { throw new InvalidOperationException($"{nameof(singleInstanceMainForm)} should have its handle created."); } // May be null. this.defaultLocalizerDictionary = defaultLocalizerDictionary; ApplicationIcon = applicationIcon; // This depends on ExecutableFileName. DeveloperMode = new SettingProperty <bool>( new SettingKey(SettingKey.ToSnakeCase(nameof(DeveloperMode))), PType.CLR.Boolean, new SettingComment($"Enables tools which assist with {ExecutableFileNameWithoutExtension} development and debugging.")); // Attempt to load default settings. DefaultSettings = SettingsFile.Create( Path.Combine(ExecutableFolder, DefaultSettingsFileName), settingsProvider.CreateBuiltIn(this)); // Save name of LOCALAPPDATA subfolder for persistent files. AppDataSubFolder = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), GetDefaultSetting(SharedSettings.AppDataSubFolderName)); #if DEBUG // In debug mode, generate default json configuration files from hard coded settings. DeployRuntimeConfigurationFiles(); #endif // Scan Languages subdirectory to load localizers. var langFolderName = GetDefaultSetting(SharedSettings.LangFolderName); registeredLocalizers = Localizers.ScanLocalizers(this, Path.Combine(ExecutableFolder, langFolderName)); LangSetting = new SettingProperty <FileLocalizer>( new SettingKey(LangSettingKey), new PType.KeyedSet <FileLocalizer>(registeredLocalizers)); // Now attempt to get exclusive write access to the .lock file so it becomes a safe mutex. string lockFileName = Path.Combine(AppDataSubFolder, LockFileName); FileStreamPair autoSaveFiles = null; // Retry a maximum number of times. int remainingRetryAttempts = MaxRetryAttemptsForLockFile; while (remainingRetryAttempts >= 0) { try { // Create the folder on startup. Directory.CreateDirectory(AppDataSubFolder); // If this call doesn't throw, exclusive access to the mutex file is obtained. // Then this process is the first instance. // Use a buffer size of 24 rather than the default 4096. lockFile = new FileStream( lockFileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read, WindowHandleLengthInBytes + MagicLengthInBytes); try { // Immediately empty the file. lockFile.SetLength(0); // Write the window handle to the lock file. // Use BitConverter to convert to and from byte[]. byte[] buffer = BitConverter.GetBytes(singleInstanceMainForm.Handle.ToInt64()); lockFile.Write(buffer, 0, WindowHandleLengthInBytes); // Generate a magic GUID for this instance. // The byte array has a length of 16. TodaysMagic = Guid.NewGuid().ToByteArray(); lockFile.Write(TodaysMagic, 0, MagicLengthInBytes); lockFile.Flush(); autoSaveFiles = OpenAutoSaveFileStreamPair(new AutoSaveFileNamePair(AutoSaveFileName1, AutoSaveFileName2)); // Loop exit point 1: successful write to lockFile. Can auto-save. break; } catch { ReleaseLockFile(lockFile); lockFile = null; } } catch { // Not the first instance. // Then try opening the lock file as read-only. try { // If opening as read-only succeeds, read the contents as bytes. FileStream existingLockFile = new FileStream( lockFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, WindowHandleLengthInBytes + MagicLengthInBytes); using (existingLockFile) { byte[] lockFileBytes = new byte[WindowHandleLengthInBytes + MagicLengthInBytes]; int totalBytesRead = 0; int remainingBytes = WindowHandleLengthInBytes + MagicLengthInBytes; while (remainingBytes > 0) { int bytesRead = existingLockFile.Read(lockFileBytes, totalBytesRead, remainingBytes); if (bytesRead == 0) { break; // Unexpected EOF? } totalBytesRead += bytesRead; remainingBytes -= bytesRead; } // For checking that EOF has been reached, evaluate ReadByte() == -1. if (remainingBytes == 0 && existingLockFile.ReadByte() == -1) { // Parse out the remote window handle and the magic bytes it is expecting. long longValue = BitConverter.ToInt64(lockFileBytes, 0); HandleRef remoteWindowHandle = new HandleRef(null, new IntPtr(longValue)); byte[] remoteExpectedMagic = new byte[MagicLengthInBytes]; Array.Copy(lockFileBytes, 8, remoteExpectedMagic, 0, MagicLengthInBytes); // Tell the singleInstanceMainForm that another instance is active. // Not a clean design to have callbacks going back and forth. // Hard to refactor since we're inside a loop. singleInstanceMainForm.NotifyExistingInstance(remoteWindowHandle, remoteExpectedMagic); // Reference remoteWindowHandle here so it won't be GC'ed until method returns. GC.KeepAlive(remoteWindowHandle); // Loop exit point 2: successful read of the lock file owned by an existing instance. return; } } } catch { } } // If any of the above steps fail, this might be caused by the other instance // shutting down for example, or still being in its startup phase. // In this case, sleep for 100 ms and retry the whole process. Thread.Sleep(PauseTimeBeforeLockRetry); remainingRetryAttempts--; // Loop exit point 3: proceed without auto-saving settings if even after 2 seconds the lock file couldn't be accessed. // This can happen for example if the first instance is running as Administrator and this instance is not. } try { AutoSave = new SettingsAutoSave(settingsProvider.CreateAutoSaveSchema(this), autoSaveFiles); // After creating the auto-save file, look for a local preferences file. // Create a working copy with correct schema first. SettingCopy localSettingsCopy = new SettingCopy(settingsProvider.CreateLocalSettingsSchema(this)); // And then create the local settings file which can overwrite values in default settings. LocalSettings = SettingsFile.Create( Path.Combine(AppDataSubFolder, GetDefaultSetting(SharedSettings.LocalPreferencesFileName)), localSettingsCopy); if (TryGetAutoSaveValue(LangSetting, out FileLocalizer localizer)) { currentLocalizer = localizer; } else { // Select best fit. currentLocalizer = Localizers.BestFit(registeredLocalizers); } // Fall back onto defaults if still null. currentLocalizer = currentLocalizer ?? defaultLocalizer ?? Localizer.Default; } catch { // Must dispose here, because Dispose() is never called if an exception is thrown in a constructor. ReleaseLockFile(lockFile); throw; } }
public void UnknownItem_Remove_ExistingChild_PreservesComments() { // Arrange var nugetConfigPath = "NuGet.Config"; var config = @" <configuration> <!-- This is a section --> <Section> <!-- Unknown Item --> <Unknown meta=""data""> <!-- Text child --> Text for test <!-- Item child --> <add key=""key"" value=""val"" /> </Unknown> </Section> </configuration>"; var expectedSetting = new UnknownItem("Unknown", attributes: new Dictionary <string, string>() { { "meta", "data" } }, children: new List <SettingBase>() { new AddItem("key", "val") }); using (var mockBaseDirectory = TestDirectory.Create()) { ConfigurationFileTestUtility.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config); var settingsFile = new SettingsFile(mockBaseDirectory); // Act var section = settingsFile.GetSection("Section"); section.Should().NotBeNull(); var element = section.Items.FirstOrDefault() as UnknownItem; element.Should().NotBeNull(); element.Remove(element.Children.First()); settingsFile.AddOrUpdate("Section", element); settingsFile.SaveToDisk(); var expectedConfig = ConfigurationFileTestUtility.RemoveWhitespace(@"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> <!-- This is a section --> <Section> <!-- Unknown Item --> <Unknown meta=""data""> <!-- Text child --> <!-- Item child --> <add key=""key"" value=""val"" /> </Unknown> </Section> </configuration>"); ConfigurationFileTestUtility.RemoveWhitespace(File.ReadAllText(Path.Combine(mockBaseDirectory, nugetConfigPath))).Should().Be(expectedConfig); // Assert element.DeepEquals(expectedSetting).Should().BeTrue(); } }
private void saveButton_Click(object sender, EventArgs e) { updateGlobalSettings(); SettingsFile.SaveGlobalSettings("default"); Close(); }