Exemplo n.º 1
0
        public override void UnsubscribeEvent(PSEventSubscriber subscriber)
        {
            if (subscriber == null)
            {
                throw new ArgumentNullException(nameof(subscriber));
            }
            Delegate handler = (Delegate)null;

            lock (this.eventSubscribers)
                handler = this.eventSubscribers[subscriber];
            if ((object)handler != null && subscriber.SourceObject != null)
            {
                if (!(subscriber.SourceObject is Type type))
                {
                    type = subscriber.SourceObject.GetType();
                }
                BindingFlags bindingAttr = BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
                EventInfo    eventInfo   = type.GetEvent(subscriber.EventName, bindingAttr);
                if (eventInfo != null && (object)handler != null)
                {
                    eventInfo.RemoveEventHandler(subscriber.SourceObject, handler);
                }
            }
            this.DrainPendingActions(subscriber);
            if (subscriber.Action != null)
            {
                subscriber.Action.NotifyJobStopped();
            }
            lock (this.eventSubscribers)
            {
                this.eventSubscribers[subscriber] = (Delegate)null;
                this.eventSubscribers.Remove(subscriber);
            }
        }
Exemplo n.º 2
0
 internal void DrainPendingActions(PSEventSubscriber subscriber)
 {
     if (this.actionQueue.Count == 0)
     {
         return;
     }
     lock (this.actionProcessingLock)
     {
         lock (((ICollection)this.actionQueue).SyncRoot)
         {
             if (this.actionQueue.Count == 0)
             {
                 return;
             }
             EventAction[] array = this.actionQueue.ToArray();
             this.actionQueue.Clear();
             foreach (EventAction nextAction in array)
             {
                 if (nextAction.Sender == subscriber && nextAction != this.processingAction)
                 {
                     while (this.IsExecutingEventAction)
                     {
                         Thread.Sleep(100);
                     }
                     this.InvokeAction(nextAction);
                 }
                 else
                 {
                     this.actionQueue.Enqueue(nextAction);
                 }
             }
         }
     }
 }
Exemplo n.º 3
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;
     }
 }
Exemplo n.º 4
0
        internal void Invoke(PSEventSubscriber eventSubscriber, PSEventArgs eventArgs)
        {
            if (this.IsFinishedState(this.JobStateInfo.State))
            {
                return;
            }
            this.SetJobState(JobState.Running);
            SessionState publicSessionState = this.action.SessionStateInternal.PublicSessionState;

            publicSessionState.PSVariable.Set(nameof(eventSubscriber), (object)eventSubscriber);
            publicSessionState.PSVariable.Set("event", (object)eventArgs);
            publicSessionState.PSVariable.Set("sender", eventArgs.Sender);
            publicSessionState.PSVariable.Set(nameof(eventArgs), (object)eventArgs.SourceEventArgs);
            ArrayList resultList = new ArrayList();

            try
            {
                this.action.InvokeWithPipe(false, false, (object)AutomationNull.Value, (object)AutomationNull.Value, (object)AutomationNull.Value, (Pipe)null, ref resultList, eventArgs.SourceArgs);
            }
            catch (Exception ex)
            {
                CommandProcessorBase.CheckForSevereException(ex);
                if (!(ex is PipelineStoppedException))
                {
                    this.LogErrorsAndOutput(resultList, publicSessionState);
                    this.SetJobState(JobState.Failed);
                }
                throw;
            }
            this.LogErrorsAndOutput(resultList, publicSessionState);
            this.moreData = true;
        }
Exemplo n.º 5
0
        internal override PSEventSubscriber SubscribeEvent(object source, string eventName, string sourceIdentifier, PSObject data, PSEventReceivedEventHandler handlerDelegate, bool supportEvent, bool forwardEvent, bool shouldQueueAndProcessInExecutionThread, int maxTriggerCount = 0)
        {
            PSEventSubscriber subscriber = this.SubscribeEvent(source, eventName, sourceIdentifier, data, handlerDelegate, supportEvent, forwardEvent, maxTriggerCount);

            subscriber.ShouldProcessInExecutionThread = shouldQueueAndProcessInExecutionThread;
            return(subscriber);
        }
Exemplo n.º 6
0
        private void ProcessNewSubscriber(
            PSEventSubscriber subscriber,
            object source,
            string eventName,
            string sourceIdentifier,
            PSObject data,
            bool supportEvent,
            bool forwardEvent)
        {
            Delegate handler = (Delegate)null;

            if (this.eventAssembly == null)
            {
                this.debugMode     = new StackFrame(0, true).GetFileName() != null;
                this.eventAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("PSEventHandler"), AssemblyBuilderAccess.Run);
            }
            if (this.eventModule == null)
            {
                this.eventModule = this.eventAssembly.DefineDynamicModule("PSGenericEventModule", this.debugMode);
            }
            if (source != null)
            {
                if (!(source is Type type))
                {
                    type = source.GetType();
                }
                BindingFlags bindingAttr = BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
                EventInfo    eventInfo   = type.GetEvent(eventName, bindingAttr);
                if (eventInfo == null)
                {
                    throw new ArgumentException(ResourceManagerCache.FormatResourceString("EventingResources", "CouldNotFindEvent", (object)eventName), nameof(eventName));
                }
                if (sourceIdentifier != null && sourceIdentifier.StartsWith("PowerShell.", StringComparison.OrdinalIgnoreCase))
                {
                    throw new ArgumentException(ResourceManagerCache.FormatResourceString("EventingResources", "ReservedIdentifier", (object)sourceIdentifier), nameof(sourceIdentifier));
                }
                if (type.GetProperty("EnableRaisingEvents") != null)
                {
                    type.InvokeMember("EnableRaisingEvents", BindingFlags.SetProperty, (Binder)null, source, new object[1]
                    {
                        (object)true
                    }, CultureInfo.CurrentCulture);
                }
                if (source is ManagementEventWatcher managementEventWatcher)
                {
                    managementEventWatcher.Start();
                }
                MethodInfo method = eventInfo.EventHandlerType.GetMethod("Invoke");
                if (method.ReturnType != typeof(void))
                {
                    throw new ArgumentException(ResourceManagerCache.GetResourceString("EventingResources", "NonVoidDelegateNotSupported"), nameof(eventName));
                }
                object eventHandler = this.GenerateEventHandler((PSEventManager)this, source, sourceIdentifier, data, method);
                handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, eventHandler, "EventDelegate");
                eventInfo.AddEventHandler(source, handler);
            }
            lock (this.eventSubscribers)
                this.eventSubscribers[subscriber] = handler;
        }
Exemplo n.º 7
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);
        }
Exemplo n.º 8
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);
                    }
                }
            }
        }
Exemplo n.º 9
0
        public override PSEventSubscriber SubscribeEvent(
            object source,
            string eventName,
            string sourceIdentifier,
            PSObject data,
            PSEventReceivedEventHandler handlerDelegate,
            bool supportEvent,
            bool forwardEvent)
        {
            PSEventSubscriber subscriber = new PSEventSubscriber(this.context, this.nextSubscriptionId++, source, eventName, sourceIdentifier, handlerDelegate, supportEvent, forwardEvent);

            this.ProcessNewSubscriber(subscriber, source, eventName, sourceIdentifier, data, supportEvent, forwardEvent);
            return(subscriber);
        }
Exemplo n.º 10
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;
 }
Exemplo n.º 11
0
 internal void SubscribeEvents(ServerSteppablePipelineDriver driver)
 {
     lock (this.syncObject)
     {
         if (!this.initialized)
         {
             this.eventManager = driver.LocalPowerShell.Runspace.Events as PSLocalEventManager;
             if (this.eventManager != null)
             {
                 this.startSubscriber   = this.eventManager.SubscribeEvent(this, "StartSteppablePipeline", Guid.NewGuid().ToString(), null, new PSEventReceivedEventHandler(this.HandleStartEvent), true, false, true, 0);
                 this.processSubscriber = this.eventManager.SubscribeEvent(this, "RunProcessRecord", Guid.NewGuid().ToString(), null, new PSEventReceivedEventHandler(this.HandleProcessRecord), true, false, true, 0);
             }
             this.initialized = true;
         }
     }
 }
Exemplo n.º 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);
            }
        }
Exemplo n.º 13
0
 public PSEventJob(
     PSEventManager eventManager,
     PSEventSubscriber subscriber,
     ScriptBlock action,
     string name)
     : base(action == null ? (string)null : action.ToString(), name)
 {
     if (eventManager == null)
     {
         throw new ArgumentNullException(nameof(eventManager));
     }
     if (subscriber == null)
     {
         throw new ArgumentNullException(nameof(subscriber));
     }
     this.action       = action;
     this.eventManager = eventManager;
     this.subscriber   = subscriber;
 }
Exemplo n.º 14
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);
                 }
             }
         }
     }
 }
Exemplo n.º 15
0
 public override void UnsubscribeEvent(PSEventSubscriber subscriber)
 {
     this.UnsubscribeEvent(subscriber, false);
 }
Exemplo n.º 16
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;
                        }
                    }
                }
            }
        }
Exemplo n.º 17
0
 public abstract void UnsubscribeEvent(PSEventSubscriber subscriber);
Exemplo n.º 18
0
 public override void UnsubscribeEvent(PSEventSubscriber subscriber)
 {
     throw new NotSupportedException(EventingResources.RemoteOperationNotSupported);
 }
Exemplo n.º 19
0
 public EventAction(PSEventSubscriber sender, PSEventArgs args)
 {
     this.sender = sender;
     this.args   = args;
 }
Exemplo n.º 20
0
 internal PSEventUnsubscribedEventArgs(PSEventSubscriber eventSubscriber)
 {
     this.eventSubscriber = eventSubscriber;
 }