public async Task <UserReference> Handle(CreateUserCommand request, CancellationToken cancellationToken) { var exists = await _userRepository.CheckUserExistsAsync(request.UserPrincipalName); if (exists) { throw new AtlasBusinessException($"A user with the id {request.UserPrincipalName} already exists."); } _unitOfWork.BeginTransaction(); try { // Get the new user from AD var userFromAd = await _graphClient.GetUserByIdAsync(request.UserPrincipalName); if (userFromAd == null) { throw new Exception($"User {request.UserPrincipalName} not found in Active Directory"); } var user = _mapper.Map <User>(request); // Filled user fields with values from AD user.AzureObjectIdentifier = userFromAd.Id; user.Email = userFromAd.Mail; user.FirstName = userFromAd.GivenName; user.LastName = userFromAd.Surname; user.FavoriteLanguage = user.FavoriteLanguage ?? userFromAd.PreferredLanguage; user.Location = userFromAd.OfficeLocation; user.PhoneNumber = userFromAd.MobilePhone; user.DisplayName = userFromAd.DisplayName; user.UserPrincipalName = userFromAd.UserPrincipalName; user.SamAccountName = userFromAd.OnPremisesSamAccountName; user.CompanyRole = userFromAd.JobTitle; user.Permissions.ToList().ForEach(p => p.Departments.ToList().ForEach(d => d.CompanyId = p.CompanyId)); // Seach user manager in AD try { var manager = (await _graphClient.GetUserManagerByIdAsync(request.UserPrincipalName)) as Microsoft.Graph.User; if (manager != null) { user.ManagerSamAccountName = manager.OnPremisesSamAccountName; // Generate a SamAccountName if not provided by AD if (string.IsNullOrWhiteSpace(user.ManagerSamAccountName)) { var name = manager.Mail ?? manager.UserPrincipalName; user.ManagerSamAccountName = name.Split('@').First(); } } } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception e) { _logger.LogError(e, $"Cannot found manager for user {request.UserPrincipalName}"); } #pragma warning restore CA1031 // Do not catch general exception types // Generate a DisplayName if not provided by AD if (string.IsNullOrWhiteSpace(user.DisplayName)) { user.DisplayName = $"{user.FirstName} {user.LastName}".Trim(); } // Generate a SamAccountName if not provided by AD if (string.IsNullOrWhiteSpace(user.SamAccountName)) { var name = user.Email ?? user.UserPrincipalName; user.SamAccountName = name.Split('@').First(); } var userId = await _userRepository.CreateUserAsync(user); _unitOfWork.Commit(); _logger.LogInformation("New user created with id {Atlas_UserId}.", userId); return(new UserReference { UserId = userId }); } catch (Exception) { _unitOfWork.Rollback(); throw; } }