Esempio n. 1
0
        public void WriteHost(string message,
                              bool newLine = true,
                              ConsoleColor?foregroundColor = null,
                              ConsoleColor?backgroundColor = null)
        {
            // Technique learned from PSv5+ Write-Host implementation, which
            // works by sending specially-marked messages to the information
            // stream.
            //
            // https://github.com/PowerShell/PowerShell/blob/v7.0.3/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs

            var data = new HostInformationMessage
            {
                Message   = message,
                NoNewLine = !newLine
            };

            if (foregroundColor.HasValue || backgroundColor.HasValue)
            {
                try
                {
                    data.ForegroundColor = foregroundColor;
                    data.BackgroundColor = backgroundColor;
                }
                catch (HostException)
                {
                    // Host is non-interactive or does not support colors.
                }
            }

            WriteInformation(data, HostTag);
        }
        protected PSWhatIfOperationResult ExecuteWhatIf()
        {
            const string statusMessage = "Getting the latest status of all resources...";
            var          clearMessage  = new string(' ', statusMessage.Length);
            var          information   = new HostInformationMessage {
                Message = statusMessage, NoNewLine = true
            };
            var clearInformation = new HostInformationMessage {
                Message = $"\r{clearMessage}\r", NoNewLine = true
            };
            var tags = new[] { "PSHOST" };

            try
            {
                // Write status message.
                this.WriteInformation(information, tags);

                PSWhatIfOperationResult whatIfResult = ResourceManagerSdkClient.ExecuteDeploymentWhatIf(this.WhatIfParameters);

                // Clear status before returning result.
                this.WriteInformation(clearInformation, tags);

                return(whatIfResult);
            }
            catch (Exception)
            {
                // Clear status before on exception.
                this.WriteInformation(clearInformation, tags);
                throw;
            }
        }
Esempio n. 3
0
        public void WriteHost(HostInformationMessage info)
        {
            var record = new InformationRecord(info, Source);

            record.Tags.Add(HostTag);
            DoWriteInformation(record);
        }
Esempio n. 4
0
        public virtual void WriteHost(HostInformationMessage info)
        {
            if (_Writer == null)
            {
                return;
            }

            _Writer.WriteHost(info);
        }
Esempio n. 5
0
        public void WriteHost(HostInformationMessage info)
        {
            if (info == null)
            {
                return;
            }

            DoWriteHost(info);
        }
Esempio n. 6
0
        protected override void DoWriteHost(HostInformationMessage info)
        {
            if (_Inner == null)
            {
                return;
            }

            _Inner.WriteHost(info);
        }
Esempio n. 7
0
        protected override void ProcessRecord()
        {
            HostInformationMessage informationMessage = new HostInformationMessage();

            informationMessage.Message   = Text.GetString(ForegroundColor, BackgroundColor, Object, Separator.ToString(), true, true);
            informationMessage.NoNewLine = NoNewline.IsPresent;

            this.WriteInformation(informationMessage, new string[] { "PSHOST" });
            // this.Host.UI.TranscribeResult(result);
        }
Esempio n. 8
0
        protected void WriteSurvey()
        {
            HostInformationMessage newLine = new HostInformationMessage()
            {
                Message = "\n"
            };
            HostInformationMessage howWas = new HostInformationMessage()
            {
                Message   = ": How was your experience using Azure PowerShell?\nRun ",
                NoNewLine = true
            };
            HostInformationMessage survey;
            HostInformationMessage link;

            try
            {
                survey = new HostInformationMessage()
                {
                    Message         = "Survey",
                    NoNewLine       = true,
                    ForegroundColor = (ConsoleColor)Host.PrivateData.Properties.Match("ProgressForegroundColor").SingleOrDefault().Value
                };
                link = new HostInformationMessage()
                {
                    Message         = "Open-AzSurveyLink",
                    NoNewLine       = true,
                    ForegroundColor = (ConsoleColor)Host.PrivateData.Properties.Match("ProgressbackgroundColor").SingleOrDefault().Value
                };
            }
            catch
            {
                survey = new HostInformationMessage()
                {
                    Message   = "Survey",
                    NoNewLine = true,
                };
                link = new HostInformationMessage()
                {
                    Message   = "Open-AzSurveyLink",
                    NoNewLine = true,
                };
            }
            HostInformationMessage action = new HostInformationMessage()
            {
                Message = " to fill out a short Survey"
            };

            WriteInformation(newLine, new string[] { "PSHOST" });
            WriteInformation(survey, new string[] { "PSHOST" });
            WriteInformation(howWas, new string[] { "PSHOST" });
            WriteInformation(link, new string[] { "PSHOST" });
            WriteInformation(action, new string[] { "PSHOST" });
        }
        public override void WriteHost(HostInformationMessage info)
        {
            if (OnWriteInformation == null)
            {
                return;
            }

            var record = new InformationRecord(info, Source);

            record.Tags.Add(HostTag);
            OnWriteInformation(record);
        }
Esempio n. 10
0
        internal override void WriteProgress(string msg)
        {
            var himsg = new HostInformationMessage
            {
                Message         = msg,
                ForegroundColor = ConsoleColor.DarkYellow,
                BackgroundColor = ConsoleColor.DarkBlue,
                NoNewLine       = false
            };

            Cmdlet.WriteInformation(himsg, tags);
        }
Esempio n. 11
0
        private string ExecuteWhatIf()
        {
            const string statusMessage = "Getting the latest status of all resources...";
            var          clearMessage  = new string(' ', statusMessage.Length);
            var          information   = new HostInformationMessage {
                Message = statusMessage, NoNewLine = true
            };
            var clearInformation = new HostInformationMessage {
                Message = $"\r{clearMessage}\r", NoNewLine = true
            };
            var tags = new[] { "PSHOST" };

            try
            {
                // Write status message.
                this.WriteInformation(information, tags);


                var parameters = new PSDeploymentWhatIfCmdletParameters
                {
                    DeploymentName           = this.Name,
                    Location                 = this.Location,
                    Mode                     = DeploymentMode.Incremental,
                    TemplateUri              = TemplateUri ?? this.TryResolvePath(TemplateFile),
                    TemplateObject           = this.TemplateObject,
                    TemplateParametersUri    = this.TemplateParameterUri,
                    TemplateParametersObject = GetTemplateParameterObject(this.TemplateParameterObject),
                    ResultFormat             = this.WhatIfResultFormat
                };

                PSWhatIfOperationResult whatIfResult = ResourceManagerSdkClient.ExecuteDeploymentWhatIf(parameters, this.WhatIfExcludeChangeType);
                string whatIfMessage = WhatIfOperationResultFormatter.Format(whatIfResult);

                // Clear status before returning result.
                this.WriteInformation(clearInformation, tags);

                // Use \r to override the built-in "What if:" in output.
                return($"\r        \r{Environment.NewLine}{whatIfMessage}{Environment.NewLine}");
            }
            catch (Exception)
            {
                // Clear status before handling exception.
                this.WriteInformation(clearInformation, tags);
                throw;
            }
        }
Esempio n. 12
0
        protected override void OnProcessRecord()
        {
            const string statusMessage = "Getting the latest status of all resources...";
            var          clearMessage  = new string(' ', statusMessage.Length);
            var          information   = new HostInformationMessage {
                Message = statusMessage, NoNewLine = true
            };
            var clearInformation = new HostInformationMessage {
                Message = $"\r{clearMessage}\r", NoNewLine = true
            };
            var tags = new[] { "PSHOST" };

            try
            {
                // Write status message.
                this.WriteInformation(information, tags);

                var parameters = new PSDeploymentWhatIfCmdletParameters
                {
                    DeploymentName           = this.Name,
                    Location                 = this.Location,
                    Mode                     = DeploymentMode.Incremental,
                    TemplateUri              = TemplateUri ?? this.TryResolvePath(TemplateFile),
                    TemplateObject           = this.TemplateObject,
                    TemplateParametersUri    = this.TemplateParameterUri,
                    TemplateParametersObject = GetTemplateParameterObject(this.TemplateParameterObject),
                    ResultFormat             = this.ResultFormat
                };

                PSWhatIfOperationResult whatIfResult = ResourceManagerSdkClient.ExecuteDeploymentWhatIf(parameters);

                // Clear status before returning result.
                this.WriteInformation(clearInformation, tags);
                this.WriteObject(whatIfResult);
            }
            catch (Exception)
            {
                // Clear status on exception.
                this.WriteInformation(clearInformation, tags);
                throw;
            }
        }
Esempio n. 13
0
        protected override void ProcessRecord()
        {
            HostInformationMessage informationMessage = new HostInformationMessage();

            informationMessage.Message   = Text.GetString(ForegroundColor, BackgroundColor, Object, Separator.ToString(), true, true, PersistentColor);
            informationMessage.NoNewLine = NoNewline.IsPresent;

            var tags = new string[] { "PSHOST" };

            // Discuss: is it worth implementing this, even though Cmdlet.WriteHost won't respect it?
            var value = GetVariableValue("HostPreference", ActionPreference.Continue);

            // NOTE: Anything but Continue and SilentlyContinue (or Ignore) is pointless, since you can set them on Information
            if (value is ActionPreference preference && (preference == ActionPreference.SilentlyContinue || preference == ActionPreference.Ignore))
            {
                tags = new string[] { };
            }

            WriteInformation(informationMessage, tags);
        }
Esempio n. 14
0
        /// <summary>
        ///
        /// Outputs the object to the host console, with optional newline
        ///
        /// </summary>
        protected override void ProcessRecord()
        {
            string result = ProcessObject(Object) ?? "";

            HostInformationMessage informationMessage = new HostInformationMessage();
            informationMessage.Message = result;
            informationMessage.NoNewLine = NoNewline.IsPresent;

            try
            {
                informationMessage.ForegroundColor = ForegroundColor;
                informationMessage.BackgroundColor = BackgroundColor;
            }
            catch (System.Management.Automation.Host.HostException)
            {
                // Expected if the host is not interactive, or doesn't have Foreground / Background
                // colours.
            }

            this.WriteInformation(informationMessage, new string[] { "PSHOST" });
            this.Host.UI.TranscribeResult(result);
        }
Esempio n. 15
0
        protected override void OnProcessRecord()
        {
            string whatIfMessage  = null;
            string warningMessage = null;
            string captionMessage = null;

            if (this.ShouldExecuteWhatIf())
            {
                PSWhatIfOperationResult whatIfResult = this.ExecuteWhatIf();
                string whatIfFormattedOutput         = WhatIfOperationResultFormatter.Format(whatIfResult);

                if (this.ShouldProcessGivenCurrentConfirmFlagAndPreference() &&
                    this.ShouldSkipConfirmationIfNoChange() &&
                    whatIfResult.Changes.All(x => x.ChangeType == ChangeType.NoChange || x.ChangeType == ChangeType.Ignore))
                {
                    var whatIfInformation = new HostInformationMessage {
                        Message = whatIfFormattedOutput
                    };
                    var tags = new[] { "PSHOST" };

                    this.WriteInformation(whatIfInformation, tags);
                    this.ExecuteDeployment();

                    return;
                }

                string cursorUp = $"{(char)27}[1A";

                // Use \r to override the built-in "What if:" in output.
                whatIfMessage  = $"\r        \r{Environment.NewLine}{whatIfFormattedOutput}{Environment.NewLine}";
                warningMessage = $"{Environment.NewLine}{Resources.ConfirmDeploymentMessage}";
                captionMessage = $"{cursorUp}{Color.Reset}{whatIfMessage}";
            }

            if (this.ShouldProcess(whatIfMessage, warningMessage, captionMessage))
            {
                this.ExecuteDeployment();
            }
        }
Esempio n. 16
0
        public override void ExecuteCmdlet()
        {
            IEnumerable <ErrorRecord> records = null;

            base.ExecuteCmdlet();
            switch (ParameterSetName)
            {
            case LastErrorParameterSet:
                var errors = GetErrorVariable();
                if (errors != null)
                {
                    var error = errors.FirstOrDefault();
                    if (error != null)
                    {
                        records = new ErrorRecord[] { error };
                    }
                }
                break;

            default:
                records = Error ?? GetErrorVariable();
                break;
            }

            if (records != null)
            {
                foreach (var error in records)
                {
                    ErrorRecord record = error as ErrorRecord;
                    HandleError(record);
                }
            }
            var informationMessage = new HostInformationMessage();

            informationMessage.Message   = $"{Environment.NewLine}{AzureProfileConstants.AzurePowerShellFeedbackMessage}{Environment.NewLine}";
            informationMessage.NoNewLine = false;
            WriteInformation(informationMessage, new string[] { "PSHOST" });
        }
Esempio n. 17
0
 protected virtual void DoWriteHost(HostInformationMessage info)
 {
 }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            using (var reader = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.None, 65536))
            {
                var tarTask = Task.Run(async() =>
                {
                    using (var writer = new AnonymousPipeClientStream(PipeDirection.Out, reader.ClientSafePipeHandle))
                    {
                        var tar = new TarWriter(writer);
                        await tar.CreateEntriesFromDirectoryAsync(string.IsNullOrEmpty(Path) ? "." : Path, ".");
                        await tar.CloseAsync();
                        writer.Close();
                    }
                });

                var parameters = new ImageBuildParameters
                {
                    NoCache     = SkipCache.ToBool(),
                    ForceRemove = ForceRemoveIntermediateContainers.ToBool(),
                    Remove      = !PreserveIntermediateContainers.ToBool(),
                };

                string repoTag = null;
                if (!string.IsNullOrEmpty(Repository))
                {
                    repoTag = Repository;
                    if (!string.IsNullOrEmpty(Tag))
                    {
                        repoTag += ":";
                        repoTag += Tag;
                    }
                    parameters.Tags.Add(repoTag);
                }
                else if (!string.IsNullOrEmpty(Tag))
                {
                    throw new Exception("tag without a repo???");
                }

                string imageId = null;
                bool   failed  = false;

                var buildTask = DkrClient.Miscellaneous.BuildImageFromDockerfileAsync(reader, parameters, CancelSignal.Token);
                using (var progress = buildTask.AwaitResult())
                    using (var progressReader = new StreamReader(progress, new UTF8Encoding(false)))
                    {
                        string line;
                        while ((line = progressReader.ReadLine()) != null)
                        {
                            var message = JsonConvert.DeserializeObject <JsonMessage>(line);
                            if (message.Stream != null)
                            {
                                if (message.Stream.StartsWith(_successfullyBuilt))
                                {
                                    // This is probably the image ID.
                                    imageId = message.Stream.Substring(_successfullyBuilt.Length).Trim();
                                }

                                var infoRecord = new HostInformationMessage();
                                infoRecord.Message = message.Stream;
                                WriteInformation(infoRecord, new string[] { "PSHOST" });
                            }

                            if (message.Error != null)
                            {
                                var error = new ErrorRecord(new Exception(message.Error.Message), null, ErrorCategory.OperationStopped, null);
                                WriteError(error);
                                failed = true;
                            }
                        }
                    }

                tarTask.WaitUnwrap();
                if (imageId == null && !failed)
                {
                    throw new Exception("Could not find image, but no error was returned");
                }

                WriteObject(ContainerOperations.GetImageById(imageId, DkrClient));
            }
        }
Esempio n. 19
0
        public void WriteJsonMessage(JsonMessage message)
        {
            if (message.Error != null)
            {
                var error = new ErrorRecord(new Exception(message.Error.Message), null, ErrorCategory.OperationStopped, null);
                _cmdlet.WriteError(error);
            }
            else if (message.Progress != null)
            {
                var id = message.ID ?? "";
                int activity;
                if (!_idToActivity.TryGetValue(id, out activity))
                {
                    activity = _nextActivity;
                    _nextActivity++;
                    _idToActivity.Add(id, activity);
                }

                var activityName = new StringBuilder(id);
                if (activityName.Length == 0)
                {
                    activityName.Append("Operation");
                }

                if (message.From != null)
                {
                    activityName.AppendFormat("(from {0})", message.From);
                }

                var record = new ProgressRecord(activity, activityName.ToString(), message.Status ?? "Processing");

                var progress = message.Progress;
                if (progress.Total > 0)
                {
                    record.PercentComplete = (int)(progress.Current * 100 / progress.Total);
                }

                if (progress.Current > 0)
                {
                    record.CurrentOperation = string.Format(" ({0} bytes)", progress.Current);
                }

                _cmdlet.WriteProgress(record);
            }
            else
            {
                var info = new StringBuilder();
                if (message.ID != null)
                {
                    info.Append(message.ID);
                    info.Append(": ");
                }

                if (message.From != null)
                {
                    info.AppendFormat("(from {0})", message.From);
                }

                var infoRecord = new HostInformationMessage();
                if (message.Stream != null)
                {
                    info.Append(message.Stream);
                    infoRecord.NoNewLine = true;
                }
                else
                {
                    info.Append(message.Status);
                }

                infoRecord.Message = info.ToString();
                _cmdlet.WriteInformation(infoRecord, new string[] { "PSHOST" });
            }
        }