User Profiles

Much like search, the configuration of the User Profile service application is usually a manual process tacked onto the end of a deployment. "Oh yeah...user profiles..." I've heard too many SharePoint architects mutter with about a week-and-a-half left in the project. However, unlike search, the code to automate this process isn't nearly as complicated. Rest assured, however, it's every bit as "interesting" as the rest of the code in this appendix.

The deployment steps we'll be discussing here involve only the provisioning of the user profile properties we're going to be defining in Constants. This is really the first of two things a complete deployment would accomplish; the second is the mapping of these properties to your Active Directory import. I've decided that this will be out of scope for this book, mainly because I have a policy that AD is sacred ground, and only the client's IT shamans should be touching it.

The Feature

First things first: add a feature called "DDD Profiles" to DDD.Web and give it all the same love we've been giving to the rest of them. This will be scoped to the site collection. Unlike search, we're not technically developing against the User Profile service application; we're starting with an SPSite, getting a Microsoft.SharePoint.SPServiceContext from it, and using that as an entry point into the Microsoft.Office.Server.UserProfiles APIs. So even though our Utilities' extensions methods are hanging off of SPSite, it's only a key to unlock the door to the user profile managers. And as you'll see in the upcoming code, "managers" is very much plural.

In addition to the standard site collection-scoped configuration, (refer to the "Taxonomy" section of this Appendix) we're going to be adding a feature activation dependency to Structure. One of our profile properties is going to be mapped to a taxonomy field, which requires a TermSet object, which requires the Structure feature to have provisioned it. So wire that up through the DDD Profiles feature designer, which should look like this when you're done:

Configuring the User Profile feature

Configuring the User Profile feature

With all the configuration in place for this feature, the next step is to add the feature receiver. Also, make sure that we have references to Microsoft.SharePoint.Taxonomy, Microsoft.Office.Server, and Microsoft.Office.Server.UserProfiles by way of DDD.Dependencies. Once that's all wired up, we can take a look at the code:

Code Listing 92: Profiles.EventReceiver.cs

  1. using Tax = Microsoft.SharePoint.Taxonomy;
  2. ...
  3. public override void FeatureActivated(SPFeatureReceiverProperties properties)
  4. {
  5. //initialization
  6. SPSite site = ((SPSite)properties.Feature.Parent);
  7. //ensure section
  8. int displayOrder = site.EnsureProfileSection(
  9. Constants.UserProfiles.Section.InternalName,
  10. Constants.UserProfiles.Section.DisplayName);
  11. //ensure about me property
  12. site.EnsureUserProfileProperty(
  13. Constants.UserProfiles.MyBio.InternalName,
  14. Constants.UserProfiles.MyBio.DisplayName,
  15. ++displayOrder,
  16. Constants.UserProfiles.MyBio.Length,
  17. Constants.UserProfiles.MyBio.Type);
  18. //ensure employee id property
  19. site.EnsureUserProfileProperty(
  20. Constants.UserProfiles.EmployeeId.InternalName,
  21. Constants.UserProfiles.EmployeeId.DisplayName,
  22. ++displayOrder,
  23. Constants.UserProfiles.EmployeeId.Length,
  24. Constants.UserProfiles.EmployeeId.Type);
  25. //ensure i like trees property
  26. site.EnsureUserProfileProperty(
  27. Constants.UserProfiles.ILikeTrees.InternalName,
  28. Constants.UserProfiles.ILikeTrees.DisplayName,
  29. ++displayOrder,
  30. Constants.UserProfiles.ILikeTrees.Length,
  31. Constants.UserProfiles.ILikeTrees.Type);
  32. //get taxonomy session
  33. Tax.TaxonomySession session = new Tax.TaxonomySession(site);
  34. //get group
  35. Tax.Group group = session.EnsureGroup(
  36. Constants.Taxonomy.GroupId,
  37. null);
  38. //get term set
  39. Tax.TermSet termSet = session.EnsureTermSet(
  40. group,
  41. Constants.Taxonomy.TermSetId,
  42. null,
  43. null);
  44. //ensure term set property
  45. site.EnsureUserProfileProperty(
  46. Constants.UserProfiles.TermSet.InternalName,
  47. Constants.UserProfiles.TermSet.DisplayName,
  48. ++displayOrder,
  49. 0,
  50. null,
  51. termSet);
  52. }

This logic, again following the "Create if not already there" paradigm in the context of a service application, first creates a profile section (Line #8), and then four profile properties under it (Line #'s 12, 19, 26, and 45). A confusing thing about the user profile API is that both sections and properties are represented by the same underlying object: a CoreProperty. This is an interesting implementation, since sections are fundamentally different and much "smaller" in complexity than properties. Nevertheless, ‘tis the nature of the beast.

Beyond being obnoxious, the pain of this architecture is felt when attempting to add custom properties to a custom section. If you don't use a section, your profiles end up in the out-of-the-box "Custom Properties" section. Since we have nice groupings for everything else in All Code, (site columns, content types, and taxonomy) then it shall be so for user profiles! I just didn't think it would be this hard.

The challenge presented by everything being a CoreProperty is that the object doesn't have a child collection (like terms) or a group property (like content types). It seems like CoreProperty was designed to model a property (makes sense) and then forced to also be a section. Since properties don't have children, then, technically, neither do sections.

Gander back at Line #8: the method to create a section returns an...integer? Yup. The way you group your profile properties under sections is to order your CoreProperties sequentially! So when we ensure a section, we grab its index (called DisplayOrder) and pass a prefix-plus-plused incrementation of it to all of our properties. So if the section we're creating has a DisplayOrder of n, (all properties and sections in the service application are in the same sequence) our four properties are indexed at (n+1), (n+2), (n+3), and (n+4) respectively. It follows that the next section's DisplayOrder would be (n+5) and its first property falls in at (n+6).

So pursuant to this convention, sections are essentially just headings nestled into an indexed listing of properties in numerical order. So to "assign" a property to a different section, you simply change its DisplayOrder to be one larger than its new parent. Furthermore, you can't change any of this ordering stuff via the UI; another win for code-based deployments!

Before looking at the much more interesting code in the extension methods, let's finish off the feature receiver. Line #'s 33-43 perform the DDD operations to get the term to map to our final profile property. I was lazy here, and instead of feeding these methods everything they need to ensure the group and term set, I simply take a dependency on Structure and assume they already exist. Of course, if you'd rather not deal with the activation dependency, feel free to fill out these methods proper.

Ensuring Properties

Now let's get dirty. We'll first look at EnsureUserProfileProperty, as EnsureProfileSection is essentially just a trimmed down version of it (much in the same way a section is a trimmed down version of a property). The code below demonstrates all of the various operations we'll be performing against the user profile APIs.

Code Listing 93: Utilities.cs

  1. using Tax = Microsoft.SharePoint.Taxonomy;
  2. ...
  3. public static CoreProperty EnsureUserProfileProperty(this SPSite site, string internalName, string displayName, int displayOrder, int length, string type, Tax.TermSet termSet = null)
  4. {
  5. //initialization
  6. bool propIsNew = false;
  7. internalName = internalName.Replace(" ", string.Empty);
  8. //get service context
  9. SPServiceContext context = SPServiceContext.GetContext(site);
  10. //get managers
  11. UserProfileConfigManager upcm = new UserProfileConfigManager(context);
  12. CorePropertyManager cpm = upcm.ProfilePropertyManager.GetCoreProperties();
  13. ProfilePropertyManager ppm = upcm.ProfilePropertyManager;
  14. UserProfileManager upm = new UserProfileManager(context);
  15. ProfileTypePropertyManager ptpm = ppm.GetProfileTypeProperties(ProfileType.User);
  16. ProfileSubtypePropertyManager pspm = upm.DefaultProfileSubtypeProperties;
  17. //get property
  18. CoreProperty cp = cpm.GetPropertyByName(internalName);
  19. if (cp == null)
  20. {
  21. //create property if it doesnt exist
  22. propIsNew = true;
  23. cp = cpm.Create(false);
  24. cp.Name = internalName;
  25. //determine type
  26. if (termSet != null)
  27. {
  28. //term set
  29. cp.Length = 3600;
  30. cp.Type = PropertyDataType.StringSingleValue;
  31. cp.TermSet = termSet;
  32. }
  33. else
  34. {
  35. //standard type
  36. cp.Type = type;
  37. if (length > 0)
  38. cp.Length = length;
  39. }
  40. //multivalued properties are not supported
  41. cp.IsMultivalued = false;
  42. cp.Separator = MultiValueSeparator.Unknown;
  43. }
  44. //property metadata
  45. cp.IsAlias = false;
  46. cp.IsSearchable = true;
  47. cp.DisplayName = displayName;
  48. cp.Description = string.Format("The is the {0} user profile property.", displayName);
  49. //save core property
  50. if (propIsNew)
  51. cpm.Add(cp);
  52. else
  53. cp.Commit();
  54. //property type
  55. ProfileTypeProperty profileTypeProp = propIsNew ? ptpm.Create(cp) : ptpm.GetPropertyByName(internalName);
  56. profileTypeProp.IsVisibleOnEditor = true;
  57. profileTypeProp.IsVisibleOnViewer = true;
  58. profileTypeProp.IsReplicable = true;
  59. //save property type
  60. if (propIsNew)
  61. ptpm.Add(profileTypeProp);
  62. else
  63. profileTypeProp.Commit();
  64. //property sub type
  65. ProfileSubtypeProperty profileSubTypeProp = propIsNew ? pspm.Create(profileTypeProp) : pspm.GetPropertyByName(internalName);
  66. profileSubTypeProp.PrivacyPolicy = PrivacyPolicy.OptIn;
  67. profileSubTypeProp.DefaultPrivacy = Privacy.Public;
  68. profileSubTypeProp.IsUserEditable = true;
  69. //save property sub type
  70. if (propIsNew)
  71. pspm.Add(profileSubTypeProp);
  72. else
  73. profileSubTypeProp.Commit();
  74. //add to section
  75. pspm.SetDisplayOrderByPropertyName(internalName, displayOrder);
  76. pspm.CommitDisplayOrder();
  77. //return
  78. return cp;
  79. }

Following DDD best practices, we have a display name and a unique identifier (internal name) for our properties just like our site columns. Unfortunately, the API doesn't let us use guids here; internal names (as strings) will have to be good enough. This is why Line #7 makes sure there are not spaces in the internal name, as that's the convention SharePoint requires.

Next, on Line #9, we new up an SPServiceContext from the extended SPSite, and from there, on Line #'s 11-16, we get the aforementioned managers. These managers are our programmatic entry point to the user profile service application. I'm guessing we're not operating against a service app explicitly because some of these manager classes have been around since the Shared Services Provider (the predecessor to service applications) days back in 2007. Let's break them down by line numbers:

  • UserProfileConfigManager: this is the queen bee in the user profile API hive; her main job is simply to lay more manager eggs. We use this class to beget the next two.
  • CorePropertyManager: this allows us create and save the underlying CoreProperty that represents our sections and properties, and deals with the "main" pieces of metadata for them. Line #'s 23-48 take care to only populate the "readonly" properties when we're allowed to: at creation time. (If you then edit these properties via the UI, you'll see them disabled.) These include the type, name, and term set (if applicable).
  • ProfilePropertyManager: this is just a pass-through to the ProfileTypePropertyManager below.
  • UserProfileManager: normally, I use this object when I'm querying the user profiles as a data source; it is generally considered read only for metadata. It's only job here to uncover the ProfileSubtypePropertyManager at the end of this list.
  • ProfileTypePropertyManager: this creates and updates ProfileTypeProperty objects, which represent other metadata about the property (see Line #'s 55-58)
  • ProfileSubtypePropertyManager: this is the same as the ProfilePropertyManager, just a different section of metadata. This is on Line #'s 66-68. It's also used to set the ordering for the section assignment on Line #'s 74 and 75.

Other than instantiating the right managers in the right order to do the right CRUD operations, there are some other interesting things going on here. First, let's talk taxonomy on Line #'s 29-31. Normally I'd split this into two different methods for metadata and non-metadata based properties (as I do for the various site column extensions) but that would necessitate massive method signatures passing these heavy managers around. So instead, if you give EnsureUserProfileProperty a termset, it ignores the "length" and "type" parameters and sets the corresponding CoreProperty members as required by the API.

Check out the persistence logic in Line #'s 50-53, 60-63, and 70-73. These use the "propIsNew" Boolean to track whether the object in question is being saved for the first time. If it's indeed new, it's "saved" by adding it to its manager's collection; updates simply need to be "committed." An important note here is that calling Commit will save a new property object, but it will not be available to the preceding manager.

This comes into play on Line #'s 75 and 76. The logic works fine on updates, because the ProfileSubtypePropertyManager will be able to find the underlying CoreProperty by internal name since it's in the database. However, on creates, it can't. Adding it to the collection the first time makes the begotten managers "aware" of the new property even if it hasn't yet been persisted to the database when the manager was instantiated.

The last thing to point out about this method is that I'm taking a lot of liberties with the property metadata. For example, everything is public, editable, and searchable. Also, I chose to lazily not deal with multi-valued properties. If your requirements are more dynamic, you can consider an approach that has the feature receiver itself instantiate all the managers, the extension method only handing persistence and returning the CoreProperty, and then setting the metadata more "globally."

Ensuring Sections

Let's now take a look at the sections. This whole mess with the ordering is completely optional as it adds no functionality; it's just prettier. As I said, sections, like properties, are just CoreProperties with no metadata. And yet it still requires instantiating five managers to get it done! Below is EnsureProfileSection which does the work for us:

Code Listing 94: Utilities.cs

  1. public static int EnsureProfileSection(this SPSite site, string internalName, string displayName)
  2. {
  3. //initialization
  4. internalName = internalName.Replace(" ", string.Empty);
  5. //get service context
  6. SPServiceContext context = SPServiceContext.GetContext(site);
  7. //get managers
  8. UserProfileConfigManager upcm = new UserProfileConfigManager(context);
  9. CorePropertyManager cpm = upcm.ProfilePropertyManager.GetCoreProperties();
  10. ProfileTypePropertyManager ptpm = upcm.ProfilePropertyManager.GetProfileTypeProperties(ProfileType.User);
  11. UserProfileManager upm = new UserProfileManager(context);
  12. ProfileSubtypePropertyManager pspm = upm.DefaultProfileSubtypeProperties;
  13. //get section
  14. CoreProperty cp = cpm.GetSectionByName(internalName);
  15. if (cp == null)
  16. {
  17. //create section core property
  18. cp = cpm.Create(true);
  19. cp.Name = internalName;
  20. cp.DisplayName = displayName;
  21. cp.Description = string.Format("The is the {0} user profile section.", displayName);
  22. cpm.Add(cp);
  23. //create section profile type
  24. ProfileTypeProperty profileTypeProp = ptpm.Create(cp);
  25. ptpm.Add(profileTypeProp);
  26. //create section profile sub type
  27. ProfileSubtypeProperty profileSubTypeProp = pspm.Create(profileTypeProp);
  28. pspm.Add(profileSubTypeProp);
  29. }
  30. else
  31. {
  32. //update section
  33. cp.DisplayName = displayName;
  34. cp.Description = string.Format("The is the {0} user profile section.", displayName);
  35. cp.Commit();
  36. }
  37. //get display order
  38. return pspm.GetSectionByName(internalName).DisplayOrder;
  39. }

This method starts out the same as its big brother: trim spaces from the internal name of the section, get a service context, and instantiate all the managers. In the "create" case of the ensuring if statement on Line #15, notice that we build-and-save a ProfileTypeProperty and a ProfileSubtypeProperty for the section, but don't do anything with these objects.

Even though they aren't represented at all in the UI screens, we need to make sure they exist to support the section; the "Manage User Properties" screen will throw an error if they don't. You can see why this is the case in Line #38: The ProfileSubtypePropertyManager won't be able to locate the section and return its DisplayOrder unless you've done your diligence in Line #'s 24-28.

The Script

The final step is to add this to our deployment scripts and push it out. Since we have an activation dependency on another site collection-scoped feature, Structure, I like to just nuzzle this guy into FeatureActivator.ps1 after it. (Feel free to separate this into its own PowerShell if you prefer.) The bolded lines below show to additions to the file:

Code Listing 95: FeatureActivator.ps1

  1. ...
  2. #get feature guids
  3. [System.Reflection.Assembly]::LoadWithPartialName("DDD.Common");
  4. Write-Host;
  5. ...
  6. $profiles = [DDD.Common.Constants+Features]::Profiles;
  7. $structure = [DDD.Common.Constants+Features]::Structure;
  8. ...
  9. #activate structure (on the site collection)
  10. Write-Host;
  11. Write-Host ("Activating Structure (on the site collection)...") -ForegroundColor Magenta;
  12. $script = Join-Path $path "\FeatureEnsureer.ps1";
  13. .$script -Url $url -Id $structure -Scope "site";
  14. ...
  15. #activate user profiles (on the site collection)
  16. Write-Host;
  17. Write-Host ("Activating Profiles (on the site collection)...") -ForegroundColor Magenta;
  18. $script = Join-Path $path "\FeatureEnsureer.ps1";
  19. .$script -Url $url -Id $profiles -Scope "site";
  20. ...

Now, the first time you run DoEverythinger.ps1 with your shiny new user profile bits included, you might see the following error in the code:

Getting a user profile permission exception

Getting a user profile permission exception

Even though this is the only account on my machine (making it intrinsically a farm administrator and an everything else administrator) we still need to grant ourselves explicit permissions in the user profile service application. Navigate to the "Manage service applications" in central admin, highlight the "User Profile Service Application" row, and click "Administrators" in the ribbon. See the screen show below:

Configuring the User Profile service application

Configuring the User Profile service application

I'm not trying to be a baby about this, as there's nothing wrong with demanding tight permissions, especially in an environment like SharePoint. But that said, code running as farm admin should be able to do whatever it wants, no questions asked. Would the president of the United States have to show ID when viewing an R-rated movie?

That does it for user profile deployment! Just like search, user profiles are usually something that's configured by hand in every environment. Too many times I've seen solutions claiming to be "one hundred percent automated" that had manual steps. When I asked how this was the case, the answer was basically "Well, you know, come on...user profiles aren't deployed." Fail. Follow Deployment Driven Design for all your projects and implement your SharePoint ones with All Code: make your one hundred percent automated deployments indeed automated one hundred percent!