Thursday, March 21, 2024

Sitecore Content Hub : Sending emails to a UserGroup - Part 2 : Creating Actions and Scripts

Sitecore Content Hub : Sending emails to a UserGroup - Part 2 : Creating Actions and Scripts

In Sitecore Content Hub, Actions are components that perform a specific task. These actions can either be manually triggered by a user via the User Interface, or automatically run by a trigger or via the APIs.

Integrating custom scripts into your business logic within Sitecore Content Hub can be a powerful way to extend functionality and automate processes.

For our use case to send email to a UserGroup, we are going to create a Script in Content Hub. The primary purpose of the script is to :

1.Create the Email Template in Content Hub

2.Fetch the members of the UserGroup who will be notified about the asset submitted for review.

3.Lastly, send the email notification to the members

To create a script:
  • Go the the Manage page, type 'scripts' in the search bar, and select Scripts:
  • Click + Script to add the Script.
  • Build the script for checking any errors and then Publish the script.
Below is the Script for our use case. Please feel free to update depending on your requirements. 


       using Stylelabs.M.Base.Querying;
using Stylelabs.M.Sdk.Contracts.Base;
using Stylelabs.M.Sdk.Contracts.Notifications;
using Stylelabs.M.Sdk.Models.Notifications;
using Stylelabs.M.Sdk.Extensions;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Threading.Tasks;
using System.Linq;

const string emailTemplatename = "Asset Activity Notification - submitted for review and approval";

await SendEmailAsync();

public async Task SendEmailAsync()
{
    var emailTemplate = await MClient.Notifications.GetMailTemplateEntityAsync(emailTemplatename);
    if(emailTemplate == null){
        await CreateEmailTemaplateAsync();
        emailTemplate = await MClient.Notifications.GetMailTemplateEntityAsync(emailTemplatename);
    }
    var userGrp = MClient.Users.GetUserGroupAsync("Activity Email Group").Result.Id;

    var query = Query.CreateQuery(entities =>
    from e in entities
    where e.DefinitionName == "User"
    select e);
    var iterator = MClient.Querying.CreateEntityIterator(query, new EntityLoadConfiguration { RelationLoadOption = RelationLoadOption.All});
    var groupUsers = new List();
    var parents = "";

    while (await iterator.MoveNextAsync().ConfigureAwait(false))
    {
        foreach (var users in iterator.Current.Items)
        {
            var user = await MClient.Entities.GetAsync((long)users.Id);
            var groupRelation = user.GetRelation("UserGroupToUser");

                foreach(var parent in groupRelation.Parents){
                    parents = parents +  " , " + parent;
                    if (parent == userGrp) 
                    {
                        groupUsers.Add(user);
                    }
                }
        }
    }


            
    var userNames = MClient.Users.GetUsernamesAsync(groupUsers.Select(i => i.Id ?? 0).ToList()).Result?.Select(i => i.Value).ToList();
    var emailRecipients = new List();
    var entityModified = Context.Target as IEntity;
    foreach(var username in userNames){
    if(!emailRecipients.Contains(username)){
        emailRecipients.Add(username);
        MClient.Logger.Info($"Username added  {username}  entity {entityModified.Id}");

    }
    else{
        MClient.Logger.Info($"Username already added  {username}");

        }
    }
    var notificationRequest = new MailRequestByUsername
    {
        MailTemplateName = emailTemplatename,
        Recipients = emailRecipients
    };

    notificationRequest.Variables.Add("AssetUrl", "https://ghd-p-001.sitecorecontenthub.cloud/en-us/asset/"+entityModified.Id);
    await MClient.Notifications.SendEmailNotificationAsync(notificationRequest);
}


public async Task CreateEmailTemaplateAsync()
{
var enUs = CultureInfo.GetCultureInfo("en-US");
var entity = await MClient.EntityFactory.CreateAsync(Constants.MailTemplate.DefinitionName);
var template = MClient.TypedEntityFactory.FromEntity(entity);
template.Name = emailTemplatename;
template.Subject[enUs] = "Asset Activity Notification - Submitted for review and approval";
template.Description[enUs] = emailTemplatename;
template.Body[enUs] = "Hello {{Username}}, The following asset has been submitted for review and approval: {{AssetUrl}}";
template.SetPropertyValue("M.Mailing.TemplateLabel", enUs, emailTemplatename);
template.SetTemplateVariables(new []
    {
        new TemplateVariable
        {
            Name = "AssetUrl",
            VariableType = TemplateVariableType.String
        },
        new TemplateVariable
        {
            Name = "Username",
            VariableType = TemplateVariableType.String
        }
    });
await MClient.Entities.SaveAsync(template);
}


The next step is to create an Action and then link the Action to the script.
  • On the menu bar, click Manage cog icon.
  • On the Manage page, click Actions.
  • On the Actions page, click New Action.
  • In the New action dialog, select an Action type and provide other details as needed.
  • Click Save.






Sitecore Content Hub : Sending emails to a UserGroup - Part 1

Sitecore Content Hub : Sending emails to a UserGroup - Part 1

Planning to create triggers in Content Hub for sending emails automatically when an Asset is created or submitted for approval or deleted?

This article goes through the steps in details to setup automatic emails for activities on Asset. These email notifications are not enabled in Content Hub by default, however this is highly important for the authors and approvers who are managing multiple assets in Content Hub on a daily basis.



Creating triggers in Content Hub to automatically send emails when certain events occur, such as asset submission for approval, deletion, or creation, can be a powerful way to streamline communication and workflow processes. Here's a general outline of how you might set up these triggers:
  • Define Trigger Events: Determine which events should trigger an email notification. For example, you would like to trigger emails for asset submission for approval, deletion, and creation.
  • Configure Email Templates: Create email templates for each type of notification. These templates should include dynamic fields to personalize the email content, such as the asset name, submitter's name, etc.
  • Map Trigger Events to Email Templates: Associate each trigger event with the corresponding email template. Ensure that the necessary information is included in the email content to provide context for the recipient.
  • Test Triggers: Before deploying the triggers in a production environment, thoroughly test each trigger to ensure they are working as expected. This will help identify any potential issues or errors that need to be addressed.
  • Deploy Triggers: Once testing is complete and everything is functioning correctly, deploy the triggers in your Content Hub environment.
  • Monitor and Maintain: Regularly monitor the triggers to ensure they continue to work properly. Make any necessary adjustments or updates as your workflow evolves.By setting up triggers in Content Hub to automatically send emails based on specific events, you can streamline communication and notification processes, improving efficiency and ensuring timely responses to important events.
We cover the technical details on how to configure sending the emails in the next part of the article and below are the links to it. We cover 
  • creating Scripts and Actions in Content Hub in Part 2 of the article
  • creating the Trigger in Part 3 and associating the trigger with the action and script created in Part 2 of the article.

Special mention to Vasiliy Fomichev for his blog on sending emails in Sitecore Content Hub as it helped me quite a lot in configuring the email Scripts.
Reference : https://www.cmsbestpractices.com/how-to-send-emails-in-sitecore-content-hub/



  1. Sitecore Content Hub : Sending emails to a UserGroup - Part 2 : Creating Action

Sitecore Content Hub : Sending emails to a UserGroup - Part 3 : Creating Trigger

Sitecore Content Hub : Sending emails to a UserGroup - Part 3 : Creating Trigger

The Sitecore Content Hub provides you with a trigger framework that allows you to configure triggers using the user interface. A trigger is fired when a specified event occurs under specified conditions. When the trigger fires, it can initiate a set of actions.

Here are the steps outlined for creating the trigger and setting up the conditions on when the trigger will be reacting, and finally setting up what the trigger action will be.
  • Create Triggers:
    • Open the Sitecore Content Hub. On the ribbon, click Manage.

    • Click Triggers, and click New trigger.

    • On the General tab, enter the following values:

      Field

      Value

      Enter a name

      Submit Asset for Review Email Trigger

      Enter a description

      Send emails to Approver User group once Asset is submitted for review

      Objective

      Entity modification

      Execution type

      In background



We need to assess while creating the trigger on what the objective will be: For our use case, we have chosen Entity modification since we want the trigger to reach when any entity is modified.
  • Entity creation - use if you want the trigger to react when any entity is created.
  • Entity modification - use if you want the trigger to react when any entity is modified.
  • Entity deletion: -use if you want the trigger to react when any entity is deleted.
You also need to specify the trigger execution type, which is the method with which the trigger's actions execute. For this use case, we are selecting "in background"
  • In Background: trigger actions execute using an asynchronous background job. With this execution type, trigger actions can only execute during the post phase (that is, after the trigger's event takes place).

  • On the Conditions tab, click Add definition, and in the drop-down list, click Asset (M.Asset). And then add the following definitions:
  • Using the below definitions, we are setting the rule that if the Final lifecycle status of the Asset changes to UnderReview from Created / Archived/ Approved, then the trigger will perform the action mentioned in the next step.
  • On the Actions tab, add the action you created previously (Send Asset Submitted Email).
  • Click Save and close. Confirm to activate the trigger.