Try our conversational search powered by Generative AI!

Oskar Zetterberg
May 2, 2024
  198
(1 votes)

Adding market segment for Customized Commerce 14

Since v.14 of commerce, the old solution for adding market segment to the url is not working anymore due to techinal changes of .NET Core. There is a post about adding market segment to Commerce 14 but that is about CMS and never got around with the commerce part. In that post Johan Björnfot added a comment suggesting using IContentUrlGeneratorEvents (thanks for the tip) and that is the approach I have used in my solution. No route mappings or overrides of internal components is needed.

In an initialization class add two methods and attach them to the url generator events :

public void Initialize(InitializationEngine context)
{
    var urlGeneratorEvents = context.Locate.Advanced.GetInstance<IContentUrlGeneratorEvents>();
    urlGeneratorEvents.GeneratedUrl += OnGeneratedUrl;

    var urlResolverEvents = context.Locate.Advanced.GetInstance<IContentUrlResolverEvents>();
    urlResolverEvents.ResolvingUrl += OnResolvingUrl;
}

private void OnGeneratedUrl(object sender, UrlGeneratorEventArgs e)
{
}

private void OnResolvingUrl(object sender, UrlResolverEventArgs e)
{
}

OnGeneratUrl, responsible for adding the market segment to the url.

private void OnGeneratedUrl(object sender, UrlGeneratorEventArgs e)
{
    // Validate if the url is a relative url and if it is a media file which we will not handle
    if (e.Context.Url.Path.StartsWith("/") && !IsMedia(e.Context.Url.Path))
    {
        var segments = e.Context.Url.Path.Split(new [] { '/' }, StringSplitOptions.RemoveEmptyEntries);

        // More validation, if the url does not contain any / or if the first segment have greater length then 2 then we consider it to be a non language
        if (segments.Length < 1 || segments[0].Length > 2)
        {
            return;
        }

        var currentUrlMarketSegment = segments.Length > 1 ? segments[1] : null;

        // Get the market, could be with ICurrentMarket or cookie value. Where ever the current market is stored or can be retrieved by current language
        var marketSegment = GetMarketSegment(e.Context.Language, currentUrlMarketSegment);
        
        if (!string.IsNullOrEmpty(marketSegment))
        {
            var langMarketArg = $"/{segments[0]}/{marketSegment}/";

            if (!e.Context.Url.Path.StartsWith(langMarketArg))
            {
                var languageArg = $"/{segments[0]}/";

                // Validate if market segment already exists in the current url. If so, add that to part to be replaced.
                // AvailableMarketSegments just returns all available segments as a string array
                if (currentUrlMarketSegment != null && currentUrlMarketSegment.Length == 2 && AvailableMarketSegments.Contains(currentUrlMarketSegment))
                {
                    languageArg += $"{currentUrlMarketSegment}/";
                }

                // Note, this value will be cached by Optimizley. That is why we need to check an existing market segment above.
                e.Context.Url.Path = e.Context.Url.Path.Replace(languageArg, langMarketArg);
            }
        }
    }
}

OnResolvingUrl, responsible for removing the market segment from the url so the "normal" url resolving can take place.

private void OnResolvingUrl(object sender, UrlResolverEventArgs e)
{
    // Skip if url is media
    if (IsMedia(e.Context.Url.Path))
    {
        return;
    }

    var segments = e.Context.Url.Path.Split(new [] { '/' }, StringSplitOptions.RemoveEmptyEntries);
    
    if (segments.Length >= 2)
    {
        // Validate if segments are valid language and valid market and replace incoming segments with language only to let Optimizley resolve it internally
        if (AvailableLanguageSegments.Contains(segments[0]) && AvailableMarketSegments.Contains(segments[1]))
        {
            var replaceArg = segments[0] + "/" + segments[1] + "/";
            e.Context.RemainingSegments = e.Context.RemainingSegments.ToString()
                .Replace(replaceArg, segments[0] + "/", StringComparison.OrdinalIgnoreCase).AsMemory();
            e.Context.Url = new Url(e.Context.Url.Uri.OriginalString.Replace(replaceArg, segments[0] + "/"));
        }
    }
}

Take note, as markets are contextual, using the UrlResolver it will resolve market from the current context. So if you are storing urls in some searchindex or something like that, make sure you handle the urls accordingly. We are for example storing urls without language- and market segment and are adding those in the correct context when requested.

The code can for sure be optimized and improved. Comment with suggestions.

Hope this will be to use for someone.

May 02, 2024

Comments

Please login to comment.
Latest blogs
The downside of being too fast

Today when I was tracking down some changes, I came across this commit comment Who wrote this? Me, almost 5 years ago. I did have a chuckle in my...

Quan Mai | May 17, 2024 | Syndicated blog

Optimizely Forms: Safeguarding Your Data

With the rise of cyber threats and privacy concerns, safeguarding sensitive information has become a top priority for businesses across all...

K Khan | May 16, 2024

The Experimentation Process

This blog is part of the series -   Unlocking the Power of Experimentation: A Marketer's Insight. Welcome back, to another insightful journey into...

Holly Quilter | May 16, 2024

Azure AI Language – Sentiment Analysis in Optimizely CMS

In the following article, I showcase how sentiment analysis, which is part of the Azure AI Language service, can be used to detect the sentiment of...

Anil Patel | May 15, 2024 | Syndicated blog