Update My Site User Profile Picture of another User using Visual Studio Sequential Workflow in SharePoint 2010

Ahamed Fazil Buhari
 
Senior Developer
June 24, 2017
 
Rate this article
 
Views
2709

In my previous article – Update ‘My Site’ User Profile Picture of Any User Using SSOM In SharePoint, I covered updating User Profile Picture using Server Side Object Model and also I mentioned the limitations in that approach (If we want to update other user’s Profile picture, then the currently logged in user should be User Profile Service Application Administrator).

In this article, we are going to achieve the same functionality i.e., Update ‘My Site’ User Profile Picture of other users by any logged in user (doesn’t need to be User Profile Service Application Administrator). This can be done using Visual Studio Workflow. Two things are needed here, one is Picture Library and second thing is Visual Studio Sequential Workflow

Step 1: Create a Picture Library in your SharePoint site where you want to upload the profile pictures,

image

We can use this Picture Library to store the pictures of users.

image

Step 2: Open Visual Studio, Create New Project -> Select Sequential Workflow as shown below,

image

Step 3: Enter the URL of the site and click on Next.

image

Step 4: Give name to the workflow and select type as List Workflow.

image

Step 5: Associate the Picture Library which we created in Step 1.

image

Step 6: Select the check boxes based on your requirement.

image

Step 7: Drag and drop the Code activity in your sequential workflow window under ‘onWorkflowActivated1’.

image

Step 8: Double click on the Code Activity and paste the below code. Add the Microsoft.Office.Server.UserProfiles references.

image

Add the below code, the code is self-explanatory with comments

————————x————————

 private void UpdateUserProfile(object sender, EventArgs e)
         {
             try
             {      
                 //Give your domain name, for example - abccompanyahamed
                 string domainName = "abccompany";
                 //Retrieving account name from picture File name, in my case picture name is ahamed.jpg 
                 string accName = Path.GetFileNameWithoutExtension(workflowProperties.Item["EncodedAbsUrl"].ToString());
                 SPUser targetUser = workflowProperties.Web.EnsureUser(domainName + "\" + accName);                             
 
                 if (targetUser != null)
                 {
                     string username = targetUser.LoginName.ToString();
 
                     if (!string.IsNullOrEmpty(username))
                     {                        
                         using (SPSite site = new SPSite(workflowProperties.SiteId))
                         {        
                             //Get Service Context
                             SPServiceContext context = SPServiceContext.GetContext(site);
                             //Create User Profile Manager obj from the context
                             UserProfileManager profileManager = new UserProfileManager(context);
                             //Get profie of the user by using his/her name
                             UserProfile profile = profileManager.GetUserProfile(username);  
                             //Check for Profile existance
                             if (profile != null)
                             {          
                                 //Update the PictureURL property of the selected User Profile.
                                 profile[PropertyConstants.PictureUrl].Value = workflowProperties.Item["EncodedAbsUrl"].ToString();
                                 profile.Commit();                                
                             }
                         }
                     }
                 }                
             }
             catch (Exception ex)
             {            
                 SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("User Profile Update", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
             }
 
         }
 

————————x————————

Overall, the .cs file looks like below screenshot,

image

Sometimes, there might be a chance that it takes time to reach User Profile Property before workflow complete. To avoid this, add ‘delayActivitey’ and add the TimeoutDuratoin value to be 00:00:30 like this

image

 

Step 9: Build and Deploy the solution. Once it is deployed successfully, go to Picture Library created in Step 1 and upload the image (Image file name should be user name, example – ahamed.jpg)

Sample My Site – My Profile

image

Note: Make sure My Site is up and running in your environment and the user profile page should be available prior to updating user profile picture.

 

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
 

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
 

How to restore SharePoint mysites from database backup

Tarun Kumar Chatterjee
 
Net – Technology Specialist
June 9, 2016
 
Rate this article
 
Views
8437

In one of our project suddenly Active directory was messed up because of some network issue and SharePoint user profile synch service was not able reach to Active Directory. All the users got the email notification that within 14 days all the mysites will be deleted. It became nightmare to us as it was supported by our team only & we could not say to take the manual backup individually as because user used to keep their personal information like mail backup (PST) etc. in their own mysite & so the size was also huge. It happened because of my site clean-up timer job deleting the profile if it does not find in active directory.  While deleting the profile it will also delete the manual entered personal information like note, photo and links etc. Though the active directory was available after 2 hrs but my site clean-up timer job marked all the mysites deleted flag as true, so there were no option we found to avoid the mysites deletion, even disable clean-up timer job also not worked.

After a very hard try we found an ultimate solution i.e. to take the database backup and restore the mysites after 14 days of mysites deletion. Thought of sharing with you with the details if it helps anyone. Let see the steps we followed

We can verify restorable count by running the query in sharepoint database

select * from SharePoint_Content_MySites.dbo.SiteDeletion where Restorable = 1

Before the clean-up timer job automatically delete all the mysites ,we took the below database backup and restore in a test environment rather in production environment, as because we should not touch the live box SharePoint database.

· SharePoint_SA_User_Profiles

· SharePoint_SA_User_Profiles_Sync

· SharePoint_SA_Social_Data

· SharePoint_Content_MySites

After 14 days while all the mysites are deleted we did follow the below steps

· On the Start screen, click SharePoint 2013 Central Administration.

· If SharePoint 2013 Central Administration is not on the Start screen:

Right-click Computer, clicks all apps, and then clicks SharePoint 2013 Central Administration.

· Go to Application Management and Manage Content Database

clip_image002

· Change the Webapplication where we have the Mysites

clip_image004

· Make the existing pointed database as Offline

clip_image006

· Now Click on Add Content Database

clip_image008

· Point the restored SharePoint_Content_MySites database and Click on ok.

· Go to Backup and Restore, click on Export to Site or List

clip_image010

· Change the Site Collection, select the mysite under the Site section, provide the Exported shared file path ( The file name should have cmp extension) & then click on Start Export

clip_image011

It will take some times to create the backup, will get the notfication as soon as the backup is being completed. It will generate a cmp backup file as well as a log file.

We can also export the cmp file by using the below powershell commands

 Export-SPWeb http://sharepoint.com/mysites/personal/tkumarch1 –Path "C:Mysites_exporttkumarch1_export.cmp"
 Export-SPWeb http://sharepoint.com/mysites/personal/tkumarch2 –Path "C:Mysites_exporttkumarch2_export.cmp"
 

To restore the backup we need to run the below powershell commands in production enviornment

 import-SPWeb http://sharepoint.com/mysites/personal/tkumarch1 –Path "C:Mysites_exporttkumarch1_export.cmp"
 import-SPWeb http://sharepoint.com/mysites/personal/tkumarch2 –Path "C:Mysites_exporttkumarch2_export.cmp"
 

We need to repeat the export and import for all the individual mysites which are deleted.

After all the imports are done we need to make the current content database as offline and previous pointed content database as online in test environment. That’s all, we are all set, cheers!!!

Happy coding

Tarun Kumar Chatterjee

Category : SharePoint

Author Info

Tarun Kumar Chatterjee
 
Net – Technology Specialist
 
Rate this article
 
Tarun has been working in IT Industry for over 12+ years. He holds a B-tech degree. He is passionate about learning and sharing the tricks and tips in Azure, .Net ...read more
 

Leave a comment