Trikks

The digital adventures of Eric Herlitz

Archive for the ‘EpiServer Commerce’ Category

Deleting a Contact (Customer) from Mediachase / EPiCommerce programmatically

Posted by trikks on September 30, 2012

This is a somewhat undocumented function but if you are familiar with the class BusinessManager in the Mediachase.BusinessFoundation.Data.Business namespace things become quite easy.

To demonstrate this I created a customer called Test Testson

Snippet

To remove this customer contact programmatically with c# the following code is required

// Fetch the user
Mediachase.Commerce.Customers.CustomerContext customerContext = new Mediachase.Commerce.Customers.CustomerContext();
Mediachase.Commerce.Customers.CustomerContact testTestson = customerContext.GetContactById(new Guid("1c8279d8-85bd-4063-a018-a627f98c99cb"));

// Delete
Mediachase.BusinessFoundation.Data.Business.BusinessManager.Delete(testTestson);

That’s it.

Posted in EPiServer, EpiServer Commerce, Mediachase | Tagged: , , , | Leave a Comment »

EPiServer Commerce error message “Failed to check the license.”

Posted by trikks on August 17, 2012

Usually I develop most of my EPiServer Commerce stuff in console applications and then deploy them in a proper .net manner. Occasionally this error shows up when invoking a method that has license check involved.

License section

Verify that everything in this section in the app (or web) config is correct

<mediachase.license>
    <licenseProvider defaultProvider="sqlProvider" allowUpload="True" licenseServerUri="http://licensing.mediachase.com/2.0/License.aspx">
        <providers>
            <add name="fileProvider" type="Mediachase.Licensing.FileStorageProvider, Mediachase.Licensing" storagePath="C:\EPiServer\eCommerceFramework\5.2\EPiServerCommerceManager\Licensing"/>
            <add name="sqlProvider" type="Mediachase.Licensing.SqlStorageProvider, Mediachase.Licensing" connectionStringName="EcfSqlConnection" tableName="" createTable="True"/>
        </providers>
    </licenseProvider>
</mediachase.license>

and this section

These settings may not even be present in your app/web.config. Please ensure that they are and setup according to your preferences.

<appSettings>
    <add key="BaseCatalog" value="Everything"/>
    <add key="BaseAddress" value="http://localhost:17000"/>
</appSettings>

Posted in EpiServer Commerce, Mediachase | Leave a Comment »

Programmatically register a display template in EPiServer Commerce [Snippet]

Posted by trikks on August 15, 2012

This is quite simple and follow the general behind the scenes pattern Mediachase use.

Expected result

To programmatically register template references in the commerce manager

Code

// Get all templates
Mediachase.Cms.Dto.TemplateDto templateDto = Mediachase.Cms.Managers.DictionaryManager.GetTemplateDto();

string newTemplateName = "PromotionTemplate";
string newTemplateFriendlyName = "Promotion Template";

// Check if the template exist
if (!templateDto.main_Templates.Any(x => x.Name.Equals(newTemplateName, StringComparison.InvariantCultureIgnoreCase)))
{
    // Create empty template dto
    templateDto = new Mediachase.Cms.Dto.TemplateDto();
    Mediachase.Cms.Dto.TemplateDto.main_TemplatesRow row = null;

    row = templateDto.main_Templates.Newmain_TemplatesRow();
    row.ApplicationId = Mediachase.Cms.CmsConfiguration.Instance.ApplicationId;

    row.Name = newTemplateName;
    row.FriendlyName = newTemplateFriendlyName;
    row.Path = string.Format("~/Templates/DisplayTemplates/{0}.ascx", newTemplateName);
    row.TemplateType = "Entry";
    row.LanguageCode = "en-us";

    if (row.RowState == DataRowState.Detached)
        templateDto.main_Templates.Rows.Add(row);

    // Save any changes
    if (templateDto.HasChanges())
        Mediachase.Cms.Managers.DictionaryManager.SaveTemplateDto(templateDto);
}

Posted in EpiServer Commerce, Mediachase | Tagged: , | Leave a Comment »

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;
}

Posted in EpiServer Commerce, Mediachase | 1 Comment »

Cannot change Language when UseCurrentUICulture is on

Posted by trikks on January 17, 2012

This error occurs since you forgot to set the UseCurrentUICulture to false when instantiating the MetaDataContext object

The error message looks something like this
MetaDataPlusException was unhandled
Cannot change Language when UseCurrentUICulture is on

To solve this you simple need to set the UseCurrentUICulture to false when instantiating your MetaDataContext object, in example

MetaDataContext metaDataContext = new MetaDataContext(connectionString)
{
    UseCurrentUICulture = false,
    Language = Capo.EPiServer.Constants.ProductCatalogConstants.DefaultLanguage
};

Cheers!

Posted in EpiServer Commerce | Leave a Comment »

EPiServer Commerce (Mediachase) Unable to cast object of type ‘System.DBNull’ to type ‘System.String’. after creating a new catalog

Posted by trikks on December 22, 2011

This means you (or someone) where sloppy when creating a new catalog. the error may vary but check the InvalidCastException in the stacktrace for hints.

In this scenario the catalog didn’t have a default language set, so removing it and adding that property when creating it solved the issue.

Method to create new EPiServer Commerce Catalog

Here is my method to create working catalog

public static bool Create(string catalogName)
{
    try
    {
        CatalogDto catalogDto1 = CatalogContext.Current.GetCatalogDto(-1, new CatalogResponseGroup(CatalogResponseGroup.ResponseGroup.CatalogInfo));
        CatalogDto.CatalogRow newCatalogRow = catalogDto1.Catalog.NewCatalogRow();
        newCatalogRow.Name = catalogName;
        newCatalogRow.StartDate = DateTime.Now;
        newCatalogRow.EndDate = DateTime.Now.AddYears(20);
        newCatalogRow.IsActive = true;
        newCatalogRow.SortOrder = 0;
        newCatalogRow.ApplicationId = AppContext.Current.ApplicationId;
        newCatalogRow.Created = DateTime.Now;
        newCatalogRow.Modified = DateTime.Now;
        newCatalogRow.IsPrimary = false;
        newCatalogRow.DefaultLanguage = "sv-SE";

        // save
        catalogDto1.Catalog.AddCatalogRow(newCatalogRow);
        CatalogContext.Current.SaveCatalog(catalogDto1);
        return true;
    }
    catch
    {
        return false;
    }
}

Method to delete an EPiServer Commerce Catalog

public static void Delete(string catalogName)
{
    CatalogDto catalogs = CatalogContext.Current.GetCatalogDto();
    CatalogDto.CatalogRow catalog = catalogs.Catalog.FirstOrDefault(x => x.Name.ToLower().Equals(catalogName.ToLower()));
    CatalogContext.Current.DeleteCatalog(catalog.CatalogId);
}

The full error

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Unable to cast object of type ‘System.DBNull’ to type ‘System.String’.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

 

Stack Trace:

[InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.String'.]
   Mediachase.Commerce.Catalog.Dto.CatalogRow.get_DefaultLanguage() +80

[StrongTypingException: The value for column 'DefaultLanguage' in table 'Catalog' is DBNull.]
   Mediachase.Commerce.Catalog.Dto.CatalogRow.get_DefaultLanguage() +193
   EPiServer.Business.Commerce.HttpModules.<>c__DisplayClass1b.<GetAllCommerceLanguages>b__18(CatalogRow catalogRow) +29
   System.Collections.Generic.List`1.ForEach(Action`1 action) +76
   EPiServer.Business.Commerce.HttpModules.ProductUrlRewriteModule.GetAllCommerceLanguages() +337
   EPiServer.Business.Commerce.HttpModules.ProductUrlRewriteModule.GetProductByLink(UrlBuilder url) +729
   EPiServer.Business.Commerce.HttpModules.ProductUrlRewriteModule.UrlRewriteProvider_ConvertingToInternal(Object sender, UrlRewriteEventArgs e) +147
   EPiServer.Web.UrlRewriteProvider.OnConvertingToInternal(UrlRewriteEventArgs e) +26
   EPiServer.Web.FriendlyUrlRewriteProvider.TryConvertToInternal(UrlBuilder url, LanguageApiMode apiMode, CultureInfo& preferredCulture, Object& internalObject) +173
   EPiServer.Web.FriendlyUrlRewriteProvider.TryConvertToInternal(UrlBuilder url, CultureInfo& preferredCulture, Object& internalObject) +23
   EPiServer.Web.UrlRewriteModule.HttpUrlRewriteToInternal(UrlBuilder url) +483
   EPiServer.Web.UrlRewriteModuleBase.BeginRequestEventHandler(Object sender, EventArgs e) +205
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +171

 


Version Information: Microsoft .NET Framework Version:2.0.50727.5448; ASP.NET Version:2.0.50727.5420

 

Posted in EpiServer Commerce, Mediachase | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.