logo
logo

Script Examples

The out-of-the-box scripts have been updated to use the Fluent SDK in the following samples.

CMP - Campaign - impact

using System.Linq;

var contentId = Context.TargetId;
if (!contentId.HasValue) 
{
    return;
}

var fluentClient = new FluentClient(MClient);

long? campaignId;
fluentClient.Entities
    .Get(contentId.Value)?
    .Parent("CampaignToContent", relation => campaignId = relation.Parent.Value);

if (!campaignId.HasValue) 
{
    // No parent found.
    return;
}

MClient.Logger.Info($"Calculate impact value for {campaignId.Value}");

// Load all impacts for each where used entity associated with this content Item
var entities = 
    fluentClient
        .UsePropertyLoadOption("Content.Impact")
        .QueryableEntities(entities => from e in entities where e.DefinitionName == "M.Content" && e.Parent("CampaignToContent") == campaignId.Value select e)
        .GetIterator()
        .IterateAll()
        .Items;

long totalImpact = 0;
foreach (var entity in entities)
{
    var impactValue = (long?)entity["Content.Impact"];
    totalImpact += impactValue.GetValueOrDefault(0);
}

// Load campaign item
fluentClient.Entities
    .Get(campaignId.Value)?
    .SetPropertyValue("Campaign.Impact", totalImpact)
    .Save();

MClient.Logger.Info($"Impact value calculated for campaign {campaignId.Value}");

CMP - Create public links for linked assets

using System.Linq;
using System.Threading.Tasks;

var assetId = Context.TargetId;
var fluentClient = new FluentClient(MClient);

// Check if public links don't exist yet
var result = await fluentClient
    .QueryableEntities(entities => from e in entities
        where e.DefinitionName == "M.PublicLink"
        && e.Parent("AssetToPublicLink") == assetId.Value
        && (e.Property("Resource") == "preview" || e.Property("Resource") == "downloadOriginal")
        && e.Property("IsDisabled") == false
        select e)
    .WithTake(1)
    .GetResults();
if (result.Count() > 0)
{
    MClient.Logger.Info($"Public links already exist for asset with id '{assetId}'");
    return;
}

// Create public links
await CreateForRendition("preview", assetId.Value);
MClient.Logger.Info($"Created public link 'preview' for asset with id '{assetId}'");

await CreateForRendition("downloadOriginal", assetId.Value);
MClient.Logger.Info($"Created public link 'downloadOriginal' for asset with id '{assetId}'");

async Task CreateForRendition(string rendition, long assetId)
{
    var publicLink = fluentClient.EntityFactory.Create("M.PublicLink");

    if (publicLink.Object.CanDoLazyLoading())
    {
        await publicLink.Object.LoadMembersAsync(new PropertyLoadOption("Resource"), new RelationLoadOption("AssetToPublicLink"));
    }

    var relation = publicLink.Object.GetRelation<IChildToManyParentsRelation>("AssetToPublicLink");
    if (relation == null)
    {
        MClient.Logger.Error("Unable to create public link: no AssetToPublicLink relation found.");
        return;
    }

    relation.Parents.Add(assetId);

    await MClient.Entities.SaveAsync(publicLink.Object);
    return;
}

CMP - M.Content - delete

using System.Linq;

long? campaignId;
long? contentImpact;
const string ContentImpact = "Content.Impact";
const string CampaignToContent = "CampaignToContent";
const string CampaignImpact = "Campaign.Impact";

var fluentClient = new FluentClient(MClient);

if (Context.ExecutionPhase == ExecutionPhase.Pre)
{
    var contentId = Context.TargetId;
    if (!contentId.HasValue)
    {
        return;
    } 

    contentImpact = (long?)fluentClient.Entities
        .Get(contentId.Value)
        .Parent(CampaignToContent, relation => {
            campaignId = relation.Parent.Value;
            MClient.Logger.Debug($"Calculate impact for campaign '{campaignId}'");

            if (!Context.PropertyBag.ContainsKey("CampaignId"))
            {
                Context.PropertyBag.Add("CampaignId", campaignId.ToString());
            }
        })[ContentImpact] ?? 0;

    if (!Context.PropertyBag.ContainsKey("ContentImpact"))
    {
        Context.PropertyBag.Add("ContentImpact", contentImpact.ToString());
    }
}

if (Context.ExecutionPhase == ExecutionPhase.Post)
{
    if (!long.TryParse(Context.PropertyBag["CampaignId"], out var id))
    {
        return;
    }

    campaignId = id;

    if (long.TryParse(Context.PropertyBag["ContentImpact"], out var impact))
    {
        // Load content item
        var campaignEntity = fluentClient.Entities.Get(campaignId.Value);
        if (campaignEntity == null)
        {
            MClient.Logger.Debug($"Campaign entity not found '{campaignId.Value}'");
            return;
        }

        var campaignImpact = (long?)campaignEntity[CampaignImpact] ?? 0;
        if (campaignImpact > 0 && campaignImpact - impact > 0)
        {
            campaignEntity
                .SetPropertyValue(CampaignImpact, campaignImpact - impact)
                .Save();

            MClient.Logger.Debug($"Impact value calculated for campaign '{campaignId.Value}'");
        }
    }
}

CMP - M.Content - impact

using System.Linq;

var usageId = Context.TargetId;
if (!usageId.HasValue)
{
    return;
}

MClient.Logger.Debug($"Calculate impact for '{usageId}'");

var fluentClient = new FluentClient(MClient);

long? contentId;
fluentClient.Entities
    .Get(usageId.Value)?
    .Parent("ContentToUsage", relation => contentId = relation.Parent.Value);

// Load all impacts for each usage entity associated with this content Item
ar entities = 
    fluentClient
        .UsePropertyLoadOption("Usage.Impact")
        .QueryableEntities(entities => from e in entities where e.DefinitionName == "M.Usage" && e.Parent("ContentToUsage") == contentId.Value select e)
        .GetIterator()
        .IterateAll()
        .Items;

long totalImpact = 0;
foreach (var entity in entities)
{
    var impactValue = (long?)entity["Usage.Impact"];
    totalImpact += impactValue.GetValueOrDefault(0);
}

//  Load content item
var contentEntity = fluentClient.Entities
    .Get(contentId.Value)
    .SetPropertyValue("Content.Impact", totalImpact)
    .Save();

MClient.Logger.Debug($"Impact value calculated for content '{contentId}'");

CMP - M.Usage - delete

using System.Linq;

long? contentId;
long? usageImpact;
const string ContentImpact = "Content.Impact";
const string ContentToUsage = "ContentToUsage";
const string UsageImpact = "Usage.Impact";

var fluentClient = new FluentClient(MClient);

if (Context.ExecutionPhase == ExecutionPhase.Pre)
{
    var usageId = Context.TargetId;
    if (!usageId.HasValue) 
    {
        return;
    }

    var usageEntity = fluentClient.Entities
        .Get(usageId.Value)
        .Parent(ContentToUsage, relation => contentId = relation.Parent.Value);

    MClient.Logger.Debug($"Calculate impact for content '{contentId.Value}'");

    if (!Context.PropertyBag.ContainsKey("ContentId"))
    {
        Context.PropertyBag.Add("ContentId", contentId.Value.ToString());
    }

    usageImpact = usageEntity.Object.GetPropertyValue<long?>(UsageImpact) ?? 0;
    if (!Context.PropertyBag.ContainsKey("UsageImpact"))
    {
        Context.PropertyBag.Add("UsageImpact", usageImpact.Value.ToString());
    }
}

if (Context.ExecutionPhase == ExecutionPhase.Post)
{
    if (!long.TryParse(Context.PropertyBag["ContentId"], out var id))
    {
        return;
    }

    contentId = id;

    if (long.TryParse(Context.PropertyBag["UsageImpact"], out var impact))
    {
        // Load content item
        var contentEntity = 
            fluentClient.Entities
                .Get(contentId.Value);
            
        if (contentEntity == null)
        {
            MClient.Logger.Debug("Content entity not found" + contentId.Value);
            return;
        }

        long contentImpact = (long?)contentEntity[ContentImpact] ?? 0;

        if (contentImpact > 0 && contentImpact - impact > 0)
        {
            contentEntity
                .SetPropertyValue(ContentImpact,contentImpact - impact)
                .Save();

            MClient.Logger.Debug($"Impact value calculated for content '{contentId.Value}'");
        }
    }
}

CMP - M.Usage - impact

using Newtonsoft.Json.Linq;

// Preferences
long reachFactor = 5;
long clicksFactor = 10;
long likesFactor = 20;
long commentsFactor = 30;
long sharesFactor = 50;

var usageId = Context.TargetId;
if (!usageId.HasValue) 
{
    return;
}

MClient.Logger.Info($"Calculating impact for entity '{usageId}'");

var fluentClient = new FluentClient(MClient);

var usageEntity = fluentClient.Entities
    .Get(usageId.Value);

var metrics = (JToken)usageEntity["Usage.Metrics"];

if (metrics == null) 
{ 
    MClient.Logger.Info("Metrics property not found"); 
    return; 
}

// Clicks
var clicks = (metrics.SelectToken("clicks")?.Value<long?>() ?? 0) * clicksFactor;

// Reach
var reaches = (
    metrics.SelectToken("reach")?.Value<long?>() ?? 0
    + metrics.SelectToken("connections")?.Value<long?>() ?? 0
) * reachFactor;

// Likes
var likes = (
    metrics.SelectToken("likes")?.Value<long?>() ?? 0
    + metrics.SelectToken("favorites")?.Value<long?>() ?? 0
    + metrics.SelectToken("+1s")?.Value<long?>() ?? 0
    + metrics.SelectToken("plusOnes")?.Value<long?>() ?? 0
) * likesFactor;

// Comments
var comments = (
    metrics.SelectToken("comments")?.Value<long?>() ?? 0
    + metrics.SelectToken("mentions")?.Value<long?>() ?? 0
    + metrics.SelectToken("replies")?.Value<long?>() ?? 0
) * commentsFactor;

// Shares
var shares = (
    metrics.SelectToken("shares")?.Value<long?>() ?? 0
    + metrics.SelectToken("retweets")?.Value<long?>() ?? 0
    + metrics.SelectToken("reshares")?.Value<long?>() ?? 0
    + metrics.SelectToken("repins")?.Value<long?>() ?? 0
) * sharesFactor;

var impact = reaches + clicks + shares + likes + comments;

if (impact == usageEntity.Object.GetPropertyValue<long>("Usage.Impact"))
{
    MClient.Logger.Info("Nothing to update");
    return;
}

usageEntity
    .SetPropertyValue("Usage.Impact", impact)
    .Save();

MClient.Logger.Info($"Recalculated impact for entity {usageEntity.Id}, new value: {impact}");

CMP - Update campaign publish dates

using System.Collections.Generic;
using System.Linq;

var campaignId = Context.TargetId;
var fluentClient = new FluentClient(MClient);
var contentIds = new List<long>();

var campaignEntity = fluentClient.Entities
    .Get(campaignId.Value)?
    .Children("CampaignToContent", relation => contentIds = relation.Children.ToList());

if (contentIds == null || !contentIds.Any())
{
    MClient.Logger.Info($"Campaign with id '{campaignId}' has no linked content to update.");
    return;
}

var campaignStartDateValue = campaignEntity.Object.GetPropertyValue<DateTime?>("Campaign.StartDate");
if (!campaignStartDateValue.HasValue)
{
    MClient.Logger.Warn($"Campaign with id '{campaignId}' does not have a start date.");
    return;
}

var contentEntities = fluentClient.Entities.GetMany(contentIds.ToArray());
if (contentEntities == null || !contentEntities.Any())
{
    MClient.Logger.Error("No entities found for ids: " + string.Join(", ", contentIds));
    return;
}

foreach (var contentEntity in contentEntities)
{
    var dynamicPublishDate = contentEntity.Object.GetPropertyValue<bool>("Content.DynamicPublishDate");

    MClient.Logger.Debug($"Content id: {contentEntity.Id }, DynamicPublishDate: {dynamicPublishDate}");

    if (dynamicPublishDate)
    {
        var daysFromCampaignStart = contentEntity.Object.GetPropertyValue<int>("Content.DaysFromCampaignStart");

        MClient.Logger.Debug($"Content id: {contentEntity.Id}, DaysFromCampaignStart: {daysFromCampaignStart}");

        if (daysFromCampaignStart > 0)
        {
            var publicationDateValue = contentEntity.Object.GetPropertyValue<DateTimeOffset?>("Content.PublicationDate");

            var newDate = new DateTimeOffset(
                campaignStartDateValue.Value.Year,
                campaignStartDateValue.Value.Month,
                campaignStartDateValue.Value.Day,
                publicationDateValue.HasValue ? publicationDateValue.Value.Hour : 0,
                publicationDateValue.HasValue ? publicationDateValue.Value.Minute : 0,
                publicationDateValue.HasValue ? publicationDateValue.Value.Second : 0,
                publicationDateValue.HasValue ? publicationDateValue.Value.Offset : TimeSpan.Zero);

            var newPublicationDate = newDate.AddDays(daysFromCampaignStart);
            contentEntity
                .SetPropertyValue("Content.PublicationDate", newPublicationDate)
                .Save();

            MClient.Logger.Info($"Publication date for content entity {contentEntity.Id} is updated to {newPublicationDate}");
        }
    }
}

DRM - Approve DRM requests

using System;
using System.Linq;

var taskId = Context.TargetId;
var triggerUserId = Context.TriggeringUserId;

if (!taskId.HasValue)
{
    MClient.Logger.Error("Cannot find task id for approving a DRM request.");
    return;
}

if (!triggerUserId.HasValue)
{
    MClient.Logger.Error("Cannot find the script trigger user.");
    return;
}

MClient.Logger.Info($"Approving DRM request task '{taskId.Value}'");

var fluentClient = new FluentClient(MClient);
var statuses = new string[] { "NotStarted", "InProgress" };
var taskEntity = fluentClient.Entities.Get(taskId.Value);
var taskStatus = (string)taskEntity["Status"];

if (taskStatus != null && statuses.Contains(taskStatus, StringComparer.OrdinalIgnoreCase))
{
    if (taskStatus.Equals("NotStarted", StringComparison.OrdinalIgnoreCase))
    {
        taskEntity
            .Parents("UserToTask", relation => {
                relation.Parents.Clear();
                relation.Parents.Add(triggerUserId.Value);

                if (relation.IsDirty)
                {
                    taskEntity
                        .Save()
                        .Reload();
                }
            });
    }

    taskEntity
        .SetPropertyValue("Status", "Done")
        .Save();

    MClient.Logger.Info($"DRM request task '{taskId.Value}' is approved.");
}

DRM - Decline DRM requests

using System;
using System.Linq;

var taskId = Context.TargetId;
var triggerUserId = Context.TriggeringUserId;

if (!taskId.HasValue)
{
    MClient.Logger.Error("Cannot find task id for declining a DRM request.");
    return;
}

if (!triggerUserId.HasValue)
{
    MClient.Logger.Error("Cannot find the script trigger user.");
    return;
}

MClient.Logger.Info($"Declining DRM request task '{taskId.Value}'.");

var fluentClient = new FluentClient(MClient);
var statuses = new string[] { "NotStarted", "InProgress" };
var taskEntity = fluentClient.Entities.Get(taskId.Value);
var taskStatus = (string)taskEntity["Status"];

if (taskStatus != null && statuses.Contains(taskStatus, StringComparer.OrdinalIgnoreCase))
{
    if (taskStatus.Equals("NotStarted", StringComparison.OrdinalIgnoreCase))
    {
        taskEntity
            .Parents("UserToTask", relation => {
                relation.Parents.Clear();
                relation.Parents.Add(triggerUserId.Value);

                if (relation.IsDirty)
                {
                    taskEntity
                        .Save()
                        .Reload();
                }
            });
    }

    taskEntity
        .SetPropertyValue("Status", "Declined")
        .Save();
    MClient.Logger.Info($"DRM request task '{taskId.Value}' is declined");
}

Can we improve this article ? Provide feedback