Export (0) Print
Expand All
Expand Minimize

Capitalizing On the Social Network Capabilities of SharePoint Server 2007 User Profiles

SharePoint 2007

Summary: Learn about organization hierarchy, membership groups, and quick links to understand the user profile social network capability in Microsoft Office SharePoint Server 2007, and concepts such as custom properties, colleagues, and workgroups. (18 printed pages)

Antoine Atallah, Microsoft Corporation

Martin Gagné, Microsoft Corporation

September 2008

Applies to: Microsoft Office SharePoint Server 2007

Contents

Overview of User Profiles

Microsoft Office SharePoint Server 2007 provides an exciting set of new and enhanced features. One of them is user profiles. What makes user profiles particularly interesting is their ability to transform a SharePoint site into a complete social network. Put simply, you can use user profiles to organize and display information about users, in relation to other users.

Office SharePoint Server 2007 includes user profiles through the My Site of each user. User profiles can do many things by using Web Parts. For example, the "Colleagues Tracker" Web Part displays a list of recent changes by colleagues. The "In Common Between Us" Web Part displays what is in common between users and the "Organization Hierarchy" Web Part displays the hierarchy of coworkers within the company.

Understanding User Profiles

Microsoft SharePoint Products and Technologies (which includes Office SharePoint Server 2007 and Windows SharePoint Services 3.0) have two distinctive concepts to represent users: user accounts (SPUser object) and user profiles (UserProfile class). User accounts are tied to SharePoint list items, sites, and documents to provide security and access rights. User profiles exist in their own data store and are used to organize information about the users. The information contained by user profiles can be classified in three distinct categories: properties, relationships, and quick links. You can access the user profiles information by using the user profiles API or any custom controls (for example, Web Parts).

User Profile Properties

The information attached to user profiles is organized as properties, in the form of name/value pairs. Office SharePoint Server 2007 defines a default set of properties that you can extend. You can index and search all properties by using Office SharePoint Server 2007 Enterprise Search.

A user profile for a specific user account is automatically created when a user creates a My Site. Therefore, all the existing user accounts with a My Site have a user profile. The Shared Services Administration, part of SharePoint Central Administration, manages user profiles and their properties.

Figure 1 shows the distinction between Office SharePoint Server 2007 users and user profiles.

Figure 1. Overview of user profile properties

Overview of user profile properties

There is one user profile per user account. One important detail is that user profiles are global throughout a SharePoint Web application. A user account cannot have multiple user profiles for different sites within a SharePoint site collection.

You can synchronize the user profiles properties with external data sources. You can configure them in the Shared Services Administration.

User Profile Relationships

One of the purposes of user profiles is to maintain relationships between users. This is done through different relationships: colleagues, a workgroup, memberships, and a manager. You can access these relationships by using the privacy policy object model and you can show information to colleagues, colleagues in the workgroup, manager, or everyone. Additionally, you can use properties to filter the information displayed. You can programmatically use Web Parts to display or hide information about different relationships by using information contained in properties.

Colleagues and Workgroup

Colleagues represent a one-way relationship between two user profiles, as shown in Figure 2.

Figure 2. Overview of colleagues

Overview of colleagues

Membership Groups

Membership groups enable multiple user profiles to be grouped with each other under a common theme. A user profile can belong to multiple membership groups, independent of their workgroup, colleagues, or other relationships. Membership groups exist within the user profiles space and are only accessible to user profiles. They can be categorized in two membership group types: distribution list and SharePoint sites. It is also possible to extend these group types by using the user defined type.

Figure 3. Overview of membership groups

Overview of membership groups

Manager, Direct Reports, and Peers

Each user profile can be associated with a manager user profile. A user profile has a single manager. Unlike the workgroup, a user profile's manager does not need to be part of the colleagues of the user. A manager can be any existing user profile. Similar to user profile properties, you can synchronize managers with an external data source, such as Active Directory directory service. You can configure synchronization through the Shared Services Administration of the SharePoint Central Administration tool.

Figure 4. Manager relationship of user profiles

Manager relationship of user profiles

Associated with managers are direct reports. A manager can retrieve the list of users that are directly reporting to the manager. Similarly, a user can query their peers, for the user profiles at the same hierarchical level.

Figure 5. Manager, peers, and direct reports

Manager, peers, and direct reports

QuickLinks and User Profiles

Each user profile has a set of hyperlinks that can be shared among the user's manager, colleagues, and workgroup. They are qualified by a type, which is visible to other users. The hyperlinks are URLs called quick links. They are comparable to favorites in Internet Explorer.

Figure 6. Quick links and user profiles

Quick links and user profiles

Setting Up the Project

This article shows different methods that you can use to interact with user profiles and their properties. It is assumed that Microsoft Office SharePoint Server 2007 is installed, configured, and working on your computer. The examples demonstrated here can be compiled and executed directly on a server running Office SharePoint Server 2007, or on a computer on which a copy of the Office SharePoint Server 2007 assemblies are present.

The namespaces required to work with user profiles are:

  • Microsoft.Office.Server

  • Microsoft.Office.Server.UserProfiles

  • Microsoft.SharePoint

To create a project for the sample code in this article

  1. Ensure that Office SharePoint Server 2007 is installed, configured, and running.

  2. If you do not develop your application where Office SharePoint Server 2007 is installed, copy the Microsoft.Office.Server.dll and Microsoft.Sharepoint.dll assemblies from the following location to your local drive:

    drive:\Program Files\Common Files\Microsoft Shared\Web server extensions\12\ISAPI

  3. Start Microsoft Visual Studio 2008.

  4. On the File menu, point to New, and then click Project.

  5. In the Project Type pane of the New Project dialog box, select Windows in the Visual C# node.

  6. In the Templates pane, click Console Application.

  7. Rename your project from ConsoleApplication1 to MOSSConsoleApplication.

  8. In Solution Explorer, right click References, and then click Add References.

  9. In the Add References dialog box, click References, select Microsoft.Office.Server.dll and Microsoft.Sharepoint.dll (if you do not find the assemblies, see step 2), and then click OK.

  10. On the Project menu, click Add Class, replace Class1.cs with UserProfileHelper.cs, and then click Add.

  11. Mark the UserProfileHelper class as public.

Managing User Profiles

This section explains how to programmatically execute basic operations on a user profile, such as creating, retrieving, and deleting user profiles. When connecting to Office SharePoint Server 2007 to manage user profiles, a URL to the SharePoint server is required. User profiles are shared across site collections, on the same SharePoint Web application; any URL of a site collection can be used to manage user profiles.

Cc973103.note(en-us,office.12).gifNote:

A user profile namespace exists under Microsoft.SharePoint.Portal. This namespace is obsolete and should not be used. Use the Microsoft.SharePoint.Server.UserProfiles namespace instead.

In each example in this article, a new connection to a SharePoint site is created for each operation. Remember that, for performance reasons, you should minimize the number of connections that you open and close.

Creating User Profiles

The fact that a SharePoint user exists in the system does not mean that a user profile exists for that user. When a user accesses their My Site for the first time, a user profile is automatically created. User profiles can also be created programmatically by using the CreateUserProfile method of the UserProfileManager class.

The following example shows how to create a user profile.

using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;

/// <summary>
/// Creates a user profile if it does not already exist.
/// </summary>
/// <param name="requestUrl">URL of the SharePoint site to connect to.</param>
/// <param name="loginName">Login name of a user having access to 
/// the SharePoint site (for example, DOMAIN\User).</param>
public static void CreateUserProfile(string requestUrl, string loginName)
{
    using (SPSite siteCollection = new SPSite(requestUrl))
    {
        using (SPWeb webSite = siteCollection.OpenWeb())
        {
            // Retrieve the ServerContext of the site collection.
            ServerContext serverContext = ServerContext.GetContext(siteCollection);

            // Connect to the UserProfileManager of the SharePoint Web application.
            UserProfileManager userProfileManager = new UserProfileManager(serverContext);

            if (!userProfileManager.UserExists(loginName))
            {
                UserProfile userProfile = userProfileManager.CreateUserProfile(loginName);
             
                // Optionally edit the UserProfile properties.
                

                // Optionally create the UserProfile MySite.
                // if (userProfile.PersonalSite == null)
                //     userProfile.CreatePersonalSite();
            }
        }
    }
}

Deleting User Profiles

Deleting a user profile removes the user's entry from the user profile database. It also synchronizes other user profiles that have relationships with the deleted user profile. Deleting a user profile, however, does not remove rights to any SharePoint site library. User profiles exist in their own storage and are independent of access rights stored in user accounts.

You can accomplish the delete operation by calling the RemoveUserProfile method of the UserProfileManager class. This method takes either the GUID (ID property of the UserProfile class) or the logon name of the user.

The following example shows how to delete a user profile.

using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;

/// <summary>
/// Deletes an exising user profile.
/// </summary>
/// <param name="requestUrl">URL of the SharePoint site to connect to.</param>
/// <param name="loginName">Login name of a user having access to 
/// the SharePoint site (for example, DOMAIN\User).</param>
public static void DeleteUserProfile(string requestUrl, string loginName)
{
    using (SPSite siteCollection = new SPSite(requestUrl))
    {
        using (SPWeb webSite = siteCollection.OpenWeb())
        {
            // Retrieve the ServerContext of the site collection.
            ServerContext serverContext = ServerContext.GetContext(siteCollection);

            // Connect to the UserProfileManager of the SharePoint Web application.
            UserProfileManager userProfileManager = new UserProfileManager(serverContext);

            if (userProfileManager.UserExists(loginName))
            {
                // Optionally delete the My Site of the user profile, if it exists.
                // UserProfile userProfile = userProfileManager.GetUserProfile(loginName);
                // if (userProfile.PersonalSite != null)
                //     userProfile.PersonalSite.Delete();

                // Delete the user profile.
                userProfileManager.RemoveUserProfile(loginName);
            }
        }
    }
}

Retrieving User Profiles

To read or edit the different properties of a user profile, it is necessary to retrieve the user profiles.

The UserProfileManager class has a method called GetUserProfile that takes either a GUID (ID property of the UserProfile class) or a logon name and returns a user profile object. Other variants of the method exist to cover advanced usage scenarios.

The following example shows how to retrieve a user profile.

using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;

/// <summary>
/// Retrieves an existing user profile.
/// </summary>
/// <param name="requestUrl">URL of the SharePoint site to connect to.</param>
/// <param name="loginName">Login name of a user having access to 
/// the SharePoint site (for example, DOMAIN\User).</param>
public static void RetrieveUserProfile(string requestUrl, string loginName)
{
    using (SPSite siteCollection = new SPSite(requestUrl))
    {
        using (SPWeb webSite = siteCollection.OpenWeb())
        {
            // Retrieve the ServerContext of the site collection.
            ServerContext serverContext = ServerContext.GetContext(siteCollection);

            // Connect to the UserProfileManager of the 
            // SharePoint Web application.
            UserProfileManager userProfileManager = new UserProfileManager(serverContext);

            if (userProfileManager.UserExists(loginName))
            {
                UserProfile userProfile = userProfileManager.GetUserProfile(loginName);

                // Retrieve or edit User Profile properties.
            }
        }
    }
}

Extending User Profiles

User profile properties are used to store information about a specific user account. You can use these properties to create a customized social network, where properties represent the information shared among users within an organization.

In addition to a set of properties defined by the site administrator, user profiles can have colleagues, memberships, quick links, a workgroup, and a manager.

User Profile Custom Properties

User profiles have a set of default properties, such as first name, last name, company name, and so on. These characterize a user account. In addition to this set of default properties, you can create custom properties, either through the Site Administration Portal or programmatically.

The UserProfile object has a property bag. This property bag is expandable with additional information. When a new property is created, it becomes available globally, to all the existing user profiles. However, the values set to a property are specific to a user. The creation of a property is achieved through the Properties collection of the UserProfileManager class.

The following example creates a new multivalued custom property called FavoriteMeals. This property is used to store one or many of the favorite meals of a given user.

After the property is created, you can assign values to any user profile by using the Properties collection of the UserProfile object. To save the changes made to the Properties collection, a call to the Commit method is necessary.

The following example shows how to set a user profile custom property.

using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;

public static void UpdateFavoriteMealProperty(string requestUrl, string loginName, params string[] favoriteMeals)
{
    const string FavoriteMealsProperty = "FavoriteMeals";
    const string FavoriteMealsDisplayName = "Favorite Meals";

    using (SPSite siteCollection = new SPSite(requestUrl))
    {
        using (SPWeb webSite = siteCollection.OpenWeb())
        {
            ServerContext serverContext = ServerContext.GetContext(siteCollection);
            UserProfileManager userProfileManager = new UserProfileManager(serverContext);

            if (userProfileManager.UserExists(loginName))
            {
                // Retreive the user profile.
                UserProfile userProfile =
                    userProfileManager.GetUserProfile(loginName);

                // Check whether the property exists.
                if (userProfileManager.Properties.GetPropertyByName(FavoriteMealsProperty) == null)
                {
                    // If the property does not exist, create it. 
                    // Administrator rights are required.
                    PropertyCollection properties = userProfileManager.Properties;
                    Property property = properties.Create(false);
                    property.Name = FavoriteMealsProperty;
                    property.DisplayName = FavoriteMealsDisplayName;
                    property.Type = PropertyDataType.String;
                    property.Length = 255;
                    property.IsUserEditable = true;
                    property.PrivacyPolicy = PrivacyPolicy.OptIn;
                    property.DefaultPrivacy = Privacy.Public;

                    properties.Add(property);
                }

                foreach (string favoriteMeal in favoriteMeals)
                {
                    // Add the value stored in favoriteMeal to the 
                    // property bag.
                    userProfile[FavoriteMealsProperty].Add(favoriteMeal);
                }

                userProfile.Commit();
            }
        }
    }
}

Colleagues and Workgroup

The concept of colleagues is the backbone of the Office SharePoint Server 2007 social networking experience. Colleagues share information among each other, which you can capitalize on by using the user profiles API or any custom controls.

A UserProfile object has a Colleagues property, which is a collection of user profiles. Each of them represents a colleague of the user. By design, colleagues are unidirectional. If User A has User B as a colleague, User B does not automatically have User A as a colleague.

Colleagues can be part of the workgroup of a user. Colleagues within the workgroup can share additional information that is not available to colleagues outside of it.

The following example creates a unidirectional relationship between two user profiles by using the Create method of the Colleagues collection. To save the changes made to this collection, a call to the Commit method is necessary.

The following example shows how to create a colleague relationship.

using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;

/// <summary>
/// Adds a colleague to an existing user profile.
/// </summary>
/// <param name="requestUrl">URL of the SharePoint site to connect to.</param>
/// <param name="loginName">Login name of a user having access to 
/// the SharePoint site (for example, DOMAIN\User).</param>
/// <param name="colleagueLoginName">Login name of the user 
/// to add to loginName's colleagues (for example, DOMAIN\User).</param>
public static void AddColleague(string requestUrl, string loginName, string colleagueLoginName)
{
    using (SPSite siteCollection = new SPSite(requestUrl))
    {
        using (SPWeb webSite = siteCollection.OpenWeb())
        {
            // Retrieve the ServerContext of the site collection.
            ServerContext serverContext = ServerContext.GetContext(siteCollection);

            // Connect to the UserProfileManager of the SharePoint Web application.
            UserProfileManager userProfileManager = new UserProfileManager(serverContext);

            // Check whether the user profile and the colleague user profile exist, and that they are not
            // the same user.
            if (userProfileManager.UserExists(loginName) &&
                userProfileManager.UserExists(colleagueLoginName) &&
                string.Compare(loginName, colleagueLoginName, true) != 0)
            {
                // Retreive user profiles.
                UserProfile userProfile = userProfileManager.GetUserProfile(loginName);
                UserProfile userProfileColleague = userProfileManager.GetUserProfile(colleagueLoginName);

                // Check whether colleagueLoginName is already a colleague.
                if (userProfile.Colleagues.IsColleague(userProfileColleague.ID) == false)
                {
                    // Add the colleague UserProfile to the UserProfile.
                    // First and second parameters, specify the user profile group type (Relationship).  
                    // Third parameter, specify the custom group type Name (only for UserSpecified group type).
                    // Fourth parameter, specify whether the colleague is in the same workgroup.
                    // Fifth parameter, specify the privacy level (that is, who can see the relationship).


                    userProfile.Colleagues.Create(userProfileColleague,
                        ColleagueGroupType.Peer,            
                        string.Empty,                       
                        true,                               
                        Privacy.Public);                    

                    // Save the modification made to the user profile.
                    userProfile.Commit();
                }
            }
        }
    }
}

Deleting a relationship with a colleague is similar to creating one. The main difference, however, is that the Delete operation is executed on the relationship itself through the Colleagues collection. When creating a relationship, to save the changes made to the Colleagues collection, a call to the Commit method is necessary.

The following example shows how to delete a colleague relationship.

using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;

/// <summary>
/// Deletes a colleague relationship.
/// </summary>
/// <param name="requestUrl">URL of the SharePoint site to connect to.</param>
/// <param name="loginName">Login name of a user having access to 
/// the SharePoint site (for example, DOMAIN\User).</param>
/// <param name="colleagueLoginName">Login name of the user to add 
/// to loginName's colleagues (for example, DOMAIN\User).</param>
public static void DeleteColleague(string requestUrl, string loginName, string colleagueLoginName)
{
    using (SPSite siteCollection = new SPSite(requestUrl))
    {
        using (SPWeb webSite = siteCollection.OpenWeb())
        {
            // Retrieve the ServerContext of the site collection.
            ServerContext serverContext = ServerContext.GetContext(siteCollection);

            // Connect to the UserProfileManager of the SharePoint Web application.
            UserProfileManager userProfileManager = new UserProfileManager(serverContext);

            // Check whether the user profile and the colleague user profile exist, and that they are not
            // the same user.
            if (userProfileManager.UserExists(loginName) &&
                userProfileManager.UserExists(colleagueLoginName) &&
                string.Compare(loginName, colleagueLoginName, true) != 0)
            {
                // Retrieve user profiles.
                UserProfile userProfile = userProfileManager.GetUserProfile(loginName);
                UserProfile userProfileColleague = userProfileManager.GetUserProfile(colleagueLoginName);

                // Check whether colleagueLoginName is already a colleague.
                if (userProfile.Colleagues.IsColleague(userProfileColleague.ID) == true)
                {
                    userProfile.Colleagues[userProfileColleague].Delete();

                    // Save the modification made to the user profile.
                    userProfile.Commit();
                }
            }
        }
    }
}

Membership

Membership groups arrange users with common interests or relationships together. A UserProfile object has a Memberships property, which is a collection of membership groups. Each of them represents a membership of the user. A user profile can be a member of any membership group.

The following example creates a new membership group if it does not already exist, and then adds a user to it. This is achieved through the CreateMemberGroup of the MemberGroupManager class. An instance of the MemberGroupManager class is retrieved through the GetMemberGroups method of the UserProfileManager class.

After the group is created, the Create method of the Memberships property of the UserProfile class is called, allowing the user profile to join the membership group. To save the changes made to the Memberships collection, a call to the Commit method is necessary.

The following example shows how to create a membership group and add a user profile to the membership group.

using Microsoft.Office.Server
using Microsoft.Office.Server.UserProfiles; 
using Microsoft.SharePoint;

/// <summary>
/// Determines whether a user profile is member of a membership group.

/// </summary>
/// <param name="userProfile">A user profile.</param>
/// <param name="sourceReference">A membership group name.</param>
///</returns>True if the userProfile is part of the sourceReference group.</returns> 
public static bool IsMemberOf(UserProfile userProfile, string sourceReference)
{    
    return Array.Exists<Membership>(userProfile.Memberships.GetItems(),        
         delegate(Membership m)            
         {
         return string.Compare(m.MembershipGroup.SourceReference, sourceReference, true) == 0; 
         }
    )
}

/// <summary>
/// Adds a user profile to the NewEmployee membership group. If the membership group does
/// not already exist, create it. If the user profile is not already a member of the 
/// group, add it.

/// </summary>
/// <param name="requestUrl">URL of the SharePoint site to connect to.</param>
/// <param name="loginName">Login name of a user having access to the 
/// SharePoint site (for example, DOMAIN\User).</param>               
public static void AddUserProfileToMembershipGroup(string requestUrl, string loginName)
{
    // Group definition. The following is a sample group definition for    
    // a group of "new employees".
    const string GroupUniqueName = "NewEmployees";    
    const string GroupDisplayName = "New Employees";    
    const string GroupDescription = "Group of New Employees";
    const string GroupUrl = "http://newemployees";    
    const string GroupEmail = "newemployees@contoso.com";

    using (SPSite siteCollection = new SPSite(requestUrl))
    {
        using (SPWeb webSite = siteCollection.OpenWeb())
        {
             // Retrieve the ServerContext of the site collection.            
             ServerContext serverContext = ServerContext.GetContext(siteCollection);

             // Connect to the UserProfileManager of the SharePoint Web application.               
             UserProfileManager userProfileManager = new UserProfileManager(serverContext);
             if (userProfileManager.UserExists(loginName))
{
             // Retrieve the user profile.                
             UserProfile userProfile = userProfileManager.GetUserProfile(loginName);
             MemberGroup memberGroup = null; 

             // Obtain the member groups.  
             MemberGroupManager memberGroupManager = userProfileManager.GetMemberGroups();

             // Try to create the member group, if it does not exist.   
             // Retrieve the object in the catch block.
             try
             {
                 memberGroup = memberGroupManager.CreateMemberGroup(
                 PrivacyPolicyIdConstants.MembershipsFromDistributionLists,
                 GroupDisplayName,                           // Group Display Name
                 GroupEmail,                                 // Group Email Address
                 GroupDescription,                           // Group Description
                 GroupUrl,                                   // Group URL
                 GroupUniqueName);                           // Group Unique Name
                 memberGroup.Commit();
              }
              catch (MemberGroupExistsException)
              {
                  PrivacyPolicyIdConstants.MembershipsFromDistributionLists,                        
                  GroupUniqueName);
              }
              // Ensure that the UserProfile is not already a member of the member group.                
              if(!IsMemberOf(userProfile, GroupUniqueName))
              {
                  userProfile.Memberships.Create(memberGroup,                        
                  MembershipGroupType.DistributionList,  
                  // Type of membership                        
                  string.Empty,
                  // Name of type of membership if
                  // membership group type is UserSpecified.
                  Privacy.Public);                            // Privacy Level
               }
            }
        }
    }
}

Removing a user profile from a membership group is similar to adding a user profile to a membership group. The main difference is that the Delete operation is executed on the Membership object itself, through the Memberships collection. When creating a membership, to save the changes made to the Memberships collection, a call to the Commit method is necessary.

using Microsoft.Office.Server
using Microsoft.Office.Server.UserProfiles; 
using Microsoft.SharePoint;

/// <summary>
/// Removes a user profile from a membership group.

/// </summary>
/// <param name="requestUrl">URL of the SharePoint site to connect to.</param>
/// <param name="loginName">Login name of a user having access to 
/// the SharePoint site (for example, DOMAIN\User).</param>
public static void DeleteUserProfileFromMembershipGroup(string requestUrl, string loginName)
{
    const string GroupUniqueName = "NewEmployees";
    using (SPSite siteCollection = new SPSite(requestUrl))
    {
        using (SPWeb webSite = siteCollection.OpenWeb())
        // Retrieve the ServerContext of the site collection.
        ServerContext serverContext = ServerContext.GetContext(siteCollection);

        // Connect to the UserProfileManager of the SharePoint Web Application.    
        UserProfileManager userProfileManager = new UserProfileManager(serverContext);
        if (userProfileManager.UserExists(loginName))
        {
            // Retrieve the user profile.
            UserProfile userProfile = userProfileManager.GetUserProfile(loginName);

            // Lookup the user profile membership.
            Membership membership = Array.Find<Membership>(userProfile.Memberships.GetItems(),
                delegate(Membership m)
            {
return m.MembershipGroup.SourceReference == GroupUniqueName;
            {
      );
   // If the membership is found, delete it.
         if (membership != null)
            membership.Delete();
          }
        }
      }
    }
}
 

Manager, Peers, and Direct Reports

Managers, peers, and direct reports are used to build a hierarchy of user profiles. A UserProfile object has the following methods that allow retrieving the different hierarchical levels: GetManager, GetManagers, GetPeers, and GetDirectReports.

To associate a manager to a user profile, you must use the Manager property of the PropertyCollection. You use the GetManager method of the UserProfile class to retrieve the direct manager of a user. The GetManagers method retrieves all the managers of the user, up to the top of the hierarchy.

The GetPeers method of the UserProfile class retrieves the peers of a user profile. Peers are defined as the users under a common direct manager. The GetDirectReports method of the UserProfile class retrieves the users under the user profile.

The following example associates a manager to a given user profile. To save the changes made to the hierarchy, a call to the Commit method is necessary.

using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;

/// <summary>
/// Sets the manager of a user profile.

/// </summary>
/// <param name="requestUrl">URL of the SharePoint site to connect to.</param>
/// <param name="loginName">Login name of a user having access to 
/// the SharePoint site (for example, DOMAIN\User).</param>
/// <param name="managerLoginName">Login Name of the manager.</param>

public static void SetManager(string requestUrl, string loginName, string managerLoginName)
{
    using (SPSite siteCollection = new SPSite(requestUrl))
    {
        using (SPWeb webSite = siteCollection.OpenWeb())
        {
            // Retrieve the ServerContext of the site collection. 
            ServerContext serverContext = ServerContext.GetContext(siteCollection);

            // Connect to the UserProfileManager of the SharePoint Web application. 
            UserProfileManager userProfileManager = new UserProfileManager(serverContext);

            // Check whether the user profile and the manager user profile
            // exist, and that they are not the same user. 
            if (userprofileManager.UserExists(loginName) &&
            userProfileManager.UserExists(managerLoginName)) 
            {
               // Retrieve user profile.
               UserProfile userProfile = userprofileMananger.GetUserprofile(loginName);

               // Clears the current manager.                
               userProfile["Manager"].Clear();

               // Sets the new manager.                
               userProfile["Manager"].Add(managerLoginName);                
               userProfile.Commit();
            }
        }
    }
}

Based on the hierarchy created by using the Manager property of the UserProfile class, it is possible to obtain the different levels of relationships. The following example uses the GetManagers, GetPeers, and GetDirectReports methods to demonstrate how to interact with the user profile hierarchy to retrieve managers, peers, and direct reports.

using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;

/// <summary>
/// Retrieves the multilevel managers, the peers, and the direct reports of a user profile. 

/// </summary>
/// <param name="requestUrl">URL of the SharePoint site to connect to.</param>
/// <param name="loginName">Login name of a user having access to 
/// the SharePoint site (for example, DOMAIN\User).</param>
/// <param name="managers">List of managers, up to the top level of the hierarchy.</param>
/// <param name="peers">List of peers of the user profile.</param>
/// <param name="directReports">List of direct reprots of the user profile.</param>

public static void GetHierarchy(string requestUrl, string loginName,
    out List<UserProfile> managers,     
    out List<UserProfile> peers,     
    out List<UserProfile> directReports)
{
    // Initializes the output parameters.    
    managers = null;    
    peers = null;    
    directReports = null;

    using (SPSite siteCollection = new SPSite(requestUrl))
    {
        using (SPWeb webSite = siteCollection.OpenWeb())
        {
            // Retrieve the ServerContext of the site collection.            
            ServerContext serverContext = ServerContext.GetContext(siteCollection);            

            // Connect to the UserProfileManager of the SharePoint Web application.               
            UserProfileManager userProfileManager = new UserProfileManager(serverContext);  
          
            // Check whether the user profile and the manager user profile exist, and that they are not                  
            // the same user.            
            if (userProfileManager.UserExists(loginName))
            {
                // Retrieve the user profile.                
                UserProfile userProfile = userProfileManager.GetUserProfile(loginName);  
              
                // Get the user's multiple levels of managers, peers, and direct reports.                 
                managers = new List<UserProfile>(userProfile.GetManagers());                
                peers = new List<UserProfile>(userProfile.GetPeers());                
                directReports = new List<UserProfile>(userProfile.GetDirectReports());
             }
        }
    }
}

QuickLinks Property

Quick links enable users to share interesting URLs with their colleagues, workgroup, manager, or everyone. A UserProfile object has a QuickLinks property, which is a collection of quick links. The following example adds a new quick link to a user profile. This is achieved through the Create method of the QuickLinks property.

using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;

/// <summary>
/// Adds a quick link to a user profile.

/// </summary>
/// <param name="requestUrl">URL of the SharePoint site to connect to.</param>
/// <param name="loginName">Login name of a user having access to 
/// the SharePoint site (for example, DOMAIN\User).</param>
/// <param name="title">Title of the quick link.</param>
/// <param name="url">URL of the quick link.</param>
public static void AddQuickLink(string requestUrl, string loginName, string title, string url)
{
    using (SPSite siteCollection = new SPSite(requestUrl))
    {
        using (SPWeb webSite = siteCollection.OpenWeb())
        {
            ServerContext serverContext = ServerContext.GetContext(siteCollection);
            UserProfileManager userProfileManager = new UserProfileManager(serverContext);

            if (userProfileManager.UserExists(loginName))
            {
                // Retreive the user profiles.                
                UserProfile userProfile = userProfileManager.GetUserProfile(loginName);

                // The URL must start with the scheme (http, ftp, and so on).
                userProfile.QuickLinks.Create(title, url, QuickLinkGroupType.BestBet, 
                    string.Empty, Privacy.Public);
            }
        }
    }
}

Conclusion

This article explored many aspects of user profiles. We demonstrated how to manage them, extend them, and interact with them. User profiles provide a way for organizations to gather information about their employees. The user profiles API is a powerful tool for creating a social networking environment within a SharePoint Web application. Office SharePoint Server 2007 includes this exciting user profiles feature, and we hope this article helped you understand how powerful such a feature can be.

About the Authors

Antoine Atallah is a software design engineer that works on the development team that develops Office Online.

Martin Gagné is a software design engineer on the test team of Microsoft Dynamics Online.

Additional Resources

Community Additions

ADD
Show:
© 2014 Microsoft