Skip to content

Latest commit

 

History

History
76 lines (66 loc) · 2.38 KB

File metadata and controls

76 lines (66 loc) · 2.38 KB
title Sample: Use the WMI Event Provider in .NET
description A sample C# application uses the WMI Event Provider to return event data for all data definition language events that occur on an instance of SQL Server.
author markingmyname
ms.author maghan
ms.reviewer randolphwest
ms.date 10/30/2023
ms.service sql
ms.subservice wmi
ms.topic reference
helpviewer_keywords
WMI Provider for Server Events, samples
sample applications [WMI]
managed code [WMI]

Sample: Use the WMI Event Provider with the .NET Framework

[!INCLUDE SQL Server]

The following sample creates an application in C# that uses the WMI Event Provider to return event data for all data definition language (DDL) events that occur on a default installation instance of [!INCLUDE ssNoVersion].

Examples

The example compiles by using the following command file:

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();
        }
    }
}

Related content