Share via


Esempio: Utilizzo del provider di eventi WMI con .NET Framework

Nell'esempio seguente viene creata un'applicazione in C# che utilizza il provider di eventi WMI per restituire dati degli eventi per tutti gli eventi DDL che si verificano in un'istanza dell'installazione predefinita di SQL Server.

Esempio

Per compilare l'esempio, utilizzare il file di comando seguente:

set compiler_path=C:\WINNT\Microsoft.NET\Framework\v2.0.50110

%compiler_path%\csc %1

using System;
using System.Management;

class SQLWEPExample 
{
    public static void Main(string[] args)
    {
        string query =  @"SELECT * FROM DDL_EVENTS " ;
        // Default namespace for default instance of SQL Server 
        string managementPath =
            @"\\.\root\Microsoft\SqlServer\ServerEvents\MSSQLSERVER";
        ManagementEventWatcher  watcher = 
            new ManagementEventWatcher(new WqlEventQuery (query));
        ManagementScope scope = new ManagementScope (managementPath);
        scope.Connect();
        watcher.Scope = scope;
        Console.WriteLine("Watching...");
        while (true)
        {
            ManagementBaseObject obj = watcher.WaitForNextEvent();
            Console.WriteLine("Event!");
            foreach (PropertyData data in obj.Properties)
            {
                Console.Write("{0}:", data.Name);
                if (data.Value == null)
                {
                    Console.WriteLine("<null>");
                }
                else
                {
                    Console.WriteLine(data.Value.ToString());
                }
            }
            Console.WriteLine("-----");
            Console.WriteLine();
            Console.WriteLine();
        }
    }
}