public void Error(object message) { _logger.Error(message); }
public void Error(string message) => _logger.Error(message);
/// <summary> /// Logs the error message. /// </summary> /// <param name="message">The message.</param> public void Error(object message) { Log.Error(message); }
public void LogError(string message) { _logger.Error(message); }
public void Error(string format, params object[] args) { _logger.Error(format, args); }
public bool ValidateNodeDataType(string nodeName, string targetType, string nodeValue) { //Validate xml element value bool isValid = true; if (targetType == "Int16") { if (!Int16.TryParse(nodeValue, out var intVal)) { isValid = false; logger.Error($"Node {nodeName} Value {nodeValue} is invalid Required {targetType} "); } } else if (targetType == "Int32") { if (!int.TryParse(nodeValue, out var intVal)) { isValid = false; logger.Error($"Node {nodeName} Value {nodeValue} is invalid Required {targetType} "); } } else if (targetType == "Int64") { if (!Int64.TryParse(nodeValue, out var intVal)) { isValid = false; logger.Error($"Node {nodeName} Value {nodeValue} is invalid Required {targetType} "); } } else if (targetType == "Boolean" || targetType == "bool") { if (!bool.TryParse(nodeValue, out var intVal)) { isValid = false; logger.Error($"Node {nodeName} Value {nodeValue} is invalid Required {targetType} "); } } else if (targetType == "Double") { if (!double.TryParse(nodeValue, out var intVal)) { logger.Error($"Node {nodeName} Value {nodeValue} is invalid Required {targetType} "); } } else if (targetType == "Single") { if (!Single.TryParse(nodeValue, out var intVal)) { isValid = false; logger.Error($"Node {nodeName} Value {nodeValue} is invalid Required {targetType} "); } } else if (targetType == "Date/Time") { if (!DateTime.TryParse(nodeValue, out var intVal)) { isValid = false; logger.Error($"Node {nodeName} Value {nodeValue} is invalid Required {targetType} "); } } return(isValid); }
public override object Execute(Workflow workflow) { logger.Info("Entered Command:{0}", workflow.Command); if (!ValidateInputSchema()) { return(null); } string msg = ""; bool failed = false; this.WorkFlow = workflow; if (workflow.Command == (int)JdSuite.Common.Module.Commands.DoubleClick) { ShowParameterWindow(); } var element = workflow.GetAppState(ModuleName, Guid); if (element != null) { //ReadProgramCSV(element.Element("Root")); } if (this.OutputNode.State.Schema == null) { msg += "Process is incomplete as Output Schema is not set."; failed = true; } if (this.OutputNode.State.DataFilePath == null) { msg += " Output node data file path is not set. "; failed = true; } if (failed) { logger.Error(msg); MessageService.ShowError("Output node validation error", msg); } if (failed) { if (OutputNode.IsConnected()) { msg = "Disconnecting module due to errors: " + msg; OutputNode.Disconnect(); } logger.Warn(msg); this.OutputNode.State.DataFilePath = ""; return(null); } logger.Info("Calling RequestStateUpdate?.Invoke(workflow)"); RequestStateUpdate?.Invoke(workflow); return(null); }
private static async Task Main(string[] args) { Logger.Info("Starting..."); try { AppConfig config; /* * add a appsettings.json file that looks like this or feed the settings in some other ways * { * "Username": "******", * "Password": "******", * "Currency": "GBP", * "OddsFormat": "DECIMAL", * "BaseUrl": "https://api.pinnacle.com/" * } */ using (var r = new StreamReader("appsettings.json")) { var json = r.ReadToEnd(); config = JsonConvert.DeserializeObject <AppConfig>(json); } using (var httpClient = HttpClientFactory.GetNewInstance(config.Username, config.Password, true, config.BaseUrl)) { var api = new PinnacleClient(config.Currency, config.OddsFormat, httpClient); long lastFixture = 0; long lastLine = 0; var fixtures = await api.GetFixtures(new GetFixturesRequest(SampleSportId, lastFixture)); var lines = await api.GetOdds(new GetOddsRequest(fixtures.SportId, fixtures.Leagues.Select(i => i.Id).ToList(), lastLine, false)); var leagues = await api.GetLeagues(SampleSportId); // Subsequent calls to GetOdds or GetFixtures should pass these 'Last' values to get only what changed since instead of the full snapshot lastFixture = fixtures.Last; lastLine = lines.Last; SaveResultsToOutputFolder(fixtures, lines, leagues); var betResponse = await PlaceRandomBet(lines, api); Console.WriteLine($"Status={betResponse.Status}, BetId={betResponse.BetId}, ErrorCode={betResponse.ErrorCode}, UniqueRequestId={betResponse.UniqueRequestId}"); } Console.WriteLine("Done!"); Logger.Info("Done!"); } catch (Exception e) { Console.WriteLine(e); Logger.Error(e, "Exception in Task Run."); } Console.WriteLine("Press any key to exit."); Console.ReadKey(); }
public void Error(string message) { _internaLogger.Error(message); }
public void Error(string message, Exception exception) { _readLogger.Error(message + Environment.NewLine + exception); }
public void Error(string message, params object[] formatArgs) { _logger.Error(message, formatArgs); }
public CurrencyConvertResponse FindRate(BaseCurrency crr) { var response = new CurrencyConvertResponse { IsSuccess = false, Message = "Unknows", Rate = 0m, Status = Enum.Status.Unknown }; var line = crr is Dollar ? "USD/TRY" : crr is Euro ? "EUR/TRY" : "ERROR"; var web = new HtmlWeb(); var doc = web.Load("http://www.bloomberght.com/"); var currencyRate = doc.DocumentNode.SelectNodes("//div[@class='line2']").FirstOrDefault(c => c.ParentNode.InnerHtml.Contains(line)); if (currencyRate == null) { // log error Logger.Error($"CurrencyRate is null"); return(response); } var rateContent = Regex.Replace(currencyRate.InnerText.ToLower(), @"\s+", string.Empty); rateContent = rateContent.Replace(",", "."); var rate = 0m; #region Exception Handling try { rate = Convert.ToDecimal(rateContent); Console.WriteLine("The string as a decimal is {0}.", rate); } catch (OverflowException ex) { Logger.Error($"Error while calculation rate, OverflowException", ex); response.Status = Enum.Status.Error; response.Message = "The conversion from string to decimal overflowed."; } catch (FormatException ex) { Logger.Error($"Error while calculation rate, FormatException", ex); response.Status = Enum.Status.Error; response.Message = "The string is not formatted as a decimal."; } catch (ArgumentNullException ex) { Logger.Error($"Error while calculation rate, ArgumentNullException", ex); response.Status = Enum.Status.Error; response.Message = "The string is null."; } #endregion response.IsSuccess = true; response.Message = "Well done kereta"; response.Rate = rate; response.Status = Enum.Status.Success; Logger.Debug($"Response : {JsonConvert.SerializeObject(response)}"); return(response); }
public GameItemViewModel(AggregatedGame game, IDependencyResolver resolver) { Game = game; _logger = resolver.GetService <ILogger>(); _vpdbClient = resolver.GetService <IVpdbClient>(); _gameManager = resolver.GetService <IGameManager>(); _pinballXManager = resolver.GetService <IPinballXManager>(); _messageManager = resolver.GetService <IMessageManager>(); var threadManager = resolver.GetService <IThreadManager>(); game.WhenAnyValue(g => g.IsDownloading).ToProperty(this, vm => vm.IsDownloading, out _isDownloading); game.WhenAnyValue(g => g.IsQueued).ToProperty(this, vm => vm.IsQueued, out _isQueued); // release identify IdentifyRelease = ReactiveCommand.CreateFromObservable(() => _vpdbClient.Api.GetReleasesBySize(Game.FileSize, MatchThreshold).SubscribeOn(threadManager.WorkerScheduler)); IdentifyRelease.Select(releases => releases .Select(release => new { release, release.Versions }) .SelectMany(x => x.Versions.Select(version => new { x.release, version, version.Files })) .SelectMany(x => x.Files.Select(file => new GameResultItemViewModel(game, x.release, x.version, file, CloseResults))) ).Subscribe(x => { var releases = x as GameResultItemViewModel[] ?? x.ToArray(); var numMatches = 0; _logger.Info("Found {0} releases for game to identify.", releases.Length); GameResultItemViewModel match = null; foreach (var vm in releases) { if (game.FileName == vm.TableFile.Reference.Name && game.FileSize == vm.TableFile.Reference.Bytes) { numMatches++; match = vm; } } _logger.Info("Found {0} identical match(es).", numMatches); // if file name and file size are identical, directly match. if (numMatches == 1 && match != null) { _logger.Info("File name and size are equal to local release, linking."); _gameManager.MapGame(match.Game, match.Release, match.TableFile.Reference.Id); //_messageManager.LogReleaseLinked(match.Game, match.Release, match.TableFile.Reference.Id); } else { _logger.Info("View model updated with identified releases."); IdentifiedReleases = releases; ShowResults = true; } }, exception => _vpdbClient.HandleApiError(exception, "identifying a game by file size")); //var canSync = this.WhenAnyValue(x => x.Game.IsSynced, x => x.Game.HasRelease, (isSynced, hasRelease) => isSynced && hasRelease); //var canSync = this.WhenAnyValue(x => x.Game.Mapping.IsSynced, x => x.Game.MappedRelease, (isSynced, rls) => isSynced && rls != null); //SyncToggled = ReactiveCommand.Create(() => { _gameManager.Sync(Game); }, canSync); // handle errors IdentifyRelease.ThrownExceptions.Subscribe(e => { _logger.Error(e, "Error matching game."); }); // result switch IdentifyRelease.Select(r => r.Count > 0).Subscribe(hasResults => { HasResults = hasResults; }); // add to db button AddGame = ReactiveCommand.Create(() => _gameManager.AddGame(Game)); // remove from db button RemoveGame = ReactiveCommand.Create(() => _pinballXManager.RemoveGame(Game.XmlGame)); // close button CloseResults = ReactiveCommand.Create(() => { ShowResults = false; }); // hide button HideGame = ReactiveCommand.Create(() => _gameManager.HideGame(Game)); // unhide button UnHideGame = ReactiveCommand.Create(() => _gameManager.UnHideGame(Game)); // download button DownloadMissing = ReactiveCommand.Create(() => _gameManager.DownloadGame(Game)); // spinner IdentifyRelease.IsExecuting.ToProperty(this, vm => vm.IsExecuting, out _isExecuting); // global buttons hide this.WhenAnyValue( vm => vm.ShowResults, vm => vm.IsExecuting, vm => vm.IsDownloading, vm => vm.IsQueued, (showResults, isExecuting, isDownloading, isQueued) => !showResults && !isExecuting && !isDownloading && !isQueued ).ToProperty(this, vm => vm.ShowButtons, out _showButtons); // identify button visibility this.WhenAny( vm => vm.Game.HasLocalFile, vm => vm.Game.MappedTableFile, vm => vm.ShowButtons, (hasLocalFile, mappedFile, showButtons) => hasLocalFile.Value && mappedFile.Value == null && showButtons.Value ).ToProperty(this, vm => vm.ShowIdentifyButton, out _showIdentifyButton); // hide button visibility this.WhenAny( vm => vm.Game.Mapping, vm => vm.Game.HasLocalFile, vm => vm.Game.HasMappedRelease, vm => vm.Game.HasXmlGame, vm => vm.ShowButtons, (mapping, hasLocalFile, hasMappedRelease, hasXmlGame, showButtons) => (mapping.Value == null || !mapping.Value.IsHidden) && hasLocalFile.Value && !hasMappedRelease.Value && !hasXmlGame.Value && showButtons.Value ).ToProperty(this, vm => vm.ShowHideButton, out _showHideButton); // unhide button visibility this.WhenAny( vm => vm.Game.Mapping, vm => vm.ShowButtons, (mapping, showButtons) => mapping.Value != null && mapping.Value.IsHidden && showButtons.Value ).ToProperty(this, vm => vm.ShowUnHideButton, out _showUnHideButton); // add to db button visibility this.WhenAny( vm => vm.Game.HasLocalFile, vm => vm.Game.HasXmlGame, vm => vm.Game.MappedTableFile, vm => vm.ShowButtons, (hasLocalFile, hasXmlGame, mappedFile, showButtons) => hasLocalFile.Value && !hasXmlGame.Value && mappedFile.Value != null && showButtons.Value ).ToProperty(this, vm => vm.ShowAddToDbButton, out _showAddToDbButton); // remove from db button visibility this.WhenAny( vm => vm.Game.HasLocalFile, vm => vm.Game.HasXmlGame, vm => vm.ShowButtons, (hasLocalFile, hasXmlGame, showButtons) => !hasLocalFile.Value && hasXmlGame.Value && showButtons.Value ).ToProperty(this, vm => vm.ShowRemoveFromDbButton, out _showRemoveFromDbButton); // download button visibility this.WhenAny( vm => vm.Game.HasLocalFile, vm => vm.Game.MappedTableFile, vm => vm.ShowButtons, (hasLocalFile, mappedFile, showButtons) => !hasLocalFile.Value && mappedFile.Value != null && showButtons.Value ).ToProperty(this, vm => vm.ShowDownloadMissingButton, out _showDownloadMissingButton); // download progress this.WhenAnyValue(vm => vm.IsDownloading).Subscribe(isDownloading => { if (isDownloading) { Game.MappedJob.WhenAnyValue(j => j.TransferPercent) .Sample(TimeSpan.FromMilliseconds(300)) .Where(x => !Game.MappedJob.IsFinished) .Subscribe(progress => { // on main thread System.Windows.Application.Current.Dispatcher.Invoke(() => { DownloadPercent = progress; }); }); } }); }
public void LogError(string messageFormat, params object[] values) { _localLogger.Error(messageFormat, values); }
/// <summary> /// Run Data menu workflow /// </summary> public override bool Run(WorkInfo workInfo) { bool bStatus; try { logger.Info($"{this.DisplayName} Running_workflow"); workInfo.Log(this.DisplayName, NLog.LogLevel.Info, "Running workflow"); if (!CanRun(workInfo)) { return(false); } logger.Trace($"Creating [{DisplayName}] Scripting object"); workInfo.Log(this.DisplayName, NLog.LogLevel.Info, "Starting Scripting process"); var inputFiles = new Dictionary <string, string>(); var outputFiles = new Dictionary <string, string>(); for (int i = 0; i < InputNodes.Count; i++) { inputFiles.Add($"Input_{i}", InputNodes[i].State.DataFilePath); } for (int i = 0; i < OutputNodes.Count; i++) { outputFiles.Add($"Output_{i}.{FullOutputSchema.ChildNodes[i].ChildNodes[0].Name}", OutputNodes[i].State.DataFilePath); } var tempFile = Path.GetTempFileName(); var result = CompilerService.GenerateCodeAndCompile(tempFile, FullInputSchema, FullOutputSchema, CodeText, inputFiles, outputFiles); File.Delete(tempFile); try { if (result.CompilerResult.Errors.HasErrors) { for (int i = 0; i < result.CompilerResult.Errors.Count; i++) { workInfo.Log(this.DisplayName, NLog.LogLevel.Error, $"Line {result.CompilerResult.Errors[i].Line - result.CodeLine}, Error {result.CompilerResult.Errors[i].ErrorNumber}: {result.CompilerResult.Errors[i].ErrorText}"); } return(false); } Assembly loAssembly = result.CompilerResult.CompiledAssembly; object loObject = loAssembly.CreateInstance("WinFormCodeCompile.Transform"); if (loObject == null) { return(false); } try { var type = loObject.GetType(); var method = type.GetMethod("UpdateText"); var invokationResult = method.Invoke(loObject, null); } catch (Exception ex) { logger.Error(ex); workInfo.Log(this.DisplayName, NLog.LogLevel.Error, $"Line {ex.InnerException.LineNumber() - result.CodeLine}, {ex.InnerException?.Message}"); return(false); } } catch { return(false); } bStatus = true; } catch (XPathException ex) { var msg = $"Critical failure in [{DisplayName}] module error: {ex.Message} "; logger.Error(msg); workInfo.Log(this.DisplayName, NLog.LogLevel.Error, msg); bStatus = false; } catch (Exception ex) { var msg = $"Critical failure in [{DisplayName}] module error: {ex.Message} "; logger.Error(msg); workInfo.Log(this.DisplayName, NLog.LogLevel.Error, msg); bStatus = false; } workInfo.Log(this.DisplayName, NLog.LogLevel.Info, $"Module completed processing with Status: {bStatus}"); logger.Info($"{this.DisplayName} module completed processing with status:{bStatus}"); return(bStatus); }
public void Error(string message) { _log.Error(message); }
public RedisCache(String name, RedisCachePolicy policy) { this.name = name; this.log = NLog.LogManager.GetLogger(typeof(RedisCache).FullName); log.Debug("Init Cache {0}", this.name); if (policy == null) { log.Error("Invalid Policy for Cache {0}", this.name); throw new ArgumentNullException(nameof(policy)); } if (!string.IsNullOrEmpty(policy.ConnectionName)) { this.connectionString = CacheManager.GetConnectionString(policy.ConnectionName)?.ConnectionString; if (string.IsNullOrEmpty(connectionString)) { throw new ArgumentException( $"{nameof(ICacheConnectionString.ConnectionString)} not found for {nameof(policy.ConnectionName)} {policy.ConnectionName}", $"{nameof(policy)}.{nameof(policy.ConnectionName)}"); } } else if (!string.IsNullOrEmpty(policy.ConnectionString)) { this.connectionString = policy.ConnectionString; } else { throw new ArgumentException( $"{nameof(policy.ConnectionString)} is undefined", $"{nameof(policy)}.{nameof(policy.ConnectionString)}"); } this.monitorPort = policy.MonitorPort; this.monitorIntervalMilliseconds = policy.MonitorIntervalMilliseconds; this.converterType = policy.Converter; this.clusterType = policy.ClusterType; if (policy.SlidingExpiration.HasValue && policy.SlidingExpiration.Value < TimeSpan.MaxValue) { this.expireWithin = policy.SlidingExpiration.Value; this.useSlidingExpiration = true; this.expireAt = null; } else if (policy.ExpirationFromAdd.HasValue && policy.ExpirationFromAdd.Value < TimeSpan.MaxValue) { this.expireWithin = policy.ExpirationFromAdd.Value; this.useSlidingExpiration = false; this.expireAt = null; } else if (policy.AbsoluteExpiration.HasValue && policy.AbsoluteExpiration.Value < DateTimeOffset.MaxValue) { this.expireWithin = null; this.useSlidingExpiration = false; this.expireAt = policy.AbsoluteExpiration.Value.LocalDateTime; } else { this.expireWithin = null; this.useSlidingExpiration = false; this.expireAt = null; } this.useSlidingExpiration = (policy.SlidingExpiration < TimeSpan.MaxValue); this.innerCache = new CacheContext( this.connectionString, this.converterType, this.clusterType, this.monitorPort, this.monitorIntervalMilliseconds); this.notiferName = policy.SyncProvider; this.synchronizer = CacheSynchronizer.CreateCacheSynchronizer(this, this.notiferName); }
public async Task <string> Save(int handlingId, int processId, int?abandonReason = null) { try { Logger.Info("ActionListViewModel is starting. HandlingId={handlingId}, ProcessId={processId}, AbandonReason={abandonReason}", handlingId, processId, abandonReason); List <Task <string> > listOfTask = new List <Task <string> >(); foreach (ProcessAction pa in CheckedItems.Where(i => i.IsMutable == true)) { Logger.Info("ProcessAction: ID={ProcessActionId}, IsChecked={IsChecked}, IsMutable={IsMutable}", pa.ProcessActionId, pa.IsChecked, pa.IsMutable); pa.HandlingId = handlingId; pa.ProcessId = processId; if (pa.IsChecked == false || pa.IsChecked == null) { pa.AbandonReasonId = abandonReason; } if (pa.IsMutable == true && (pa.IsChecked == true || (pa.IsChecked == false && abandonReason != null))) { //save changes to process action only when it's mutable and: //- it's checked //- it's not checked and the user provided a reason why he abandoned it if (pa.ProcessActionId == 0) { listOfTask.Add(pa.Add()); } else { listOfTask.Add(pa.Edit()); } } } IEnumerable <string> results = await Task.WhenAll <string>(listOfTask); Task.Run(() => TakeSnapshot()); if (results.Where(r => r != "OK").Any()) { return(string.Join("; ", results.Where(r => r != "OK"))); } else { return("OK"); } } catch (InvalidCastException ex) { Logger.Error(ex); string additionalInfo = $"handlingId={handlingId}, processId={processId}, abandonReason={abandonReason}"; Static.Functions.CreateError(ex, "InvalidCast", nameof(this.Save), this.GetType().Name, additionalInfo); return(ex.Message); } catch (Exception ex) { Logger.Error(ex); string additionalInfo = $"handlingId={handlingId}, processId={processId}, abandonReason={abandonReason}"; Static.Functions.CreateError(ex, "No connection", nameof(this.Save), this.GetType().Name, additionalInfo); return(ex.Message); } }
/// <summary> /// Logs the error. /// </summary> /// <param name="ex">The exception.</param> /// <param name="message">The additional message.</param> public void Error(Exception ex, string message = null) { _nlogger.Error(ex, message ?? String.Empty); }
public virtual void ReadXml(XmlReader reader) { if (!reader.IsStartElement("BaseModule")) { logger.Error("Cannot load base module as <BaseModule> is missing from xml"); throw new XmlException("Cannot load base module as <BaseModule> is missing from xml"); } XElement bmnode = XElement.ReadFrom(reader) as XElement; int attrCount = reader.AttributeCount; _Guid = Guid.Parse(bmnode.Attribute("Guid").Value); var inputCount = Int32.Parse(bmnode.Attribute("InputCount").Value); var outputCount = Int32.Parse(bmnode.Attribute("OutputCount").Value); var stateCount = Int32.Parse(bmnode.Attribute("StateCount").Value); var attrib = bmnode.Attribute("ParameterCount"); if (attrib != null) { this.ParameterCount = Int32.Parse(attrib.Value); } if (stateCount > 0) { var dict = bmnode.XPathSelectElement("dictionary"); if (dict != null) { var dictReader = dict.CreateReader(); XmlSerializer keySerializer = new XmlSerializer(typeof(SerializableDictionary <Guid, ModuleState>)); Store = (SerializableDictionary <Guid, ModuleState>)keySerializer.Deserialize(dictReader); } } var stateInfo = bmnode.XPathSelectElement("StateInfo"); if (stateInfo != null) { var dict = stateInfo.XPathSelectElement("dictionary"); if (dict != null) { var dictReader = dict.CreateReader(); XmlSerializer keySerializer = new XmlSerializer(typeof(SerializableDictionary <string, string>)); StateInfo = (SerializableDictionary <string, string>)keySerializer.Deserialize(dictReader); } } InputNodes.Clear(); foreach (var ioNode in bmnode.XPathSelectElements("//InputNodes/InputNode")) { var identifier = Guid.Parse(ioNode.Attribute("Identifier").Value); var displayName = ioNode.Attribute("DisplayName").Value; var ext = ioNode.Attribute("Extension").Value; var moduleNode = new InputNode(this, this.DisplayName, ext); moduleNode.Identity = identifier; if (Store.ContainsKey(identifier)) { moduleNode.State = Store[identifier]; } else { moduleNode.State = new ModuleState(); } AddInputNode(moduleNode); } OutputNodes.Clear(); foreach (var ioNode in bmnode.XPathSelectElements("//OutputNodes/OutputNode")) { var identifier = Guid.Parse(ioNode.Attribute("Identifier").Value); var displayName = ioNode.Attribute("DisplayName").Value; var ext = ioNode.Attribute("Extension").Value; var moduleNode = new OutputNode(this, this.DisplayName, ext); moduleNode.Identity = identifier; if (Store.ContainsKey(identifier)) { moduleNode.State = Store[identifier]; } else { moduleNode.State = new ModuleState(); } AddOutputNode(moduleNode); } ReadParameter(bmnode); }
/// <summary> /// Application enrty point. /// </summary> /// <param name="args">Command line arguments.</param> private static Int32 Main(String[] args) { try { var assembly = Assembly.GetEntryAssembly() ?? Assembly.GetCallingAssembly(); Log.Warn($"{assembly.VersionString()} (build: {assembly.BuildString()})"); // NOTE: .NET Core 3.x CommandLineConfigurationProvider does not support "parameters with no value" // See also: https://github.com/aspnet/Configuration/issues/780 var isConsoleMode = (Array.IndexOf(args, "--console") >= 0); if (isConsoleMode) { args = args.Where(a => a != "--console").ToArray(); } // // Set-up application Host // var builder = new HostBuilder() .ConfigureHostConfiguration((config) => config .AddEnvironmentVariables("NETCORE_").AddCommandLine(args)); // // Configure application components // builder .ConfigureAppConfiguration((_, config) => config .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)) .ConfigureAppConfiguration((hostContext, config) => config .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true)) .ConfigureLogging((hostContext, logging) => logging .AddConfiguration(hostContext.Configuration.GetSection("Logging")) .ClearProviders().AddNLog()) .ConfigureServices((hostContext, services) => services .AddOptions() .Configure <HostOptions>(hostContext.Configuration.GetSection("Host"))) .ConfigureDataProviders() .ConfigureApiHost() .ConfigureServicesHost() .ConfigureAppConfiguration((_, config) => config .AddCommandLine(args)); // // Configure Service vs Console // if (!isConsoleMode) { // IMPORTANT: Update working directory when running as a Windows Service System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory); builder .ConfigureServices((_, services) => services.AddSingleton <IHostLifetime, Service>()); } else { builder // HACK: Supress startup messages written by HostBuilder directly into Console! .ConfigureServices((hostContext, services) => services // TODO: Find where is this SH*T is read from config by default! // See also: https://github.com/aspnet/Extensions/issues/1103 .Configure <ConsoleLifetimeOptions>(hostContext.Configuration.GetSection("Console"))) .UseConsoleLifetime(); } // // Execute // builder.Build().Run(); Log.Warn("Done."); Log.Info(String.Empty); Log.Info(String.Empty); Log.Info(String.Empty); } catch (Exception ex) { try { Log.Error(ex, ex.Message); } catch (Exception) { // // NOTE: Keep console output in place in case someone screw logs configuration // Console.ForegroundColor = ConsoleColor.Red; Console.Error.WriteLine(); Console.Error.WriteLine($"FATAL: {ex.DetailedMessage()}"); Console.Error.WriteLine(); Console.ResetColor(); } return(-1); } finally { NLog.LogManager.Shutdown(); } return(0); }
/// <summary> /// Use this as it manages to run multiple passes to process all xpath expressions /// </summary> public void Filter() { logger.Trace("Starting main_filtering_process"); logger.Info("InputFile [{0}]", InputFileName); logger.Info("OutputFile [{0}]", OutputFileName); if (!string.IsNullOrEmpty(OutputFileName2)) { logger.Info("OutputFile2 [{0}]", OutputFileName2); } WriterQue.Clear(); string filter = ""; try { if (XPathFilter.Count <= 0) { CreateXPathExpressions(); } if (XPathFilter.Count == 1) { filter = XPathFilter[0]; Filter(InputFileName, OutputFileName, filter); return; } Random rand = new Random(); if (File.Exists(OutputFileName)) { File.Delete(OutputFileName); } string inputFileName = InputFileName; for (int i = 0; i < XPathFilter.Count - 1; i++) { filter = XPathFilter[i]; string outputFile = DataDir + "DataFilter_" + DateTime.Now.ToString("yyMMddHHmmssfff") + "_" + rand.Next(1900).ToString() + ".xml"; Filter(inputFileName, outputFile, filter); inputFileName = outputFile; } filter = XPathFilter[XPathFilter.Count - 1]; Filter(inputFileName, OutputFileName, filter); } catch (Exception ex) { logger.Error(ex, $"XmlFilter_Error Input [{InputFileName}] XPath[{filter}]"); throw; } finally { while (WriterQue.Count > 0) { var writer = WriterQue.Dequeue(); try { writer.Close(); } catch { } } } }
public GameItemViewModel(Game game, IDependencyResolver resolver) { Game = game; _logger = resolver.GetService<ILogger>(); _vpdbClient = resolver.GetService<IVpdbClient>(); _gameManager = resolver.GetService<IGameManager>(); _messageManager = resolver.GetService<IMessageManager>(); var threadManager = resolver.GetService<IThreadManager>(); // release identify IdentifyRelease = ReactiveCommand.CreateAsyncObservable(_ => _vpdbClient.Api.GetReleasesBySize(Game.FileSize, MatchThreshold).SubscribeOn(threadManager.WorkerScheduler)); IdentifyRelease.Select(releases => releases .Select(release => new {release, release.Versions}) .SelectMany(x => x.Versions.Select(version => new {x.release, version, version.Files})) .SelectMany(x => x.Files.Select(file => new GameResultItemViewModel(game, x.release, x.version, file, CloseResults))) ).Subscribe(x => { var releases = x as GameResultItemViewModel[] ?? x.ToArray(); var numMatches = 0; _logger.Info("Found {0} releases for game to identify.", releases.Length); GameResultItemViewModel match = null; foreach (var vm in releases) { if (game.Filename == vm.TableFile.Reference.Name && game.FileSize == vm.TableFile.Reference.Bytes) { numMatches++; match = vm; } } _logger.Info("Found {0} identical match(es).", numMatches); // if file name and file size are identical, directly match. if (numMatches == 1 && match != null) { _logger.Info("File name and size are equal to local release, linking."); _gameManager.LinkRelease(match.Game, match.Release, match.TableFile.Reference.Id); _messageManager.LogReleaseLinked(match.Game, match.Release, match.TableFile.Reference.Id); } else { _logger.Info("View model updated with identified releases."); IdentifiedReleases = releases; HasExecuted = true; } }, exception => _vpdbClient.HandleApiError(exception, "identifying a game by file size")); //SyncToggled // .Where(_ => Game.IsSynced && Game.HasRelease) // .Subscribe(_ => { GameManager.Sync(Game); }); // handle errors IdentifyRelease.ThrownExceptions.Subscribe(e => { _logger.Error(e, "Error matching game."); }); // spinner IdentifyRelease.IsExecuting.ToProperty(this, vm => vm.IsExecuting, out _isExecuting); // result switch IdentifyRelease.Select(r => r.Count > 0).Subscribe(hasResults => { HasResults = hasResults; }); // close button CloseResults.Subscribe(_ => { HasExecuted = false; }); // identify button visibility this.WhenAny( vm => vm.HasExecuted, vm => vm.Game.HasRelease, vm => vm.IsExecuting, (hasExecuted, hasRelease, isExecuting) => !hasExecuted.Value && !hasRelease.Value && !isExecuting.Value ).ToProperty(this, vm => vm.ShowIdentifyButton, out _showIdentifyButton); }
public override bool Run(WorkInfo workInfo) { bool bStatus = false; string msg = ""; try { workInfo.Log(this.DisplayName, NLog.LogLevel.Info, "Executing workflow"); // JdSuite.Common.ApplicationWindowUtil.ShowStatusBarMessage("CSV Module: Running Command"); logger.Info($"Running {DisplayName}"); if (!File.Exists(this.DataFileInfo.FilePath)) { msg = $"{DisplayName} is not configured, Input File does not exist"; workInfo.Log(this.DisplayName, NLog.LogLevel.Info, msg); logger.Error(msg); return(false); } if (this.OutputNode.State.Schema == null) { msg = $"{DisplayName} schema is not set, {DisplayName} is not configured"; logger.Error(msg); //MessageService.ShowError($"{DisplayName} schema is not set", $"{DisplayName} is not configured"); workInfo.Log(this.DisplayName, NLog.LogLevel.Error, msg); return(false); } if (this.OutputNode.State.DataFilePath == null) { msg = $"Halting execution as {DisplayName} xml output file is not set"; // MessageService.ShowError($"{DisplayName} xml output file is not set", $"{DisplayName} is not configured"); workInfo.Log(this.DisplayName, NLog.LogLevel.Error, msg); logger.Error(msg); return(false); } if (this.DataFileInfo.FileType.ToLower() == "csv") { logger.Info("Creating xml file from csv {0}", this.DataFileInfo.FilePath); workInfo.Log(this.DisplayName, NLog.LogLevel.Info, $"Creating xml file from csv {this.DataFileInfo.FilePath}"); CSVParser parser = new CSVParser(); parser.Delimiter = this.DataFileInfo.Delimiter; parser.FileEncoding = Encoding.GetEncoding(this.DataFileInfo.Encoding); parser.FirstLineHasHeaders = this.DataFileInfo.FirstRowHasHeader; parser.SkipFirstLine = false; parser.SourceFileName = this.DataFileInfo.FilePath; parser.XMLRootName = this.DataFileInfo.RootArrayName; //JdSuite.Common.ApplicationWindowUtil.ShowStatusBarMessage("CSV Module: Starting to parse CSV File"); workInfo.Log(this.DisplayName, NLog.LogLevel.Info, $"CSV Module: Starting to parse CSV File"); parser.Parse(); logger.Trace("Writing_to_output_file {0}", this.OutputNode.State.DataFilePath); workInfo.Log(this.DisplayName, NLog.LogLevel.Info, $"Writing to output file {this.OutputNode.State.DataFilePath}"); //JdSuite.Common.ApplicationWindowUtil.ShowStatusBarMessage("CSV Module: Saving CSV file xml"); parser.SaveXML(this.OutputNode.State.DataFilePath); logger.Info($"Created xml file from csv {this.OutputNode.State.DataFilePath}"); workInfo.Log(this.DisplayName, NLog.LogLevel.Info, $"Created xml file from csv {this.OutputNode.State.DataFilePath}"); } else if (this.DataFileInfo.FileType.ToLower() == "dbf") { logger.Info(msg = $"Creating xml file from dbf {this.DataFileInfo.FilePath}"); workInfo.Log(this.DisplayName, NLog.LogLevel.Info, msg); DBFParser parser = new DBFParser(); parser.FileEncoding = Encoding.GetEncoding(this.DataFileInfo.Encoding); parser.SourceFileName = this.DataFileInfo.FilePath; parser.XMLRootName = this.DataFileInfo.RootArrayName; msg = "CSV Module: Parsing DBF File"; workInfo.Log(this.DisplayName, NLog.LogLevel.Info, msg); // JdSuite.Common.ApplicationWindowUtil.ShowStatusBarMessage("CSV Module: Parsing DBF File"); parser.Parse(); // JdSuite.Common.ApplicationWindowUtil.ShowStatusBarMessage("CSV Module: Saving DBF file xml"); msg = "CSV Module: Saving DBF file xml"; workInfo.Log(this.DisplayName, NLog.LogLevel.Info, msg); parser.SaveXML(this.OutputNode.State.DataFilePath); logger.Info("Created xml file from dbf {0}", this.OutputNode.State.DataFilePath); msg = $"CSV Module: Transformed DBF to xml {this.OutputNode.State.DataFilePath}"; workInfo.Log(this.DisplayName, NLog.LogLevel.Info, msg); } msg = "CSV Module: Executed its part successfully"; workInfo.Log(this.DisplayName, NLog.LogLevel.Info, msg); //JdSuite.Common.ApplicationWindowUtil.ShowStatusBarMessage("CSV Module: Executed its part successfully"); bStatus = true; } catch (Exception ex) { logger.Error(ex, $"An error occured in {this.DisplayName}"); msg = $"An error occured in {this.DisplayName} Error:{ex.Message}"; workInfo.Log(this.DisplayName, NLog.LogLevel.Error, msg); bStatus = false; } return(bStatus); }