Thursday, December 13, 2012

Upload profile picture programatically sharepoint 2010

Here is simple code for uploading profile picture in internal profile  picture library "profile pictures".Inorder to implement this first you configure profile service in your site.
protected void btnUpload_Click(object sender, EventArgs e)
 {
   byte[] bytImgProfile = FUProfileImage.FileBytes;
   UploadProfileImages(your login name ,  web, bytImgProfile, out profileImgURL);
 }
public bool UploadProfileImages(string accountName,  SPWeb web, byte[] bytImgProfile, out string pictureUrl)
 { 
              SPWeb mySiteWeb = web;
              SPFolder subfolderForPictures = null;
              string accountNameForFileName = null;
              SPSecurity.RunWithElevatedPrivileges(delegate()
               {
                    using (SPSite site = new SPSite("address of your my site host"))
                     {
                               using ( mySiteWeb = site.OpenWeb())
                                {
                                    site.AllowUnsafeUpdates = true;
                                    mySiteWeb.AllowUnsafeUpdates = true;
                                    SPWeb webi = site.RootWeb;
                ProfileImagePicker profileImagePicker = new ProfileImagePicker();
                profileImagePicker.FolderName = "Profile Pictures";
                InitializeProfileImagePicker(profileImagePicker, mySiteWeb);
                subfolderForPictures = GetSubfolderForPictures(profileImagePicker);
                accountNameForFileName = (accountName.StartsWith("i:0#.f") == true ?
                accountName.Substring(accountName.LastIndexOf('|') + 1, (accountName.Length - (accountName.LastIndexOf('|') + 1))) :
                    accountName);
                UploadPhoto(accountNameForFileName, bytImgProfile, subfolderForPictures, profileImagePicker);
               
                                }
                            }
                        });
              return SetPictureUrl(accountName, accountNameForFileName, subfolderForPictures, out pictureUrl);
           
                   

  }

 private bool SetPictureUrl(string accountName, string accountNameForFileName, SPFolder subfolderForPictures, out string pictureUrl)
   {
           SPSite site = subfolderForPictures.ParentWeb.Site;
            //code comment by tayyab
            //clsProfileGeneral objProf = new clsProfileGeneral();
            //UserProfile user = objProf.getUserProfile(string.Empty, accountName, true, true);

            string fileNameWithoutExtension = GetFileNameFromAccountName(accountNameForFileName);
            pictureUrl = String.Format("{0}/{1}/{2}_MThumb.jpg", site.Url, subfolderForPictures.Url, fileNameWithoutExtension);
            return true;

 }


 private void UploadPhoto(string accountName, byte[] buffer, SPFolder subfolderForPictures, ProfileImagePicker profileImagePicker)
 {
           
                 string fileNameWithoutExtension = GetFileNameFromAccountName(accountName);

                 if (subfolderForPictures != null)
                 {
                   
                     int mediumThumbnailSize = 0x60;
                     int smallThumbnailSize = 0x20;
                     int largeThumbnailSize = 0x90;
         
                     using (MemoryStream stream = new MemoryStream(buffer))
                     {
                         using (Bitmap bitmap = new Bitmap(stream, true))
                         {
                             //CreateThumbnail(bitmap, smallThumbnailSize, smallThumbnailSize, subfolderForPictures, fileNameWithoutExtension + "_SThumb.jpg");
                             //CreateThumbnail(bitmap, largeThumbnailSize, largeThumbnailSize, subfolderForPictures, fileNameWithoutExtension + "_LThumb.jpg");
                             CreateThumbnail(bitmap, mediumThumbnailSize, mediumThumbnailSize, subfolderForPictures, fileNameWithoutExtension + "_MThumb.jpg");

                         }
                     }

                 }
             //}
  }
private void InitializeProfileImagePicker(ProfileImagePicker profileImagePicker, SPWeb web)
{
             Type profileImagePickerType = typeof(ProfileImagePicker);
             profileImagePicker.FolderName = "Profile Pictures";
             FieldInfo fi_m_objWeb = profileImagePickerType.GetField("m_objWeb", BindingFlags.NonPublic | BindingFlags.Instance);
             fi_m_objWeb.SetValue(profileImagePicker, web);

             MethodInfo mi_LoadPictureLibraryInternal = profileImagePickerType.GetMethod("LoadPictureLibraryInternal", BindingFlags.NonPublic | BindingFlags.Instance);
             if (mi_LoadPictureLibraryInternal != null)
             {
                 mi_LoadPictureLibraryInternal.Invoke(profileImagePicker, new object[] { });
             }
  }


 private SPFile CreateThumbnail(Bitmap original, int idealWidth, int idealHeight, SPFolder folder, string fileName)
{
             SPFile file = null;
             // hack to get the Microsoft.Office.Server.UserProfiles assembly
             Assembly userProfilesAssembly = typeof(Microsoft.Office.Server.UserProfiles.UserProfile).Assembly;
             // or assuming you know all the details of the assembly
             // Assembly userProfilesAssembly = Assembly.Load(“Microsoft.Office.Server.UserProfiles, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c”);

            // UserProfilePhotos is internal class,
            // so you cannot get it directly from Visual Studio            
             Type userProfilePhotosType = userProfilesAssembly.GetType("Microsoft.Office.Server.UserProfiles.UserProfilePhotos");
              MethodInfo mi_CreateThumbnail = userProfilePhotosType.GetMethod("CreateThumbnail", BindingFlags.NonPublic | BindingFlags.Static);
             if (mi_CreateThumbnail != null)
             {
                 file = (SPFile)mi_CreateThumbnail.Invoke(null, new object[] { original, idealWidth, idealHeight, folder, fileName });
             }
              return file;
}

private SPFolder GetSubfolderForPictures(ProfileImagePicker profileImagePicker)
{
             SPFolder folder = null;
             Type profileImagePickerType = typeof(ProfileImagePicker);
             MethodInfo mi_GetSubfolderForPictures = profileImagePickerType.GetMethod("GetSubfolderForPictures", BindingFlags.NonPublic | BindingFlags.Instance);
            ParameterInfo[] obj = mi_GetSubfolderForPictures.GetParameters();
           if (mi_GetSubfolderForPictures != null)
             {
                 folder = (SPFolder)mi_GetSubfolderForPictures.Invoke(profileImagePicker, new object[]{ false} );
             }
              return folder;
}
private string GetFileNameFromAccountName(string accountName)
 {
            string result = accountName;
            string charsToReplace = @"\/:*?""<>|";
            Array.ForEach(charsToReplace.ToCharArray(), charToReplace => result = result.Replace(charToReplace, '_'));
            return result;
  }