public override void Log(string message, Exception ex, TraceLevel traceLevel, params object[] formatArgs) { switch (traceLevel) { case TraceLevel.Error: _psHostUserInterface.WriteErrorLine(string.Format(message, formatArgs)); break; case TraceLevel.Info: _psHostUserInterface.WriteLine(string.Format(message, formatArgs)); break; case TraceLevel.Verbose: _psHostUserInterface.WriteVerboseLine(string.Format(message, formatArgs)); break; case TraceLevel.Warning: _psHostUserInterface.WriteWarningLine(string.Format(message, formatArgs)); break; default: _psHostUserInterface.WriteLine(string.Format(message, formatArgs)); break; } }
internal PromptResponse PromptUser(PSHostUserInterface console) { char ch = char.MinValue; for (int i = 0; i < this.actualPrompt.Count; i++) { if (i < (this.actualPrompt.Count - 1)) { console.WriteLine(this.actualPrompt[i]); } else { console.Write(this.actualPrompt[i]); } } do { this.callingCmdlet.CheckStopProcessing(); switch (console.RawUI.ReadKey(ReadKeyOptions.IncludeKeyUp | ReadKeyOptions.NoEcho).Character) { case 'q': case 'Q': console.WriteLine(); return(PromptResponse.Quit); case ' ': console.WriteLine(); return(PromptResponse.NextPage); } }while (ch != '\r'); console.WriteLine(); return(PromptResponse.NextLine); }
// Maybe we shouldn't do update check and show notification when it's from a mini-shell, meaning when // 'ConsoleShell.Start' is not called by 'ManagedEntrance.Start'. // But it seems so unusual that it's probably not worth bothering. Also, a mini-shell probably should // just disable the update notification feature by setting the opt-out environment variable. internal static void ShowUpdateNotification(PSHostUserInterface hostUI) { if (!Directory.Exists(s_cacheDirectory)) { return; } if (TryParseUpdateFile( updateFilePath: out _, out SemanticVersion lastUpdateVersion, lastUpdateDate: out _) && lastUpdateVersion != null) { string releaseTag = lastUpdateVersion.ToString(); string notificationMsgTemplate = s_notificationType == NotificationType.LTS ? ManagedEntranceStrings.LTSUpdateNotificationMessage : string.IsNullOrEmpty(lastUpdateVersion.PreReleaseLabel) ? ManagedEntranceStrings.StableUpdateNotificationMessage : ManagedEntranceStrings.PreviewUpdateNotificationMessage; string notificationColor = string.Empty; string resetColor = string.Empty; string line2Padding = string.Empty; string line3Padding = string.Empty; // We calculate how much whitespace we need to make it look nice if (hostUI.SupportsVirtualTerminal) { // Swaps foreground and background colors. notificationColor = "\x1B[7m"; resetColor = "\x1B[0m"; // The first line is longest, if the message changes, this needs to be updated int line1Length = notificationMsgTemplate.IndexOf('\n'); int line2Length = notificationMsgTemplate.IndexOf('\n', line1Length + 1); int line3Length = notificationMsgTemplate.IndexOf('\n', line2Length + 1); line3Length -= line2Length + 1; line2Length -= line1Length + 1; line2Padding = line2Padding.PadRight(line1Length - line2Length + releaseTag.Length); // 3 represents the extra placeholder in the template line3Padding = line3Padding.PadRight(line1Length - line3Length + 3); } string notificationMsg = string.Format(CultureInfo.CurrentCulture, notificationMsgTemplate, releaseTag, notificationColor, resetColor, line2Padding, line3Padding); hostUI.WriteLine(); hostUI.WriteLine(notificationMsg); } }
public override void WriteLine() { string[] lines = writeCache.ToString().Split(new[] { "\r\n", "\n" }, StringSplitOptions.None); foreach (string line in lines) { string temp = line; SendToSubscribers(s => s.WriteOutput(temp.TrimEnd() + "\r\n")); } writeCache.Length = 0; if (externalUI != null) { externalUI.WriteLine(); } }
private void DisplayBanner(PSHostUserInterface hostUI, string?bannerText) { if (_showBanner && !_showHelp) { // If banner text is not supplied do nothing. if (!string.IsNullOrEmpty(bannerText)) { hostUI.WriteLine(bannerText); hostUI.WriteLine(); } if (UpdatesNotification.CanNotifyUpdates) { UpdatesNotification.ShowUpdateNotification(hostUI); } } }
internal static SecureString PromptForSecureString(PSHostUserInterface hostUI, string prompt) { hostUI.Write(prompt); SecureString secureString = hostUI.ReadLineAsSecureString(); hostUI.WriteLine(""); return(secureString); }
/// <summary> /// Do the actual prompting. /// </summary> /// <param name="console">PSHostUserInterface instance to prompt to.</param> internal PromptResponse PromptUser(PSHostUserInterface console) { // NOTE: assume the values passed to ComputePromptLines are still valid // write out the prompt line(s). The last one will not have a new line // at the end because we leave the prompt at the end of the line for (int k = 0; k < _actualPrompt.Count; k++) { if (k < (_actualPrompt.Count - 1)) { console.WriteLine(_actualPrompt[k]); // intermediate line(s) } else { console.Write(_actualPrompt[k]); // last line } } while (true) { _callingCmdlet.CheckStopProcessing(); KeyInfo ki = console.RawUI.ReadKey(ReadKeyOptions.IncludeKeyUp | ReadKeyOptions.NoEcho); char key = ki.Character; if (key == 'q' || key == 'Q') { // need to move to the next line since we accepted input, add a newline console.WriteLine(); return(PromptResponse.Quit); } else if (key == ' ') { // need to move to the next line since we accepted input, add a newline console.WriteLine(); return(PromptResponse.NextPage); } else if (key == '\r') { // need to move to the next line since we accepted input, add a newline console.WriteLine(); return(PromptResponse.NextLine); } } }
private void ShowHelp(PSHostUserInterface hostUI, string?helpText) { if (helpText is null) { return; } if (_showHelp) { hostUI.WriteLine(); hostUI.Write(helpText); if (_showExtendedHelp) { hostUI.Write(ManagedEntranceStrings.ExtendedHelp); } hostUI.WriteLine(); } }
/// <summary> /// present a prompt for a SecureString data /// </summary> /// /// <param name="hostUI"> ref to host ui interface </param> /// /// <param name="prompt"> prompt text </param> /// /// <returns> user input as secure string </returns> /// /// <remarks> </remarks> /// internal static SecureString PromptForSecureString(PSHostUserInterface hostUI, string prompt) { SecureString ss = null; hostUI.Write(prompt); ss = hostUI.ReadLineAsSecureString(); hostUI.WriteLine(string.Empty); return(ss); }
public override void WriteLine(string value) { if (_threadHostUserInterface == null) { _originalWriter.WriteLine(value); } else { _threadHostUserInterface.WriteLine(value); } }
private void DisplayScript(PSHost host, InvocationInfo invocationInfo, int start, int count) { host.UI.WriteLine(); for (int index = start; index <= this.lines.Length && index < start + count; ++index) { PSHostUserInterface ui = host.UI; string str; if (index != invocationInfo.ScriptLineNumber) { str = string.Format((IFormatProvider)CultureInfo.CurrentCulture, "{0,5}: {1}", (object)index, (object)this.lines[index - 1]); } else { str = string.Format((IFormatProvider)CultureInfo.CurrentCulture, "{0,5}:* {1}", (object)index, (object)this.lines[index - 1]); } ui.WriteLine(str); this.lastLineDisplayed = index; } host.UI.WriteLine(); }
// Maybe we shouldn't do update check and show notification when it's from a mini-shell, meaning when // 'ConsoleShell.Start' is not called by 'ManagedEntrance.Start'. // But it seems so unusual that it's probably not worth bothering. Also, a mini-shell probably should // just disable the update notification feature by setting the opt-out environment variable. internal static void ShowUpdateNotification(PSHostUserInterface hostUI) { if (!Directory.Exists(s_cacheDirectory)) { return; } if (TryParseUpdateFile( updateFilePath: out _, out SemanticVersion lastUpdateVersion, lastUpdateDate: out _) && lastUpdateVersion != null) { string releaseTag = lastUpdateVersion.ToString(); string notificationMsgTemplate = string.IsNullOrEmpty(lastUpdateVersion.PreReleaseLabel) ? ManagedEntranceStrings.StableUpdateNotificationMessage : ManagedEntranceStrings.PreviewUpdateNotificationMessage; string notificationMsg = string.Format(CultureInfo.CurrentCulture, notificationMsgTemplate, releaseTag); hostUI.WriteLine(notificationMsg); } }
public override void WriteLine(string value) { _ui.WriteLine(value); }
private static void WriteBanner(PSHostUserInterface ui) { ui.WriteLine(ConsoleColor.White, ConsoleColor.Black, BannerText); ui.WriteLine(); }
/// <summary> /// Writes an IEnumerable of Exceptions to the provided PSHost console. This /// function allows us to print in both PowerShell ISE and the regular PowerShell /// console. It tries to get a PSHost even if one isn't provided /// </summary> /// <param name="exceptions">The exceptions to print</param> /// <param name="host">The PSHost to write the content out to.</param> private static void WriteExceptions(IEnumerable <Exception> exceptions, PSHost host = null) { if (exceptions != null) { if (host == null) { Runspace Runspace = Runspace.DefaultRunspace; //Attempt to get the default host value if (Runspace != null) { Pipeline NewPipeline = Runspace.CreateNestedPipeline("Get-Variable host -ValueOnly", false); /* The returned object from the Cmdlet: * Name : ConsoleHost * * Name : Windows PowerShell ISE Host * Version : 5.1.15063.138 * InstanceId : 71ed23e7-7b80-4273-a3d7-a0ab70dfb21b * UI : System.Management.Automation.Internal.Host.InternalHostUserInterface * CurrentCulture : en-US * CurrentUICulture : en-US * PrivateData : Microsoft.PowerShell.Host.ISE.ISEOptions * DebuggerEnabled : True * IsRunspacePushed : False * Runspace : System.Management.Automation.Runspaces.LocalRunspace */ Collection <PSObject> Results = NewPipeline.Invoke(); if (Results.Count > 0) { host = Results[0].BaseObject as PSHost; } } } //If a default host was found or one was provided if (host != null) { PSHostUserInterface UserInterface = host.UI; foreach (Exception Ex in exceptions) { UserInterface.WriteLine(); UserInterface.WriteLine(ConsoleColor.Red, ConsoleColor.Black, $"ERROR: {Ex.GetType().FullName}"); if (Ex.GetType() == typeof(InfobloxCustomException)) { InfobloxCustomException ce = (InfobloxCustomException)Ex; UserInterface.WriteLine(ConsoleColor.Red, ConsoleColor.Black, $"INFOBLOX ERROR: {ce.Error}"); UserInterface.WriteLine(ConsoleColor.Red, ConsoleColor.Black, $"INFOBLOX TEXT: {ce.Text}"); UserInterface.WriteLine(ConsoleColor.Red, ConsoleColor.Black, $"HTTP STATUS CODE: {ce.HttpResponseCode}"); UserInterface.WriteLine(ConsoleColor.Red, ConsoleColor.Black, $"HTTP STATUS: {ce.HttpStatus}"); UserInterface.WriteLine(ConsoleColor.Red, ConsoleColor.Black, $"HTTP ERROR REASON: {ce.HttpErrorReason}"); } else { UserInterface.WriteLine(ConsoleColor.Red, ConsoleColor.Black, $"MESSAGE: {Ex.Message}"); } if (!String.IsNullOrEmpty(Ex.StackTrace)) { UserInterface.WriteLine(ConsoleColor.Red, ConsoleColor.Black, $"STACK TRACE: {Ex.StackTrace}"); } UserInterface.WriteLine(); } } else //Otherwise, just use console write { foreach (Exception Ex in exceptions) { ConsoleColor OriginalBackground = Console.BackgroundColor; ConsoleColor OriginalForeground = Console.ForegroundColor; Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Red; Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine($"ERROR: {Ex.GetType().FullName}"); if (Ex.GetType() == typeof(InfobloxCustomException)) { InfobloxCustomException IbxEx = (InfobloxCustomException)Ex; Console.WriteLine($"INFOBLOX ERROR: {IbxEx.Error}"); Console.WriteLine($"INFOBLOX TEXT: {IbxEx.Text}"); Console.WriteLine($"HTTP STATUS CODE: {IbxEx.HttpResponseCode}"); Console.WriteLine($"HTTP STATUS: {IbxEx.HttpStatus}"); Console.WriteLine($"HTTP ERROR REASON: {IbxEx.HttpErrorReason}"); } else { Console.WriteLine($"MESSAGE: {Ex.Message}"); } if (!String.IsNullOrEmpty(Ex.StackTrace)) { Console.WriteLine($"STACK TRACE: {Ex.StackTrace}"); } //Reset console colors Console.BackgroundColor = OriginalBackground; Console.ForegroundColor = OriginalForeground; Console.WriteLine(); } } } else { throw new ArgumentNullException("exceptions", "The list of exceptions to print cannot be null"); } }
public void WriteLine(string msg) { _ui.WriteLine(msg); }