Imports DigitalData.Modules.Database Imports DigitalData.Modules.Logging Namespace SyncUsers Public Class SyncUsersMSSQL Implements ISyncUsers Private _logConfig As LogConfig Private _logger As Logger Private _mssql As MSSQLServer Private Const ADDED_WHO = "Active Directory Sync" Public Sub New(LogConfig As LogConfig, MSSQL As MSSQLServer) _logConfig = LogConfig _logger = LogConfig.GetLogger() _mssql = MSSQL End Sub Public Function SyncUsers(GroupName As String, Users As List(Of ADUser), PropertyMapping As List(Of AttributeMapping)) As List(Of ADUser) Implements ISyncUsers.SyncUsers Dim oGroupId As Integer Dim oSyncedUsers As New List(Of ADUser) Try _logger.Debug("Getting group Id for group {0}", GroupName) oGroupId = GetGroupId(GroupName) If oGroupId = 0 Then _logger.Debug("Group {0} does not exist in database. Exiting.", GroupName) Return oSyncedUsers End If _logger.Debug("Using group Id {0}", oGroupId) Catch ex As Exception _logger.Error(ex) Return oSyncedUsers End Try For Each oUser In Users Dim oUserId As Int64 Dim oUserExists As Boolean = False ' Check if user already exists Try _logger.Debug("Checking if user {0} exists", oUser) oUserId = GetUserId(oUser.samAccountName) oUserExists = oUserId > 0 _logger.Debug("User {0} exists in database: {1}", oUser, oUserExists) Catch ex As Exception _logger.Error(ex) _logger.Warn("Could not get UserId for user. Skipping.") Continue For End Try ' I user does not exist, create a new user Try If Not oUserExists Then _logger.Debug("Creating new user for {0}", oUser) oUserId = CreateUser(oUser) _logger.Debug("User created with Id {0}", oUserId) End If Catch ex As Exception _logger.Error(ex) _logger.Warn("Could not create user. Skipping.") Continue For End Try ' Add custom attributes to user Try AddCustomAttributesToUser(oUser, oUserId) Catch ex As Exception _logger.Error(ex) _logger.Debug("Could not add custom attributes to user {0}. Continuing.", oUser) End Try ' Add the user to group Try AddUserToGroup(oUserId, oGroupId) Catch ex As Exception _logger.Error(ex) _logger.Warn("Could not add user {0} to group {1}. Skipping.", oUser, GroupName) Continue For End Try oSyncedUsers.Add(oUser) Next Return oSyncedUsers End Function Private Sub AddUserToGroup(UserId As Integer, GroupId As Integer) Implements ISyncUsers.AddUserToGroup Try Dim oSQL = $"SELECT COUNT(*) FROM TBDD_GROUPS_USER WHERE USER_ID = {UserId} AND GROUP_ID = {GroupId}" Dim oResult = True If _mssql.NewExecuteScalar(oSQL) = 0 Then oSQL = $"INSERT INTO TBDD_GROUPS_USER (USER_ID, GROUP_ID, ADDED_WHO) VALUES ({UserId}, {GroupId}, '{ADDED_WHO}')" oResult = _mssql.NewExecutenonQuery(oSQL) Else _logger.Debug($"UserGroup-Relation [{UserId}/{GroupId}] already existing") End If If oResult = False Then Throw New Exception("Error while adding user to group!") End If Catch ex As Exception _logger.Error(ex) Throw ex End Try End Sub Private Function GetGroupId(GroupName As String) As Integer Implements ISyncUsers.GetGroupId Try Dim oSQL As String = $"SELECT GUID FROM TBDD_GROUPS WHERE UPPER(NAME) = UPPER('{GroupName}') AND AD_SYNC = 1 AND ACTIVE = 1" Dim oGroupId = _mssql.NewExecuteScalar(oSQL) If IsDBNull(oGroupId) OrElse oGroupId = 0 Then _logger.Debug("Group {0} not found in database.", GroupName) Return 0 End If Return oGroupId Catch ex As Exception _logger.Error(ex) Throw ex End Try End Function Private Function GetUserId(UserName As String) As Integer Implements ISyncUsers.GetUserId Try Dim oSQL As String = $"SELECT GUID FROM TBDD_USER WHERE UPPER(USERNAME) = UPPER('{UserName}')" Dim oUserId = _mssql.NewExecuteScalar(oSQL) If IsDBNull(oUserId) OrElse oUserId = 0 Then Return 0 End If Return oUserId Catch ex As Exception _logger.Error(ex) Throw ex End Try End Function Private Function CreateUser(User As ADUser) As Integer Implements ISyncUsers.CreateUser Try Dim oUserId As Integer = GetUserId(User.samAccountName) If oUserId = 0 Then Dim oSQL As String = $"INSERT INTO TBDD_USER (PRENAME, NAME, USERNAME, EMAIL, ADDED_WHO) VALUES ('{User.GivenName}', '{User.Surname}', UPPER('{User.samAccountName}'), '{User.Email}', '{ADDED_WHO}')" Dim oResult = _mssql.NewExecutenonQuery(oSQL) If oResult = True Then oUserId = _mssql.NewExecuteScalar("SELECT MAX(GUID) FROM TBDD_USER") Return oUserId Else Throw New Exception("Error while inserting user!") End If Else Return oUserId End If Catch ex As Exception _logger.Error(ex) Throw ex End Try End Function Public Sub AddCustomAttributesToUser(User As ADUser, UserId As Integer) Implements ISyncUsers.AddCustomAttributesToUser Dim oCustomAttributes = User.CustomAttributes _logger.Debug("Adding {0} Custom Attributes to User {1}", oCustomAttributes.Count, User) For Each oAttribute In oCustomAttributes Dim oSQL As String = $"UPDATE TBDD_USER SET {oAttribute.MSSQLColumn} = '{oAttribute.Value}', CHANGED_WHO = '{ADDED_WHO}' WHERE GUID = {UserId}" Dim oResult = _mssql.NewExecutenonQuery(oSQL) If oResult = False Then _logger.Debug("Custom Attribute {0} could not be added to user {1}", oAttribute.Name, User.samAccountName) Continue For End If Next End Sub End Class End Namespace