Extract Metadata Properties from File and Update Asset fields in Content Hub through Script While Asset Creation

Hello everyone, In this blog, we will see how we can update custom field values define in M.Asset Entity definition, when we add any asset.

Let's see the custom field in M.Asset Entity Definition. Here we assume, we are aware, how to add custom fields to M.Asset Schema.

Let's get started. Below are the steps that are required to accomplish this process.

  • Step 1: Creating a Metadata Processing Script : This script will be having logic to update the fields.
  • Step 2: Creating an Enitity by uploading a new Asset.
  • Step 3: Verifying the updated values in the Entity newly created.

let's start with creating a new script in Content Hub. Click on Manage page section as highlighted below in screenshot in blue. Then search for Scripts in search box. Click on the scripts result and you will be navigated to Scripts page

On Scripts click on Add Script button to add a new script.

On click a Dialog box will open just give a appropriate script name and choose action as Metadata Processing from drop down and click save.

Now click the newly created script from script list. It will open script editor and here we will write our c# logic to extract the metadata properties and update the fields for that Assets or Enitity

Add the below code to script editor, save the changes, build it and publish it.

Below is the code snippet

       
using Stylelabs.M.Sdk; 
using Stylelabs.M.Sdk.Models.Notifications; 
using Stylelabs.M.Sdk.Contracts.Notifications; 
using Stylelabs.M.Sdk.Contracts.Base; 
using Stylelabs.M.Sdk.Contracts.Content; 
using Stylelabs.M.Base.Querying; 
using Stylelabs.M.Base.Querying.Filters; 
  
try
{ 
    var masterFileRelation = await Context.File.GetRelationAsync("MasterFile"); 
    
    if (!masterFileRelation.Parents.Any() || !masterFileRelation.Parents.Contains(Context.Asset.Id.Value)) 
    { 
        return; 
    } 
    
    //Log the start of Metadata Mapping in the script logger  
    MClient.Logger.Info("Metadata Mapping starts.");  
    

    var DictionaryofMetadataProps = new Dictionary();
    DictionaryofMetadataProps.Add("EXIF:Model","CameraBrand");
    DictionaryofMetadataProps.Add("Composite:ShutterSpeed","ShutterSpeed");
    DictionaryofMetadataProps.Add("EXIF:ISO","ISOImage");
    DictionaryofMetadataProps.Add("Composite:Aperture","Aperture");
    foreach(var item in DictionaryofMetadataProps)
    {
        JToken jToken;
        Context.MetadataProperties.TryGetValue(item.Key, out jToken);
        if(jToken!=null)
        {
            //var val = JsonConvert.SerializeObject(jToken);
            var val = jToken.Value();
            MClient.Logger.Debug(val);
            if(string.IsNullOrEmpty(val))
                continue;
            Context.Asset.SetPropertyValue(item.Value, val);
        }
        else{
            MClient.Logger.Warn($"Key{item.Key} is not found");
        }
    }
     
    await MClient.Entities.SaveAsync(Context.Asset);
} 
catch (Exception e) 
{ 
    MClient.Logger.Info(e.ToString()); 
    return;  
} 
	   

Let's try to understand the code. The context here is uploaded file. In our case, its image. When we upload a file, before the asset entity is created, few relation are mapped to it. One of them is MasterFile relation as one MasteFile is created for that upload asset. We are fetching the Master File relation and getting all the Parent relation for that Master File relation. You can check this by navigating to your entities detail in JSON format from the given url "{Your Sandbox URL}/api/entities/{Entity ID}?tab6843=System". Search for MasterFile and you will get the relation as shown below.Click the children url and it will open that entity definition in JSON format. Again search for MasterFile relation and you will get the url. Click it. It will open entity page where you will have parent relation. Then we are checking the context id available in Parent relation with context id of the Asset and if it is not available we will return.

The next line in code is where we are creating a dictionary which has two value. One is the metadata key and second is the field name which will be used while updating the asset value.To check all available metadata properties, just Navigate to Settings from Manage Page--> Search for MetadatsImportConfiguration setting --> Click on it--> You will get From and To Object. From contains the metadata key and in Tosection, we have the property value mapped to actual property. Then we are reading the Context Data which is basically JOject. We are passing the key from dictionary to get the JToken value for that property. We are then updating the Custom Propert which we created with the value and then we saving the asset and hence our task is done.

Hope you enjoyed this blog. I will be back with more such practical blog as my learning will continue. Thanks for reading. Happy Learning!!

You can check my other blogs blog related to Sitecore

Comments

Popular posts from this blog

Sitecore XM Cloud Form Integration with Azure Function as Webhook

Automate RSS Feed to Sitecore XM Cloud: Logic App, Next.js API & Authoring API Integration

Create and Fetch Content From Sitecore Content Hub One using GraphQL and React