First, I talked about WMI and the way it can be used to discuss mirroring, then, I discussed the events that are generated through WMI.
In the end, it is all about the code. As always, the big disclaimer here is that this code is just a sample and it purposely leaves out error handling and a bunch of documentation every program must have. The other big disclaimer is that this is provided as is and there are no guarantees of usefulness. Part of my team is also testing this class as this is only a skeleton project produced as a proof of concept – so there will be bugs! ;)
The sample contains a VS 2008 solution with two projects:
MirrorMonitorWMI – Contains the MirrorEvent and MirrorMonitor classes.
WPFMonitor – a simple app that demonstrates the MirrorMonitor classes.
The MirrorMonitorWMI project contains the following two classes:
- MirrorEvent: encapsulates a WMI event related to mirroring (DATABASE_MIRRORING_CHANGE).
- MirrorMonitor: provides a simple way to connect to both principal and mirror servers. It also provides the event hooks for failover, manual and automatic.
How do you use this?
First, create the class and specify both the server and the instance name; and attach the event handlers.
As seen here, the MirrorMonitor constructor expects four arguments: 1) the principal server information, 2) the mirror server information, 3) the time threshold required to wait after a fail over event (as I discussed in my previous post), and 4) the database name that is being monitored.
// start the monitors
monitor = new MirrorMonitor(
new ServerInformation(txtPrincipalServer.Text, "MSSQLSERVER", null),
new ServerInformation(txtMirrorServer.Text., "MSSQLSERVER", null),
new TimeSpan(0, 0, 0, 20),
txtDatabaseName.Text);
monitor.AutomaticFailover += monitor_AutomaticFailover;
monitor.ManualFailover += monitor_ManualFailover;
The last two lines here idenfity the event handlers for both and automatic and a manual failover.
Second, start the monitoring process. Since this process will take a few seconds to connect to the principal and mirror servers (and this could be more than a few seconds depending on where the server is), I would get a worker thread and launch it there:
Thread a = new Thread(StartMonitor);
a.Start();
StartMonitor is just a function that calls monitor.StartMonitor().
private void StartMonitor()
{
monitor.StartMonitoring();
SimpleDelegate del = delegate()
{
btnEndMonitoring.IsEnabled = true;
this.Cursor = Cursors.Arrow;
};
Dispatcher.Invoke(del);
}
The two event handlers you define will be invoked once the Failover events occur and after the time span you specified in the constructor has passed.
That’s it for this post, I’ll review the actual MirrorMonitor class in another post.
You can download the code here