public List<CMSResearch> GetWeeklyInsightsDocuments(UserSettings userSettings)
        {
            var cacheKey = string.Format("WeeklyInsights-{0}-{1}", _token, userSettings.Language);

            var weeklyInsightsDocuments = TryGetDocumentsFromCache(cacheKey,
                                                                   _configurationService.GetGeneralSettings().ResearchReportsStillFreshInterval);
            if (weeklyInsightsDocuments == null)
            {
                var weeklyInsightsOffset = _configurationService.GetSetting(3, "WeeklyInsightsDateOffset", "Dictionaries", "AppSettings", "General", "ResearchReports");
                var latestResearchModel = new LatestResearchModel
                {
                    Count = int.MaxValue,
                    StartDate = DateTime.Now.AddMonths(-weeklyInsightsOffset).ToString("d", new CultureInfo("en-US")),
                    EndDate = DateTime.Now.ToString("d", new CultureInfo("en-US")),
                    Category = ResearchCategory.TheWeekAhead,
                };

                weeklyInsightsDocuments = GetCMSResearchDocuments(latestResearchModel, userSettings, ResearchType.WEEK_AHEAD).OrderByDescending(e => e.LastUpdatedDate).ToList();

                PutDocumentsInCache(cacheKey,
                    _configurationService.GetGeneralSettings().ResearchReportsSlidingExpiration,
                    weeklyInsightsDocuments);
            }


            return weeklyInsightsDocuments;
        }
Exemple #2
0
 public async void Load()
 {
     instanceLock.WaitOne();
     if (loaded)
     {
         instanceLock.ReleaseMutex();
         return;
     }
     instanceLock.ReleaseMutex();
     instance = new UserSettings();
     try
     {
         StorageFile file = await storageFolder.GetFileAsync(filename);
         string text = await FileIO.ReadTextAsync(file);
         instance.TryParse(text);
         instanceLock.WaitOne();
         loaded = true;
         instanceLock.ReleaseMutex();
         //Stream s = file.OpenStreamForReadAsync().Result;
         //XmlSerializer deserializer = new XmlSerializer(typeof(List<UserSettings>));
         //List<UserSettings> us = (List<UserSettings>)deserializer.Deserialize(s);
         //instance = us[0];
     }
     catch
     {
         IsFirstRun = true;
         if (OnFirstRun != null)
             OnFirstRun();
     }
     //ApplyPermissions();
 }
            public UserSettings(UserSettings copy, String newName)
            {
                SettingsName = newName;
                InputWorldDirectory = copy.InputWorldDirectory;
                OutputPreviewDirectory = copy.OutputPreviewDirectory;
                IsChestFilterEnabled = copy.IsChestFilterEnabled;
                UseOfficialColors = copy.UseOfficialColors;
                AreWallsDrawable = copy.AreWallsDrawable;
                OpenImageAfterDraw = copy.OpenImageAfterDraw;
                ShowChestTypes = copy.ShowChestTypes;
                UseCustomMarkers = copy.UseCustomMarkers;
                ChestListSortType = copy.ChestListSortType;
                ShowChestItems = copy.ShowChestItems;
                ShowNormalItems = copy.ShowNormalItems;

                MarkerStates = new Dictionary<String, MarkerSettings>();

                foreach (KeyValuePair<String, MarkerSettings> kvp in copy.MarkerStates)
                    MarkerStates.Add(kvp.Key, kvp.Value);

                ChestFilterItems = new List<String>();

                foreach (String s in copy.ChestFilterItems)
                    ChestFilterItems.Add(s);
            }
 public void Save(UserSettings settings)
 {
     string json = JsonConvert.SerializeObject(settings);
     if (!store.CollectionExists("MonoDebugger"))
         store.CreateCollection("MonoDebugger");
     store.SetString("MonoDebugger", "Settings", json);
 }
		/// <summary>
		/// ビューの設定を保存する
		/// </summary>
		/// <param name="settings"></param>
		public void SaveSettings(UserSettings settings)
		{
			foreach (DataGridViewColumn column in dataGridView1.Columns) {
				UserSettings.ColumnStatus colState = null;

				foreach (UserSettings.ColumnStatus cs in settings.ColumnStates) {
					if (cs.Name == column.Name) {
						colState = cs;
						break;
					}
				}

				if (colState == null) {
					colState = new UserSettings.ColumnStatus();
					colState.Name = column.Name;
					settings.ColumnStates.Add(colState);

				}

				colState.Visible = column.Visible;
				colState.Width = column.Width;
				colState.DisplayIndex = column.DisplayIndex;

			}
		}
        public string GetEnclosureUrlByGuid(string guid, UserSettings userSettings)
        {
            ReadAndSaveUserSettings(userSettings);

            var cacheKey = string.Format("TechnicalAnalysis-{0}-{1}", _token, _language);

            var docs = TryGetFromCache(cacheKey);

            if (docs == null)
            {
                docs = LoadGetTechnicalAnalysisFromService();
            }

            if (docs != null)
            {
                var document = docs.FirstOrDefault(e => e.Id == guid);

                if (document != null)
                {
                    var result = string.Format(@"<br/> <b>{0}</b> <br/> <hr size=1> <br/> {1} <img src=""{2}"" alt=""{3}"" >",
                                               document.Title,
                                               document.Description,
                                               document.EnclosureUrl,
                                               document.Title);
                    return result;
                }
            }

            return string.Empty;
        }
Exemple #7
0
        static DebugConfig()
        {
            #if DEBUG
            string uncommitedXml = "Uncommited.xml";
            if (!File.Exists(uncommitedXml))
                uncommitedXml = Path.Combine(AppDomain.CurrentDomain.RelativeSearchPath, "Uncommited.xml");
            if (!File.Exists(uncommitedXml) && HttpContext.Current != null)
                uncommitedXml = HttpContext.Current.Server.MapPath(uncommitedXml);

            if (File.Exists(uncommitedXml))
            {
                var ser = new XmlSerializer(typeof(UserSettings));
                using (var reader = XmlReader.Create(uncommitedXml))
                    userSettings = (UserSettings)ser.Deserialize(reader);
            }
            else
            {
                userSettings = new UserSettings
                    {
                        CommonPath = @"C:\",
                        DesktopPath = @"C:\",
                        SolutionPath = @"C:\",
                    };
            }

            // reading the debug.config file placed in a common path
            var commonPath = userSettings.CommonPath;
            cerebelloDebugPath = Path.Combine(commonPath, "Cerebello.Debug");
            cerebelloDebugConfigPath = Path.Combine(cerebelloDebugPath, "debug.config");

            if (Directory.Exists(commonPath))
            {
                {
                    var watcher = new FileSystemWatcher(commonPath, "debug.config");
                    watcher.Created += WatcherEvent;
                    watcher.Deleted += WatcherEvent;
                    watcher.Changed += WatcherEvent;
                    watcher.Renamed += WatcherEvent;
                    watcher.Error += WatcherError;
                    watcher.Disposed += WatcherDisposed;
                    watcher.IncludeSubdirectories = true;
                    watcher.EnableRaisingEvents = true;
                }

                {
                    var watcher = new FileSystemWatcher(commonPath, "Cerebello.Debug");
                    watcher.Created += WatcherEvent;
                    watcher.Deleted += WatcherEvent;
                    watcher.Changed += WatcherEvent;
                    watcher.Renamed += WatcherEvent;
                    watcher.Error += WatcherError;
                    watcher.Disposed += WatcherDisposed;
                    watcher.EnableRaisingEvents = true;
                }

                inst = new DebugConfig();
            }
            #endif
        }
        public UserSettings Add(UserSettings usersSetting)
        {
            var userSettingAdded = _userSettingsRepository.Add(usersSetting);

            _scope.Commit();

            return userSettingAdded;
        }
        public MyDomainViewModel(Uri myDomain, Action<Uri> onValidMyDomain, UserSettings userSettings)
        {
            this.onValidMyDomain = onValidMyDomain;
            this.MyDomain = myDomain == null ? null : myDomain.ToString();
            this.userSettings = userSettings;

            this.RefreshErrorState();
        }
Exemple #10
0
 public UserDataItem(UserSettings user)
 {
     Password = user.Password;
     StartingDirectory = user.StartingDirectory;
     AccessRights = user.AccessRights;
     MaxNrOfConnections = user.MaxNrOfConnections;
     name = user.Name;
 }
 void Awake()
 {
     settings = UserSettings.Instance;
     if (settings.Players.Count == 0) {
         //TODO Go to the name Registration page
     } else {
         currentPlayer = settings.CurrentPlayer;
     }
 }
        public MembershipServiceTests()
        {
            _service = new MembershipService { EnableNotifications = false };

            UserSettings settings = new UserSettings();
            settings.UserNameRegEx = @"[a-zA-Z1-9\._]{3,15}";
            settings.PasswordRegEx = "[a-zA-Z1-9]{5,15}"; 
            User.Init(new UserService(new RepositoryInMemory<User>(), new UserValidator(), settings));
            Profile.Init(new RepositoryInMemory<Profile>(), false);
        }
 public ConfigODataEndpointViewModel(UserSettings userSettings)
     : base()
 {
     this.Title = "Configure endpoint";
     this.Description = "Enter the endpoint to OData service to begin";
     this.Legend = "Endpoint";
     this.View = new ConfigODataEndpoint();
     this.View.DataContext = this;
     this.userSettings = userSettings;
 }
 public ConfigODataEndpointViewModel(UserSettings userSettings)
     : base()
 {
     this.Title = "Configure endpoint";
     this.Description = "Enter or choose an OData service endpoint to begin";
     this.Legend = "Endpoint";
     this.View = new ConfigODataEndpoint();
     this.ServiceName = Constants.DefaultServiceName;
     this.View.DataContext = this;
     this.userSettings = userSettings;
 }
Exemple #15
0
 public SettingsForm()
 {
     InitializeComponent();
     _userSettings = UserSettings.Load();
     numTransitionSlices.Text = _userSettings.TransitionSlices;
     numTransitionTime.Text = _userSettings.TransitionTimeMilliseconds;
     cmbWallpaperStyle.DataSource = Enum.GetValues(typeof (WallpaperStyle));
     cmbWallpaperStyle.SelectedItem = _userSettings.WallpaperStyle;
     _userSettings.FileTimes.ForEach(u => pnlFileTimes.Controls.Add(new FileAndTimeControl(u, _userSettings)));
     chkStartWithWindows.Checked = _userSettings.StartApplicationWithWindows;
 }
Exemple #16
0
 private ListViewItem addUserToList(UserSettings user)
 {
     var subItems = new[]
                        {
                            user.Name,
                            user.StartingDirectory,
                            user.AccessRights.ToString(),
                            user.MaxNrOfConnections.ToString()
                        };
     return listViewUsers.Items.Add(new ListViewItem(subItems));
 }
		public override Instrumentation CreateInstrument (TestContext ctx)
		{
			var instrumentation = new Instrumentation ();

			var settings = new UserSettings ();

			instrumentation.SettingsInstrument = new ConnectionInstrument (settings, ctx, this);
			if (Parameters.HandshakeInstruments != null)
				instrumentation.HandshakeInstruments.UnionWith (Parameters.HandshakeInstruments);
			return instrumentation;
		}
        public SalesforceConnectedServiceWizard(ConnectedServiceProviderContext context, VisualStudioWorkspace visualStudioWorkspace)
        {
            this.context = context;
            this.visualStudioWorkspace = visualStudioWorkspace;

            this.telemetryHelper = new TelemetryHelper(context);
            this.telemetryHelper.TrackWizardStartedEvent();

            this.userSettings = UserSettings.Load(context.Logger);

            this.InitializePages();
        }
        private bool SetupUserSettings(ActionExecutingContext filterContext)
        {
            // Prepare UserSettings property for user inside actions.
            _userSettings = PopulateUserSettingsFromCookies();

            if (UserSettings == null || !User.Identity.IsAuthenticated)
            {
                filterContext.Result = RedirectPermanent("~/Error1.html");
                return false;
            }
            filterContext.Controller.ViewBag.UserSettings = _userSettings;
            return true;
        }
        public ODataConnectedServiceWizard(ConnectedServiceProviderContext context)
        {
            this.Context = context;
            this.Project = ProjectHelper.GetProjectFromHierarchy(this.Context.ProjectHierarchy);
            this.userSettings = UserSettings.Load(context.Logger);

            ConfigODataEndpointViewModel = new ConfigODataEndpointViewModel(this.userSettings);
            AdvancedSettingsViewModel = new AdvancedSettingsViewModel();
            AdvancedSettingsViewModel.NamespacePrefix = ProjectHelper.GetProjectNamespace(this.Project);
            this.Pages.Add(ConfigODataEndpointViewModel);
            this.Pages.Add(AdvancedSettingsViewModel);

            this.IsFinishEnabled = true;
        }
		public List<TechnicalOutlook> GetTechnicalOutlook(UserSettings userSettings)
		{
			var token = __configurationService.GetSetting("Test", "LatestResearchToken", "Dictionaries", "AppSettings", "General");
			var cacheKey = string.Format("TechnicalOutlook-{0}-{1}", token, userSettings.Language);

			var technicalOutlookItems = TryGetProductSettingsFromCache(cacheKey);
			if (technicalOutlookItems == null)
			{
				technicalOutlookItems = LoadTechnicalOutlookFromService(token, userSettings.Language);
				PutProductSettingsInCache(cacheKey, technicalOutlookItems);
			}

			return technicalOutlookItems.OrderByDescending(e => e.LastUpdateDate).ToList();
		}
 public List<string> GetCategories(UserSettings userSettings)
 {
     var values = _configurationService.GetSetting(string.Empty,
                                                   "CategoryChoices",
                                                   "Dictionaries",
                                                   "AppSettings",
                                                   "Vendors",
                                                   "_default",
                                                   "_default",
                                                   userSettings.Language,
                                                   "LatestResearch");
     var categories = values.Split(new[] { ',' });
     return categories.ToList();
 }
Exemple #23
0
        private SettingsManager()
        {
            UserSettings us = new UserSettings();

            this.settingsList = new List<UserSettings>();
            this.settingsList.Add(us);
            curSettings = 0;

            this.HighestVersion = Global.CurrentVersion;

            SetDefaults(us);

            this.settings = us;
        }
Exemple #24
0
        private void InitializeSettings()
        {
            if (Settings.Default.UpgradeSettings)
            {
                Settings.Default.Upgrade();
                Settings.Default.UpgradeSettings = false;
                Settings.Default.Save();

                // Adds new settings from this version
                UserSettings.Load()?.Save();
            }

            UserSettings = UserSettings.Load();
            if (UserSettings == null) Shutdown();
        }
 public void Rollback()
 {
     try
     {
         _settings = UserSettingsRepository.Reload(_settings.Id);
         if (_settings == null) // No settings found in database, so create default
         {
             LoadDefault();
         }
     }
     catch
     {
         LoadDefault();
     }
 }
        public ODataConnectedServiceWizard(ConnectedServiceProviderContext context)
        {
            this.Context = context;
            this.Project = ProjectHelper.GetProjectFromHierarchy(this.Context.ProjectHierarchy);
            this.userSettings = UserSettings.Load(context.Logger);

            ConfigODataEndpointViewModel = new ConfigODataEndpointViewModel(this.userSettings);
            AdvancedSettingsViewModel = new AdvancedSettingsViewModel();

            if (this.Context.IsUpdating)
            {
                //Since ServiceConfigurationV4 is a derived type of ServiceConfiguration. So we can deserialize a ServiceConfiguration into a ServiceConfigurationV4.
                ServiceConfigurationV4 serviceConfig = this.Context.GetExtendedDesignerData<ServiceConfigurationV4>();
                ConfigODataEndpointViewModel.Endpoint = serviceConfig.Endpoint;
                ConfigODataEndpointViewModel.EdmxVersion = serviceConfig.EdmxVersion;
                ConfigODataEndpointViewModel.ServiceName = serviceConfig.ServiceName;
                var configODataEndpoint = (ConfigODataEndpointViewModel.View as ConfigODataEndpoint);
                configODataEndpoint.IsEnabled = false;

                //Restore the advanced settings to UI elements.
                AdvancedSettingsViewModel.PageEntering += (sender, args) =>
                {
                    var advancedSettingsViewModel = sender as AdvancedSettingsViewModel;
                    if (advancedSettingsViewModel != null)
                    {
                        AdvancedSettings advancedSettings = advancedSettingsViewModel.View as AdvancedSettings;

                        advancedSettingsViewModel.GeneratedFileName = serviceConfig.GeneratedFileNamePrefix;
                        advancedSettings.ReferenceFileName.IsEnabled = false;
                        advancedSettingsViewModel.UseNamespacePrefix = serviceConfig.UseNameSpacePrefix;
                        advancedSettingsViewModel.NamespacePrefix = serviceConfig.NamespacePrefix;
                        advancedSettingsViewModel.UseDataServiceCollection = serviceConfig.UseDataServiceCollection;

                        if (serviceConfig.EdmxVersion == Common.Constants.EdmxVersion4)
                        {
                            advancedSettingsViewModel.IgnoreUnexpectedElementsAndAttributes = serviceConfig.IgnoreUnexpectedElementsAndAttributes;
                            advancedSettingsViewModel.EnableNamingAlias = serviceConfig.EnableNamingAlias;
                            advancedSettingsViewModel.IncludeT4File = serviceConfig.IncludeT4File;
                            advancedSettings.IncludeT4File.IsEnabled = false;
                        }
                    }
                };
            }

            this.Pages.Add(ConfigODataEndpointViewModel);
            this.Pages.Add(AdvancedSettingsViewModel);
            this.IsFinishEnabled = true;
        }
        public List<TradeIdeasResult> GetTradeIdeas(UserSettings userSettings, string tradeIdeasId = null)
        {
            var gs = _configurationService.GetGeneralSettings();
            var token = gs.AutochartSessionToken;
            var langCode = userSettings.Language;
            var isDemoAccount = gs.IsDemoAutochartSessionToken;

            var cacheKey = string.Format("TradeIdeas-{0}-{1}", token, langCode);
            var items = TryGetTradeIdeasItemsFromCache(cacheKey);

            if (items == null)
            {
                var autoChartToken = string.Empty;
                var autoChartUrl = string.Empty;
                var researchServiceAddress = WebservicesConfig.Webservices["Research"].Settings["URL"].Value;

                var researchServiceSoapClient = researchServiceAddress.Contains("https://")
                                                    ? new ResearchServiceSoapClient("ResearchServiceSoapHttps", researchServiceAddress)
                                                    : new ResearchServiceSoapClient("ResearchServiceSoap", researchServiceAddress);

                var lang = GetLanguageByLangCode(langCode);
                var blotterOfAutoCharting = researchServiceSoapClient.GetAutoChartSession(new Authenticator { Language = lang }, token);
                if (blotterOfAutoCharting.Success)
                {
                    autoChartToken = blotterOfAutoCharting.Output[0].AutoChartToken;
                    autoChartUrl = blotterOfAutoCharting.Output[0].AutoChartURL;
                }
                var links = _configurationService.GetSettingsForUser(userSettings);

                var tradeIdeasUrl =
                    links("TradeIdeas")
                        .Where(ti => !String.IsNullOrWhiteSpace(ti))
                        .GetValueOrDefault(
                                           "{0}?sessionid={1}&request=tradeideas&maxhits=100&sourceapp=FOREXTraderPRO&language={2}&demo={3}");


                var url = string.Format(tradeIdeasUrl, autoChartUrl, autoChartToken, lang, isDemoAccount ? "1" : "0");

                return FetchTradeIdeasItems(autoChartToken, cacheKey, url, tradeIdeasId);
            }

            if (!string.IsNullOrWhiteSpace(tradeIdeasId))
            {
                return new List<TradeIdeasResult> { _tradeIdeasStorage.GetTradeIdeasEntry(cacheKey, tradeIdeasId) };
            }

            return items;
        }
		public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
		{
			UserSettings settings = new UserSettings();
			settings.UserID = DictionaryHelper.GetValue(dictionary, "UserID", string.Empty);

			if (dictionary.ContainsKey("Categories"))
			{
				UserSettingsCategoryCollection categories = JSONSerializerExecute.Deserialize<UserSettingsCategoryCollection>(dictionary["Categories"]);

				settings.Categories.Clear();
				settings.Categories.CopyFrom(categories);

			}

			return settings;
		}
		public sealed override Instrumentation CreateInstrument (TestContext ctx)
		{
			var instrumentation = new Instrumentation ();

			var settings = new UserSettings ();
			settings.EnableDebugging = Parameters.EnableDebugging;
			var connectionInstrument = CreateConnectionInstrument (ctx, settings);

			instrumentation.SettingsInstrument = connectionInstrument;
			instrumentation.EventSink = connectionInstrument.EventSink;

			if (Parameters.HandshakeInstruments != null)
				instrumentation.HandshakeInstruments.UnionWith (Parameters.HandshakeInstruments);

			return instrumentation;
		}
 public FileAndTimeControl(FileAtTime fat, UserSettings userSettings)
 {
     InitializeComponent();
     _fileAtTime = fat;
     _userSettings = userSettings;
     dtpTimeOfDay.Text = fat.TimeOfDay;
     txtFilePath.Text = fat.WallpaperPath;
     if (!string.IsNullOrEmpty(txtFilePath.Text))
     {
         var directoryInfo = new FileInfo(txtFilePath.Text).Directory;
         if (directoryInfo != null)
         {
             ofdBrowse.InitialDirectory = directoryInfo.FullName;
         }
     }
 }
Exemple #31
0
 public AppSettings(ISettingsStorage storage, UserSettings userSettings)
 {
     _storage      = storage;
     _userSettings = userSettings;
 }
        public static void ConfigureServices(IServiceCollection container, IConfiguration configuration, IWebAssemblyHostEnvironment webAssemblyHostEnvironment)
        {
            container.Configure <AppSettings>(configuration.GetSection(nameof(AppSettings)));

            container.AddSingleton <IAppState, AppState>();
            container.AddSingleton <ICookieManager, CookieManager>();
            container.AddSingleton <IFileManager, FileManager>();
            container.AddSingleton <ISessionStore, SessionStore>();
            container.AddSingleton(sp =>
            {
                var appSettings   = sp.GetRequiredService <IOptions <AppSettings> >();
                var sessionStore  = sp.GetRequiredService <ISessionStore>();
                var cookieManager = sp.GetRequiredService <ICookieManager>();

                var funds = sessionStore.Get <Dictionary <Symbol, FundInfo> >(StoreKeys.Funds)
                            ?? new Dictionary <Symbol, FundInfo>();

                var currencyCode       = cookieManager.Get <CurrencyCode>(CookieKeys.CurrencyCode);
                var durationMode       = cookieManager.Get <DurationMode>(CookieKeys.DurationMode);
                var addr               = cookieManager.Get <string>(CookieKeys.WalletAddresses);
                var secondaryAddresses = cookieManager.Get <string>(CookieKeys.SecondaryWalletAddresses)
                                         ?.Split(',', StringSplitOptions.RemoveEmptyEntries)
                                         ?.Select(x => x.ToLower())
                                         ?.ToList()
                                         ?? new List <string>();

                var settings = new UserSettings(appSettings, funds, secondaryAddresses)
                {
                    CurrencyCode = currencyCode,
                    DurationMode = durationMode
                };

                settings.SetAddress(addr);

                return(settings);
            });

            container.AddSingleton <IUserSettings>(sp => sp.GetRequiredService <UserSettings>());
            container.AddSingleton <IUserSettingsHandle, UserSettingsHandle>();
            container.AddSingleton <IEnvironmentNameAccessor, EnvironmentNameAccessor>();

            container.AddScoped(sp => new HttpClient(
                                    new DefaultBrowserOptionsMessageHandler()
            {
                DefaultBrowserRequestCache       = BrowserRequestCache.NoCache,
                DefaultBrowserRequestCredentials = BrowserRequestCredentials.Include,
                DefaultBrowserRequestMode        = BrowserRequestMode.Cors,
            })
            {
                BaseAddress = new Uri(webAssemblyHostEnvironment.BaseAddress),
            });

            container
            .AddScoped <IHostClient, HostClient>()
            .AddHttpClient(
                nameof(HostClient),
                (sp, client) =>
            {
                var settings = sp.GetRequiredService <IOptions <AppSettings> >();

                client.BaseAddress = new Uri(webAssemblyHostEnvironment.BaseAddress, UriKind.Absolute);
                client.Timeout     = TimeSpan.FromSeconds(10);
                client.DefaultRequestHeaders.TryAddWithoutValidation(Headers.Origin, webAssemblyHostEnvironment.BaseAddress);
                client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(settings.Value.ServiceName, $"v{settings.Value.Version}"));
            });

            container
            .AddScoped <IApiClient, ApiClient>()
            .AddHttpClient(
                nameof(ApiClient),
                (sp, client) =>
            {
                var settings = sp.GetRequiredService <IOptions <AppSettings> >();

                client.BaseAddress = settings.Value.ApiUrl;
                client.Timeout     = TimeSpan.FromSeconds(30);
                client.DefaultRequestHeaders.TryAddWithoutValidation(Headers.Origin, webAssemblyHostEnvironment.BaseAddress);
                client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(settings.Value.ServiceName, $"v{settings.Value.Version}"));
            });
        }
 public IActionResult SendUserSettings([FromBody] UserSettings userSettings)
 {
     return(Ok());
 }
        public void SaveSettings(string path, string USERSETTINGS, UserSettings settings)
        {
            string json = settings.ToJson();

            FileWriter.WriteJsonToFile(json, USERSETTINGS, path);
        }
 protected abstract void GetSettings(UserSettings settings);
 internal void SaveSettings()
 {
     CodeIDXSettings.Default.SearchHistory = SearchHistory.ToList();
     UserSettings.Save();
 }
Exemple #37
0
        public async Task <IActionResult> CreateApplication([FromBody] ViewModels.Application item)
        {
            // for association with current user
            string       userJson     = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
            UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(userJson);
            int          count        = GetSubmittedCountByApplicant(userSettings.AccountId);

            if (count >= 8)
            {
                return(BadRequest("8 applications have already been submitted. Can not create more"));
            }
            MicrosoftDynamicsCRMadoxioApplication adoxioApplication = new MicrosoftDynamicsCRMadoxioApplication();

            // copy received values to Dynamics Application
            adoxioApplication.CopyValues(item);
            adoxioApplication.AdoxioApplicanttype = (int?)item.ApplicantType;
            try
            {
                var adoxioLicencetype = _dynamicsClient.GetAdoxioLicencetypeByName(item.LicenseType);

                // set license type relationship
                adoxioApplication.AdoxioLicenceTypeODataBind = _dynamicsClient.GetEntityURI("adoxio_licencetypes", adoxioLicencetype.AdoxioLicencetypeid);
                adoxioApplication.AdoxioApplicantODataBind   = _dynamicsClient.GetEntityURI("accounts", userSettings.AccountId);
                adoxioApplication = _dynamicsClient.Applications.Create(adoxioApplication);
            }
            catch (OdataerrorException odee)
            {
                string applicationId = _dynamicsClient.GetCreatedRecord(odee, null);
                if (!string.IsNullOrEmpty(applicationId) && Guid.TryParse(applicationId, out Guid applicationGuid))
                {
                    adoxioApplication = await _dynamicsClient.GetApplicationById(applicationGuid);
                }
                else
                {
                    _logger.LogError("Error creating application");
                    _logger.LogError("Request:");
                    _logger.LogError(odee.Request.Content);
                    _logger.LogError("Response:");
                    _logger.LogError(odee.Response.Content);
                    // fail if we can't create.
                    throw (odee);
                }
            }

            // in case the job number is not there, try getting the record from the server.
            if (adoxioApplication.AdoxioJobnumber == null)
            {
                _logger.LogError("AdoxioJobnumber is null, fetching record again.");
                Guid id = Guid.Parse(adoxioApplication.AdoxioApplicationid);
                adoxioApplication = await _dynamicsClient.GetApplicationById(id);
            }

            if (adoxioApplication.AdoxioJobnumber == null)
            {
                _logger.LogError("Unable to get the Job Number for the Application.");
                throw new Exception("Error creating Licence Application.");
            }

            await initializeSharepoint(adoxioApplication);

            return(Json(await adoxioApplication.ToViewModel(_dynamicsClient)));
        }
Exemple #38
0
        // This is called immediately after initialising the speech recogniser in MainWindow
        public static void initialise(AudioPlayer audioPlayer, SpeechRecogniser speechRecogniser)
        {
            stopped = false;
            macros.Clear();
            if (UserSettings.GetUserSettings().getBoolean("enable_command_macros"))
            {
                // load the json:
                MacroContainer macroContainer = loadCommands(getUserMacrosFileLocation());
                // if it's valid, load the command sets:
                if (macroContainer.assignments != null && macroContainer.assignments.Length > 0 && macroContainer.macros != null)
                {
                    // get the assignments by game:
                    Dictionary <String, KeyBinding[]> assignmentsByGame = new Dictionary <String, KeyBinding[]>();
                    foreach (Assignment assignment in macroContainer.assignments)
                    {
                        if (!assignmentsByGame.ContainsKey(assignment.gameDefinition))
                        {
                            assignmentsByGame.Add(assignment.gameDefinition, assignment.keyBindings);
                        }
                    }

                    Dictionary <string, ExecutableCommandMacro> voiceTriggeredMacros = new Dictionary <string, ExecutableCommandMacro>();
                    foreach (Macro macro in macroContainer.macros)
                    {
                        Boolean hasCommandForCurrentGame = false;
                        Boolean allowAutomaticTriggering = false;
                        // eagerly load the key bindings for each macro:
                        foreach (CommandSet commandSet in macro.commandSets)
                        {
                            if (commandSet.gameDefinition.Equals(CrewChief.gameDefinition.gameEnum.ToString(), StringComparison.InvariantCultureIgnoreCase))
                            {
                                // this does the conversion from key characters to key enums and stores the result to save us doing it every time
                                if (!commandSet.loadActionItems(assignmentsByGame[commandSet.gameDefinition]))
                                {
                                    Console.WriteLine("Macro \"" + macro.name + "\" failed to load - some actionItems didn't parse succesfully");
                                }
                                else
                                {
                                    allowAutomaticTriggering = commandSet.allowAutomaticTriggering;
                                    hasCommandForCurrentGame = true;
                                }
                                break;
                            }
                        }
                        if (hasCommandForCurrentGame)
                        {
                            // make this macro globally visible:
                            ExecutableCommandMacro commandMacro = new ExecutableCommandMacro(audioPlayer, macro, assignmentsByGame, allowAutomaticTriggering);
                            macros.Add(macro.name, commandMacro);
                            // if there's a voice command, load it into the recogniser:
                            if (macro.voiceTriggers != null && macro.voiceTriggers.Length > 0)
                            {
                                foreach (String voiceTrigger in macro.voiceTriggers)
                                {
                                    if (voiceTriggeredMacros.ContainsKey(voiceTrigger))
                                    {
                                        Console.WriteLine("Voice trigger " + voiceTrigger + " has already been allocated to a different command");
                                    }
                                    else
                                    {
                                        voiceTriggeredMacros.Add(voiceTrigger, commandMacro);
                                    }
                                }
                            }
                            else if (macro.integerVariableVoiceTrigger != null && macro.integerVariableVoiceTrigger.Length > 0)
                            {
                                if (voiceTriggeredMacros.ContainsKey(macro.integerVariableVoiceTrigger))
                                {
                                    Console.WriteLine("Voice trigger " + macro.integerVariableVoiceTrigger + " has already been allocated to a different command");
                                }
                                else
                                {
                                    voiceTriggeredMacros.Add(macro.integerVariableVoiceTrigger, commandMacro);
                                }
                            }
                        }
                    }
                    try
                    {
                        speechRecogniser.loadMacroVoiceTriggers(voiceTriggeredMacros);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Failed to load command macros into speech recogniser: " + e.Message);
                    }
                }
            }
            else
            {
                Console.WriteLine("Command macros are disabled");
            }
        }
Exemple #39
0
        public override void Refresh()
        {
            base.Refresh();

            if (m_type == LatitudeLongitudeType.LONGITUDE)
            {
                radioButton1.Text = "EAST";
                radioButton2.Text = "WEST";

                string d = UserSettings.Get(UserSettingTags.GPSLocationFixedLonDegrees);
                if (d != null)
                {
                    textBoxDegrees.Text = d;
                }
                else
                {
                    textBoxDegrees.Text = null;
                }

                string m = UserSettings.Get(UserSettingTags.GPSLocationFixedLonMinutes);
                if (m != null)
                {
                    double minSecs = Convert.ToDouble(m);
                    double frac    = minSecs - Math.Floor(minSecs);
                    double secs    = frac * 60;
                    textBoxMinutes.Text = Math.Floor(minSecs).ToString();
                    textBoxSeconds.Text = secs.ToString();
                }
                else
                {
                    textBoxMinutes.Text = null;
                }

                d = UserSettings.Get(UserSettingTags.GPSLocationFixedLonDirection);
                radioButton2.Checked = true;// default setting
                if (d != null)
                {
                    if (d.Contains("EAST"))
                    {
                        radioButton2.Checked = false;
                        radioButton1.Checked = true;
                        radioButton1.Invalidate();
                        radioButton2.Invalidate();
                    }
                    else
                    {
                        radioButton2.Checked = true;
                        radioButton1.Checked = false;
                        radioButton1.Invalidate();
                        radioButton2.Invalidate();
                    }
                }
            }

            if (m_type == LatitudeLongitudeType.LATITUDE)
            {
                radioButton1.Text = "NORTH";
                radioButton2.Text = "SOUTH";

                string d = UserSettings.Get(UserSettingTags.GPSLocationFixedLatDegrees);
                if (d != null)
                {
                    textBoxDegrees.Text = d;
                }
                else
                {
                    textBoxDegrees.Text = null;
                }

                string m = UserSettings.Get(UserSettingTags.GPSLocationFixedLatMinutes);
                if (m != null)
                {
                    double minSecs = Convert.ToDouble(m);
                    double frac    = minSecs - Math.Floor(minSecs);
                    double secs    = frac * 60;
                    textBoxMinutes.Text = Math.Floor(minSecs).ToString();
                    textBoxSeconds.Text = secs.ToString();
                }
                else
                {
                    textBoxMinutes.Text = null;
                }

                d = UserSettings.Get(UserSettingTags.GPSLocationFixedLatDirection);
                radioButton1.Checked = true;// default setting

                if (d != null)
                {
                    if (d.Contains("NORTH"))
                    {
                        radioButton2.Checked = false;
                        radioButton1.Select();
                        radioButton1.Checked = true;
                        radioButton1.Invalidate();
                        radioButton2.Invalidate();
                    }
                    else
                    {
                        radioButton1.Checked = false;

                        radioButton2.Select();
                        radioButton2.Checked = true;
                        radioButton1.Invalidate();
                        radioButton2.Invalidate();
                    }
                }
            }
        }
Exemple #40
0
 static SaveAllTheTimeAdornment()
 {
     settings = UserSettings.Load();
     settings.AutoSave();
 }
Exemple #41
0
 public void SetStarred(string name, bool starred)
 {
     UserSettings.SetReportStarred(name, starred);
 }
        /// <exclude />
        public static bool SetUp(string setupDescriptionXml, string username, string password, string email, string language, string consoleLanguage, bool newsletter)
        {
            ApplicationOnlineHandlerFacade.TurnApplicationOffline(false);

            username = username.Trim().ToLowerInvariant();

            XElement setupDescription = XElement.Parse(setupDescriptionXml);

            XElement setupRegistrationDescription = new XElement("registration",
                                                                 new XElement("user_email", email),
                                                                 new XElement("user_newsletter", newsletter),
                                                                 new XElement("user_consolelanguage", consoleLanguage),
                                                                 new XElement("user_websitelanguage", language),
                                                                 setupDescription);

            bool success = false;

            try
            {
                Log.LogInformation(VerboseLogTitle, "Downloading packages");

                string[]       packageUrls = GetPackageUrls(setupDescription).ToArray();
                MemoryStream[] packages    = new MemoryStream[packageUrls.Length];

                Parallel.For(0, packageUrls.Length, i =>
                {
                    packages[i] = DownloadPackage(packageUrls[i]);
                });

                Log.LogInformation(VerboseLogTitle, "Setting up the system for the first time");

                CultureInfo locale      = new CultureInfo(language);
                CultureInfo userCulture = new CultureInfo(consoleLanguage);

                ApplicationLevelEventHandlers.ApplicationStartInitialize();

                Log.LogInformation(VerboseLogTitle, "Creating first locale: " + language);
                LocalizationFacade.AddLocale(locale, "", true, false);
                LocalizationFacade.SetDefaultLocale(locale);


                Log.LogInformation(VerboseLogTitle, "Creating first user: "******"Installing package from url " + packageUrls[i]);
                        InstallPackage(packageUrls[i], packages[i]);

                        // Releasing a reference to reduce memory usage
                        packages[i].Dispose();
                        packages[i] = null;
                    }
                }

                RegisterSetup(setupRegistrationDescription.ToString(), "");

                Log.LogInformation(VerboseLogTitle, "Done setting up the system for the first time! Enjoy!");

                success = true;
            }
            catch (Exception ex)
            {
                Log.LogCritical(LogTitle, ex);
                Log.LogWarning(LogTitle, "First time setup failed - could not download, install package or otherwise complete the setup.");
                RegisterSetup(setupRegistrationDescription.ToString(), ex.ToString());

                if (RuntimeInformation.IsDebugBuild)
                {
                    ApplicationOnlineHandlerFacade.TurnApplicationOnline();
                    throw;
                }
            }

            ApplicationOnlineHandlerFacade.TurnApplicationOnline();
            return(success);
        }
        public void BindWebItem(int packageId, WebVirtualDirectory item)
        {
            fileLookup.PackageId    = item.PackageId;
            fileLookup.SelectedFile = item.ContentPath;

            string resSuffix = item.IIs7 ? "IIS7" : "";

            chkRedirectExactUrl.Text       = GetLocalizedString("chkRedirectExactUrl.Text" + resSuffix);
            chkRedirectDirectoryBelow.Text = GetLocalizedString("chkRedirectDirectoryBelow.Text" + resSuffix);
            chkRedirectPermanent.Text      = GetLocalizedString("chkRedirectPermanent.Text" + resSuffix);

            chkRedirectExactUrl.Checked       = item.RedirectExactUrl;
            chkRedirectDirectoryBelow.Checked = item.RedirectDirectoryBelow;
            chkRedirectPermanent.Checked      = item.RedirectPermanent;

            chkDirectoryBrowsing.Checked = item.EnableDirectoryBrowsing;
            chkParentPaths.Checked       = item.EnableParentPaths;
            chkWrite.Checked             = item.EnableWritePermissions;

            chkDedicatedPool.Checked = item.DedicatedApplicationPool;
            chkDedicatedPool.Enabled = !item.SharePointInstalled;

            chkAuthAnonymous.Checked      = item.EnableAnonymousAccess;
            chkAuthWindows.Checked        = item.EnableWindowsAuthentication;
            chkAuthBasic.Checked          = item.EnableBasicAuthentication;
            chkDynamicCompression.Checked = item.EnableDynamicCompression;
            chkStaticCompression.Checked  = item.EnableStaticCompression;

            // default documents
            txtDefaultDocs.Text = String.Join("\n", item.DefaultDocs.Split(',', ';'));

            // redirection
            txtRedirectUrl.Text = item.HttpRedirect;
            bool redirectionEnabled = !String.IsNullOrEmpty(item.HttpRedirect);

            rbLocationFolder.Checked   = !redirectionEnabled;
            rbLocationRedirect.Checked = redirectionEnabled;
            valRedirection.Enabled     = redirectionEnabled;

            // store app pool value
            ViewState["ApplicationPool"] = item.ApplicationPool;

            ToggleLocationControls();

            // toggle controls by quotas
            fileLookup.Enabled         = PackagesHelper.CheckGroupQuotaEnabled(packageId, ResourceGroups.Web, Quotas.WEB_HOMEFOLDERS);
            rbLocationRedirect.Visible = PackagesHelper.CheckGroupQuotaEnabled(packageId, ResourceGroups.Web, Quotas.WEB_REDIRECTIONS);
            bool customSecurity = PackagesHelper.CheckGroupQuotaEnabled(packageId, ResourceGroups.Web, Quotas.WEB_SECURITY);

            chkWrite.Visible = customSecurity;
            // hide authentication options if not allowed
            pnlCustomAuth.Visible = customSecurity;
            //
            chkDedicatedPool.Visible    = PackagesHelper.CheckGroupQuotaEnabled(packageId, ResourceGroups.Web, Quotas.WEB_APPPOOLS);
            pnlDefaultDocuments.Visible = PackagesHelper.CheckGroupQuotaEnabled(packageId, ResourceGroups.Web, Quotas.WEB_DEFAULTDOCS);

            UserSettings settings = ES.Services.Users.GetUserSettings(PanelSecurity.SelectedUserId, "WebPolicy");

            if (Utils.ParseBool(settings["EnableDedicatedPool"], false) == true)
            {
                chkDedicatedPool.Checked = true;
            }

            chkDedicatedPool.Enabled = !(Utils.ParseBool(settings["EnableDedicatedPool"], false));
        }
Exemple #44
0
 public void SaveState()
 {
     _clonedSettings = ((UserSettings)DataContext).Clone() as UserSettings;
 }
        private async void ExecuteSave()
        {
            // Prevent multiple tap on save button
            _tapCount += 1;
            if (_tapCount > 1)
            {
                _tapCount = 0;
                return;
            }

            Expense exp = new Expense();

            exp.Date = this.Date;

            if (this.CategorySelectedItem == null)
            {
                await base.ShowErrorMessage("Select a category.");

                return;
            }
            exp.Category = this.CategorySelectedItem;

            if (this.Value == 0)
            {
                await base.ShowErrorMessage("Inform a value.");

                return;
            }
            exp.Value = this.Value;

            if (this.PaymentTypeSelectedItem == null)
            {
                await base.ShowErrorMessage("Select a payment type.");

                return;
            }
            exp.PaymentType = this.PaymentTypeSelectedItem;


            if (string.IsNullOrEmpty(this.Description))
            {
                exp.Description = exp.Category;
            }
            else
            {
                exp.Description = this.Description;
            }



            exp.UserName = UserSettings.GetEmail();


            HttpResponseMessage httpResponse = await _expenseTrackerWebApiService.SaveExpenseAsync(exp);

            if (httpResponse.IsSuccessStatusCode)
            {
                string imageToShow = GetImageToShow(exp);
                await App.NavigateMasterDetailModalBack(imageToShow);
            }
            else
            {
                await base.ShowErrorMessage("Error creating Expense on server.");
            }
        }
        public JsonResult GetCurrentSecurityScreeningSummaryNew()
        {
            // get the current user.
            UserSettings userSettings = UserSettings.CreateFromHttpContext(_httpContextAccessor);

            // check that the session is setup correctly.
            userSettings.Validate();

            // get data for the current account.
            string currentAccountId = userSettings.AccountId;

            var contacts = _dynamicsClient.GetLEConnectionsForAccount(currentAccountId, _logger, _configuration);
            List <SecurityScreeningStatusItem> securityItems = GetConnectionsScreeningData(contacts);

            // get the current user's applications and licences
            var licences     = _dynamicsClient.GetLicensesByLicencee(_cache, currentAccountId);
            var applications = _dynamicsClient.GetApplicationsForLicenceByApplicant(currentAccountId);

            SecurityScreeningSummary result = new SecurityScreeningSummary();

            // determine how many of each licence there are.
            int cannabisLicenceCount = 0;
            int liquorLicenceCount   = 0;

            if (licences != null && licences.Count() > 0)
            {
                cannabisLicenceCount = licences.Count(x => x.AdoxioLicenceType.AdoxioName.ToUpper().Contains("CANNABIS"));
                liquorLicenceCount   = licences.Count() - cannabisLicenceCount;
            }

            // determine how many applications of each type there are.
            int cannabisApplicationCount = 0;
            int liquorApplicationCount   = 0;

            if (applications != null && applications.Count() > 0)
            {
                cannabisApplicationCount = applications.Count(x => x.AdoxioApplicationTypeId != null && x.AdoxioApplicationTypeId.AdoxioName != null && x.AdoxioApplicationTypeId.AdoxioName.ToUpper().Contains("CANNABIS"));
                liquorApplicationCount   = applications.Count() - cannabisApplicationCount;
            }


            if (cannabisLicenceCount > 0 || cannabisApplicationCount > 0)
            {
                var data = securityItems.Select(item =>
                {
                    item.IsComplete = (item.Contact?.AdoxioCascomplete == (int)YesNoOptions.Yes);
                    return(item);
                });
                result.Cannabis = new SecurityScreeningCategorySummary()
                {
                    CompletedItems   = data.Where(item => item.IsComplete).ToList(),
                    OutstandingItems = data.Where(item => !item.IsComplete).ToList()
                };
            }

            if (liquorLicenceCount > 0 || liquorApplicationCount > 0)
            {
                var data = securityItems.Select(item =>
                {
                    item.IsComplete = (item.Contact?.AdoxioPhscomplete == (int)YesNoOptions.Yes);
                    return(item);
                });
                result.Liquor = new SecurityScreeningCategorySummary()
                {
                    CompletedItems   = data.Where(item => item.IsComplete).ToList(),
                    OutstandingItems = data.Where(item => !item.IsComplete).ToList()
                };
            }

            return(new JsonResult(result));
        }
Exemple #47
0
 public WatcherTests()
 {
     _formMock     = new Moq.Mock <IFrmEspionSpotify>().Object;
     _fileSystem   = new MockFileSystem(new Dictionary <string, MockFileData>());
     _userSettings = new UserSettings();
 }
Exemple #48
0
 public DeleteProfileCommandHandler(UserSettings settings)
 {
     _settings = settings;
 }
 /// <summary>
 ///  Constructor that get implemented based on CloudService
 ///  when passing in the api key and http client
 /// </summary>
 /// <param name="key"> API key for Bing Entity Search </param>
 public EntitySearchHandler(string keyFile) : base(keyFile)
 {
     Host     = UserSettings.GetKey(keyFile + "Endpoint", "api.cognitive.microsoft.com/bing/v7.0");
     Endpoint = "entities";
 }
 /// <summary>
 /// Called when the form is closed. We dispose of our
 /// <see cref="UserSettings"/> instance here.
 /// </summary>
 /// <param name="sender">Event sender.</param>
 /// <param name="e">Event arguments.</param>
 private void UserSettingsWieldingForm_FormClosed(object sender, FormClosedEventArgs e)
 {
     Settings?.Dispose();
     Settings = null;
 }
        protected override ConnectionInstrument CreateConnectionInstrument(TestContext ctx, UserSettings settings)
        {
            var instrument = base.CreateConnectionInstrument(ctx, settings);

            instrument.EventSink = new MyEventSink(ctx, (RenegotiationInstrumentConnectionHandler)ConnectionHandler);
            return(instrument);
        }
Exemple #52
0
 private void LoadOpenCount()
 {
     OpenCount = UserSettings.GetReportOpenCount(Path.GetFileName(_fileName));
 }
        public FrmEspionSpotify()
        {
            SuspendLayout();

            Instance = this;
            InitializeComponent();

            _userSettings = new UserSettings();
            Rm            = new ResourceManager(typeof(en));
            BackImage     = Resources.spytify_logo;

            if (Settings.Default.Directory.Equals(string.Empty))
            {
                Settings.Default.Directory = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic);
                Settings.Default.Save();
            }

            if (Settings.Default.AnalyticsCID.Equals(string.Empty))
            {
                Settings.Default.AnalyticsCID = Analytics.GenerateCID();
                Settings.Default.Save();
            }

            _analytics = new Analytics(Settings.Default.AnalyticsCID, Assembly.GetExecutingAssembly().GetName().Version.ToString());
            Task.Run(async() => await _analytics.LogAction("launch"));

            var clientId = Settings.Default.SpotifyAPIClientId;
            var secretId = Settings.Default.SpotifyAPISecretId;

            if (!string.IsNullOrEmpty(clientId) && !string.IsNullOrEmpty(secretId))
            {
                ExternalAPI.Instance = new MediaTags.SpotifyAPI(clientId, secretId);
            }

            var indexLanguage            = Settings.Default.Language;
            var indexBitRate             = Settings.Default.Bitrate;
            var indexAudioEndPointDevice = Settings.Default.AudioEndPointDeviceIndex.ToNullableInt();

            tcMenu.SelectedIndex = Settings.Default.TabNo;

            rbMp3.Checked             = Settings.Default.MediaFormat == 0;
            rbWav.Checked             = Settings.Default.MediaFormat == 1;
            tbMinTime.Value           = Settings.Default.MinimumRecordedLengthSeconds / 5;
            tgEndingSongDelay.Checked = Settings.Default.EndingSongDelayEnabled;
            tgAddSeparators.Checked   = Settings.Default.TrackTitleSeparatorEnabled;
            tgNumTracks.Checked       = Settings.Default.OrderNumberInMediaTagEnabled;
            tgNumFiles.Checked        = Settings.Default.OrderNumberInfrontOfFileEnabled;
            tgAddFolders.Checked      = Settings.Default.GroupByFoldersEnabled;
            txtPath.Text         = Settings.Default.Directory;
            tgDisableAds.Checked = ManageHosts.AreAdsDisabled(ManageHosts.HostsSystemPath);
            tgMuteAds.Checked    = Settings.Default.MuteAdsEnabled;
            tgDuplicateAlreadyRecordedTrack.Checked = Settings.Default.DuplicateAlreadyRecordedTrack;
            folderBrowserDialog.SelectedPath        = Settings.Default.Directory;

            SetLanguageDropDown();

            var language = (LanguageType)indexLanguage;

            SetLanguage(language);

            cbBitRate.SelectedIndex  = indexBitRate;
            cbLanguage.SelectedIndex = indexLanguage;

            _userSettings.OutputPath  = Settings.Default.Directory;
            _userSettings.Bitrate     = ((KeyValuePair <LAMEPreset, string>)cbBitRate.SelectedItem).Key;
            _userSettings.MediaFormat = (MediaFormat)Settings.Default.MediaFormat;
            _userSettings.MinimumRecordedLengthSeconds    = Settings.Default.MinimumRecordedLengthSeconds;
            _userSettings.GroupByFoldersEnabled           = Settings.Default.GroupByFoldersEnabled;
            _userSettings.TrackTitleSeparator             = Settings.Default.TrackTitleSeparatorEnabled ? "_" : " ";
            _userSettings.OrderNumberInMediaTagEnabled    = Settings.Default.OrderNumberInMediaTagEnabled;
            _userSettings.OrderNumberInfrontOfFileEnabled = Settings.Default.OrderNumberInfrontOfFileEnabled;
            _userSettings.EndingTrackDelayEnabled         = Settings.Default.EndingSongDelayEnabled;
            _userSettings.DuplicateAlreadyRecordedTrack   = Settings.Default.DuplicateAlreadyRecordedTrack;
            _userSettings.AudioEndPointDeviceIndex        = indexAudioEndPointDevice; // TODO: settings default stay last saved

            txtRecordingNum.Text = _userSettings.InternalOrderNumber.ToString("000");

            _audioSession = new MainAudioSession(indexAudioEndPointDevice);
            SetAudioEndPointDevicesDropDown();
            UpdateAudioEndPointFields();

            var lastVersionPrompted = Settings.Default.LastVersionPrompted.ToVersion();

            lnkRelease.Visible = lastVersionPrompted != null && lastVersionPrompted > Assembly.GetExecutingAssembly().GetName().Version;

            ResumeLayout();

            GitHub.GetVersion();
        }
Exemple #54
0
 public void SaveOpenCount()
 {
     UserSettings.SetReportOpenCount(Path.GetFileName(_fileName), OpenCount);
 }
 public UserSettingsBuilder()
 {
     ruleSettings = new RulesSettings();
     UserSettings = new UserSettings(ruleSettings);
 }
 async Task UseLanguageAsync(Locale language)
 {
     UserSettings.Edit <GeneralUserSetting>(s => s.Language = language);
     await ReplyAsync(LanguageText.CHANGED, ReplyType.Success, language);
 }
        internal static void SaveSettings(UserSettings settings)
        {
            var json = JsonConvert.SerializeObject(settings);

            File.WriteAllText(PathProvider.UserSettingsFilePath, json);
        }
Exemple #58
0
 public List <string> GetUnstarredBulk()
 {
     return(UserSettings.GetUnstarredBulk());
 }
Exemple #59
0
        public void LoadSettings()
        {
            String       curSettingsName = "Default";
            Int32        settingsNodeCount;
            UserSettings us;
            Int32        settingsVer;
            XmlNode      baseNode;
            XmlNodeList  settingsNodes;
            XmlNode      parseNode;
            XmlNodeList  parseNodeList;
            XmlDocument  xmlDoc = new XmlDocument();

            xmlDoc.Load(Global.ApplicationUserSettingsFile);

            baseNode = xmlDoc.DocumentElement;

            // There's no UserSettings element so we'll use the default settings.
            if (baseNode.Name != "UserSettings")
            {
                return;
            }

            if (baseNode.Attributes["version"] == null)
            {
                settingsVer = 0;
            }
            else
            {
                settingsVer = Int32.Parse(baseNode.Attributes["version"].Value);
            }

            switch (settingsVer)
            {
            case 0:
                break;

            case 1:
                parseNode = baseNode.SelectSingleNode("GlobalSettings");

                if (parseNode == null)
                {
                    break;
                }

                parseNodeList = parseNode.SelectNodes("item");

                foreach (XmlNode node in parseNodeList)
                {
                    parseNode = node.Attributes["name"];

                    if (parseNode == null)
                    {
                        continue;
                    }

                    switch (parseNode.Value)
                    {
                    case "UseSettings":
                        parseNode = node.Attributes["value"];

                        if (parseNode != null)
                        {
                            curSettingsName = parseNode.Value;
                        }
                        break;

                    case "HighestVersion":
                        parseNode = node.Attributes["value"];

                        if (parseNode != null)
                        {
                            this.HighestVersion = Int32.Parse(parseNode.Value);
                        }
                        break;

                    default:
                        break;
                    }
                }
                break;

            default:
                break;
            }

            if (settingsVer > 0)
            {
                settingsNodes = baseNode.SelectNodes("Settings");
            }
            else
            {
                settingsNodes = xmlDoc.SelectNodes("UserSettings");
            }

            settingsNodeCount = 0;
            foreach (XmlNode settingsNode in settingsNodes)
            {
                String settingsName;

                parseNode = settingsNode.Attributes["name"];

                if (parseNode == null)
                {
                    settingsName = "Default";
                }
                else
                {
                    settingsName = parseNode.Value;
                }

                us = null;

                foreach (UserSettings testUs in this.settingsList)
                {
                    if (testUs.SettingsName == settingsName)
                    {
                        us = testUs;
                    }
                }

                if (us == null)
                {
                    us = new UserSettings();
                    SetDefaults(us);
                    us.SettingsName = settingsName;

                    this.settingsList.Add(us);
                }

                if (us.SettingsName == curSettingsName)
                {
                    this.settings = us;
                    curSettings   = settingsNodeCount;
                }
                settingsNodeCount++;

                switch (settingsVer)
                {
                case 0:
                    #region UserSettings version 0 Loader
                    foreach (XmlNode node in settingsNode)
                    {
                        switch (node.Name)
                        {
                        case "InputWorldDirectory":
                            us.InputWorldDirectory = node.InnerXml;
                            break;

                        case "OutputPreviewDirectory":
                            us.OutputPreviewDirectory = node.InnerXml;
                            break;

                        case "IsChestFilterEnabled":
                            us.IsChestFilterEnabled = Boolean.Parse(node.InnerXml);
                            break;

                        case "IsWallsDrawable":
                            us.AreWallsDrawable = Boolean.Parse(node.InnerXml);
                            break;

                        case "OpenImageAfterDraw":
                            us.OpenImageAfterDraw = Boolean.Parse(node.InnerXml);
                            break;

                        case "ScanForNewChestItems":
                            us.ScanForNewChestItems = Boolean.Parse(node.InnerXml);
                            break;

                        case "ShowChestTypes":
                            us.ShowChestTypes = Boolean.Parse(node.InnerXml);
                            break;

                        case "UseCustomMarkers":
                            us.UseCustomMarkers = Boolean.Parse(node.InnerXml);
                            break;

                        case "ChestListSortType":
                            us.ChestListSortType = Int32.Parse(node.InnerXml);
                            break;

                        case "HighestVersion":
                            this.HighestVersion = Int32.Parse(node.InnerXml);
                            break;

                        case "SymbolStates":
                            parseNodeList = node.SelectNodes("item");

                            foreach (XmlNode n in parseNodeList)
                            {
                                String         Key;
                                Boolean        Value;
                                MarkerSettings mi;

                                parseNode = n.SelectSingleNode("key").SelectSingleNode("string");
                                Key       = parseNode.InnerXml;

                                parseNode = n.SelectSingleNode("value").SelectSingleNode("boolean");
                                Value     = Boolean.Parse(parseNode.InnerXml);

                                if (us.MarkerStates.ContainsKey(Key))
                                {
                                    us.MarkerStates[Key].Drawing = Value;
                                }
                                else
                                {
                                    String newKey = Global.Instance.Info.MarkerImageToName(Key);

                                    if (!us.MarkerStates.ContainsKey(newKey))
                                    {
                                        newKey = String.Empty;
                                    }

                                    if (newKey == String.Empty)
                                    {
                                        mi         = new MarkerSettings();
                                        mi.Drawing = Value;
                                        us.MarkerStates.Add(Key, mi);
                                    }
                                    else
                                    {
                                        us.MarkerStates[newKey].Drawing = Value;
                                    }
                                }
                            }
                            break;

                        case "ChestFilterItems":
                            parseNodeList = node.SelectNodes("item");

                            foreach (XmlNode n in parseNodeList)
                            {
                                String  Key;
                                Boolean Value;

                                parseNode = n.SelectSingleNode("key").SelectSingleNode("string");
                                Key       = parseNode.InnerXml;

                                parseNode = n.SelectSingleNode("value").SelectSingleNode("boolean");
                                Value     = Boolean.Parse(parseNode.InnerXml);

                                if (Value == true)
                                {
                                    us.ChestFilterItems.Add(Key);
                                }
                            }
                            break;

                        default:
                            break;
                        }
                    }
                    #endregion
                    break;

                case 1:
                    #region UserSettings version 1 Loader
                    foreach (XmlNode node in settingsNode)
                    {
                        parseNode = node.Attributes["name"];

                        if (parseNode == null)
                        {
                            continue;
                        }

                        switch (parseNode.Value)
                        {
                        case "InputWorldDirectory":
                            parseNode = node.Attributes["value"];

                            if (parseNode != null)
                            {
                                us.InputWorldDirectory = parseNode.Value;
                            }
                            break;

                        case "OutputPreviewDirectory":
                            parseNode = node.Attributes["value"];

                            if (parseNode != null)
                            {
                                us.OutputPreviewDirectory = parseNode.Value;
                            }
                            break;

                        case "IsChestFilterEnabled":
                            parseNode = node.Attributes["value"];

                            if (parseNode != null)
                            {
                                us.IsChestFilterEnabled = Boolean.Parse(parseNode.Value);
                            }
                            break;

                        case "AreWiresDrawable":
                            parseNode = node.Attributes["value"];

                            if (parseNode != null)
                            {
                                us.AreWiresDrawable = Boolean.Parse(parseNode.Value);
                            }
                            break;

                        case "AreWallsDrawable":
                            parseNode = node.Attributes["value"];

                            if (parseNode != null)
                            {
                                us.AreWallsDrawable = Boolean.Parse(parseNode.Value);
                            }
                            break;

                        case "OpenImageAfterDraw":
                            parseNode = node.Attributes["value"];

                            if (parseNode != null)
                            {
                                us.OpenImageAfterDraw = Boolean.Parse(parseNode.Value);
                            }
                            break;

                        case "ScanForNewChestItems":
                            parseNode = node.Attributes["value"];

                            if (parseNode != null)
                            {
                                us.ScanForNewChestItems = Boolean.Parse(parseNode.Value);
                            }
                            break;

                        case "ShowChestTypes":
                            parseNode = node.Attributes["value"];

                            if (parseNode != null)
                            {
                                us.ShowChestTypes = Boolean.Parse(parseNode.Value);
                            }
                            break;

                        case "UseCustomMarkers":
                            parseNode = node.Attributes["value"];

                            if (parseNode != null)
                            {
                                us.UseCustomMarkers = Boolean.Parse(parseNode.Value);
                            }
                            break;

                        case "ChestListSortType":
                            parseNode = node.Attributes["value"];

                            if (parseNode != null)
                            {
                                us.ChestListSortType = Int32.Parse(parseNode.Value);
                            }
                            break;

                        case "CropImageType":
                            parseNode = node.Attributes["value"];

                            if (parseNode != null)
                            {
                                us.CropImageType = Int32.Parse(parseNode.Value);
                            }
                            break;

                        case "ShowChestItems":
                            parseNode = node.Attributes["value"];

                            if (parseNode != null)
                            {
                                us.ShowChestItems = Boolean.Parse(parseNode.Value);
                            }
                            break;

                        case "ShowNormalItems":
                            parseNode = node.Attributes["value"];

                            if (parseNode != null)
                            {
                                us.ShowNormalItems = Boolean.Parse(parseNode.Value);
                            }
                            break;

                        case "ShowCustomItems":
                            parseNode = node.Attributes["value"];

                            if (parseNode != null)
                            {
                                us.ShowCustomItems = Boolean.Parse(parseNode.Value);
                            }
                            break;

                        case "MarkerStates":
                            parseNodeList = node.SelectNodes("listitem");

                            foreach (XmlNode n in parseNodeList)
                            {
                                String         Name;
                                MarkerSettings mi;

                                parseNode = n.Attributes["name"];

                                if (parseNode == null)
                                {
                                    break;
                                }

                                Name = parseNode.Value;

                                if (us.MarkerStates.TryGetValue(Name, out mi) == false)
                                {
                                    mi = new MarkerSettings();
                                }

                                parseNode = n.Attributes["draw"];

                                if (parseNode != null)
                                {
                                    mi.Drawing = Boolean.Parse(parseNode.Value);
                                }

                                parseNode = n.Attributes["filter"];

                                if (parseNode != null)
                                {
                                    mi.Filtering = Boolean.Parse(parseNode.Value);
                                }

                                parseNode = n.Attributes["min"];

                                if (parseNode != null)
                                {
                                    mi.Min = Int32.Parse(parseNode.Value);
                                }

                                parseNode = n.Attributes["max"];

                                if (parseNode != null)
                                {
                                    mi.Max = Int32.Parse(parseNode.Value);
                                }

                                if (!us.MarkerStates.ContainsKey(Name))
                                {
                                    us.MarkerStates.Add(Name, mi);
                                }
                            }
                            break;

                        case "ChestFilterItems":
                            parseNode = node.Attributes["filter"];

                            if (parseNode == null)
                            {
                                continue;
                            }

                            String[] splitList = parseNode.Value.Split(';');

                            foreach (String s in splitList)
                            {
                                us.ChestFilterItems.Add(s);
                            }
                            break;

                        default:
                            break;
                        }
                    }
                    #endregion
                    break;

                default:
                    return;
                }
            }

            parseNode = baseNode.SelectSingleNode("CustomItems");

            if (parseNode != null)
            {
                parseNode = parseNode.Attributes["list"];

                if (parseNode != null)
                {
                    String[] itemList = parseNode.Value.Split(';');

                    foreach (String s in itemList)
                    {
                        if (!Global.Instance.Info.Items.ContainsKey(s))
                        {
                            Global.Instance.Info.AddCustomItem(s);
                        }
                    }
                }
            }

            parseNode = baseNode.SelectSingleNode("CustomColors");

            if (parseNode != null)
            {
                parseNode = parseNode.Attributes["list"];

                if (parseNode != null)
                {
                    String[] colorList = parseNode.Value.Split(';');
                    Color    newColor;

                    for (Int32 sPos = 0; sPos < colorList.Length; sPos += 2)
                    {
                        if (Global.TryParseColor(colorList[sPos + 1], out newColor) == false)
                        {
                            continue;
                        }

                        if (Global.Instance.Info.Colors.ContainsKey(colorList[sPos]))
                        {
                            continue;
                        }


                        Global.Instance.Info.AddCustomColor(colorList[sPos], newColor);
                    }
                }
            }
        }
 /// <summary>
 /// Constructor. Instanciates the <see cref="UserSettings"/>.
 /// </summary>
 public UserSettingsWieldingForm()
     : base()
 {
     Settings         = new UserSettings();
     this.FormClosed += UserSettingsWieldingForm_FormClosed;
 }