diff --git a/src/AgDatabase.cs b/src/AgDatabase.cs index d44cf0c..127092a 100755 --- a/src/AgDatabase.cs +++ b/src/AgDatabase.cs @@ -12,9 +12,13 @@ namespace AgDatabaseMove using System.Data.SqlClient; using System.Linq; using System.Threading; + using System.Threading.Tasks; using Exceptions; + using Microsoft.SqlServer.Management.Smo; using Polly; using SmoFacade; + using AvailabilityGroup = SmoFacade.AvailabilityGroup; + using Server = SmoFacade.Server; public interface IAgDatabase @@ -158,7 +162,29 @@ public void DropAllLogins() public void AddLogin(LoginProperties login) { - _listener.ForEachAgInstance(server => server.AddLogin(login)); + if (login.LoginType == LoginType.SqlLogin && login.Sid == null) { + AddNewSqlLogin(login); + } else + { + _listener.ForEachAgInstance(server => server.AddLogin(login)); + } + } + + /// + /// Creates a new Sql login across all members of the availability group. + /// Assumes associated database has been created and the login being + /// created does not previously exist. In the case of + /// Sql logins on availability groups, the login must first be created on + /// a singular instance in the availability group, in this case the primary, + /// so Sql Server will generate a new SID. This SID will be saved and used to + /// create the same login on each ag replica. + /// + /// A new login to create across all members of an availability group. + private void AddNewSqlLogin(LoginProperties login) + { + var createdLogin = _listener.Primary.AddLogin(login); + login.Sid = createdLogin.Sid; + Parallel.ForEach(_listener.Secondaries, server => server.AddLogin(login)); } public IEnumerable AssociatedRoles() diff --git a/src/SmoFacade/Login.cs b/src/SmoFacade/Login.cs index 6aa0ed3..e31d403 100755 --- a/src/SmoFacade/Login.cs +++ b/src/SmoFacade/Login.cs @@ -123,6 +123,7 @@ private static Microsoft.SqlServer.Management.Smo.Login ConstructLogin(LoginProp else { login.Create(); } + login.Refresh(); return login; } diff --git a/src/SmoFacade/Server.cs b/src/SmoFacade/Server.cs index d137465..ceea404 100755 --- a/src/SmoFacade/Server.cs +++ b/src/SmoFacade/Server.cs @@ -278,11 +278,11 @@ private void Backup(Backup backup, string backupDirectoryPathQuery, string datab backup.SqlBackup(_server); } - public void AddLogin(LoginProperties login) + public Login AddLogin(LoginProperties login) { var matchingLogin = Logins.SingleOrDefault(l => l.Name.Equals(login.Name, StringComparison.InvariantCultureIgnoreCase)); - if(matchingLogin == null) matchingLogin = new Login(login, this); + return matchingLogin ?? new Login(login, this); } public void AddRole(LoginProperties login, RoleProperties role)