Example #1
0
        internal static int FindMatchingHandler(MutableTuple tuple, RuntimeException rte, Type[] types, ExecutionContext context)
        {
            Exception replaceParentContainsErrorRecordException = rte;
            Exception innerException = rte.InnerException;
            int       index          = -1;

            if (innerException != null)
            {
                index = FindMatchingHandlerByType(innerException.GetType(), types);
                replaceParentContainsErrorRecordException = innerException;
            }
            if ((index == -1) || types[index].Equals(typeof(CatchAll)))
            {
                index = FindMatchingHandlerByType(rte.GetType(), types);
                replaceParentContainsErrorRecordException = rte;
            }
            if ((index == -1) || types[index].Equals(typeof(CatchAll)))
            {
                ActionPreferenceStopException exception3 = rte as ActionPreferenceStopException;
                if (exception3 != null)
                {
                    replaceParentContainsErrorRecordException = exception3.ErrorRecord.Exception;
                    if (replaceParentContainsErrorRecordException is RuntimeException)
                    {
                        return(FindMatchingHandler(tuple, (RuntimeException)replaceParentContainsErrorRecordException, types, context));
                    }
                    if (replaceParentContainsErrorRecordException != null)
                    {
                        index = FindMatchingHandlerByType(replaceParentContainsErrorRecordException.GetType(), types);
                    }
                }
                else if ((rte is CmdletInvocationException) && (innerException != null))
                {
                    replaceParentContainsErrorRecordException = innerException.InnerException;
                    if (replaceParentContainsErrorRecordException != null)
                    {
                        index = FindMatchingHandlerByType(replaceParentContainsErrorRecordException.GetType(), types);
                    }
                }
            }
            if (index != -1)
            {
                ErrorRecord record = new ErrorRecord(rte.ErrorRecord, replaceParentContainsErrorRecordException);
                tuple.SetAutomaticVariable(AutomaticVariable.Underbar, record, context);
            }
            return(index);
        }
Example #2
0
        internal ContinueStatus WriteHelper(string inquireCaption, string inquireMessage, ActionPreference preference, ContinueStatus lastContinueStatus, string preferenceVariableName, string message)
        {
            switch (lastContinueStatus)
            {
                case ContinueStatus.YesToAll:
                    return ContinueStatus.YesToAll;

                case ContinueStatus.NoToAll:
                    return ContinueStatus.NoToAll;
            }
            switch (preference)
            {
                case ActionPreference.SilentlyContinue:
                case ActionPreference.Continue:
                case ActionPreference.Ignore:
                    return ContinueStatus.Yes;

                case ActionPreference.Stop:
                {
                    ActionPreferenceStopException exception = new ActionPreferenceStopException(this.MyInvocation, this.CBResourcesBaseName, "ErrorPreferenceStop", new object[] { preferenceVariableName, message });
                    throw this.ManageException(exception);
                }
                case ActionPreference.Inquire:
                    return this.InquireHelper(inquireMessage, inquireCaption, true, false, true);
            }
            ActionPreferenceStopException e = new ActionPreferenceStopException(this.MyInvocation, this.CBResourcesBaseName, "PreferenceInvalid", new object[] { preferenceVariableName, preference });
            throw this.ManageException(e);
        }
Example #3
0
 internal void _WriteErrorSkipAllowCheck(ErrorRecord errorRecord, ActionPreference? actionPreference = new ActionPreference?())
 {
     this.ThrowIfStopping();
     if ((errorRecord.ErrorDetails != null) && (errorRecord.ErrorDetails.TextLookupError != null))
     {
         Exception textLookupError = errorRecord.ErrorDetails.TextLookupError;
         errorRecord.ErrorDetails.TextLookupError = null;
         MshLog.LogCommandHealthEvent(this.context, textLookupError, Severity.Warning);
     }
     this.pipelineProcessor.ExecutionFailed = true;
     if (this.shouldLogPipelineExecutionDetail)
     {
         this.pipelineProcessor.LogExecutionError(this.thisCommand.MyInvocation, errorRecord);
     }
     ActionPreference errorAction = this.ErrorAction;
     if (actionPreference.HasValue)
     {
         errorAction = actionPreference.Value;
     }
     if (ActionPreference.Ignore != errorAction)
     {
         if (errorAction == ActionPreference.SilentlyContinue)
         {
             this.AppendErrorToVariables(errorRecord);
         }
         else
         {
             if (ContinueStatus.YesToAll == this.lastErrorContinueStatus)
             {
                 errorAction = ActionPreference.Continue;
             }
             switch (errorAction)
             {
                 case ActionPreference.Stop:
                 {
                     ActionPreferenceStopException e = new ActionPreferenceStopException(this.MyInvocation, errorRecord, this.CBResourcesBaseName, "ErrorPreferenceStop", new object[] { "ErrorActionPreference", errorRecord.ToString() });
                     throw this.ManageException(e);
                 }
                 case ActionPreference.Inquire:
                     this.lastErrorContinueStatus = this.InquireHelper(RuntimeException.RetrieveMessage(errorRecord), null, true, false, true);
                     break;
             }
             this.AppendErrorToVariables(errorRecord);
             PSObject obj2 = PSObject.AsPSObject(errorRecord);
             if (obj2.Members["writeErrorStream"] == null)
             {
                 PSNoteProperty member = new PSNoteProperty("writeErrorStream", true);
                 obj2.Properties.Add(member);
             }
             if (this.ErrorMergeTo != MergeDataStream.None)
             {
                 this.OutputPipe.AddWithoutAppendingOutVarList(obj2);
             }
             else
             {
                 this.ErrorOutputPipe.AddWithoutAppendingOutVarList(obj2);
             }
         }
     }
 }
Example #4
0
 internal ContinueStatus InquireHelper(string inquireMessage, string inquireCaption, bool allowYesToAll, bool allowNoToAll, bool replaceNoWithHalt)
 {
     Collection<ChoiceDescription> choices = new Collection<ChoiceDescription>();
     int num = 0;
     int num2 = 0x7fffffff;
     int num3 = 0x7fffffff;
     int num4 = 0x7fffffff;
     int num5 = 0x7fffffff;
     int num6 = 0x7fffffff;
     int num7 = 0x7fffffff;
     string continueOneLabel = CommandBaseStrings.ContinueOneLabel;
     string continueOneHelpMessage = CommandBaseStrings.ContinueOneHelpMessage;
     choices.Add(new ChoiceDescription(continueOneLabel, continueOneHelpMessage));
     num2 = num++;
     if (allowYesToAll)
     {
         string continueAllLabel = CommandBaseStrings.ContinueAllLabel;
         string continueAllHelpMessage = CommandBaseStrings.ContinueAllHelpMessage;
         choices.Add(new ChoiceDescription(continueAllLabel, continueAllHelpMessage));
         num3 = num++;
     }
     if (replaceNoWithHalt)
     {
         string haltLabel = CommandBaseStrings.HaltLabel;
         string haltHelpMessage = CommandBaseStrings.HaltHelpMessage;
         choices.Add(new ChoiceDescription(haltLabel, haltHelpMessage));
         num4 = num++;
     }
     else
     {
         string skipOneLabel = CommandBaseStrings.SkipOneLabel;
         string skipOneHelpMessage = CommandBaseStrings.SkipOneHelpMessage;
         choices.Add(new ChoiceDescription(skipOneLabel, skipOneHelpMessage));
         num5 = num++;
     }
     if (allowNoToAll)
     {
         string skipAllLabel = CommandBaseStrings.SkipAllLabel;
         string skipAllHelpMessage = CommandBaseStrings.SkipAllHelpMessage;
         choices.Add(new ChoiceDescription(skipAllLabel, skipAllHelpMessage));
         num6 = num++;
     }
     if (this.IsSuspendPromptAllowed())
     {
         string pauseLabel = CommandBaseStrings.PauseLabel;
         string helpMessage = StringUtil.Format(CommandBaseStrings.PauseHelpMessage, "exit");
         choices.Add(new ChoiceDescription(pauseLabel, helpMessage));
         num7 = num++;
     }
     if (string.IsNullOrEmpty(inquireMessage))
     {
         inquireMessage = CommandBaseStrings.ShouldContinuePromptCaption;
     }
     if (string.IsNullOrEmpty(inquireCaption))
     {
         inquireCaption = CommandBaseStrings.InquireCaptionDefault;
     }
     while (true)
     {
         int num8 = this.CBhost.UI.PromptForChoice(inquireCaption, inquireMessage, choices, 0);
         if (num2 == num8)
         {
             return ContinueStatus.Yes;
         }
         if (num3 == num8)
         {
             return ContinueStatus.YesToAll;
         }
         if (num4 == num8)
         {
             ActionPreferenceStopException e = new ActionPreferenceStopException(this.MyInvocation, this.CBResourcesBaseName, "InquireHalt", new object[0]);
             throw this.ManageException(e);
         }
         if (num5 == num8)
         {
             return ContinueStatus.No;
         }
         if (num6 == num8)
         {
             return ContinueStatus.NoToAll;
         }
         if (num7 != num8)
         {
             if (-1 == num8)
             {
                 ActionPreferenceStopException exception2 = new ActionPreferenceStopException(this.MyInvocation, this.CBResourcesBaseName, "InquireCtrlC", new object[0]);
                 throw this.ManageException(exception2);
             }
             InvalidOperationException exception3 = PSTraceSource.NewInvalidOperationException();
             throw this.ManageException(exception3);
         }
         this.CBhost.EnterNestedPrompt(this.thisCommand);
     }
 }
        internal void WriteDebugLine(string message, ref ActionPreference preference)
        {
            ErrorRecord error = null;
            switch (preference)
            {
                case ActionPreference.SilentlyContinue:
                case ActionPreference.Ignore:
                    return;

                case ActionPreference.Stop:
                {
                    this.WriteDebugLineHelper(message);
                    error = new ErrorRecord(new ParentContainsErrorRecordException(InternalHostUserInterfaceStrings.WriteDebugLineStoppedError), "ActionPreferenceStop", ErrorCategory.OperationStopped, null);
                    ActionPreferenceStopException exception2 = new ActionPreferenceStopException(error);
                    throw exception2;
                }
                case ActionPreference.Continue:
                    this.WriteDebugLineHelper(message);
                    return;

                case ActionPreference.Inquire:
                    if (!this.DebugShouldContinue(message, ref preference))
                    {
                        error = new ErrorRecord(new ParentContainsErrorRecordException(InternalHostUserInterfaceStrings.WriteDebugLineStoppedError), "UserStopRequest", ErrorCategory.OperationStopped, null);
                        ActionPreferenceStopException exception = new ActionPreferenceStopException(error);
                        throw exception;
                    }
                    this.WriteDebugLineHelper(message);
                    return;
            }
            throw PSTraceSource.NewArgumentException("preference", "InternalHostUserInterfaceStrings", "UnsupportedPreferenceError", new object[] { (ActionPreference) preference });
        }
Example #6
0
        } // WriteHelper

        /// <summary>
        /// Helper for continue prompt, handles Inquire
        /// </summary>
        /// <param name="inquireMessage">may be null</param>
        /// <param name="inquireCaption">may be null</param>
        /// <param name="allowYesToAll"></param>
        /// <param name="allowNoToAll"></param>
        /// <param name="replaceNoWithHalt"></param>
        /// <param name="hasSecurityImpact"></param>
        /// <returns>user's selection</returns>
        /// <exception cref="System.Management.Automation.PipelineStoppedException">
        /// The pipeline has already been terminated, or was terminated
        /// during the execution of this method.
        /// The Cmdlet should generally just allow PipelineStoppedException
        /// to percolate up to the caller of ProcessRecord etc.
        /// </exception>
        /// <remarks>
        /// If the pipeline is terminated due to ActionPreference.Stop
        /// or ActionPreference.Inquire, this method will throw
        /// <see cref="System.Management.Automation.PipelineStoppedException"/>,
        /// but the command failure will ultimately be
        /// <see cref="System.Management.Automation.ActionPreferenceStopException"/>,
        /// </remarks>
        internal ContinueStatus InquireHelper(
            string inquireMessage,
            string inquireCaption,
            bool allowYesToAll,
            bool allowNoToAll,
            bool replaceNoWithHalt,
            bool hasSecurityImpact
            )
        {
            Collection<ChoiceDescription> choices =
                new Collection<ChoiceDescription>();
            int currentOption = 0;

            int continueOneOption = Int32.MaxValue,
                continueAllOption = Int32.MaxValue,
                haltOption = Int32.MaxValue,
                skipOneOption = Int32.MaxValue,
                skipAllOption = Int32.MaxValue,
                pauseOption = Int32.MaxValue;

            string continueOneLabel = CommandBaseStrings.ContinueOneLabel;
            string continueOneHelpMsg = CommandBaseStrings.ContinueOneHelpMessage;
            choices.Add(new ChoiceDescription(continueOneLabel, continueOneHelpMsg));
            continueOneOption = currentOption++;

            if (allowYesToAll)
            {
                string continueAllLabel = CommandBaseStrings.ContinueAllLabel;
                string continueAllHelpMsg = CommandBaseStrings.ContinueAllHelpMessage;
                choices.Add(new ChoiceDescription(continueAllLabel, continueAllHelpMsg));
                continueAllOption = currentOption++;
            }

            if (replaceNoWithHalt)
            {
                string haltLabel = CommandBaseStrings.HaltLabel;
                string haltHelpMsg = CommandBaseStrings.HaltHelpMessage;
                choices.Add(new ChoiceDescription(haltLabel, haltHelpMsg));
                haltOption = currentOption++;
            }
            else
            {
                string skipOneLabel = CommandBaseStrings.SkipOneLabel;
                string skipOneHelpMsg = CommandBaseStrings.SkipOneHelpMessage;
                choices.Add(new ChoiceDescription(skipOneLabel, skipOneHelpMsg));
                skipOneOption = currentOption++;
            }

            if (allowNoToAll)
            {
                string skipAllLabel = CommandBaseStrings.SkipAllLabel;
                string skipAllHelpMsg = CommandBaseStrings.SkipAllHelpMessage;
                choices.Add(new ChoiceDescription(skipAllLabel, skipAllHelpMsg));
                skipAllOption = currentOption++;
            }

            // Hide the "Suspend" option in the remoting case since that is not supported. If the user chooses
            // Suspend that will produce an error message. Why show the user an option that the user cannot use?
            // Related to bug Win7/116823.
            if (IsSuspendPromptAllowed())
            {
                string pauseLabel = CommandBaseStrings.PauseLabel;
                string pauseHelpMsg = StringUtil.Format(CommandBaseStrings.PauseHelpMessage, "exit");
                choices.Add(new ChoiceDescription(pauseLabel, pauseHelpMsg));
                pauseOption = currentOption++;
            }

            if (String.IsNullOrEmpty(inquireMessage))
            {
                inquireMessage = CommandBaseStrings.ShouldContinuePromptCaption;
            }

            if (String.IsNullOrEmpty(inquireCaption))
            {
                inquireCaption = CommandBaseStrings.InquireCaptionDefault;
            }

            do
            {
                // Transcribe the confirmation message
                CBhost.InternalUI.TranscribeResult(inquireCaption);
                CBhost.InternalUI.TranscribeResult(inquireMessage);

                System.Text.StringBuilder textChoices = new System.Text.StringBuilder();
                foreach (ChoiceDescription choice in choices)
                {
                    if (textChoices.Length > 0)
                    {
                        textChoices.Append("  ");
                    }
                    textChoices.Append(choice.Label);
                }
                CBhost.InternalUI.TranscribeResult(textChoices.ToString());

                int defaultOption = 0;
                if (hasSecurityImpact)
                {
                    defaultOption = skipOneOption;
                }

                int response = this.CBhost.UI.PromptForChoice(
                    inquireCaption, inquireMessage, choices, defaultOption);

                string chosen = choices[response].Label;
                int labelIndex = chosen.IndexOf('&');
                if (labelIndex > -1)
                {
                    chosen = chosen[labelIndex + 1].ToString();
                }

                CBhost.InternalUI.TranscribeResult(chosen);

                if (continueOneOption == response)
                    return ContinueStatus.Yes;
                else if (continueAllOption == response)
                    return ContinueStatus.YesToAll;
                else if (haltOption == response)
                {
                    ActionPreferenceStopException e =
                        new ActionPreferenceStopException(
                            MyInvocation,
                            CommandBaseStrings.InquireHalt);
                    throw ManageException(e);
                }
                else if (skipOneOption == response)
                    return ContinueStatus.No;
                else if (skipAllOption == response)
                    return ContinueStatus.NoToAll;
                else if (pauseOption == response)
                {
                    // This call returns when the user exits the nested prompt.
                    CBhost.EnterNestedPrompt(_thisCommand);
                    // continue loop
                }
                else if (-1 == response)
                {
                    ActionPreferenceStopException e =
                        new ActionPreferenceStopException(
                            MyInvocation,
                            CommandBaseStrings.InquireCtrlC);
                    throw ManageException(e);
                }
                else
                {
                    Dbg.Assert(false, "all cases should be checked");
                    InvalidOperationException e =
                        PSTraceSource.NewInvalidOperationException();
                    throw ManageException(e);
                }
            } while (true);
        } // InquireHelper
Example #7
0
        } // WriteHelper_ShouldWrite

        /// <summary>
        /// Complete implementation of WriteDebug/WriteVerbose/WriteProgress
        /// </summary>
        /// <param name="inquireCaption"></param>
        /// <param name="inquireMessage"></param>
        /// <param name="preference"></param>
        /// <param name="lastContinueStatus"></param>
        /// <param name="preferenceVariableName"></param>
        /// <param name="message"></param>
        /// <returns>Did Inquire return YesToAll?</returns>
        /// <exception cref="System.Management.Automation.PipelineStoppedException">
        /// The pipeline has already been terminated, or was terminated
        /// during the execution of this method.
        /// The Cmdlet should generally just allow PipelineStoppedException
        /// to percolate up to the caller of ProcessRecord etc.
        /// </exception>
        /// <remarks>
        /// If the pipeline is terminated due to ActionPreference.Stop
        /// or ActionPreference.Inquire, this method will throw
        /// <see cref="System.Management.Automation.PipelineStoppedException"/>,
        /// but the command failure will ultimately be
        /// <see cref="System.Management.Automation.ActionPreferenceStopException"/>,
        /// </remarks>
        internal ContinueStatus WriteHelper(
            string inquireCaption,
            string inquireMessage,
            ActionPreference preference,
            ContinueStatus lastContinueStatus,
            string preferenceVariableName,
            string message)
        {
            switch (lastContinueStatus)
            {
                case ContinueStatus.NoToAll:  // previously answered NoToAll
                    return ContinueStatus.NoToAll;
                case ContinueStatus.YesToAll: // previously answered YesToAll
                    return ContinueStatus.YesToAll;
            }

            switch (preference)
            {
                case ActionPreference.Ignore: // YesToAll
                case ActionPreference.SilentlyContinue:
                case ActionPreference.Continue:
                    return ContinueStatus.Yes;

                case ActionPreference.Stop:
                    ActionPreferenceStopException e =
                        new ActionPreferenceStopException(
                            MyInvocation,
                            StringUtil.Format(CommandBaseStrings.ErrorPreferenceStop, preferenceVariableName, message));
                    throw ManageException(e);

                case ActionPreference.Inquire:
                    break;

                default:
                    Dbg.Assert(false, "Bad preference value" + preference);
                    ActionPreferenceStopException apse =
                        new ActionPreferenceStopException(
                            MyInvocation,
                            StringUtil.Format(CommandBaseStrings.PreferenceInvalid, preferenceVariableName, preference));
                    throw ManageException(apse);
            }

            return InquireHelper(
                inquireMessage,
                inquireCaption,
                true,  // allowYesToAll
                false, // allowNoToAll
                true,  // replaceNoWithHalt
                false  // hasSecurityImpact
            );
        } // WriteHelper
Example #8
0
        } // DoWriteError

        // NOTICE-2004/06/08-JonN 959638
        // Use this variant to skip the ThrowIfWriteNotPermitted check
        /// <exception cref="System.Management.Automation.PipelineStoppedException">
        /// The pipeline has already been terminated, or was terminated
        /// during the execution of this method.
        /// The Cmdlet should generally just allow PipelineStoppedException
        /// to percolate up to the caller of ProcessRecord etc.
        /// </exception>
        /// <remarks>
        /// If the pipeline is terminated due to ActionPreference.Stop
        /// or ActionPreference.Inquire, this method will throw
        /// <see cref="System.Management.Automation.PipelineStoppedException"/>,
        /// but the command failure will ultimately be
        /// <see cref="System.Management.Automation.ActionPreferenceStopException"/>,
        /// </remarks>
        internal void _WriteErrorSkipAllowCheck(ErrorRecord errorRecord, ActionPreference? actionPreference = null, bool isNativeError = false)
        {
            ThrowIfStopping();

            if (null != errorRecord.ErrorDetails
                && null != errorRecord.ErrorDetails.TextLookupError)
            {
                Exception textLookupError = errorRecord.ErrorDetails.TextLookupError;
                errorRecord.ErrorDetails.TextLookupError = null;
                MshLog.LogCommandHealthEvent(
                    Context,
                    textLookupError,
                    Severity.Warning);
            }

            this.PipelineProcessor.ExecutionFailed = true;
            if (LogPipelineExecutionDetail)
            {
                this.PipelineProcessor.LogExecutionError(_thisCommand.MyInvocation, errorRecord);
            }

            ActionPreference preference = ErrorAction;
            if (actionPreference.HasValue)
            {
                preference = actionPreference.Value;
            }

            // No trace of the error in the 'Ignore' case
            if (ActionPreference.Ignore == preference)
            {
                return; // do not write or record to output pipe
            }

            // 2004/05/26-JonN
            // The object is not written in the SilentlyContinue case
            if (ActionPreference.SilentlyContinue == preference)
            {
                AppendErrorToVariables(errorRecord);
                return; // do not write to output pipe
            }

            if (ContinueStatus.YesToAll == lastErrorContinueStatus)
            {
                preference = ActionPreference.Continue;
            }

            switch (preference)
            {
                case ActionPreference.Stop:
                    ActionPreferenceStopException e =
                        new ActionPreferenceStopException(
                            MyInvocation,
                            errorRecord,
                            StringUtil.Format(CommandBaseStrings.ErrorPreferenceStop,
                                              "ErrorActionPreference",
                                              errorRecord.ToString()));
                    throw ManageException(e);

                case ActionPreference.Inquire:
                    // ignore return value
                    // this will throw if the user chooses not to continue
                    lastErrorContinueStatus = InquireHelper(
                        RuntimeException.RetrieveMessage(errorRecord),
                        null,
                        true,  // allowYesToAll
                        false, // allowNoToAll
                        true,  // replaceNoWithHalt
                        false  // hasSecurityImpact
                    );
                    break;
            } // switch (preference)

            // 2005/01/20 Do not write the object to $error if
            // ManageException has already done so
            AppendErrorToVariables(errorRecord);

            // Add this note property and set its value to true for F&O
            // to decide whether to call WriteErrorLine or WriteLine.
            // We want errors to print in red in both cases.
            PSObject errorWrap = PSObject.AsPSObject(errorRecord);
            // It's possible we've already added the member (this method is recursive sometimes
            // when tracing), so don't add the member again.

            // We don't add a note property on messages that comes from stderr stream.
            if (!isNativeError && errorWrap.Members["writeErrorStream"] == null)
            {
                PSNoteProperty note = new PSNoteProperty("writeErrorStream", true);
                errorWrap.Properties.Add(note);
            }

            // 2003/11/19-JonN Previously, PSObject instances in ErrorOutputPipe
            // wrapped the TargetObject and held the CoreException as a note.
            // Now, they wrap the CoreException and hold the TargetObject as a note.
            if (ErrorMergeTo != MergeDataStream.None)
            {
                Dbg.Assert(ErrorMergeTo == MergeDataStream.Output, "Only merging to success output is supported.");
                this.OutputPipe.AddWithoutAppendingOutVarList(errorWrap);
            }
            else
            {
                // If this is an error pipe for a hosting application and we are logging,
                // then create a temporary PowerShell to log the error.
                if (Context.InternalHost.UI.IsTranscribing)
                {
                    Context.InternalHost.UI.TranscribeError(Context, errorRecord.InvocationInfo, errorWrap);
                }

                this.ErrorOutputPipe.AddWithoutAppendingOutVarList(errorWrap);
            }
        }