Author: Fredrik Gustavsson

  • Re-installing your Umbraco 8 database

    When using Umbraco CMS, there are a couple of things that are helpful in how to be able to use the same software for multiple installations and being able to start from scratch over and over.

    We have switched to Umbraco recently on our own e-commerce solution and there are a couple of things that makes the managing of database more smooth.

    Restart your Umbraco installation

    In order to restart your Umbraco you with to start up with a blank database. To do this, change the setting in the web.config file where you can see the current version of your Umbraco installation.

    If you set it to blank, then you will be able to run the installation wizard once more.

    This will guide you through the installation and finally you will end up with an installation.

    If you just delete the App_Data\Umbraco.sdf file having the default setting for connection string in your Web.config, you will have a problem on startup:


    If you have a problem like this on startup:

    Boot failed: Umbraco cannot run. See Umbraco’s log file for more details.

    -> Umbraco.Core.Exceptions.BootFailedException: A connection string is configured but Umbraco could not connect to the database.
    vid Umbraco.Core.RuntimeState.DetermineRuntimeLevel(IUmbracoDatabaseFactory databaseFactory, ILogger logger) i D:\a\1\s\src\Umbraco.Core\RuntimeState.cs:rad 194
    vid Umbraco.Core.Runtime.CoreRuntime.DetermineRuntimeLevel(IUmbracoDatabaseFactory databaseFactory, IProfilingLogger profilingLogger) i D:\a\1\s\src\Umbraco.Core\Runtime\CoreRuntime.cs:rad 290
    vid Umbraco.Core.Runtime.CoreRuntime.Boot(IRegister register, DisposableTimer timer) i D:\a\1\s\src\Umbraco.Core\Runtime\CoreRuntime.cs:rad 169
    Beskrivning: Ett undantag som inte kunde hanteras uppstod när den aktuella webbegäran kördes. Mer information om felet och var i koden det uppstod finns i stackspårningen.

    Undantagsinformation: Umbraco.Core.Exceptions.BootFailedException: Boot failed: Umbraco cannot run. See Umbraco’s log file for more details.

    -> Umbraco.Core.Exceptions.BootFailedException: A connection string is configured but Umbraco could not connect to the database.
    vid Umbraco.Core.RuntimeState.DetermineRuntimeLevel(IUmbracoDatabaseFactory databaseFactory, ILogger logger) i D:\a\1\s\src\Umbraco.Core\RuntimeState.cs:rad 194
    vid Umbraco.Core.Runtime.CoreRuntime.DetermineRuntimeLevel(IUmbracoDatabaseFactory databaseFactory, IProfilingLogger profilingLogger) i D:\a\1\s\src\Umbraco.Core\Runtime\CoreRuntime.cs:rad 290
    vid Umbraco.Core.Runtime.CoreRuntime.Boot(IRegister register, DisposableTimer timer) i D:\a\1\s\src\Umbraco.Core\Runtime\CoreRuntime.cs:rad 169

    This problem is because there already is an entry in the Web.config file pointing to an existing installation and then the database will not be created.

    You will have the same problem if you change the connection string to point to a SQL Server instance but with no contents.

    To resolve the problem, reset the setting in Web.config as mentioned above.

  • Building a data model for Headless Commerce

    Building a data model for Headless Commerce

    Headless Commerce for the systems architect

    When you are about to go headless, you will be in control of your own data model for commerce and is not just limited to the representation provided by the vendor of your headless platform. If you are a consultant with multiple implementations, you may take the oppurtunity to align several clients to use the same data model for easeier code reuse. In this blog post, I will address the question why you should want to have your own model and not be limited only to use the model provided by the vendor.

    This blog postis the first in a series of blog posts explaining how to implement an e-commerce application on top of an existing CMS and headless commerce solution. For examples in the future posts, we will be using Sitecore and Umbraco as CMS and Storm Commerce as the headless commerce platform.

    The layers of an application

    But before we address the data model, we need to find out the purpose of why there may be a need for a data model different than the one provided by the vendor. This applies to you if you are using a multi layered appliction where some of the interaction with the end users includes exposure of the data in Json for the presentation layer.

    The managers layer

    This is the bottom layer that I’m using for accessing data from the systems where it is stored. Each manager has it’s purpose to be responsible for the business logic understaning how the systems underneath the managers layers and the database data is structured. Each manager is there for one purpose and is only allowed to perform actions in it’s own domain. Managers are managed by dependency injection. The managers are using the internal data model that is an implementation of the externally exposed interfaces on top of the model.


    The services layer

    A service may interact between multiple managers and is responsible for coordinating which managers that are invoked to perform a task regardless of how many managers there are. Each service has a constructor where it will receive it’s managers required by dependency injection. The service is invoked by the layers above and does expose the objects customized for the specific customer. To be able to reuse the data model, make sure that this model is only communicating by interfaces of the domain model. This layer may expose the data transfer objects implementing the interfaces of your domain model.


    The frontend backend layer

    This is where the logic happens that will be in interaction with the end user and where most of the code will not be shared between different clients except for the base functionality of an e-commerce site. This layer is allowed to communicate with the layers below by using the services layer. This layer will have no knowledge of the systems underneath and their implementations, it will just be aware of the services layer and the Data Transfer Objects data model. It will have the services required injected by dependency injection so that it does not know exactly which implementation of a service that is used, which will make it easy to replace a service underneath to provide customer specific logic in the service layer without altering the contract between the service and the models underneath.

    The domain model

    In order to be able to have code reuse and to not be totally dependant on to always keep the same infrastructure, I would recommend you to build your own data model on top of the systems that you are interacting with in your implementations, so if you decide to replace the customer services system with a different one, you don’t need to start all over again. This is why I’m always using the data model in three layers.


    Top layer Data Transfer Objects

    This layer is what may be exposed as JSON objects through my controllers. It is sufficient to do basic calculations and logic on, but is totally independant on which backnd system that is being used. It will implement an interface that allows this data transfer object to be sent down to the system levele underneath with the use of reflection or similar technologies.


    The implementation layer

    This is where the data model is managed so that it may contain all the attributes required to do business logic on them but where not all the information is intended for the top layers. It is i.e. irrevevant to expose purchase details about a product to any layer above or any kind of data that is not supposed to leave this layer. There are methods on this layer to transform from and to the data transfer layer and methods to interact with the vendor data model.


    The vendor data model

    This is the data model provided by the vendor. This model is used to send requests and interpret responses from the vendor. There are often different models from different vendors, such as the e-commerce headless commerce platform with it’s data model and the CMS that may also keep information about e-commerde data such as customer logins.

    The result will be a model where your frontend logic will communicate down to the below systems using Data Transfer Objects (DTOs) and they will respond back in that way. You may replace the managers and services in different projects if those that you implement won’t do the job for the current project, but the data structure will be intact. Remember to use Dependency Injection to support this model.

    About this series of blogs

    This is the first entry in a series of entries to spread knowledge on the topic for how to implement an e-commerce solution that depends on one ore several underlying SAAS systems and local software.

    The author, Fredrik Gustavsson at Jolix AB is working to spread the knowledge on how to be able to do this using standard platforms and how to be able to reuse code between clients.

  • Sitecore: Checking for existence of a field in an item

    Check for existence
    One of the most common tasks when developing for a system where the users of the system may alter the data model, is to check that the indata is always correct. Assume that if is possible to have different indata, then expect the power user to be able to provide a piece of unexpected data.

    One of the really great things about Sitecore is they way to build content in a tree structure with folders grouping different types of content together to benefit from sorting and attributes on the objects below. A typical solution could be a blog post, that may consist of a structure of:

    • Blog post about LED Dimmers
      • Product References (folder)
        • Dimmer X 20-315W GLE
        • Dimmer Y 40-600W GLE
        • Dimmer Z 0-100W for LED
      • Related Blog Post References (folder)
        • What is the difference between a light bulb and a LED lighting source
        • How to use a dimmer for electronic transformators

    In such a case, the objects are probably not inheriting from the same base templates as the blog post, and if it is also possible to have a structure for blog entries underneath the blog entry, you need to make sure that any logic that is processing the child items also is sure which content to expect.

    You could of course check for which template ids that are applicable as child items, but this would not be a great solution, since a change in design may cause you having to re-deploy the code in order to add a new data template.

    The solution is to use the Sitecore template structure to inherit base templates which will add functionality to the page and by doing this, we will make it possible to have the logic work and be future proof in a much better way. I’m for instance using the type of base templates as:

    • Page Metadata – this is a page that will contain the neccessary metadata to work as a stand-alone page with a title, meta description and other meta tags that may be needed for the project.
    • Page in Navigation Structure – the metadata for making the page part of the navigation structure.

    When at first working with Sitecore, it felt odd that an attribute may only exist once in the template structure, and it was easy to thing that the Meta Description field could be created for each template. This is of course not a good way of doing it even if is possible, but that won’t give you the benefit of dynamic data model changes that you will have by inheriting page capabilities by inheriting base templates.

    The really good thing about inheriting base templates for template names, is that you don’t have to refer to a field by it’s name, you can instead refer to it by it’s ID and a set of constants that the logic that requires the fields know their ID and access them like that instead of by the field name.

    Define the attributes in a constants class:

    public class ModelFields {
      public static ID MetaTitleID = new ID("{499946DB-175A-4A41-88C7-103F513A24D0}");
      public static ID MetaDescriptionID = new ID("{DB3B8336-DDCC-460A-B522-52E4966CBBD3}");
    }
    
    public class ModelTemplates {
      public static ID PageMetadataTemplateID = new ID("{F7AD3B12-F155-49EA-9B46-C6112722BDB4}");
    }
    

    Then, you could check if the current item’s template is a decendant of the base template that contains the required fields by introducing a method.

    public static bool InheritsBaseTemplate(ID baseTemplateId, Item item)
    {
        if( baseTemplateId.IsNull ) return false; 
        if( item == null ) return false;
        var itemTemplateDefinition = TemplateManager.GetTemplate(item);
        if( itemTemplateDefinition == null ) return false;
        return itemTemplateDefinition.DescendsFromOrEquals(baseTemplateId);
    }
    

    This nice little utility method gives me the ability to always check that a child item is applicable:

    foreach (var child in item.Children)
    {
       // Make sure this item inherits the Page Metadata Template 
       // to proceed to processing logic
       if ( ! ItemUtil.InheritsBaseTemplate(
                ModelTemplates.PageMetadataTemplateID, 
                child)) 
          continue;
    
       // Do logic when the selected template exists
    }
    

    There is also an alternative way of testing for just a specific field instead of the entire template, since each field is unique by it’s ID. We are always using the serialization tools to ensure that fields share the ID between environments, it’s always possible to refer to a field by it’s GUID and then there is no need to load the template to check wether the field exists.

    foreach (var child in item.Children)
    {
       // Make sure this item inherits the Page Metadata Template to 
       // proceed to processing logic
       if (!TemplateManager.IsFieldPartOfTemplate(
               ModelFields.MetaTitleID, 
               child)) 
           continue;
       
       // Do logic when the selected template exists
    }
    

    As of many things in Sitecore, it is for you to decide which method to use. I tend to use both methods.

    Before reading this, you have probably already tested some of the not so reliable methods:

    // Typical Null Reference Exception problem
    if( item.Fields["Meta Title"] == null ) continue;
    
    // Another Null Reference Exception problem
    if( item.Fields["Meta Title"].Value == null ) continue;
    

    The problem with both of the above examples is that the item is not fully loaded. In order to test for all the possible fields, you would have to load all the fields of the item

    item.Fields.ReadAll();