Second Life of a Hungarian SharePoint Geek

March 10, 2010

95 Comments »

  1. This is amazing! It saved me a lot of time!

    one minor issue: the compiler says “ProfileImagePicker.LargeThumbnailSize” is not defined, so I specified the number directly.

    //64×64 small
    //96×96 medium
    //128×128 large

    Comment by Eric Fang — May 30, 2010 @ 11:14

    • Hi Eric,

      Thanks for the comment. In the final version of SP 2010 the properties that reflect the thumbnail sizes are the members of the internal static class UserProfilePhotos, so it really not so simple to reference them from the code.

      The size can be defined as (see the static constructor of the UserProfilePhotos class):
      largeThumbnailSize = 0x90;
      mediumThumbnailSize = 0x60;
      smallThumbnailSize = 0x20;

      Peter

      Comment by pholpar — June 4, 2010 @ 22:09

      • Hi Pholpar,

        One issue I am facing while creating Larg thumbnail.
        I have used size as,
        144 x 144 px , 96 x 96 px and 32 x 32 pxfor Large,medium and small images resp. But for few images i am not able to create large size image.
        It says ,”Exception has been thrown by the target of an invocation.”
        I tried reducing the size of image and for 124 x 124 px it is working fine.
        I have tried using size mentioned by you i.e. 96 x 96 , 60 x 60 and 20 x 20 this is working fine ,but images are too small with this .
        Your help is appreciated.

        Comment by SharepointTeam — November 16, 2010 @ 10:19

  2. For RTM I had to change the code to:

    Assembly a = Assembly.Load(“Microsoft.Office.Server.UserProfiles, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c”);

    Type userProfilePhotos = a.GetType(“Microsoft.Office.Server.UserProfiles.UserProfilePhotos”);

    MethodInfo mi_CreateThumbnail = userProfilePhotos.GetMethod(“CreateThumbnail”, BindingFlags.NonPublic | BindingFlags.Static);

    Regards,
    Frode

    Comment by Frode Sorhoy — June 3, 2010 @ 12:48

    • Hi Frode,

      Thanks for the comment! I was to update my code but I see you were quicker.

      Peter

      Comment by pholpar — June 4, 2010 @ 21:46

    • Frode, you are legend!

      Comment by Eric Fang — June 5, 2010 @ 00:25

  3. Hi Frode,

    This is good when you only need to upload pictures for one to a handful of users but I don’t see this being much of an option if like me you need to upload pictures for up to 5,000 users.

    Good work though!

    Comment by Larry — June 8, 2010 @ 06:36

    • Hi Larry,

      Although you addressed Frode in your comment I feel myself to be addressed because the original code “belongs” to me. I don’t see why can’t you use the code to upload images for even several thousands of users using the same method. You should iterate through the users as indicated with the comments in the UploadProfileImages method. Of course, it requires more time than uploading only a few photos, but AFAIK there is no OOB way of batch uploading photos.

      Another alternative might be you prepare the photos in all required size for all of your users and upload the photos directly to the user photos folder of the my site host of SharePoint.

      Peter

      Comment by pholpar — June 8, 2010 @ 07:02

  4. Hi Pholpar,
    I am facing an issue with this.
    I am able to upload picture to Profile Pictures library with above mentined code but i m not able to see them in My Profile where it shud get updated.
    Please help me out

    Comment by SharepointTeam — June 10, 2010 @ 12:59

    • Hi,

      The code in this post really does (or did, to be exact) nothing more than the title says: upload the photo (including the built-in rename and resize functionality) to the User Photos image library of the My Site Host site.

      To include the image in the profile, one should set the PictureUrl property of the user profile to the URL of the uploaded image. Since it is a common requirement, I’ve updated the code in the post with the SetPictureUrl method that does exactly that.

      Peter

      Comment by pholpar — June 10, 2010 @ 15:35

  5. Thanks Peter.Its working fine.

    Comment by SharepointTeam — June 11, 2010 @ 05:23

  6. everything goes fine until this line:

    UserProfileManager userProfileManager = new UserProfileManager(SPServiceContext.GetContext(site));

    where I get this:

    Microsoft.Office.Server.UserProfiles.UserProfileApplicationNotAvailableException was unhandled
    Message=No User Profile Application available to service the request. Contact your farm administrator.
    Source=Microsoft.Office.Server.UserProfiles
    StackTrace:
    at Microsoft.Office.Server.Administration.UserProfileApplicationProxy.get_ApplicationProperties()
    at Microsoft.Office.Server.Administration.UserProfileApplicationProxy.CheckAdministrationAccess(UserProfileApplicationAdminRights rights, Boolean requireAllRights)
    at Microsoft.Office.Server.Administration.UserProfileApplicationProxy.CheckAdministrationAccess(UserProfileApplicationAdminRights rights)
    at Microsoft.Office.Server.UserProfiles.ProfileManagerBase.CanManagePeople(UserProfileApplicationProxy userProfileApplicationProxy)
    at Microsoft.Office.Server.UserProfiles.ProfileManagerBase.get_IsProfileAdmin()
    at Microsoft.Office.Server.UserProfiles.UserProfileManager..ctor(SPServiceContext serviceContext, Boolean IgnoreUserPrivacy, Boolean backwardCompatible)
    at Microsoft.Office.Server.UserProfiles.UserProfileManager..ctor(SPServiceContext serviceContext)
    at UploadProfileImage.Program.SetPictureUrl(String accountName, SPFolder subfolderForPictures) in C:\Users\greg.admin\documents\visual studio 2010\Projects\SharePointPhotoUpload\SharePointPhotoUpload\Program.cs:line 55
    at UploadProfileImage.Program.UploadProfileImages() in C:\Users\greg.admin\documents\visual studio 2010\Projects\SharePointPhotoUpload\SharePointPhotoUpload\Program.cs:line 41
    at UploadProfileImage.Program.Main(String[] args) in C:\Users\greg.admin\documents\visual studio 2010\Projects\SharePointPhotoUpload\SharePointPhotoUpload\Program.cs:line 18
    at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
    at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
    at System.Threading.ThreadHelper.ThreadStart()
    InnerException:

    The photo upload works perfectly I can browse to the list on my sites host and see the 3 photos there! Any idea why this error is occurring have I configured my users profiles wrongly?

    Comment by Greg — June 28, 2010 @ 23:00

  7. Thanks for the post.

    MethodInfo mi_LoadPictureLibraryInternal = profileImagePickerType.GetMethod(“LoadPictureLibraryInternal”, BindingFlags.NonPublic | BindingFlags.Instance);
    doesn’t work for me.
    Can you suggest some solution for this?

    Comment by Ritu — July 2, 2010 @ 11:27

    • Hmmm. It should work. What SharePoint version do you use? SP 2010 RTM? What do you mean it does not work? Does it throw an exception, does it return null or something else?

      Peter

      Comment by pholpar — July 3, 2010 @ 07:30

  8. Hi Peter,

    I am using SP2010. The function returns null.

    Ritu

    Comment by Ritu — July 5, 2010 @ 06:23

  9. HI ,
    i m facing an issue when I ran this code for timer job.
    timer job ,runs on daily basis to upload images.
    But the problem is ,though I set picture property to medium size ,internally timer job sets that propery to http://server/my/User%20Photos/Profile%20Pictures/%E2%80%8Bus_first.last_LThumb.jpg.
    Here I dont know how it is addding internally the character sequence “/%E2%80%8B” to the URL.My timer service runs with admin credential.I tried running with console application it is running fine for that.
    Please help me out for this.

    Comment by SharepointTeam — July 19, 2010 @ 12:17

  10. And I m using SP2010 realesed 14.0.4763.1000 version

    Comment by SharepointTeam — July 19, 2010 @ 13:28

  11. my sync with AD is working fine except it is not pulling the pictures in the AD.

    Here is my issue, we have photos of all employees stored as xyz.jpg in the custom attribute (emp_pics_2001) with type string, but the picture url type is url (is this the culprit type change), I am using the custom attribute to map the field in the Sharepoint 2010 miis client.

    I am using the below url to do the set up: http://goodbadtechnology.blogspot.com/2010/05/setting-up-pictureurl-user-profile.html

    i did check the profile db picture url field is NULL, i have all the other values for person except the picture.. , I have already wasted more than 2 days in figuring this out

    If i just get xyz.jpg pulled to sharepoint, then i can prefix a url in front of it using powershell

    I am using a full trusted service account with full permissions to the domain

    please help me out..

    thank you

    Neel

    Comment by Neel — July 19, 2010 @ 18:12

    • Hi Neel,

      My post has nothing to do with AD synchronization. I suggest you to consult with the author of the post you refer to. As I see you’ve already posted a comment there.

      Peter

      Comment by pholpar — July 20, 2010 @ 16:28

  12. Have the same problem that

    MethodInfo mi_CreateThumbnail = userProfilePhotos.GetMethod(“CreateThumbnail”, BindingFlags.NonPublic | BindingFlags.Static);

    returns NullReference exception;

    I use RTM version of SPS2010

    Comment by Chris Chmielewski — July 20, 2010 @ 14:58

    • Hi Chris,

      What is the version number of your Microsoft.Office.Server.UserProfiles.dll assembly? In my environment it is 14.0.4756.1000.

      Peter

      Comment by pholpar — July 20, 2010 @ 16:24

  13. Hi Peter,

    Yes I have the same version 14.0.4756.1000. I will check if that program works on another 3 environments and will give you the result.

    Chris

    Comment by Chris Chmielewski — July 21, 2010 @ 08:12

    • Chris,

      If MethodInfo mi_CreateThumbnail = userProfilePhotosType.GetMethod(“CreateThumbnail”, BindingFlags.NonPublic | BindingFlags.Static); throws NullReferenceException it means the userProfilePhotos should be null. Verify that please.

      (BTW, you wrote userProfilePhotos instead of userProfilePhotosType but I assume you meant this line of code.)

      If it is the case, then check the content of the Microsoft.Office.Server.UserProfiles.dll assembly using Reflector to verify the “missing” method (Microsoft.Office.Server.UserProfiles.UserProfilePhotos.CreateThumbnail) is there.

      Peter

      Comment by pholpar — July 21, 2010 @ 09:50

  14. Ok,

    I have checked the program on one more enviroment that I installed and it works great :). I think it could be the configuration of the server and wrong assemblies issue.

    It’s not my server so I can’t make more test why it does not work.

    Chris

    Comment by Chris Chmielewski — July 21, 2010 @ 10:01

  15. […] was a bit more: to synchronize the image binary as well, not only URLs. As I’ve already created tools to upload user photos from file system to SharePoint profile programmatically I thought it would be nice to reuse that […]

    Pingback by Synchronizing user image between Active Directory and SharePoint profile « Second Life of a Hungarian SharePoint Geek — August 10, 2010 @ 01:30

  16. Hi Pholpar,

    I don’t have any “/profiles/host” on my Sharepoint mysite, and so the method

    folder = (SPFolder)mi_GetSubfolderForPictures.Invoke(….)

    just returns null. What am I missing?

    Comment by Skywise — September 16, 2010 @ 13:31

    • Hi Skywise,

      The code example assumes you have the user profile service activated on you SharePoint server, and you have created a my site host site at the specific URL. If you have the my site host at a different URL, just replace that into the code. It is important to note that it is not the URL of the my site, but the parent site that hosts all of the my sites.

      See my other post that includes a code to get that URL:
      Getting the My Site host URL from code

      You can read more about user profile service here:
      User Profile service overview (SharePoint Server 2010)
      Configuring the User Profile Service in SharePoint 2010

      Hope it helps.

      Peter

      Comment by pholpar — September 16, 2010 @ 13:53

      • Thanks for the quick reply.

        My MySite web application is located at http://devoslmysite.mydomain.com/, and when running the “Getting the Mysite host URL from code” code, it returns http://devoslmysite.mydomain.com:80/

        But I have nothing at http://devoslmysite.mydomain.com/profiles/hosts

        I do have the User Profile service enabled, and I do have Full control to it..

        Comment by Skywise — September 16, 2010 @ 17:06

      • Hi Skywise,

        Then it means you have a dedicated SharePoint application having its own FQDN for my site host and not a site collection root as a subsite as in my example. It means your my site host URL is http://devoslmysite.mydomain.com. Try to use simply that URL.

        Peter

        Comment by pholpar — September 16, 2010 @ 17:40

      • Damn, now it works. That was indeed the first thing I tried, but at the same time I had forgotten to grant myself access to the user profile service. And after I fixed that, I obviously forgot to test with the http://devoslmysite.mydomain.com address… >.<
        Sorry for wasting you time

        Comment by Skywise — September 17, 2010 @ 07:55

      • No problem. It’s great that the feature works now. I had also issues with the permissions at the first time I worked with user profiles from code, and at former installations I’ve also used dedicated web applications for the My site feature, but later got used to integrate it into an existing web application as a sub site collection root.

        Peter

        Comment by pholpar — September 17, 2010 @ 08:15

  17. on this line of code i get an “Exception has been thrown by the target of an invocation.”
    mi_LoadPictureLibraryInternal.Invoke(profileImagePicker, new object[]
    { });

    what could this mean

    Comment by Meyers — September 22, 2010 @ 18:10

    • the InnerException = {“The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again.”} is this.

      Comment by Meyers — September 22, 2010 @ 18:16

      • Hi,

        Do you use the original code from command line or have modified anything?

        Peter

        Comment by Peter Holpar — September 22, 2010 @ 18:22

  18. use the original code. only replaced the mysite url .

    Comment by Meyers — September 22, 2010 @ 19:04

  19. When i moved the wsp file to the main sharepoint portal i get that the temp.jpg does not exist or has invalid extension. This code works just fine on my vm. the jpg is located on the local drive of the sharepoint server. any suggestions.

    Comment by Meyers — September 24, 2010 @ 17:12

    • Hi Meyers,

      What kind of WSP file do you mean? As written above, the code in this post is a console application (x64, .NET Framework 3.5) and is intended to be used as an .EXE file.

      Peter

      Comment by Peter Holpar — September 24, 2010 @ 17:31

      • i created as a asp.net page and installed as a package on the server. runs great from my local vm sharepoint but get file access error when running from the normal sharepoint site.

        Comment by Meyers — September 24, 2010 @ 18:12

  20. […] SharePoint 2010 User Profile Images Posted on October 2, 2010 by jlinssen This blog describes code that you can use to upload a collection of images from a directory to the SharePoint 2010 MySite Host and also set the pictureURL to the right location. The code is based on the code from : https://pholpar.wordpress.com/2010/03/10/how-to-upload-a-user-profile-photo-programmatically/ […]

    Pingback by SharePoint 2010 User Profile Images | Jack's space — October 2, 2010 @ 15:18

  21. Thanks for this. You are a genius and should receive a gold medal or something…

    Comment by Sebas — October 26, 2010 @ 16:12

  22. Hi Pholpar – Thank you posting your code. I can access the User Profile Photos at http://my/User%20Photos/Forms/AllItems.aspx on my Sharepoint server with no issues and confirmed that I am able to upload files.

    I modified your code so that String url = “http://sp2010/profiles/host”;
    is now String url = “http://my”. However, when I run the executable on my Sharepoint server I receive the error:

    C:\Head Shots>UploadProfileImage.exe

    Unhandled Exception: System.IO.FileNotFoundException: The Web application at http://my could not be found. Verify that you hav
    e typed the URL correctly. If the URL should be serving existing content, the sy
    stem administrator may need to add a new request URL mapping to the intended app
    lication.
    at Microsoft.SharePoint.SPSite..ctor(SPFarm farm, Uri requestUri, Boolean con
    textSite, SPUserToken userToken)
    at Microsoft.SharePoint.SPSite..ctor(String requestUrl)
    at UploadProfileImage.Program.UploadProfileImages()
    at UploadProfileImage.Program.Main(String[] args)

    Any thoughts? I appreciate your help.

    Mike

    Comment by Mike — October 28, 2010 @ 19:58

  23. Thank you, this helped me out a lot.

    Comment by Sigge — October 29, 2010 @ 13:13

  24. Hi Pholpar,

    One issue I am facing while creating Larg thumbnail.
    I have used size as,
    144 x 144 px , 96 x 96 px and 32 x 32 pxfor Large,medium and small images resp. But for few images i am not able to create large size image.
    It says ,”Exception has been thrown by the target of an invocation.”
    I tried reducing the size of image and for 124 x 124 px it is working fine.
    I have tried using size mentioned by you i.e. 96 x 96 , 60 x 60 and 20 x 20 this is working fine ,but images are too small with this .
    Your help is appreciated.

    Comment by SharepointTeam — November 19, 2010 @ 10:18

  25. Can this be done from a winform app? The app runs but on this line: file = (SPFile)mi_CreateThumbnail.Invoke(null, new object[] { original, idealWidth, idealHeight, folder, fileName });

    I get this error:
    Exception has been thrown by the target of an invocation.
    Source mscorlib

    InnerException: 0x80070005Access denied.

    at Microsoft.SharePoint.SPFileCollection.AddStreamOrBytesInternal(String urlOfFile, Stream file, PutFileOpt fileOpt, String createdBy, String modifiedBy, Int32 createdByID, Int32 modifiedByID, DateTime timeCreated, DateTime timeLastModified, Object varProperties, String checkInComment, Stream formatMetadata, String lockIdMatch, String etagToMatch, SPLockType lockType, String lockId, TimeSpan lockTimeout, Boolean validateRequiredFields, SPVirusCheckStatus& virusCheckStatus, String& virusCheckMessage, String& etagNew, Boolean& ignoredRequiredProps)
    at Microsoft.SharePoint.SPFileCollection.Add(String urlOfFile, Stream file, Boolean overwrite, String checkInComment, Boolean checkRequiredFields)
    at Microsoft.SharePoint.SPFileCollection.Add(String urlOfFile, Stream file, Boolean overwrite)
    at Microsoft.Office.Server.UserProfiles.UserProfilePhotos.CreateThumbnail(Bitmap original, Int32 idealWidth, Int32 idealHeight, SPFolder folder, String fileName)

    I am a site collection admin.

    Comment by CMD — December 1, 2010 @ 00:29

    • Should Add:

      Server 2008 x64
      Application is compiled for x64
      Sharepoint 2010
      I’ve made myself an admin for the User Profile Service Application

      Comment by CMD — December 1, 2010 @ 01:15

      • Hi CMD,

        The same method should work from a WinForm application as well. Be sure you have adequate rights on the My Site Host site (and access to the file in the file system, of course).

        Peter

        Comment by Peter Holpar — December 2, 2010 @ 22:08

      • I do have permissions. I’ve validated that the process is executing as me and I am a site collection administrator and an admin on the profile service in SP not to mention a Domain Admin. I can retrieve the file fine from the network too. I can also update other properties like DOB, FAX, etc on user profiles but when I try and Invoke “CreateThumbnail” I get this error:

        System.Reflection.TargetInvocationException was unhandled by user code
        Message=”Exception has been thrown by the target of an invocation.”
        Source=”mscorlib”
        StackTrace:
        at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
        at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
        at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
        at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
        at CTSharePointEx.Service1.CreateThumbnail(Bitmap original, Int32 idealWidth, Int32 idealHeight, SPFolder folder, String fileName) in C:\Users\me\Documents\Visual Studio 2008\Projects\UpdateADProperties\CTSharePointEx\Service1.svc.cs:line 210
        at CTSharePointEx.Service1.UploadPhoto(String accountName, String imageFilePath, SPFolder subfolderForPictures, ProfileImagePicker profileImagePicker) in C:\Users\chris.duden\Documents\Visual Studio 2008\Projects\UpdateADProperties\CTSharePointEx\Service1.svc.cs:line 159
        at CTSharePointEx.Service1.c__DisplayClass6.b__4() in C:\Users\me\Documents\Visual Studio 2008\Projects\UpdateADProperties\CTSharePointEx\Service1.svc.cs:line 99
        at Microsoft.SharePoint.SPSecurity.c__DisplayClass4.b__2()
        at Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRunElevated secureCode)
        InnerException: System.UnauthorizedAccessException
        Message=”0x80070005Access denied.”
        Source=””
        StackTrace:
        at Microsoft.SharePoint.SPFileCollection.AddStreamOrBytesInternal(String urlOfFile, Stream file, PutFileOpt fileOpt, String createdBy, String modifiedBy, Int32 createdByID, Int32 modifiedByID, DateTime timeCreated, DateTime timeLastModified, Object varProperties, String checkInComment, Stream formatMetadata, String lockIdMatch, String etagToMatch, SPLockType lockType, String lockId, TimeSpan lockTimeout, Boolean validateRequiredFields, SPVirusCheckStatus& virusCheckStatus, String& virusCheckMessage, String& etagNew, Boolean& ignoredRequiredProps)
        at Microsoft.SharePoint.SPFileCollection.Add(String urlOfFile, Stream file, Boolean overwrite, String checkInComment, Boolean checkRequiredFields)
        at Microsoft.SharePoint.SPFileCollection.Add(String urlOfFile, Stream file, Boolean overwrite)
        at Microsoft.Office.Server.UserProfiles.UserProfilePhotos.CreateThumbnail(Bitmap original, Int32 idealWidth, Int32 idealHeight, SPFolder folder, String fileName)
        InnerException:

        I’ve moved the call to a WCF service and tried it from there with the same result… I’m not sure what other permissions I need… I am EVERYTHING LOL.

        Any ideas?

        Comment by CMD — December 3, 2010 @ 01:32

      • I figured it out. The account the process is running under must be a site collection administrator for the MYSITE site collection in order for this to work.

        Comment by CMD — December 4, 2010 @ 00:10

      • Hi CMD,

        It’s nice to know that the code is working for you. The solution sounds pretty similar to my original suggestion: “Be sure you have adequate rights on the My Site Host site”. You wrote in your previous comment that you’ve validated the process is executing with your credentials, and you do have permissions. It sounds you had not enough permission.

        Setting other properties (like FAX) modify the user profile database, however uploading a user image takes place in a dedicated document library on the My Site Host, so it requires extra permissions.

        Peter

        Comment by Peter Holpar — December 4, 2010 @ 00:28

  26. Hi Pholpar,

    I noticed a bug in the behaviour: Let’s say a person has a profile image for a while, posting updates and working normally. Then, he removes his image, and this code deletes all three image resolutions from the DB. Then he posts some more updates etc.

    My problem is: The sharepoint activity databases (?) still contains references to his old profile image (SThumb) for the old status updates and other changes he did while having an image. For all updates he does after the image has been removed, he gets the standard silhouette image.

    Have you seen this problem?

    The old updates referencing the now non-existing SThumb show the classic image missing X, as seen in this screen shot:

    Tips highly appreciated 🙂

    Comment by Skywise — December 17, 2010 @ 09:25

    • Not seen this problem? Anyone else?

      Comment by Skywise — January 3, 2011 @ 10:14

  27. I have written an app to do this from the desktop rather than the server
    http://spc3.codeplex.com/wikipage?title=ProfileImageUpload

    Comment by djeeg — January 20, 2011 @ 13:08

  28. This worked great in our test environment without a hitch, however is not working in prod. The sub folder for the images is coming back as null. Any thoughts as to why, or what to look for?

    Comment by Marc Johnson — May 3, 2011 @ 13:04

    • Hi Marc,

      Unfortunately, similar issues were already reported, see my former conversation with Chris Chmielewski above. Seems to be some configuration / assembly version issue. I would add a trace line (Console.WriteLine or similar) inside the if (mi_GetSubfolderForPictures != null) condition in GetSubfolderForPictures method to check whether the MethodInfo is retrieved successfully. If not, there should be something wrong with the assembly, check for the GetSubfolderForPictures method of the ProfileImagePicker type.

      Hope it helps.

      Peter

      Comment by Peter Holpar — May 6, 2011 @ 07:51

  29. Hi all,

    This works well for me, but I’ve run into an issue when I’ve deployed this in a web app. I access this code using WCF, and it works fine for my account (I am a site collection admin), however I get a ThreadAbortException when accessed via a lower privileged account. (I have the service account that is running my app as a site collection admin as well)

    I have tried executing the code using SPSecurity.RunWithElevatedPrivileges and tried using (WindowsImpersonationContext wic = WindowsIdentity.Impersonate(IntPtr.Zero)) { …

    but neither changed the behavior.

    This feels like a permissions issue, but I don’t know how permissions affect (or if it’s possible) reflection.

    Thanks!
    -Andy

    System.Threading.ThreadAbortException: Thread was being aborted.
    at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
    at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
    at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
    at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
    at MyAssembly.UserProfiles.UserProfileImageUploader.CreateThumbnail(Bitmap original, Int32 idealWidth, Int32 idealHeight, SPFolder folder, String fileName)
    at MyAssembly.UserProfiles.UserProfileImageUploader.UploadPhoto(String accountName, Byte[] imageBytes, SPFolder subfolderForPictures)
    at MyAssembly.UserProfiles.UserProfileImageUploader.UploadProfileImages(String accountName, Byte[] imageBytes)

    Comment by Andy — June 10, 2011 @ 17:47

    • Fix: This was a permissions issue. I had to give Contribute rights to users of the Profile Pictures folder.

      Comment by Andy — June 10, 2011 @ 20:47

  30. Did you try your solution with Service Pack 1? In my environment it doesn’t work with SP1.

    Comment by Pavel — July 1, 2011 @ 14:13

    • Hi Pavel,

      Thanks for the information, I’ve not tried that yet. Bad news, there were changes in the internal methods from beta 2 to RTM too, soo it is possible that I should alter the code for SP1.

      Peter

      Comment by Peter Holpar — July 1, 2011 @ 18:44

  31. Hi

    i am using the code you have described here, however i am facing a weird issue. The Mthumnail and SThumnail get propely uploaded however the LThumnail I can see in the library since its coming from /_t or /w subfolder but it shows a X mark when I eventually navigate to the file.

    Its the same behaviour if i set the picture manually using the edid profile link. Any help would be appreciated..

    Comment by Vaibhav upadhyay — August 12, 2011 @ 20:38

  32. I got it!! Its a problem with the image if you are using an image which does not scale, it just shows you a cross X.

    Comment by Vaibhav upadhyay — August 12, 2011 @ 20:43

  33. Pholpar,

    Thanks for sharing. We’ve been having a lot of difficulties getting into and staying in the CA User Profile Editor. Looking at using this as a substitute for HR to manage user photos.

    Your provided code has a typo: when specifying the thumbnail sizes, the ‘x’ has somehow changed to a multiplication sign.

    —PaulE—

    Comment by PaulE — September 19, 2011 @ 18:41

    • Hi Paul,

      Thanks for you feedback! Unfortunately the blog engine makes sometimes this kind of “auto-correction” and I have not found how to turn it off.

      Peter

      Comment by Peter Holpar — September 19, 2011 @ 19:58

  34. Thanks for the post.

    Running into a parameter count mismatch exception when the script gets to this line in GetSubfolderForPictures method:
    folder = (SPFolder)mi_GetSubfolderForPictures.Invoke(profileImagePicker, new object[] { });

    Any idea what might be causing this ?

    Thanks again,
    Tom

    Comment by Tom H — September 20, 2011 @ 20:26

    • Hi Tom,

      You might have SP1 installed and the code was not tested with that. Other comments already complained about that, but unfortunately I had no time yet to “upgrade” this solution. Could you write the exact exception / inner exception?

      Peter

      Comment by Peter Holpar — September 20, 2011 @ 21:02

    • For SP1, there’s a few changes to work around. First, GetSubfolderForPictures now requires a boolean parameter. Calling with ‘false’ is a good idea since, otherwise, the method will attempt to create a folder you should already have. As follows:

      folder = (SPFolder)mi_GetSubfolderForPictures.Invoke(profileImagePicker, new object[] { false });

      Worse yet, though, is that GetSubfolderForPictures incorrectly evaluates profileImagePicker.FolderName. I doesn’t handle the case where FolderName is null and incorrectly assumes it won’t be. Thus, the try/catch block fails to the catch which then returns null when you pass in ‘false’ for createIfMissing. But, of course, you don’t want to create because it’s not really missing.

      I got around this by modifying my GetSubfolderForPictures(ProfileImagePicker) method as follows:

      private SPFolder GetSubfolderForPictures(ProfileImagePicker profileImagePicker)
      {
      Type profileImagePickerType = typeof(ProfileImagePicker);
      SPList objPicLib = null;
      System.Reflection.FieldInfo mi_objPicLib = profileImagePickerType.GetField(“m_objPicLib”, BindingFlags.NonPublic | BindingFlags.Instance);
      if (mi_objPicLib != null)
      {
      objPicLib = (SPList)mi_objPicLib.GetValue(profileImagePicker);
      }
      return objPicLib.RootFolder;
      }

      —PaulE—

      Comment by PaulE — September 26, 2011 @ 18:36

      • Paul, I really appreciate your investigation on the subject and sharing the results with us!

        Peter

        Comment by Peter Holpar — September 26, 2011 @ 18:50

      • Object reference not set to an instance of an object error while “objPicLib = (SPList)mi_objPicLib.GetValue(profileImagePicker);” line execution. Please help me!!!!!!!

        Comment by Buddha — September 28, 2011 @ 12:50

      • Hi Buddha,

        Again, you might have SP1 installed and the code was not tested with that. See the altered code version sent by Paul above. Hope it helps.

        Peter

        Comment by Peter Holpar — September 28, 2011 @ 13:12

      • Thanx a lot! Works perfect! Running SP 1 and August 2011 CU.

        Comment by Frode — October 26, 2011 @ 12:28

  35. Thanks for your reply Peter.
    I tried with that only, still getting an error in ‘objPicLib = (SPList)mi_objPicLib.GetValue(profileImagePicker)’ line of PaulE’s code.

    Please help me to solve this issue.
    Thanks in advance.

    Comment by Buddha — September 28, 2011 @ 14:23

    • Do you have SP1 installed? If not, have you tried the original code? Which version of SharePoint do you have (including language info)?

      Comment by Peter Holpar — September 28, 2011 @ 14:40

      • Hi Peter,

        Yes I have SP1 and version is 14.0.6029.1000…

        Please help me..

        Comment by Buddha — September 28, 2011 @ 15:02

    • Don’t forget to initialize the profileImagePicker first. Peter’s InitializeProfileImagePicker(ProfileImagePicker) method does this nicely.

      Comment by PaulE — September 28, 2011 @ 17:18

  36. Hi Peter,

    Yes I have installed SP1 (i.e. Microsoft SharePoint 2010 Service Pack 1 (SP1) ).

    First i tried the original code then I got an error same as Tom H’s then I tried the modified code. still getting the error explained above.

    So please help me in solving this issue.
    Thanks,
    Buddha

    Comment by Buddha — September 28, 2011 @ 14:49

  37. Could you please update on Buddha’s issue? I am also facing the same issue.

    Comment by Swati — September 29, 2011 @ 12:04

  38. Hi Paul and Peter i too get the same error as Buddha,,
    your help would be appreciated

    Comment by kulkarni — October 3, 2011 @ 14:27

  39. hi
    i am getting an error in the following line
    file = (SPFile)mi_CreateThumbnail.Invoke(null, new object[] { original, idealWidth, idealHeight, folder, fileName });

    error message

    Exception has been thrown by the target of an invocation.

    can you kindly let us know what is the issue

    Comment by venkat — October 13, 2011 @ 15:17

    • Hi,

      I suggest you to debug your application and see the InnerException property of the exception thrown. You can check the SharePoint logs as well to see if there is something unexpected.

      Peter

      Comment by Peter Holpar — October 13, 2011 @ 15:51

    • Increase mysite qouta limit. That will solve the problem.

      Comment by Markus — October 19, 2011 @ 08:14

  40. Hi Peter,

    Thanks for a brilliant post – I was wondering how to achieve this the other day and this came up on my first google search :-).

    I got the same error as venkat above but after some investigation I found I had not set the thumbnail sizes correctly.

    int largeThumbnailSize = 0×90 – I had used a star instead of the x(times) symbol – silly me!

    After I fixed this it worked perfectly – I will definitely be bookmarking this link for the future.

    Cheers

    Alex

    Comment by Alex Clark (@sharepointalex) — October 19, 2011 @ 02:34

  41. Could you please update on Buddha’s issue? I am also facing the same issue.

    Comment by kulkarni — October 20, 2011 @ 10:29

  42. folder = (SPFolder)mi_GetSubfolderForPictures.Invoke(profileImagePicker, new object[] { });

    I am gettng “Parameter count mismatch.” Error. When I look at the profileImagePicker

    IsSuccessfulSave ‘profileImagePicker.IsSuccessfulSave’ threw an exception of type ‘System.NullReferenceException’ bool {System.NullReferenceException}

    but m_objPicLib {User Photos} Microsoft.SharePoint.SPList {Microsoft.SharePoint.SPPictureLibrary}

    So It looks to me the picture library got set right.

    I try to send true or false to

    folder = (SPFolder)mi_GetSubfolderForPictures.Invoke(profileImagePicker, new object[] { true });

    but Always I get null returned I checked my site host it looked right.

    No Idea why It is not allowing me I dont know where to give what rights to the user but I am using farm admin so It should work

    Thanks In advance for your help

    Comment by Samy — October 27, 2011 @ 15:17

  43. Here is the working code if you are using latest version of SP2010

    Thanks for all the help guys

    Type profileImagePickerType = typeof(ProfileImagePicker);

    SPList objPicLib = null;

    SPFolder folder = null;

    FieldInfo mi_objPicLib = profileImagePickerType.GetField(“m_objPicLib”, BindingFlags.NonPublic | BindingFlags.Instance);

    if (mi_objPicLib != null)
    {
    objPicLib = (SPList)mi_objPicLib.GetValue(profileImagePicker);
    }

    foreach (SPFolder subFolder in objPicLib.RootFolder.SubFolders)
    {
    if (subFolder.Name == “Profile Pictures”)
    {
    folder = subFolder;
    }
    }

    if (folder == null)
    {
    folder = objPicLib.RootFolder.SubFolders.Add(“Profile Pictures”);
    }
    return folder;

    Comment by Samy — October 27, 2011 @ 16:33

  44. Hi
    Good content, It helped me alot… but I’m still struggling with problem when deleting user profiles picture.

    I tried this code :

    theProfile[“PictureUrl”].Clear();
    theProfile.Commit();

    Or

    theProfile[“PictureUrl”].Value = null;
    theProfile.Commit();

    But this not seems to works correctly….
    The picture for user in his “http://mysites” was removed with success, but we still see the old picture when we browse _layouts/People.aspx (pages showing group members).

    How can I programmatically removes the picture for a specific user profile ?

    Thanks,

    Marc

    Comment by Marc — November 15, 2011 @ 14:31

  45. Dear all,

    i have an issue in
    file = (SPFile)mi_CreateThumbnail.Invoke(null, new object[] { original, idealWidth, idealHeight, folder, fileName });

    it return exception “An exception was thrown by the target call”
    dll version microsoft.userprofile “14.0.4756.1000”

    any help ??

    Comment by mahmoudhussien — January 21, 2012 @ 10:04

  46. Dear All,

    I have created as it is, but still I am having a problem
    When I debug the code, it shows the specified web application could not found, but I have given the correct URL only.
    Could you please let me know your findings.

    Comment by SSS — February 15, 2012 @ 07:59

  47. This is fantastic. I can’t imagine how much trial and error it took to get this code but I can say it works just fine if you take the original post and merge Samy’s changes for the GetSubfolderForPictures method into it.

    I did have problems initially and thought I’d share the root cause. In my environments, My Sites are hosted on a different web application which runs under a different process identity. As it turns out, the web application on which I was attempting to run this code, did not have access tot he My Sites content database in SQL server, nor did it have SharePoint permissions to the My Sites web application. I set the former in SQL Management Studio and set the latter via web policy (just for testing). Those two pieces were enough to allow the solution to run as designed.

    Comment by Andrew — April 20, 2012 @ 22:05

    • Oh, yes, I’m using the most current SP binaries as of 4/20/12.

      Comment by Andrew — April 20, 2012 @ 22:05

  48. Hi Peter,

    Awesome solution! I was wondering if you know about NewsGator and have a similar solution for their product. The way it works for them is that they have a Profile Setting Tutorial and you add the picture there. When you’re done with that, the only way to add a new picture is to restart the tutorial which is not very intuitive for users.

    Thank you for your help!

    Comment by Jean-François — September 20, 2013 @ 20:44


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: