示例#1
0
 internal void Invoke(PSEventSubscriber eventSubscriber, PSEventArgs eventArgs)
 {
     if (!base.IsFinishedState(base.JobStateInfo.State))
     {
         base.SetJobState(JobState.Running);
         SessionState publicSessionState = this.action.SessionStateInternal.PublicSessionState;
         publicSessionState.PSVariable.Set("eventSubscriber", eventSubscriber);
         publicSessionState.PSVariable.Set("event", eventArgs);
         publicSessionState.PSVariable.Set("sender", eventArgs.Sender);
         publicSessionState.PSVariable.Set("eventArgs", eventArgs.SourceEventArgs);
         ArrayList resultList = new ArrayList();
         try
         {
             Pipe outputPipe = new Pipe(resultList);
             this.action.InvokeWithPipe(false, System.Management.Automation.ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe, AutomationNull.Value, AutomationNull.Value, AutomationNull.Value, outputPipe, null, eventArgs.SourceArgs);
         }
         catch (Exception exception)
         {
             CommandProcessorBase.CheckForSevereException(exception);
             if (!(exception is PipelineStoppedException))
             {
                 this.LogErrorsAndOutput(resultList, publicSessionState);
                 base.SetJobState(JobState.Failed);
             }
             throw;
         }
         this.LogErrorsAndOutput(resultList, publicSessionState);
         this.moreData = true;
     }
 }
        public AzPredictorSurveyHelper(IPowerShellRuntime powerShellRuntime)
        {
            var host = powerShellRuntime.HostName;

            if ((host.IndexOf("Visual Studio Code", StringComparison.InvariantCultureIgnoreCase) == -1) &&
                !string.Equals(host, AzPredictorConstants.MockPSHostName, StringComparison.Ordinal))
            {
                var promptMessageScript = @"
                    if ([Microsoft.Azure.PowerShell.Tools.AzPredictor.AzPredictorData]::ShowSurveyOnIdle) {
                        [Microsoft.Azure.PowerShell.Tools.AzPredictor.AzPredictorData]::ShowSurveyOnIdle = $False
                        Write-Host ''
                        Write-Host ''; Write-Host `Survey: -ForegroundColor $Host.PrivateData.VerboseBackgroundColor -BackgroundColor $host.PrivateData.VerboseForegroundColor -NoNewLine; Write-Host ' How was your experience using the Az Predictor module?'
                        Write-Host ''
                        Write-Host 'Run ' -NoNewline; Write-Host Open-AzPredictorSurvey -ForegroundColor $Host.PrivateData.VerboseBackgroundColor -BackgroundColor $host.PrivateData.VerboseForegroundColor -NoNewline; Write-Host ' to give us your feedback.'
                        Write-Host ''
                        Write-Host '(Use ""Ctrl + C"" to return to the prompt)'
                    }";

                ScriptBlock scriptBlock = ScriptBlock.Create(promptMessageScript);
                _powerShellEventManager = powerShellRuntime.ConsoleRuntime.Runspace.Events;
                _idleEventSubscriber    = _powerShellEventManager.SubscribeEvent(source: null,
                                                                                 eventName: null,
                                                                                 sourceIdentifier: PSEngineEvent.OnIdle,
                                                                                 data: null,
                                                                                 action: scriptBlock,
                                                                                 supportEvent: true,
                                                                                 forwardEvent: false);

                _promptDelayTimer          = new Timer(TimeSpan.FromSeconds(1).TotalMilliseconds);
                _promptDelayTimer.Elapsed += OnPromptDelayTimer;
            }
        }
示例#3
0
        protected override void EndProcessing()
        {
            object targetObject          = PSObject.Base(this.GetSourceObject());
            string sourceObjectEventName = this.GetSourceObjectEventName();

            try
            {
                if (((targetObject != null) || (sourceObjectEventName != null)) && base.Events.GetEventSubscribers(this.sourceIdentifier).GetEnumerator().MoveNext())
                {
                    ErrorRecord errorRecord = new ErrorRecord(new ArgumentException(string.Format(Thread.CurrentThread.CurrentCulture, EventingResources.SubscriberExists, new object[] { this.sourceIdentifier })), "SUBSCRIBER_EXISTS", ErrorCategory.InvalidArgument, targetObject);
                    base.WriteError(errorRecord);
                }
                else
                {
                    this.newSubscriber = base.Events.SubscribeEvent(targetObject, sourceObjectEventName, this.sourceIdentifier, this.messageData, this.action, (bool)this.supportEvent, (bool)this.forward, this._maxTriggerCount);
                    if ((this.action != null) && (this.supportEvent == false))
                    {
                        base.WriteObject(this.newSubscriber.Action);
                    }
                }
            }
            catch (ArgumentException exception)
            {
                ErrorRecord record2 = new ErrorRecord(exception, "INVALID_REGISTRATION", ErrorCategory.InvalidArgument, targetObject);
                base.WriteError(record2);
            }
            catch (InvalidOperationException exception2)
            {
                ErrorRecord record3 = new ErrorRecord(exception2, "INVALID_REGISTRATION", ErrorCategory.InvalidOperation, targetObject);
                base.WriteError(record3);
            }
        }
 protected override void EndProcessing()
 {
     object targetObject = PSObject.Base(this.GetSourceObject());
     string sourceObjectEventName = this.GetSourceObjectEventName();
     try
     {
         if (((targetObject != null) || (sourceObjectEventName != null)) && base.Events.GetEventSubscribers(this.sourceIdentifier).GetEnumerator().MoveNext())
         {
             ErrorRecord errorRecord = new ErrorRecord(new ArgumentException(string.Format(Thread.CurrentThread.CurrentCulture, EventingResources.SubscriberExists, new object[] { this.sourceIdentifier })), "SUBSCRIBER_EXISTS", ErrorCategory.InvalidArgument, targetObject);
             base.WriteError(errorRecord);
         }
         else
         {
             this.newSubscriber = base.Events.SubscribeEvent(targetObject, sourceObjectEventName, this.sourceIdentifier, this.messageData, this.action, (bool) this.supportEvent, (bool) this.forward, this._maxTriggerCount);
             if ((this.action != null) && (this.supportEvent == false))
             {
                 base.WriteObject(this.newSubscriber.Action);
             }
         }
     }
     catch (ArgumentException exception)
     {
         ErrorRecord record2 = new ErrorRecord(exception, "INVALID_REGISTRATION", ErrorCategory.InvalidArgument, targetObject);
         base.WriteError(record2);
     }
     catch (InvalidOperationException exception2)
     {
         ErrorRecord record3 = new ErrorRecord(exception2, "INVALID_REGISTRATION", ErrorCategory.InvalidOperation, targetObject);
         base.WriteError(record3);
     }
 }
        /// <summary>
        /// Subscribe to the event on the object.
        /// </summary>
        protected override void EndProcessing()
        {
            object inputObject = PSObject.Base(GetSourceObject());
            string eventName   = GetSourceObjectEventName();

            try
            {
                if (
                    ((inputObject != null) || (eventName != null)) &&
                    (Events.GetEventSubscribers(_sourceIdentifier).GetEnumerator().MoveNext())
                    )
                {
                    // Detect if the event identifier already exists
                    ErrorRecord errorRecord = new ErrorRecord(
                        new ArgumentException(
                            string.Format(
                                System.Globalization.CultureInfo.CurrentCulture,
                                EventingResources.SubscriberExists, _sourceIdentifier)),
                        "SUBSCRIBER_EXISTS",
                        ErrorCategory.InvalidArgument,
                        inputObject);

                    WriteError(errorRecord);
                }
                else
                {
                    _newSubscriber =
                        Events.SubscribeEvent(
                            inputObject,
                            eventName,
                            _sourceIdentifier, _messageData, _action, (bool)_supportEvent, (bool)_forward, _maxTriggerCount);

                    if ((_action != null) && (!(bool)_supportEvent))
                    {
                        WriteObject(_newSubscriber.Action);
                    }
                }
            }
            catch (ArgumentException e)
            {
                ErrorRecord errorRecord = new ErrorRecord(
                    e,
                    "INVALID_REGISTRATION",
                    ErrorCategory.InvalidArgument,
                    inputObject);

                WriteError(errorRecord);
            }
            catch (InvalidOperationException e)
            {
                ErrorRecord errorRecord = new ErrorRecord(
                    e,
                    "INVALID_REGISTRATION",
                    ErrorCategory.InvalidOperation,
                    inputObject);

                WriteError(errorRecord);
            }
        }
 private void SetSubscriberExecutionThreadWithReflection(PSEventSubscriber subscriber)
 {
     // We need to create the PowerShell object in the same thread so we can get a nested
     // PowerShell.  This is the only way to consistently take control of the pipeline.  The
     // alternative is to make the subscriber a script block and have that create and process
     // the PowerShell object, but that puts us in a different SessionState and is a lot slower.
     s_shouldProcessInExecutionThreadProperty.SetValue(subscriber, true);
 }
        protected override void EndProcessing()
        {
            base.EndProcessing();
            PSEventSubscriber newSubscriber = base.NewSubscriber;

            if (newSubscriber != null)
            {
                newSubscriber.Unsubscribed += new PSEventUnsubscribedEventHandler(this.newSubscriber_Unsubscribed);
            }
        }
示例#8
0
        protected override void EndProcessing()
        {
            DebugHelper.WriteLogEx();
            base.EndProcessing();
            PSEventSubscriber newSubscriber = base.NewSubscriber;

            if (newSubscriber != null)
            {
                DebugHelper.WriteLog("RegisterCimIndicationCommand::EndProcessing subscribe to Unsubscribed event", 4);
                newSubscriber.Unsubscribed += new PSEventUnsubscribedEventHandler(RegisterCimIndicationCommand.newSubscriber_Unsubscribed);
            }
        }
示例#9
0
        /// <summary>
        /// Processes the event subscriber after the base class has registered.
        /// </summary>
        protected override void EndProcessing()
        {
            base.EndProcessing();

            // Register for the "Unsubscribed" event so that we can stop the
            // event watcher.
            PSEventSubscriber newSubscriber = NewSubscriber;

            if (newSubscriber != null)
            {
                newSubscriber.Unsubscribed += new PSEventUnsubscribedEventHandler(newSubscriber_Unsubscribed);
            }
        }
示例#10
0
        private void RegisterModuleCleanUp(PSModuleInfo moduleInfo)
        {
            if (moduleInfo == null)
            {
                throw PSTraceSource.NewArgumentNullException("moduleInfo");
            }
            string            sourceIdentifier = StringUtil.Format(ImplicitRemotingStrings.EventSourceIdentifier, base.Session.InstanceId, base.ModuleGuid);
            PSEventSubscriber subscriber       = base.Context.Events.SubscribeEvent(base.Session.Runspace, "StateChanged", sourceIdentifier, PSObject.AsPSObject(moduleInfo), base.Context.Engine.ParseScriptBlock("& {\r\n            if ('Closed' -eq $eventArgs.RunspaceStateInfo.State)\r\n            {\r\n                $sourceIdentifier = [system.management.automation.wildcardpattern]::Escape($eventSubscriber.SourceIdentifier)\r\n                Unregister-Event -SourceIdentifier $sourceIdentifier -Force -ErrorAction SilentlyContinue\r\n\r\n                $moduleInfo = $event.MessageData\r\n                Remove-Module -ModuleInfo $moduleInfo -Force -ErrorAction SilentlyContinue\r\n\r\n                Remove-Item -LiteralPath $moduleInfo.ModuleBase -Recurse -Force -ErrorAction SilentlyContinue\r\n                $moduleInfo = $null\r\n            }\r\n}\r\n            ", false), true, false);
            ScriptBlock       newClosure       = base.Context.Engine.ParseScriptBlock("\r\n            $sourceIdentifier = [system.management.automation.wildcardpattern]::Escape($eventSubscriber.SourceIdentifier)\r\n            Unregister-Event -SourceIdentifier $sourceIdentifier -Force -ErrorAction SilentlyContinue\r\n\r\n            if ($previousScript -ne $null)\r\n            {\r\n                & $previousScript $args\r\n            }\r\n            ", false).GetNewClosure();

            newClosure.Module.SessionState.PSVariable.Set("eventSubscriber", subscriber);
            newClosure.Module.SessionState.PSVariable.Set("previousScript", moduleInfo.OnRemove);
            moduleInfo.OnRemove = newClosure;
        }
示例#11
0
 public PSEventJob(PSEventManager eventManager, PSEventSubscriber subscriber, System.Management.Automation.ScriptBlock action, string name) : base((action == null) ? null : action.ToString(), name)
 {
     if (eventManager == null)
     {
         throw new ArgumentNullException("eventManager");
     }
     if (subscriber == null)
     {
         throw new ArgumentNullException("subscriber");
     }
     base.UsesResultsCollection = true;
     this.action = action;
     this.eventManager = eventManager;
     this.subscriber = subscriber;
 }
示例#12
0
 private void AutoUnregisterEventIfNecessary(PSEventSubscriber subscriber)
 {
     bool flag = false;
     if (subscriber.AutoUnregister)
     {
         lock (subscriber)
         {
             subscriber.RemainingActionsToProcess--;
             flag = (subscriber.RemainingTriggerCount == 0) && (subscriber.RemainingActionsToProcess == 0);
         }
     }
     if (flag)
     {
         this.UnsubscribeEvent(subscriber, true);
     }
 }
        /// <summary>
        /// EndProcessing method.
        /// </summary>
        protected override void EndProcessing()
        {
            DebugHelper.WriteLogEx();

            base.EndProcessing();

            // Register for the "Unsubscribed" event so that we can stop the
            // Cimindication event watcher.
            PSEventSubscriber newSubscriber = NewSubscriber;

            if (newSubscriber != null)
            {
                DebugHelper.WriteLog("RegisterCimIndicationCommand::EndProcessing subscribe to Unsubscribed event", 4);
                newSubscriber.Unsubscribed += new PSEventUnsubscribedEventHandler(newSubscriber_Unsubscribed);
            }
        }
        private PSEventSubscriber CreateInvocationSubscriber()
        {
            PSEventSubscriber subscriber = _runspace.Events.SubscribeEvent(
                source: null,
                eventName: PSEngineEvent.OnIdle,
                sourceIdentifier: PSEngineEvent.OnIdle,
                data: null,
                handlerDelegate: OnPowerShellIdle,
                supportEvent: true,
                forwardEvent: false);

            SetSubscriberExecutionThreadWithReflection(subscriber);

            subscriber.Unsubscribed += OnInvokerUnsubscribed;

            return(subscriber);
        }
        public void Dispose()
        {
            AzPredictorData.ShowSurveyOnIdle = false;

            if (_idleEventSubscriber is not null)
            {
                _powerShellEventManager.UnsubscribeEvent(_idleEventSubscriber);
                _idleEventSubscriber = null;
            }

            if (_promptDelayTimer is not null)
            {
                _promptDelayTimer.Elapsed -= OnPromptDelayTimer;
                _promptDelayTimer.Dispose();
                _promptDelayTimer = null;
            }
        }
        internal void SubscribeEvents(ServerSteppablePipelineDriver driver)
        {
            lock (_syncObject)
            {
                if (!_initialized)
                {
                    _eventManager = (object)driver.LocalPowerShell.Runspace.Events as PSLocalEventManager;

                    if (_eventManager != null)
                    {
                        _startSubscriber = _eventManager.SubscribeEvent(this, "StartSteppablePipeline", Guid.NewGuid().ToString(), null,
                            new PSEventReceivedEventHandler(this.HandleStartEvent), true, false, true);

                        _processSubscriber = _eventManager.SubscribeEvent(this, "RunProcessRecord", Guid.NewGuid().ToString(), null,
                            new PSEventReceivedEventHandler(this.HandleProcessRecord), true, false, true);
                    }
                    _initialized = true;
                }
            }
        }
        internal void SubscribeEvents(ServerSteppablePipelineDriver driver)
        {
            lock (_syncObject)
            {
                if (!_initialized)
                {
                    _eventManager = (object)driver.LocalPowerShell.Runspace.Events as PSLocalEventManager;

                    if (_eventManager != null)
                    {
                        _startSubscriber = _eventManager.SubscribeEvent(this, "StartSteppablePipeline", Guid.NewGuid().ToString(), null,
                                                                        new PSEventReceivedEventHandler(this.HandleStartEvent), true, false, true);

                        _processSubscriber = _eventManager.SubscribeEvent(this, "RunProcessRecord", Guid.NewGuid().ToString(), null,
                                                                          new PSEventReceivedEventHandler(this.HandleProcessRecord), true, false, true);
                    }

                    _initialized = true;
                }
            }
        }
示例#18
0
 public override void UnsubscribeEvent(PSEventSubscriber subscriber)
 {
     this.UnsubscribeEvent(subscriber, false);
 }
示例#19
0
 public abstract void UnsubscribeEvent(PSEventSubscriber subscriber);
示例#20
0
 public EventAction(PSEventSubscriber sender, PSEventArgs args)
 {
     this.sender = sender;
     this.args = args;
 }
示例#21
0
 public EventAction(PSEventSubscriber sender, PSEventArgs args)
 {
     this.sender = sender;
     this.args   = args;
 }
 internal PSEventUnsubscribedEventArgs(PSEventSubscriber eventSubscriber)
 {
     this.eventSubscriber = eventSubscriber;
 }
示例#23
0
 public override PSEventSubscriber SubscribeEvent(object source, string eventName, string sourceIdentifier, PSObject data, ScriptBlock action, bool supportEvent, bool forwardEvent, int maxTriggerCount)
 {
     PSEventSubscriber subscriber = new PSEventSubscriber(this.context, this.nextSubscriptionId++, source, eventName, sourceIdentifier, action, supportEvent, forwardEvent, maxTriggerCount);
     this.ProcessNewSubscriber(subscriber, source, eventName, sourceIdentifier, data, supportEvent, forwardEvent);
     subscriber.RegisterJob();
     return subscriber;
 }
示例#24
0
 public override void UnsubscribeEvent(PSEventSubscriber subscriber)
 {
     throw new NotSupportedException(EventingResources.RemoteOperationNotSupported);
 }
示例#25
0
 private void ProcessNewSubscriber(PSEventSubscriber subscriber, object source, string eventName, string sourceIdentifier, PSObject data, bool supportEvent, bool forwardEvent)
 {
     Delegate handler = null;
     if (this.eventAssembly == null)
     {
         StackFrame frame = new StackFrame(0, true);
         this.debugMode = frame.GetFileName() != null;
         this.eventAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("PSEventHandler"), AssemblyBuilderAccess.Run);
     }
     if (this.eventModule == null)
     {
         this.eventModule = this.eventAssembly.DefineDynamicModule("PSGenericEventModule", this.debugMode);
     }
     string a = null;
     bool flag = false;
     if (source != null)
     {
         if ((sourceIdentifier != null) && sourceIdentifier.StartsWith("PowerShell.", StringComparison.OrdinalIgnoreCase))
         {
             throw new ArgumentException(StringUtil.Format(EventingResources.ReservedIdentifier, sourceIdentifier), "sourceIdentifier");
         }
         EventInfo info = null;
         Type type = source as Type;
         if (type == null)
         {
             type = source.GetType();
         }
         if (WinRTHelper.IsWinRTType(type))
         {
             throw new InvalidOperationException(EventingResources.WinRTEventsNotSupported);
         }
         BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.IgnoreCase;
         info = type.GetEvent(eventName, bindingAttr);
         if (info == null)
         {
             throw new ArgumentException(StringUtil.Format(EventingResources.CouldNotFindEvent, eventName), "eventName");
         }
         if (type.GetProperty("EnableRaisingEvents") != null)
         {
             try
             {
                 type.InvokeMember("EnableRaisingEvents", BindingFlags.SetProperty, null, source, new object[] { true }, CultureInfo.CurrentCulture);
             }
             catch (TargetInvocationException exception)
             {
                 if (exception.InnerException != null)
                 {
                     throw exception.InnerException;
                 }
                 throw;
             }
         }
         ManagementEventWatcher watcher = source as ManagementEventWatcher;
         if (watcher != null)
         {
             watcher.Start();
         }
         MethodInfo method = info.EventHandlerType.GetMethod("Invoke");
         if (method.ReturnType != typeof(void))
         {
             throw new ArgumentException(EventingResources.NonVoidDelegateNotSupported, "eventName");
         }
         string key = source.GetType().FullName + "|" + eventName;
         Type type2 = null;
         if (GeneratedEventHandlers.ContainsKey(key))
         {
             type2 = GeneratedEventHandlers[key];
         }
         else
         {
             lock (GeneratedEventHandlers)
             {
                 if (GeneratedEventHandlers.ContainsKey(key))
                 {
                     type2 = GeneratedEventHandlers[key];
                 }
                 else
                 {
                     type2 = this.GenerateEventHandler(method);
                     GeneratedEventHandlers[key] = type2;
                 }
             }
         }
         object target = type2.GetConstructor(new Type[] { typeof(PSEventManager), typeof(object), typeof(string), typeof(PSObject) }).Invoke(new object[] { this, source, sourceIdentifier, data });
         handler = Delegate.CreateDelegate(info.EventHandlerType, target, "EventDelegate");
         info.AddEventHandler(source, handler);
     }
     else if (PSEngineEvent.EngineEvents.Contains(sourceIdentifier))
     {
         a = sourceIdentifier;
         flag = string.Equals(a, "PowerShell.OnIdle", StringComparison.OrdinalIgnoreCase);
     }
     lock (this.eventSubscribers)
     {
         this.eventSubscribers[subscriber] = handler;
         if (a != null)
         {
             lock (this.engineEventSubscribers)
             {
                 if (flag && !this._timerInitialized)
                 {
                     this.InitializeTimer();
                     this._timerInitialized = true;
                 }
                 List<PSEventSubscriber> list = null;
                 if (!this.engineEventSubscribers.TryGetValue(a, out list))
                 {
                     list = new List<PSEventSubscriber>();
                     this.engineEventSubscribers.Add(a, list);
                 }
                 list.Add(subscriber);
                 if (flag && !this._isTimerActive)
                 {
                     this.EnableTimer();
                     this._isTimerActive = true;
                 }
             }
         }
     }
 }
示例#26
0
 internal void DrainPendingActions(PSEventSubscriber subscriber)
 {
     if (this.actionQueue.Count != 0)
     {
         lock (this.actionProcessingLock)
         {
             lock (((ICollection) this.actionQueue).SyncRoot)
             {
                 if (this.actionQueue.Count != 0)
                 {
                     bool flag = false;
                     do
                     {
                         EventAction[] actionArray = this.actionQueue.ToArray();
                         this.actionQueue.Clear();
                         foreach (EventAction action in actionArray)
                         {
                             if ((action.Sender == subscriber) && (action != this.processingAction))
                             {
                                 while (this.IsExecutingEventAction)
                                 {
                                     Thread.Sleep(100);
                                 }
                                 bool addActionBack = false;
                                 this.InvokeAction(action, out addActionBack);
                                 if (addActionBack)
                                 {
                                     flag = true;
                                 }
                             }
                             else
                             {
                                 this.actionQueue.Enqueue(action);
                             }
                         }
                     }
                     while (flag);
                 }
             }
         }
     }
 }
示例#27
0
 private void UnsubscribeEvent(PSEventSubscriber subscriber, bool skipDraining)
 {
     if (subscriber == null)
     {
         throw new ArgumentNullException("subscriber");
     }
     Delegate delegate2 = null;
     lock (this.eventSubscribers)
     {
         if (subscriber.IsBeingUnsubscribed || !this.eventSubscribers.TryGetValue(subscriber, out delegate2))
         {
             return;
         }
         subscriber.IsBeingUnsubscribed = true;
     }
     if ((delegate2 != null) && (subscriber.SourceObject != null))
     {
         subscriber.OnPSEventUnsubscribed(subscriber.SourceObject, new PSEventUnsubscribedEventArgs(subscriber));
         EventInfo info = null;
         Type sourceObject = subscriber.SourceObject as Type;
         if (sourceObject == null)
         {
             sourceObject = subscriber.SourceObject.GetType();
         }
         BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.IgnoreCase;
         info = sourceObject.GetEvent(subscriber.EventName, bindingAttr);
         if ((info != null) && (delegate2 != null))
         {
             info.RemoveEventHandler(subscriber.SourceObject, delegate2);
         }
     }
     if (!skipDraining)
     {
         this.DrainPendingActions(subscriber);
     }
     if (subscriber.Action != null)
     {
         subscriber.Action.NotifyJobStopped();
     }
     lock (this.eventSubscribers)
     {
         this.eventSubscribers[subscriber] = null;
         this.eventSubscribers.Remove(subscriber);
         lock (this.engineEventSubscribers)
         {
             if (PSEngineEvent.EngineEvents.Contains(subscriber.SourceIdentifier))
             {
                 this.engineEventSubscribers[subscriber.SourceIdentifier].Remove(subscriber);
             }
         }
     }
 }
        /// <summary>
        /// Subscribe to the event on the object
        /// </summary>
        protected override void EndProcessing()
        {
            Object inputObject = PSObject.Base(GetSourceObject());
            string eventName = GetSourceObjectEventName();

            try
            {
                if (
                    ((inputObject != null) || (eventName != null)) &&
                    (Events.GetEventSubscribers(_sourceIdentifier).GetEnumerator().MoveNext())
                    )
                {
                    // Detect if the event identifier already exists
                    ErrorRecord errorRecord = new ErrorRecord(
                        new ArgumentException(
                            String.Format(
                                System.Globalization.CultureInfo.CurrentCulture,
                                EventingResources.SubscriberExists, _sourceIdentifier)),
                        "SUBSCRIBER_EXISTS",
                        ErrorCategory.InvalidArgument,
                        inputObject);

                    WriteError(errorRecord);
                }
                else
                {
                    _newSubscriber =
                        Events.SubscribeEvent(
                            inputObject,
                            eventName,
                            _sourceIdentifier, _messageData, _action, (bool)_supportEvent, (bool)_forward, _maxTriggerCount);

                    if ((_action != null) && (!(bool)_supportEvent))
                        WriteObject(_newSubscriber.Action);
                }
            }
            catch (ArgumentException e)
            {
                ErrorRecord errorRecord = new ErrorRecord(
                    e,
                    "INVALID_REGISTRATION",
                    ErrorCategory.InvalidArgument,
                    inputObject);

                WriteError(errorRecord);
            }
            catch (InvalidOperationException e)
            {
                ErrorRecord errorRecord = new ErrorRecord(
                    e,
                    "INVALID_REGISTRATION",
                    ErrorCategory.InvalidOperation,
                    inputObject);

                WriteError(errorRecord);
            }
        }