コード例 #1
0
ファイル: Command.cs プロジェクト: soulhakr/Pash
        internal void SetMergeResultOptions(CommandProcessorBase procBase)
        {
            var rt = procBase.CommandRuntime;

            rt.MergeErrorToOutput = (MergeMyResult.Equals(PipelineResultTypes.Error) &&
                                     MergeToResult.Equals(PipelineResultTypes.Output));
            rt.MergeUnclaimedPreviousErrors = MergeUnclaimedPreviousCommandResults != PipelineResultTypes.None;
        }
コード例 #2
0
        /// <summary>
        /// End Processing
        /// </summary>
        protected override void EndProcessing()
        {
            // Check for host that supports interactive remote sessions.
            _interactiveHost = this.Host as IHostSupportsInteractiveSession;
            if (_interactiveHost == null)
            {
                WriteError(
                    new ErrorRecord(
                        new ArgumentException(RemotingErrorIdStrings.HostDoesNotSupportIASession),
                        "EnterPSHostProcessHostDoesNotSupportIASession",
                        ErrorCategory.InvalidArgument,
                        null));

                return;
            }

            // Check selected process for existence, and whether it hosts PowerShell.
            switch (ParameterSetName)
            {
            case ProcessIdParameterSet:
                Process = GetProcessById(Id);
                break;

            case ProcessNameParameterSet:
                Process = GetProcessByName(Name);
                break;

            case PSHostProcessInfoParameterSet:
                Process = GetProcessByHostProcessInfo(HostProcessInfo);
                break;
            }
            VerifyProcess(Process);

            // Create named pipe runspace for selected process and open.
            Runspace namedPipeRunspace = CreateNamedPipeRunspace(Process.Id, AppDomainName);

            // Set runspace prompt.  The runspace is closed on pop so we don't
            // have to reverse this change.
            PrepareRunspace(namedPipeRunspace);

            try
            {
                // Push runspace onto host.
                _interactiveHost.PushRunspace(namedPipeRunspace);
            }
            catch (Exception e)
            {
                CommandProcessorBase.CheckForSevereException(e);
                namedPipeRunspace.Close();

                ThrowTerminatingError(
                    new ErrorRecord(
                        e,
                        "EnterPSHostProcessCannotPushRunspace",
                        ErrorCategory.InvalidOperation,
                        this));
            }
        }
コード例 #3
0
        private static Type LookForTypeInAssemblies(TypeName typeName, IEnumerable <Assembly> assemblies, TypeResolutionState typeResolutionState, bool reportAmbiguousException, out Exception exception)
        {
            exception = null;
            string alternateNameToFind = typeResolutionState.GetAlternateTypeName(typeName.Name);
            Type   foundType           = null;
            Type   foundType2          = null;

            foreach (Assembly assembly in assemblies)
            {
                try
                {
                    Type targetType = LookForTypeInSingleAssembly(assembly, typeName.Name);;
                    if (targetType == null && alternateNameToFind != null)
                    {
                        targetType = LookForTypeInSingleAssembly(assembly, alternateNameToFind);
                    }

                    if (targetType != null)
                    {
                        if (!reportAmbiguousException)
                        {
                            // accelerator  for the common case, when we are not interested  in ambiguity exception.
                            return(targetType);
                        }

                        // .NET has forward notation for types, when they declared in one assembly and implemented in another one.
                        // We want to support both scenarios:
                        // 1) When we pass assembly with declared forwarded type (CoreCLR)
                        // 2) When we pass assembly with declared forwarded type and assembly with implemented forwarded type (FullCLR)
                        // In the case (2) we should not report duplicate, hence this check
                        if (foundType != targetType)
                        {
                            if (foundType != null)
                            {
                                foundType2 = targetType;
                                break;
                            }
                            else
                            {
                                foundType = targetType;
                            }
                        }
                    }
                }
                catch (Exception e) // Assembly.GetType might throw unadvertised exceptions
                {
                    CommandProcessorBase.CheckForSevereException(e);
                }
            }

            if (foundType2 != null)
            {
                exception = new AmbiguousTypeException(typeName, new String[] { foundType.AssemblyQualifiedName, foundType2.AssemblyQualifiedName });
                return(null);
            }

            return(foundType);
        }
コード例 #4
0
ファイル: Command.cs プロジェクト: soulhakr/Pash
        // internals
        //internal Command Clone();
        //internal Command(Command command);
        internal CommandProcessorBase CreateCommandProcessor(ExecutionContext executionContext, CommandManager commandFactory, bool addToHistory)
        {
            CommandProcessorBase cmdProcBase = commandFactory.CreateCommandProcessor(this);

            cmdProcBase.ExecutionContext = executionContext;
            cmdProcBase.AddParameters(Parameters);
            SetMergeResultOptions(cmdProcBase);
            return(cmdProcBase);
        }
コード例 #5
0
        // Create a new command in the shell context.
        internal void CreateCommand(
            IntPtr pluginContext,
            WSManNativeApi.WSManPluginRequest requestDetails,
            int flags,
            string commandLine,
            WSManNativeApi.WSManCommandArgSet arguments)
        {
            try
            {
                // inbound cmd information is already verified.. so no need to verify here.
                WSManPluginCommandTransportManager serverCmdTransportMgr = new WSManPluginCommandTransportManager(transportMgr);
                serverCmdTransportMgr.Initialize();

                // Apply quota limits on the command transport manager
                _remoteSession.ApplyQuotaOnCommandTransportManager(serverCmdTransportMgr);

                WSManPluginCommandSession mgdCmdSession = new WSManPluginCommandSession(requestDetails, serverCmdTransportMgr, _remoteSession);
                AddToActiveCmdSessions(mgdCmdSession);
                mgdCmdSession.SessionClosed += new EventHandler <EventArgs>(this.HandleCommandSessionClosed);

                mgdCmdSession.shutDownContext = new WSManPluginOperationShutdownContext(
                    pluginContext,
                    creationRequestDetails.unmanagedHandle,
                    mgdCmdSession.creationRequestDetails.unmanagedHandle,
                    false);

                do
                {
                    if (!mgdCmdSession.ProcessArguments(arguments))
                    {
                        WSManPluginInstance.ReportOperationComplete(
                            requestDetails,
                            WSManPluginErrorCodes.InvalidArgSet,
                            StringUtil.Format(
                                RemotingErrorIdStrings.WSManPluginInvalidArgSet,
                                "WSManPluginCommand"));
                        break;
                    }

                    // Report plugin context to WSMan
                    mgdCmdSession.ReportContext();
                } while (false);
            }
            catch (System.Exception e)
            {
                CommandProcessorBase.CheckForSevereException(e);

                // if there is an exception creating remote session send the message to client.
                WSManPluginInstance.ReportOperationComplete(
                    requestDetails,
                    WSManPluginErrorCodes.ManagedException,
                    StringUtil.Format(
                        RemotingErrorIdStrings.WSManPluginManagedException,
                        e.Message));
            }
        }
コード例 #6
0
        private string ValidateComputerNames(string computer)
        {
            IPAddress pAddress = null;
            string    str;
            string    str1 = null;

            if (computer.Equals(".", StringComparison.OrdinalIgnoreCase) || computer.Equals("localhost", StringComparison.OrdinalIgnoreCase) || computer.Equals(this._shortLocalMachineName, StringComparison.OrdinalIgnoreCase) || computer.Equals(this._fullLocalMachineName, StringComparison.OrdinalIgnoreCase))
            {
                str1 = "localhost";
            }
            else
            {
                bool flag = false;
                try
                {
                    flag = IPAddress.TryParse(computer, out pAddress);
                }
                catch (Exception exception1)
                {
                    Exception exception = exception1;
                    CommandProcessorBase.CheckForSevereException(exception);
                }
                try
                {
                    string hostName = Dns.GetHostEntry(computer).HostName;
                    if (hostName.Equals(this._shortLocalMachineName, StringComparison.OrdinalIgnoreCase) || hostName.Equals(this._fullLocalMachineName, StringComparison.OrdinalIgnoreCase))
                    {
                        str1 = "localhost";
                    }
                    else
                    {
                        str1 = computer;
                    }
                    return(str1);
                }
                catch (Exception exception3)
                {
                    Exception exception2 = exception3;
                    CommandProcessorBase.CheckForSevereException(exception2);
                    if (flag)
                    {
                        str1 = computer;
                        return(str1);
                    }
                    else
                    {
                        string      str2        = StringUtil.Format(ComputerResources.CannotResolveComputerName, computer, exception2.Message);
                        ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(str2), "AddressResolutionException", ErrorCategory.InvalidArgument, computer);
                        base.WriteError(errorRecord);
                        str = null;
                    }
                }
                return(str);
            }
            return(str1);
        }
コード例 #7
0
        /// <summary>
        /// Raises events for changes in execution state.
        /// </summary>
        protected void RaisePipelineStateEvents()
        {
            Queue <ExecutionEventQueueItem>       tempEventQueue = null;
            EventHandler <PipelineStateEventArgs> stateChanged   = null;
            bool runspaceHasAvailabilityChangedSubscribers       = false;

            lock (SyncRoot)
            {
                stateChanged = this.StateChanged;
                runspaceHasAvailabilityChangedSubscribers = _runspace.HasAvailabilityChangedSubscribers;

                if (stateChanged != null || runspaceHasAvailabilityChangedSubscribers)
                {
                    tempEventQueue       = _executionEventQueue;
                    _executionEventQueue = new Queue <ExecutionEventQueueItem>();
                }
                else
                {
                    //Clear the events if there are no EventHandlers. This
                    //ensures that events do not get called for state
                    //changes prior to their registration.
                    _executionEventQueue.Clear();
                }
            }

            if (tempEventQueue != null)
            {
                while (tempEventQueue.Count > 0)
                {
                    ExecutionEventQueueItem queueItem = tempEventQueue.Dequeue();

                    if (runspaceHasAvailabilityChangedSubscribers && queueItem.NewRunspaceAvailability != queueItem.CurrentRunspaceAvailability)
                    {
                        _runspace.RaiseAvailabilityChangedEvent(queueItem.NewRunspaceAvailability);
                    }

                    // this is shipped as part of V1. So disabling the warning here.
#pragma warning disable 56500
                    //Exception rasied in the eventhandler are not error in pipeline.
                    //silently ignore them.
                    if (stateChanged != null)
                    {
                        try
                        {
                            stateChanged(this, new PipelineStateEventArgs(queueItem.PipelineStateInfo));
                        }
                        catch (Exception exception) // ignore non-severe exceptions
                        {
                            CommandProcessorBase.CheckForSevereException(exception);
                        }
                    }
#pragma warning restore 56500
                }
            }
        }
コード例 #8
0
 private void CloseThreadProc()
 {
     try
     {
         this.DoCloseHelper();
     }
     catch (Exception exception)
     {
         CommandProcessorBase.CheckForSevereException(exception);
     }
 }
コード例 #9
0
        internal void LinkPipelineSuccessOutput(Pipe pipeToUse)
        {
            CommandProcessorBase base2 = this._commands[this._commands.Count - 1];

            if ((base2 == null) || (base2.CommandRuntime == null))
            {
                throw PSTraceSource.NewInvalidOperationException();
            }
            base2.CommandRuntime.OutputPipe = pipeToUse;
            this._linkedSuccessOutput       = true;
        }
コード例 #10
0
ファイル: WinSQMWrapper.cs プロジェクト: mmoenfly/GitCook2021
 public static bool IsWinSqmOptedIn()
 {
     try
     {
         return(WinSQMWrapper.WinSqmIsOptedIn());
     }
     catch (Exception ex)
     {
         CommandProcessorBase.CheckForSevereException(ex);
     }
     return(false);
 }
コード例 #11
0
 internal void ServicePendingCallbacks(object objectToProcess)
 {
     tracer.WriteLine("ServicePendingCallbacks thread is starting", new object[0]);
     PSEtwLog.ReplaceActivityIdForCurrentThread(this.runspacePoolInstanceId, PSEventId.OperationalTransferEventRunspacePool, PSEventId.AnalyticTransferEventRunspacePool, PSKeyword.Transport, PSTask.None);
     try
     {
         while (!this.isClosed)
         {
             CallbackNotificationInformation information = null;
             lock (this.callbackNotificationQueue)
             {
                 if ((this.callbackNotificationQueue.Count <= 0) || this.suspendQueueServicing)
                 {
                     return;
                 }
                 information = this.callbackNotificationQueue.Dequeue();
             }
             if (information != null)
             {
                 if (information.transportError != null)
                 {
                     this.RaiseErrorHandler(information.transportError);
                     return;
                 }
                 if (information.privateData != null)
                 {
                     this.ProcessPrivateData(information.privateData);
                 }
                 else
                 {
                     base.OnDataAvailableCallback(information.remoteObject);
                 }
             }
         }
     }
     catch (Exception exception)
     {
         CommandProcessorBase.CheckForSevereException(exception);
         tracer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Exception processing data. {0}", new object[] { exception.Message }), new object[0]);
         PSRemotingTransportException   e         = new PSRemotingTransportException(exception.Message, exception);
         TransportErrorOccuredEventArgs eventArgs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.ReceiveShellOutputEx);
         this.RaiseErrorHandler(eventArgs);
     }
     finally
     {
         lock (this.callbackNotificationQueue)
         {
             tracer.WriteLine("ServicePendingCallbacks thread is exiting", new object[0]);
             this.isServicingCallbacks = false;
             this.EnqueueAndStartProcessingThread(null, null, null);
         }
     }
 }
コード例 #12
0
        private void HandleSessionClosed(object sender, RemoteDataEventArgs <Exception> eventArgs)
        {
            RunspacePoolState     state;
            RunspacePoolStateInfo info;

            if (eventArgs.Data != null)
            {
                this.closingReason = eventArgs.Data;
            }
            lock (base.syncObject)
            {
                state = base.stateInfo.State;
                switch (state)
                {
                case RunspacePoolState.Opening:
                case RunspacePoolState.Opened:
                case RunspacePoolState.Disconnecting:
                case RunspacePoolState.Disconnected:
                case RunspacePoolState.Connecting:
                    this.SetRunspacePoolState(new RunspacePoolStateInfo(RunspacePoolState.Broken, this.closingReason));
                    break;

                case RunspacePoolState.Closing:
                    this.SetRunspacePoolState(new RunspacePoolStateInfo(RunspacePoolState.Closed, this.closingReason));
                    break;
                }
                info = new RunspacePoolStateInfo(base.stateInfo.State, base.stateInfo.Reason);
            }
            try
            {
                base.RaiseStateChangeEvent(info);
            }
            catch (Exception exception)
            {
                CommandProcessorBase.CheckForSevereException(exception);
            }
            switch (state)
            {
            case RunspacePoolState.Disconnecting:
            case RunspacePoolState.Disconnected:
                this.SetDisconnectAsCompleted();
                break;

            default:
                if (state == RunspacePoolState.Connecting)
                {
                    this.SetReconnectAsCompleted();
                }
                break;
            }
            this.SetCloseAsCompleted();
        }
コード例 #13
0
        /// <summary>
        /// Commits the current transaction
        /// </summary>
        protected override void EndProcessing()
        {
            using (CurrentPSTransaction)
            {
                try
                {
                    var emptyArray = Utils.EmptyArray <object>();
                    _transactedScript.InvokeUsingCmdlet(
                        contextCmdlet: this,
                        useLocalScope: false,
                        errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe,
                        dollarUnder: null,
                        input: emptyArray,
                        scriptThis: AutomationNull.Value,
                        args: emptyArray);
                }
                catch (Exception e)
                {
                    // Catch-all OK. This is a third-party call-out.
                    CommandProcessorBase.CheckForSevereException(e);

                    ErrorRecord errorRecord = new ErrorRecord(e, "TRANSACTED_SCRIPT_EXCEPTION", ErrorCategory.NotSpecified, null);

                    // The "transaction timed out" exception is
                    // exceedingly obtuse. We clarify things here.
                    bool      isTimeoutException = false;
                    Exception tempException      = e;
                    while (tempException != null)
                    {
                        if (tempException is System.TimeoutException)
                        {
                            isTimeoutException = true;
                            break;
                        }

                        tempException = tempException.InnerException;
                    }

                    if (isTimeoutException)
                    {
                        errorRecord = new ErrorRecord(
                            new InvalidOperationException(
                                TransactionResources.TransactionTimedOut),
                            "TRANSACTION_TIMEOUT",
                            ErrorCategory.InvalidOperation,
                            e);
                    }

                    WriteError(errorRecord);
                }
            }
        }
コード例 #14
0
 private void OnOutputDataReceived(object sender, DataReceivedEventArgs e)
 {
     try
     {
         OutOfProcessUtils.ProcessData(e.Data, this.dataProcessingCallbacks);
     }
     catch (Exception exception)
     {
         CommandProcessorBase.CheckForSevereException(exception);
         PSRemotingTransportException exception2 = new PSRemotingTransportException(PSRemotingErrorId.IPCErrorProcessingServerData, RemotingErrorIdStrings.IPCErrorProcessingServerData, new object[] { exception.Message });
         this.RaiseErrorHandler(new TransportErrorOccuredEventArgs(exception2, TransportMethodEnum.ReceiveShellOutputEx));
     }
 }
コード例 #15
0
 internal void ServicePendingCallbacks(object objectToProcess)
 {
     BaseClientTransportManager.tracer.WriteLine("ServicePendingCallbacks thread is starting", new object[0]);
     BaseTransportManager.ETWTracer.ReplaceActivityIdForCurrentThread(this.runspacePoolInstanceId, PSEventId.OperationalTransferEventRunspacePool, PSEventId.AnalyticTransferEventRunspacePool, PSKeyword.Transport, PSTask.None);
     try
     {
         while (!this.isClosed)
         {
             BaseClientTransportManager.ReceivedDataInformation receivedDataInformation = (BaseClientTransportManager.ReceivedDataInformation)null;
             lock (this.callbackNotificationQueue)
             {
                 if (this.callbackNotificationQueue.Count <= 0)
                 {
                     break;
                 }
                 receivedDataInformation = this.callbackNotificationQueue.Dequeue();
             }
             if (receivedDataInformation != null)
             {
                 if (receivedDataInformation.transportException != null)
                 {
                     this.RaiseErrorHandler(new TransportErrorOccuredEventArgs(receivedDataInformation.transportException, TransportMethodEnum.ReceiveShellOutputEx));
                     break;
                 }
                 if (receivedDataInformation.privateData != null)
                 {
                     this.ProcessPrivateData(receivedDataInformation.privateData);
                 }
                 else
                 {
                     this.OnDataAvailableCallback(receivedDataInformation.remoteObject);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         CommandProcessorBase.CheckForSevereException(ex);
         BaseClientTransportManager.tracer.WriteLine(string.Format((IFormatProvider)CultureInfo.InvariantCulture, "Exception processing data. {0}", (object)ex.Message), new object[0]);
         this.RaiseErrorHandler(new TransportErrorOccuredEventArgs(new PSRemotingTransportException(ex.Message), TransportMethodEnum.ReceiveShellOutputEx));
     }
     finally
     {
         lock (this.callbackNotificationQueue)
         {
             BaseClientTransportManager.tracer.WriteLine("ServicePendingCallbacks thread is exiting", new object[0]);
             this.isServicingCallbacks = false;
             this.EnqueueAndStartProcessingThread((RemoteDataObject <PSObject>)null, (PSRemotingTransportException)null, (object)null);
         }
     }
 }
コード例 #16
0
ファイル: Command.cs プロジェクト: whatevergeek/poshvx
        SetMergeSettingsOnCommandProcessor(CommandProcessorBase commandProcessor)
        {
            Dbg.Assert(commandProcessor != null, "caller should valiadate the parameter");

            MshCommandRuntime mcr = commandProcessor.Command.commandRuntime as MshCommandRuntime;

            if (_mergeUnclaimedPreviousCommandResults != PipelineResultTypes.None)
            {
                //Currently only merging previous unclaimed error and output is supported.
                if (mcr != null)
                {
                    mcr.MergeUnclaimedPreviousErrorResults = true;
                }
            }

            // Error merge.
            if (MergeInstructions[(int)MergeType.Error] == PipelineResultTypes.Output)
            {
                //Currently only merging error with output is supported.
                mcr.ErrorMergeTo = MshCommandRuntime.MergeDataStream.Output;
            }

            // Warning merge.
            PipelineResultTypes toType = MergeInstructions[(int)MergeType.Warning];

            if (toType != PipelineResultTypes.None)
            {
                mcr.WarningOutputPipe = GetRedirectionPipe(toType, mcr);
            }

            // Verbose merge.
            toType = MergeInstructions[(int)MergeType.Verbose];
            if (toType != PipelineResultTypes.None)
            {
                mcr.VerboseOutputPipe = GetRedirectionPipe(toType, mcr);
            }

            // Debug merge.
            toType = MergeInstructions[(int)MergeType.Debug];
            if (toType != PipelineResultTypes.None)
            {
                mcr.DebugOutputPipe = GetRedirectionPipe(toType, mcr);
            }

            // Information merge.
            toType = MergeInstructions[(int)MergeType.Information];
            if (toType != PipelineResultTypes.None)
            {
                mcr.InformationOutputPipe = GetRedirectionPipe(toType, mcr);
            }
        }
コード例 #17
0
 private void CoreInvoke(IEnumerable input, bool syncCall)
 {
     using (PipelineBase._trace.TraceMethod())
     {
         lock (this.SyncRoot)
         {
             if (this._disposed)
             {
                 throw PipelineBase._trace.NewObjectDisposedException("pipeline");
             }
             if (this.Commands == null || this.Commands.Count == 0)
             {
                 throw PipelineBase._trace.NewInvalidOperationException("Runspace", "NoCommandInPipeline");
             }
             if (this.PipelineState != PipelineState.NotStarted)
             {
                 InvalidPipelineStateException pipelineStateException = new InvalidPipelineStateException(ResourceManagerCache.FormatResourceString("Runspace", "PipelineReInvokeNotAllowed"), this.PipelineState, PipelineState.NotStarted);
                 PipelineBase._trace.TraceException((Exception)pipelineStateException);
                 throw pipelineStateException;
             }
             if (syncCall)
             {
                 if (input != null)
                 {
                     foreach (object obj in input)
                     {
                         this._inputStream.Write(obj);
                     }
                 }
                 this._inputStream.Close();
             }
             this._syncInvokeCall        = syncCall;
             this._pipelineFinishedEvent = new ManualResetEvent(false);
             this.RunspaceBase.DoConcurrentCheckAndAddToRunningPipelines(this, syncCall);
             this.SetPipelineState(PipelineState.Running);
         }
         try
         {
             this.StartPipelineExecution();
         }
         catch (Exception ex)
         {
             CommandProcessorBase.CheckForSevereException(ex);
             PipelineBase._trace.TraceException(ex);
             this.RunspaceBase.RemoveFromRunningPipelineList(this);
             this.SetPipelineState(PipelineState.Failed, ex);
             throw;
         }
     }
 }
コード例 #18
0
ファイル: PSSQMAPI.cs プロジェクト: modulexcite/pash-1
 public static void NoteWorkflowOutputStreamSize(int size, string streamType)
 {
     if (isWinSQMEnabled)
     {
         try
         {
             WinSQMWrapper.WinSqmAddToStream(0x269a, streamType, size);
         }
         catch (Exception exception)
         {
             CommandProcessorBase.CheckForSevereException(exception);
         }
     }
 }
コード例 #19
0
ファイル: PSSQMAPI.cs プロジェクト: modulexcite/pash-1
 public static void NoteSessionConfigurationIdleTimeout(int idleTimeout)
 {
     if (isWinSQMEnabled)
     {
         try
         {
             WinSQMWrapper.WinSqmAddToStream(0x209f, idleTimeout.ToString(CultureInfo.InvariantCulture));
         }
         catch (Exception exception)
         {
             CommandProcessorBase.CheckForSevereException(exception);
         }
     }
 }
コード例 #20
0
ファイル: PSSQMAPI.cs プロジェクト: modulexcite/pash-1
 public static void NoteWorkflowEndpointConfiguration(string quotaName, int data)
 {
     if (isWinSQMEnabled)
     {
         try
         {
             WinSQMWrapper.WinSqmAddToStream(0x2699, quotaName, data);
         }
         catch (Exception exception)
         {
             CommandProcessorBase.CheckForSevereException(exception);
         }
     }
 }
コード例 #21
0
ファイル: PSSQMAPI.cs プロジェクト: modulexcite/pash-1
 public static void NoteSessionConfigurationOutputBufferingMode(string optBufferingMode)
 {
     if (isWinSQMEnabled)
     {
         try
         {
             WinSQMWrapper.WinSqmAddToStream(0x20b8, optBufferingMode);
         }
         catch (Exception exception)
         {
             CommandProcessorBase.CheckForSevereException(exception);
         }
     }
 }
コード例 #22
0
ファイル: PSSQMAPI.cs プロジェクト: modulexcite/pash-1
 public static void NoteWorkflowCommonParametersValues(string parameterName, int data)
 {
     if (isWinSQMEnabled)
     {
         try
         {
             WinSQMWrapper.WinSqmAddToStream(0x268d, parameterName, data);
         }
         catch (Exception exception)
         {
             CommandProcessorBase.CheckForSevereException(exception);
         }
     }
 }
コード例 #23
0
 private void SetupOutErrorVariable()
 {
     for (int i = 0; i < this._commands.Count; i++)
     {
         CommandProcessorBase base2 = this._commands[i];
         if ((base2 == null) || (base2.CommandRuntime == null))
         {
             throw PSTraceSource.NewInvalidOperationException();
         }
         base2.CommandRuntime.SetupOutVariable();
         base2.CommandRuntime.SetupErrorVariable();
         base2.CommandRuntime.SetupWarningVariable();
     }
 }
コード例 #24
0
 private void ProcessingThreadStart(object state)
 {
     try
     {
         OutOfProcessUtils.ProcessData(state as string, this.callbacks);
     }
     catch (Exception ex)
     {
         CommandProcessorBase.CheckForSevereException(ex);
         OutOfProcessMediator.ETWTracer.OperationalChannel.WriteError(PSEventId.TransportError, PSOpcode.Open, PSTask.None, (object)Guid.Empty, (object)Guid.Empty, (object)4000, (object)ex.Message, (object)ex.StackTrace);
         OutOfProcessMediator.ETWTracer.AnalyticChannel.WriteError(PSEventId.TransportError_Analytic, PSOpcode.Open, PSTask.None, (object)Guid.Empty, (object)Guid.Empty, (object)4000, (object)ex.Message, (object)ex.StackTrace);
         this.originalStdErr.WriteLine(ex.Message + ex.StackTrace);
         Environment.Exit(4000);
     }
 }
コード例 #25
0
 private void SetExternalErrorOutput()
 {
     if (this.ExternalErrorOutput != null)
     {
         for (int i = 0; i < this._commands.Count; i++)
         {
             CommandProcessorBase base2 = this._commands[i];
             Pipe errorOutputPipe       = base2.CommandRuntime.ErrorOutputPipe;
             if (!errorOutputPipe.IsRedirected)
             {
                 errorOutputPipe.ExternalWriter = this.ExternalErrorOutput;
             }
         }
     }
 }
コード例 #26
0
        internal bool ItemExists(string path, CmdletProviderContext context)
        {
            base.Context = context;
            bool flag = false;

            try
            {
                flag = this.ItemExists(path);
            }
            catch (Exception exception)
            {
                CommandProcessorBase.CheckForSevereException(exception);
            }
            return(flag);
        }
コード例 #27
0
 internal virtual void ProcessRawData(byte[] data, string stream)
 {
     try
     {
         this.ProcessRawData(data, stream, this.onDataAvailableCallback);
     }
     catch (Exception exception)
     {
         CommandProcessorBase.CheckForSevereException(exception);
         baseTracer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Exception processing data. {0}", new object[] { exception.Message }), new object[0]);
         PSRemotingTransportException   e         = new PSRemotingTransportException(exception.Message, exception);
         TransportErrorOccuredEventArgs eventArgs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.ReceiveShellOutputEx);
         this.RaiseErrorHandler(eventArgs);
     }
 }
コード例 #28
0
 private static string SafeToString(object obj)
 {
     if (obj != null)
     {
         try
         {
             return(obj.ToString());
         }
         catch (Exception exception)
         {
             CommandProcessorBase.CheckForSevereException(exception);
         }
     }
     return("");
 }
コード例 #29
0
        protected override void OnAvailabilityChanged(RunspaceAvailabilityEventArgs e)
        {
            EventHandler <RunspaceAvailabilityEventArgs> availabilityChanged = this.AvailabilityChanged;

            if (availabilityChanged != null)
            {
                try
                {
                    availabilityChanged(this, e);
                }
                catch (Exception exception)
                {
                    CommandProcessorBase.CheckForSevereException(exception);
                }
            }
        }
コード例 #30
0
 private void ProcessingThreadStart(object state)
 {
     try
     {
         string data = state as string;
         OutOfProcessUtils.ProcessData(data, this.callbacks);
     }
     catch (Exception exception)
     {
         CommandProcessorBase.CheckForSevereException(exception);
         PSEtwLog.LogOperationalError(PSEventId.TransportError, PSOpcode.Open, PSTask.None, PSKeyword.UseAlwaysOperational, new object[] { Guid.Empty.ToString(), Guid.Empty.ToString(), 0xfa0, exception.Message, exception.StackTrace });
         PSEtwLog.LogAnalyticError(PSEventId.TransportError_Analytic, PSOpcode.Open, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, new object[] { Guid.Empty.ToString(), Guid.Empty.ToString(), 0xfa0, exception.Message, exception.StackTrace });
         this.originalStdErr.WriteLine(exception.Message + exception.StackTrace);
         Environment.Exit(0xfa0);
     }
 }
コード例 #31
0
ファイル: PipelineProcessor.cs プロジェクト: mauve/Pash
 public void Add(CommandProcessorBase commandProcessor)
 {
     var commandCount = _commandsToExecute.Count;
     var commandInput = commandProcessor.CommandRuntime.InputStream;
     // redirect output of last command to new input
     if (commandCount > 0)
     {
         var lastCommand = _commandsToExecute[commandCount - 1];
         lastCommand.CommandRuntime.OutputStream.Redirect(commandInput);
     }
     // check if the command collets previous error results
     if (commandCount >  0 &&
         commandProcessor.CommandRuntime.MergeUnclaimedPreviousErrors)
     {
         foreach (var prevCommand in _commandsToExecute)
         {
             if (prevCommand.CommandRuntime.ErrorStream.ClaimedBy == null)
             {
                 prevCommand.CommandRuntime.ErrorStream.Redirect(commandInput);
             }
         }
     }
     _commandsToExecute.Add(commandProcessor);
 }
コード例 #32
0
ファイル: pipeline.cs プロジェクト: 40a/PowerShell
 /// <summary>
 /// Add a single InternalCommand to the end of the pipeline
 /// </summary>
 /// <returns>Results from last pipeline stage</returns>
 /// <exception cref="InvalidOperationException">
 /// see AddCommand
 /// </exception>
 /// <exception cref="ObjectDisposedException"></exception>
 internal int Add(CommandProcessorBase commandProcessor)
 {
     commandProcessor.CommandRuntime.PipelineProcessor = this;
     return AddCommand(commandProcessor, _commands.Count, false);
 }
コード例 #33
0
ファイル: pipeline.cs プロジェクト: 40a/PowerShell
        } // internal Array SynchronousExecuteEnumerate()

        private void DoCompleteCore(CommandProcessorBase commandRequestingUpstreamCommandsToStop)
        {
            // Call DoComplete() for all the commands. DoComplete() will internally call Complete()
            MshCommandRuntime lastCommandRuntime = null;

            if (_commands != null)
            {
                for (int i = 0; i < _commands.Count; i++)
                {
                    CommandProcessorBase commandProcessor = _commands[i];

                    if (null == commandProcessor)
                    {
                        // "null command " + i
                        throw PSTraceSource.NewInvalidOperationException();
                    }

                    if (object.ReferenceEquals(commandRequestingUpstreamCommandsToStop, commandProcessor))
                    {
                        commandRequestingUpstreamCommandsToStop = null;
                        continue; // do not call DoComplete/EndProcessing on the command that initiated stopping
                    }
                    if (commandRequestingUpstreamCommandsToStop != null)
                    {
                        continue; // do not call DoComplete/EndProcessing on commands that were stopped upstream
                    }

                    try
                    {
                        commandProcessor.DoComplete();
                    }
                    catch (PipelineStoppedException)
                    {
                        StopUpstreamCommandsException stopUpstreamCommandsException =
                            _firstTerminatingError != null
                                ? _firstTerminatingError.SourceException as StopUpstreamCommandsException
                                : null;
                        if (stopUpstreamCommandsException == null)
                        {
                            throw;
                        }
                        else
                        {
                            _firstTerminatingError = null;
                            commandRequestingUpstreamCommandsToStop = stopUpstreamCommandsException.RequestingCommandProcessor;
                        }
                    }

                    EtwActivity.SetActivityId(commandProcessor.PipelineActivityId);

                    // Log a command stopped event
                    MshLog.LogCommandLifecycleEvent(
                        commandProcessor.Command.Context,
                        CommandState.Stopped,
                        commandProcessor.Command.MyInvocation);

                    // Log the execution of a command (not script chunks, as they
                    // are not commands in and of themselves)
                    if (commandProcessor.CommandInfo.CommandType != CommandTypes.Script)
                    {
                        commandProcessor.CommandRuntime.PipelineProcessor.LogExecutionComplete(
                            commandProcessor.Command.MyInvocation, commandProcessor.CommandInfo.Name);
                    }
                    lastCommandRuntime = commandProcessor.CommandRuntime;
                }
            }

            // Log the pipeline completion.
            if (lastCommandRuntime != null)
            {
                // Only log the pipeline completion if this wasn't a nested pipeline, as
                // pipeline state in transcription is associated with the toplevel pipeline
                if ((this.LocalPipeline == null) || (!this.LocalPipeline.IsNested))
                {
                    lastCommandRuntime.PipelineProcessor.LogPipelineComplete();
                }
            }

            // If a terminating error occurred, report it now.
            if (_firstTerminatingError != null)
            {
                this.LogExecutionException(_firstTerminatingError.SourceException);
                _firstTerminatingError.Throw();
            }
        }
コード例 #34
0
ファイル: PipelineProcessor.cs プロジェクト: b333z/Pash
 public void Add(CommandProcessorBase commandProcessor)
 {
     commandsToExecute.Add(commandProcessor);
 }
コード例 #35
0
ファイル: pipeline.cs プロジェクト: 40a/PowerShell
        // 2004/02/28-JSnover (from spec review) ReadFromErrorQueue
        //   should be an int or enum to allow for more queues
        // 2005/03/08-JonN: This is an internal API
        /// <summary>
        /// Add a command to the pipeline
        /// </summary>
        /// <param name="commandProcessor"></param>
        /// <param name="readFromCommand">reference number of command from which to read, 0 for none</param>
        /// <param name="readErrorQueue">read from error queue of command readFromCommand</param>
        /// <returns>reference number of this command for use in readFromCommand</returns>
        /// <exception cref="ObjectDisposedException"></exception>
        /// <exception cref="ArgumentException">
        /// FirstCommandCannotHaveInput: <paramref name="readFromCommand"/> must be zero
        ///   for the first command in the pipe
        /// InvalidCommandNumber: there is no command numbered <paramref name="readFromCommand"/>
        ///   A command can only read from earlier commands; this prevents circular queues
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// ExecutionAlreadyStarted: pipeline has already started or completed
        /// PipeAlreadyTaken: the downstream pipe of command <paramref name="readFromCommand"/>
        ///   is already taken
        /// </exception>
        internal int AddCommand(CommandProcessorBase commandProcessor, int readFromCommand, bool readErrorQueue)
        {
            if (null == commandProcessor)
            {
                throw PSTraceSource.NewArgumentNullException("commandProcessor");
            }
            if (null == _commands)
            {
                // "_commands == null"
                throw PSTraceSource.NewInvalidOperationException();
            }
            if (_disposed)
            {
                throw PSTraceSource.NewObjectDisposedException("PipelineProcessor");
            }
            if (_executionStarted)
            {
                throw PSTraceSource.NewInvalidOperationException(
                    PipelineStrings.ExecutionAlreadyStarted);
            }
            if (commandProcessor.AddedToPipelineAlready)
            {
                throw PSTraceSource.NewInvalidOperationException(
                    PipelineStrings.CommandProcessorAlreadyUsed);
            }
            if (0 == _commands.Count)
            {
                if (0 != readFromCommand)
                {
                    // "First command cannot have input"
                    throw PSTraceSource.NewArgumentException(
                        "readFromCommand",
                        PipelineStrings.FirstCommandCannotHaveInput);
                }

                commandProcessor.AddedToPipelineAlready = true;
            }
            // 2003/08/11-JonN Subsequent commands must have predecessor
            else if (readFromCommand > _commands.Count || readFromCommand <= 0)
            {
                // "invalid command number"
                throw PSTraceSource.NewArgumentException(
                    "readFromCommand",
                    PipelineStrings.InvalidCommandNumber);
            }
            else
            {
                CommandProcessorBase prevcommandProcessor = _commands[readFromCommand - 1] as CommandProcessorBase;
                if (null == prevcommandProcessor || null == prevcommandProcessor.CommandRuntime)
                {
                    // "PipelineProcessor.AddCommand(): previous request object == null"
                    throw PSTraceSource.NewInvalidOperationException();
                }
                Pipe UpstreamPipe = (readErrorQueue) ?
                    prevcommandProcessor.CommandRuntime.ErrorOutputPipe : prevcommandProcessor.CommandRuntime.OutputPipe;
                if (null == UpstreamPipe)
                {
                    // "PipelineProcessor.AddCommand(): UpstreamPipe == null"
                    throw PSTraceSource.NewInvalidOperationException();
                }
                if (null != UpstreamPipe.DownstreamCmdlet)
                {
                    throw PSTraceSource.NewInvalidOperationException(
                        PipelineStrings.PipeAlreadyTaken);
                }

                commandProcessor.AddedToPipelineAlready = true;

                commandProcessor.CommandRuntime.InputPipe = UpstreamPipe;
                UpstreamPipe.DownstreamCmdlet = commandProcessor;

                // 2004/09/14-JonN This code could be moved to SynchronousExecute
                //  if this setting needed to bind at a later time
                //  than AddCommand.
                if (commandProcessor.CommandRuntime.MergeUnclaimedPreviousErrorResults)
                {
                    for (int i = 0; i < _commands.Count; i++)
                    {
                        prevcommandProcessor = _commands[i];
                        if (null == prevcommandProcessor || null == prevcommandProcessor.CommandRuntime)
                        {
                            // "PipelineProcessor.AddCommand(): previous request object == null"
                            throw PSTraceSource.NewInvalidOperationException();
                        }
                        // check whether the error output is already claimed
                        if (null != prevcommandProcessor.CommandRuntime.ErrorOutputPipe.DownstreamCmdlet)
                            continue;
                        if (null != prevcommandProcessor.CommandRuntime.ErrorOutputPipe.ExternalWriter)
                            continue;

                        // Set the upstream cmdlet's error output to go down
                        // the same pipe as the downstream cmdlet's input
                        prevcommandProcessor.CommandRuntime.ErrorOutputPipe = UpstreamPipe;
                    }
                } // if MergeUnclaimedPreviousErrorResults
            }
            _commands.Add(commandProcessor);

            // We give the Command a pointer back to the
            // PipelineProcessor so that it can check whether the
            // command has been stopped.
            commandProcessor.CommandRuntime.PipelineProcessor = this;

            return _commands.Count;
        } // AddCommand( CommandProcessorBase commandProcessor, int readFromCommand, bool readErrorQueue )