Product Gallery - Get assets added and put in a property bag

Use the following code to get assets added and put them in a property bag.

RequestResponse

using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using Stylelabs.M.Sdk;
using Stylelabs.M.Sdk.Contracts.Base;

string executionId = string.Empty;

LogScriptCalled(Context, MClient);

//Get the Product ID
var productId = Context.TargetId.Value;

//Add the executionId to Property Bag
Context.PropertyBag.Add($"{productId}-executionId", executionId);

//Get the Product entity
IEntity product = Context.Target as IEntity;

if (product == null)
{
    LogInfo(Context, MClient, $"The product entity is null");
    return;
}

//Get the change set (newly added assets)
var changeSet = Context.ChangeTracker.GetChangeSet();
var relationChanges = changeSet.RelationChanges;
var productGalleryRelationChange = relationChanges.FirstOrDefault(x => x.Name == "ProductToGalleryAsset");
var addedAssetIds = productGalleryRelationChange.NewValues;

if (addedAssetIds.Count <= 0)
{
    LogInfo(Context, MClient, $"There are no assets added to the Product Gallery");
    return;
}

var strAddedAssetIds = string.Join(",", addedAssetIds.ToArray());

LogInfo(Context, MClient, $"Product Gallery changed asset Ids: { strAddedAssetIds }");

//Add the asset IDs to Property Bag
Context.PropertyBag.Add($"{productId}-{executionId}", strAddedAssetIds);

#region Helpers

void LogScriptCalled(IActionScriptContext context, IMClient client)
{
    executionId = Guid.NewGuid().ToString("N").Substring(0, 6);
    LogInfo(context, client, $"{executionId}: Execution started. Context: {context}");
}

void LogDebug(IActionScriptContext context, IMClient client, string message)
{
    client.Logger.Debug(LogPrefix(context) + message);
}

void LogInfo(IActionScriptContext context, IMClient client, string message)
{
    client.Logger.Info(LogPrefix(context) + message);
}

string LogPrefix(IActionScriptContext context)
{
    return $"{ (context?.TargetId != null ? context.TargetId.Value.ToString() : string.Empty)} | ";
}

#endregion

Do you have some feedback for us?

If you have suggestions for improving this article,