/// <summary>
        /// Initializes data
        /// </summary>
        public void Init()
        {
            LogHelper.LogDebug(_host);

            try
            {
                // set connection options
                ConnectionOptions co = new ConnectionOptions();
                co.EnablePrivileges = true;
                co.Authentication   = AuthenticationLevel.Default;
                co.Impersonation    = ImpersonationLevel.Impersonate;

                // initialize __InstanceCreationEvent
                EventWatcherOptions ewo = new EventWatcherOptions();

                // subscribe to InstanceOperationEvent
                _eventWatcher               = new ManagementEventWatcher();
                _eventWatcher.Query         = new EventQuery("SELECT * FROM __InstanceOperationEvent WITHIN " + _interval + " WHERE TargetInstance ISA \"Win32_PrintJob\"");
                _eventWatcher.Scope         = new ManagementScope(@"\\" + _host + @"\root\CIMV2", co);
                _eventWatcher.Options       = ewo;
                _eventWatcher.EventArrived += mewPrintJobs_OperationSet;

                // start the watcher
                _eventWatcher.Start();

                LogHelper.LogDebug("Active " + _host);
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex);
            }
        }
示例#2
0
        /// <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);
        }
示例#3
0
        public void CanSynchronouslyListenToWmiEvents()
        {
            string eventFilter =
                string.Format("TargetInstance ISA \"Win32_NTLogEvent\" AND TargetInstance.SourceName = \"{0}\"",
                              _eventLogSource);
            WqlEventQuery query = new WqlEventQuery("__InstanceCreationEvent", TimeSpan.FromSeconds(1), eventFilter);

            EventWatcherOptions watcherOptions = new EventWatcherOptions();

            watcherOptions.Timeout = TimeSpan.FromMilliseconds(1000);

            using (
                ManagementEventWatcher watcher =
                    new ManagementEventWatcher(NewPrivilegedConnection, query, watcherOptions))
            {
                watcher.Start();

                ThreadPool.QueueUserWorkItem(delegate {
                    Thread.Sleep(200); //pause to allow for watcher to start waiting for event
                    EventLog.WriteEntry(_eventLogSource, "Hello World", EventLogEntryType.Information);
                });

                try
                {
                    using (ManagementBaseObject nextEvent = watcher.WaitForNextEvent())
                    {
                        Assert.That(nextEvent, Is.Not.Null);
                    }
                }
                finally
                {
                    watcher.Stop();
                }
            }
        }
示例#4
0
        public BrightnessWatcher()
        {
            var scope  = @"root\wmi";
            var query  = "SELECT * FROM WmiMonitorBrightnessEvent";
            var option = new EventWatcherOptions(null, TimeSpan.FromSeconds(1), 1);

            _watcher = new ManagementEventWatcher(scope, query, option);
        }
        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);
        }
示例#6
0
        public static int Main(string[] args)
        {
            // Create a timer event instance
            ManagementClass timerClass = new ManagementClass("root/default",
                                                             "__IntervalTimerInstruction",
                                                             null);
            ManagementObject timerObj = timerClass.CreateInstance();

            timerObj["IntervalBetweenEvents"] = 500;                    //fire every half a second
            timerObj["TimerID"] = "Timer62";
            timerObj.Put();

            // Create an EventWatcherOptions
            EventWatcherOptions options = new EventWatcherOptions();

            options.Timeout   = new TimeSpan(0, 0, 0, 5, 0);            // timeout in 5 secs
            options.BlockSize = 2;

            // Create an event query
            WQLEventQuery query = new WQLEventQuery("__TimerEvent", "TimerID='Timer62'");

            // Create an event watcher and subscribe the events that matches the event query
            ManagementEventWatcher watcher = new ManagementEventWatcher(
                new ManagementScope("root/default"),
                query,
                options);

            // Create a Stopped handler
            EventStoppedHandler stopHandlerObj = new EventStoppedHandler();

            watcher.Stopped += new StoppedEventHandler(stopHandlerObj.Stopped);

            // Block until next event arrives or throw a ManagementException:TimedOut
            ManagementBaseObject e = watcher.WaitForNextEvent();

            // Assertion: Event was received.
            // Cancel subscription
            watcher.Stop();
            while (!stopHandlerObj.IsStopped)
            {
                System.Threading.Thread.Sleep(1000);
            }
            return(0);
        }
示例#7
0
    public static int Main(string[] args)
    {
        // Create event query to be notified within 1 second of
        // a change in a service
        string query = "SELECT * FROM" +
                       " __InstanceCreationEvent WITHIN 1 " +
                       "WHERE TargetInstance isa \"Win32_Process\"";

        // Event options
        EventWatcherOptions eventOptions = new
                                           EventWatcherOptions();

        eventOptions.Timeout = System.TimeSpan.MaxValue;
        // return after 1 event is received
        eventOptions.BlockSize = 1;

        // Initialize an event watcher and subscribe to events
        // that match this query
        ManagementEventWatcher watcher =
            new ManagementEventWatcher("root\\CIMV2", query,
                                       eventOptions);

        // Block until the next event occurs
        // Note: this can be done in a loop if waiting for
        //        more than one occurrence
        Console.WriteLine(
            "Open an application (notepad.exe) to trigger an event.");
        ManagementBaseObject e = watcher.WaitForNextEvent();

        //Display information from the event
        Console.WriteLine(
            "Process {0} has been created, path is: {1}",
            ((ManagementBaseObject)e
             ["TargetInstance"])["Name"],
            ((ManagementBaseObject)e
             ["TargetInstance"])["ExecutablePath"]);

        //Cancel the subscription
        watcher.Stop();
        return(0);
    }
示例#8
0
        public void CanRetreieveUnderlyingObjectThatWmiEventReleatesTo()
        {
            string eventFilter =
                string.Format("TargetInstance ISA \"Win32_NTLogEvent\" AND TargetInstance.SourceName = \"{0}\"",
                              _eventLogSource);
            WqlEventQuery query = new WqlEventQuery("__InstanceCreationEvent", TimeSpan.FromSeconds(1), eventFilter);

            EventWatcherOptions watcherOptions = new EventWatcherOptions();

            watcherOptions.Timeout = TimeSpan.FromMilliseconds(1000);

            using (
                ManagementEventWatcher watcher =
                    new ManagementEventWatcher(NewPrivilegedConnection, query, watcherOptions))
            {
                watcher.Start();

                ThreadPool.QueueUserWorkItem(delegate {
                    Thread.Sleep(100); //pause to allow for watcher to start waiting for event
                    EventLog.WriteEntry(_eventLogSource, "Hello World", EventLogEntryType.Information);
                });

                try
                {
                    using (ManagementBaseObject nextEvent = watcher.WaitForNextEvent())
                    {
                        ManagementBaseObject eventLogEntry = (ManagementBaseObject)nextEvent["TargetInstance"];
                        Assert.That(eventLogEntry["Message"], Is.EqualTo("Hello World\r\n"));
                    }
                }
                finally
                {
                    watcher.Stop();
                }
            }
        }
示例#9
0
        protected override void ProcessRecord()
        {
            var watcherOptions = new EventWatcherOptions(SessionName, GetAllEventSourceDefinitionsFromParameters(), OnEvent);

            WriteObject(watcherOptions);
        }
示例#10
0
 public ManagementEventWatcher(ManagementScope scope, EventQuery query, EventWatcherOptions options)
 {
 }
示例#11
0
 public ManagementEventWatcher(string scope, string query, EventWatcherOptions options)
 {
 }
	public ManagementEventWatcher(string scope, string query, EventWatcherOptions options) {}
	public ManagementEventWatcher(ManagementScope scope, EventQuery query, EventWatcherOptions options) {}
示例#14
0
        public static int Main(string[] args)
        {
            try
            {
                // Create a timer event instance
                ManagementClass timerClass = new ManagementClass("root/default",
                                                                 "__IntervalTimerInstruction",
                                                                 null);
                ManagementObject timerObj = timerClass.CreateInstance();
                timerObj["IntervalBetweenEvents"] = 5000;               //fire every ten seconds
                timerObj["TimerID"] = "Timer612";
                timerObj.Put();

                // Create an EventWatcherOptions
                EventWatcherOptions options = new EventWatcherOptions();
                options.Timeout   = new TimeSpan(0, 0, 0, 2, 0);        // time out in 2 secs
                options.BlockSize = 2;

                // Create an event query
                WQLEventQuery query = new WQLEventQuery("__TimerEvent",
                                                        "TimerID='Timer612'");

                // Create an event watcher and subscribe the events that matches the event query
                ManagementEventWatcher watcher = new ManagementEventWatcher(
                    new ManagementScope("root/default"),
                    query,
                    options);

                // Block until next event arrives or throw a ManagementException:TimedOut
                ManagementBaseObject e = watcher.WaitForNextEvent();

                // Assertion: Event was received.
                Console.WriteLine("Unable to specify Timeout for an event when calling ManagementEventWatcher.WaitForNextEvent().");
                return(1);
            }
            catch (ManagementException e)
            {
                Console.WriteLine("Error Message is " + e.Message);
                Console.WriteLine("Error Code is " + e.ErrorCode);
                Console.WriteLine("Status.Timedout is " + ManagementStatus.Timedout);
                if (ManagementStatus.Timedout == e.ErrorCode)
                {
                    // Assertion: Event was not received within time out period
                    // Clean up -
                    ManagementObject timerObj = new ManagementObject("root/default:__IntervalTimerInstruction.TimerID='Timer612'");
                    timerObj.Delete();
                    Console.WriteLine("Test6.1.2: Able to specify Timeout for an event when calling ManagementEventWatcher.WaitForNextEvent().");
                    return(0);
                }
                else
                {
                    Console.WriteLine("Test6.1.2: Unable to specify Timeout for an event when calling ManagementEventWatcher.WaitForNextEvent().");
                    return(1);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Test6.1.2: " + e.GetType());
                Console.WriteLine(e.Message + e.StackTrace);
                return(1);
            }
        }
示例#15
0
        } // 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>
        /// Checks if the heartbeat message from the app is recieved
        /// </summary>
        /// <param name="process"></param>
        /// <returns></returns>
        public ProcessState CheckHeartbeat(Process process)
        {
            this.monitoredProcessName = process.Name;

            var heartbeatTimeout = process.HeartbeatTimeout != 0 ? process.HeartbeatTimeout : defaultHeartbeatTimeout;

            // Check for heartbeat from the application using WMI provider
            // Timeout on eventwatcher should be more than the frequency with which app publishes event to WMI
            var eventWatcherOptions = new EventWatcherOptions(null, new TimeSpan(0, 0, heartbeatTimeout), 1);

            // Initialize an event watcher and subscribe to timer events
            var watcher = new ManagementEventWatcher(@"\\" + Environment.MachineName + @"\root\AmbreCorp", "SELECT * FROM ProcessMonitor WHERE ProcessName = '" + this.monitoredProcessName + "'", eventWatcherOptions);

            try
            {
                // Initially set currentProcessState to Stopped.
                this.currentProcessState = ProcessState.Stopped;

                // Check if windows error reporting is showing
                this.CheckWindowsErrorReportingMessage();

                // Set up a listener for events
                watcher.EventArrived += HandleEventWatcher;

                var stopWatch = Stopwatch.StartNew();

                // Start listening
                watcher.Start();

                // If currentProcessState is stopped keep checking if elapsedtime has exceeded heartbeat timeout of the process

                while (this.currentProcessState == ProcessState.Stopped)
                {
                    var elapsedTicks = stopWatch.ElapsedTicks;

                    var elapsedTimeInSeconds = elapsedTicks / Stopwatch.Frequency;

                    if ((int)elapsedTimeInSeconds > heartbeatTimeout)
                    {
                        break;
                    }

                    System.Threading.Thread.Sleep(2000);
                }

                stopWatch.Stop();

                return(this.currentProcessState);
            }
            catch (Exception ex)
            {
                // for some reason when eventwatcher times out it throws a timed out exception so that needs to be caught.This tells us that event was not receieved in set time
                if (ex.Message.ToLower().Trim() == "timed out")
                {
                    Console.WriteLine(string.Format("Event was not received from {0}.Event watcher timed out.", this.monitoredProcessName));
                    return(ProcessState.Error);
                }
                else
                {
                    return(ProcessState.Error);
                }
            }
            finally
            {
                if (watcher != null)
                {
                    // for some reason if fault window is open then watcher.stop() does not work hence need to close that error window first so call CheckWindowsErrorReportingMessage again.
                    this.CheckWindowsErrorReportingMessage();

                    // Stop listening
                    watcher.Stop();

                    // Remove listener
                    watcher.EventArrived -= HandleEventWatcher;

                    watcher.Dispose();
                }
            }
        }