Например, тест:
Код: Выделить всё
[Test]
public async Task EnableUser()
{
IlgAdUser b2CUser = await _graphClient.CreateLocalUser(false, false, USER_FIRSTNAME_S, USER_LASTNAME_S, "some-password", USR_EMAIL_S);
b2CUser.AccountEnabled.Should().Be(false);
await _graphClient.EnableUser(b2CUser.Id);
await LongDelay(); // this was added recently
IlgAdUser loaded = (await _graphClient.GetUserById(b2CUser.Id))!;
loaded.Should().NotBeNull();
loaded.AccountEnabled.Should().Be(true);
loaded.Should().BeEquivalentTo(b2CUser, options => options.Excluding(u => u.AccountEnabled).ComparingByMembers());
}
Вот реализация GraphClient:
Код: Выделить всё
public async Task CreateLocalUser(bool accountEnabled, bool isGlobalAdmin, string firstName, string lastName, string password, string? email = null,
string? displayName = null, string? mailNickname = null, bool isOrganizationAdmin = false, string? companyName = null, string? jobTitle = null,
string? department = null, string? mobilePhone = null, string? officePhone = null, CultureInfo? preferredCulture = null)
{
//
// https://learn.microsoft.com/en-us/graph/api/user-post-users?view=graph-rest-1.0&tabs=csharp#example-1-create-a-user
//
string dispName = string.IsNullOrWhiteSpace(displayName) ? MakeDisplayName(lastName, firstName) : displayName.Trim();
string mailNick = string.IsNullOrWhiteSpace(mailNickname) ? MakeMailNickname(email, firstName, lastName) : mailNickname.Trim();
User user = new()
{
AccountEnabled = accountEnabled,
GivenName = firstName.Trim(),
Surname = lastName.Trim(),
DisplayName = dispName,
Mail = string.IsNullOrWhiteSpace(email) ? string.Empty : email,
MailNickname = mailNick,
UserPrincipalName = MakeUserPrincipalName(mailNick),
PasswordProfile = new() { ForceChangePasswordNextSignIn = false, Password = password }
};
...
try
{
User newUser = await _graphClient.Users.PostAsync(user).ConfigureAwait(false) ?? throw new IlgGraphClientException("Failed to create new user");
if (string.IsNullOrEmpty(newUser.Id)) throw new IlgGraphClientException("Failed to create new user: Id is empty");
IlgAdUser loaded = await GetUserById(newUser.Id).ConfigureAwait(false) ??
throw new IlgGraphClientException($"User with email='{email}' is created but subsequent load operation failed");
return loaded;
}
catch (ODataError ex)
{
if (!ex.Message.Equals("A conflicting object with one or more of the specified property values is present in the directory.")) throw;
string errMsg = $"User with same email already exists {email}";
LogFailedToAddUserEmailAlreadyTaken(email, ex);
throw new IlgGraphClientUserExistsException(errMsg, ex);
}
catch (Exception ex)
{
string errMsg = $"Could not create new user with email='{email}'.";
LogFailedToCreateNewUser(email, ex);
throw new IlgGraphClientException(errMsg, ex);
}
}
Код: Выделить всё
public async Task EnableUser(string userId)
{
using (_logger.BeginScope(nameof(EnableUser)))
{
try
{
IlgAdUser user = await GetUserById(userId).ConfigureAwait(false) ??
throw new IlgGraphClientException($"Failed to enable user: User with Id={userId} not found in the Directory");
User usr = new()
{
AccountEnabled = true
};
// the returned user value is NULL here, do not use variable
await _graphClient.Users[user.Id].PatchAsync(usr).ConfigureAwait(false);
}
catch (Exception ex)
{
string errMsg = $"Could not enable user with Id={userId}";
LogFailedToEnableUser(userId, ex);
throw new IlgGraphClientException(errMsg, ex);
}
}
}
Код: Выделить всё
public async Task GetUserById(string userId)
{
using (_logger.BeginScope(nameof(GetUserById)))
{
if (string.IsNullOrWhiteSpace(userId))
throw new ArgumentNullException(nameof(userId));
try
{
IEnumerable users = await GetUsers($"id eq '{userId}'").ConfigureAwait(false);
IEnumerable usersArr = users as IlgAdUser[] ?? [..users];
return !usersArr.Any() ? null : usersArr.First();
}
catch (Exception ex)
{
LogFailedToLoadUserById(userId, ex);
string errMsg = $"Could not get user with Id={userId}";
throw new IlgGraphClientException(errMsg, ex);
}
}
}
Код: Выделить всё
public async Task GetUsers(string? filter = null)
{
using (_logger.BeginScope("GetUsers"))
{
try
{
string[] selectAttributes = await MakeUserAttributesList().ConfigureAwait(false);
UserCollectionResponse? userColResp = await _graphClient.Users.GetAsync(config =>
{
config.QueryParameters.Filter = filter;
config.QueryParameters.Select = selectAttributes;
// config.QueryParameters.Orderby = ["displayName"];
}).ConfigureAwait(false);
return await RetrieveUsersForRequestSortedByFullName(userColResp).ConfigureAwait(false);
}
catch (Exception ex)
{
LogFailedToLoadUsers(filter, ex);
const string ERR_MGS_S = "Could not get all users";
throw new IlgGraphClientException(ERR_MGS_S, ex);
}
}
}