Esempio n. 1
0
        private void OnWarning(object sender, DataAddedEventArgs e)
        {
            var           data   = (PSDataCollection <WarningRecord>)sender;
            WarningRecord record = data[e.Index];

            WriteLine(record.ToString());
        }
 /// <summary>
 /// Constructor taking WarningRecord to wrap and OriginInfo.
 /// </summary>
 /// <param name="warningRecord">WarningRecord to wrap</param>
 /// <param name="originInfo">OriginInfo</param>
 internal RemotingWarningRecord(
     WarningRecord warningRecord,
     OriginInfo originInfo)
     : base(warningRecord.FullyQualifiedWarningId, warningRecord.Message)
 {
     _originInfo = originInfo;
 }
 /// <summary>
 /// Writes the WarningRecord to informational buffers.
 /// </summary>
 /// <param name="record">WarningRecord.</param>
 internal void WriteWarningInfoBuffers(WarningRecord record)
 {
     if (_informationalBuffers != null)
     {
         _informationalBuffers.AddWarning(record);
     }
 }
Esempio n. 4
0
 private void Warning_DataAdded(object sender, DataAddedEventArgs e)
 {
     lock (this._syncObject)
     {
         if (this._isDisposed)
         {
             return;
         }
     }
     this._writeExistingData.WaitOne();
     this._resultsReaderWriterLock.EnterReadLock();
     try
     {
         if (this._results.IsOpen)
         {
             PSDataCollection <WarningRecord> collection = sender as PSDataCollection <WarningRecord>;
             WarningRecord data = this.GetData <WarningRecord>(collection, e.Index);
             if (data != null)
             {
                 this._results.Add(new PSStreamObject(PSStreamObjectType.Warning, data.Message, Guid.Empty));
             }
         }
     }
     finally
     {
         this._resultsReaderWriterLock.ExitReadLock();
     }
 }
Esempio n. 5
0
        void Warning_DataAdded(object sender, DataAddedEventArgs e)
        {
            PSDataCollection <WarningRecord> collection = sender as PSDataCollection <WarningRecord>;

            lastWarning = collection[e.Index];
            PSObject psObj = new PSObject(lastWarning);

            psObj.Properties.Add(new PSNoteProperty("TimeStamp", DateTime.Now));
            psObj.Properties.Add(new PSNoteProperty("Stream", "Warning"));
            timeStampedOutput.Add(psObj);
            if (Dispatcher != null)
            {
                RunOnUIThread(
                    new DispatcherOperationCallback(
                        delegate
                {
                    NotifyWarningChanged();
                    return(null);
                }),
                    true);
            }
            else
            {
                NotifyWarningChanged();
            }
        }
Esempio n. 6
0
 private void OnWarningReady(ScriptRunner sender, WarningRecord data)
 {
     if (data != null)
     {
         WarningReady(data.Message);
     }
 }
Esempio n. 7
0
        /// <summary>
        /// This method implements the ProcessRecord method for Write-Warning command
        /// </summary>
        protected override void ProcessRecord()
        {
            //
            // The write-warning command must use the script's InvocationInfo rather than its own,
            // so we create the WarningRecord here and fill it up with the appropriate InvocationInfo;
            // then, we call the command runtime directly and pass this record to WriteWarning().
            //
            MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime;

            if (mshCommandRuntime != null)
            {
                WarningRecord record = new WarningRecord(Message);

                InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo;

                if (invocationInfo != null)
                {
                    record.SetInvocationInfo(invocationInfo);
                }

                mshCommandRuntime.WriteWarning(record);
            }
            else
            {
                WriteWarning(Message);
            }
        } //processrecord
 internal void WriteWarningRecord(WarningRecord record)
 {
     this.WriteWarningInfoBuffers(record);
     if (this.externalUI != null)
     {
         this.externalUI.WriteWarningLine(record.Message);
     }
 }
Esempio n. 9
0
        protected void Write(WarningRecord warning)
        {
            if (warning == null)
            {
                return;
            }

            _outputAction?.Invoke($"\t{warning.Message}");
        }
        /// <summary>
        /// </summary>
        internal void WriteWarningRecord(WarningRecord record)
        {
            WriteWarningInfoBuffers(record);

            if (_externalUI == null)
            {
                return;
            }

            _externalUI.WriteWarningLine(record.Message);
        }
        public async Task RunTaskAsync(SAFPowerShellCommand command, string contextDirectory)
        {
            if (string.IsNullOrWhiteSpace(command?.Name) || string.IsNullOrWhiteSpace(contextDirectory))
            {
                return;
            }

            using (PowerShell ps = PowerShell.Create())
            {
                // Ensure 64-bit PowerShell
                ps.AddScript(
                    $@"& ""$env:WINDIR\sysnative\windowspowershell\v1.0\powershell.exe"" -NonInteractive -NoProfile -File ""{_scriptsService.Wrapper}"" -ContextDirectory {contextDirectory} -SAFCommand {command.Name}");

                ps.Streams.Progress.DataAdded += (sender, args) =>
                {
                    PSDataCollection <ProgressRecord> progress = (PSDataCollection <ProgressRecord>)sender;
                    OnStreamUpdated($"PROGRESS: {progress[args.Index].PercentComplete}% complete");
                };

                ps.Streams.Error.DataAdded += (sender, args) =>
                {
                    ErrorRecord error = ((PSDataCollection <ErrorRecord>)sender)[args.Index];
                    OnStreamUpdated($"ERROR: {error}");
                };

                ps.Streams.Warning.DataAdded += (sender, args) =>
                {
                    WarningRecord warning = ((PSDataCollection <WarningRecord>)sender)[args.Index];
                    OnStreamUpdated($"WARNING: {warning}");
                };

                var regularOutput = new PSDataCollection <PSObject>();
                regularOutput.DataAdded += (sender, args) =>
                {
                    PSObject output = ((PSDataCollection <PSObject>)sender)[args.Index];
                    OnStreamUpdated($"{output}");
                };

                try
                {
                    await Task <PSDataCollection <PSObject> > .Factory.FromAsync(
                        ps.BeginInvoke <PSObject, PSObject>(null, regularOutput), ps.EndInvoke);
                }
                catch (Exception ex)
                {
                    OnStreamUpdated($"EXCEPTION: {ex.Message}");
                }
            }
        }
Esempio n. 12
0
 public static PsStreamEventHandlers GetUIHandlers(WorkerContext ctx) => new PsStreamEventHandlers()
 {
     Debug = (o, e) =>
     {
         DebugRecord newRecord = ((PSDataCollection <DebugRecord>)o)[e.Index];
         if (!string.IsNullOrEmpty(newRecord.Message))
         {
             Program.MainFrmInstance.SetStatus(newRecord.Message);
         }
     },
     Error = (o, ev) =>
     {
         ErrorRecord newRecord = ((PSDataCollection <ErrorRecord>)o)[ev.Index];
         MessageBox.Show(newRecord.ToString(), "Powershell Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     },
     Information = (o, e) =>
     {
         InformationalRecord newRecord = ((PSDataCollection <InformationalRecord>)o)[e.Index];
         if (!string.IsNullOrEmpty(newRecord.Message))
         {
             Program.MainFrmInstance.SetStatus(newRecord.Message);
         }
     },
     Progress = (o, ev) =>
     {
         ProgressRecord r = ((PSDataCollection <ProgressRecord>)o)[ev.Index];
         ctx.d.ReportCaption(r.Activity);
         if (r.PercentComplete >= 0 && r.PercentComplete <= 100)
         {
             ctx.d.ReportProgress(r.PercentComplete);
         }
     },
     Verbose = (o, e) =>
     {
         VerboseRecord newRecord = ((PSDataCollection <VerboseRecord>)o)[e.Index];
         if (!string.IsNullOrEmpty(newRecord.Message))
         {
             Program.MainFrmInstance.SetStatus(newRecord.Message);
         }
     },
     Warning = (o, e) =>
     {
         WarningRecord newRecord = ((PSDataCollection <WarningRecord>)o)[e.Index];
         if (!string.IsNullOrEmpty(newRecord.Message))
         {
             Program.MainFrmInstance.SetStatus(newRecord.Message);
         }
     }
 };
Esempio n. 13
0
 internal void WriteWarningRecord(WarningRecord record)
 {
     using (InternalHostUserInterface.tracer.TraceMethod(record.Message, new object[0]))
     {
         if (this.informationalBuffers != null)
         {
             this.informationalBuffers.AddWarning(record);
         }
         if (this.externalUI == null)
         {
             InternalHostUserInterface.tracer.WriteLine("no external user interface implemented; doing nothing", new object[0]);
         }
         else
         {
             this.externalUI.WriteWarningLine(record.Message);
         }
     }
 }
Esempio n. 14
0
        protected override void ProcessRecord()
        {
            MshCommandRuntime commandRuntime = base.CommandRuntime as MshCommandRuntime;

            if (commandRuntime != null)
            {
                WarningRecord  record        = new WarningRecord(this.Message);
                InvocationInfo variableValue = base.GetVariableValue("MyInvocation") as InvocationInfo;
                if (variableValue != null)
                {
                    record.SetInvocationInfo(variableValue);
                }
                commandRuntime.WriteWarning(record, false);
            }
            else
            {
                base.WriteWarning(this.Message);
            }
        }
Esempio n. 15
0
        /// <summary>
        /// 
        /// </summary>
        internal void WriteWarningRecord(WarningRecord record)
        {
            WriteWarningInfoBuffers(record);

            if (_externalUI == null)
            {
                return;
            }

            _externalUI.WriteWarningLine(record.Message);
        }
Esempio n. 16
0
        /// <summary>
        ///
        /// </summary>
        protected override void BeginProcessing()
        {
            //ValidateNotNullOrEmpty attribute is not working for System.Uri datatype, so handling it here
            if ((_cssuriSpecified) && (string.IsNullOrEmpty(_cssuri.OriginalString.Trim())))
            {
                ArgumentException ex = new ArgumentException(StringUtil.Format(UtilityCommonStrings.EmptyCSSUri, "CSSUri"));
                ErrorRecord       er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.InvalidArgument, "CSSUri");
                ThrowTerminatingError(er);
            }

            _propertyMshParameterList = ProcessParameter(_property);

            if (!String.IsNullOrEmpty(_title))
            {
                WebUtility.HtmlEncode(_title);
            }


            // This first line ensures w3c validation will succeed. However we are not specifying
            // an encoding in the HTML because we don't know where the text will be written and
            // if a particular encoding will be used.

            if (!_fragment)
            {
                if (!_transitional)
                {
                    WriteObject("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"  \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
                }
                else
                {
                    WriteObject("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"  \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
                }
                WriteObject("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
                WriteObject("<head>");
                if (_charsetSpecified)
                {
                    WriteObject("<meta charset=\"" + _charset + "\">");
                }
                if (_metaSpecified)
                {
                    List <string> useditems = new List <string>();
                    foreach (string s in _meta.Keys)
                    {
                        if (!useditems.Contains(s))
                        {
                            switch (s.ToLower())
                            {
                            case "content-type":
                            case "default-style":
                            case "x-ua-compatible":
                                WriteObject("<meta http-equiv=\"" + s + "\" content=\"" + _meta[s] + "\">");
                                break;

                            case "application-name":
                            case "author":
                            case "description":
                            case "generator":
                            case "keywords":
                            case "viewport":
                                WriteObject("<meta name=\"" + s + "\" content=\"" + _meta[s] + "\">");
                                break;

                            default:
                                MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime;
                                string            Message           = StringUtil.Format(ConvertHTMLStrings.MetaPropertyNotFound, s, _meta[s]);
                                WarningRecord     record            = new WarningRecord(Message);
                                InvocationInfo    invocationInfo    = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo;

                                if (invocationInfo != null)
                                {
                                    record.SetInvocationInfo(invocationInfo);
                                }
                                mshCommandRuntime.WriteWarning(record);
                                WriteObject("<meta name=\"" + s + "\" content=\"" + _meta[s] + "\">");
                                break;
                            }
                            useditems.Add(s);
                        }
                    }
                }
                WriteObject(_head ?? new string[] { "<title>" + _title + "</title>" }, true);
                if (_cssuriSpecified)
                {
                    WriteObject("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + _cssuri + "\" />");
                }
                WriteObject("</head><body>");
                if (_body != null)
                {
                    WriteObject(_body, true);
                }
            }
            if (_preContent != null)
            {
                WriteObject(_preContent, true);
            }
            WriteObject("<table>");
            _isTHWritten       = false;
            _propertyCollector = new StringCollection();
        }
Esempio n. 17
0
 public static UniversalStreamRecord FromWarningRecord(WarningRecord record)
 {
     return(FromInformationalRecord(record));
 }
Esempio n. 18
0
        internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInquire = false)
        {
            switch (this.ObjectType)
            {
            case PSStreamObjectType.Output:
                if (instanceId != Guid.Empty)
                {
                    PSObject psObj = this.Value as PSObject;
                    if (psObj != null)
                    {
                        AddSourceJobNoteProperty(psObj, instanceId);
                    }
                }
                cmdlet.WriteObject(this.Value);
                return;

            case PSStreamObjectType.Error:
            {
                ErrorRecord errorRecord = (ErrorRecord)this.Value;
                if ((!(errorRecord is RemotingErrorRecord) && (errorRecord.ErrorDetails != null)) && !string.IsNullOrEmpty(errorRecord.ErrorDetails.RecommendedAction))
                {
                    string str;
                    Guid   guid;
                    GetIdentifierInfo(errorRecord.ErrorDetails.RecommendedAction, out guid, out str);
                    errorRecord = new RemotingErrorRecord(errorRecord, new OriginInfo(str, Guid.Empty, guid));
                }
                errorRecord.PreserveInvocationInfoOnce = true;
                MshCommandRuntime commandRuntime = cmdlet.CommandRuntime as MshCommandRuntime;
                if (commandRuntime == null)
                {
                    break;
                }
                commandRuntime.WriteError(errorRecord, overrideInquire);
                return;
            }

            case PSStreamObjectType.MethodExecutor:
            case PSStreamObjectType.BlockingError:
            case PSStreamObjectType.ShouldMethod:
            case PSStreamObjectType.WarningRecord:
                this.WriteStreamObject(cmdlet, overrideInquire);
                break;

            case PSStreamObjectType.Warning:
            {
                string            message  = (string)this.Value;
                WarningRecord     record   = new WarningRecord(message);
                MshCommandRuntime runtime2 = cmdlet.CommandRuntime as MshCommandRuntime;
                if (runtime2 == null)
                {
                    break;
                }
                runtime2.WriteWarning(record, overrideInquire);
                return;
            }

            case PSStreamObjectType.Debug:
            {
                string            str5     = (string)this.Value;
                DebugRecord       record7  = new DebugRecord(str5);
                MshCommandRuntime runtime5 = cmdlet.CommandRuntime as MshCommandRuntime;
                if (runtime5 == null)
                {
                    break;
                }
                runtime5.WriteDebug(record7, overrideInquire);
                return;
            }

            case PSStreamObjectType.Progress:
            {
                ProgressRecord progressRecord = (ProgressRecord)this.Value;
                if (!(progressRecord is RemotingProgressRecord))
                {
                    Guid   guid2;
                    string str4;
                    GetIdentifierInfo(progressRecord.CurrentOperation, out guid2, out str4);
                    OriginInfo originInfo = new OriginInfo(str4, Guid.Empty, guid2);
                    progressRecord = new RemotingProgressRecord(progressRecord, originInfo);
                }
                MshCommandRuntime runtime4 = cmdlet.CommandRuntime as MshCommandRuntime;
                if (runtime4 == null)
                {
                    break;
                }
                runtime4.WriteProgress(progressRecord, overrideInquire);
                return;
            }

            case PSStreamObjectType.Verbose:
            {
                string            str3     = (string)this.Value;
                VerboseRecord     record4  = new VerboseRecord(str3);
                MshCommandRuntime runtime3 = cmdlet.CommandRuntime as MshCommandRuntime;
                if (runtime3 == null)
                {
                    break;
                }
                runtime3.WriteVerbose(record4, overrideInquire);
                return;
            }

            default:
                return;
            }
        }
Esempio n. 19
0
        internal void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false)
        {
            switch (this.ObjectType)
            {
            case PSStreamObjectType.Output:
                cmdlet.WriteObject(this.Value);
                return;

            case PSStreamObjectType.Error:
            {
                ErrorRecord errorRecord = (ErrorRecord)this.Value;
                errorRecord.PreserveInvocationInfoOnce = true;
                MshCommandRuntime commandRuntime = cmdlet.CommandRuntime as MshCommandRuntime;
                if (commandRuntime == null)
                {
                    break;
                }
                commandRuntime.WriteError(errorRecord, overrideInquire);
                return;
            }

            case PSStreamObjectType.MethodExecutor:
                ((ClientMethodExecutor)this.Value).Execute(cmdlet);
                return;

            case PSStreamObjectType.Warning:
            {
                string            message  = (string)this.Value;
                WarningRecord     record   = new WarningRecord(message);
                MshCommandRuntime runtime3 = cmdlet.CommandRuntime as MshCommandRuntime;
                if (runtime3 == null)
                {
                    break;
                }
                runtime3.WriteWarning(record, overrideInquire);
                return;
            }

            case PSStreamObjectType.BlockingError:
            {
                CmdletMethodInvoker <object> cmdletMethodInvoker = (CmdletMethodInvoker <object>) this.Value;
                InvokeCmdletMethodAndWaitForResults <object>(cmdletMethodInvoker, cmdlet);
                return;
            }

            case PSStreamObjectType.ShouldMethod:
            {
                CmdletMethodInvoker <bool> invoker2 = (CmdletMethodInvoker <bool>) this.Value;
                InvokeCmdletMethodAndWaitForResults <bool>(invoker2, cmdlet);
                return;
            }

            case PSStreamObjectType.WarningRecord:
            {
                WarningRecord     record5  = (WarningRecord)this.Value;
                MshCommandRuntime runtime6 = cmdlet.CommandRuntime as MshCommandRuntime;
                if (runtime6 == null)
                {
                    break;
                }
                runtime6.AppendWarningVarList(record5);
                return;
            }

            case PSStreamObjectType.Debug:
            {
                string            str      = (string)this.Value;
                DebugRecord       record2  = new DebugRecord(str);
                MshCommandRuntime runtime2 = cmdlet.CommandRuntime as MshCommandRuntime;
                if (runtime2 == null)
                {
                    break;
                }
                runtime2.WriteDebug(record2, overrideInquire);
                return;
            }

            case PSStreamObjectType.Progress:
            {
                MshCommandRuntime runtime5 = cmdlet.CommandRuntime as MshCommandRuntime;
                if (runtime5 == null)
                {
                    break;
                }
                runtime5.WriteProgress((ProgressRecord)this.Value, overrideInquire);
                return;
            }

            case PSStreamObjectType.Verbose:
            {
                string            str3     = (string)this.Value;
                VerboseRecord     record4  = new VerboseRecord(str3);
                MshCommandRuntime runtime4 = cmdlet.CommandRuntime as MshCommandRuntime;
                if (runtime4 == null)
                {
                    break;
                }
                runtime4.WriteVerbose(record4, overrideInquire);
                return;
            }

            case PSStreamObjectType.Exception:
            {
                Exception exception = (Exception)this.Value;
                throw exception;
            }

            default:
                return;
            }
        }
Esempio n. 20
0
 public void Warning(WarningRecord warningRecord)
 {
     Warning(warningRecord.Message);
 }
Esempio n. 21
0
        /// <summary>
        /// Handles a robust connection layer notification from the transport
        /// manager.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HandleRobustConnectionNotification(
            object sender,
            ConnectionStatusEventArgs e)
        {
            // Create event arguments and warnings/errors for this robust connection notification.
            PSConnectionRetryStatusEventArgs connectionRetryStatusArgs = null;
            WarningRecord warningRecord = null;
            ErrorRecord   errorRecord   = null;
            int           maxRetryConnectionTimeMSecs   = this.runspacePool.MaxRetryConnectionTime;
            int           maxRetryConnectionTimeMinutes = maxRetryConnectionTimeMSecs / 60000;

            switch (e.Notification)
            {
            case ConnectionStatus.NetworkFailureDetected:
                warningRecord = new WarningRecord(
                    PSConnectionRetryStatusEventArgs.FQIDNetworkFailureDetected,
                    StringUtil.Format(RemotingErrorIdStrings.RCNetworkFailureDetected,
                                      this.computerName, maxRetryConnectionTimeMinutes));

                connectionRetryStatusArgs =
                    new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.NetworkFailureDetected,
                                                         this.computerName, maxRetryConnectionTimeMSecs, warningRecord);
                break;

            case ConnectionStatus.ConnectionRetryAttempt:
                warningRecord = new WarningRecord(
                    PSConnectionRetryStatusEventArgs.FQIDConnectionRetryAttempt,
                    StringUtil.Format(RemotingErrorIdStrings.RCConnectionRetryAttempt, this.computerName));

                connectionRetryStatusArgs =
                    new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.ConnectionRetryAttempt,
                                                         this.computerName, maxRetryConnectionTimeMSecs, warningRecord);
                break;

            case ConnectionStatus.ConnectionRetrySucceeded:
                warningRecord = new WarningRecord(
                    PSConnectionRetryStatusEventArgs.FQIDConnectionRetrySucceeded,
                    StringUtil.Format(RemotingErrorIdStrings.RCReconnectSucceeded, this.computerName));

                connectionRetryStatusArgs =
                    new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.ConnectionRetrySucceeded,
                                                         this.computerName, maxRetryConnectionTimeMinutes, warningRecord);
                break;

            case ConnectionStatus.AutoDisconnectStarting:
            {
                warningRecord = new WarningRecord(
                    PSConnectionRetryStatusEventArgs.FQIDAutoDisconnectStarting,
                    StringUtil.Format(RemotingErrorIdStrings.RCAutoDisconnectingWarning, this.computerName));

                connectionRetryStatusArgs =
                    new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.AutoDisconnectStarting,
                                                         this.computerName, maxRetryConnectionTimeMinutes, warningRecord);
            }

            break;

            case ConnectionStatus.AutoDisconnectSucceeded:
                warningRecord = new WarningRecord(
                    PSConnectionRetryStatusEventArgs.FQIDAutoDisconnectSucceeded,
                    StringUtil.Format(RemotingErrorIdStrings.RCAutoDisconnected, this.computerName));

                connectionRetryStatusArgs =
                    new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.AutoDisconnectSucceeded,
                                                         this.computerName, maxRetryConnectionTimeMinutes, warningRecord);
                break;

            case ConnectionStatus.InternalErrorAbort:
            {
                string           msg    = StringUtil.Format(RemotingErrorIdStrings.RCInternalError, this.computerName);
                RuntimeException reason = new RuntimeException(msg);
                errorRecord = new ErrorRecord(reason,
                                              PSConnectionRetryStatusEventArgs.FQIDNetworkOrDisconnectFailed,
                                              ErrorCategory.InvalidOperation, this);

                connectionRetryStatusArgs =
                    new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.InternalErrorAbort,
                                                         this.computerName, maxRetryConnectionTimeMinutes, errorRecord);
            }

            break;
            }

            if (connectionRetryStatusArgs == null)
            {
                return;
            }

            // Update connection status.
            _connectionRetryStatus = connectionRetryStatusArgs.Notification;

            if (warningRecord != null)
            {
                RemotingWarningRecord remotingWarningRecord = new RemotingWarningRecord(
                    warningRecord,
                    new OriginInfo(this.computerName, this.InstanceId));

                // Add warning record to information channel.
                HandleInformationalMessageReceived(this,
                                                   new RemoteDataEventArgs <InformationalMessage>(
                                                       new InformationalMessage(remotingWarningRecord, RemotingDataType.PowerShellWarning)));

                // Write warning to host.
                RemoteHostCall writeWarning = new RemoteHostCall(
                    -100,
                    RemoteHostMethodId.WriteWarningLine,
                    new object[] { warningRecord.Message });

                try
                {
                    HandleHostCallReceived(this,
                                           new RemoteDataEventArgs <RemoteHostCall>(writeWarning));
                }
                catch (PSNotImplementedException)
                { }
            }

            if (errorRecord != null)
            {
                RemotingErrorRecord remotingErrorRecord = new RemotingErrorRecord(
                    errorRecord,
                    new OriginInfo(this.computerName, this.InstanceId));

                // Add error record to error channel, will also be written to host.
                HandleErrorReceived(this,
                                    new RemoteDataEventArgs <ErrorRecord>(remotingErrorRecord));
            }

            // Raise event.
            RCConnectionNotification.SafeInvoke(this, connectionRetryStatusArgs);
        }
Esempio n. 22
0
        /// <summary>
        /// Sets up the PowerShell shell stream event handlers.
        /// </summary>
        /// <param name="shell">The PowerShell shell.</param>
        private static void SetupStreamEventHandlers(PowerShell shell)
        {
            Logger.Instance.WriteMethodEntry(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlers);

            try
            {
                shell.Streams.ClearStreams();
                shell.Streams.Error.DataAdded += delegate(object sender, DataAddedEventArgs e)
                {
                    PSDataCollection <ErrorRecord> errorStream = (PSDataCollection <ErrorRecord>)sender;
                    ErrorRecord record = errorStream[e.Index];
                    if (record == null)
                    {
                        return;
                    }

                    StringBuilder builder = new StringBuilder();
                    builder.AppendLine(record.ToString());

                    if (record.InvocationInfo != null)
                    {
                        builder.AppendLine();
                        builder.AppendLine(record.InvocationInfo.PositionMessage);
                    }

                    Logger.Instance.WriteError(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersErrorEvents, builder.ToString());
                };
                shell.Streams.Warning.DataAdded += delegate(object sender, DataAddedEventArgs e)
                {
                    PSDataCollection <WarningRecord> warningStream = (PSDataCollection <WarningRecord>)sender;
                    WarningRecord record = warningStream[e.Index];
                    if (record != null)
                    {
                        Logger.Instance.WriteWarning(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersWarningEvents, record.ToString());
                    }
                };
                shell.Streams.Debug.DataAdded += delegate(object sender, DataAddedEventArgs e)
                {
                    PSDataCollection <DebugRecord> debugStream = (PSDataCollection <DebugRecord>)sender;
                    DebugRecord record = debugStream[e.Index];
                    if (record != null)
                    {
                        Logger.Instance.WriteInfo(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersDebugEvents, record.ToString());
                    }
                };
                shell.Streams.Verbose.DataAdded += delegate(object sender, DataAddedEventArgs e)
                {
                    PSDataCollection <VerboseRecord> versboseStream = (PSDataCollection <VerboseRecord>)sender;
                    VerboseRecord record = versboseStream[e.Index];
                    if (record != null)
                    {
                        Logger.Instance.WriteVerbose(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersEvents, record.ToString());
                    }
                };
                shell.Streams.Progress.DataAdded += delegate(object sender, DataAddedEventArgs e)
                {
                    PSDataCollection <ProgressRecord> progressStream = (PSDataCollection <ProgressRecord>)sender;
                    ProgressRecord record = progressStream[e.Index];
                    if (record != null)
                    {
                        Logger.Instance.WriteInfo(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersProgressEvents, record.ToString());
                    }
                };
            }
            finally
            {
                Logger.Instance.WriteMethodExit(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlers);
            }
        }
Esempio n. 23
0
        private void HandleRobustConnectionNotification(object sender, ConnectionStatusEventArgs e)
        {
            PSConnectionRetryStatusEventArgs eventArgs = null;
            WarningRecord infoRecord             = null;
            ErrorRecord   record2                = null;
            int           maxRetryConnectionTime = this.runspacePool.MaxRetryConnectionTime;
            int           num2 = maxRetryConnectionTime / 0xea60;

            switch (e.Notification)
            {
            case ConnectionStatus.NetworkFailureDetected:
                infoRecord = new WarningRecord("PowerShellNetworkFailureDetected", StringUtil.Format(RemotingErrorIdStrings.RCNetworkFailureDetected, this.computerName, num2));
                eventArgs  = new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.NetworkFailureDetected, this.computerName, maxRetryConnectionTime, infoRecord);
                break;

            case ConnectionStatus.ConnectionRetryAttempt:
                infoRecord = new WarningRecord("PowerShellConnectionRetryAttempt", StringUtil.Format(RemotingErrorIdStrings.RCConnectionRetryAttempt, this.computerName));
                eventArgs  = new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.ConnectionRetryAttempt, this.computerName, maxRetryConnectionTime, infoRecord);
                break;

            case ConnectionStatus.ConnectionRetrySucceeded:
                infoRecord = new WarningRecord("PowerShellConnectionRetrySucceeded", StringUtil.Format(RemotingErrorIdStrings.RCReconnectSucceeded, this.computerName));
                eventArgs  = new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.ConnectionRetrySucceeded, this.computerName, num2, infoRecord);
                break;

            case ConnectionStatus.AutoDisconnectStarting:
                infoRecord = new WarningRecord("PowerShellNetworkFailedStartDisconnect", StringUtil.Format(RemotingErrorIdStrings.RCAutoDisconnectingWarning, this.computerName));
                eventArgs  = new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.AutoDisconnectStarting, this.computerName, num2, infoRecord);
                break;

            case ConnectionStatus.AutoDisconnectSucceeded:
                infoRecord = new WarningRecord("PowerShellAutoDisconnectSucceeded", StringUtil.Format(RemotingErrorIdStrings.RCAutoDisconnected, this.computerName));
                eventArgs  = new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.AutoDisconnectSucceeded, this.computerName, num2, infoRecord);
                break;

            case ConnectionStatus.InternalErrorAbort:
            {
                RuntimeException exception = new RuntimeException(StringUtil.Format(RemotingErrorIdStrings.RCInternalError, this.computerName));
                record2   = new ErrorRecord(exception, "PowerShellNetworkOrDisconnectFailed", ErrorCategory.InvalidOperation, this);
                eventArgs = new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.InternalErrorAbort, this.computerName, num2, record2);
                break;
            }
            }
            if (eventArgs != null)
            {
                this.connectionRetryStatus = eventArgs.Notification;
                if (infoRecord != null)
                {
                    RemotingWarningRecord message = new RemotingWarningRecord(infoRecord, new OriginInfo(this.computerName, this.InstanceId));
                    this.HandleInformationalMessageReceived(this, new RemoteDataEventArgs <InformationalMessage>(new InformationalMessage(message, RemotingDataType.PowerShellWarning)));
                    RemoteHostCall data = new RemoteHostCall(-100L, RemoteHostMethodId.WriteWarningLine, new object[] { infoRecord.Message });
                    try
                    {
                        this.HandleHostCallReceived(this, new RemoteDataEventArgs <RemoteHostCall>(data));
                    }
                    catch (PSNotImplementedException)
                    {
                    }
                }
                if (record2 != null)
                {
                    RemotingErrorRecord record4 = new RemotingErrorRecord(record2, new OriginInfo(this.computerName, this.InstanceId));
                    this.HandleErrorReceived(this, new RemoteDataEventArgs <ErrorRecord>(record4));
                }
                this.RCConnectionNotification.SafeInvoke <PSConnectionRetryStatusEventArgs>(this, eventArgs);
            }
        }
Esempio n. 24
0
        private void Warning_DataAdded(object sender, DataAddedEventArgs e)
        {
            WarningRecord warningRecord = PS.Streams.Warning.Last();

            Logger.Log(warningRecord.Message, LogLevels.Warning);
        }
Esempio n. 25
0
        /// <summary>
        /// Handle the object obtained from an ObjectStream's reader
        /// based on its type.
        /// </summary>
        /// <param name="cmdlet">Cmdlet to use for outputting the object.</param>
        /// <param name="overrideInquire">Used by Receive-Job to suppress inquire preference.</param>
        public void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false)
        {
            if (cmdlet != null)
            {
                switch (this.ObjectType)
                {
                case PSStreamObjectType.Output:
                {
                    cmdlet.WriteObject(this.Value);
                }

                break;

                case PSStreamObjectType.Error:
                {
                    ErrorRecord errorRecord = (ErrorRecord)this.Value;
                    errorRecord.PreserveInvocationInfoOnce = true;
                    MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime;
                    if (mshCommandRuntime != null)
                    {
                        mshCommandRuntime.WriteError(errorRecord, overrideInquire);
                    }
                }

                break;

                case PSStreamObjectType.Debug:
                {
                    string            debug             = (string)Value;
                    DebugRecord       debugRecord       = new DebugRecord(debug);
                    MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime;
                    if (mshCommandRuntime != null)
                    {
                        mshCommandRuntime.WriteDebug(debugRecord, overrideInquire);
                    }
                }

                break;

                case PSStreamObjectType.Warning:
                {
                    string            warning           = (string)Value;
                    WarningRecord     warningRecord     = new WarningRecord(warning);
                    MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime;
                    if (mshCommandRuntime != null)
                    {
                        mshCommandRuntime.WriteWarning(warningRecord, overrideInquire);
                    }
                }

                break;

                case PSStreamObjectType.Verbose:
                {
                    string            verbose           = (string)Value;
                    VerboseRecord     verboseRecord     = new VerboseRecord(verbose);
                    MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime;
                    if (mshCommandRuntime != null)
                    {
                        mshCommandRuntime.WriteVerbose(verboseRecord, overrideInquire);
                    }
                }

                break;

                case PSStreamObjectType.Progress:
                {
                    MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime;
                    if (mshCommandRuntime != null)
                    {
                        mshCommandRuntime.WriteProgress((ProgressRecord)Value, overrideInquire);
                    }
                }

                break;

                case PSStreamObjectType.Information:
                {
                    MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime;
                    if (mshCommandRuntime != null)
                    {
                        mshCommandRuntime.WriteInformation((InformationRecord)Value, overrideInquire);
                    }
                }

                break;

                case PSStreamObjectType.WarningRecord:
                {
                    WarningRecord     warningRecord     = (WarningRecord)Value;
                    MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime;
                    if (mshCommandRuntime != null)
                    {
                        mshCommandRuntime.AppendWarningVarList(warningRecord);
                    }
                }

                break;

                case PSStreamObjectType.MethodExecutor:
                {
                    Dbg.Assert(this.Value is ClientMethodExecutor,
                               "Expected psstreamObject.value is ClientMethodExecutor");
                    ClientMethodExecutor methodExecutor = (ClientMethodExecutor)Value;
                    methodExecutor.Execute(cmdlet);
                }

                break;

                case PSStreamObjectType.BlockingError:
                {
                    CmdletMethodInvoker <object> methodInvoker = (CmdletMethodInvoker <object>)Value;
                    InvokeCmdletMethodAndWaitForResults(methodInvoker, cmdlet);
                }

                break;

                case PSStreamObjectType.ShouldMethod:
                {
                    CmdletMethodInvoker <bool> methodInvoker = (CmdletMethodInvoker <bool>)Value;
                    InvokeCmdletMethodAndWaitForResults(methodInvoker, cmdlet);
                }

                break;

                case PSStreamObjectType.Exception:
                {
                    Exception e = (Exception)Value;
                    throw e;
                }
                }
            }
            else if (ObjectType == PSStreamObjectType.Exception)
            {
                Exception e = (Exception)Value;
                throw e;
            }
        }
Esempio n. 26
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="command"></param>
        /// <param name="sb"></param>
        /// <param name="filePath"></param>
        /// <param name="initSb"></param>
        /// <param name="argumentList"></param>
        /// <param name="inputObject"></param>
        /// <param name="psCmdlet"></param>
        /// <param name="currentLocationPath"></param>
        /// <param name="streamingHost"></param>
        public ThreadJob(
            string name,
            string command,
            ScriptBlock sb,
            string filePath,
            ScriptBlock initSb,
            object[] argumentList,
            PSObject inputObject,
            PSCmdlet psCmdlet,
            string currentLocationPath,
            PSHost streamingHost)
            : base(command, name)
        {
            _sb           = sb;
            _filePath     = filePath;
            _initSb       = initSb;
            _argumentList = argumentList;
            _input        = new PSDataCollection <object>();
            if (inputObject != null)
            {
                _input.Add(inputObject);
            }
            _output              = new PSDataCollection <PSObject>();
            _streamingHost       = streamingHost;
            _currentLocationPath = currentLocationPath;

            this.PSJobTypeName = "ThreadJob";

            // Get script block to run.
            if (!string.IsNullOrEmpty(_filePath))
            {
                _sb = GetScriptBlockFromFile(_filePath, psCmdlet);
                if (_sb == null)
                {
                    throw new InvalidOperationException(Properties.Resources.CannotParseScriptFile);
                }
            }
            else if (_sb == null)
            {
                throw new PSArgumentNullException(Properties.Resources.NoScriptToRun);
            }

            // Create Runspace/PowerShell object and state callback.
            // The job script/command will run in a separate thread associated with the Runspace.
            var iss = InitialSessionState.CreateDefault2();

            // Determine session language mode for Windows platforms
            WarningRecord lockdownWarning = null;

            if (Environment.OSVersion.Platform.ToString().Equals("Win32NT", StringComparison.OrdinalIgnoreCase))
            {
                bool enforceLockdown = (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce);
                if (enforceLockdown && !string.IsNullOrEmpty(_filePath))
                {
                    // If script source is a file, check to see if it is trusted by the lock down policy
                    enforceLockdown = (SystemPolicy.GetLockdownPolicy(_filePath, null) == SystemEnforcementMode.Enforce);

                    if (!enforceLockdown && (_initSb != null))
                    {
                        // Even if the script file is trusted, an initialization script cannot be trusted, so we have to enforce
                        // lock down.  Otherwise untrusted script could be run in FullLanguage mode along with the trusted file script.
                        enforceLockdown = true;
                        lockdownWarning = new WarningRecord(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                Properties.Resources.CannotRunTrustedFileInFL,
                                _filePath));
                    }
                }

                iss.LanguageMode = enforceLockdown ? PSLanguageMode.ConstrainedLanguage : PSLanguageMode.FullLanguage;
            }

            if (_streamingHost != null)
            {
                _rs = RunspaceFactory.CreateRunspace(_streamingHost, iss);
            }
            else
            {
                _rs = RunspaceFactory.CreateRunspace(iss);
            }
            _ps          = PowerShell.Create();
            _ps.Runspace = _rs;
            _ps.InvocationStateChanged += (sender, psStateChanged) =>
            {
                var newStateInfo = psStateChanged.InvocationStateInfo;

                // Update Job state.
                switch (newStateInfo.State)
                {
                case PSInvocationState.Running:
                    SetJobState(JobState.Running);
                    break;

                case PSInvocationState.Stopped:
                    SetJobState(JobState.Stopped, newStateInfo.Reason, disposeRunspace: true);
                    break;

                case PSInvocationState.Failed:
                    SetJobState(JobState.Failed, newStateInfo.Reason, disposeRunspace: true);
                    break;

                case PSInvocationState.Completed:
                    if (_runningInitScript)
                    {
                        // Begin running main script.
                        _runningInitScript = false;
                        RunScript();
                    }
                    else
                    {
                        SetJobState(JobState.Completed, newStateInfo.Reason, disposeRunspace: true);
                    }
                    break;
                }
            };

            // Get any using variables.
            var usingAsts = _sb.Ast.FindAll(ast => ast is UsingExpressionAst, searchNestedScriptBlocks: true).Cast <UsingExpressionAst>();

            if (usingAsts != null &&
                usingAsts.FirstOrDefault() != null)
            {
                // Get using variables as dictionary, since we now only support PowerShell version 5.1 and greater
                _usingValuesMap = GetUsingValuesAsDictionary(usingAsts, psCmdlet);
            }

            // Hook up data streams.
            this.Output = _output;
            this.Output.EnumeratorNeverBlocks = true;

            this.Error = _ps.Streams.Error;
            this.Error.EnumeratorNeverBlocks = true;

            this.Progress = _ps.Streams.Progress;
            this.Progress.EnumeratorNeverBlocks = true;

            this.Verbose = _ps.Streams.Verbose;
            this.Verbose.EnumeratorNeverBlocks = true;

            this.Warning = _ps.Streams.Warning;
            this.Warning.EnumeratorNeverBlocks = true;
            if (lockdownWarning != null)
            {
                this.Warning.Add(lockdownWarning);
            }

            this.Debug = _ps.Streams.Debug;
            this.Debug.EnumeratorNeverBlocks = true;

            this.Information = _ps.Streams.Information;
            this.Information.EnumeratorNeverBlocks = true;

            // Create the JobManager job definition and job specification, and add to the JobManager.
            ThreadJobDefinition = new JobDefinition(typeof(ThreadJobSourceAdapter), "", Name);
            Dictionary <string, object> parameterCollection = new Dictionary <string, object>();

            parameterCollection.Add("NewJob", this);
            var jobSpecification = new JobInvocationInfo(ThreadJobDefinition, parameterCollection);
            var newJob           = psCmdlet.JobManager.NewJob(jobSpecification);

            System.Diagnostics.Debug.Assert(newJob == this, "JobManager must return this job");
        }
Esempio n. 27
0
 public PSOutput(WarningRecord warning)
 {
     Stream  = PowerShellStreamType.Warning;
     Warning = warning ?? throw new ArgumentNullException(nameof(warning));
 }
Esempio n. 28
0
 /// <summary>
 /// Constructor taking WarningRecord to wrap and OriginInfo.
 /// </summary>
 /// <param name="warningRecord">WarningRecord to wrap</param>
 /// <param name="originInfo">OriginInfo</param>
 internal RemotingWarningRecord(
     WarningRecord warningRecord,
     OriginInfo originInfo)
     : base(warningRecord.FullyQualifiedWarningId, warningRecord.Message)
 {
     _originInfo = originInfo;
 }
Esempio n. 29
0
 internal RemotingWarningRecord(WarningRecord warningRecord, System.Management.Automation.Remoting.OriginInfo originInfo) : base(warningRecord.FullyQualifiedWarningId, warningRecord.Message)
 {
     this._originInfo = originInfo;
 }
        internal void ProcessReceivedData(RemoteDataObject <PSObject> receivedData)
        {
            if (receivedData.PowerShellId != this.clientPowerShellId)
            {
                throw new PSRemotingDataStructureException(RemotingErrorIdStrings.PipelineIdsDoNotMatch, new object[] { receivedData.PowerShellId, this.clientPowerShellId });
            }
            switch (receivedData.DataType)
            {
            case RemotingDataType.PowerShellOutput:
            {
                object powerShellOutput = RemotingDecoder.GetPowerShellOutput(receivedData.Data);
                this.OutputReceived.SafeInvoke <RemoteDataEventArgs <object> >(this, new RemoteDataEventArgs <object>(powerShellOutput));
                return;
            }

            case RemotingDataType.PowerShellErrorRecord:
            {
                ErrorRecord powerShellError = RemotingDecoder.GetPowerShellError(receivedData.Data);
                this.ErrorReceived.SafeInvoke <RemoteDataEventArgs <ErrorRecord> >(this, new RemoteDataEventArgs <ErrorRecord>(powerShellError));
                return;
            }

            case RemotingDataType.PowerShellStateInfo:
            {
                PSInvocationStateInfo powerShellStateInfo = RemotingDecoder.GetPowerShellStateInfo(receivedData.Data);
                this.InvocationStateInfoReceived.SafeInvoke <RemoteDataEventArgs <PSInvocationStateInfo> >(this, new RemoteDataEventArgs <PSInvocationStateInfo>(powerShellStateInfo));
                return;
            }

            case RemotingDataType.PowerShellDebug:
            {
                DebugRecord powerShellDebug = RemotingDecoder.GetPowerShellDebug(receivedData.Data);
                this.InformationalMessageReceived.SafeInvoke <RemoteDataEventArgs <InformationalMessage> >(this, new RemoteDataEventArgs <InformationalMessage>(new InformationalMessage(powerShellDebug, RemotingDataType.PowerShellDebug)));
                return;
            }

            case RemotingDataType.PowerShellVerbose:
            {
                VerboseRecord powerShellVerbose = RemotingDecoder.GetPowerShellVerbose(receivedData.Data);
                this.InformationalMessageReceived.SafeInvoke <RemoteDataEventArgs <InformationalMessage> >(this, new RemoteDataEventArgs <InformationalMessage>(new InformationalMessage(powerShellVerbose, RemotingDataType.PowerShellVerbose)));
                return;
            }

            case RemotingDataType.PowerShellWarning:
            {
                WarningRecord powerShellWarning = RemotingDecoder.GetPowerShellWarning(receivedData.Data);
                this.InformationalMessageReceived.SafeInvoke <RemoteDataEventArgs <InformationalMessage> >(this, new RemoteDataEventArgs <InformationalMessage>(new InformationalMessage(powerShellWarning, RemotingDataType.PowerShellWarning)));
                return;
            }

            case ((RemotingDataType)0x4100a):
            case ((RemotingDataType)0x4100b):
            case ((RemotingDataType)0x4100c):
            case ((RemotingDataType)0x4100d):
            case ((RemotingDataType)0x4100e):
            case ((RemotingDataType)0x4100f):
                break;

            case RemotingDataType.PowerShellProgress:
            {
                ProgressRecord powerShellProgress = RemotingDecoder.GetPowerShellProgress(receivedData.Data);
                this.InformationalMessageReceived.SafeInvoke <RemoteDataEventArgs <InformationalMessage> >(this, new RemoteDataEventArgs <InformationalMessage>(new InformationalMessage(powerShellProgress, RemotingDataType.PowerShellProgress)));
                return;
            }

            case RemotingDataType.RemoteHostCallUsingPowerShellHost:
            {
                RemoteHostCall data = RemoteHostCall.Decode(receivedData.Data);
                this.HostCallReceived.SafeInvoke <RemoteDataEventArgs <RemoteHostCall> >(this, new RemoteDataEventArgs <RemoteHostCall>(data));
                break;
            }

            default:
                return;
            }
        }
Esempio n. 31
0
        /// <summary>
        /// Handles a robust connection layer notification from the transport
        /// manager.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HandleRobustConnectionNotification(
            object sender,
            ConnectionStatusEventArgs e)
        {
            // Create event arguments and warnings/errors for this robust connection notification.
            PSConnectionRetryStatusEventArgs connectionRetryStatusArgs = null;
            WarningRecord warningRecord = null;
            ErrorRecord errorRecord = null;
            int maxRetryConnectionTimeMSecs = this.runspacePool.MaxRetryConnectionTime;
            int maxRetryConnectionTimeMinutes = maxRetryConnectionTimeMSecs / 60000;
            switch (e.Notification)
            {
                case ConnectionStatus.NetworkFailureDetected:
                    warningRecord = new WarningRecord(
                        PSConnectionRetryStatusEventArgs.FQIDNetworkFailureDetected,
                        StringUtil.Format(RemotingErrorIdStrings.RCNetworkFailureDetected,
                        this.computerName, maxRetryConnectionTimeMinutes));

                    connectionRetryStatusArgs =
                        new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.NetworkFailureDetected,
                            this.computerName, maxRetryConnectionTimeMSecs, warningRecord);
                    break;

                case ConnectionStatus.ConnectionRetryAttempt:
                    warningRecord = new WarningRecord(
                        PSConnectionRetryStatusEventArgs.FQIDConnectionRetryAttempt,
                        StringUtil.Format(RemotingErrorIdStrings.RCConnectionRetryAttempt, this.computerName));

                    connectionRetryStatusArgs =
                        new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.ConnectionRetryAttempt,
                            this.computerName, maxRetryConnectionTimeMSecs, warningRecord);
                    break;

                case ConnectionStatus.ConnectionRetrySucceeded:
                    warningRecord = new WarningRecord(
                        PSConnectionRetryStatusEventArgs.FQIDConnectionRetrySucceeded,
                        StringUtil.Format(RemotingErrorIdStrings.RCReconnectSucceeded, this.computerName));

                    connectionRetryStatusArgs =
                        new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.ConnectionRetrySucceeded,
                            this.computerName, maxRetryConnectionTimeMinutes, warningRecord);
                    break;

                case ConnectionStatus.AutoDisconnectStarting:
                    {
                        warningRecord = new WarningRecord(
                            PSConnectionRetryStatusEventArgs.FQIDAutoDisconnectStarting,
                            StringUtil.Format(RemotingErrorIdStrings.RCAutoDisconnectingWarning, this.computerName));

                        connectionRetryStatusArgs =
                            new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.AutoDisconnectStarting,
                                this.computerName, maxRetryConnectionTimeMinutes, warningRecord);
                    }
                    break;

                case ConnectionStatus.AutoDisconnectSucceeded:
                    warningRecord = new WarningRecord(
                        PSConnectionRetryStatusEventArgs.FQIDAutoDisconnectSucceeded,
                        StringUtil.Format(RemotingErrorIdStrings.RCAutoDisconnected, this.computerName));

                    connectionRetryStatusArgs =
                        new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.AutoDisconnectSucceeded,
                            this.computerName, maxRetryConnectionTimeMinutes, warningRecord);
                    break;

                case ConnectionStatus.InternalErrorAbort:
                    {
                        string msg = StringUtil.Format(RemotingErrorIdStrings.RCInternalError, this.computerName);
                        RuntimeException reason = new RuntimeException(msg);
                        errorRecord = new ErrorRecord(reason,
                            PSConnectionRetryStatusEventArgs.FQIDNetworkOrDisconnectFailed,
                            ErrorCategory.InvalidOperation, this);

                        connectionRetryStatusArgs =
                            new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.InternalErrorAbort,
                                this.computerName, maxRetryConnectionTimeMinutes, errorRecord);
                    }
                    break;
            }

            if (connectionRetryStatusArgs == null)
            {
                return;
            }

            // Update connection status.
            _connectionRetryStatus = connectionRetryStatusArgs.Notification;

            if (warningRecord != null)
            {
                RemotingWarningRecord remotingWarningRecord = new RemotingWarningRecord(
                    warningRecord,
                    new OriginInfo(this.computerName, this.InstanceId));

                // Add warning record to information channel.
                HandleInformationalMessageReceived(this,
                    new RemoteDataEventArgs<InformationalMessage>(
                        new InformationalMessage(remotingWarningRecord, RemotingDataType.PowerShellWarning)));

                // Write warning to host.
                RemoteHostCall writeWarning = new RemoteHostCall(
                    -100,
                    RemoteHostMethodId.WriteWarningLine,
                    new object[] { warningRecord.Message });

                try
                {
                    HandleHostCallReceived(this,
                        new RemoteDataEventArgs<RemoteHostCall>(writeWarning));
                }
                catch (PSNotImplementedException)
                { }
            }

            if (errorRecord != null)
            {
                RemotingErrorRecord remotingErrorRecord = new RemotingErrorRecord(
                    errorRecord,
                    new OriginInfo(this.computerName, this.InstanceId));

                // Add error record to error channel, will also be written to host.
                HandleErrorReceived(this,
                    new RemoteDataEventArgs<ErrorRecord>(remotingErrorRecord));
            }

            // Raise event.
            RCConnectionNotification.SafeInvoke(this, connectionRetryStatusArgs);
        }
Esempio n. 32
0
 /// <summary>
 /// Writes the WarningRecord to informational buffers.
 /// </summary>
 /// <param name="record">WarningRecord</param>
 internal void WriteWarningInfoBuffers(WarningRecord record)
 {
     if (_informationalBuffers != null)
     {
         _informationalBuffers.AddWarning(record);
     }
 }
Esempio n. 33
0
        /// <summary>
        /// Handle the object obtained from an ObjectStream's reader
        /// based on its type.
        /// </summary>
        /// <param name="cmdlet">Cmdlet to use for outputting the object.</param>
        /// <param name="instanceId"></param>
        /// <param name="overrideInquire">Suppresses prompt on messages with Inquire preference.
        /// Needed for Receive-Job</param>
        internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInquire = false)
        {
            switch (ObjectType)
            {
            case PSStreamObjectType.Output:
            {
                if (instanceId != Guid.Empty)
                {
                    PSObject o = Value as PSObject;
                    if (o != null)
                    {
                        AddSourceJobNoteProperty(o, instanceId);
                    }
                }

                cmdlet.WriteObject(Value);
            }

            break;

            case PSStreamObjectType.Error:
            {
                ErrorRecord         errorRecord       = (ErrorRecord)this.Value;
                RemotingErrorRecord remoteErrorRecord = errorRecord as RemotingErrorRecord;

                if (remoteErrorRecord == null)
                {
                    // if we get a base ErrorRecord object, check if the computerName is
                    // populated in the RecommendedAction field
                    if (errorRecord.ErrorDetails != null && !string.IsNullOrEmpty(errorRecord.ErrorDetails.RecommendedAction))
                    {
                        string computerName;
                        Guid   jobInstanceId;
                        GetIdentifierInfo(errorRecord.ErrorDetails.RecommendedAction,
                                          out jobInstanceId, out computerName);

                        errorRecord = new RemotingErrorRecord(errorRecord,
                                                              new OriginInfo(computerName, Guid.Empty,
                                                                             jobInstanceId));
                    }
                }
                else
                {
                    errorRecord = remoteErrorRecord;
                }

                errorRecord.PreserveInvocationInfoOnce = true;
                MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime;
                if (mshCommandRuntime != null)
                {
                    mshCommandRuntime.WriteError(errorRecord, overrideInquire);
                }
            }

            break;

            case PSStreamObjectType.Warning:
            {
                string            warning           = (string)Value;
                WarningRecord     warningRecord     = new WarningRecord(warning);
                MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime;
                if (mshCommandRuntime != null)
                {
                    mshCommandRuntime.WriteWarning(warningRecord, overrideInquire);
                }
            }

            break;

            case PSStreamObjectType.Verbose:
            {
                string            verbose           = (string)Value;
                VerboseRecord     verboseRecord     = new VerboseRecord(verbose);
                MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime;
                if (mshCommandRuntime != null)
                {
                    mshCommandRuntime.WriteVerbose(verboseRecord, overrideInquire);
                }
            }

            break;

            case PSStreamObjectType.Progress:
            {
                ProgressRecord progressRecord = (ProgressRecord)Value;

                RemotingProgressRecord remotingProgressRecord = progressRecord as RemotingProgressRecord;
                if (remotingProgressRecord == null)
                {
                    Guid   jobInstanceId;
                    string computerName;
                    GetIdentifierInfo(progressRecord.CurrentOperation, out jobInstanceId,
                                      out computerName);
                    OriginInfo info = new OriginInfo(computerName, Guid.Empty, jobInstanceId);
                    progressRecord = new RemotingProgressRecord(progressRecord, info);
                }
                else
                {
                    progressRecord = remotingProgressRecord;
                }

                MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime;
                if (mshCommandRuntime != null)
                {
                    mshCommandRuntime.WriteProgress(progressRecord, overrideInquire);
                }
            }

            break;

            case PSStreamObjectType.Debug:
            {
                string            debug             = (string)Value;
                DebugRecord       debugRecord       = new DebugRecord(debug);
                MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime;
                if (mshCommandRuntime != null)
                {
                    mshCommandRuntime.WriteDebug(debugRecord, overrideInquire);
                }
            }

            break;

            case PSStreamObjectType.Information:
            {
                InformationRecord         informationRecord       = (InformationRecord)this.Value;
                RemotingInformationRecord remoteInformationRecord = informationRecord as RemotingInformationRecord;

                if (remoteInformationRecord == null)
                {
                    // if we get a base InformationRecord object, check if the computerName is
                    // populated in the Source field
                    if (!string.IsNullOrEmpty(informationRecord.Source))
                    {
                        string computerName;
                        Guid   jobInstanceId;
                        GetIdentifierInfo(informationRecord.Source, out jobInstanceId, out computerName);
                        informationRecord = new RemotingInformationRecord(informationRecord,
                                                                          new OriginInfo(computerName, Guid.Empty,
                                                                                         jobInstanceId));
                    }
                }
                else
                {
                    informationRecord = remoteInformationRecord;
                }

                MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime;
                if (mshCommandRuntime != null)
                {
                    mshCommandRuntime.WriteInformation(informationRecord, overrideInquire);
                }
            }

            break;

            case PSStreamObjectType.WarningRecord:
            case PSStreamObjectType.MethodExecutor:
            case PSStreamObjectType.BlockingError:
            case PSStreamObjectType.ShouldMethod:
            {
                WriteStreamObject(cmdlet, overrideInquire);
            }

            break;
            }
        }
Esempio n. 34
0
 private void SyncWarningReady(ScriptRunner sender, WarningRecord data)
 {
     OnWarningReady(this, data);
 }