From 005b809d31ef71f48c333f6974653642c3ee4608 Mon Sep 17 00:00:00 2001 From: jeppesc11 Date: Sun, 23 Nov 2025 14:50:55 +0100 Subject: [PATCH] Added EnsureAndSetUserFields method to ClientContextExtensions Implements safe user field assignment with automatic user resolution and error handling using ExceptionHandlingScope pattern. --- .../Extensions/ClientContextExtensions.cs | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) 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;