Skip to main content

Detecting Management Events using .Net






Namespace: System.Management



ConnectionOptions
Specifies all settings required to make a WMI connection
Authentication
Gets or sets the COM authentication level to be used for operations in this connection.
Authority
Gets or sets the authority to be used to authenticate the specified user.
Context 
Gets or sets a WMI context object. This is a name-value pairs list to be passed through to a WMI provider that supports context information for customized operation. (Inherited from ManagementOptions.)
EnablePrivileges
Gets or sets a value indicating whether user privileges need to be enabled for the connection operation. This property should only be used when the operation performed requires a certain user privilege to be enabled (for example, a machine restart).
Impersonation
Gets or sets the COM impersonation level to be used for operations in this connection.
Locale
Gets or sets the locale to be used for the connection operation.
Password
Sets the password for the specified user.
Timeout 
Gets or sets the time-out to apply to the operation. Note that for operations that return collections, this time-out applies to the enumeration through the resulting collection, not the operation itself (the ReturnImmediately property is used for the latter). This property is used to indicate that the operation should be performed semi synchronously. (Inherited from ManagementOptions.)
Username
Gets or sets the user name to be used for the connection operation.


ManagementScope
It represents a scope (namespace) for management operations.

Properties
IsConnected
Gets a value indicating whether the ManagementScope is currently bound to a WMI server and a namespace.
Options
Gets or sets options for making the WMI connection.
Path
Gets or sets the path for the ManagementScope.

Methods

Connect
Connects this ManagementScope to the actual WMI scope.

ObjectQuery Class
It represents a management query that returns instances or classes.

Public Properties
QueryLanguage 
Gets or sets the query language used in the query string, defining the format of the query string.
QueryString 
Gets or sets the query in text format.

Sample Queries


EventQuery
It represents a WMI event query.

ManagementEventWatcher
Subscribes to temporary event notifications based on a specified event query.

Public Properties
Container 
Gets the IContainer that contains the Component.(Inherited from Component.)
Options
Gets or sets the options used to watch for events.
Query
Gets or sets the criteria to apply to events.
Scope
Gets or sets the scope in which to watch for events (namespace or scope).
Site 
Gets or sets the ISite of the Component.(Inherited from Component.)

Public Methods

GetLifetimeService 
Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
InitializeLifetimeService 
Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Start
Subscribes to events with the given query and delivers them, asynchronously, through the EventArrived event.
Stop
Cancels the subscription whether it is synchronous or asynchronous.
WaitForNextEvent
Waits for the next event that matches the specified query to arrive, and then returns it.

Public Events

Disposed 
Adds an event handler to listen to the Disposed event on the component.
EventArrived
Occurs when a new event arrives.
Stopped
Occurs when a subscription is canceled.

ManagementBaseObject Class
It contains the basic elements of a management object. It serves as a base class to more specific management object classes.

Public Properties
ClassPath
Gets the path to the management object's class.
Container 
Gets the IContainer that contains the Component.(Inherited from Component.)
Item
Gets access to property values through [] notation. This property is the indexer for the ManagementBaseObject class. You can use the default indexed properties defined by a type, but you cannot explicitly define your own. However, specifying the expando attribute on a class automatically provides a default indexed property whose type is Object and whose index type is String.
Properties
Gets a collection of PropertyData objects describing the properties of the management object.
Qualifiers
Gets the collection of QualifierData objects defined on the management object. Each element in the collection holds information such as the qualifier name, value, and flavor.
Site 
Gets or sets the ISite of the Component.(Inherited from Component.)
SystemProperties
Gets the collection of WMI system properties of the management object (for example, the class name, server, and namespace). WMI system property names begin with "__".

Public Methods

CreateObjRef 
Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
GetLifetimeService 
Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
GetPropertyQualifierValue
Returns the value of the specified property qualifier.
GetPropertyValue
Gets an equivalent accessor to a property's value.
GetQualifierValue
Gets the value of the specified qualifier.
InitializeLifetimeService 
Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
op_Explicit
Provides the internal WMI object represented by a ManagementObject.
SetPropertyQualifierValue
Sets the value of the specified property qualifier.
SetPropertyValue
Sets the value of the named property.
SetQualifierValue
Sets the value of the named qualifier.

Public Event

Disposed 
Adds an event handler to listen to the Disposed event on the component.(Inherited from Component.)

Sample:

public static int Main(string[] args)
    {
        // Create event query to be notified within 1 second of
        // a change in a service
        WqlEventQuery query =
            new WqlEventQuery("__InstanceCreationEvent",
            new TimeSpan(0,0,1),
            "TargetInstance isa \"Win32_Process\"");

        // Initialize an event watcher and subscribe to events
        // that match this query
        ManagementEventWatcher watcher =
            new ManagementEventWatcher();
        watcher.Query = query;
        // times out watcher.WaitForNextEvent in 5 seconds
        watcher.Options.Timeout = new TimeSpan(0,0,5);
     
        // 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;
    }

Comments

Popular posts from this blog

Culture Information and Localization in .NET

Namespace: System.Globalization CultureInfo Class:                 It provides information like the Format of numbers and dates, Culture’s Calendar, Culture’s language and sublanguage (if applicable), Country and region of the culture. The Basic use of CultureInfo class is shown here: • How string Comparisons are performed • How Number Comparison & Formats are performed • Date Comparison and Formats. • How resources are retrieved and used. Cultures are grouped into three categories: Invariant Culture : It’s Culture Insensitive. It can be used to build some trial application. It can be also used to build an application with hard-coded expiry date that ignores cultures. But using it for every comparison will be incorrect and inappropriate. Neutral Culture : English(en), Frensh(fr), and Spanish(sp). A neutral culture is related to language but it’s not related to specific regi...

Concept of App Domain in .Net

Creating Application Domains: Application domain is just like process, provides separate memory space, and isolates from other code. But it’s quite light weight. It also provides the following advantages: 1-       Reliability : If a domain crashes, it can be unloaded. Hence doesn’t affect the other assemblies. 2-       Efficiency : Loading all assemblies in one domain can be cumbersome and can make the process heavy but Appdomains are efficient in this manner. Important properties of AppDomain: ApplicationIdentity , ApplicationTrust , BaseDirectory , CurrentDomain , DomainManager , DomainDirectory , Evidence , FriendlyName , ID , RelativeSearchPath , SetupInformation , ShadowCopyFiles . Important methods of AppDomain: ApplyPolicy , CreateCOMInstanceFrom , CreateDomain , CreateInstance (Assembly). To create an AppDomain: AppDomain adomain = AppDomain.CreateDomain(“D”); To execute an assembly:...

ASP.NET Working With Data-Bound Web Server Controls

Suppose we have: List<Car> vCars = new List<Car>(); There are three types of databound controls: Simple databound controls(List, AdRotater), Composite data bound controls(GridView, DetailsView, FormView that inherit from CompositeDataBoundControl), and Hierarchal data bound controls (TreeView, Menu).   DataBoundControl has a DataBind method that can be used when data is ready. It calls DataBind for child controls as well. Page.DataBind() will call DataBind for all child controls. Using DataSource Objects:                                       BaseDataBound control exposes DataSource property that accepts objects that implement IEnumerable , IListSource , IDataSource , or IHierarchalDataSource . DataSourceID accepts ID of SqlDataSource . If both specified Data...