/// <summary> /// Lookups for files in current directory using search options and writes them using logger method "Message" /// </summary> /// <param name="fileNamePatterns">Collection of file search patterns in format *.*</param> /// <param name="recursievly">Flag that controls the search in subfolders</param> /// <param name="regularExpression">Regular expression that should be matched in file. If you use this option, then /// search string parameter must be null or empty</param> /// <param name="searchString">Substring that should be found in file. If you use this option, then /// regular expression parameter must be null or empty</param> /// <param name="sortPatterns">Patterns that controls order of output results</param> /// <param name="token">Cancellation token</param> public void FindFiles(IEnumerable <string> fileNamePatterns, bool recursievly, string regularExpression, string searchString, IEnumerable <SortPattern> sortPatterns, CancellationToken token) { if (!String.IsNullOrWhiteSpace(regularExpression) && !String.IsNullOrWhiteSpace(searchString)) { throw new ArgumentException("Cannot use both search options: regular expression and search string"); } _logger.Message( $"\nПоиск во вложенных папках: {recursievly}\n" + $"Регулярное выражение: {regularExpression}\n" + $"Текст поиска: {searchString}\n" + $"Шаблоны имени фала: {String.Join(" | ", fileNamePatterns)}\n" + $"Шаблоны сортировки: {String.Join(" | ", sortPatterns.Select(sp => (sp.Type.ToString() + " - По убыванию: " + sp.IsDescending)))}"); var files = GetFilesFromCurrentDirectory(fileNamePatterns, recursievly); var filteredFiles = FilterFilesByContetns(files, regularExpression, searchString, token); filteredFiles = SortFiles(filteredFiles, sortPatterns); LogFileNames(filteredFiles); // Вывод количества обработанных файлов, после того, как получена отмена операции. _logger.Message($"Всего найдено файлов: {files.Count()}. Из них соответствуют критериям поиска {filteredFiles.Count()}"); }
public static void RunSimple() { StateBase initialState = new StateA() { A = 1 }; IReadOnlyCollection <ITaskBase <StateBase, StateBase> > tasks = new ITaskBase <StateBase, StateBase>[] { new DeterministicTask(), new DryTask(), new GenericInputTask() }; Logger.Message($"InitialState: {initialState}"); var terminationState = SimpleExecutor.Run(initialState, tasks); Logger.Message($"FinalState: {terminationState}"); initialState = new StateA() { A = 2 }; Logger.Message($"InitialState: {initialState}"); terminationState = SimpleExecutor.Run(initialState, tasks); Logger.Message($"FinalState: {terminationState}"); }
public void RegisterModule(ISamplesModule samplesModule) { samplesModule.ThrowIfNull(nameof(samplesModule)); _samplesModules.Add(samplesModule); Logger.Message($"Sample module '{samplesModule.ModuleName}' was registered to run."); }
private async void AddUser() { ErrorMsgVisibility = Visibility.Collapsed; if (!CheckAllInputFields()) { return; } var _searchedCustomer = CustomerCollection.FirstOrDefault(s => s.CustomerName == CustomerName); // Check if there is already a book with same name and same authorname if (_searchedCustomer != null && _searchedCustomer.PhoneNo == PhoneNo) { ErrorMsg = Properties.Resources.UserAlreadyExistMsg; ErrorMsgVisibility = Visibility.Visible; return; } CustomerModel customer = new CustomerModel() { CustomerId = DateTime.Now.ToString().GetHashCode().ToString("x"), CustomerName = this.CustomerName, Address = this.Address, PhoneNo = this.PhoneNo }; _log.Message("Adding New User having UserId :" + customer.CustomerId); await _customerDataAccess.InsertData(customer, Properties.Resources.AddUser); GetAllCustomer(); ClearAllField(); InvokeCustomerUpdateEvent(); }
private async void LoginValidation(object parameter) { try { ErrorMsgVisibility = Visibility.Hidden; var win = parameter as Window; await AuthenticateUser(); if (AdminList.Count == 0) { ErrorMsg = Properties.Resources.AuthenticationFailedMsg; ErrorMsgVisibility = Visibility.Visible; } else { MainWindowView _mainWindow = new MainWindowView(_log); _mainWindow.Show(); if (win != null) { win.Close(); } _log.Message("User Authenticated"); } } catch (System.Data.SqlClient.SqlException ex) { _log.Error(ex); _log.Message("Unable to connect to database"); ErrorMsg = Properties.Resources.DatabaseConnFailedMsg; ErrorMsgVisibility = Visibility.Visible; } }
public static bool ConvertDirectionEnumToTextValue(Direction directionToConvert, out string enumTxt) { enumTxt = null; if (!Enum.IsDefined(typeof(Direction), directionToConvert)) { _log.Message(LogLevel.Error, ($"{DirectionConverterException}: Value: {directionToConvert}")); return(false); } switch (directionToConvert) { case Direction.N: enumTxt = "North"; return(true); case Direction.E: enumTxt = "East"; return(true); case Direction.S: enumTxt = "South"; return(true); case Direction.W: enumTxt = "West"; return(true); case Direction.NE: enumTxt = "Northeast"; return(true); case Direction.SE: enumTxt = "Southeast"; return(true); case Direction.SW: enumTxt = "Southwest"; return(true); case Direction.NW: enumTxt = "Northwest"; return(true); default: _log.Message(LogLevel.Error, ($"{DirectionConverterException}: Value: {directionToConvert}")); return(false); } }
public void StartServer(CancellationToken cancellationToken) { try { clientManager = clientManagerProvider.GetClientManager(cancellationToken); } catch (MeepoException) { return; } logger.Message("Server is running..."); try { Task.Factory.StartNew(() => clientManager.Listen(), cancellationToken); } catch (OperationCanceledException) { logger.Message("Server has stopped"); } catch (Exception ex) { logger.Error("Unknown server error", ex); } }
public void Clear() { Logger.Message($"Clearing {_rollbackActions.Count.ToString()} rollback actions."); _rollbackActions.Clear(); _rollbackActions.TrimExcess(); }
private static int Run(Options options, ILogger logger) { // Initialize basic command options. //Parser.Default.ParseArguments<Options>(args) // .WithParsed(options => // { try { var(workingFolder, intermediateFolder, generatedCodeFolder, compilingFiles) = DeconstructPaths(options); var rebuildRequired = options.RebuildRequired; var cachedExcludesListFile = Path.Combine(intermediateFolder, "Excludes.txt"); // 如果可以差量编译,那么检测之前已经生成的文件,然后将其直接输出。 if (!rebuildRequired && File.Exists(cachedExcludesListFile)) { var cachedExcludeLines = File.ReadAllLines(cachedExcludesListFile, Encoding.UTF8); foreach (var exclude in cachedExcludeLines) { logger.Message(exclude); } return(0); } var assembly = new CompileAssembly(compilingFiles); // 分析 IPlainCodeTransformer。 var transformer = new CodeTransformer(workingFolder, generatedCodeFolder, assembly); var excludes = transformer.Transform(); // 分析 CompileTimeTemplate。 var templateTransformer = new TemplateTransformer(workingFolder, generatedCodeFolder, assembly); var templateExcludes = templateTransformer.Transform(); var toExcludes = excludes.Union(templateExcludes) .Select(x => PathEx.MakeRelativePath(workingFolder, x)).ToArray(); foreach (var exclude in toExcludes) { logger.Message(exclude); } File.WriteAllLines(cachedExcludesListFile, toExcludes, Encoding.UTF8); } catch (CompilingException ex) { foreach (var error in ex.Errors) { logger.Error($"error:{error}"); } } catch (Exception ex) { logger.Error($"error:{ex}"); } //}) //.WithNotParsed(errorList => { }); return(0); }
private List <ProjectInfo> TryGetProjectsInfo(string filePath) { var solutionInfos = new List <ProjectInfo>(); try { var solution = SolutionParser.Parse(filePath); var solutionDirectory = Path.GetDirectoryName(filePath); if (solutionDirectory == null) { _logger.Message($"Solution directory wasn't found for file {filePath}"); return(solutionInfos); } foreach (var project in solution.Projects) { if (project.TypeGuid == ProjectTypeGuids.SolutionFolder) { continue; } var projectFilePath = Path.Combine(solutionDirectory, project.Path); var projectDirectory = Path.GetDirectoryName(projectFilePath); if (projectDirectory == null) { _logger.Message($"Project directory wasn't found for project {project.Name}"); return(solutionInfos); } var packageConfigPath = Path.Combine(projectDirectory, "packages.config"); if (File.Exists(packageConfigPath)) { var packages = _projectParser.ParsePackageConfig(packageConfigPath); solutionInfos.Add(new ProjectInfo(project.Name, packages)); } else if (File.Exists(projectFilePath)) { var packages = _projectParser.ParseProjectFile(projectFilePath); solutionInfos.Add(new ProjectInfo(project.Name, packages)); } else { _logger.Message($"Unable to find project or package.config file for project {project.Path}"); } } return(solutionInfos); } catch (Exception e) { _logger.Message($"Unable to get project info for {filePath}\r\n {e}"); } return(solutionInfos); }
private void ValidateSetupValue(int value) { if (GeneralValidationHelper.IsIntegerValueNegative(value)) { _log.Message(LogLevel.Warn, RobotConstantsValues.MatrixSetupFailureBackToDefault); // no need to throw exception. Mission will fail PreDefaultMatrix(); } }
public int Execute(int parameter) { if (parameter != 1) { throw new ArgumentException($"Expected 1 argument, got {parameter.ToString()}.", nameof(parameter)); } Logger.Message("Action two done."); return(2); }
public void AddJob(int jobId, string data, TimeSpan ts) { logger.Message(data); Job j = new Job(jobId); j.Data = data; j.Time = timeService.Now + ts; jobs.Add(jobId, j); }
public Startup(IFileManager fileManager, ILogger logger) { _fileManager = fileManager; _logger = logger; _logger.Message("Reddit Retweeter v0.5"); _logger.Message("Pulls Reddit posts then Tweets them on interval"); _logger.Message("Only supports text and images\n"); GetUserInput(); Initialize(); }
private ModuleDefinition?ResolveAssemblyNameReference(DefaultAssemblyResolver resolver, AssemblyNameReference assembly) { try { return(resolver.Resolve(assembly).MainModule); } catch (Exception ex) { _logger.Message(ex.Message); return(null); } }
public override WorkLog DoWork(WorkItem workItem) { Logger.Message("Reserving car"); Object car = workItem.Arguments["vehicleType"]; int reservationId = Rnd.Next(100000); Logger.Message($"Reserved car {reservationId.ToString()}."); return(new WorkLog(this, new WorkResult { { "reservationId", reservationId } })); }
public override WorkLog DoWork(WorkItem workItem) { Logger.Message("Reserving flight"); object car = workItem.Arguments["fatzbatz"]; // this throws int reservationId = Rnd.Next(100000); Logger.Message($"Reserved flight {reservationId.ToString()}."); return(new WorkLog(this, new WorkResult { { "reservationId", reservationId } })); }
private void RunSafe(string sampleId, Action sample) { try { Logger.Message($"Run sample '{sampleId}'."); sample(); Logger.Message($"Sample '{sampleId}' was finished successfully.{Environment.NewLine}"); } catch (Exception ex) { Logger.Exception(ex, $"Failed to run sample '{sampleId}'. Skipping it."); Logger.Message($"Sample '{sampleId}' was finished with failures.{Environment.NewLine}"); } }
public NightlyFrogBoiling(IConfiguration config, ILogger logger) { _logger = logger; _operativeAmount = double.Parse(config.GetValue("operative_amount")); _logger.Message("Nightly Frog Boiling trader initialized with operative amount " + _operativeAmount + " BTC"); _requestor = new BtcChinaApi(config, logger); }
public void Create(Order order) { User user = this.userProvider.GetById(order.CreateUserId); order.CreateUserName = user.Name; logger.Message(string.Format("order created : {0}", order)); }
public bool TryRollbackSafe(int rollbackParameter) { Logger.Message( $"Rollback action two with parameter: '{rollbackParameter.ToString()}'." ); return(true); }
public NaiveBear(IConfiguration config, ILogger logger) { _logger = logger; _logger.Message("Naive Bear trader initialized with operative share " + OPERATIVE_AMOUNT + " BTC"); _requestor = new BtcChinaApi(config, logger); _trend = new MarketTrend(); }
public void Dispose() { try { if (_stopWatch == null) { return; } _stopWatch.Stop(); var elapsedTime = String.Empty; switch (_measure) { case CounterMeasureType.Sec: elapsedTime = $"{_stopWatch.Elapsed.Seconds} sec."; break; case CounterMeasureType.MilliSec: elapsedTime = $"{_stopWatch.ElapsedMilliseconds} millisec."; break; case CounterMeasureType.Ticks: elapsedTime = $"{_stopWatch.ElapsedTicks} ticks."; break; default: throw new ArgumentOutOfRangeException(); } _logger.Message($"{_type}[{_description}]:{elapsedTime}"); } catch (Exception) { } }
public NaiveBull(IConfiguration config, ILogger logger) { _logger = logger; _logger.Message("Naive Bull trader initialized with operative amount " + OPERATIVE_AMOUNT + " BTC"); _requestor = new HuobiApi(config, logger); _trend = new MarketTrend(); }
/// <summary> /// Handles VendingMachine purchase. /// <para/> /// <br>throws ArgumentException if count is less than 1</br> /// <br>throws PurchaseFailedException if purchase fails otherwise</br> /// </summary> /// <param name="buyerId">Buyer that have triggered the purchase</param> /// <param name="itemId">ItemId that the buyer tries to buy</param> /// <param name="count">Count of the item user wants to buy</param> public void PurchaseItem(string buyerId, string itemId, int count) { logger.Debug($"Try Purchase: {count} items[{itemId}] from VendingMachine[{GetHashCode()}] to buyer: {buyerId}"); if (count <= 0) { error(new ArgumentException($"You are trying to purchase {count} items, you have to buy atleast 1 item.")); } else if (!TryGetItemStockInfo(itemId, out var itemInfo)) { error(new PurchaseFailedException("Item does not exist in catalogue")); } else if (itemInfo.count < count) { error(new PurchaseFailedException("Vending machine doesn't have enough items to buy.")); } else if (!consumePurchaseProsessor.ConsumePurchase(buyerId, itemInfo.price * count)) { error(new PurchaseFailedException("Failed to consume purchase")); } RemoveItems(itemId, count); receiveItemProsessor.ReceiveItems(buyerId, itemId, count); logger.Message($"Purchase completed: {count} items[{itemId}] was purchased from VendingMachine[{GetHashCode()}] and added to buyer: {buyerId}"); }
public Task <StringWrapper> Echo2Async(string value) { _logger?.Message(string.Join("\n", _httpContextAccessor.HttpContext.User.Claims.Select(c => $"{c.Type} - {c.Value}"))); return(Task.FromResult(new StringWrapper { Value = value, User = _httpContextAccessor.HttpContext.User.FindFirst(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn")?.Value })); }
/// <summary> /// Stop timer and write stats to <see cref="ILogger"/>. /// </summary> /// <param name="header"> Header to prepand to output message. </param> public void Stop(string header) { _stopwatch.Stop(); long elapsed = _stopwatch.ElapsedMilliseconds; _logger?.Message(header + " time elapsed: " + elapsed + "ms"); }
public ParseRes Parse(string inputPath, string outputPath, bool watch, string dir = null) { var rootPath = dir ?? new FileInfo(inputPath).Directory?.FullName ?? string.Empty; var watchList = new List <string> { inputPath }; var watchers = new List <FileSystemWatcher>(); inputPath = Path.Combine(rootPath, inputPath); outputPath = Path.Combine(rootPath, outputPath); var parseRes = ParseFile(); watchList.AddRange(parseRes.InsertedFiles); if (watch) { foreach (var inputFile in watchList) { var watcher = new FileSystemWatcher { Path = rootPath, NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.CreationTime, Filter = Path.GetFileName(inputFile), }; // Add event handlers. watcher.Changed += (sender, eventArgs) => { ParseFile(); }; watcher.Renamed += (sender, eventArgs) => { ParseFile(); }; // Begin watching. watcher.EnableRaisingEvents = true; watchers.Add(watcher); logger.Message($"watching changes for {inputFile}"); } } return(new ParseRes { Watchers = watchers, Errors = parseRes.Errors }); OssParseResult ParseFile() { // read input file var str = fileOp.ReadText(inputPath); var res = ParseOssString(str, rootPath); fileOp.WriteText(outputPath, res.ParseRes); Console.WriteLine("parsed to {0} at {1}", outputPath, DateTime.Now); return(res); } }
private void StartListening() { var thread = new Thread(Listen); logger.Message(IsToServer ? $"Connection accepted from {Address.IPAddress}:{Address.Port}" : "Connection accepted"); thread.Start(); }
public bool OsInitialization() { try { _robotConfig = _robotSettings.GetEnviromentSettings(); if (_robotConfig == null || _robotConfig.MatrixSize == null || _robotConfig.Position == null) { _log.Message(LogLevel.Warn, "Default settings will be applied, Config Settings read error"); _robotConfig = RobotConstantsValues.RobotDefaultCongifs; } Console.WriteLine($"Robot {_robotConfig.Name} settings read finish!"); Console.WriteLine($"Start position :---> [{ _robotConfig.Position.X}:{ _robotConfig.Position.Y}:{ _robotConfig.Position.Direction}]"); Console.WriteLine($"Matrix settings :---> [{ _robotConfig.MatrixSize.Max_X_Value}:{ _robotConfig.MatrixSize.Max_Y_Value}]"); RobotCommand command = new RobotCommand { QueueId = 0, Type = RobotCommandType.Initialization, CurentDirection = _robotConfig.Position.Direction, MoveTo = new Position { X = _robotConfig.Position.X, Y = _robotConfig.Position.Y, } }; var cmdResult = _robotStateMachine.Build(RobotCommandType.Initialization).ProcessState(command, _robotConfig.MatrixSize); if (cmdResult.isSuccess && cmdResult.stateResponse != null && cmdResult.stateResponse.CurrentPosition != null) { _currentPosition = cmdResult.stateResponse.CurrentPosition; } _log.Message(LogLevel.Info, cmdResult.isSuccess ? $"{RobotCommandType.Initialization} Success" : $"{RobotCommandType.Initialization} Failure"); return(cmdResult.isSuccess); } catch (Exception ex) { Console.WriteLine(RobotConstantsValues.CriticalErrorOccuredMissionWillNotContinue); _log.Exception(ex); return(false); } }
private async void CheckInBook() { VisibilityCollapser(); if (SelectedBookOfSelectedCustomer != null && SelectedCustomerHavingBook != null) { var obj = new CheckOutModel() { BookId = SelectedBookOfSelectedCustomer.BookId, CustomerId = SelectedCustomerHavingBook.CustomerId, Quantity = SelectedBookOfSelectedCustomer.Quantity + 1 }; await _allCheckInoutOrderDataAccess.CheckOutBook(obj, Properties.Resources.CheckInBook); _log.Message("Checkin book "); RaiseCheckInOutEvent(); GetAllOrders(); GetBooks(); GetAllCustomerHavingBook(); BookCollectionBelongingToSelectedCustomer.Clear(); } else { CheckInErrorMessage = Properties.Resources.EmptyFieldErrorMsg; CheckInErrorMessageVisibility = Visibility.Visible; } }
public IRibbonControlObject GetControlObject(Office.IRibbonControl control) { List <IRibbonControlObject> controlObjects = null; if (control?.Context == null) { return(null); } var contextHashCode = control.Context.GetHashCode(); Debug.WriteLine($"Context hash code:{contextHashCode}"); logger.Message($"Context hash code:{contextHashCode}"); IRibbonControlObject controlObject = null; controls.TryGetValue(contextHashCode, out controlObjects); if (controlObjects != null) { controlObject = controlObjects.FirstOrDefault(c => c.Tag == control.Tag); } if (controlObject == null) { controlObject = ControlFactoryMethod(control); if (controlObject != null) { if (controlObjects != null) { controlObjects.Add(controlObject); controls[contextHashCode] = controlObjects; } else { controlObjects = new List <IRibbonControlObject>(new[] { controlObject }); controls.Add(contextHashCode, controlObjects); } } } return(controlObject); }
private void CloseApplication(object Parameter) { var _window = Parameter as Window; if (_window != null) { _log.Message("Shutting Down Application....."); _window.Close(); } }