Update ‘My Site’ User Profile Picture of any User using SSOM in SharePoint

Ahamed Fazil Buhari
 
Senior Developer
April 23, 2017
 
Rate this article
 
Views
4213

In this article let’s see how to update User Profile Picture (of any user) in My Site. Most of the blog posts explains how to change the Profile Picture of currently logged in User. But in this article we can see how to update profile picture of any user with this code. Let’s get started.

Before we get into the coding part, make sure you have ‘My Site’ configured and running in your environment. In the following server side code, user can select a picture and upload it to SharePoint through Browse Button. Ensure that the image name is in the name of user’s account name (for example: ahamedsp.jpg (make sure it is in jpg or jpeg format)). In this example, I am using <asp:FileUpload ID="imgUpload" runat="server" /> element to upload the picture

 if (Page.IsValid && imgUpload.HasFile)
 {
 string loginNameForProfileToUpdatePic = "companyNameuserABC”;
 
 try
 	{                                       
 		#region Impersonate using RunWithElevatedPrivileges
 		
 		SPSecurity.RunWithElevatedPrivileges(delegate()
 		{
 			using (SPSite site = new SPSite(SPContext.Current.Site.Url))
 			{
 				SPServiceContext serviceContext = SPServiceContext.GetContext(site);
 				UserProfileManager userProfileMgr = new UserProfileManager(serviceContext,false);
 				ProfilePropertyManager profilePropMgr =
 				new UserProfileConfigManager(serviceContext).ProfilePropertyManager;
 
 				// Retrieve all properties for the "UserProfile" profile subtype,
 				// and retrieve the property values for a specific user.
 				ProfileSubtypePropertyManager subtypePropMgr =
 				profilePropMgr.GetProfileSubtypeProperties("UserProfile");
 				UserProfile userProfile = userProfileMgr.GetUserProfile(loginNameForProfileToUpdatePic);
 
 				SPSite mySite = new SPSite(userProfileMgr.MySiteHostUrl);
 				SPWeb web = mySite.RootWeb;
 				SPFolder subfolderForPictures = web.Folders["User Photos"];
 				web.AllowUnsafeUpdates = true;
 
 				Stream fs = imgUpload.PostedFile.InputStream;
 				byte[] buffer = new byte[imgUpload.PostedFile.ContentLength];
 				fs.Read(buffer, 0, Convert.ToInt32(imgUpload.PostedFile.ContentLength));
 				fs.Close();
 				int largeThumbnailSize = 300;
 				int mediumThumbnailSize = 72;
 				int smallThumbnailSize = 48;
 
 				string accName = accountName.Substring(accountName.IndexOf(@"") + 1);
 				using (MemoryStream stream = new MemoryStream(buffer))
 				{
 					using (Bitmap bitmap = new Bitmap(stream, true))
 					{
 						CreateThumbnail(bitmap, largeThumbnailSize, largeThumbnailSize, subfolderForPictures,
 						accName + "_LThumb.jpg");
 						CreateThumbnail(bitmap, mediumThumbnailSize, mediumThumbnailSize, subfolderForPictures,
 						accName + "_MThumb.jpg");
 						CreateThumbnail(bitmap, smallThumbnailSize, smallThumbnailSize, subfolderForPictures,
 						accName + "_SThumb.jpg");
 					}
 				}
 				string pictureUrl = String.Format("{0}/{1}/{2}_MThumb.jpg", subfolderForPictures.ParentWeb.Site.Url, subfolderForPictures.Url, accName);
 				// Change the value of a single-value user property.
 				userProfile[PropertyConstants.PictureUrl].Value = pictureUrl;                          
 				// Save the changes to the server.
 				userProfile.Commit();
 				web.AllowUnsafeUpdates = false;
 				lblMessage.Text = accountName + " Account Profile Picture has been Updated Successfully.";
 			}                       
 		});
 		 
 		#endregion
 
 							
 	}
 	catch(Exception ex)
 	{
 	 SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("User Profile Picture Upload", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);                                           
 	}
 }
 
 
 //Below function is used to create Thumbnail picture of uploaded picture file.
 public SPFile CreateThumbnail(Bitmap original, int idealWidth, int idealHeight, SPFolder folder, string fileName)
 {
 	SPFile file = null;
 	Assembly userProfilesAssembly = typeof(UserProfile).Assembly;
 
 	Type userProfilePhotosType = userProfilesAssembly.GetType("Microsoft.Office.Server.UserProfiles.UserProfilePhotos");
 	MethodInfo[] mi_methods = userProfilePhotosType.GetMethods(BindingFlags.NonPublic | BindingFlags.Static);
 
 	MethodInfo mi_CreateThumbnail = mi_methods[0];
 	if (mi_CreateThumbnail != null)
 	{                
 		file = (SPFile)mi_CreateThumbnail.Invoke(null, new object[] { original, idealWidth, idealHeight, folder, fileName });
 	}
 	return file;
 }

Note : Impersonating or Elevating privileges won’t work if you want to update other User’s Profile information. To change other user’s profile details, the logged-on user must be a User Profile administrator or should have full control permissions in the User Profile Service Application. Still , In this article, we have used Elevated Privilege to update Profile picture of currently logged in user without any access issue.

Happy Coding

Ahamed

Author Info

Ahamed Fazil Buhari
 
Senior Developer
 
Rate this article
 
Ahamed is a Senior Developer and he has very good experience in the field of Microsoft Technologies, especially SharePoint, Azure, M365, SPFx, .NET and client side scripting - JavaScript, TypeScript, ...read more
 

Leave a comment