Save() public static méthode

public static Save ( obj ) : void
Résultat void
Exemple #1
0
        private void OnApplicationUnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            var exceptionType = e.ExceptionObject.GetType();

            ApplicationSettings["76991776-7356-4006-87CF-0DF0E46655AE_UnhandledException"]            = exceptionType.IsSerializable ? e.ExceptionObject : null;
            ApplicationSettings["76991776-7356-4006-87CF-0DF0E46655AE_UnhandledException.Message"]    = e.ExceptionObject.Message;
            ApplicationSettings["76991776-7356-4006-87CF-0DF0E46655AE_UnhandledException.StackTrace"] = e.ExceptionObject.StackTrace;
            ApplicationSettings["76991776-7356-4006-87CF-0DF0E46655AE_UnhandledException.Source"]     = e.ExceptionObject.Source;
            ApplicationSettings["76991776-7356-4006-87CF-0DF0E46655AE_UnhandledException.HResult"]    = e.ExceptionObject.HResult;
            var innerExceptionTypeIsSerializable = e.ExceptionObject.InnerException != null && e.ExceptionObject.InnerException.GetType().IsSerializable;

            ApplicationSettings["76991776-7356-4006-87CF-0DF0E46655AE_UnhandledException.InnerException"] = innerExceptionTypeIsSerializable ? e.ExceptionObject.InnerException : null;
            ApplicationSettings.Save();
        }
        public void Execute()
        {
            // setup and load user settings
            ApplicationSettings _settings = new ApplicationSettings(this);

            _settings.Load();

            // show startup values
            Console.WriteLine("Status-Code value: " + StatusCode);
            Console.WriteLine("Status-Code setting: " + _settings["StatusCode"]);
            Console.WriteLine();

            // user input
            Console.Write("Please enter a number (Enter to reset): ");

            string _consoleInput = Console.ReadLine();

            if (string.IsNullOrEmpty(_consoleInput))
            {
                _settings.Reset();
            }
            else
            {
                try
                {
                    StatusCode = int.Parse(_consoleInput); // modifying the field value
                }
                catch
                {
                    Console.Write("Invalid input. Press any key...");
                    Console.ReadKey();
                    return;
                }
            }

            // save user settings
            _settings.Save();
            Console.WriteLine();
            Console.WriteLine("Settings saved to: " + ApplicationSettings.UserConfigurationFilePath);

            // show working values
            Console.WriteLine();
            Console.WriteLine("Status-Code value: " + StatusCode);
            Console.WriteLine("Status-Code setting: " + _settings["StatusCode"]);

            Console.WriteLine();
            Console.Write("Press any key...");
            Console.ReadKey();
        }
        public static void SaveApplicationSettings()
        {
            var mainWindow          = Application.Current.MainWindow;
            var layersGridSplitter  = (ColumnDefinition)mainWindow.FindName("layersGridSplitter");
            var actionsGridSplitter = (ColumnDefinition)mainWindow.FindName("actionsGridSplitter");

            settings.height          = Convert.ToInt32(mainWindow.Height);
            settings.width           = Convert.ToInt32(mainWindow.Width);
            settings.x               = Convert.ToInt32(mainWindow.Left);
            settings.y               = Convert.ToInt32(mainWindow.Top);
            settings.fullScreen      = mainWindow.WindowState == WindowState.Maximized;
            settings.layersSplitter  = Convert.ToInt32(layersGridSplitter.Width.Value);
            settings.actionsSplitter = Convert.ToInt32(actionsGridSplitter.Width.Value);
            settings.Save();
        }
Exemple #4
0
        private void OnAppExit(object sender, ExitEventArgs e)
        {
            Log.Debug("App OnAppExit");
            InstanceSettings.GetInstance().EnableMouseInput = false;

            // cause not having a cursor is a pain in the ass
            Utility.ShowCursor(true);

            UserSettings.Save(UserSettings.PROFILE_PREVIOUS);
            ApplicationSettings.Save();

            VigemManager.Stop(InstanceSettings.GetInstance());

            //TODO: hardcoded, fix.
            //Injector.FindProcess("RemotePlay").Kill();
        }
Exemple #5
0
        /// <summary>
        /// Opens the settings menu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void settingsPictureBox_Click(object sender, EventArgs e)
        {
            var oldSettingsInstance = AppSettings.ShallowCopy();
            var settings            = new Settings(AppSettings);
            var result = settings.ShowDialog();

            //Settings were OK, no database changes!
            if (result == DialogResult.OK)
            {
                AppSettings = settings.LocalApplicationSettings;
                StartOrStopTimer();
                AppSettings.Save();
            }

            //Settings were ok, database need to migrate to new location!
            if (result == DialogResult.Retry)
            {
                AppSettings = settings.LocalApplicationSettings;

                var oldDb = Path.Combine(oldSettingsInstance.DatabaseDirectory, oldSettingsInstance.DatabaseName);
                var newDb = Path.Combine(AppSettings.DatabaseDirectory, AppSettings.DatabaseName);

                AppSettings.Save();

                if (!File.Exists(oldDb))
                {
                    MessageBox.Show("Gammel database kan ikke tilgåes lige nu, prøv igen!", "Fejl!", MessageBoxButtons.OK);
                    return;
                }

                if (File.Exists(newDb))
                {
                    MessageBox.Show("Der findes allerede en database", "Fejl", MessageBoxButtons.OK);
                    return;
                }

                File.Copy(oldDb, newDb);

                if (File.Exists(newDb))
                {
                    _db = new LiteDatabase(newDb);
                }

                StartOrStopTimer();
            }
        }
        protected void BtnSaveSettings_Click(object sender, EventArgs e)
        {
            int timeInterval = EnableFeed.Checked ? AlwaysConvert.ToInt(TimeInterval.Text) : 0;

            if (timeInterval == 0)
            {
                EnableFeed.Checked = false;
            }
            _appSettings.GoogleFeedInterval = timeInterval;
            _appSettings.Save();

            _settings.GoogleFeedIncludeAllProducts = AllProducts.Checked;
            _settings.GoogleFeedDefaultBrand       = DefaultBrand.Text.Trim();
            _settings.GoogleFeedDefaultCategory    = DefaultCategory.Text.Trim();
            _settings.Save();
            SavedMessage.Visible = true;
            SavedMessage.Text    = string.Format(SavedMessage.Text, LocaleHelper.LocalNow);
        }
Exemple #7
0
        private void FormMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            applicationSettings.Save();

            Properties.Settings settings = Properties.Settings.Default;
            Properties.Settings.Default.Panel1H     = panel1.Height;
            Properties.Settings.Default.Panel1W     = panel1.Width;
            Properties.Settings.Default.FormL       = Left;
            Properties.Settings.Default.FormT       = Top;
            Properties.Settings.Default.FormW       = Width;
            Properties.Settings.Default.FormH       = Height;
            Properties.Settings.Default.ViewToolbar = tsMain.Visible;
            Properties.Settings.Default.WindowState = WindowState;
            settings.formsize = Size;
            settings.Save();

            Properties.Settings.Default.Save();
        }
Exemple #8
0
        private void OnClick_NugetFeedManager(object sender, RoutedEventArgs e)
        {
            string appDataPath        = new EnvironmentSettings().GetEnvironmentVariablePath();
            string appSettingsDirPath = Directory.GetParent(appDataPath).FullName;

            var appSettings      = new ApplicationSettings().GetOrCreateApplicationSettings(appSettingsDirPath);
            var packageSourcesDT = appSettings.ClientSettings.PackageSourceDT;

            NugetFeedManager nugetFeedManager = new NugetFeedManager(packageSourcesDT);

            nugetFeedManager.Owner = this;
            nugetFeedManager.ShowDialog();

            if (nugetFeedManager.isDataUpdated)
            {
                appSettings.ClientSettings.PackageSourceDT = nugetFeedManager.GetPackageSourcesData();
                appSettings.Save(appSettings, appSettingsDirPath);
            }
        }
 private void uiBtnOk_Click(object sender, EventArgs e)
 {
     if (!Directory.Exists(Path.Combine(txtFolderLocation.Text, "OB Scripts")))
     {
         try
         {
             Directory.CreateDirectory(Path.Combine(txtFolderLocation.Text, "OB Scripts"));
             var settings = new ApplicationSettings().GetOrCreateApplicationSettings();
             settings.ClientSettings.ScriptsFolder = Path.Combine(txtFolderLocation.Text, "OB Scripts");
             settings.Save();
             DialogResult = DialogResult.OK;
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
             return;
         }
     }
 }
        private void SaveSettings()
        {
            bool databaseChanged = false;

            if ((PortfolioDatabasePath != _Settings.PortfolioDatabase) ||
                (StockDatabasePath != _Settings.StockDatabase))
            {
                _Settings.PortfolioDatabase = PortfolioDatabasePath;
                _Settings.StockDatabase     = StockDatabasePath;

                databaseChanged = true;
            }

            _Settings.Save();

            if (databaseChanged)
            {
                _Settings.OnDatabaseChanged();
            }
        }
        private void frmScriptBuilder_Shown(object sender, EventArgs e)
        {
            if (!_isFirstTimeSetupComplete)
            {
                _studioFormShownEarly = true;
                Hide();
                return;
            }

            DialogResult result;

            if (_appSettings == null)
            {
                _appSettings = new ApplicationSettings().GetOrCreateApplicationSettings();
            }

            if (!_appSettings.ClientSettings.IsRestarting)
            {
                Program.SplashForm.Close();
                result = AddProject();
            }
            else
            {
                _appSettings.ClientSettings.IsRestarting = false;
                _appSettings.Save();

                frmProjectBuilder restartProjectBuilder = new frmProjectBuilder()
                {
                    ExistingProjectPath = ScriptProjectPath,
                    ExistingConfigPath  = Path.Combine(ScriptProjectPath, "project.obconfig"),
                    Action       = ProjectAction.OpenProject,
                    DialogResult = DialogResult.OK
                };
                result = AddProject(restartProjectBuilder);
            }

            if (result != DialogResult.Abort)
            {
                Notify("Welcome! Select a Command to get started!", Color.White);
            }
        }
Exemple #12
0
        public void TestRestore3()
        {
            string   fname     = Path.GetTempFileName();
            var      settings  = new ApplicationSettings(fname);
            DateTime timestamp = DateTime.Now;

            settings.DataSources.Add(new DataSource("dawadaw")
            {
                LastViewed = timestamp
            });

            settings.Save();
            settings = new ApplicationSettings(fname);
            settings.Restore();

            settings.DataSources.Count.Should().Be(1);
            DataSource source = settings.DataSources[0];

            source.Should().NotBeNull();
            source.LastViewed.Should().Be(timestamp);
        }
Exemple #13
0
        public void TestDataSourceId()
        {
            string fname      = Path.GetTempFileName();
            var    settings   = new ApplicationSettings(fname);
            var    dataSource = new DataSource("foo");

            dataSource.Id = DataSourceId.CreateNew();
            settings.DataSources.Add(dataSource);
            settings.Save();

            var  settings2 = new ApplicationSettings(fname);
            bool neededPatching;

            settings2.Restore(out neededPatching);
            neededPatching.Should().BeFalse();
            settings2.DataSources.Count.Should().Be(1);
            DataSource dataSource2 = settings2.DataSources[0];

            dataSource2.File.Should().Be("foo");
            dataSource2.Id.Should().Be(dataSource.Id);
        }
Exemple #14
0
        public void TestRestore4()
        {
            string fname    = Path.GetTempFileName();
            var    settings = new ApplicationSettings(fname);

            settings.DataSources.Add(new DataSource("dawadaw")
            {
                VisibleLogLine   = 42,
                HorizontalOffset = 142.42
            });

            settings.Save();
            settings = new ApplicationSettings(fname);
            settings.Restore();

            settings.DataSources.Count.Should().Be(1);
            DataSource source = settings.DataSources[0];

            source.Should().NotBeNull();
            source.VisibleLogLine.Should().Be(42);
            source.HorizontalOffset.Should().Be(142.42);
        }
        /// <summary>
        /// save default/last saved settings
        /// </summary>
        private void SaveSettings()
        {
            ApplicationSettings settings = new ApplicationSettings();

            /// <summary>
            /// application settings
            /// </summary>
            settings.DirectoryToScan     = txtDirectoryToScan.Text.Trim();
            settings.FileAgeLimit        = Convert.ToInt32(txtFileAgeLimit.Text.Trim());
            settings.ServiceExecuteEvery = txtServiceInterval.Text.Trim();

            /// <summary>
            /// database settings
            /// </summary>
            settings.ServerName = txtServer.Text.Trim();
            settings.Database   = txtDatabase.Text.Trim();
            settings.User       = txtUser.Text.Trim();
            settings.Password   = txtPassword.Text.Trim();

            settings.FileDeleteCSVFile = txtFileDeleteCSVFile.Text.Trim();
            settings.DatabaseType      = rdoSQLDatabase.Checked ? DatabaseTypeEnum.SQLDatabase : DatabaseTypeEnum.CSVDatabase;
            settings.Delimeter         = txtDelimeter.Text.Trim();
            settings.Save();
        }
Exemple #16
0
        public static int Main(string[] args)
        {
            String version     = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            String versionName = version.Substring(0, version.LastIndexOf('.'));

            versionName = versionName.Substring(0, versionName.LastIndexOf('.'));

            Assembly assembly = Assembly.GetExecutingAssembly();

            object[] attributes = assembly.GetCustomAttributes(true);
            object   configRaw  = attributes.FirstOrDefault(a => a.GetType() == typeof(AssemblyConfigurationAttribute));

            if (configRaw != null)
            {
                AssemblyConfigurationAttribute config = (AssemblyConfigurationAttribute)configRaw;
                if (config.Configuration != "")
                {
                    versionName += "-" + config.Configuration;
                }
            }

            ApplicationDataModel.ApplicationVersion     = versionName;
            ApplicationDataModel.ApplicationFullVersion = version;

            if (args.Length > 1 && args[0] == "--build-config")
            {
                System.IO.StreamWriter file = new System.IO.StreamWriter(args[1]);
                file.WriteLine(String.Format("#define AppVersion \"{0}\"\r\n#define AppFullVersion \"{1}\"", versionName, version));
                file.Close();
                return(0);
            }

            ApplicationSettings applicationSettings = new ApplicationSettings();

            applicationSettings.Load();

            if (args.Length > 0 && args[0] == "--register")
            {
                MainWindow.RegisterStartup(true);

                applicationSettings.StartWithWindows = true;
                applicationSettings.Save();
                return(0);
            }
            else if (args.Length > 0 && args[0] == "--unregister")
            {
                MainWindow.RegisterStartup(false);

                applicationSettings.StartWithWindows = false;
                applicationSettings.Save();
                return(0);
            }

            Boolean ambilightMode = args.Length > 0 && args[0] == "--ambilight";

            if (ambilightMode)
            {
                Logger.Setup(Path.Combine(MainWindow.LogFolder, "ambilight.log"), applicationSettings.LogLevel);
            }
            else
            {
                Logger.Setup(MainWindow.LogFile, applicationSettings.LogLevel);
            }

            log = LogManager.GetLogger("Main");

            log.Info("--------------------------------------");
            log.InfoFormat("BlinkStick Client {0} application started", ApplicationDataModel.ApplicationVersion);

            if (ambilightMode)
            {
                #if !__MonoCS__
                AmbilightWindowsService service = new AmbilightWindowsService();
                service.Run();
                #endif
                Logger.Stop();
                return(0);
            }

            #if !DEBUG
            GLib.ExceptionManager.UnhandledException += delegate(GLib.UnhandledExceptionArgs args2) {
                Exception e = (Exception)args2.ExceptionObject;
                log.Fatal("Unhandled exception occured:");
                if (e.InnerException != null)
                {
                    log.FatalFormat("Inner Exception: {0}", e.InnerException.Message);
                    log.Fatal(e.InnerException.StackTrace);
                }
                else
                {
                    log.Fatal(e.Message);
                    log.Fatal(e.StackTrace);
                }

                args2.ExitApplication = true;

                BlinkStickClient.Utils.MessageBox.Show(null, "Unfortunately BlinkStick Client has crashed :(\n\r" +
                                                       "The details about the crash are available in the log file: \r\n\r\n" +
                                                       MainWindow.LogFile + "\r\n\r\n" +
                                                       "The application will now close.", MessageType.Error);
            };
            #endif

            if (HidSharp.PlatformDetector.RunningPlatform() == HidSharp.PlatformDetector.Platform.Windows && !CheckWindowsGtk())
            {
                return(1);
            }

            Environment.SetEnvironmentVariable("GTK2_RC_FILES", Path.Combine(MainWindow.ExecutableFolder, "Theme", applicationSettings.Theme, "gtk-2.0", "gtkrc"));

            Application.Init();
            MainWindow win = new MainWindow();
            win.ApplicationSettings = applicationSettings;
            win.LoadEverything();
#if DEBUG
            win.Show();
#else
            if (HidSharp.PlatformDetector.RunningPlatform() == HidSharp.PlatformDetector.Platform.Windows && !(args.Length > 0 && args[0] == "--tray"))
            {
                win.Show();
            }
#endif
            Application.Run();

            HidSharp.HidDeviceLoader.FreeUsbResources();
            Logger.Stop();

            return(0);
        }
Exemple #17
0
        private async void tvPackageFeeds_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            lblError.Text = "";
            try
            {
                if (tvPackageFeeds.SelectedNode != null)
                {
                    lbxNugetPackages.Clear();
                    lbxNugetPackages.Visible  = false;
                    tpbLoadingSpinner.Visible = true;

                    if (tvPackageFeeds.SelectedNode.Name == "Settings")
                    {
                        var addPackageSource = new frmAddPackageSource(_packageSourceDT);
                        addPackageSource.ShowDialog();
                        if (addPackageSource.DialogResult == DialogResult.OK)
                        {
                            _packageSourceDT = addPackageSource.PackageSourceDT;
                            PopulatetvPackageFeeds();
                            _settings.Save(_settings);
                        }

                        addPackageSource.Dispose();
                        tpbLoadingSpinner.Visible = false;
                    }
                    else if (tvPackageFeeds.SelectedNode.Name == "ProjectDependencies")
                    {
                        lblPackageCategory.Text  = "Project Dependencies";
                        pbxPackageCategory.Image = Resources.OpenBots_icon;
                        await GetCurrentDepencies();

                        PopulateListBox(_projectDependencies);
                    }
                    else if (tvPackageFeeds.SelectedNode.Name == "AllPackages")
                    {
                        lblPackageCategory.Text  = "All Packages";
                        pbxPackageCategory.Image = Resources.OpenBots_icon;
                        PopulateListBox(_allResults);
                    }
                    else if (tvPackageFeeds.SelectedNode.Name == "Gallery")
                    {
                        lblPackageCategory.Text  = "Gallery";
                        pbxPackageCategory.Image = Resources.OpenBots_gallery_icon;
                        var sourceResults = await NugetPackageManager.SearchPackages("", tvPackageFeeds.SelectedNode.ToolTipText, _includePrerelease);

                        PopulateListBox(sourceResults);
                    }
                    else
                    {
                        lblPackageCategory.Text  = tvPackageFeeds.SelectedNode.Text;
                        pbxPackageCategory.Image = Resources.nuget_icon;
                        var sourceResults = await NugetPackageManager.SearchPackages("", tvPackageFeeds.SelectedNode.ToolTipText, _includePrerelease);

                        PopulateListBox(sourceResults);
                    }
                }
            }
            catch (Exception)
            {
                lblPackageCategory.Text   = "Source Not Found";
                tpbLoadingSpinner.Visible = false;
            }
        }
        public async Task Initialize()
        {
            try
            {
                var settings = new ApplicationSettings();

                var config = new Configuration {
                    BasePath = settings.OrchestratorInstance
                };
                var auth = new AuthorizationService(config, AuthorizationPrefix);


                bool isLoggedIn = false;

                if (!string.IsNullOrWhiteSpace(settings.LastBearerToken))
                {
                    isLoggedIn = await auth.CanBearerTokenUsed(settings.LastBearerToken);
                }


                if (settings.AutoLogin)
                {
                    if (isLoggedIn)
                    {
                        await auth.UseBearerToken(settings.LastBearerToken);
                    }
                    else if (!string.IsNullOrWhiteSpace(settings.Tenant) &&
                             !string.IsNullOrWhiteSpace(settings.UserName) &&
                             !string.IsNullOrWhiteSpace(settings.Password))
                    {
                        await auth.Authorization(new LoginModel(
                                                     settings.Tenant,
                                                     settings.UserName,
                                                     settings.Password
                                                     ));

                        settings.LastBearerToken = auth.CurrentBearerToken;
                        settings.Save();
                    }

                    var authenticated = await auth.StillAuthenticated();

                    if (authenticated)
                    {
                        await StartMainWindow(auth);
                    }
                    else
                    {
                        await StartLoginWindow();
                    }
                }
                else
                {
                    await StartLoginWindow();
                }
            }
            catch (Exception e)
            {
                await StartLoginWindow();
            }
        }
Exemple #19
0
    public void SaveSchemes()
    {
        var serialisedRules = MyJsonSerializer.Serialize(mBuildingRules);

        ApplicationSettings.Save("BuildingRules", serialisedRules);
    }
Exemple #20
0
        private void uiBtnOk_Click(object sender, EventArgs e)
        {
            //create references to old and new root folders
            var oldRootFolder = startingRootFolder;
            var newRootFolder = txtAppFolderPath.Text;

            if (oldRootFolder != newRootFolder)
            {
                //ask user to confirm
                var confirmNewFolderSelection = MessageBox.Show("Please confirm the changes below:" +
                                                                Environment.NewLine + Environment.NewLine + "Old Root Folder: " + oldRootFolder +
                                                                Environment.NewLine + Environment.NewLine + "New Root Folder: " + newRootFolder,
                                                                "Change Default Root Folder", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);

                //handle if user decides to cancel
                if (confirmNewFolderSelection == DialogResult.Cancel)
                {
                    txtAppFolderPath.Text = oldRootFolder;
                    return;
                }
                //ask if we should migrate the data
                var migrateCopyData = MessageBox.Show("Would you like to attempt to move the data from" +
                                                      " the old folder to the new folder?  Please note, depending on how many files you have," +
                                                      " this could take a few minutes.", "Migrate Data?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                //check if user wants to migrate data
                if (migrateCopyData == DialogResult.Yes)
                {
                    try
                    {
                        //find and copy files
                        foreach (string dirPath in Directory.GetDirectories(oldRootFolder, "*", SearchOption.AllDirectories))
                        {
                            Directory.CreateDirectory(dirPath.Replace(oldRootFolder, newRootFolder));
                        }
                        foreach (string newPath in Directory.GetFiles(oldRootFolder, "*.*", SearchOption.AllDirectories))
                        {
                            File.Copy(newPath, newPath.Replace(oldRootFolder, newRootFolder), true);
                        }

                        MessageBox.Show("Data Migration Complete", "Data Migration Complete", MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                    }
                    catch (Exception ex)
                    {
                        //handle any unexpected errors
                        MessageBox.Show("An Error Occurred during Data Migration Copy: " + ex.ToString());
                    }
                }
            }

            _newAppSettings.EngineSettings.CancellationKey = (Keys)cbxCancellationKey.SelectedValue;

            if ((SinkType)cbxSinkType.SelectedItem == SinkType.File && string.IsNullOrEmpty(txtLoggingValue.Text.Trim()))
            {
                _newAppSettings.EngineSettings.LoggingValue = Path.Combine(Folders.GetFolder(FolderType.LogFolder), "OpenBots Engine Logs.txt");
            }

            _newAppSettings.Save();

            Close();
        }
Exemple #21
0
        public void TestStoreRestore()
        {
            const string fileName = "applicationsettingstest.xml";
            var          settings = new ApplicationSettings(fileName);

            settings.MainWindow.Left   = 1;
            settings.MainWindow.Top    = 2;
            settings.MainWindow.Width  = 3;
            settings.MainWindow.Height = 4;
            settings.MainWindow.State  = WindowState.Maximized;
            settings.DataSources.Add(new DataSource(@"SharpRemote.Host.1600.log")
            {
                Id                    = DataSourceId.CreateNew(),
                FollowTail            = true,
                SearchTerm            = "foobar",
                LevelFilter           = LevelFlags.Debug,
                VisibleLogLine        = new LogLineIndex(1),
                ShowLineNumbers       = false,
                HideEmptyLines        = true,
                ActivatedQuickFilters =
                {
                    QuickFilterId.CreateNew(),
                    QuickFilterId.CreateNew(),
                    QuickFilterId.CreateNew(),
                }
            });
            settings.DataSources.Add(new DataSource(@"SharpRemote.Host.1700.log")
            {
                Id              = DataSourceId.CreateNew(),
                FollowTail      = false,
                ShowLineNumbers = true,
                IsSingleLine    = true,
            });
            List <QuickFilterId> guids = settings.DataSources[0].ActivatedQuickFilters.ToList();

            settings.QuickFilters.Add(new QuickFilter
            {
                Value      = "foobar",
                IgnoreCase = true,
                MatchType  = FilterMatchType.RegexpFilter,
                IsInverted = true,
            });
            settings.QuickFilters.Add(new QuickFilter
            {
                Value      = "clondykebar",
                IgnoreCase = false,
                MatchType  = FilterMatchType.WildcardFilter,
                IsInverted = false,
            });
            QuickFilterId filterId1 = settings.QuickFilters[0].Id;
            QuickFilterId filterId2 = settings.QuickFilters[1].Id;

            settings.DataSources.SelectedItem = settings.DataSources[0].Id;
            settings.Export.ExportFolder      = @"C:\hello\world";
            settings.LogFile.DefaultEncoding  = Encoding.BigEndianUnicode;
            settings.Save().Should().BeTrue();

            settings = new ApplicationSettings(fileName);
            settings.Restore();
            settings.MainWindow.Left.Should().Be(1);
            settings.MainWindow.Top.Should().Be(2);
            settings.MainWindow.Width.Should().Be(3);
            settings.MainWindow.Height.Should().Be(4);
            settings.MainWindow.State.Should().Be(WindowState.Maximized);
            settings.DataSources.Count.Should().Be(2);
            settings.DataSources[0].File.Should().Be(@"SharpRemote.Host.1600.log");
            settings.DataSources[0].FollowTail.Should().BeTrue();
            settings.DataSources[0].ShowLineNumbers.Should().BeFalse();
            settings.DataSources[0].HideEmptyLines.Should().BeTrue();
            settings.DataSources[0].IsSingleLine.Should().BeFalse();
            settings.DataSources[0].SearchTerm.Should().Be("foobar");
            settings.DataSources[0].LevelFilter.Should().Be(LevelFlags.Debug);
            settings.DataSources[0].VisibleLogLine.Should().Be(new LogLineIndex(1));
            settings.DataSources[0].ActivatedQuickFilters.Should().Equal(guids);

            settings.DataSources[1].File.Should().Be(@"SharpRemote.Host.1700.log");
            settings.DataSources[1].FollowTail.Should().BeFalse();
            settings.DataSources[1].ShowLineNumbers.Should().BeTrue();
            settings.DataSources[1].HideEmptyLines.Should().BeFalse();
            settings.DataSources[1].IsSingleLine.Should().BeTrue();
            settings.DataSources.SelectedItem.Should().NotBe(Guid.Empty);
            settings.DataSources.SelectedItem.Should().Be(settings.DataSources[0].Id);

            settings.QuickFilters.Count.Should().Be(2);
            settings.QuickFilters[0].Id.Should().Be(filterId1);
            settings.QuickFilters[0].Value.Should().Be("foobar");
            settings.QuickFilters[0].IgnoreCase.Should().BeTrue();
            settings.QuickFilters[0].MatchType.Should().Be(FilterMatchType.RegexpFilter);
            settings.QuickFilters[0].IsInverted.Should().BeTrue();

            settings.QuickFilters[1].Id.Should().Be(filterId2);
            settings.QuickFilters[1].Value.Should().Be("clondykebar");
            settings.QuickFilters[1].IgnoreCase.Should().BeFalse();
            settings.QuickFilters[1].MatchType.Should().Be(FilterMatchType.WildcardFilter);
            settings.QuickFilters[1].IsInverted.Should().BeFalse();

            settings.Export.Should().NotBeNull();
            settings.Export.ExportFolder.Should().Be(@"C:\hello\world");

            settings.LogFile.DefaultEncoding.Should().Be(Encoding.BigEndianUnicode);
        }
Exemple #22
0
 private void App_Closing(object sender, CancelEventArgs e)
 {
     CaptureApplicationSettings();
     applicationSettings.Save();
 }
        protected override void OnExit(ExitEventArgs e)
        {
            ApplicationSettings.Save(DefaultSettingspath);

            base.OnExit(e);
        }
Exemple #24
0
 private void SaveSettings()
 {
     UpdateSettingsFromUi();
     _settings.Save(ChangeName(_settings.SettingsFile, "Studio.Plugins.Spotcheck"));
 }
        internal static bool GetInitialSettings(ApplicationSettings appSettings, out string messages)
        {
            bool showSettingsDialog = false;

            messages = "";

            // Attempt to get the Steam program folder
            if (string.IsNullOrEmpty(appSettings.SteamFolder) || !Directory.Exists(appSettings.SteamFolder))
            {
                appSettings.SteamFolder = Registry.GetValue(appSettings.SteamRegistryKey32, "InstallPath", "") as string;
                if (string.IsNullOrEmpty(appSettings.SteamFolder) || !Directory.Exists(appSettings.SteamFolder))
                {
                    appSettings.SteamFolder = Registry.GetValue(appSettings.SteamRegistryKey64, "InstallPath", "") as string;
                }
            }
            if (string.IsNullOrEmpty(appSettings.SteamFolder) || !Directory.Exists(appSettings.SteamFolder))
            {
                appSettings.SteamFolder = "";
                showSettingsDialog      = true;
            }

            // Attempt to get the Spintires: Mudrunner game files folder
            if (string.IsNullOrEmpty(appSettings.GameFolder) || !Directory.Exists(appSettings.GameFolder))
            {
                var gamePath = AppLogic.PathCombine(appSettings.SteamFolder, appSettings.GameSubfolder);
                // Check the default steam library path
                if (Directory.Exists(gamePath))
                {
                    appSettings.GameFolder = gamePath;
                }
                else
                {
                    // Scan the library config file for game library paths
                    var libraryFolderConfigPath = AppLogic.PathCombine(appSettings.SteamFolder, appSettings.LibraryFoldersConfig);
                    if (!Directory.Exists(AppLogic.PathCombine(appSettings.SteamFolder, appSettings.GameSubfolder)))
                    {
                        if (File.Exists(libraryFolderConfigPath))
                        {
                            bool foundGamePath = false;
                            // Open steam config and find library folder paths
                            var libraryReg = new Regex(@"""\d+""\s+""([^""]+)""");
                            foreach (var line in File.ReadAllLines(libraryFolderConfigPath))
                            {
                                var match = libraryReg.Match(line);
                                if (match.Success)
                                {
                                    var libraryPath = match.Groups[1].Value.Replace(@"\\", @"\");
                                    gamePath = AppLogic.PathCombine(libraryPath, appSettings.GameSubfolder);                                        // Naive unescaping for Valves path values
                                    // See if the game folder exists in this library
                                    if (Directory.Exists(gamePath))
                                    {
                                        appSettings.GameFolder = gamePath;
                                        foundGamePath          = true;
                                        break;
                                    }
                                }
                            }

                            if (!foundGamePath)
                            {
                                appSettings.GameFolder = "";
                                showSettingsDialog     = true;
                            }
                        }
                        else
                        {
                            appSettings.GameFolder = "";
                            showSettingsDialog     = true;
                        }
                    }
                    else
                    {
                        appSettings.GameFolder = appSettings.SteamFolder;
                    }
                }
            }

            // Attempt to get the Spintires: Mudrunner AppData folder
            if (string.IsNullOrEmpty(appSettings.GameAppDataFolder) || !Directory.Exists(appSettings.GameAppDataFolder))
            {
                var gameAppDataFolder = AppLogic.PathCombine(KnownFolders.RoamingAppData.ExpandedPath, appSettings.GameAppDataFolderName);
                if (Directory.Exists(gameAppDataFolder))
                {
                    appSettings.GameAppDataFolder = gameAppDataFolder;
                }
                else
                {
                    appSettings.GameAppDataFolder = "";
                    showSettingsDialog            = true;
                }
            }

            // Attempt to get the Spintires: Mudrunner Mod folder
            if (!string.IsNullOrEmpty(appSettings.GameFolder))
            {
                if (!string.IsNullOrEmpty(appSettings.ModFolder))
                {
                    if (!AppLogic.IsSubdirectory(appSettings.GameFolder, appSettings.ModFolder))
                    {
                        appSettings.ModFolder = "";
                    }
                }

                if (string.IsNullOrEmpty(appSettings.ModFolder) || !Directory.Exists(appSettings.ModFolder))
                {
                    var modFolder = AppLogic.PathCombine(appSettings.GameFolder, appSettings.ModSubfolderName);
                    try
                    {
                        Directory.CreateDirectory(modFolder);
                        appSettings.ModFolder = modFolder;
                    }
                    catch
                    {
                        appSettings.ModFolder = null;
                        messages = "The mod folder could not be created.";
                    }
                }
            }

            appSettings.Save();

            // Attempt to create the profile folder
            if (!string.IsNullOrEmpty(appSettings.GameAppDataFolder))
            {
                try
                {
                    Directory.CreateDirectory(AppLogic.PathCombine(appSettings.GameAppDataFolder, appSettings.ProfilesSubfolderName));
                }
                catch
                {
                    messages = "The profile folder could not be created";
                }
            }

            return(showSettingsDialog);
        }