Set an avatar

To set the avatar of the user, you must perform the following:

  1. Get instances of the required managers.
    You must get instances of the UsersManager, UserProfileManagerand LibrariesManagerclasses.
  2. Get instance of the user.
    Get the specified user. For more information, read For developers: Query users.
  3. Get instance of the user profile.
    Get instance of the user profile of the specified user. For more information, read For developers: Query user profiles.
  4. Get instance of the image.
    The image to be used as an avatar, must be located in the Sitefinity CMS image libraries. For more information about working with image, read For developers: CRUD operations with images.
  5. Create a content link.
    To create a ContentLinkobject, call the CreateContentLinkstatic method of the ContentLinksExtensionsclass. Pass the profile and the image as arguments.
  6. Set the Avatarproperty.
    Set the value of the Avatarproperty to the ContentLinkobject.
  7. Save the changes.
    Save the changes to the UserProfileManagerinstance.

Here is a code example:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telerik.Sitefinity.Data.ContentLinks;
using Telerik.Sitefinity.Libraries.Model;
using Telerik.Sitefinity.Model.ContentLinks;
using Telerik.Sitefinity.Modules.Libraries;
using Telerik.Sitefinity.Security;
using Telerik.Sitefinity.Security.Model;

namespace Telerik.Sitefinity.Documentation.CodeSnippets.DeepDive.Security.Users
{
   public partial class UserProfilesSnippets
   {
       public static void SetAvatar(Guid userId, Guid imageId)
       {
           UserManager userManager = UserManager.GetManager();
           UserProfileManager profileManager = UserProfileManager.GetManager();
           LibrariesManager librariesManager = LibrariesManager.GetManager();

           User user = userManager.GetUser(userId);

           if (user != null)
           {
               SitefinityProfile profile = profileManager.GetUserProfile<SitefinityProfile>(user);

               if (profile != null)
               {
                   Image avatarImage = librariesManager.GetImages().Where(i => i.Id == imageId).SingleOrDefault();

                   if (avatarImage != null)
                   {
                       ContentLink avatarLink = ContentLinksExtensions.CreateContentLink(profile, avatarImage);

                       profile.Avatar = avatarLink;

                       profileManager.SaveChanges();
                   }
               }
           }
       }
   }
}
Want to learn more?
Enhance your Sitefinity skills by enrolling in free training sessions. Become Sitefinity certified through Progress Education Community to strengthen your professional credentials.
New to Sitefinity?