// QUESTION/COMMENT - If part of what you're concerned about is code readability for new programmers coming on, then I think // SetDefaultPrinter() could use a better name. Usually when you have a method that's called something like SetX, you're able to pass a // value that X will take on. This method doesn't give the user any ability to say what the default printer should be. // Instead it discovers the configured default printer, if there is one, and otherwise tries to set the first valid Zebra printer // in its list as the default. // GetDefaultPrinter() isn't a great name either since if there isn't a default printer configured, the code tries to set one // in the printer repository, which seems like it is an external data source where that change will live on past this class instance. // A lot of people would not expect a Get method to have any data side-effects. // RetrieveOrImplicitlySetDefaultPrinter() is a clunky name but it is accurate. // Sets this instance to use the printer configured in the repository as the default. If no default is found, // it sets the first Zebra-named printer in the list of installed printers as the default printer in the repository // and then uses that printer. private void SetDefaultPrinter() { // Get the name of the default printer, if one has been configured, from the printer database repositorty. // Question - could SettingsRepository.Get() return a null? String printer = SettingsRepository.Get("DefaultPrinter"); // If there is a default printer name and it's a valid name, then set it as the default printer // and get out. Otherwise, keep going. if (printer != "" && this.Validate(printer)) { this.defaultPrinter = printer; return; } // If we got this far, there was no default printer configured, so we're going to set one. // Loop through all the installed printers. If you find one whose name contains "zebra" // and whose name is also generally valid, set that as the default printer for this class // instance and then save it to the printer settings repository as the default printer. // Zebra printers are (presumably) our stock printer brand. // If there is no printer with a valid name that contains the string "zebra," then we will not // configure any default printer. // Should that be an exception? There's no way in this class to specify a printer to use and the Print() // method presumes that you do have a default printer configured. If there's no default configured // and the class can't find one using the logic below, the class instance will essentially be broken. foreach (String printerName in this.GetInstalledPrinters()) { if (printerName.ToLower().Contains("zebra") && this.Validate(printerName)) { this.defaultPrinter = printerName; SettingsRepository.Save("DefaultPrinter", this.defaultPrinter); break; } } }
private void OnFocusedWindowTitleChanged(object sender, FocusedWindowTitleChangedEventArgs e) { if (_settingsRepository.Get().DebugMode) { _logger.Write(LogLevel.Debug, $"[FocusedWindowChange][Old] {e.OldFocusedWindow?.Title} [{e.OldFocusedWindow?.ProcessId}] [{e.OldFocusedWindow?.ThreadId}]"); _logger.Write(LogLevel.Debug, $"[FocusedWindowChange][New] {e.NewFocusedWindow?.Title} [{e.NewFocusedWindow?.ProcessId}] [{e.NewFocusedWindow?.ThreadId}]"); } }
public async Task <string> GetLastUpdated(string siteId, string resourceName) { var settings = await _settingsRepository.Get(siteId, resourceName); var date = settings?.LastUpdated; return(date?.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'") ?? string.Empty); }
public void Distribute() { activeRequests = requestRepository.GetAll().Where(r => !r.IsComplete); workers = workerRepository.GetAll(); activeSettings = settingsRepository.Get(0); void CheckTakenRequests() { foreach (var request in TakenRequest) { if (DateTime.Now.Ticks >= request.ExecutedDate) { request.IsComplete = true; var worker = workers.SingleOrDefault(x => x.WorkingRequestId == request.Id); worker.WorkingRequestId = null; SaveChanges(request, worker); Debug.WriteLine($"{worker.Name} закончил с запросом {request.Id}!"); } } } void DistributeForFreeWorkers() { foreach (var worker in FreeWorkers) { var request = NotTakenRequest.FirstOrDefault(); if (request is null) { break; } if (!worker.CheckRequest(request, activeSettings)) { continue; } else { Debug.WriteLine($"Запрос {request.Id} подходит {worker.Name}!"); Random random = new Random(); request.TakenDate = DateTime.Now.Ticks; request.Executor = $"{worker.Position} {worker.Name}"; request.ExecutedDate = DateTime.Now.AddSeconds(random.Next(activeSettings.ExecuteTimeLimitLeft, activeSettings.ExecuteTimeLimitRight)).Ticks; worker.WorkingRequestId = request.Id; SaveChanges(request, worker); } } } CheckTakenRequests(); DistributeForFreeWorkers(); Debug.WriteLine($"Запросов в очереди: {NotTakenRequest.Count()}"); if (FreeWorkers.Count() == 0) { Debug.WriteLine($"Нет свободных сотрудников!"); } }
public GCSPropertiesController() { SettingsRepository = new SettingsRepository(); InstancesRepository = new InstancesRepository(); settings = SettingsRepository.Get(); //if (settings == null) { // settings = SettingsRepository.Initiate(); // InstancesRepository.CreateWithSettingsId(settings.Id); //} }
public void Get_FiltersByUserId() { var userId = _settingsData.First().UserId; _userHelperMock.SetupGet(p => p.UserId).Returns(userId); List <SettingEntity> expectedResult = _settingsData.Where(s => s.UserId == userId).ToList(); List <SettingEntity> actualResult = _settingsRepository.Get().ToList(); Assert.That(actualResult, Is.EquivalentTo(expectedResult)); }
public async Task UpdateSchema(CancellationToken cancellationToken) { int currentDbSchemaVersion = await _settingsRepository.Get <int>(SchemaVersionSetting, cancellationToken); _logger.LogInformation(LoggingEvents.UpdateDatabaseSchema, "Current DB schema is at version {schemaVersion}", currentDbSchemaVersion); if (currentDbSchemaVersion < 1) { _logger.LogInformation(LoggingEvents.UpdateDatabaseSchema, "Updating DB schema from version {currentSchemaVersion} to {newSchemaVersion}", currentDbSchemaVersion, 1); await Task.WhenAll(_schemaUpdaters.Select(x => x.Update(currentDbSchemaVersion, cancellationToken))); await _settingsRepository.Set(SchemaVersionSetting, 1); } _logger.LogInformation(LoggingEvents.UpdateDatabaseSchema, "Current DB schema is at version {schemaVersion}", 1); }
static void QuerySettings() { SettingsRepository settingsRepository = new SettingsRepository(connectionString, "settings"); var s = settingsRepository.Get(1); if (s == null) { settingsRepository.Create(new Setting() { SettingKey = "AesIV", SettingValue = "::\"bla'+" }); } s = settingsRepository.GetByKey("AesIV"); s.SettingValue += "upd."; settingsRepository.Update(s); }
private void SetDefaultPrinter() { String printer = SettingsRepository.Get("DefaultPrinter"); if (printer != "" && this.Validate(printer)) { this.defaultPrinter = printer; return; } foreach (String printerName in this.GetInstalledPrinters()) { if (printerName.ToLower().Contains("zebra") && this.Validate(printerName)) { this.defaultPrinter = printerName; SettingsRepository.Save("DefaultPrinter", this.defaultPrinter); break; } } }
public SettingsPageViewModel() { LoadSettingsCommand = new Command(async() => { var settings = await _repo.Get(); if (settings != null) { this.Settings.Id = settings.Id; MasterTemplateFile = settings.MasterTemplateFile; ProofingFolder = settings.ProofingFolder; WorkingCalendarFolder = settings.WorkingCalendarFolder; APIKey = settings.APIKey; APIUrl = settings.APIUrl; SecretKey = settings.SecretKey; ProoferInitials = settings.ProoferInitials; } }); SaveSettingsCommand = new Command(async() => { this.Settings.LastModifiedDate = DateTime.Now; await _repo.Save(this.Settings); }); }
public async Task <DTOSettings> GetSettings(int id) { Settings settings = await _settingsRepository.Get(id); return(_mapper.Map <DTOSettings>(settings)); }
public JsonResult Get(SearchRequest model) { SearchSettings settings = SettingsRepository.Get(); SearchResponse SearchResponse = new SearchResponse(); RootObject obj = new RootObject(); bool retry = false; String FormattedQuery = model.Query; String DevelopmentURL = settings.DevelopmentURL; JsonResult json = new JsonResult(); if (ValidateSettings(settings)) { //https://stackoverflow.com/questions/30611114/google-custom-search-engine-result-counts-changing-as-results-are-paged do { retry = false; IPublishedContent currentNode = UmbracoContext.ContentCache.GetById(model.CurrentNodeID); IPublishedContent rootNode = uh.ContentAtRoot().FirstOrDefault(t => t.GetCulture().Culture == NodeService.GetCurrentCulture(currentNode).Culture); if (rootNode == null) { rootNode = currentNode.AncestorsOrSelf(2).FirstOrDefault(); } if (!String.IsNullOrEmpty(model.Section)) { IPublishedContent node = rootNode.Descendant(model.Section); if (node != null) { FormattedQuery = String.Format("{0} site:{1}", model.Query, !String.IsNullOrEmpty(DevelopmentURL) ? Regex.Replace(node.UrlAbsolute(), @"http.*:\/\/" + HttpContext.Request.Url.DnsSafeHost, DevelopmentURL) : node.UrlAbsolute()); } } else { FormattedQuery = String.Format("{0} site:{1}", model.Query, !String.IsNullOrEmpty(DevelopmentURL) ? DevelopmentURL : rootNode.UrlAbsolute()); } if (!String.IsNullOrEmpty(model.FileType)) { FormattedQuery = String.Format("{0} filetype:{1}", FormattedQuery, model.FileType); } string URL = string.Format("{0}?filter=1&key={1}&cx={2}&q={3}&start={4}&num={5}&prettyPrint=false", settings.BaseURL, settings.APIKey, settings.CXKey, FormattedQuery, model.StartIndex, settings.ItemsPerPage); if (settings.DateRestrict != null && settings.DateRestrict.Value != null && String.IsNullOrEmpty(model.FileType)) { URL += String.Format("&dateRestrict=d{0}", Math.Abs((DateTime.Now - settings.DateRestrict.Value).Days)); } SearchResponse = SearchRequest(URL); obj = JsonConvert.DeserializeObject <RootObject>(SearchResponse.Response); if (obj != null) { retry = int.Parse(obj.searchInformation.totalResults) == 0 && model.StartIndex > 0 ? !retry : retry; model.StartIndex = retry ? model.StartIndex - settings.ItemsPerPage : model.StartIndex; } } while (int.Parse(obj.searchInformation.totalResults) == 0 && model.StartIndex > 1 && retry); if (settings != null && obj != null && obj.items != null && !String.IsNullOrEmpty(settings.ExcludeNodeIds)) { List <String> urls = NodeService.GetAbsoluteURLByUdi(settings.ExcludeNodeIds); if (urls != null) { foreach (var url in urls) { String _url = url; if (!String.IsNullOrEmpty(DevelopmentURL)) { _url = Regex.Replace(_url, @"http.*:\/\/" + HttpContext.Request.Url.DnsSafeHost, DevelopmentURL); } Item item = obj.items.FirstOrDefault(i => i.link == _url); if (item != null) { obj.items.Remove(item); } } } } String TopResultURL = obj.items != null && obj.items.Count > 0 && obj.items.First() != null?obj.items.First().formattedUrl : ""; if (obj.spelling != null && !String.IsNullOrEmpty(obj.spelling.correctedQuery)) { obj.spelling.correctedQuery = obj.spelling.correctedQuery.Replace(String.Format("site:{0}", DevelopmentURL), ""); } SearchEntry SearchEntry = QueriesRepository.Create(new SearchEntry() { Query = model.Query, Date = DateTime.Now, TotalCount = int.Parse(obj.searchInformation.totalResults), Timing = double.Parse(obj.searchInformation.formattedSearchTime), TopResultURL = TopResultURL, CorrectedQuery = obj.spelling != null ? obj.spelling.correctedQuery : "" }); json = new JsonResult() { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = new { success = SearchResponse.Success, list = RenderViewService.GetRazorViewAsString(obj, "~/App_Plugins/W3S_GCS/Views/Partials/SearchResults.cshtml"), spelling = settings.ShowSpelling && obj.spelling != null && !String.IsNullOrEmpty(obj.spelling.correctedQuery) ? RenderViewService.GetRazorViewAsString(new SpellingModel() { CorrectedQuery = obj.spelling.correctedQuery, SearchURL = settings.RedirectNodeURL }, "~/App_Plugins/W3S_GCS/Views/Partials/SearchSpelling.cshtml") : "", totalCount = obj.searchInformation.totalResults, timing = obj.searchInformation.formattedSearchTime, totalPages = Math.Ceiling((double)int.Parse(obj.searchInformation.totalResults) / int.Parse(settings.ItemsPerPage.ToString())), pagination = settings.LoadMoreSetUp == "pagination" ? RenderViewService.GetRazorViewAsString(PaginationService.GetPaginationModel(Request, obj, settings.ItemsPerPage, model.StartIndex, model.Query, model.FileType, model.Section, settings.MaxPaginationPages), "~/App_Plugins/W3S_GCS/Views/Partials/SearchPagination.cshtml") : "", filetypefilter = settings.ShowFilterFileType ? RenderViewService.GetRazorViewAsString(new FileTypeFilter(), "~/App_Plugins/W3S_GCS/Views/Partials/SearchFileTypeFilterSelect.cshtml") : "", queryId = SearchEntry.Id } }; } return(json); }
public T Get <T>(string key) { return(_settingsRepository.Get <T>(key)); }
private void CreateVisionProcess(ref SettingsRepository.SettingsRepository setRepo) { colorVideoSource = new ColorVideoSource(); colorVideoSource.ResultReady += DisplayVideo; Hsv min = new Hsv((int)setRepo.Get("min-h") , (int)setRepo.Get("min-s") , (int)setRepo.Get("min-v")), max = new Hsv((int)setRepo.Get("max-h") , (int)setRepo.Get("max-s") , (int)setRepo.Get("max-v")); filter = new HsvFilter(colorVideoSource, min, max); roadDetector = new RoadCenterDetector(filter); // roadDetector.Perceptor.perspectiveTransform.ResultReady += DisplayVideo; visRoad = new VisualiseSimpleRoadModel(roadDetector.Perceptor.roadDetector); invPerp = new PerspectiveCorrectionRgb(visRoad, CamModel.dstPerspective, CamModel.srcPerspective); brain = new FollowTheRoadBrainCentre(roadDetector, carController); brain.evNewTargetWheelAngeCalculated += new FollowTheRoadBrainCentre.newTargetWheelAngeCalculatedEventHandler(brain_evNewTargetWheelAngeCalculated); brain.evNewTargetSpeedCalculated += new FollowTheRoadBrainCentre.newTargetSpeedCalculatedEventHandler(brain_evNewTargetSpeedCalculated); roadDetector.Perceptor.laneDetector.Tau = (int) setRepo.Get("tau"); roadDetector.Perceptor.laneDetector.Threshold = (byte)((int)setRepo.Get("threshold")); roadDetector.Perceptor.laneDetector.VerticalOffset = (int) setRepo.Get("v-offset"); visRoad.ResultReady += DisplayVideo; invPerp.ResultReady += DisplayVideo; colorVideoSource.Start(); }
public async Task <Settings> Get() { return(await _settingsService.Get()); }
public JsonResult Get(SearchSettings model) { IPublishedContent currentNode = null; SearchSettings SearchSettings = SettingsRepository.Get(); if (DomainService == null) { DomainService = Services.DomainService; } if (Domains == null) { Domains = DomainService.GetAll(true).ToList(); } var currentDomain = NodeService.GetCurrentDomain(Domains, model.CurrentURL); if (currentDomain != null) { currentNode = UmbracoContext.ContentCache.GetById(currentDomain.RootContentId.Value); SearchSettings.RedirectNodeURL = NodeService.GetRedirectNodeURL(currentNode, SearchSettings.RedirectAlias); } else { IPublishedContent rootNode = UmbracoContext.ContentCache.GetAtRoot().FirstOrDefault(); IPublishedContent searchPage = rootNode.DescendantOrSelf(SearchSettings.RedirectAlias); if (searchPage != null) { currentNode = rootNode; SearchSettings.RedirectNodeURL = searchPage.Url; } } JsonResult json = new JsonResult() { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = new { id = SearchSettings.Id, baseUrl = SearchSettings.BaseURL, //cxKey = SearchSettings.CXKey, //apiKey = SearchSettings.APIKey, itemsPerPage = SearchSettings.ItemsPerPage, redirectPath = !String.IsNullOrEmpty(SearchSettings.RedirectNodeURL) ? SearchSettings.RedirectNodeURL : "", excludeUrls = !String.IsNullOrEmpty(SearchSettings.ExcludeNodeIds) ? String.Join(",", NodeService.GetPathsByUdi(SearchSettings.ExcludeNodeIds)) : "", loadMoreSetUp = SearchSettings.LoadMoreSetUp, maxPaginationPages = SearchSettings.MaxPaginationPages, showQuery = SearchSettings.ShowQuery, showTotalCount = SearchSettings.ShowTotalCount, showTiming = SearchSettings.ShowTiming, showSpelling = SearchSettings.ShowSpelling, excludeNodeIds = SearchSettings.ExcludeNodeIds, showFilterFileType = SearchSettings.ShowFilterFileType, showThumbnail = SearchSettings.ShowThumbnail, thumbnailFallback = !String.IsNullOrEmpty(SearchSettings.ThumbnailFallbackGUID) ? NodeService.GetMediaPathByUdi(SearchSettings.ThumbnailFallbackGUID) : "", preloaderIcon = !String.IsNullOrEmpty(SearchSettings.LoadIconGUID) ? NodeService.GetMediaPathByUdi(SearchSettings.LoadIconGUID) : "", developmentURL = SearchSettings.DevelopmentURL, currentNodeId = currentNode.Id, keepquery = SearchSettings.KeepQuery } }; return(json); }
public GamepadButtonAction GetButtonMapping(ButtonNames button) => _settingsRepository.Get() .GetActionForButton(button);