diff --git a/src/lib/PnP.Framework/Extensions/ClientContextExtensions.cs b/src/lib/PnP.Framework/Extensions/ClientContextExtensions.cs index dbaf9aa93..eabdc4cee 100644 --- a/src/lib/PnP.Framework/Extensions/ClientContextExtensions.cs +++ b/src/lib/PnP.Framework/Extensions/ClientContextExtensions.cs @@ -1158,6 +1158,56 @@ public static async Task DeleteSiteAsync(this ClientContext clientContext) return await SiteCollection.DeleteSiteAsync(clientContext); } + /// + /// Safely assigns user email addresses to SharePoint list item user fields with automatic user resolution and error handling + /// + /// The SharePoint client context for executing operations + /// The target list item to update with user field assignments + /// Collection of field-email pairs where Field is the internal field name and Email is the user's email address + /// If true, clears the field when email is null/empty; if false, skips the assignment + /// + /// 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. + /// + 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;