Monthly User Notifications in Content Hub: How They Work and How to Customize Them.

Hello Sitecorians! 👋


Welcome to another exciting blog!


How many people actually used your Content Hub last month? And how many of them uploaded something? Business owners ask these questions all the time, and Content Hub has no built-in monthly report that emails the answer.


On our project, we solved this with a small Monthly User Notifications job: once a month, it counts the active users and the "power users" (people who uploaded assets), and emails the numbers to a list of stakeholders using a Content Hub mail template.


In this blog, I'll walk you through how it works end to end, the pieces involved (an Azure Durable Function, the Web SDK and a mail template), and how you can customize it for your own needs. I'll also share a few lessons we learned along the way.


So, let's get started! 😊


The Use Case

Every month, send an email to the platform owners with the number of active users (people who signed in during the last month) and power users (people who created at least one asset during the last month).


The job must run on its own, survive large numbers of users and assets, and use the same email look and feel as other Content Hub notifications.


How It Works End to End

A timer starts an Azure Durable Function once a month; it counts users with two Content Hub queries and sends the numbers through a Content Hub mail template.


  1. Timer trigger. A timer function fires on a schedule from the app settings (for example 08:00 UTC on the 1st) and starts an orchestration.
  2. Orchestrator. It sets one cut-off date (one month ago) and calls the activities, with retries.
  3. Active users. An activity queries the User definition for users whose LastLoginDateTime is after the cut-off and reads the total.
  4. Power users. Another activity queries M.Asset for assets created after the cut-off, in batches, and returns the IDs of their creators. The orchestrator keeps the distinct IDs.
  5. Email. For each recipient, a send activity fills a Content Hub mail template with the numbers and sends it through the Web SDK's notifications client.


Why a Durable Function and not a Content Hub script? Scripts are triggered by entity events and have a short time limit; a scheduled job that pages through every asset of a month needs a scheduler, retries and no time pressure. Durable Functions give you all three, and you only write the steps.


Step 1: Create the Mail Template


The email itself is a Content Hub mail template, so admins can change the wording without a deployment.


Go to Manage → Email templates and create a template, for example UsageReport, with these variables:


Variable

Type

Used for

MailSubject

String

The subject line

BodyTitle

String

The heading in the email

BodyDescription

String

The numbers

EnvironmentName

String

Which environment sent it (DEV, QA, PROD)


In the body, use the variables like {{BodyTitle}} and {{BodyDescription}}, and set the subject to {{MailSubject}}.


Tip: We reuse one generic "system alert" template for several jobs (this report, script error alerts and so on). Each job only fills different variables. One template, one look, less to maintain.



Step 2: Write the Durable Function


The job has four parts: a timer that starts it, an orchestrator that coordinates, activities that query Content Hub, and an activity that sends the email.


The timer and the orchestrator:


public class MonthlyUsageReport { private readonly IWebMClient _client; private readonly ILogger<MonthlyUsageReport> _logger; public MonthlyUsageReport(IWebMClient client, ILogger<MonthlyUsageReport> logger) { _client = client; _logger = logger; } [FunctionName("MonthlyUsageReport_Timer")] public async Task Start( [TimerTrigger("%MonthlyUsageReport_Schedule%")] TimerInfo timer, [DurableClient] IDurableOrchestrationClient starter) { // Read settings here, not in the orchestrator: orchestrators must be deterministic. var input = new ReportInput { Recipients = (Environment.GetEnvironmentVariable("MonthlyUsageReport_Recipients") ?? "") .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries), EnvironmentName = Environment.GetEnvironmentVariable("ContentHub_EnvironmentName") }; var id = await starter.StartNewAsync("MonthlyUsageReport_Orchestrator", input); _logger.LogInformation("Started monthly usage report {InstanceId}", id); } [FunctionName("MonthlyUsageReport_Orchestrator")] public async Task Orchestrate([OrchestrationTrigger] IDurableOrchestrationContext context) { var input = context.GetInput<ReportInput>(); var retry = new RetryOptions(TimeSpan.FromSeconds(30), maxNumberOfAttempts: 3); // One cut-off for every activity, from the replay-safe clock. var since = context.CurrentUtcDateTime.AddMonths(-1); var activeUsers = await context.CallActivityWithRetryAsync<long>("CountActiveUsers", retry, since); // Distinct creators across ALL batches, not per batch. var creators = new HashSet<long>(); const int batchSize = 500; for (var skip = 0; ; skip += batchSize) { var batch = await context.CallActivityWithRetryAsync<CreatorBatch>( "GetAssetCreators", retry, new CreatorQuery { Since = since, Skip = skip, Take = batchSize }); if (batch.ItemCount == 0) break; creators.UnionWith(batch.CreatorIds); } // Fan out: one email activity per recipient, in parallel. await Task.WhenAll(input.Recipients.Select(recipient => context.CallActivityWithRetryAsync("SendUsageReport", retry, new UsageReport { Recipient = recipient, EnvironmentName = input.EnvironmentName, ActiveUsers = activeUsers, PowerUsers = creators.Count }))); } }


The activities that query Content Hub:

[FunctionName("CountActiveUsers")]
public async Task<long> CountActiveUsers([ActivityTrigger] DateTime since)
{
    var query = Query.CreateQuery(entities => from e in entities
                                              where e.DefinitionName == "User"
                                                    && e.Property("LastLoginDateTime") > since
                                              select e);
    query.Take = 1; // we only need the total, not the users
    var result = await _client.Querying.QueryAsync(query, EntityLoadConfiguration.Minimal);
    return result.TotalNumberOfResults;
}

[FunctionName("GetAssetCreators")]
public async Task<CreatorBatch> GetAssetCreators([ActivityTrigger] CreatorQuery input)
{
    var since = input.Since;
    var query = Query.CreateQuery(entities => from e in entities
                                              where e.DefinitionName == "M.Asset" && e.CreatedOn > since
                                              select e);
    query.Skip = input.Skip;
    query.Take = input.Take;
    var result = await _client.Querying.QueryAsync(query, EntityLoadConfiguration.Minimal);

    // No try/catch that swallows errors: let the activity fail so the retry policy can work.
    return new CreatorBatch
    {
        ItemCount = result.Items.Count,
        CreatorIds = result.Items.Where(e => e.CreatedBy.HasValue).Select(e => e.CreatedBy.Value).Distinct().ToList()
    };
}


The activity that sends the email:

[FunctionName("SendUsageReport")]
public async Task SendUsageReport([ActivityTrigger] UsageReport report)
{
    var userId = await _client.Users.GetUserIdAsync(report.Recipient);
    if (userId == null)
    {
        _logger.LogWarning("Recipient {Recipient} is not a Content Hub user", report.Recipient);
        return;
    }

    var mail = new MailRequestById { MailTemplateName = "UsageReport" };
    mail.Variables.Add("MailSubject", $"Monthly usage – {report.EnvironmentName}");
    mail.Variables.Add("BodyTitle", "Monthly usage");
    mail.Variables.Add("BodyDescription", $"Active users: {report.ActiveUsers}, power users: {report.PowerUsers}");
    mail.Variables.Add("EnvironmentName", report.EnvironmentName);
    mail.Recipients.Add(userId.Value);

    await _client.Notifications.SendEmailNotificationAsync(mail);
}


The small DTOs (ReportInput, CreatorQuery, CreatorBatch, UsageReport) are plain classes with the properties used above. The code uses the Content Hub Web SDK (Stylelabs.M.Sdk.WebClient) and Durable Functions in the in-process model; check the method names against the SDK version you use.


Step 3: Configure the Schedule and Recipients


Everything that changes per environment lives in the Function App settings, not in code:

Setting

Example

Meaning

MonthlyUsageReport_Schedule

0 0 8 1 * *

08:00 UTC on the 1st of every month (six-field NCRONTAB)

MonthlyUsageReport_Recipients

owner1@company.com,owner2@company.com

Who gets the email (Content Hub users)

ContentHub_EnvironmentName

PROD

Shown in the subject and body



The %MonthlyUsageReport_Schedule% syntax in the timer reads the schedule from that setting, so you can change it per environment without a deployment.



How to Customize It


Once the pattern is in place, most changes are small:

  • Add a metric. Write one more activity (assets uploaded, downloads, new users), call it from the orchestrator, and add the number to BodyDescription or to a new template variable.
  • Change the period. Pass a different cut-off, for example AddDays(-7) for a weekly report, and change the schedule.
  • Change the wording or design. Edit the mail template in Content Hub. No code change needed.
  • Change the audience. Edit the recipients setting, or look up the members of a user group instead of a fixed list.
  • Report per brand or region. Add a filter to the queries and send one email per group, using the same fan-out.


It's Working! 🎉


You don't want to wait a month to see the email, so test it like this:

  1. In a dev environment, set MonthlyUsageReport_Schedule to run every few minutes, for example 0 */5 * * * *.
  2. Put only your own email in MonthlyUsageReport_Recipients.
  3. Watch the orchestration in the Function App logs, or in the Durable Functions monitor.
  4. Check the email, then compare the numbers with a quick search in Content Hub (users who signed in, assets created in the period).
  5. Set the schedule back to monthly before you deploy.


Conclusion


Content Hub doesn't ship a monthly usage email, but you can build one with three things you probably already have: the Web SDK for the queries, a mail template for the message, and a Durable Function on a schedule. Keep the numbers in activities, the schedule and recipients in settings, and the wording in the template, and the report stays easy to change.



And that's a wrap! 🎉


I hope this helps you in your Content Hub journey! If you have any questions, feel free to drop a comment below. 😊


Stay tuned for more! 👋

Post a Comment (0)
Previous Post Next Post