Create Role on deploy of feature

It’s trivial case when you develop some feature which implies creating some roles within Sitecore. This post is about how to ensure creating of necessary roles after you deliver feature to test/demo/live environment.

At first extend initialize pipeline with processor which create necessary roles.

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <initialize>
        <processor type="Roles.Components.Pipelines.Loader.CreateRoles,Roles" />
      </initialize>
    </pipelines>
  </sitecore>
</configuration>

Secondly implement CreateRoles class.

namespace Roles.Components.Pipelines.Loader
{
    using Sitecore.Diagnostics;
    using Sitecore.Pipelines;
    using Sitecore.Security.Accounts;
    using Sitecore.Security.Domains;
    using Sitecore.SecurityModel;
    using System.Web.Security;

    public class CreateRoles
    {
        public void Process(PipelineArgs args)
        {
            const string testRoleName = "test_custom_domain\\test_role";

            if (Role.Exists(testRoleName))
            {
                return;
            }

            this.EnsureDomainExists(testRoleName);
            Roles.CreateRole(testRoleName);
        }

        protected void EnsureDomainExists(string roleName)
        {
            Assert.ArgumentNotNull(roleName, "roleName");
            var domainName = Domain.ExtractDomainName(roleName);

            if (!string.IsNullOrEmpty(domainName) && (DomainManager.GetDomain(domainName) != null))
            {
                return;
            }

            using (new UserSwitcher("sitecore\\admin", true))
            {
                DomainManager.AddDomain(domainName);
            }
        }
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s