Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions src/lib/PnP.Framework/Extensions/ClientContextExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1158,6 +1158,56 @@ public static async Task<bool> DeleteSiteAsync(this ClientContext clientContext)
return await SiteCollection.DeleteSiteAsync(clientContext);
}

/// <summary>
/// Safely assigns user email addresses to SharePoint list item user fields with automatic user resolution and error handling
/// </summary>
/// <param name="ctx">The SharePoint client context for executing operations</param>
/// <param name="item">The target list item to update with user field assignments</param>
/// <param name="fieldAssignments">Collection of field-email pairs where Field is the internal field name and Email is the user's email address</param>
/// <param name="clearIfNullOrWhiteSpace">If true, clears the field when email is null/empty; if false, skips the assignment</param>
/// <remarks>
/// This method queues operations using ExceptionHandlingScope but does not execute them.
/// The caller must call ctx.ExecuteQueryRetry() after this method to execute the queued operations.
/// Multiple calls can be batched together before executing.
/// </remarks>
public static void EnsureAndSetUserFields(
this ClientContext ctx,
ListItem item,
IEnumerable<(string Field, string Email)> fieldAssignments,
bool clearIfNullOrWhiteSpace)
{
foreach (var (field, email) in fieldAssignments)
{
if (string.IsNullOrWhiteSpace(email))
{
if (clearIfNullOrWhiteSpace)
{
item[field] = null;
item.Update();
}

continue;
}

var scope = new ExceptionHandlingScope(ctx);
using (scope.StartScope())
{
using (scope.StartTry())
{
item[field] = FieldUserValue.FromUser(email);
item.Update();
}

using (scope.StartCatch())
{
ctx.Web.EnsureUser(email);
item[field] = FieldUserValue.FromUser(email);
item.Update();
}
}
}
}

internal static CookieContainer GetAuthenticationCookies(this ClientContext context)
{
var authCookiesContainer = context.GetContextSettings()?.AuthenticationManager.CookieContainer;
Expand Down