void SendLogEntry(WmiTraceListener listener, LogEntry logEntry) { ManagementScope scope = new ManagementScope(@"\\." + wmiPath); scope.Options.EnablePrivileges = true; StringBuilder sb = new StringBuilder("SELECT * FROM "); sb.Append("LogEntryV20"); string query = sb.ToString(); EventQuery eq = new EventQuery(query); using (ManagementEventWatcher watcher = new ManagementEventWatcher(scope, eq)) { watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived); watcher.Start(); LogSource source = new LogSource("notfromconfig", SourceLevels.All); source.Listeners.Add(listener); source.TraceData(TraceEventType.Error, 1, logEntry); BlockUntilWMIEventArrives(); watcher.Stop(); } }
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 Watcher() { // look up configurations from the app config file _logFileName = ConfigurationManager.AppSettings["logFileName"]; _eventType = ConfigurationManager.AppSettings["eventType"]; _eventCode = ConfigurationManager.AppSettings["eventCode"]; _partialPattern = ConfigurationManager.AppSettings["partialPattern"]; _runnable = ConfigurationManager.AppSettings["runnable"]; _query = new EventQuery(String.Format(QueryTemplate, _logFileName, _eventType, _eventCode)); _watcher = CreateWatcher(); }
/// <summary> /// /// </summary> /// /// <param name="eventName"></param> /// <param name="executor"></param> /// <param name="expected"></param> /// public void ExecuteWMI(string eventName, WmiEventExecutor executor, string expected) { ManagementScope scope = new ManagementScope(@"\\." + WmiPath); scope.Options.EnablePrivileges = true; EventQuery query = new EventQuery("select * from " + eventName); using (ManagementEventWatcher watcher = new ManagementEventWatcher(scope, query)) { watcher.EventArrived += new EventArrivedEventHandler(EventArrived); watcher.Start(); executor(); StartRunner(); watcher.Stop(); } }
public void FireMessageToWMI(string eventName, WmiEventDelegate action, string expected) { ManagementScope scope = new ManagementScope(@"\\." + WmiPath); scope.Options.EnablePrivileges = true; EventQuery eq = new EventQuery("SELECT * FROM " + eventName); using (ManagementEventWatcher watcher = new ManagementEventWatcher(scope, eq)) { watcher.EventArrived += new EventArrivedEventHandler(WatcherEventArrived); watcher.Start(); action(); WaiUntilWMIEventArrives(); watcher.Stop(); } Assert.IsTrue(this.wmiLogged); Assert.IsTrue(this.wmiResult.IndexOf(expected) > -1); }
static void Main(string[] args) { ManagementObjectSearcher processorSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_Processor"); foreach (ManagementObject obj in processorSearcher.Get()) { Console.WriteLine(obj["Name"]); Console.WriteLine("{0} / {1}", obj["CurrentClockSpeed"], obj["MaxClockSpeed"]); } EventQuery query = new EventQuery(); //query.QueryString = "SELECT * FROM _InstanceModifiationEvent WITHIN 3600 WHERE TargetInstance ISA 'Win32_DiskDrive'"; query.QueryString = "SELECT * FROM __InstanceCreationEvent WITHIN 1 WHERE TargetInstance isa \"Win32_Process\""; ManagementEventWatcher watcher = new ManagementEventWatcher(query); watcher.Options.Timeout = new TimeSpan(0, 0, 30); EventArrivedEventHandler eventArrived = new EventArrivedEventHandler(EventReceived); watcher.EventArrived += eventArrived; watcher.Start(); Console.WriteLine("Open an application (notepad.exe) to trigger an event."); //ManagementBaseObject e = watcher.WaitForNextEvent(); Console.WriteLine("Actually I rewrote this to use events, it will now monitor all application starts until you hit a key..."); ConsoleKeyInfo key; while (true) { key = Console.ReadKey(); if (key.KeyChar.Equals('q')) break; } /* //Display information from the event Console.WriteLine("Process {0} has been created, path is: {1}", ((ManagementBaseObject)e["TargetInstance"])["Name"], ((ManagementBaseObject)e["TargetInstance"])["ExecutablePath"]); */ watcher.Stop(); }
/// <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); }
/// <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); }
public void TestLoggingAInheritedCustomEntry() { ManagementScope scope = new ManagementScope(@"\\." + this.wmiPath); scope.Options.EnablePrivileges = true; string query = "SELECT * FROM MyInheritedCustomLogEntry"; EventQuery eq = new EventQuery(query); using (ManagementEventWatcher watcher = new ManagementEventWatcher(scope, eq)) { watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived); watcher.Start(); this.sink.SendMessage(GetCustomLogEntry()); BlockUntilWMIEventArrives(); watcher.Stop(); } Assert.IsTrue(this.wmiLogged); Assert.IsTrue(this.wmiResult.IndexOf(CommonUtil.MsgBody) > -1); }
public MainWindow() { InitializeComponent(); try { EventQuery eventQuery = new EventQuery(); eventQuery.QueryString = string.Format("SELECT * FROM __InstanceModificationEvent within 2 WHERE targetinstance isa 'Win32_Service' and targetinstance.name = '{0}'", ServiceName); EventWatcher = new ManagementEventWatcher(eventQuery); EventWatcher.Options.Timeout = new TimeSpan(1, 0, 0); EventWatcher.EventArrived += new EventArrivedEventHandler(eventWatcher_EventArrived); EventWatcher.Start(); ServiceController = new ServiceController(); ServiceController.ServiceName = ServiceName; lblServiceStatus.Content = ServiceController.Status.ToString(); if (ServiceController.Status == ServiceControllerStatus.Running) { WindowsServiceReference = new SettingsServiceClient(); lblCurrentOutputMessage.Content = WindowsServiceReference.GetOutputMessage(); } changeBtnState(); } catch (Exception ex) { lblError.Content = ex.Message; btnStartService.IsEnabled = false; btnStopService.IsEnabled = false; btnRestartService.IsEnabled = false; txtNewOutputMessage.IsEnabled = false; btnChangeOutputMessage.IsEnabled = false; } }
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType != null) { if (value as EventQuery != null && destinationType == typeof(InstanceDescriptor)) { EventQuery eventQuery = (EventQuery)value; Type[] typeArray = new Type[1]; typeArray[0] = typeof(string); ConstructorInfo constructor = typeof(EventQuery).GetConstructor(typeArray); if (constructor != null) { object[] queryString = new object[1]; queryString[0] = eventQuery.QueryString; return(new InstanceDescriptor(constructor, queryString)); } } if (value as ObjectQuery != null && destinationType == typeof(InstanceDescriptor)) { ObjectQuery objectQuery = (ObjectQuery)value; Type[] typeArray1 = new Type[1]; typeArray1[0] = typeof(string); ConstructorInfo constructorInfo = typeof(ObjectQuery).GetConstructor(typeArray1); if (constructorInfo != null) { object[] objArray = new object[1]; objArray[0] = objectQuery.QueryString; return(new InstanceDescriptor(constructorInfo, objArray)); } } return(base.ConvertTo(context, culture, value, destinationType)); } else { throw new ArgumentNullException("destinationType"); } }
public ManagementEventWatcher (ManagementScope scope, EventQuery query, EventWatcherOptions options) { throw new NotImplementedException (); }
/// <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.</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> public ManagementEventWatcher( ManagementScope scope, EventQuery query) : this(scope, query, null) { }
//parameterized constructors /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class when given a WMI event query.</para> /// </summary> /// <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> /// <remarks> /// <para>The namespace in which the watcher will be listening for /// events is the default namespace that is currently set.</para> /// </remarks> public ManagementEventWatcher( EventQuery query) : this(null, query, null) { }
public ManagementEventWatcher(ManagementScope scope, EventQuery query, EventWatcherOptions options) { throw new NotImplementedException(); }
public ManagementEventWatcher(ManagementScope scope, EventQuery query) : this(scope, query, new EventWatcherOptions()) { }
public static int RunCommand(string machineName, string commandLine, TimeSpan timeout, bool throwOnTimeout = false) { var connOptions = new ConnectionOptions { EnablePrivileges = true }; var scope = new ManagementScope(@"\\{0}\root\cimv2".FormatWith(machineName), connOptions); scope.Connect(); using (var processClass = new ManagementClass(scope, new ManagementPath("Win32_Process"), new ObjectGetOptions())) using (var exitEvent = new AutoResetEvent(false)) { var query = new EventQuery("SELECT * FROM Win32_ProcessStopTrace"); var watcher = new ManagementEventWatcher(scope, query) { Options = { Timeout = timeout + TimeSpan.FromSeconds(10) } }; var exitCodes = new Dictionary<int, int>(); watcher.EventArrived += (sender, args) => { var id = Convert.ToInt32(args.NewEvent["ProcessID"]); var exitCode = Convert.ToInt32(args.NewEvent["ExitStatus"]); lock (exitCodes) exitCodes[id] = exitCode; exitEvent.Set(); }; var inParams = processClass.GetMethodParameters("Create"); inParams["CommandLine"] = commandLine; watcher.Start(); var exitStopwatch = Stopwatch.StartNew(); var outParams = processClass.InvokeMethod("Create", inParams, null); var returnCode = Convert.ToUInt32(outParams["returnValue"]); switch ((CreateProcessResult)returnCode) { case CreateProcessResult.Success: break; case CreateProcessResult.AccessDenied: throw new WmiCreateProcessException("Failed to create remote process, access was denied."); case CreateProcessResult.InsufficentPrivileges: throw new WmiCreateProcessException("Failed to create remote process, the credentials used have insufficient privileges."); case CreateProcessResult.PathNotFound: throw new WmiCreateProcessException(@"Failed to create remote process, the path to the specified executable could not be found. To run shell commands, use ""cmd /c <command>""."); case CreateProcessResult.InvalidParameter: throw new WmiCreateProcessException("Failed to create remote process, an invalid parameter was specified."); default: throw new WmiCreateProcessException(string.Format("Failed to create process, and unknown error has occurred (return code {0}).", returnCode)); } var pid = Convert.ToInt32(outParams["processId"]); if (pid == 0) return 0; Logging.Coarse("[wmi] Waiting for pid '{0}' to exit...", pid); while (true) { if (exitStopwatch.Elapsed >= timeout) { Logging.Warn("[wmi] Tried waiting for '{0}', pid '{1}' still alive - operation timed out.", exitStopwatch.Elapsed, pid); if (throwOnTimeout) throw new TimeoutException(string.Format("Remote process '{0}' on machine '{1}' did not exit after the specified timeout of {2}", pid, machineName, timeout)); return 1; // TODO: This causes the task to fail, rendering throwOnTimeout meaningless } if (exitStopwatch.Elapsed >= TimeSpan.FromSeconds(10)) Logging.Coarse("[wmi] Still waiting for pid '{0}' to exit...", pid); exitEvent.WaitOne(TimeSpan.FromSeconds(10)); int? exitCode = null; lock (exitCodes) { if (exitCodes.ContainsKey(pid)) exitCode = exitCodes[pid]; } if (exitCode != null) { watcher.Stop(); Logging.Coarse("[wmi] Pid '{0}' exited with code '{1}' after {2}", pid, exitCode, exitStopwatch.Elapsed); return exitCodes[pid]; } } } }
/// <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.</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> public ManagementEventWatcher( ManagementScope scope, EventQuery query) : this(scope, query, null) {}
/// <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); }
public USBAddedOrRemovedEventWatcher(IUSBAddedOrRemoved parent, ManagementScope scope, EventQuery query) : base(scope, query) { this.parent = parent; }
public ManagementEventWatcher (ManagementScope scope, EventQuery query) : this (scope, query, new EventWatcherOptions ()) { }
public ManagementEventWatcher (EventQuery query) : this (null, query) { }