/// <summary>Run the console in memory and get the results that would be output to the shell</summary> public static AppRunnerResult RunInMem(this AppRunner runner, string[] args, ILogger logger, Func <TestConsole, string> onReadLine = null, IEnumerable <string> pipedInput = null, IPromptResponder promptResponder = null) { TestToolsLogProvider.InitLogProvider(logger); var testConsole = new TestConsole( onReadLine, pipedInput, promptResponder == null ? (Func <TestConsole, ConsoleKeyInfo>)null : promptResponder.OnReadKey); runner.Configure(c => c.Console = testConsole); var outputs = InjectTestOutputs(runner); try { var exitCode = runner.Run(args); var consoleOut = testConsole.Joined.ToString(); logger?.WriteLine("\nconsole output:\n"); logger?.WriteLine(consoleOut); return(new AppRunnerResult(exitCode, testConsole, outputs)); } catch (Exception e) { logger?.WriteLine("\nconsole output:\n"); logger?.WriteLine(testConsole.Joined.ToString()); throw; } }
public async Task <bool> RegisterAsync(VectorTimeStamp vts = null, string nsEndpoint = null) { nsEndpoint = nsEndpoint ?? NsEndpoint; if (string.IsNullOrWhiteSpace(nsEndpoint)) { return(false); } RegClient.Connect(nsEndpoint, ZeroMQ.ZSocketType.REQ); Logger?.WriteLine($"Connected to NameServer at {nsEndpoint}"); var packet = new Packet <SystemRegistration> { Payload = SystemRegistration, VectorTimeStamp = vts ?? new VectorTimeStamp() }; var json = JsonConvert.SerializeObject(packet); await RegClient.SendAsync($"REG: {json}", (ZFrame frame) => { if (frame == null) { return; } var responseJson = frame.ToString(); var responsePacket = JsonConvert.DeserializeObject <Packet <SystemRegistration> >(responseJson); SystemRegistration = responsePacket.Payload; Endpoint = SystemRegistration.EndPoint; IsRegistered = true; }); Logger?.WriteLine($"Sent system registration to NameServer. Name: {SystemRegistration.Name}, Endpoint: {SystemRegistration.EndPoint}"); return(IsConnected); }
private static CommandBinding ParseCommandBinding(ITokenStream stream, ILogger logger) { var tokens = stream.Peek(); if (tokens == null) { return(null); } if (tokens.Length > 3 && tokens[2].Value == "=") { var command = tokens[1].Value; var action = ParseAction(tokens, 3, out var end); if (action != null) { if (end != tokens.Length) { logger?.WriteLine( $"Warning: Ignored unknown symbols at {stream.Path}:{stream.Line}."); } return(new CommandBinding(command, action)); } action = new NoOpAction(); logger?.WriteLine($"Error: Could not parse action at {stream.Path}:{stream.Line}."); return(new CommandBinding(command, action)); } logger?.WriteLine($"Error: Malformed binding at {stream.Path}:{stream.Line}."); return(null); }
public override void ExportToLog(Summary summary, ILogger logger) { logger.WriteLine(string.Join(";", columns.Select(c => c.Title))); foreach (var report in summary.Reports.Values) foreach (var measurement in report.AllMeasurements) logger.WriteLine(string.Join(";", columns.Select(column => column.GetValue(summary, report, measurement)))); }
private void PrintTable(SummaryTable table, ILogger logger) { if (table.FullContent.Length == 0) { logger.WriteLineError("<pre>There are no benchmarks found</pre>"); return; } logger.Write("<pre><code>"); table.PrintCommonColumns(logger); logger.WriteLine("</code></pre>"); logger.WriteLine(); logger.WriteLine("<table>"); logger.Write("<tr>"); table.PrintLine(table.FullHeader, logger, "<th>", "</th>"); logger.Write("</tr>"); foreach (var line in table.FullContent) { logger.Write("<tr>"); table.PrintLine(line, logger, "<td>", "</td>"); logger.Write("</tr>"); } logger.WriteLine("</table>"); }
public override void ExportToLog(Summary summary, ILogger logger) { if (useCodeBlocks) { logger.WriteLine(codeBlockStart); } logger = GetRightLogger(logger); logger.WriteLine(); foreach (var infoLine in HostEnvironmentInfo.GetCurrent().ToFormattedString()) { logger.WriteLineInfo(infoLine); } logger.WriteLineInfo(summary.JobRuntimes); logger.WriteLine(); PrintTable(summary.Table, logger); // TODO: move this logic to an analyser var benchmarksWithTroubles = summary.Reports.Where(r => !r.GetResultRuns().Any()).Select(r => r.Benchmark).ToList(); if (benchmarksWithTroubles.Count > 0) { logger.WriteLine(); logger.WriteLineError("Benchmarks with issues:"); foreach (var benchmarkWithTroubles in benchmarksWithTroubles) { logger.WriteLineError(" " + benchmarkWithTroubles.DisplayInfo); } } }
public override void ExportToLog(Summary summary, ILogger logger) { logger.WriteLine($"<pre><code>{EnvironmentHelper.GetCurrentInfo().ToFormattedString("Host")}</code></pre>"); logger.WriteLine(); PrintTable(summary.Table, logger); }
public async Task <bool> RegisterSystem(SystemRegistration registration) { return(await Task.Run(() => { lock (Sync) { if (registration.Id > 0) { var storedRegistration = Repo.Read(registration.Id); if (storedRegistration != null) { registration = storedRegistration; } } if (registration.Id < 1) { registration.Id = NextId; NextId++; } if (registration.Port == 0) { registration.Port = (ushort)Random.Next(5000, 65000); } if (registration.IpAddress == null) { registration.IpAddress = UseLocalHost ? IpAddress.LocalHost : (IpAddress) new byte[] { Subnet[0], Subnet[1], Subnet[2], (byte)NextIp }; } Logger?.WriteLine($"System Registration: Id = {registration.Id}, Name = {registration.Name} "); var createdregistration = Repo.Create(registration); return true; } })); }
internal static async Task StartAsync(TimeSpan offset) { var name = Args.Value(Constants.DistrictServerName); Logger = new MultiLogger( new ConsoleLogger(), new LoggerClient(Args.Value(Constants.LoggerEndpoint), name, Args.Value("NsEndpoint")) ); Logger?.WriteLine($"{name} has started."); Console.WriteLine("Health District: " + name); var endpoint = Args.Value(Constants.DistrictServerEndPoint); var nsEndpoint = Args.Value(Constants.NameServerEndpoint); Console.WriteLine("Endpoint: " + endpoint); var districtServer = new DistrictServer("DS1", endpoint, nsEndpoint, offset, Logger); await districtServer.RegisterAsync(); await districtServer.Start(endpoint); var publisherArgInput = Args.Value(Constants.PublisherEndpoints); Logger?.WriteLine("Publisher endpoints: " + publisherArgInput); var pubEndpoints = publisherArgInput.ToArray(); foreach (var publisherEndPoint in pubEndpoints) { var subscriber = new OutbreakSubscriber(Logger); subscriber.Connect(publisherEndPoint); subscriber.Subscribe(name); } }
public static void w2t(this string logText) { #if DEBUGALL if (_logger == null) { throw new InvalidOperationException("Textlogger must be initialized first"); } #endif _logger?.WriteLine(logText); }
public override void ExportToLog(Summary summary, ILogger logger) { logger.Write("<pre><code>"); logger.WriteLine(); foreach (var infoLine in HostEnvironmentInfo.GetCurrent().ToFormattedString()) { logger.WriteLine(infoLine); } logger.Write("</code></pre>"); logger.WriteLine(); PrintTable(summary.Table, logger); }
private async System.Threading.Tasks.Task InitAsync() { ILogger logger = null; try { logger = await this.GetMefServiceAsync <ILogger>(); logger.WriteLine(Resources.Strings.Daemon_Initializing); daemon = await this.GetMefServiceAsync <ISonarLintDaemon>(); var settings = await this.GetMefServiceAsync <ISonarLintSettings>(); LegacyInstallationCleanup.CleanupDaemonFiles(logger); if (daemon.IsInstalled) { if (settings.IsActivateMoreEnabled && !daemon.IsRunning) { daemon.Start(); } } else { if (settings.IsActivateMoreEnabled) { // User already agreed to have the daemon installed, so directly start download await JoinableTaskFactory.SwitchToMainThreadAsync(); new SonarLintDaemonInstaller(settings, daemon, logger).Show(); } else if (!settings.SkipActivateMoreDialog) { await JoinableTaskFactory.SwitchToMainThreadAsync(); var result = new SonarLintDaemonSplashscreen(settings).ShowDialog(); if (result == true) { new SonarLintDaemonInstaller(settings, daemon, logger).Show(); } } } } catch (Exception ex) when(!ErrorHandler.IsCriticalException(ex)) { logger?.WriteLine(Resources.Strings.ERROR_InitializingDaemon, ex); } logger?.WriteLine(Resources.Strings.Daemon_InitializationComplete); }
private async System.Threading.Tasks.Task InitAsync() { try { logger = await this.GetMefServiceAsync <ILogger>(); logger.WriteLine(Resources.Strings.Daemon_Initializing); await DisableRuleCommand.InitializeAsync(this, logger); await CFamilyReproducerCommand.InitializeAsync(this, logger); cFamilyPreCompiledHeadersEventListener = await this.GetMefServiceAsync <IPreCompiledHeadersEventListener>(); daemon = await this.GetMefServiceAsync <ISonarLintDaemon>(); LegacyInstallationCleanup.CleanupDaemonFiles(logger); // Set up the solution tracker so we can shut down the daemon when a solution is closed var solutionTracker = await this.GetMefServiceAsync <IActiveSolutionTracker>(); solutionTracker.ActiveSolutionChanged += HandleActiveSolutionChanged; IDaemonInstaller installer = await this.GetMefServiceAsync <IDaemonInstaller>(); if (!installer.IsInstalled()) { // Set up the status bar download handler in case the user enables // support for additional languages during the VS session var sbService = await this.GetServiceAsync(typeof(IVsStatusbar)) as IVsStatusbar; statusBarDownloadProgressHandler = new StatusBarDownloadProgressHandler(sbService, installer, logger); var settings = await this.GetMefServiceAsync <ISonarLintSettings>(); if (settings.IsActivateMoreEnabled) { // User already agreed to have the daemon installed so directly start download. // No UI interation so we don't need to be on the UI thread. installer.Install(); } } } catch (Exception ex) when(!ErrorHandler.IsCriticalException(ex)) { logger?.WriteLine(Resources.Strings.ERROR_InitializingDaemon, ex); } logger?.WriteLine(Resources.Strings.Daemon_InitializationComplete); }
private void LogMovieList(string operation, IEnumerable <IMovie> movies) { if (CanLog) { string list = operation; foreach (var movie in movies) { list += $"{movie.Abbreviation} ${movie.Earnings:N0}|"; } _logger?.WriteLine(list); _logger?.WriteLine(_elapsed.FormatRemaining()); } }
public static bool Starts(this ITokenStream stream, string type, ILogger logger, out string name) { var row = stream.PeekNonEmpty(); if (row == null) { name = null; return(false); } if (string.Equals(row[0].Value, type, StringComparison.OrdinalIgnoreCase)) { if (row.Length > 1) { name = row[1].Value; } else { name = null; logger?.WriteLine($"Warning: No item name at {stream.Path}:{stream.Line}. Items without a name may get ignored."); } stream.Move(); return(true); } name = null; return(false); }
private async System.Threading.Tasks.Task InitOnUIThreadAsync() { Debug.Assert(ThreadHelper.CheckAccess(), "Expecting to be on the UI thread"); ILogger logger = null; // HACK: the telemetry manager has to be imported on the UI thread because // of a complicated chain of transitive dependencies: // TelemetryManager -> IActiveSolutionBoundTracker -> IBindingConfiguration -> IHost. // The host expects to be initialized on the UI thread. // The ui and non-ui parts of the host should be split into separate classes. try { logger = await this.GetMefServiceAsync <ILogger>(); logger.WriteLine(Resources.Strings.Telemetry_Initializing); telemetryManager = await this.GetMefServiceAsync <ITelemetryManager>(); logger.WriteLine(Resources.Strings.Telemetry_InitializationComplete); if (await IsSolutionFullyOpenedAsync()) { telemetryManager.Update(); } } catch (Exception ex) when(!ErrorHandler.IsCriticalException(ex)) { // Suppress non-critical exceptions logger?.WriteLine(Resources.Strings.Telemetry_ERROR, ex.Message); } }
public static bool Ends(this ITokenStream stream, string type, ILogger logger, out Token[] row, out string token0) { row = stream.PeekNonEmpty(); if (row == null) { token0 = null; return(true); } token0 = row[0].Value.ToLower(); if (token0 == "end") { if (row.Length > 1) { if (!string.Equals(row[1].Value, type, StringComparison.OrdinalIgnoreCase)) { logger?.WriteLine($"Warning: Expected 'end {type}' at {stream.Path}:{stream.Line}."); } } stream.Move(); return(true); } return(false); }
public static void PrintLine(this SummaryTable table, string[] line, ILogger logger, string leftDel, string rightDel, bool highlightRow, bool startOfGroup, bool startOfGroupInBold) { for (int columnIndex = 0; columnIndex < table.ColumnCount; columnIndex++) { if (!table.Columns[columnIndex].NeedToShow) { continue; } var text = (startOfGroup && startOfGroupInBold) ? BuildBoldText(table, line, leftDel, rightDel, columnIndex) : BuildStandardText(table, line, leftDel, rightDel, columnIndex); if (highlightRow) // write the row in an alternative colour { logger.WriteHeader(text); } else { logger.WriteStatistic(text); } } logger.WriteLine(); }
internal void ReceiveAction(ZFrame frame) { var json = frame.ReadString(); Console.WriteLine("** OUTBREAK ALLERT **"); Console.WriteLine(json); Logger?.WriteLine("Outbreak alert: " + json); }
private ExecuteResult ExecuteImpl(Process process, string exeName, Benchmark benchmark, ILogger logger, IDiagnoser compositeDiagnoser = null) { process.PriorityClass = ProcessPriorityClass.High; if (!benchmark.Job.Affinity.IsAuto) { process.ProcessorAffinity = new IntPtr(benchmark.Job.Affinity.Value); } var lines = new List <string>(); string line; while ((line = process.StandardOutput.ReadLine()) != null) { logger?.WriteLine(line); if (!line.StartsWith("//") && !string.IsNullOrEmpty(line)) { lines.Add(line); } if (compositeDiagnoser == null) { continue; } // This is important so the Diagnoser can know the [Benchmark] methods will have run and (e.g.) it can do a Memory Dump if (diagnosticsAlreadyRun == false && line.StartsWith(IterationMode.MainWarmup.ToString())) { try { compositeDiagnoser.AfterBenchmarkHasRun(benchmark, process); } finally { // Always set this, even if something went wrong, otherwise we will try on every run of a benchmark batch diagnosticsAlreadyRun = true; } } } if (process.HasExited && process.ExitCode != 0) { if (logger != null) { logger.WriteError( $"Something bad happened during the execution of {exeName}. Try to run the benchmark again using an AnyCPU application\n"); } else { if (exeName.ToLowerInvariant() == "msbuild") { Console.WriteLine("Build failed"); } } return(new ExecuteResult(true, new string[0])); } return(new ExecuteResult(true, lines)); }
public static HelpConfiguration ParseHelp(ITokenStream stream, ILogger logger, string suffix = "") { var key = "help" + suffix; if (!stream.Starts(key)) { return(null); } string text = null; var inputHelpTexts = new List <InputHelpText>(); while (true) { if (stream.Ends(key, logger, out var row, out var token0)) { break; } if (row.Length < 3 || row[1].Value != "=") { logger?.WriteLine($"Error: Malformed assignment at {stream.Path}:{stream.Line}."); stream.Move(); continue; } var rest = string.Join(" ", row.Skip(2)); if (token0 == "text") { text = rest; } else if (Enum.TryParse(token0, true, out HelpKey helpKey)) { inputHelpTexts.Add(new InputHelpText(helpKey, rest)); } else { logger?.WriteLine($"Warning: Invalid symbol '{token0}' at {stream.Path}:{stream.Line}."); } stream.Move(); } return(new HelpConfiguration(text, inputHelpTexts)); }
private static (IImageWriter <MutableByteImage>, bool throwMe) SetOutput(CommonOptions commonOptions, ILogger logger, IMutableImageFactory <MutableByteImage> factory) { if (commonOptions.UseOutputPipe) { return(new ImageStreamWriter <MutableByteImage>(logger, factory, Console.OpenStandardOutput()), false); } if (!string.IsNullOrWhiteSpace(commonOptions.OutputFolder) && !string.IsNullOrWhiteSpace(commonOptions.OutputFile)) { return(new ImageFileWriter <MutableByteImage>(commonOptions.OutputFile, commonOptions.OutputFolder, factory), false); } logger?.WriteLine("No Output Mode defined", Verbosity.Error); logger?.WriteLine("Consider specifying --UseOutputPipe or --OutputFolder and --OutputFile", Verbosity.Error); logger?.WriteLine("", Verbosity.Error); return(null, true); }
private static (IImageReader <MutableByteImage>, bool throwMe) SetInput(CommonOptions commonOptions, IMutableImageFactory <MutableByteImage> factory, ILogger logger) { if (commonOptions.UseInputPipe) { var inputSize = commonOptions.InputSize; if (string.IsNullOrWhiteSpace(inputSize)) { throw new ArgumentException("Inputsize must be defined for inputpipes "); } var wh = Regex.Split(inputSize, "[^0-9]"); int.TryParse(wh[0], out int width); int.TryParse(wh[1], out int height); return(new ImageStreamReader <MutableByteImage>( logger, factory, Console.OpenStandardOutput(width * height * 3), width, height, PixelFormat.Format24bppRgb), false); } if (commonOptions.InputFiles != null && commonOptions.InputFiles.Count() > 0) { return(new ImageMutliFileOrderedReader <MutableByteImage>(logger, factory, new ReaderOptions { Files = commonOptions.InputFiles.ToArray() }), false); } if (!string.IsNullOrWhiteSpace(commonOptions.InputFolder)) { logger?.WriteLine("Currently only *.jpg input supported", Verbosity.Warning); if (!Directory.Exists(commonOptions.InputFolder)) { logger?.WriteLine($"InputFolder does not exist {commonOptions.InputFolder}", Verbosity.Warning); } return(new ImageMutliFileOrderedReader <MutableByteImage>(logger, factory, new ReaderOptions { FolderName = commonOptions.InputFolder, Filter = commonOptions.InputFilter }), false); } logger?.WriteLine("No Input Mode defined", Verbosity.Error); return(null, true); }
public void DisplayResults(ILogger logger) { foreach (var diagnoser in diagnosers) { // TODO when Diagnosers/Diagnostis are wired up properly, instead of the Type name, // print the name used on the cmd line, i.e. -d=<NAME> logger.WriteLineHeader($"// * Diagnostic Output - {diagnoser.GetType().Name} *"); diagnoser.DisplayResults(logger); logger.WriteLine(); } }
public static void PrintCommonColumns(this SummaryTable table, ILogger logger) { var commonColumns = table.Columns.Where(c => !c.NeedToShow && !c.IsDefault).ToArray(); if (commonColumns.Any()) { var paramsOnLine = 0; foreach (var column in commonColumns) { logger.WriteInfo($"{column.Header}={column.Content[0]} "); paramsOnLine++; if (paramsOnLine == 3) { logger.WriteLine(); paramsOnLine = 0; } } if (paramsOnLine != 0) logger.WriteLine(); } }
public void ExportToLog(Summary summary, ILogger logger) { if (summary.Reports.Length > 0) { foreach (var r in summary.Reports) { try { var log = new Dictionary <string, object> { { "short_message", r.BenchmarkCase.DisplayInfo }, { "host", this.HostName }, { "_time_taken_median_ns", r.ResultStatistics.Median }, { "_time_taken_mean_ns", r.ResultStatistics.Mean }, { "_bytes_allocated", r.GcStats.BytesAllocatedPerOperation }, { "_gen0_collections", r.GcStats.Gen0Collections }, { "_gen1_collections", r.GcStats.Gen1Collections }, { "_gen2_collections", r.GcStats.Gen2Collections }, { "_total_operations", r.GcStats.TotalOperations }, { "_env", this.env }, { "_platform", this.platform }, { "_p", this.product }, { "_facility", "benchmark" }, }; var inputString = JsonConvert.SerializeObject(log); logger?.WriteLine(inputString); if (this.Enabled) { var bytes = Encoding.UTF8.GetBytes(inputString); this.udpClient.Send(bytes, bytes.Length); } } catch (Exception ex) { logger?.WriteLine(LogKind.Error, ex.ToString()); } } } }
public override void ExportToLog(Summary summary, ILogger logger) { logger.WriteLine(string.Join(";", columns.Select(c => c.Title))); foreach (var report in summary.Reports) { foreach (var measurement in report.AllMeasurements) { for (int i = 0; i < columns.Length; ) { logger.Write(columns[i].GetValue(summary, report, measurement)); if (++i < columns.Length) { logger.Write(";"); } } logger.WriteLine(); } } }
public static void PrintLine(this SummaryTable table, string[] line, ILogger logger, string leftDel, string rightDel) { for (int columnIndex = 0; columnIndex < table.ColumnCount; columnIndex++) { if (table.Columns[columnIndex].NeedToShow) { logger.WriteStatistic(BuildStandardText(table, line, leftDel, rightDel, columnIndex)); } } logger.WriteLine(); }
public override void ExportToLog(Summary summary, ILogger logger) { logger.WriteLine("...."); foreach (var infoLine in HostEnvironmentInfo.GetCurrent().ToFormattedString()) { logger.WriteLineInfo(infoLine); } logger.WriteLineInfo(summary.JobRuntimes); logger.WriteLine(); PrintTable(summary.Table, logger); var benchmarksWithTroubles = summary.Reports .Where(r => !r.GetResultRuns().Any()) .Select(r => r.Benchmark) .ToList(); if (benchmarksWithTroubles.Count > 0) { logger.WriteLine(); logger.WriteLine("[WARNING]"); logger.WriteLineError(".Benchmarks with issues"); logger.WriteLine("===="); foreach (var benchmarkWithTroubles in benchmarksWithTroubles) logger.WriteLineError("* " + benchmarkWithTroubles.DisplayInfo); logger.WriteLine("===="); } }
protected virtual void SliceMesh(PrintMeshAssembly meshes, out PlanarSliceStack slices, double layerHeight) { logger?.WriteLine("Slicing..."); // Do slicing MeshPlanarSlicer slicer = new MeshPlanarSlicer() { LayerHeightMM = layerHeight, }; slicer.Add(meshes); slices = slicer.Compute(); }
private void SliceMesh(PrintMeshAssembly meshes, out PlanarSliceStack slices) { logger?.WriteLine("Slicing..."); // Do slicing MeshPlanarSlicer slicer = new MeshPlanarSlicer() { LayerHeightMM = Settings.LayerHeightMM }; slicer.Add(meshes); slices = slicer.Compute(); }
private async System.Threading.Tasks.Task InitAsync() { try { logger = await this.GetMefServiceAsync <ILogger>(); logger.WriteLine(Resources.Strings.Daemon_Initializing); await DisableRuleCommand.InitializeAsync(this, logger); await CFamilyReproducerCommand.InitializeAsync(this, logger); cFamilyPreCompiledHeadersEventListener = await this.GetMefServiceAsync <IPreCompiledHeadersEventListener>(); LegacyInstallationCleanup.CleanupDaemonFiles(logger); } catch (Exception ex) when(!ErrorHandler.IsCriticalException(ex)) { logger?.WriteLine(Resources.Strings.ERROR_InitializingDaemon, ex); } logger?.WriteLine(Resources.Strings.Daemon_InitializationComplete); }
public void Start(int pollIntervalInSeconds, IDataAccess dal, ILogger logger) { while (true) { try { var batch = dal.DequeueTransform(); if (batch.Count > 0) { var docsToUpsert = new Dictionary<string, string> (); foreach (var rootId in batch) { var allRows = dal.GetRows (rootId); JObject finalDoc = CombineRows (rootId, allRows); if (finalDoc != null) { finalDoc ["_transformed_on"] = DateTime.Now; string doc = JsonConvert.SerializeObject (finalDoc); docsToUpsert.Add (rootId, doc); } } dal.UpsertDocuments(docsToUpsert); logger.WriteLine ("Transformed {0}...", batch.Count); } else { Thread.Sleep (pollIntervalInSeconds * 1000); } _backoff = 1; } catch (Exception ex) { if (_backoff < 5) { _backoff++; } logger.WriteLine (ex.ToString ()); Debug.WriteLine (ex.ToString ()); Thread.Sleep (_backoff * 1000); } } }
public PID this[PIDCode pidCode] { get { var pid = PID.GetPID(pidCode); if (pid == null) // not registered in PID.cs { Logger?.WriteLine($"{pidCode} not found in static PID list (PID.cs)"); } return(pid); } }
public RulesSettings SafeLoad(string filePath) { RulesSettings settings = null; if (!fileSystem.File.Exists(filePath)) { logger?.WriteLine(CoreStrings.Settings_NoSettingsFile, filePath); } else { try { logger?.WriteLine(CoreStrings.Settings_LoadedSettingsFile, filePath); var data = fileSystem.File.ReadAllText(filePath); settings = JsonConvert.DeserializeObject <RulesSettings>(data); } catch (Exception ex) when(!ErrorHandler.IsCriticalException(ex)) { logger?.WriteLine(CoreStrings.Settings_ErrorLoadingSettingsFile, filePath, ex.Message); } } return(settings); }
public void Connect(MailServer host) { Host = host; _client = new TcpClient(Host.Server, Host.Port); try { _stream = new SslStream(_client.GetStream()); ((SslStream)_stream).AuthenticateAsClient(Host.Server); } catch (Exception) { _client.Close(); _client = new TcpClient(Host.Server, Host.Port); _stream = _client.GetStream(); } _reader = new StreamReader(_stream); _writer = new StreamWriter(_stream); _responseManager = new ResponseManager(_reader); _logger?.WriteLine("S:\t" + GetResponse()); SendCommand(string.Format("{0} {1}", SmtpCommands.HelloExtended, Dns.GetHostName()), 250); }
public void Start(int pollIntervalInSeconds, IDataAccess dal, ILogger logger) { while (true) { var tables = dal.GetAllTables(); int rc = 0; foreach (Table t in tables.OrderByDescending(t => t.Prefetch)) { try { int rowCount = 0; var changedRows = dal.Extract (t); if(changedRows.Count > 0) { logger.WriteLine ("Extracting {0} from {1}...", changedRows.Count, t); } foreach (var changedRow in changedRows) { t.MaxExtractedVersion = (byte[])changedRow ["Version"]; changedRow ["_extracted_on"] = DateTime.Now; changedRow ["_environment"] = t.Environment; if (t.Prefetch) { // prefetched data needs to be updated in cache when it changes Cache.Set (t.Environment, t.Name, t.GetKey (changedRow), changedRow); } dal.UpsertRow (t, changedRow); dal.PersistVersion (t); rowCount++; } rc += rowCount; } catch (Exception ex) { Console.WriteLine(ex.ToString()); Debug.WriteLine(ex.ToString()); } } if (rc == 0) { Thread.Sleep(pollIntervalInSeconds*1000); } } }
protected override void OnLoadOptions(string key, Stream stream) { // TODO: investigate why this method is called before package.Initialize // has completed. Calling base.Initialize causes this method to be called, // before the rest of the Initialize method has completed i.e. before the // logger has been retrieved. // This method is then called a second time, after Initialize has completed. if (key != SonarLintDataKey) { return; } try { if (stream.Length > 0) { logger?.WriteLine("Binding: reading binding information from the .suo file"); var data = formatter.Deserialize(stream); var boundProject = JsonHelper.Deserialize <BoundSonarQubeProject>(data as string); var configuration = BindingConfiguration.CreateBoundConfiguration(boundProject, isLegacy: false); InMemoryConfigurationProvider.Instance.WriteConfiguration(configuration); logger?.WriteLine(GetBindingAsText(configuration)); } else { logger?.WriteLine("Binding: no binding information found in the .suo file"); } } catch (Exception ex) { logger?.WriteLine($"Failed to read binding data from the .suo file: {ex.Message}"); } }
private void HandleActiveSolutionChanged(object sender, ActiveSolutionChangedEventArgs e) { try { // Stop the daemon running when a solution is closed if (!e.IsSolutionOpen) { this.daemon.Stop(); } } catch (Exception ex) when(!ErrorHandler.IsCriticalException(ex)) { logger?.WriteLine(Strings.ERROR_StoppingDaemon, ex); } }
public static void InstallModLoader(IParkitect parkitect, ILogger logger) { if (parkitect == null) throw new ArgumentNullException(nameof(parkitect)); if (logger == null) throw new ArgumentNullException(nameof(logger)); try { InstallModLoaderFile(parkitect, "ParkitectNexus.Mod.ModLoader", "dll"); } catch (Exception e) { logger.WriteLine("Failed to install mod loader.", LogLevel.Warn); logger.WriteException(e, LogLevel.Warn); } }
public override void ExportToLog(Summary summary, ILogger logger) { foreach (var line in summary.Table.FullContentWithHeader) { for (int i = 0; i < line.Length;) { logger.Write(CsvHelper.Escape(line[i])); if (++i < line.Length) { logger.Write(separator); } } logger.WriteLine(); } }
internal static async Task StartAsync(string name, string endpoint, string nsEndpoint, ILog log, bool alsoLogToConsole) { Logger = new Log4NetLogger(log); if (alsoLogToConsole) { Logger = new MultiLogger(Logger, new ConsoleLogger()); } Logger?.WriteLine($"{name} has started."); LS = new LoggerServer(name, endpoint, nsEndpoint, Logger); await LS.RegisterAsync(LS.VTS); while (!LS.IsRegistered) { } await LS.StartAsync(endpoint); }
async void OnUploadTrip(object sender, EventArgs e) { if (trips.SelectedItem is Trip trip) { string file = Path.Combine(TripViewModel.PersonalPath, trip.FileName) + ".csv"; if (await DisplayAlert("CarAssist", "Sollen die Daten zu ThingSpeak hochgeladen werden?", "Ja", "Nein") == true) { string result = await UploadTrip(file); _logger?.WriteLine(result); } if (await DisplayAlert("CarAssist", "Sollen die Daten in Ihre OwnCloud hochgeladen werden?", "Ja", "Nein") == true) { UploadTripToOwnCloud(file); } } }
public override void ExportToLog(Summary summary, ILogger logger) { foreach (var report in summary.Reports) { var runs = report.AllMeasurements; var modes = runs.Select(it => it.IterationMode).Distinct(); logger.WriteLineHeader($"*** {report.Benchmark.DisplayInfo} ***"); logger.WriteLineHeader("* Raw *"); foreach (var run in runs) logger.WriteLineResult(run.ToStr()); foreach (var mode in modes) { logger.WriteLine(); logger.WriteLineHeader($"* Statistics for {mode}"); logger.WriteLineStatistic(runs.Where(it => it.IterationMode == mode).GetStatistics().ToTimeStr()); } } }
internal static void Start() { var name = Args.Value(Constants.Name); var nsEndpoint = Args.Value(Constants.NameServerEndpoint); var timeSimulator = new TimeSimulator(); int year = Args.Value(Constants.Year).To <int>(); int month = Args.Value(Constants.Month).To <int>(); int day = Args.Value(Constants.Day).To <int>(); int timeMultiplier = Args.Value(Constants.TimeMultiplier).To <int>(); int duration = Args.Value(Constants.Duration).To <int>(); Logger = new LoggerClient(Args.Value(Constants.LoggerServerName), name, nsEndpoint); var client = new DiseaseSimulatorClient(name, nsEndpoint, Logger) { Client = new RequestClient(true, false) }; Logger?.WriteLine($"{Constants.Year}: {year}", client.SystemRegistration.Id); Logger?.WriteLine($"{Constants.Month}: {month}", client.SystemRegistration.Id); Logger?.WriteLine($"{Constants.Day}: {day}", client.SystemRegistration.Id); Logger?.WriteLine($"{Constants.TimeMultiplier}: {timeMultiplier}", client.SystemRegistration.Id); Logger?.WriteLine($"{Constants.Duration}: {duration}", client.SystemRegistration.Id); Logger?.WriteLine($"{name} has started."); Console.WriteLine("Simulator: " + name); string endpoint = Args.Value(Constants.Endpoint); Logger?.WriteLine($"{Constants.Endpoint}: {endpoint}"); var startDate = new DateTime(year, month, day); Logger?.WriteLine($"{Constants.StartDate}: {startDate.ToLongDateString()}"); var reportAction = new ReportAction(client.SystemRegistration, timeSimulator, new Random(), new DiseaseRecordGenerator(), client, endpoint); timeSimulator.Start(startDate, timeMultiplier, duration, reportAction.Action); timeSimulator.Wait(); }
/// <summary> /// Entry point for your mod. /// </summary> public async void Start(IModLoaderV1 loader) { _modLoader = (IModLoader)loader; _logger = (ILogger)_modLoader.GetLogger(); _modLoader.GetController <IReloadedHooks>().TryGetTarget(out _hooks); /* Your mod code starts here. */ SDK.Init(_hooks, s => { _logger.WriteLine(s); }); await ImguiHook.Create(RenderTestWindow, new ImguiHookOptions() { EnableViewports = true, IgnoreWindowUnactivate = true, Implementations = new List <IImguiHook>() { new ImguiHookDx9(), new ImguiHookDx11() } }).ConfigureAwait(false); }
public override void ExportToLog(Summary summary, ILogger logger) { if (useCodeBlocks) logger.WriteLine($"```{codeBlocksSyntax}"); logger = new LoggerWithPrefix(logger, prefix); logger.WriteLineInfo(EnvironmentHelper.GetCurrentInfo().ToFormattedString("Host")); logger.NewLine(); PrintTable(summary.Table, logger); // TODO: move this logic to an analyser var benchmarksWithTroubles = summary.Reports.Values.Where(r => !r.GetResultRuns().Any()).Select(r => r.Benchmark).ToList(); if (benchmarksWithTroubles.Count > 0) { logger.NewLine(); logger.WriteLineError("Benchmarks with troubles:"); foreach (var benchmarkWithTroubles in benchmarksWithTroubles) logger.WriteLineError(" " + benchmarkWithTroubles.ShortInfo); } }
/// <summary> /// Installs the parkitectnexus:// protocol. /// </summary> public static void Install(ILogger logger) { try { // Find the path the the client application. var appPath = Assembly.GetEntryAssembly().Location; // Create registry keys in the classes tree for the parkitectnexus:// protocol. var parkitectNexus = Registry.CurrentUser?.CreateSubKey(@"Software\Classes\parkitectnexus"); parkitectNexus?.SetValue("", "ParkitectNexus Client"); parkitectNexus?.SetValue("URL Protocol", ""); parkitectNexus?.CreateSubKey(@"DefaultIcon")?.SetValue("", $"{appPath},0"); parkitectNexus?.CreateSubKey(@"shell\open\command")?.SetValue("", $"\"{appPath}\" --url \"%1\""); } catch (Exception e) { logger.WriteLine("Failed to install parkitectnexus:// protocol.", LogLevel.Fatal); logger.WriteException(e); } }
private static void PrintTable(SummaryTable table, ILogger logger) { if (table.FullContent.Length == 0) { logger.WriteLine("[WARNING]"); logger.WriteLine("===="); logger.WriteLineError("There are no benchmarks found "); logger.WriteLine("===="); logger.WriteLine(); return; } table.PrintCommonColumns(logger); logger.WriteLine("...."); logger.WriteLine("[options=\"header\"]"); logger.WriteLine("|==="); table.PrintLine(table.FullHeader, logger, "|", string.Empty); foreach (var line in table.FullContent) table.PrintLine(line, logger, "|", string.Empty); logger.WriteLine("|==="); }
public override void ExportToLog(Summary summary, ILogger logger) { var columns = lazyColumns.Value; logger.WriteLine(string.Join(Separator, columns.Select(c => CsvHelper.Escape(c.Title)))); foreach (var report in summary.Reports) { foreach (var measurement in report.AllMeasurements) { for (int i = 0; i < columns.Length; ) { logger.Write(CsvHelper.Escape(columns[i].GetValue(summary, report, measurement))); if (++i < columns.Length) { logger.Write(Separator); } } logger.WriteLine(); } } }
public ExecuteResult Execute(BuildResult buildResult, Benchmark benchmark, ILogger logger, IResolver resolver, IDiagnoser diagnoser) { logger.WriteLine("Executing"); Done = true; return new ExecuteResult(true, 0, new string[0], new string[0]); }
internal void PrintOptions(ILogger logger, int prefixWidth, int outputWidth) { foreach (var option in configuration) { var optionText = $" {optionPrefix}{option.Key} <{option.Key.ToUpperInvariant()}>"; logger.WriteResult($"{optionText.PadRight(prefixWidth)}"); var maxWidth = outputWidth - prefixWidth - Environment.NewLine.Length - breakText.Length; var lines = StringAndTextExtensions.Wrap(option.Value, maxWidth); if (lines.Count == 0) { logger.WriteLine(); continue; } logger.WriteLineInfo($"{breakText}{lines.First().Trim(trimChars)}"); var padding = new string(' ', prefixWidth); foreach (var line in lines.Skip(1)) logger.WriteLineInfo($"{padding}{breakText}{line.Trim(trimChars)}"); } }
private static Summary Run(Benchmark[] benchmarks, ILogger logger, string title, IConfig config, string rootArtifactsFolderPath, Func<IJob, IToolchain> toolchainProvider) { logger.WriteLineHeader("// ***** BenchmarkRunner: Start *****"); logger.WriteLineInfo("// Found benchmarks:"); foreach (var benchmark in benchmarks) logger.WriteLineInfo($"// {benchmark.ShortInfo}"); logger.WriteLine(); var validationErrors = Validate(benchmarks, logger, config); if (validationErrors.Any(validationError => validationError.IsCritical)) { return Summary.CreateFailed(benchmarks, title, HostEnvironmentInfo.GetCurrent(), config, GetResultsFolderPath(rootArtifactsFolderPath), validationErrors); } var globalChronometer = Chronometer.Start(); var reports = new List<BenchmarkReport>(); foreach (var benchmark in benchmarks) { var report = Run(benchmark, logger, config, rootArtifactsFolderPath, toolchainProvider); reports.Add(report); if (report.GetResultRuns().Any()) logger.WriteLineStatistic(report.GetResultRuns().GetStatistics().ToTimeStr()); logger.WriteLine(); } var clockSpan = globalChronometer.Stop(); var summary = new Summary(title, reports, HostEnvironmentInfo.GetCurrent(), config, GetResultsFolderPath(rootArtifactsFolderPath), clockSpan.GetTimeSpan(), validationErrors); logger.WriteLineHeader("// ***** BenchmarkRunner: Finish *****"); logger.WriteLine(); logger.WriteLineHeader("// * Export *"); var currentDirectory = Directory.GetCurrentDirectory(); foreach (var file in config.GetCompositeExporter().ExportToFiles(summary)) { logger.WriteLineInfo($" {file.Replace(currentDirectory, string.Empty).Trim('/', '\\')}"); } logger.WriteLine(); logger.WriteLineHeader("// * Detailed results *"); // TODO: make exporter foreach (var report in reports) { logger.WriteLineInfo(report.Benchmark.ShortInfo); logger.WriteLineStatistic(report.GetResultRuns().GetStatistics().ToTimeStr()); logger.WriteLine(); } LogTotalTime(logger, clockSpan.GetTimeSpan()); logger.WriteLine(); logger.WriteLineHeader("// * Summary *"); MarkdownExporter.Console.ExportToLog(summary, logger); // TODO: make exporter var warnings = config.GetCompositeAnalyser().Analyse(summary).ToList(); if (warnings.Count > 0) { logger.WriteLine(); logger.WriteLineError("// * Warnings * "); foreach (var warning in warnings) logger.WriteLineError($"{warning.Message}"); } if (config.GetDiagnosers().Count() > 0) { logger.WriteLine(); config.GetCompositeDiagnoser().DisplayResults(logger); } logger.WriteLine(); logger.WriteLineHeader("// ***** BenchmarkRunner: End *****"); return summary; }
private static List<ExecuteResult> Execute(ILogger logger, Benchmark benchmark, IToolchain toolchain, BuildResult buildResult, IConfig config) { var executeResults = new List<ExecuteResult>(); logger.WriteLineInfo("// *** Execute ***"); var launchCount = Math.Max(1, benchmark.Job.LaunchCount.IsAuto ? 2 : benchmark.Job.LaunchCount.Value); for (int processNumber = 0; processNumber < launchCount; processNumber++) { var printedProcessNumber = (benchmark.Job.LaunchCount.IsAuto && processNumber < 2) ? "" : " / " + launchCount.ToString(); logger.WriteLineInfo($"// Launch: {processNumber + 1}{printedProcessNumber}"); var executeResult = toolchain.Executor.Execute(buildResult, benchmark, logger); if (!executeResult.FoundExecutable) logger.WriteLineError("Executable not found"); executeResults.Add(executeResult); var measurements = executeResults .SelectMany(r => r.Data) .Select(line => Measurement.Parse(logger, line, 0)) .Where(r => r.IterationMode != IterationMode.Unknown). ToArray(); if (!measurements.Any()) { // Something went wrong during the benchmark, don't bother doing more runs logger.WriteLineError($"No more Benchmark runs will be launched as NO measurements were obtained from the previous run!"); break; } if (benchmark.Job.LaunchCount.IsAuto && processNumber == 1) { var idleApprox = new Statistics(measurements.Where(m => m.IterationMode == IterationMode.IdleTarget).Select(m => m.Nanoseconds)).Median; var mainApprox = new Statistics(measurements.Where(m => m.IterationMode == IterationMode.MainTarget).Select(m => m.Nanoseconds)).Median; var percent = idleApprox / mainApprox * 100; launchCount = (int)Math.Round(Math.Max(2, 2 + (percent - 1) / 3)); // an empirical formula } } logger.WriteLine(); // Do a "Diagnostic" run, but DISCARD the results, so that the overhead of Diagnostics doesn't skew the overall results if (config.GetDiagnosers().Count() > 0) { logger.WriteLineInfo($"// Run, Diagnostic"); config.GetCompositeDiagnoser().Start(benchmark); var executeResult = toolchain.Executor.Execute(buildResult, benchmark, logger, config.GetCompositeDiagnoser()); var allRuns = executeResult.Data.Select(line => Measurement.Parse(logger, line, 0)).Where(r => r.IterationMode != IterationMode.Unknown).ToList(); var report = new BenchmarkReport(benchmark, null, null, new[] { executeResult }, allRuns); config.GetCompositeDiagnoser().Stop(benchmark, report); if (!executeResult.FoundExecutable) logger.WriteLineError("Executable not found"); logger.WriteLine(); } return executeResults; }
private static BuildResult Build(ILogger logger, IToolchain toolchain, GenerateResult generateResult, Benchmark benchmark) { logger.WriteLineInfo("// *** Build ***"); var buildResult = toolchain.Builder.Build(generateResult, logger, benchmark); if (buildResult.IsBuildSuccess) { logger.WriteLineInfo("// Result = Success"); } else { logger.WriteLineError("// Result = Failure"); if (buildResult.BuildException != null) logger.WriteLineError($"// Exception: {buildResult.BuildException.Message}"); } logger.WriteLine(); return buildResult; }
private static GenerateResult Generate(ILogger logger, IToolchain toolchain, Benchmark benchmark, string rootArtifactsFolderPath, IConfig config) { logger.WriteLineInfo("// *** Generate *** "); var generateResult = toolchain.Generator.GenerateProject(benchmark, logger, rootArtifactsFolderPath, config); if (generateResult.IsGenerateSuccess) { logger.WriteLineInfo("// Result = Success"); logger.WriteLineInfo($"// {nameof(generateResult.ArtifactsPaths.BinariesDirectoryPath)} = {generateResult.ArtifactsPaths?.BinariesDirectoryPath}"); } else { logger.WriteLineError("// Result = Failure"); if (generateResult.GenerateException != null) logger.WriteLineError($"// Exception: {generateResult.GenerateException.Message}"); } logger.WriteLine(); return generateResult; }
private void PrintTable(SummaryTable table, ILogger logger) { if (table.FullContent.Length == 0) { logger.WriteLineError("There are no benchmarks found "); logger.WriteLine(); return; } table.PrintCommonColumns(logger); logger.WriteLine(); if (useCodeBlocks) { logger.Write("```"); logger.WriteLine(); } table.PrintLine(table.FullHeader, logger, string.Empty, " |"); logger.WriteLineStatistic(string.Join("", table.Columns.Where(c => c.NeedToShow).Select(c => new string('-', c.Width) + " |"))); var rowCounter = 0; var highlightRow = false; foreach (var line in table.FullContent) { // Each time we hit the start of a new group, alternative the colour (in the console) or display bold in Markdown if (table.FullContentStartOfGroup[rowCounter]) { highlightRow = !highlightRow; } table.PrintLine(line, logger, string.Empty, " |", highlightRow, table.FullContentStartOfGroup[rowCounter], startOfGroupInBold); rowCounter++; } }
/// <summary> /// The usage. /// </summary> /// <param name="logger"> /// The logger. /// </param> /// <param name="extraInfo"> /// The extra info. /// </param> protected void Usage(ILogger logger, string extraInfo) { logger.WriteLine(LogLevel.Msg, string.Empty); logger.Write(LogLevel.Msg, " {0,-20}:", this.Name); this.PrintParagraph(logger, this.Description, true); // Print extra info ( if we have any ) if (!string.IsNullOrEmpty(extraInfo)) { logger.WriteLine(LogLevel.Msg, string.Empty); this.PrintParagraph(logger, extraInfo, false); } // Print info if this argument is Required. if (this.Required) { logger.WriteLine(LogLevel.Msg, string.Empty); this.PrintParagraph(logger, "Required.", false); } // Print valid values. if (this.ArgumentValidValues.Count > 0) { logger.WriteLine(LogLevel.Msg, string.Empty); logger.Write(LogLevel.Msg, "{0,23}", " "); logger.WriteLine( LogLevel.Msg, "Valid Values:[{0}]", string.Join(",", (string[])this.ArgumentValidValues.ToArray(typeof(string)))); } // Print default values. if (this.ArgumentDefaults.Count > 0) { logger.WriteLine(LogLevel.Msg, string.Empty); logger.Write(LogLevel.Msg, "{0,23}", " "); logger.WriteLine( LogLevel.Msg, "Default:[{0}]", string.Join(",", (string[])this.ArgumentDefaults.ToArray(typeof(string)))); } }
/// <summary> /// The print paragraph. /// </summary> /// <param name="logger"> /// The logger. /// </param> /// <param name="text"> /// The text. /// </param> /// <param name="doNotIndentFirstLine"> /// The do not indent first line. /// </param> private void PrintParagraph(ILogger logger, string text, bool doNotIndentFirstLine) { string line = string.Empty; bool firstTime = doNotIndentFirstLine; string[] words = text.Split(new[] { ' ' }); foreach (string word in words) { if (!string.IsNullOrEmpty(word)) { if (line.Length + 1 + word.Length > 35) { // Print current line, and start // a new line. if (!firstTime) { logger.Write(LogLevel.Msg, "{0,23}", " "); } logger.WriteLine(LogLevel.Msg, line); line = word + " "; firstTime = false; } else { // We add the current word into the line. line += word + " "; } } } // Print last line. if (!firstTime) { logger.Write(LogLevel.Msg, "{0,23}", " "); } logger.WriteLine(LogLevel.Msg, line); }
public override void ExportToLog(Summary summary, ILogger logger) { foreach (var line in summary.Table.FullContentWithHeader) logger.WriteLine(string.Join(";", line)); }