private void Initialize()
        {
            //If the query is not set yet we can't do it
            if (null == query)
            {
                throw new InvalidOperationException();
            }

            if (null == options)
            {
                Options = new EventWatcherOptions();
            }

            //If we're not connected yet, this is the time to do it...
#pragma warning disable CA2002
            lock (this)
#pragma warning restore CA2002
            {
                if (null == scope)
                {
                    Scope = new ManagementScope();
                }

                if (null == cachedObjects)
                {
                    cachedObjects = new IWbemClassObjectFreeThreaded[options.BlockSize];
                }
            }

            lock (scope)
            {
                scope.Initialize();
            }
        }
Exemple #2
0
 public ManagementEventWatcher(ManagementScope scope, EventQuery query, EventWatcherOptions options)
 {
     if (scope != null)
     {
         this.scope = ManagementScope._Clone(scope, new IdentifierChangedEventHandler(this.HandleIdentifierChange));
     }
     else
     {
         this.scope = ManagementScope._Clone(null, new IdentifierChangedEventHandler(this.HandleIdentifierChange));
     }
     if (query != null)
     {
         this.query = (EventQuery)query.Clone();
     }
     else
     {
         this.query = new EventQuery();
     }
     this.query.IdentifierChanged += new IdentifierChangedEventHandler(this.HandleIdentifierChange);
     if (options != null)
     {
         this.options = (EventWatcherOptions)options.Clone();
     }
     else
     {
         this.options = new EventWatcherOptions();
     }
     this.options.IdentifierChanged += new IdentifierChangedEventHandler(this.HandleIdentifierChange);
     this.enumWbem        = null;
     this.cachedCount     = 0;
     this.cacheIndex      = 0;
     this.sink            = null;
     this.delegateInvoker = new WmiDelegateInvoker(this);
 }
 public ManagementEventWatcher(ManagementScope scope, EventQuery query, EventWatcherOptions options)
 {
     if (scope != null)
     {
         this.scope = ManagementScope._Clone(scope, new IdentifierChangedEventHandler(this.HandleIdentifierChange));
     }
     else
     {
         this.scope = ManagementScope._Clone(null, new IdentifierChangedEventHandler(this.HandleIdentifierChange));
     }
     if (query != null)
     {
         this.query = (EventQuery) query.Clone();
     }
     else
     {
         this.query = new EventQuery();
     }
     this.query.IdentifierChanged += new IdentifierChangedEventHandler(this.HandleIdentifierChange);
     if (options != null)
     {
         this.options = (EventWatcherOptions) options.Clone();
     }
     else
     {
         this.options = new EventWatcherOptions();
     }
     this.options.IdentifierChanged += new IdentifierChangedEventHandler(this.HandleIdentifierChange);
     this.enumWbem = null;
     this.cachedCount = 0;
     this.cacheIndex = 0;
     this.sink = null;
     this.delegateInvoker = new WmiDelegateInvoker(this);
 }
        /// <summary>
        ///    <para>Creates a new watcher that will listen for events conforming to the given WMI
        ///       event query, in the given WMI scope, and according to the specified options. For
        ///       this variant the query and the scope are specified objects. The options object
        ///       specifies options such as a timeout and possibly context information.</para>
        /// </summary>
        public ManagementEventWatcher(
            ManagementScope scope,
            EventQuery query,
            EventWatcherOptions options)
        {
            if (null != scope)
            {
                Scope = scope;
            }
            else
            {
                Scope = new ManagementScope();
            }

            if (null != query)
            {
                Query = query;
            }
            else
            {
                Query = new EventQuery();
            }

            if (null != options)
            {
                Options = options;
            }
            else
            {
                Options = new EventWatcherOptions();
            }

            enumWbem        = null;
            cachedCount     = 0;
            cacheIndex      = 0;
            sink            = null;
            delegateInvoker = new WmiDelegateInvoker(this);
        }
        } // end _DoInstall()


        // This can throw a Win32Exception, a ManagementException, or an
        // OperationCanceledException.
        private int _RunCommand( string command, bool instaKill, ICauPluginCallbackBase callback )
        {
            int exitCode = -1;
            int processId = 0;
            string username = null;
            SecureString password = null;
            if( null != m_cred )
            {
                username = m_cred.UserName;
                password = m_cred.Password;
            }

            object gate = new object();

            ConnectionOptions co = new ConnectionOptions( null,        // locale
                                                          username,
                                                          password,
                                                          null,        // authority
                                                          ImpersonationLevel.Impersonate,
                                                          AuthenticationLevel.PacketPrivacy,
                                                          true,        // enable privileges
                                                          null,        // context
                                                          TimeSpan.Zero );
            string path = String.Format( CultureInfo.InvariantCulture, @"\\{0}\root\cimv2", m_machine );
            ManagementScope scope = new ManagementScope( path, co );
            ObjectGetOptions objGetOptions = new ObjectGetOptions();

            scope.Connect();

            // We start the query before launching the process to prevent any possibility
            // of a timing or PID recycling problem.
            WqlEventQuery query = new WqlEventQuery( "Win32_ProcessStopTrace" );
            EventWatcherOptions watcherOptions = new EventWatcherOptions( null, TimeSpan.MaxValue, 1 );
            using( ManagementEventWatcher watcher = new ManagementEventWatcher( scope, query, watcherOptions ) )
            {
                watcher.EventArrived += (sender, arg) =>
                {
                    int stoppedProcId = (int) (uint) arg.NewEvent[ "ProcessID" ];
                    if( stoppedProcId == processId )
                    {
                        exitCode = (int) (uint) arg.NewEvent[ "ExitStatus" ];

                        if( null != callback )
                        {
                            callback.WriteVerbose( String.Format( CultureInfo.CurrentCulture,
                                                                  "Process ID {0} on {1} exited with code: {2}",
                                                                  processId,
                                                                  m_machine,
                                                                  exitCode ) );
                        }

                        lock( gate )
                        {
                            Monitor.PulseAll( gate );
                        }
                    }
                };

                watcher.Start();

                int timeout = Timeout.Infinite;
                ManagementPath mPath = new ManagementPath( "Win32_Process" );
                using( ManagementClass mc = new ManagementClass( scope, mPath, objGetOptions ) )
                using( ManagementBaseObject inParams = mc.GetMethodParameters( "Create" ) )
                {
                    inParams[ "CommandLine" ] = command;
                    using( ManagementBaseObject outParams = mc.InvokeMethod( "Create", inParams, null ) )
                    {
                        int err = (int) (uint) outParams[ "returnValue" ];
                        if( 0 != err )
                        {
                            throw new Win32Exception( err );
                        }
                        processId = (int) (uint) outParams[ "processId" ];
                        Debug.Assert( processId > 0 );
                    }
                }

                if( null != callback )
                {
                    callback.WriteVerbose( String.Format( CultureInfo.CurrentCulture,
                                                          "Process launched on {0} with ID: {1}",
                                                          m_machine,
                                                          processId ) );
                }

                // If instaKill is true, we are trying to test our ability to receive
                // Win32_ProcessStopTrace events, so kill the process immediately.
                if( instaKill )
                {
                    SelectQuery killQuery = new SelectQuery( "SELECT * FROM Win32_Process WHERE ProcessId = " + processId );
                    using( ManagementObjectSearcher searcher = new ManagementObjectSearcher( scope, killQuery ) )
                    {
                        foreach( ManagementObject obj in searcher.Get() )
                        {
                            obj.InvokeMethod( "Terminate", new object[] { (uint) c_TestWmiExitCode } );
                            obj.Dispose();
                        }
                    }

                    // If we don't receive the Win32_ProcessStopTrace event within 10
                    // seconds, we'll assume it's not coming. In that case, there's
                    // probably a firewall problem blocking WMI.
                    timeout = 10000;
                }

                // Wait until the process exits (or we get canceled).
                lock( gate )
                {
                    // If we get canceled, we stop waiting for the remote process to
                    // finish and just leave it running.
                    using( m_cancelToken.Register( () => { lock( gate ) { Monitor.PulseAll( gate ); } } ) )
                    {
                        if( !Monitor.Wait( gate, timeout ) )
                        {
                            Debug.Assert( instaKill, "This call should not time out unless we are in the instaKill scenario." );
                            throw new ClusterUpdateException( "The Fabrikam CAU plugin is able to create a process on cluster node \"{0}\" using WMI, but is not able to receive process lifetime events. Check the firewalls on both this computer and the target node and ensure that the appropriate WMI rules are enabled.",
                                                              "WmiTestReceiveEventFailed",
                                                              ErrorCategory.ResourceUnavailable );
                        }
                    }
                }

                watcher.Stop();
                m_cancelToken.ThrowIfCancellationRequested();
            }

            return exitCode;
        } // end _RunCommand()
 /// <summary>
 /// <para> Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class that listens for
 ///    events conforming to the given WMI event query, according to the specified options. For
 ///    this variant, the query and the scope are specified as strings. The options
 ///    object can specify options such as a timeout and context information.</para>
 /// </summary>
 /// <param name='scope'>The management scope (namespace) in which the watcher will listen for events.</param>
 /// <param name=' query'>The query that defines the events for which the watcher will listen.</param>
 /// <param name='options'>An <see cref='System.Management.EventWatcherOptions'/> object representing additional options used to watch for events. </param>
 public ManagementEventWatcher(
     string scope,
     string query,
     EventWatcherOptions options) : this(new ManagementScope(scope), new EventQuery(query), options)
 {
 }
 public ManagementEventWatcher(ManagementScope scope, EventQuery query, EventWatcherOptions options)
 {
     throw new NotImplementedException();
 }
		protected override object GetSourceObject()
		{
			string query = this.Query;
			if (this.Class != null)
			{
				for (int i = 0; i < this.Class.Length; i++)
				{
					if (!char.IsLetterOrDigit(this.Class[i]))
					{
						char @class = this.Class[i];
						if ([email protected]('\u005F'))
						{
							object[] objArray = new object[1];
							objArray[0] = this.Class;
							ErrorRecord errorRecord = new ErrorRecord(new ArgumentException(string.Format(Thread.CurrentThread.CurrentCulture, "Class", objArray)), "INVALID_QUERY_IDENTIFIER", ErrorCategory.InvalidArgument, null);
							errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiInvalidClass", new object[0]);
							base.ThrowTerminatingError(errorRecord);
							return null;
						}
					}
				}
				query = this.BuildEventQuery(this.Class);
			}
			ConnectionOptions connectionOption = new ConnectionOptions();
			if (this.Credential != null)
			{
				NetworkCredential networkCredential = this.Credential.GetNetworkCredential();
				if (!string.IsNullOrEmpty(networkCredential.Domain))
				{
					connectionOption.Username = string.Concat(networkCredential.Domain, "\\", networkCredential.UserName);
				}
				else
				{
					connectionOption.Username = networkCredential.UserName;
				}
				connectionOption.Password = networkCredential.Password;
			}
			ManagementScope managementScope = new ManagementScope(this.GetScopeString(this.computerName, this.Namespace), connectionOption);
			EventWatcherOptions eventWatcherOption = new EventWatcherOptions();
			if (this.timeoutSpecified)
			{
				eventWatcherOption.Timeout = new TimeSpan(this.timeOut * (long)0x2710);
			}
			ManagementEventWatcher managementEventWatcher = new ManagementEventWatcher(managementScope, new EventQuery(query), eventWatcherOption);
			return managementEventWatcher;
		}
		public ManagementEventWatcher (ManagementScope scope, EventQuery query, EventWatcherOptions options)
		{
			throw new NotImplementedException ();
		}
		public ManagementEventWatcher (string scope, string query, EventWatcherOptions options)
			: this (new ManagementScope (scope), new EventQuery (query), options)
		{
		}
        /// <summary>
        /// Returns the object that generates events to be monitored
        /// </summary>
        protected override Object GetSourceObject()
        {
            string wmiQuery = this.Query;
            if (this.Class != null)
            {
                //Validate class format
                for (int i = 0; i < this.Class.Length; i++)
                {
                    if (Char.IsLetterOrDigit(this.Class[i]) || this.Class[i].Equals('_'))
                    {
                        continue;
                    }

                    ErrorRecord errorRecord = new ErrorRecord(
                        new ArgumentException(
                            String.Format(
                                Thread.CurrentThread.CurrentCulture,
                                "Class", this.Class)),
                        "INVALID_QUERY_IDENTIFIER",
                        ErrorCategory.InvalidArgument,
                        null);
                    errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiInvalidClass");

                    ThrowTerminatingError(errorRecord);
                    return null;
                }

                wmiQuery = BuildEventQuery(this.Class);
            }

            ConnectionOptions conOptions = new ConnectionOptions();
            if (this.Credential != null)
            {
                System.Net.NetworkCredential cred = this.Credential.GetNetworkCredential();
                if (String.IsNullOrEmpty(cred.Domain))
                {
                    conOptions.Username = cred.UserName;
                }
                else
                {
                    conOptions.Username = cred.Domain + "\\" + cred.UserName;
                }
                conOptions.Password = cred.Password;
            }

            ManagementScope scope = new ManagementScope(GetScopeString(ComputerName, this.Namespace), conOptions);
            EventWatcherOptions evtOptions = new EventWatcherOptions();

            if (_timeoutSpecified)
            {
                evtOptions.Timeout = new TimeSpan(_timeOut * 10000);
            }

            ManagementEventWatcher watcher = new ManagementEventWatcher(scope, new EventQuery(wmiQuery), evtOptions);
            return watcher;
        }
        private void Initialize ()
        {
            //If the query is not set yet we can't do it
            if (null == query)
                throw new InvalidOperationException();

            if (null == options)
                Options = new EventWatcherOptions ();

            //If we're not connected yet, this is the time to do it...
            lock (this)
            {
                if (null == scope)
                    Scope = new ManagementScope ();

                if (null == cachedObjects)
                    cachedObjects = new IWbemClassObjectFreeThreaded[options.BlockSize];
            }

            lock (scope)
            {
                scope.Initialize ();
            }
        }
        /// <summary>
        /// <para> Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class 
        ///    that listens for events conforming to the given WMI event query, according to the specified
        ///    options. For this variant, the query and the scope are specified objects. The
        ///    options object can specify options such as timeout and context information.</para>
        /// </summary>
        /// <param name='scope'>A <see cref='System.Management.ManagementScope'/> object representing the scope (namespace) in which the watcher will listen for events.</param>
        /// <param name=' query'>An <see cref='System.Management.EventQuery'/> object representing a WMI event query, which determines the events for which the watcher will listen.</param>
        /// <param name='options'>An <see cref='System.Management.EventWatcherOptions'/> object representing additional options used to watch for events. </param>
        public ManagementEventWatcher(
            ManagementScope scope, 
            EventQuery query, 
            EventWatcherOptions options)
        {
            if (null != scope)
                this.scope = ManagementScope._Clone(scope, new IdentifierChangedEventHandler(HandleIdentifierChange));
            else
                this.scope = ManagementScope._Clone(null, new IdentifierChangedEventHandler(HandleIdentifierChange));

            if (null != query)
                this.query = (EventQuery)query.Clone();
            else
                this.query = new EventQuery();
            this.query.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange);

            if (null != options)
                this.options = (EventWatcherOptions)options.Clone();
            else
                this.options = new EventWatcherOptions();
            this.options.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange);

            enumWbem = null;
            cachedCount = 0; 
            cacheIndex = 0;
            sink = null;
            delegateInvoker = new WmiDelegateInvoker (this);
        }