Saturday, March 26, 2011

Getting the publishing permission levels

SharePoint has a small number of built-in permission levels, or role definitions as they are called code-wise. Several of these are easy to access through the SPRoleType enum.

However, the publishing features create new permission levels that are not found in SPRoleType. Although they can be accessed using code such as web.RoleDefinitions["Approve"], this requires hardcoded strings, and is not practical in a localized setting. Luckily, there is a way to access the localization of these permission levels. I got the solution from Alexey Sadomov, and present it here in a slightly modified form.


The localization resources used for the publishing permission levels are embedded in the publishing assembly. Furthermore, they are internal to the assembly, meaning that we cannot with ordinary means access them. Therefore we resort to use Reflection.

Just as with an ordinary resource file, the publishing resources are accessed through a string key. A complete list of these are found here.
To make the reflection part easy, we create a wrapper class that handles the reflection, and adds a public method that accepts a key and a language ID, and returns the localized string. Here is the wrapper class in all it's simplicity:

using System.Globalization;
using System.Reflection;
using System.Resources;
public static class PublishingResources
{
  private static ResourceManager manager;
  static PublishingResources()
  {
    var assembly = Assembly.Load("Microsoft.SharePoint.Publishing.Intl, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c");
    PublishingResources.manager = new ResourceManager(
      "Microsoft.SharePoint.Publishing.Strings",
      assembly);
  }
  public static string GetString(string key, uint lcid)
  {
    return PublishingResources.Manager.GetString(
      key,
      new CultureInfo((int)lcid));
  }
}

Now you can access the publishing resources in your SharePoint code using the language of the current web:

PublishingResources.GetString(key, web.Language);

To access the 'Approve' and 'Manage Hierarchy' permission level names use the keys 'RoleNameApprover' and 'RoleNameHierarchyManager'. Note: To use the above with SharePoint 2010 simply change the assembly version to 14.0.0.0.

No comments:

Post a Comment