public async Task <Unit> Handle(InsertUpdateActiveDirectoryUserCommand request, CancellationToken cancellationToken) { _unitOfWork.BeginTransaction(); try { List <UserIAG> userIAGList = new List <UserIAG>(); IEnumerable <UserDto> usersInAtlas; var usersFromAd = await _graphClient.GetTransitiveGroupMembersAsync(); if (!usersFromAd.Any()) { throw new Exception($"No users not found in Active Directory"); } usersInAtlas = await _userQueries.GetUsersAsync(); foreach (Microsoft.Graph.User user in usersFromAd.OfType <Microsoft.Graph.User>()) { UserIAG userIAG = new UserIAG(); userIAG.UserId = user.UserPrincipalName; userIAG.IsDisabled = user.AccountEnabled ?? false; userIAG.DifferentADCompanyRole = false; userIAG.DifferentADManager = false; userIAG.CompanyRole = user.JobTitle; if (usersInAtlas.Any()) { var userFound = usersInAtlas.Where(x => x.UserPrincipalName == userIAG.UserId).FirstOrDefault(); if (userFound != null) { userIAG.DifferentADCompanyRole = userFound.CompanyRole == userIAG.CompanyRole ? false : true; try { var manager = (await _graphClient.GetUserManagerByIdAsync(user.Id)) as Microsoft.Graph.User; if (manager != null) { userIAG.ManagerSamAccountName = manager.OnPremisesSamAccountName; // Generate a SamAccountName if not provided by AD if (string.IsNullOrWhiteSpace(userIAG.ManagerSamAccountName)) { var name = manager.Mail ?? manager.UserPrincipalName; userIAG.ManagerSamAccountName = name.Split('@').First(); } var managerFound = usersInAtlas.Where(x => x.ManagerSamAccountName == userIAG.ManagerSamAccountName).FirstOrDefault(); if (managerFound != null) { userIAG.DifferentADManager = managerFound.ManagerSamAccountName == userIAG.ManagerSamAccountName ? false : true; } } } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception ex) { _logger.LogError(ex, "Manager not found for {User}", user.DisplayName); } #pragma warning restore CA1031 // Do not catch general exception types userIAGList.Add(userIAG); } } } if (userIAGList.Count() > 0) { await _userRepository.UpdateUserIAGAsync(userIAGList); } _unitOfWork.Commit(); _logger.LogInformation("Sync completed successfully"); } catch { _unitOfWork.Rollback(); throw; } return(Unit.Value); }