Quantcast
Channel: Blog posts by Henrik Fransas
Viewing all articles
Browse latest Browse all 70

How to create a admin sql user through code

$
0
0

Sometimes you need to have a sql user in your development environment and this is easy to create by code on startup of the application.

In this example I added an if statement so that this is only running if the application are running in debug mode and this is because I do not want this to be created in test och production, only in dev environment.

Important, if you copy this, change the username and password to fit your needs, this is just an example with a generated password!!!

using System.Configuration.Provider;
using System.Web.Security;
using EPiServer.Framework;
using EPiServer.Framework.Initialization;
using EPiServer.Logging.Compatibility;
namespace Alloy46.Business
{
    [InitializableModule]
    public class CreateAdminUserAndRoles : IInitializableModule
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(CreateAdminUserAndRoles));
        public void Initialize(InitializationEngine context)
        {
#if DEBUG
            var mu = Membership.GetUser("EpiSQLAdmin");
            if (mu != null) return;
            try
            {
                Membership.CreateUser("EpiSQLAdmin", "6hEthU", "EpiSQLAdmin@site.com");
                try
                {
                    this.EnsureRoleExists("WebEditors");
                    this.EnsureRoleExists("WebAdmins");
                    Roles.AddUserToRoles("EpiSQLAdmin", new[] { "WebAdmins", "WebEditors" });
                }
                catch (ProviderException pe)
                {
                    Log.Error(pe);
                }
            }
            catch (MembershipCreateUserException mcue)
            {
                Log.Error(mcue);
            }
#endif
        }
        public void Uninitialize(InitializationEngine context)
        {
        }
        private void EnsureRoleExists(string roleName)
        {
            if (Roles.RoleExists(roleName)) return;
            try
            {
                Roles.CreateRole(roleName);
            }
            catch (ProviderException pe)
            {
                Log.Error(pe);
            }
        }
    }
}

 


Viewing all articles
Browse latest Browse all 70

Trending Articles