Search code examples
c#windowswindows-servicesfailoverfailovercluster

Windows Failover Cluster API still Valid?


I was looking for options for deploying. Net Windows Service under 2 windows failover clusters instances. But I stuck with Windows Failure Cluster API usage for communicating across windows service instances. I couldn't see any Ref. use it. Is it still valid?


Solution

  • The preferred method is by calling the Powershell Cmdlets from your code.

    Here's a class I wrote to cluster a virtual machine. It should give you enough to build on to get to where you want to go.

    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Management.Automation;
    
    
    public static class FailoverClustering
    {
        public static List<string> GetClusterNode(string cluster)
        {
            List<string> nodes = new List<string>();
    
            PowerShell powerShell = PowerShell.Create();
    
            powerShell.AddCommand("Get-ClusterNode");
            powerShell.AddParameter("Cluster", cluster);
            foreach (PSObject result in powerShell.Invoke())
                nodes.Add(result.Members["Name"].Value.ToString());
    
            if (powerShell.Streams.Error.Count > 0)
                throw new Exception(powerShell.Streams.Error[0].Exception.Message);
    
            powerShell.Dispose();
    
            return nodes;
        }
    
        public static ClusteredVirtualMachine AddClusterVirtualMachineRole(string cluster, string virtualMachine)
        {
            PowerShell powerShell = PowerShell.Create();
    
            powerShell.AddCommand("Add-ClusterVirtualMachineRole");
            powerShell.AddParameter("Cluster", cluster);
            powerShell.AddParameter("VirtualMachine", virtualMachine);
    
            Collection<PSObject> result = powerShell.Invoke();
    
            if (powerShell.Streams.Error.Count > 0)
                throw new Exception(powerShell.Streams.Error[0].Exception.Message);
    
            powerShell.Dispose();
    
            return new ClusteredVirtualMachine(
                result[0].Members["Name"].Value.ToString(),
                result[0].Members["OwnerNode"].Value.ToString(),
                result[0].Members["State"].Value.ToString()
                );
        }
    }
    
    public class ClusteredVirtualMachine
    {
        public string Name { get; }
        public string OwnerNode { get; }
        public State State { get; }
    
        public ClusteredVirtualMachine(string name, string ownerNode, string state)
        {
            Name = name;
            OwnerNode = ownerNode;
            switch (state)
            {
                case "Offline": State = State.Offline; break;
                case "Online": State = State.Online; break;
            }
        }
    }
    
    public enum State
    {
        Online,
        Offline
    }