Saturday, August 17, 2013

Update User Profile picture programmatically in SharePoint

User Profile Service application maintains all the Information about the User available in SharePoint as User Profiles. These Information will be synchronized with the external source such as Active Directory or Custom DB by User Profile Synchronization Service running in the SharePoint server. User Profile Photo is one of the property in User Profile called “PictureUrl”. All the User Profile Photos are maintained in SharePoint library in My Site called “User Photos”, for each User Profile 3 files are maintained with various dimensions (Large,Medium and Small size) in the library.

When a User uploads a profile picture in SharePoint, these three files will be created from the chosen file and uploaded to the Profile Pictures folder in “User Photos” library under My site and the reference to the Image will be updated to the “PictureUrl” property in the User Profile.
If we are giving an option to change the Profile picture in out custom component, we also need to create these 3 different files and update the reference in User Profile property. Below code snippet will do the need.
#region Profile Image Updation
/// 
/// Updates the current User profile Image
/// 
/// 
/// 
protected void btnProfileUpload_Click(object sender, EventArgs e)
{
    try
    {
        //Uncomment if Change profile photo functionality is required
        if (Page.IsValid && ctrlUpload.HasFile)
        {
            UploadPhoto(SPContext.Current.Web.CurrentUser.LoginName, ctrlUpload.FileBytes);
        }
    }
    catch (Exception ex)
    {
        ErrorHandling.WriteLog("btnProfileUpload_Click " + ex.Message, ex, SPContext.Current.Web);
    }
}

public void UploadPhoto(string accountName, byte[] image) 
{
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
        using (SPSite site = new SPSite(webURL))
        {
            using (SPWeb web = site.OpenWeb())
            {
                web.AllowUnsafeUpdates = true;
                ProfileImagePicker profileImagePicker = new ProfileImagePicker();
                InitializeProfileImagePicker(profileImagePicker, web);
                SPFolder subfolderForPictures = GetSubfolderForPictures(profileImagePicker);
                string fileNameWithoutExtension = GetFileNameFromAccountName(accountName);
                int largeThumbnailSize = 120; int mediumThumbnailSize = 90; int smallThumbnailSize = 30;
                using (MemoryStream stream = new MemoryStream(image))
                {
                    using (Bitmap bitmap = new Bitmap(stream, true))
                    {
                        CreateThumbnail(bitmap, largeThumbnailSize, largeThumbnailSize, subfolderForPictures, fileNameWithoutExtension + "_LThumb.jpg");
                        CreateThumbnail(bitmap, mediumThumbnailSize, mediumThumbnailSize, subfolderForPictures, fileNameWithoutExtension + "_MThumb.jpg");
                        CreateThumbnail(bitmap, smallThumbnailSize, smallThumbnailSize, subfolderForPictures, fileNameWithoutExtension + "_SThumb.jpg");
                    }
                }
                SetPictureUrl(accountName, subfolderForPictures, fileNameWithoutExtension);
                web.AllowUnsafeUpdates = false;
            }
        }               
    });
}

public void SetPictureUrl(string accountName, SPFolder subfolderForPictures, string fileNameWithoutExtension)
{

    SPSite site = subfolderForPictures.ParentWeb.Site;
    UserProfileManager userProfileManager = new UserProfileManager(SPServiceContext.GetContext(site));
    UserProfile userProfile = userProfileManager.GetUserProfile(accountName);
    string pictureUrl = String.Format("{0}/{1}/{2}_MThumb.jpg", site.Url, subfolderForPictures.Url, fileNameWithoutExtension);
    userProfile["PictureUrl"].Value = pictureUrl;
    userProfile.Commit();
} 


public string GetFileNameFromAccountName(string accountName) 
{ 
    string result = accountName; 
    string charsToReplace = @"\/:*?""<>|"; Array.ForEach(charsToReplace.ToCharArray(), charToReplace => result = result.Replace(charToReplace, '_')); 
    return result; 
}   

public void InitializeProfileImagePicker(ProfileImagePicker profileImagePicker, SPWeb web) 
{ 
    Type profileImagePickerType = typeof(ProfileImagePicker); 
    FieldInfo fieldInfo = profileImagePickerType.GetField("m_objWeb", BindingFlags.NonPublic | BindingFlags.Instance); 
    fieldInfo.SetValue(profileImagePicker, web); 
    MethodInfo miLoadPictureLibraryInternal = profileImagePickerType.GetMethod("LoadPictureLibraryInternal", BindingFlags.NonPublic | BindingFlags.Instance); 
    if (miLoadPictureLibraryInternal != null) 
    { 
        miLoadPictureLibraryInternal.Invoke(profileImagePicker, new object[] { }); 
    } 
}   

public SPFile CreateThumbnail(Bitmap original, int idealWidth, int idealHeight, SPFolder folder, string fileName) 
{ 
    SPFile file = null; Assembly userProfilesAssembly = Assembly.Load("Microsoft.Office.Server.UserProfiles, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"); 
    Type userProfilePhotosType = userProfilesAssembly.GetType("Microsoft.Office.Server.UserProfiles.UserProfilePhotos"); 
    MethodInfo miCreateThumbnail = userProfilePhotosType.GetMethod("CreateThumbnail", BindingFlags.NonPublic | BindingFlags.Static);             
    if (miCreateThumbnail != null) 
    { 
        file = (SPFile)miCreateThumbnail.Invoke(null, new object[] { original, idealWidth, idealHeight, folder, fileName }); 
    } 
    return file; 
}   

public SPFolder GetSubfolderForPictures(ProfileImagePicker profileImagePicker) 
{ 
    SPFolder folder = null; 
    Type profileImagePickerType = typeof(ProfileImagePicker); 
    MethodInfo miGetSubfolderForPictures = profileImagePickerType.GetMethod("GetSubfolderForPictures", BindingFlags.NonPublic | BindingFlags.Instance); 
    if (miGetSubfolderForPictures != null) 
    {
        folder = (SPFolder)miGetSubfolderForPictures.Invoke(profileImagePicker, new object[] {true }); 
    } 
    return folder; 
}
#endregion


 

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...