Category: Headless Development

XM Cloud local environment – Setup local development instance

This blog post will guide you through the local environment setup for XM Cloud. You may refer this documentation to do this your own way. Althoug the documentation covers most of the setup, this blog post provides visual on the steps and errors with the resolution.

https://doc.sitecore.com/xmc/en/developers/xm-cloud/walkthrough–setting-up-your-full-stack-xm-cloud-local-development-environment.html

Once the Foundation Head from Sitecore Labs is forked s(se more details here) clone the copy to the local machine for creating a local instance required for XM Cloud development.

Pre-requisite

You can find the pre-requisite in this documentation. Ensure your machine has this before setting the local development environment. Just noting down here-

https://doc.sitecore.com/xmc/en/developers/xm-cloud/walkthrough–setting-up-your-full-stack-xm-cloud-local-development-environment.html

Also make sure you are using Docker v.2, as explained here.

Access to XM Cloud – This blog post assumes you have admin access to XM Cloud where you should be able to craete/update/delete projects environments and deployment in your organisation.

I have this ready on my machine.

1. Clone the forked Foundation head repo.

I named the folder same as the repo on my local machine i.e. xmcloud-foundation-head. the same will be refered thoruhg this post.

Will see the following folder structure after cloned.

I use Visual Studio Code to make any environment related changes. You may use either Visual Studio 2022 or your choice of editor.

2. Open the .env at the root folder and you will see REPORTING_API_KEY, TELERIK_ENCRYPTION_KEY etc. empty.

3. Start the containers.

Prepare the environment

Before doing so make sure you stop the IIS and check if the port 443 (IIS Website) and 8984 (Solr service)is not used and the docker is running in Windows Containers mode. If not switch to Windows cotainers.

iisreset /stop
Get-Process -Id (Get-NetTCPConnection -LocalPort 443).OwningProcess
Get-Process -Id (Get-NetTCPConnection -LocalPort 8984).OwningProcess

Stop-Service -Name "<the name of your service>"

Copy the license file to c:\license folder. If you wish to have this in other folder you also have to change the HOST_LICENSE_FOLDER in .env(root folder) with the path where the license resides.

To prepare the Sitecore container environment, run the script init.ps1 from the root directory of the project along with the license path and desired passowrd for your instance. this form the root folder from the downloaded the repo.

.\init.ps1 -InitEnv -LicenseXmlPath "C:\license\license.xml" -AdminPassword "b"

Required certificates added.

You may also noticed .env in root folder have added values in REPORTING_API_KEY, TELERIK_ENCRYPTION_KEY and MEDIA_REQUEST_PROTECTION_SHARED_SECRET, which was earlier empty.

Download the Sitecore Docker images, install and configure the containers and client application

Run the up.ps1 to download and install containers and client application

.\up.ps1

This is should download the images and start the containers

Once the containers are started, it should ask to confirm to login to Sitecore with the Device confirmation code. Confirm if this matches. It should also ask to login to XM Cloud isntance and confirm.

One this is done indexes will be rebuilt and the Sitecore instance should be up and running.

Also notice that any items in this case none is pushed to Sitecore instance and an api key is genereated with the name xmcloudpreview-

You may also notice a jss editing secret and SITECORE_API_KEY_xmcloudpreview are updated in .env fiel in root folder along with the Sitecore Admin password which was set whilst initialising the environment.

Your local instance should now be up and running-

https://xmcloudcm.localhost/sitecore/

The highlighted key shoulld match the key while spinning up the containers.

Taking down the containers

To take down the containers run the down.ps1 from the root folder.

.\down.ps1

Errors

Invoke-RestMethod : Unable to connect to the remote server

This should be ideally staright forward but if you see any issues whilst getting CM instance up and runing. take down the container with down.ps1 command and delete any docker network.

docker network prune

Hope this helps to setup local Sitecore instance for XM Cloud development.

Loading

Debug, inspect, test and run the request triggered by XM Cloud Webhook using ngrok

Sitecore Webhooks allows to receive real-time notification about events to the web api that can handle these requests.

In this blog post will see how to debug such handlers in local environment, events triggered by XM Cloud or from the local instance using ngrok.

What is ngrok?

ngrok allows to connect external netwroks in a consistent, secure and repeatable manner without changing any network configurations.

Pre-requisite-

Sitecore Instance-

Either have a local Sitecore instance or XM Cloud instance. See how to setup local XM Cloud instance

Create a Webhook Handler(Web Api)

For this blog post I have created a simple Web Api with a endpoint /api/item/handler which receives POST requests with a Item payload and just return OK or Badrequest response.

We are going to create a Webhook with item:saved event in Sitecore.

using Microsoft.AspNetCore.Mvc;
using Sitecore.Webhook.Handler.Models;

namespace Sitecore.Webhook.Handler.Controllers;

[ApiController]
[Route("api/[controller]")]
public class ItemController : Controller
{
    [HttpPost("handler")]
    public async Task<IActionResult> ItemHandler(ItemPayload? payLoad, 
        CancellationToken cancellationToken)
    {
        if (payLoad == null)
        {
            return BadRequest();
        }

        // Process the item handler
        return Ok();
    }
}

When I run this from VS the endpoint listens on the port 7024 for me.

Host Name:- https://localhost:7024/

Endpoint: /api/item/handler

Install ngrok on dev machine

Use choclatey to install ngrok on local machine

choco install ngrok

Check the ngrok once installed

ngrok -v

IMP– Antivirus might block executing the ngrok. For me I had to turn off the real time scan. Do this at your own risk based on your antivirus software this might be different.

Execute ngrok http command to listen to the api endpoint-

ngrok http --host-header="localhost:7024" https://localhost:7024

In this example https://1a319cf7d867.ngrok.app should forward request’s to https://localhost:7024 where the Web Api is running on my local machine.

Also note the Web Interface – http://127.0.0.1:4040/

Create a Webhook Handler

Navigate to /sitecore/system/Webhooks and create a webhook handler. In this case will create a item:saved handler.

In the newly created handler select the event the webhook should trigger and call the endpoint created by nrgok (i.e. web api)

Setup the rule – “where the item is the Home item or onle of its descendants”

Means Home or any of its child items when saved this event will be triggered.

Also setup the Url the webhook should call when this event fires.

IMP – Ensure the handler is enabled or it won’t fire the event.

Save the Home or any of its child to fire the event

I changed a field in Home item and Saved the item-

Ensure your Web Api solution is running in debug mode.

And now you should be able to debug, inspect and test the handler. This was done in local Sitecore instance but can also be done in XM Cloud.

ngrok helps to forward the requests to the localy hosted web api running in debug mode.

Now you can handle what should happen on item:saved event.

XM Cloud

I did the same process in XM Cloud-

Updated the Home item and Saved. Note the item id

The event is fired and web api in my local machine is called-

Also the ngrok also shows the calls it is listening.

Web interface should also show the request and payload details-

Hope this helps debuging your Webhook requests fired from Sitecore local or XM Cloud.

If you want to see the webhook payload and perform further actions, like sending mails etc there are online tools availabl e-

https://webhook.site/

https://zapier.com/

https://hookdeck.com/

https://ifttt.com/

Hope this helps.

Loading

Setting up a Sitecore JSS development environment with the Containers template for Next.js

Follow steps in this link —

https://doc.sitecore.com/xp/en/developers/hd/211/sitecore-headless-development/walkthrough–setting-up-a-development-environment-with-the-sitecore-containers-template-for-next-js.html

Following are thre pre-requisite for setting on your local machine-

Apart from this also install Sitecore JSS CLI-

npm install -g @sitecore-jss/sitecore-jss-cli

Install the template

dotnet new -i Sitecore.DevEx.Templates --nuget-source https://sitecore.myget.org/F/sc-packages/api/v3/index.json

dotnet new sitecore.nextjs.gettingstarted -n samplejss

Should first Restores dotnet local tools for the solution and Initializes the JSS project

What is your Sitecore hostname (used if deployed to Sitecore)? (samplejss.dev.local) << leave blank or provide the host name>>

How would you like to fetch Layout and Dictionary data? 
GraphQL
REST

How would you like to prerender your application?
SSG
SSR

Which additional language do you want to support (en is already included and required)? << leave blank or type the language you want. should select da-DK by default and additional language>>

JSS application is now ready and updated for continerized environment.

Navigate to project folder and initialize the environment.

.\init.ps1 -InitEnv -LicenseXmlPath "<C:\path\to\license.xml>" -AdminPassword "<desired password>"
setx NODE_EXTRA_CA_CERTS C:\Users\sandeep\AppData\Local\mkcert\rootCA.pem

Execute up.ps1 to create containers-

.\up.ps1

Error-

CM is not coming up-

Checked the docker logs, and found this error-

The path is not set correctly. Need to escape the characters-

Resolution-

Change – entrypoint: powershell.exe -Command “& C:\tools\entrypoints\iis\Development.ps1” to entrypoint: powershell.exe -Command “& C:\\tools\\entrypoints\\iis\\Development.ps1” in docker-compose.override.yml file for xm1, xp0 and xp1

Take down all the containers and build again.

Now this should look fine-

Enter CM admin credentials and allow the access-

CM and App should load –

As of writing this post, this setup installed Sitecore 10.3.

Loading

Setup Sitecore Headless SXA with Next js

Pre-requisite-

Install Sitecore 10.3 XP0 on local machine – see this blog to install the SIF way

Install Powersehll Extensions

Sitecore PowerShell Extension for Sitecore on your local Sitecore instance

Sitecore Headless Rendering 21.0.0

Install Sitecore Headless Services for Sitecore XP on your local Sitecore instance

See the Sitecore Headless Rendering 21.0.0 download page

Install SXA module –

Sitecore Experience Accelerator on your local Sitecore instance

See the Sitecore Experience Accelerator 10.3.0 dowload page

Once you have the above installed the local instance should have options to create a Headless Tenant and Folder

Ensure all the search index and rebuilt-

Install Node js Download | Node.js (nodejs.org). Latest whilst writing this blog was v18.14.0

Create a Headless Tenant

Select the Headless Tenant

Enter a valid tenant Name and the modules to install –

Should create a tenant successfully-

Create a Headless Site

Now create a Headless Site

Provide a valid Site name and other options-

Select the modules to install-

Keep the Site settings as is for now and will generate the deployment secret later-

Site should be crated within the tenant-

Setup the rendering host

Site Settings – Check for the rendering host- should have set to Default

/sitecore/content/mycompany/retail/Settings/Site Grouping/retail

Find the Default rendering host on this location-

/sitecore/system/Settings/Services/Rendering Hosts/Default

Server side rendering engine endpoint URL:- http://localhost:3000/api/editing/render

Server side rendering engine application URL:- http://localhost:3000

Application name:- e.g.:- retail-app

Where is the above value coming from – when a next js app is created by default it is hosted on port 3000. Please see section below- NEXT STEPS

Create JSS Api key

Navigate to this location to create API key- /sitecore/system/Settings/Services/API Keys

Provide a valid name-

Set the CORS and Allowed Controllers to all domains. Set this to *

Will need API key while setting up the next js app.

Install JSS globally

https://doc.sitecore.com/xp/en/developers/hd/200/sitecore-headless-development/install-the-jss-cli-globally.html

npm install -g @sitecore-jss/sitecore-jss-cli

Initialise JSS App

Refer following for various options –https://doc.sitecore.com/xp/en/developers/hd/210/sitecore-headless-development/the-jss-app-initializer.html

Use following command-

npx create-sitecore-jss --templates nextjs,nextjs-sxa --appName retail-app --hostName xp103.sc --fetchWith GraphQL

Possible values for templates arguments-

Base templatesnextjs. Other possible values-

Other templates

appName – enter the app name provided in the rendering host. See Setup the rendering host section

hostname– enter the hostname of the Sitecore instance

While installing following questions are asked-

? Where would you like your new app created? – provide the location to create a next jss app

? How would you like to prerender your application? – Select SSG

Understand the pre-rendering to select. In this case I have selected SSG option.

https://doc.sitecore.com/xp/en/developers/hd/190/sitecore-headless-development/prerendering-methods-and-data-fetching-strategies-in-jss-next-js-apps.html

https://doc.sitecore.com/xp/en/developers/hd/210/sitecore-headless-development/switch-the-pre-rendering-method-in-a-jss-next-js-app.html

Following files will be created in a new folder (retail-app) –

Setup JSS app-

see this link- https://doc.sitecore.com/xp/en/developers/hd/190/sitecore-headless-development/start-a-jss-app-in-disconnected-mode.html

Setup the JSS app-

jss setup

Following options are asked, provide the required details-

Is your Sitecore instance on this machine or accessible via network share? [y/n]: y

Path to the Sitecore folder (e.g. c:\inetpub\wwwroot\my.siteco.re): C:\inetpub\wwwroot\XP103.sc

Sitecore hostname (e.g. http://myapp.local.siteco.re; see /sitecore/config; ensure added to hosts): https://xp103.sc

Sitecore import service URL [https://xp103.sc/sitecore/api/jss/import]: [Leave blank]

Sitecore API Key (ID of API key item): B418AB1D-A7A9-48F4-9A96-51F7D6C2105F [enter the api key created earlier- see section Create JSS Api key ]

Please enter your deployment secret (32+ random chars; or press enter to generate one): [Leave this blank and it should create one or enter the value here]

See the highlighted values. Also note the where the deployment secret is written-C:\projects\Sitecore\HeadlessSXA\retail-app\sitecore\config\retail-app.deploysecret.config

NEXT STEPS

Remove/Comment the site definition in this case as opposed to JSS sites as this will be handled in Sitecore site settings-

Remove it from /sitecore/config/retail-app.config

Verify JSS app registration-

See the values of Endpoint Url and Application URL. The same url was configured in rendering host.

Set JSS Editing Secret in .env file- Use the deployment secret from the /sitecore/config/app-name.deploysecret.config

Deploy config

jss deploy config

Note the config was deployed to C:\inetpub\wwwroot\XP103.sc\App_Config\Include\zzz folder in the Sitecore instance

Start Application in connected mode

jss start:connected

Application should listen to http://localhost:3000

Try accessing – http://localhost:3000

Errors:-

Solution

$env:NODE_TLS_REJECT_UNAUTHORIZED=0

Error-

Solution-

Search for root item in code- open \src\lib\dictionary-service-factory.ts

Error- Page not found

Solution – Ensute the site and the app name is same.

After all the above errors, it should show the blank page- Since there are no component s added.

Lets add some content, for this opne the Home page in experienec editor and see this error-

Error- Connection to your rendering host failed with an Unauthorized error. Ensure the JSS Editing Secret is configured.

Update the JSS Editing Secret in Sitecore instance at following path (best practice-you have to patch the config instead of updating the Sitecore configs directly)

App_Config\Sitecore\JavaScriptServices\Sitecore.JavaScriptServices.ViewEngine.Http.config

Update the value to the deployment secret used earlier in .env file-

After update-

Finally we can see the experience editor-

Add some content –

Save and Publish

Finally we have next js app showing the content- on localhost:3000

Layout Services

Lets check if the layout services are accessible-

Get Item data (home) and secret key-

https://xp103.sc/sitecore/api/layout/render/jss?item={40A111E6-6B4D-41D5-BA0D-FD993C5D00E4}&sc_apikey={B418AB1D-A7A9-48F4-9A96-51F7D6C2105F}

Graphql

https://xp103.sc/sitecore/api/graph/edge/ui?sc_apikey={B418AB1D-A7A9-48F4-9A96-51F7D6C2105F}

Loading

Sitecore Asp.Net rendering with Content Resolver for Helix Examples Solution

In my previous post we saw how to create a simple rendering with data source.

For creating rendering using content resolver first follow the blog <<enter blog url here>>

Content resolvers help provice more complex data beyond the serialization of a component data source.

In this blog will list all the Articles on the page which are marked as Featured Article.

The custom logic for filtering will go in Content resolver.

Craete a project for Content Resolver(.net framework 4.8) . This framework is used just to follow with the exisitng content resolvers provided by Helix Examples Solution.

Content Resolver Project (BasicCompany.Feature.Articles.Platform)

Create a new .Net Framework project

Instead of creating new poroject I will copy the project from Navigation/Platform folder and rename it to BasicCompany.Feature.Articles.Platform.

Delete all the files from this project as it relates to Navigation. You may also want to change the AssemblyName and the AssemblyInfo file.

Create Models for Articles and Article

Create Models Folder and add below models

Articles.cs

using Sitecore.Data.Items;
using System.Collections.Generic;

namespace BasicCompany.Feature.Articles.Models
{
    public class Articles
    {
        public Item ArticlesPage { get; set; }

        public IList<Article> ArticleItems { get; set; }
    }
}

Article.cs

using Sitecore.Data.Items;

namespace BasicCompany.Feature.Articles.Models
{
    public class Article
    {
        public Item Item { get; set; }

        public Item ItemData { get; set; }
        public string Url { get; set; }
    }
}

Create Service for ArticleBuilder and ArticleRootResolver

Create a new folder Services and following-

//IArticleBuilder
 public interface IArticleBuilder
    {
        Articles.Models.Articles GetArticles(Item contextItem);
    }
//ArticleBuilder 

 public class ArticleBuilder : IArticleBuilder
    {
        private readonly IArticleRootResolver _articleRootResolver;
        private readonly BaseLinkManager _linkManager;

        public ArticleBuilder(BaseLinkManager linkManager, IArticleRootResolver articleRootResolver)
        {
            _articleRootResolver = articleRootResolver;
            _linkManager = linkManager;
        }

        public Articles.Models.Articles GetArticles(Item contextItem)
        {
            var articleRoot = _articleRootResolver.GetArticleRoot(contextItem);
            if (articleRoot == null)
            {
                return new Articles.Models.Articles();
            }

            return new Articles.Models.Articles()
            {
                ArticlesPage = articleRoot,
                ArticleItems = GetArticleItems(articleRoot, contextItem)
            };
        }

        private IList<Article> GetArticleItems(Item articleRoot, Item contextItem)
        {
            var items = new List<Item>();

            items.AddRange(articleRoot.Children.Where(item => item.DescendsFrom(Templates.ArticleItem.Id)));

            var articleItems = items.Select(item => new Article()
            {
                Item = item,
                ItemData = item.Axes.GetDescendants().FirstOrDefault(itemData => itemData.DescendsFrom(Templates.ArticleItemData.Id)),
                Url = _linkManager.GetItemUrl(item)
            }).ToList();

            return articleItems;
        }
    }
//IArticleRootResolver

 public interface IArticleRootResolver
    {
        Item GetArticleRoot(Item contextItem);
    }

namespace BasicCompany.Feature.Articles.Services
{
    public class ArticleRootResolver : IArticleRootResolver
    {
        public Item GetArticleRoot(Item contextItem)
        {
            if (contextItem == null)
            {
                return null;
            }
            return contextItem.DescendsFrom(Templates.ArticleRoot.Id)
                ? contextItem
                : contextItem.Axes.GetAncestors().LastOrDefault(x => x.DescendsFrom(Templates.ArticleRoot.Id));
        }
    }
}

Create Layout Service i.e. content resolver class

Create new folder LayoutServices and add following-

namespace BasicCompany.Feature.Articles.LayoutService
{
    public class ArticleContentResolver : Sitecore.LayoutService.ItemRendering.ContentsResolvers.RenderingContentsResolver
    {
        private readonly IArticleBuilder _articleBuilder;

        public ArticleContentResolver(IArticleBuilder articleBuilder)
        {
            _articleBuilder = articleBuilder;
        }

        public override object ResolveContents(Rendering rendering, IRenderingConfiguration renderingConfig)
        {
            var articles = _articleBuilder.GetArticles(this.GetContextItem(rendering, renderingConfig));

            var contents = new
            {
                ArticleItems = articles.ArticleItems.Select(item => new
                {
                    Item = item.Item,
                    ItemData = item.ItemData,
                    Serialized = base.ProcessItem(item.ItemData, rendering, renderingConfig)
                }).Select(article => new
                {
                    Url = LinkManager.GetItemUrl(article.Item),
                    Id = article.Item.ID,
                    Fields = new
                    {
                        Title = article.Serialized[article.ItemData.Fields["Title"].Name],
                        Description = article.Serialized[article.ItemData.Fields["Description"].Name],
                        ShortDescription = article.Serialized[article.ItemData.Fields["ShortDescription"].Name],
                    }
                })
            };

            return contents;
        }
    }
}

Create Service Configurator to register the services-

namespace BasicCompany.Feature.Articles
{
    public class ServicesConfigurator : IServicesConfigurator
    {
        public void Configure(IServiceCollection serviceCollection)
        {
            serviceCollection.AddTransient<Services.IArticleBuilder, Services.ArticleBuilder>();
            serviceCollection.AddTransient<Services.IArticleRootResolver, Services.ArticleRootResolver>();
        }
    }
}

Create Template Class

Change the Item ID’s as per your Sitecore Instance

namespace BasicCompany.Feature.Articles
{
  public static class Templates
  {
        public static class ArticleItem
        {
            public static readonly ID Id = new ID("{EE5CE126-890D-4F01-9DD5-3D81FC397A91}"); //
        }

        public static class ArticleItemData
        {
            public static readonly ID Id = new ID("{8AA19CA1-99A6-4588-B1D7-3FA9A8F6756A}"); //
        }

        public static class ArticleRoot
        {
            public static readonly ID Id = new ID("{A46A11C6-C7F9-4F61-BF0C-FFF060F0FECC}"); //
        }
  }
}

Create App Config to register the ServiceConfigurator-

Create Feature.Articles.config file in App_Config/Include/Feature folder

<?xml version="1.0"?>

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <services>
      <configurator type="BasicCompany.Feature.Navigation.ServicesConfigurator, BasicCompany.Feature.Navigation" />
    </services>
  </sitecore>
</configuration>

Create Templates for Article

These templates are used to indicate the different level s of Article. i..e Article Page- will inherit from _ArticleRoot, ArticlePage will inherit from _ArticleItem and Article Content will inherit from _ArticleItemData

Sitecore Items

Create Rendering Content Resolver

Create a New “Rendering Contents Resolvers Folder” in /sitecore/system/Modules/Layout Service

Craete a New “Rendering Contents Resolver” in this folder.

Provide the type – BasicCompany.Feature.Articles.LayoutService.ArticleContentResolver, BasicCompany.Feature.Articles

Create Articles Json Rendering

Craete a neJson rendering name “Articles” and newly created content resolver in the “Rendering Contents Resolver” field.

Add the new rendering to the page

Publish items

Rendering Project

Create Models Articles.cs

using Sitecore.AspNet.RenderingEngine.Binding.Attributes;
using Sitecore.LayoutService.Client.Response.Model.Fields;

namespace BasicCompany.Feature.Articles.Models
{
    public class Articles
    {
        [SitecoreComponentField]
        public ContentListField<Article> ArticleItems { get; set; }
    }
}

Create new view Articles.cshtml in /Views/Shared/Components/SitecoreComponent

@using Sitecore.AspNet.RenderingEngine.Extensions
@model BasicCompany.Feature.Articles.Models.Articles


<div class="container">
    <div class="product-list-columns columns is-multiline">
        @foreach (var article in Model.ArticleItems)
        {
            <partial name="_ArticleList" model="article" />
        }
    </div>
</div>

Create _ArticleList.cshtml in Views/Shared folder

Note its using ItemLinkField

@model ItemLinkField<Article>

<a href="@Model.Url" class="column product-list-column is-4-desktop is-6-tablet">
    <div class="card">
        <div class="card-content">
            <div class="content">
                <h4 asp-for="@Model.Fields.Title"></h4>
                <p asp-for="@Model.Fields.ShortDescription"></p>
            </div>
        </div>
    </div>
</a>

Update the RenderingEngineOptionsExtensions

namespace BasicCompany.Feature.Articles.Extensions
{
    public  static class RenderingEngineOptionsExtensions
    {
        public static RenderingEngineOptions AddFeatureArticle(this RenderingEngineOptions options)
        {
            options

                .AddModelBoundView<Article>("Article")
                .AddModelBoundView<Models.Articles>("Articles");
            return options;
        }
    }
}

Update Articles.modules.json to serialiaze content resolver

{
  "namespace": "Feature.Articles",
  "items": {
    "includes": [
      {
        "name": "templates",
        "path": "/sitecore/templates/Feature/Articles"
      },
      {
        "name": "renderings",
        "path": "/sitecore/layout/Renderings/Feature/Articles"
      },
      {
        "name": "contents-resolvers",
        "path": "/sitecore/system/Modules/Layout Service/Rendering Contents Resolvers/Articles"
      }
    ]
  }
}

IMP – Ensure the Startup.cs has AddFeatureArticle() added in AddSitecoreRenderingEngine

Output

List of Articles-

When we click on any of the Article take to the Article page-

The above pages are shown as per this structure in Sitecore

Configure Sitecore Content Serialization for ASP.Net Rendering with Helix Examples Solution

In this blog will creata a new component name Article in the Helix Examples Solution to demonstrate how to configure and use Sitecore Content Serlialization (SCS).

Assuming the Sitecore CLI is installed along with Sitecore.DevEx.Extensibility.SerializationSitecore.DevEx.Extensibility.Publishing plugins are installed.

For more details on the plugin installation please see this link- https://doc.sitecore.com/xp/en/developers/101/developer-tools/install-sitecore-command-line-interface.html

Open the helix-basic-aspnetcore folder in Visual Studio and see Sitecore.json file. This file has the configuration settings for SCS.

modules – willl look into the src folder for *.module.json file for any component specific configuration the items that need to be serialized.

So lets create a new module or rendering feature named “Articles”. Just a folder and not a project itself

1. Create a module json for serlialization configuration

IMP – Create Articles.module.json file in the project root folder

Add following to the json file-

{
  "namespace": "Feature.Articles",
  "items": {
    "includes": [
      {
        "name": "templates",
        "path": "/sitecore/templates/Feature/Articles"
      },
      {
        "name": "renderings",
        "path": "/sitecore/layout/Renderings/Feature/Articles"
      }
    ]
  }
}

Here the items that will be serliazed are templates and rendering from the given path in Sitecore to the local Solution Folder configured in Sitecore.json file the path mentioned in defaultModuleRelativeSerializationPath property. See step 1

IMP- Ensure the module file is in Articles folder. Your project folder should looks like this-

2. Create a Sitecore Template and Rendering for Articles

Create a Json Rendering for now(fill in the details later)

3. Sync the items (manual)

Execute following command to serlaize the items for Articles-

dotnet sitecore ser pull

Project folder should now have items folder with templates and rendering-

Thats it any Templates and rendering created for Articles (new component) should be serliazed.

Refer BasicCompany.module.json for any placeholders, layouts etc serlization at the project level.

Hope this helps.

Create a Asp.Net simple rendering using data source in Helix Examples Solution

In this blog will create a simple rendering uing Asp.Net Rendering SDK in Helix Examples Solution

Please refer the blog to create a rendering folder and configure the SCS before proceeding this blog.

So lets create a new module or rendering feature named “Articles”.

1. Create a Feature project using Razor Class Library

Project Name – BasicCompany.Feature.Articles.Rendering

Notice the project path

Choose .Net Core 3.1 Framework-

Delete any exisitng files and folders under this project-

Edit the project to use netcoreapp3.1 and AddRazorSupportForMvc to true

Rename helix-basic-aspnetcore\src\Feature\Articles\BasicCompany.Feature.Articles.Rendering to rendering. Just to follow other feature fodler structure.

2. Install Sitecore packages

Sitecore.AspNet.RenderingEngine

Sitecore.LayoutService.Client

I have installed verions 16 just to be in sync with other projects. You may install the latest.

New rendering project should have these packages installed-

Remove these packages as this may be not required at thi point of time or downgrade this to 3.1.1

Refer the new created rendering project to BasicCompany.Project.BasicCompany.Rendering

When the solution is build you may see this error-

Severity Code Description Project File Line Suppression State
Error The package reference ‘Sitecore.AspNet.RenderingEngine’ should not specify a version. Please specify the version in ‘C:\projects\Helix.Examples\examples\helix-basic-aspnetcore\Packages.props’ or set VersionOverride to override the centrally defined version. BasicCompany.Feature.Articles.Rendering C:\projects\Helix.Examples\examples\helix-basic-aspnetcore\src\Feature\Articles\rendering\BasicCompany.Feature.Articles.Rendering.csproj

Solution– Remove the version for the plugin fropm project file

Edit the project file and remove version from the PackageReference-

Solution should build successully.

3. Ensure Articles.modules.json file in Feature folder

Please see this blog <<Enter blog url here>> how to create a module.json file to serliaze the Sitecore items for new Feature.

4. Create required Sitecore Templates, content, renderings and Placeholder Settings

Template – Article in following path- /sitecore/templates/Feature/Articles

Page Type Template – Create 2 page type templates “Articles” and “Article” page as below.

Add any required Insert Options where necessary.

IMP- inherit from _NavigationItem to display the Articles as Navigation option

Enter Navigation Title for Articles page-

Content

Create content in Home page based on the Article templates created.

Rendering

Create a new Json Rendering Article. See previous post

Set Datasource Location- ./Page Components|query:./ancestor-or-self::*[@@templatename=’Site’]/Shared Content/Articles

Datasource Template- /sitecore/templates/Feature/Articles/Article

Add rendering to Template

Add Header, Article and Footer Controls to the Presentation

Select appropriate datasource for the Article component-

You can also add the component from experience editor. For simplicity purpose I am adding this from the presentation details manually.

Publish the changes and see https://www.basic-company-aspnetcore.localhost

Note:- If you get bad gateway error the resolution is in this blog <<blog for resolution>>

you should see the Articles option in Navigation-

Note- We wont be configuring “Articles” page in this blog. Will see that in next blog when uing Content Resolver.

See thie Article page-

https://www.basic-company-aspnetcore.localhost/Articles/Sitecore%20Content%20Serialization%20structural%20overview

There is a error – “Unknown component ‘Article'”. This is because we havent yet created view for this component.

Create Model in BasicCompany.Feature.Articles.Rendering project for rendering Article component

Note the propeties are using Sitecore.LayoutService.Client.Response.Model.Fields

using Sitecore.LayoutService.Client.Response.Model.Fields;
using System;
using System.Collections.Generic;
using System.Text;

namespace BasicCompany.Feature.Articles.Rendering.Models
{
    public class Article
    {
        public TextField Title { get; set; }

        public RichTextField Description { get; set; }

        public TextField ShortDescription { get; set; }
    }
}

Create View in BasicCompany.Feature.Articles.Rendering project for rendering Article component

Create Article.cshtml file under Views/Shared/Components/SitecoreComponent

Add following markup-


@model Article

<div class="container">
    <section class="hero is-small product-detail-hero">
        <div class="hero-body">
             <h3  class="title" asp-for="Title"></h3>
            <sc-text class="subtitle is-one-quarter" asp-for="Description"></sc-text>
        </div>
    </section>
</div>

InViews Folder create _ViewImports.cshtml file and put the following in file-

@using Sitecore.LayoutService.Client.Response.Model
@using Sitecore.LayoutService.Client.Response.Model.Fields
@using Sitecore.AspNet.RenderingEngine.Extensions
@using BasicCompany.Feature.Articles.Rendering.Models

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, Sitecore.AspNet.RenderingEngine

Add Extensions for registering the ModelBoundView. This is a static class and will be used in Project Rendering on application startup (BasicCompany.Project.BasicCompany.Rendering).

using BasicCompany.Feature.Articles.Rendering.Models;
using Sitecore.AspNet.RenderingEngine.Configuration;
using Sitecore.AspNet.RenderingEngine.Extensions;

namespace BasicCompany.Feature.Articles.Extensions
{
    public  static class RenderingEngineOptionsExtensions
    {
        public static RenderingEngineOptions AddFeatureArticle(this RenderingEngineOptions options)
        {
            options
                .AddModelBoundView<Article>("Article");            
            return options;
        }
    }
}

In BasicCompany.Project.BasicCompany.Rendering project, Startup.cs register the component-

Build the Project

Output– https://www.basic-company-aspnetcore.localhost/Articles/Sitecore%20Content%20Serialization%20structural%20overview

Issues

Bad gateway error while accessing – https://www.basic-company-aspnetcore.localhost/

Solution-

Restart the rendering container

docker ps
docker restart <<rebdering container>>

Debug Helix Examples solution using Asp.Net Rendering hosted in Docker Containers

See this blog to setup the development environment for Helix Examlpes using Docker

Open the solution from following location – \examples\helix-basic-aspnetcore

Open the containers tab and should list all the containsers with its status-

You may also use following command to check the status of contrianers-

docker ps

Lets debug the Navigation which has content resolver-

Right click the CD container and Attach to Process

Select Managed(.Net 4.x) debug type. Select w3wp.exe and click Attach.

Helix Examples Solution should now run in debug mode.

Build the solution, add a breakpoint to any of the resolvers (Header or Footer)

Refresh or visit the site – https://www.basic-company-aspnetcore.localhost/ and should be able to see the debugger-

Issues debuging or just building the solution-

Bad Gateway-

Solution- You may see the errors with command-

docker-compose logs -f rendering

Following log appears- binary is being used by another process. This is the issues with the dotnet watch with the docker

Solution- Restart the rendering container

This should bring up the site.

You can also watch the changes outside the docker. See here for more details-

https://sitecore.stackexchange.com/questions/29566/asp-net-core-rendering-sdk-every-time-i-have-to-run-docker-compose-restart-ren

Sitecore Headless Development with ASP.NET Rendering SDK – Helix Examples Solution – The Docker Way

This blog will give a quick overview of setting development environment for Headless Development with ASP.Net Rendering SDK using the Helix Examples and the docker.

Although there are videos and blogs around same I will do a quick walk through on setting Helix Examples and any errors I faced whilst setting up the environment.

Refer the following for same – https://github.com/Sitecore/Helix.Examples/tree/master/examples/helix-basic-aspnetcore

Install .Net Core 3.1

https://dotnet.microsoft.com/en-us/download/dotnet/3.1

Install .Net core 3.1 on your machine and this is required to create any rendering or platform projects later to extend the Helix Examples Solution or compiling the existing code.

Install Docker Desktop on Windows

https://docs.docker.com/desktop/windows/install/

Run this on Hyper-V mode and Switch to Windows Containers

Install Visual Studio Code and Visual Studio 2022 Community Edition

https://visualstudio.microsoft.com/vs/community/

https://code.visualstudio.com/download

Whilst installing Visual Studio 2022 select the .Net Framework project and templates option as the platform projects uses .Net Framework 4.8 version. This will also help further if you want to extend the solution.

Install and Configure Windows Terminal (optional)

https://docs.microsoft.com/en-us/windows/terminal/install

https://dev.to/shahinalam02/customize-your-terminal-using-oh-my-posh-theme-38if

https://www.hanselman.com/blog/my-ultimate-powershell-prompt-with-oh-my-posh-and-the-windows-terminal

Install Windows Terminal, refer above link and if you fancy applying the themes, although this is optional.

Install git

https://git-scm.com/download/win

Clone Helix Examples Solution

https://github.com/Sitecore/Helix.Examples

https://github.com/Sitecore/Helix.Examples.git

Initialise the config

Navigate to \examples\helix-basic-aspnetcore and run following-

.\init.ps1 -LicenseXmlPath C:\<<path to license>>\license.xml -SitecoreAdminPassword "b"

This should initalise teh .env file and fill in the values of the variables for License and Admin Password. Also it will populate other variables.

Build Images

Once the config are initialised run folowing command-

up.ps1

Once all the images are downloaded and built along with solution login to CM should will be asked.

Login to the CM and Allow access to Sitecore API and Offline Access

Once this done the CD and CM app should be ready along with the data been synched.

Check the logs for any errors in rendering with following command-

docker-compose logs -f rendering

Access Application

Site can be accessed with the following url –

Sitecore Content Management: https://cm.basic-company-aspnetcore.localhost/sitecore/

Sitecore Identity Server: https://id.basic-company-aspnetcore.localhost

Basic Company site: https://www.basic-company-aspnetcore.localhost

Use following to stop/remove containers-

docker compose down

Issues while building the images

Error response from daemon: Unrecognised volume spec: file ‘\\.\pipe\docker_engine’ cannot be mapped. Only directories can be mapped on this platform

Solution-

Disable Docker Compose V2 using command or in Docker Desktop-

docker-compose disable-v2

or Uncheck the “Use Docker Compose V2” option

https://stackoverflow.com/questions/68010612/error-response-from-daemon-unrecognised-volume-spec-file-pipe-docker-engi