private Ty Await_User_Input() { string userInput = string.Empty; try { InputContext = ConsoleInput.Capture(Pre_Handle_Input_Key); while (true) { List <string> opts = Get_Valid_Options()?.ToList(); if (!ReferenceEquals(opts, null) && opts.Count > 0) { string strOpts = string.Join(", ", opts); xLogEngine.Console(string.Concat(ANSI.WhiteBright("Options: "), ANSI.White(strOpts))); Update(); } try { UserInputSignal.Wait(taskCancel.Token); } catch (OperationCanceledException) {/* Ignore */ Set_Input(string.Empty); return(default);
static void Main(string[] args) { Console.WriteLine("Generate ANSI table ..."); ANSI ascii = new ANSI(); ascii.WriteToFile(); Console.WriteLine("ANSI table generated."); Console.WriteLine("Start encoding " + fileToCompress + " ..."); string text = File.ReadAllText(fileToCompress, System.Text.ASCIIEncoding.Default); LZWEncoder encoder = new LZWEncoder(); byte[] b = encoder.EncodeToByteList(text); File.WriteAllBytes(encodedFile, b); Console.WriteLine("File " + fileToCompress + " encoded to " + encodedFile); Console.WriteLine("Start decoding " + encodedFile); LZWDecoder decoder = new LZWDecoder(); byte[] bo = File.ReadAllBytes(encodedFile); string decodedOutput = decoder.DecodeFromCodes(bo); File.WriteAllText(decodedFile, decodedOutput, System.Text.Encoding.Default); Console.WriteLine("File " + encodedFile + " decoded to " + decodedFile); }
public async Task BomScan(Encoding enc) { var data = Enumerable.Range(0, byte.MaxValue).Select(x => ANSI.GetChars(new byte[] { (byte)x })[0]).ToArray(); var encodedBytes = (enc.GetPreamble().AsBucket() + enc.GetBytes(data).AsBucket()).ToArray(); for (int i = 1; i < encodedBytes.Length - 1; i++) { var encSpan = encodedBytes.AsMemory(); var b = encSpan.Slice(0, i).ToArray().AsBucket() + encSpan.Slice(i).ToArray().AsBucket(); BucketBytes bb = await b.ConvertToUtf8(enc).ReadFullAsync(1024); Assert.AreEqual(Escape(new String(data)), Escape(bb.ToUTF8String()), $"Convert Iteration {i}"); if (enc is UnicodeEncoding u && !u.GetPreamble().Any()) { continue; // Unicode without preamble not detectable without scan via .Peek() } b = encSpan.Slice(0, i).ToArray().AsBucket() + encSpan.Slice(i).ToArray().AsBucket(); bb = await b.NormalizeToUtf8().ReadFullAsync(1024); Assert.AreEqual(Escape(new String(data)), Escape(bb.ToUTF8String()), $"Normalize Iteration {i}"); } }
/// <summary> /// Inline processing /// </summary> /// <param name="i"></param> /// <returns></returns> protected string ProcessInline(MarkdownInline i) { string para = string.Empty; switch (i.Type) { //case MarkdownInlineType.Comment: // break; //case MarkdownInlineType.TextRun: // break; case MarkdownInlineType.Bold: para += ANSI.WriteMode(ANSICodes.Modes.Bold) + i.ToString().Trim('*') + ANSI.WriteMode(); break; //case MarkdownInlineType.Italic: // break; case MarkdownInlineType.MarkdownLink: MarkdownLinkInline mitLink = (MarkdownLinkInline)i; if (mitLink.Url.ToLower().EndsWith(".md")) { actionsCount++; para += $"{mitLink.Inlines[0]}[{actionsCount}]"; Data.Actions.Add(actionsCount.ToString(), new BBSCodeResult.Action() { module = "MarkdownScreen", data = (mitLink.Url.StartsWith("http") ? "" : basePath) + mitLink.Url }); } else { para += mitLink.ToString(); } break; //case MarkdownInlineType.RawHyperlink: // break; //case MarkdownInlineType.RawSubreddit: // break; //case MarkdownInlineType.Strikethrough: // break; //case MarkdownInlineType.Superscript: // break; //case MarkdownInlineType.Subscript: // break; //case MarkdownInlineType.Code: // break; //case MarkdownInlineType.Image: // break; //case MarkdownInlineType.Emoji: // break; //case MarkdownInlineType.LinkReference: // break; default: para += i.ToString(); break; } return(para); }
public void SendMessage(string message) { this.SendLine("{0}{1}{0} {2}", ANSI.SetColorANSI16("-", ANSI.ANSIColor_16.BrightYellow), ANSI.SetColorANSI16("♦", ANSI.ANSIColor_16.White), ANSI.SetColorANSI16(message, messageColor)); }
public CommandResult <string> NugetDownload( CommandEvaluationContext context, [Parameter(0, "package (.nuget) ID")] string id, [Parameter(1, "package version")] string ver, [Option("o", "output", "output path", true, true)] string @out = ".", [Option("u", "download-url", "nuget server api query service template url", true, true)] string url = DownloadUrl ) { id = id.Trim().ToLower(); ver = ver.ToLower(); var queryString = url .Replace("{LOWER_ID}", id) .Replace("{LOWER_VERSION}", ver); context.Out.Echo(context.ShellEnv.Colors.Log + $"GET {queryString} ... "); using var httpClient = new HttpClient(); using var request = new HttpRequestMessage(new HttpMethod("GET"), queryString); var tsk = httpClient.SendAsync(request); var result = tsk.Result; if (result.IsSuccessStatusCode) { var str = result.Content.ReadAsStreamAsync().Result; context.Out.Echoln(" Done(rdc)"); context.Out.Echo(ANSI.RSTXTA + ANSI.CPL(1) + ANSI.EL(ANSI.ELParameter.p2)); // TODO: add as ANSI combo if (str == null) { context.Warning("result is empty"); } else { var fn = $"{id}.{ver}.nupkg"; @out = Path.Combine(@out, fn); using var fstr = new FileStream(@out, FileMode.Create, FileAccess.Write); int b; while ((b = str.ReadByte()) != -1) { fstr.WriteByte((byte)b); } str.Close(); fstr.Close(); context.Out.Echoln($"package '{fn}' has been downloaded to: {new FilePath(@out)}"); return(new CommandResult <string>(@out)); } } else { context.Errorln($"can't get response content: {result.ReasonPhrase}"); return(new CommandResult <string>(ReturnCode.Error)); } return(new CommandResult <string>(ReturnCode.Error)); }
/// <summary> /// Shows the message and force disconnection /// </summary> public override void Show() { Write(ANSI.ClearScreen()); ShowLines(Header, 0, Header.Count, 1); NameValueCollection netconfig = (NameValueCollection)ConfigurationManager.GetSection("Networking"); int inactivityTimeout = Convert.ToInt32(netconfig["InactivityTimeout"]); client.lastActivity = DateTime.Now.AddSeconds(-(inactivityTimeout - 10)); }
/// <summary> /// Clears all lines of the header /// </summary> protected void ClearHeader() { for (int j = 1; j < dataAreaStart; j++) { if (Data.HasHeaderBackground) { Write(ANSI.WriteBackColor(Data.HeaderBackground)); } ClearLine(j); } }
/// <summary> /// Clears all lines of the footer /// </summary> protected void ClearFooter() { for (int j = dataAreaStart + dataAreaSize; j <= client.screenHeight; j++) { if (Data.HasFooterBackground) { Write(ANSI.WriteBackColor(Data.FooterBackground)); } ClearLine(j); } }
public async Task ConvertBucketToUtf8(Encoding enc) { var data = Enumerable.Range(0, byte.MaxValue).Select(x => ANSI.GetChars(new byte[] { (byte)x })[0]).ToArray(); var encodedBytes = (enc.GetPreamble().AsBucket() + enc.GetBytes(data).AsBucket()).ToArray(); using var b = encodedBytes.AsBucket(); var bb = await b.ConvertToUtf8(enc).ReadFullAsync(1024); Assert.AreEqual(Escape(new String(data)), Escape(bb.ToUTF8String()), Escape(new String(encodedBytes.Select(x => (char)x).ToArray()))); }
/// <summary> /// Sets colors for body line /// </summary> /// <param name="line"></param> protected void setColorLine(int line) { if (line % 2 > 0) { Write(ANSI.WriteBackColor(Data.BodyAlternateBackground)); } else { Write(ANSI.WriteBackColor(ANSI.defaultBackColor)); } }
/// <summary> /// Execute this command. /// </summary> /// <param name="sender">Session attempting to execute this command</param> /// <param name="args">Command parameters</param> public void Execute(Session sender, string[] args) { var users = ChattingState.Who.Values; var msg = string.Join(" ", args); var cyan = ANSI.Color(ANSI.FGColorBit.Cyan); var white = ANSI.Color(ANSI.FGColorBit.White); foreach (var user in users) { user.Write($"{cyan}{sender.User.Username} {msg}{white}{Environment.NewLine}", true); } }
internal static int Output(StringPtr Str) { if (RequiresEmulation) { return(Emulate(Str)); } else { Console.Write(Str); return(ANSI.Strip(Str)?.Length ?? 0); } }
public static void Test() { Widget_Countdown widget = new Widget_Countdown(TimeSpan.FromSeconds(20), ANSI.CyanBright("Countdown")); Task.WaitAll(widget.Get_Task()); using (Widget_Prompt prompt = new Widget_Prompt("Press ANY key to exit.")) { prompt.Wait(); } Environment.Exit(0); }
public void SendSucessMessage(string message, string status) { this.SendFormat("{0}{1}{0} {2}", ANSI.SetColorANSI16("-", ANSI.ANSIColor_16.BrightCyan), ANSI.SetColorANSI16("♦", ANSI.ANSIColor_16.White), ANSI.SetColorANSI16(message.PadRight(60), messageColor)); this.SendFormat("{2}[ {0}{1}{2} ]\r\n", ANSI.ColorANSI16(ANSI.ANSIColor_16.Green), status, ANSI.ClearFormat() ); }
private static bool Execute_XLOG_Command(DataStream <int> ParameterStream) { /* Currently we are only emulating color codes. */ /* XXX: Implement emulation for other codes such as the cursor controls */ XLOG_CODE Code = (XLOG_CODE)Int32.MinValue; if (!ParameterStream.atEnd) { Code = (XLOG_CODE)ParameterStream.Consume(); } switch (Code) { case XLOG_CODE.PUSH_FG: Color_Stack_FG.Push(ANSI.Color_Console_To_ANSI(Console.ForegroundColor)); break; case XLOG_CODE.POP_FG: { if (Color_Stack_FG.Count == 0) { break; } ANSI_COLOR clr = Color_Stack_FG.Pop(); Console.ForegroundColor = ANSI.Color_ANSI_To_Console(clr); } break; case XLOG_CODE.PUSH_BG: Color_Stack_BG.Push(ANSI.Color_Console_To_ANSI(Console.BackgroundColor)); break; case XLOG_CODE.POP_BG: { if (Color_Stack_BG.Count == 0) { break; } ANSI_COLOR clr = Color_Stack_BG.Pop(); Console.BackgroundColor = ANSI.Color_ANSI_To_Console(clr); } break; default: { throw new ArgumentException($"Unrecognized xLOG code: {(XLOG_CODE)Code}"); } } return(true); }
public void Init(CommandEvaluationContext context) { // init settings var branchSymbol = Unicode.EdgeRowLeft; var sepSymbol = Unicode.RightChevron; context.ShellEnv.AddNew(_namespace, VarIsEnabled, true, false); var behindColor = "(b=darkred)"; var aheadColor = ANSI.SGR_SetBackgroundColor8bits(136); var infoColor = ANSI.SGR_SetBackgroundColor8bits(237 /*59*/); context.ShellEnv.AddNew(_namespace, VarInfoBackgroundColor, infoColor); context.ShellEnv.AddNew( _namespace, VarModifiedTextTemplate, $"%bgColor%(f=white) %repoName% {branchSymbol} %branch% %sepSymbol%%errorMessage%{infoColor}+%indexAdded% ~%indexChanges% -%indexDeleted% | ~%worktreeChanges% -%worktreeDeleted% ?%untracked%(rdc) ", false); context.ShellEnv.AddNew( _namespace, VarBehindTextTemplate, $"%bgColor%(f=white) %repoName% {branchSymbol} %branch% %sepSymbol%%errorMessage%{infoColor}+%indexAdded% ~%indexChanges% -%indexDeleted% | ~%worktreeChanges% -%worktreeDeleted% ?%untracked% {behindColor}{Unicode.ArrowDown}%behind%(rdc) ", false); context.ShellEnv.AddNew( _namespace, VarAheadBehindTextTemplate, $"%bgColor%(f=white) %repoName% {branchSymbol} %branch% %sepSymbol%%errorMessage%{infoColor}+%indexAdded% ~%indexChanges% -%indexDeleted% | ~%worktreeChanges% -%worktreeDeleted% ?%untracked% {aheadColor}{Unicode.ArrowUp}%ahead%{behindColor}{Unicode.ArrowDown}%behind%(rdc) ", false); context.ShellEnv.AddNew( _namespace, VarAheadTextTemplate, $"%bgColor%(f=white) %repoName% {branchSymbol} %branch% %sepSymbol%%errorMessage%{infoColor}+%indexAdded% ~%indexChanges% -%indexDeleted% | ~%worktreeChanges% -%worktreeDeleted% ?%untracked% {aheadColor}{Unicode.ArrowUp}%ahead%(rdc) ", false); context.ShellEnv.AddNew( _namespace, VarTextTemplateNoData, $"%bgColor%(f=white) %repoName% {branchSymbol} %branch% %errorMessage%(rdc) ", false); context.ShellEnv.AddNew( _namespace, VarTextTemplateNoRepository, $"(b=darkblue)(f=white) {sepSymbol} %errorMessage%(rdc) ", false); context.ShellEnv.AddNew(_namespace, VarBehindBackgroundColor, behindColor, false); context.ShellEnv.AddNew(_namespace, VarAheadBackgroundColor, aheadColor, false); context.ShellEnv.AddNew(_namespace, VarUpToDateBackgroundColor, ANSI.SGR_SetBackgroundColor8bits(22), false); context.ShellEnv.AddNew(_namespace, VarModifiedBackgroundColor, ANSI.SGR_SetBackgroundColor8bits(130), false); context.ShellEnv.AddNew(_namespace, VarModifiedUntrackedBackgroundColor, ANSI.SGR_SetBackgroundColor8bits(166), false); context.ShellEnv.AddNew(_namespace, VarUnknownBackgroundColor, "(b=darkblue)", false); }
private static Tuple <ANSI_COLOR, ANSI_COLOR> Get_Console_Default_Colors() { ConsoleColor stackFG = Console.ForegroundColor; ConsoleColor stackBG = Console.BackgroundColor; Console.ResetColor(); ANSI_COLOR fgVal = ANSI.Color_Console_To_ANSI(Console.ForegroundColor); ANSI_COLOR bgVal = ANSI.Color_Console_To_ANSI(Console.BackgroundColor); Console.ForegroundColor = stackFG; Console.BackgroundColor = stackBG; return(new Tuple <ANSI_COLOR, ANSI_COLOR>(fgVal, bgVal)); }
/// <summary> /// Redraws the screen /// </summary> /// <returns></returns> protected virtual int Redraw() { Write(ANSI.ClearScreen()); ShowLines(Header, 0, Header.Count, 1); ShowLines(Footer, 0, Footer.Count, dataAreaStart + dataAreaSize); Write(ANSI.SaveCursorPosition); if (Data.HasBodyAlternateBackground) { ClearBody(); } int ret = ShowLines(); Write(ANSI.RestoreCursorPosition); return(ret); }
public CommandResult <PackageVersions> NugetVer( CommandEvaluationContext context, [Parameter(0, "package (.nuget) ID")] string id, [Option("q", "quiet", "mute output of result")] bool quiet = false, [Option("u", "get-url", "nuget server api query service template url", true, true)] string url = GetVerUrl ) { var queryString = url.Replace("{ID}", id.Trim()); context.Out.Echo(context.ShellEnv.Colors.Log + $"GET {queryString} ... "); using var httpClient = new HttpClient(); using var request = new HttpRequestMessage(new HttpMethod("GET"), queryString); var tsk = httpClient.SendAsync(request); var result = tsk.Result; if (result.IsSuccessStatusCode) { var res = result.Content.ReadAsStringAsync().Result; context.Out.Echoln(" Done(rdc)"); context.Out.Echo(ANSI.RSTXTA + ANSI.CPL(1) + ANSI.EL(ANSI.ELParameter.p2)); // TODO: add as ANSI combo if (res != null && !string.IsNullOrWhiteSpace(res)) { if (!quiet) { context.Out.Echoln(res); } var obj = JsonConvert.DeserializeObject <PackageVersions>(res); return(new CommandResult <PackageVersions>(obj)); } else { context.Warning("result is empty"); } } else { context.Errorln($"can't get response content: {result.ReasonPhrase}"); } return(new CommandResult <PackageVersions>(null)); }
/// <summary> /// Sets the progress being displayed to a new value /// </summary> /// <param name="Percent">Progress percentage in the [0.0 - 1.0] range</param> public void Set_Progress(double Percent) { lock (Line) { if (Equals(Disposed, 1)) { return; } if (!last_time.HasValue) { last_time = DateTime.UtcNow; LastPct = (float)Percent; } else { History.Enqueue(new Tuple <TimeSpan, float>(DateTime.UtcNow.Subtract(last_time.Value), (float)Percent - LastPct)); while (History.Count > MAX_HIST) { History.Dequeue(); } } Buffer.Clear(); Buffer.Append(string.Format(ANSI.Yellow("{0,6:#00.00}%") + ANSI.MagentaBright(" ["), Percent * 100f));// 9 chars // draw the active '=' portion of the bar const int ACTIVE_SPACE = PROG_BAR_WIDTH; double progSafe = Math.Min(1.0, Math.Max(0.0, Percent)); int active = (int)(progSafe * ACTIVE_SPACE); bool has_cap = active < ACTIVE_SPACE; string active_str = new string('=', active);// always draw an arrow head to cap the active portion of the bar UNLESS it would extend past the bars end if (has_cap) { active_str += ">"; } Buffer.Append(ANSI.CyanBright(active_str)); Buffer.Append(new string(' ', ACTIVE_SPACE - active_str.Length));// pad out the bar's unused space Buffer.Append(ANSI.MagentaBright("]")); Line.Set(Buffer.ToString()); } }
/// <summary> /// Reads the text and stores it in lists of lines /// </summary> /// <param name="name">File to load</param> protected virtual void ReadText(string name) { BBSCodeTranslator translator = new BBSCodeTranslator(client, server); Data = translator.GetProcessed(GetFile(name)); if (!Data.HasBodyFocusedBackground) { NameValueCollection appearance = (NameValueCollection)ConfigurationManager.GetSection("Appearance"); FocusedBackground = ANSI.GetColorByName(appearance["FocusedColor"], true); } else { FocusedBackground = Data.BodyFocusedBackground; } Text = Data.GetRows(); Header = Data.GetHeaderRows(); Footer = Data.GetFooterRows(); }
private void Compress(object sender, RoutedEventArgs e) { if (!filenameCom.fileIsEmpty()) { string noteCompressed = @"D:\RealEncAndCom\noteCompressed.txt"; File.Delete(noteCompressed); ANSI ascii = new ANSI(); LZWEncoder encoder = new LZWEncoder(); string text = File.ReadAllText(filenameCom, System.Text.Encoding.Default); ascii.WriteToFile(); byte[] b = encoder.EncodeToByteList(text); File.WriteAllBytes(noteCompressed, b); comLabel1.Content = "Файл был сжат!"; } else { comLabel1.Content = "Файл не был сжат!"; } }
public CommandVoidResult AnsiParseTest(CommandEvaluationContext context) { var str = ANSI.CSI + "1;2Z" + ANSI.RIS + ANSI.CHA(10) + "hello" + ANSI.CRLF + ANSI.SGRF24("50:100:150") + "WORLD(f=red) RED"; //var str = ANSI.ESC; context.Out.Echoln(str, true); context.Out.Echoln(); var paths = ANSIParser.Parse(str); foreach (var p in paths) { context.Out.Echoln(ASCII.GetNonPrintablesCodesAsLabel(p.ToString(), false), true); } context.Out.Echoln(); context.Out.Echoln($"text={paths.GetText()}", true); context.Out.Echoln($"text length={paths.GetTextLength()}", true); return(CommandVoidResult.Instance); }
public void CleanUpReadln() { if (_inputReaderThread != null) { lock (ConsoleLock) { //Out.ConsoleCursorPosRestore(); // both works Out.CursorPos = _beginOfLineCurPos; if (CommandLineProcessor.CommandEvaluationContext.ShellEnv.IsOptionSetted(ShellEnvironmentVar.settings_console_enableCompatibilityMode)) { /* 💥 */ // ED p0 clean up screen in ConPty Out.Write(ANSI.EL(ANSI.ELParameter.p0)); // minimum compatible } else { Out.Write(ANSI.ED(ANSI.EDParameter.p0)); // not in compatibility mode ( TODO: check) } _inputReaderStringBuilder.Clear(); } } }
public async Task EncodeScan() { var enc = new UTF8Encoding(false); var data = Enumerable.Range(120, 20).Select(x => ANSI.GetChars(new byte[] { (byte)x })[0]).ToArray(); var encodedBytes = (enc.GetPreamble().AsBucket() + enc.GetBytes(data).AsBucket()).ToArray(); for (int i = 1; i < encodedBytes.Length - 1; i++) { var encSpan = encodedBytes.AsMemory(); var b = encSpan.Slice(0, i).ToArray().AsBucket() + encSpan.Slice(i).ToArray().AsBucket(); BucketBytes bb = await b.ConvertToUtf8(enc).ReadFullAsync(1024); Assert.AreEqual(Escape(new String(data)), Escape(bb.ToUTF8String()), $"Convert Iteration {i}"); b = encSpan.Slice(0, i).ToArray().AsBucket() + encSpan.Slice(i).ToArray().AsBucket(); bb = await b.NormalizeToUtf8().ReadFullAsync(1024); Assert.AreEqual(Escape(new String(data)), Escape(bb.ToUTF8String()), $"Normalize Iteration {i}"); } }
public async Task NormalizeBucketToUtf8(Encoding enc) { var data = Enumerable.Range(0, byte.MaxValue).Select(x => ANSI.GetChars(new byte[] { (byte)x })[0]).ToArray(); var encodedBytes = (enc.GetPreamble().AsBucket() + enc.GetBytes(data).AsBucket()).ToArray(); using var b = encodedBytes.AsBucket(); // This wil test the peaking var bb = await b.NormalizeToUtf8().ReadFullAsync(1024); Assert.AreEqual(Escape(new String(data)), Escape(bb.ToUTF8String()), Escape(new String(encodedBytes.Select(x => (char)x).ToArray()))); if (enc is UnicodeEncoding u && !u.GetPreamble().Any()) { return; // Unicode without preamble not detectable without scan via .Peek() } // This will check the byte reading BucketBytes ec = encodedBytes; bb = await(ec.Slice(0, 1).ToArray().AsBucket() + ec.Slice(1).ToArray().AsBucket()).NormalizeToUtf8().ReadFullAsync(1024); Assert.AreEqual(Escape(new String(data)), Escape(bb.ToUTF8String()), Escape(new String(encodedBytes.Select(x => (char)x).ToArray()))); }
public CommandResult <QueryResultRoot> NugetQuery( CommandEvaluationContext context, [Parameter("the search terms to used to filter packages", true)] string query, [Option("s", "skip", "the number of results to skip, for pagination", true, true)] int skip = -1, [Option("t", "take", "the number of results to return, for pagination", true, true)] int take = -1, [Option("r", "pre-release", "true or false determining whether to include pre-release packages (default no)")] bool preRelease = false, [Option("l", "sem-ver-level", "a SemVer 1.0.0 version string", true, true)] string semVerLevel = "2.0.0", [Option("p", "package-type", "the package type to use to filter packages (added in SearchQueryService/3.5.0)", true, true)] string packageType = null, [Option("u", "query-url", "nuget server api query service template url", true, true)] string url = QueryUrl ) { QueryResultRoot @return = null; query ??= ""; var queryString = url.Replace("{QUERY}", query.Trim()); if (skip > -1) { queryString = queryString.Replace("{SKIP}", skip + ""); } if (take > -1) { queryString = queryString.Replace("{TAKE}", take + ""); } queryString = queryString.Replace("{PRERELEASE}", preRelease.ToString().ToLower()); if (semVerLevel != null) { queryString = queryString.Replace("{SEMVERLEVEL}", semVerLevel); } if (packageType != null) { queryString = queryString.Replace("{PACKAGETYPE}", packageType); } queryString = queryString .Replace("&skip={SKIP}", "") .Replace("&take={TAKE}", "") .Replace("&prerelease={PRERELEASE}", "") .Replace("&semVerLevel={SEMVERLEVEL}", "") .Replace("&packageType={PACKAGETYPE}", ""); context.Out.Echo(context.ShellEnv.Colors.Log + $"GET {queryString} ... "); using var httpClient = new HttpClient(); using var request = new HttpRequestMessage(new HttpMethod("GET"), queryString); var tsk = httpClient.SendAsync(request); var result = tsk.Result; if (result.IsSuccessStatusCode) { var res = result.Content.ReadAsStringAsync().Result; context.Out.Echoln(" Done(rdc)"); context.Out.Echo(ANSI.RSTXTA + ANSI.CPL(1) + ANSI.EL(ANSI.ELParameter.p2)); // TODO: add as ANSI combo var obj = JsonConvert.DeserializeObject <QueryResultRoot>(res); @return = obj; if (obj != null && obj.Data != null) { obj.Echo(new EchoEvaluationContext(context.Out, context)); } else { context.Errorln("invalid json"); } } else { context.Errorln($"can't get response content: {result.ReasonPhrase}"); } return(new CommandResult <QueryResultRoot>(@return)); }
public CommandResult <string> NugetPush( CommandEvaluationContext context, [Parameter(0, "package (.nuget) file path")] FilePath pkgFile, [Parameter(1, "target server api key")] string apiKey, [Option("u", "push-url", "nuget server api push service url", true, true)] string url = PushUrl, [Option("p", "protocol-version", "nuget thir party client protocol version", true, true)] string protocolVersion = ProtocolVersion ) { var @return = ""; if (pkgFile.CheckExists(context)) { var ext = Path.GetExtension(pkgFile.FullName); var atExt = ".nupkg"; if (ext.ToLower() != atExt) { context.Errorln($"bad file extension: '{ext}', should be '{atExt}'"); } else { if (string.IsNullOrWhiteSpace(apiKey)) { context.Errorln($"api key is required and can't be empty"); } else { using var httpClient = new HttpClient(); using var request = new HttpRequestMessage(new HttpMethod("PUT"), url); request.Headers.Add("X-NuGet-ApiKey", apiKey); request.Headers.AcceptEncoding.ParseAdd("gzip,deflate"); request.Headers.Add("X-NuGet-Protocol-Version", protocolVersion); //request.Headers.Add("X-NuGet-Client-Version", "5.8.1"); //request.Headers.Add("user-agent", "NuGet Command Line / 5.8.1 (Microsoft Windows NT 10.0.19042.0)"); var content = new MultipartFormDataContent(); var fileContent = new ByteArrayContent(File.ReadAllBytes(pkgFile.FullName)); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue( "form-data" ) { FileName = "package.nupkg" }; fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); content.Add(fileContent); request.Content = content; context.Out.Echo(context.ShellEnv.Colors.Log + $"PUT {PushUrl} ... "); var tsk = httpClient.SendAsync(request); var result = tsk.Result; if (result.IsSuccessStatusCode) { var res = result.Content.ReadAsStringAsync().Result; context.Out.Echoln(" Done(rdc)"); context.Out.Echo(ANSI.RSTXTA + ANSI.CPL(1) + ANSI.EL(ANSI.ELParameter.p2)); // TODO: add as ANSI combo @return = res; if (res != null) { if (!string.IsNullOrWhiteSpace(res)) { context.Out.Echoln(res); } } else { context.Warningln("quey result is empty"); } context.Warningln("quey result is empty"); if (result.StatusCode == HttpStatusCode.Created || result.StatusCode == HttpStatusCode.Accepted) { context.Out.Echoln($"package '{Path.GetFileName(pkgFile.FullName)}' has been successfully pushed"); } } else { context.Errorln($"can't get response content: {(int)result.StatusCode} {result.ReasonPhrase}"); } } } } return(new CommandResult <string>(@return)); }
public CommandVoidResult DoomFireAlgo( CommandEvaluationContext context, [Option("w", "width", "width in characters", true, true)] int width = 100, [Option("h", "height", "height in characters", true, true)] int height = 40, [Option("d", "decay-delta", "decay delta", true, true)] int decayDelta = 3, [Option("g", "gray", "gray mode - no colors")] bool gray = false, [Option("s", "slow", "0 max speed - pause time between images in ms", true, true)] int slow = 0, [Option("t", "no-text", "do not add text info above anim")] bool noText = false, [Option(null, "color-palette", "color palette. 36 symbols separated by " + PalettePatternSeparator, true, true)] string firePattern = DefaultFirePattern ) { // remove directives to speed up (TODO: the directives lead to stack overflow in this case) firePattern = firePattern.ToLower(); var firePallete = firePattern.Split(PalettePatternSeparator); var sb = new StringBuilder(width * height * 20); if (!gray) { // add colors var n = firePallete.Length; var stp = 256 / n; int r = 0; int g = 0; int b = 0; for (int i = 0; i < firePallete.Length; i++) { firePallete[i] = ANSI.SGR_SetForegroundColor24bits(r, g, b) + firePallete[i]; r += stp; if (r > 100) { g += stp; } } } var o = context.Out; o.Echo("pixelPalete.Length=" + firePallete.Length); var pixels = width * height; var pixelsArray = new int[pixels]; var random = new Random(); void createPixelsStructure() { for (var i = 0; i < pixels; i++) { pixelsArray[i] = 0; } }; void calculatePropagation() { for (var column = 0; column < width; column++) { for (var row = 0; row < height; row++) { var index = column + (width * row); updatePixelIntensity(index); } } }; void updatePixelIntensity(int index) { var belowIndex = index + width; if (belowIndex < width * height) { var decay = (int)Math.Floor(random.NextDouble() * decayDelta); var belowIntensity = pixelsArray[belowIndex]; var newIntensity = belowIntensity - decay; if (index - decay > 0) { pixelsArray[index - decay] = newIntensity > 0 ? newIntensity : 0; } } }; void createSource() { for (var column = 0; column < width; column++) { var overflowPixel = width * height; var index = (overflowPixel - width) + column; pixelsArray[index] = firePallete.Length - 1; } }; void render() { sb.Clear(); sb.Append(ANSI.CUP()); for (var row = 0; row < height; row++) { for (var column = 0; column < width; column++) { var index = column + (width * row); var intensity = pixelsArray[index]; sb.Append(firePallete[intensity]); } sb.AppendLine(); } o.ConsolePrint(sb.ToString()); // fast print }; void start() { o.ClearScreen(); try { o.HideCur(); } catch (Exception ex) { o.Errorln(ex.Message); } createPixelsStructure(); createSource(); } start(); var end = false; while (!end) { var sw0 = Stopwatch.StartNew(); calculatePropagation(); sw0.Stop(); var sw1 = Stopwatch.StartNew(); render(); sw1.Stop(); if (!noText) { o.Echoln($"(rdc)Doom fire algo - {Math.Round(1d / (sw0.ElapsedMilliseconds+sw1.ElapsedMilliseconds) * 1000,2)} fps"); } //end = context.CommandLineProcessor.CancellationTokenSource.IsCancellationRequested; end = context.CommandLineProcessor.IsCancellationRequested; if (slow > 0) { Thread.Sleep(slow); } } o.ShowCur(); return(CommandVoidResult.Instance); }
public Encoder() { table = new ANSI(); dict = table.Table; }