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.
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.
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);
}
}
}
}
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());
}
}
}
}