Trikks

The digital adventures of Eric Herlitz

Creating Users in EPiServer Commerce

Posted by trikks on February 22, 2012

So, I got tired of the SDK documentation of this pretty nice system and did stuff by myself as usual. What I was trying to accomplish is to have one method that allows me to standardize the Customer Contact and MemberShip Account creation process no matter if you will interface the method from the web or through an integration or console.

Lets call it flexible account creation method that works form Console, Web services and Web pages. The result below, have fun :)

Done in version EpiServer Commerce version 1 R2 SP1 (1.1.1)
This article also applies to Mediachase Commerce 5.2

/// <summary>
/// Create Contact and Membership User
/// </summary>
/// <param name="firstName"></param>
/// <param name="lastName"></param>
/// <param name="email">Also used as username</param>
/// <param name="password"></param>
private static void CreateUser(string firstName, string lastName, string email, string password)
{
    // Ensure we have a datacontext, nice to have if we are outside the web envionment
    if (DataContext.Current == null)
    {
        string connectionstring = ConfigurationManager.ConnectionStrings["EcfSqlConnection"].ConnectionString;
        Mediachase.BusinessFoundation.Data.DataContext.Current = new Mediachase.BusinessFoundation.Data.DataContext(connectionstring);
    }
 
    string userName = email;
    string fullName = string.Concat(firstName, " ", lastName);
 
    // Try to get the user
    MembershipUser user = Membership.GetUser(userName);
 
    // If the used didn't exist lets create it
    if (user == null)
        user = Membership.CreateUser(userName, password, email);
 
    // Ensure user is approved
    user.IsApproved = true;
    Membership.UpdateUser(user);
 
    // Add user to default roles, if they exist
    try
    {
        if (RoleExists(AppRoles.EveryoneRole))
            SecurityContext.Current.AssignUserToGlobalRole(user, AppRoles.EveryoneRole);
 
        if (RoleExists(AppRoles.RegisteredRole))
            SecurityContext.Current.AssignUserToGlobalRole(user, AppRoles.RegisteredRole);
    }
    catch { }
 
    CustomerContact contact = CustomerContact.CreateInstance(user);
    contact.FullName = fullName;
    contact.FirstName = firstName; // Overwrites the default comming from CreateInstance
    contact.LastName = lastName;
    contact.RegistrationSource = "ByCode"; // Could be IP or anything
    contact.CustomerGroup = Constants.ProductCatalogConstants.DefaultCustomerGroup; // String value "Customers"
    contact.PreferredCurrency = Constants.ProductCatalogConstants.DefaultCurrency.ToUpper(); // String value "SEK"
    contact.PreferredLanguage = Constants.ProductCatalogConstants.DefaultLanguage; // String value "sv-SE"
 
    contact.SaveChanges();
}
 
/// <summary>
/// Verify existance of roles
/// </summary>
/// <param name="roleName"></param>
/// <returns></returns>
private static bool RoleExists(string roleName)
{
    // Ensure we have a datacontext, nice to have if we are outside the web envionment
    if (DataContext.Current == null)
    {
        string connectionstring = ConfigurationManager.ConnectionStrings["EcfSqlConnection"].ConnectionString;
        Mediachase.BusinessFoundation.Data.DataContext.Current = new Mediachase.BusinessFoundation.Data.DataContext(connectionstring);
    }
 
    try
    {
        // If we got a SecurityContext
        if (SecurityContext.Current != null)
        {
            if (SecurityContext.Current.GetAllRegisteredRoles().Any())
                return SecurityContext.Current.GetAllRegisteredRoles().FirstOrDefault(x => x.RoleName == roleName) != null;
        }
 
        // ... and if we dont
        if (SecurityContext.Current == null)
        {
            string ProviderName = "CustomerSecurityProvider";
            SecurityContext securityContext = SecurityContext.CreateInstance(ProviderName);
 
            if (securityContext != null && securityContext.GetAllRegisteredRoles().Any())
                return securityContext.GetAllRegisteredRoles().FirstOrDefault(x => x.RoleName == roleName) != null;
        }
 
    }
    catch { }
 
    return false;
}
About these ads

One Response to “Creating Users in EPiServer Commerce”

  1. Nathan said

    Hi,

    Thank you very much for providing the code for ecommerce. Just wondering is there anything else in either the app or web config that you need to include in order to get user from ecommerce database. At the moment I’m getting null value when try to get user. I followed your example but it doesn’t work.

    This is what I did.

    I created a new project in VS (does it matter if I use framework 4?)
    I include all the mediachase section group in app.config including the licensing, framework and connection string
    I copied the configs folder from ecommerce website
    I then create a unit test to confirm whether i’m getting the data

    Just wondering if you can provide me with a working example if possible.

    Your help is highly appreciated

    Thanks
    Nathan

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 )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: