Brandon
Brandon

Reputation: 745

How do I register a class to WMI in .NET?

I'm migrating an old .NET Framework shared library to .NET 9 (or something close). It uses a combination of System.Diagnostics.Tracing.EventSource (to put the event) and System.Management.ManagementEventWatcher to query for the event being published in the unit test.

The goal is to Put a WMI event of a particular type defined in a C# class called MyWMIEvent that is contained in the library.

Here's the code that is supported in .NET Framework, but not .NET Standard or .NET:

if (!System.Management.Instrumentation.Instrumentation.IsAssemblyRegistered(System.Reflection.Assembly.GetExecutingAssembly()))
  
   System.Management.Instrumentation.Instrumentation.RegisterAssembly(System.Reflection.Assembly.GetExecutingAssembly());

There is support for System.Management in .NET, but not for System.Management.Instrumentation. I believe this is the code that registered an event class that allowed us to publish a special event of a particular type.

Here's where I'm writing the event (that used to work)

public void Fire()
{
    using (var eventSource = new EventSource("MyWMIEvent", EventSourceSettings.ThrowOnEventWriteErrors))
    {
        eventSource.Write("MyWMIEvent", new { Id, Server, DateCreated, Category, EventType, EventNumber, Message, Data });
    }
}

When the registration code snippet is commented out, EventSource.Write doesn't do anything because IsEnabled() internally returns false, which means nobody is listening for this type of event. But the WMI query is looking for it with the following WQL query:

select * from MyWMIEvent where Category = 'Test'

I think this is because the event is not registered properly now that the first snippet has been commented out since it doesn't work in .NET.

How do I migrate that registration logic in .NET Standard, .NET 9, or anywhere in-between?

Upvotes: 0

Views: 16

Answers (0)

Related Questions