/// <summary> /// Creates availability group using Smo /// </summary> /// <param name="agName">Availability group name.</param> /// <param name="dbNames">Datbases to be part of the AG.</param> /// <param name="replicas">replicas to be part of the AG.</param> /// <param name="server">smo server.</param> public static AvailabilityGroup CreateAG(string agName, IEnumerable <string> dbNames, IEnumerable <Smo.Server> replicas, Smo.Server server) { if (!AGHelper.IsAGExist(agName, server)) { AvailabilityGroup ag = new AvailabilityGroup(server, agName); foreach (string dbName in dbNames) { ag.AvailabilityDatabases.Add(new AvailabilityDatabase(ag, dbName)); } foreach (Smo.Server replica in replicas) { AvailabilityReplica ar = new AvailabilityReplica(ag, replica.Name); ar.EndpointUrl = ARHelper.GetHadrEndpointUrl(replica); ar.AvailabilityMode = AvailabilityReplicaAvailabilityMode.AsynchronousCommit; ar.FailoverMode = AvailabilityReplicaFailoverMode.Manual; ag.AvailabilityReplicas.Add(ar); } ag.Create(); return(ag); } else { throw new Exception(string.Format("The requested availability Group {0} already exist in the given server {1}", agName, server.Name)); } }
// When we called this primary and secondary should being create public void TestCreateAGWithTwoReplicasWithoutDatabase() { Smo.Server primary = replicas[0]; AvailabilityGroup ag = new AvailabilityGroup(primary, agName); List <Smo.Server> secondaries = replicas.GetRange(1, replicas.Count - 1); for (int i = 0; i < replicas.Count; ++i) { AvailabilityReplica ar = ARHelper.BuildAR(ag, replicas[i].Name, replicaEndpointUrls[i]); ag.AvailabilityReplicas.Add(ar); } try { Console.WriteLine("Creating availability group '{0}' on server '{1}", ag.Name, primary.Name); ag.Create(); Thread.Sleep(1000); //Sleep a tick to let AG create take effect foreach (Smo.Server srv in secondaries) { srv.JoinAvailabilityGroup(agName); } CreateAGListener(); // enable autoseeding in secondary //secondary.GrantAvailabilityGroupCreateDatabasePrivilege(agName); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine("Failed to create AG {0}", ag.Name); AGHelper.DropAG(ag.Name, primary); } }