Frontend - Alpha Solutions

In this Alpha Solutions Tech Tip, we walk you through how to generate public links for Content Hub Assets.

1.18.22

BY NIKET ASHESH

If you are looking to build a public link in code, here is a snippet that might help. (In this case the script is triggered when an image rendition is generated).

GENERATING A PUBLIC LINK

using System.Linq;
using System.Net;
using System.Net.Http;
using Stylelabs.M.Sdk.Models.Notifications;
using Stylelabs.M.Sdk.Contracts.Base;
using Stylelabs.M.Base.Querying.Filters;
using Stylelabs.M.Sdk.Contracts.Notifications;
using System.Globalization;
MClient.Logger.Info("Public link rendition code started!");
var assetId = Context.TargetId.Value;
CreateRendition("preview", assetId);

async void CreateRendition(string rendition, long assetId)
{
    var publicLink = await MClient.EntityFactory.CreateAsync("M.PublicLink");
    if(publicLink.CanDoLazyLoading())
    {
        await publicLink.LoadMembersAsync(new PropertyLoadOption("Resource"), new RelationLoadOption("AssetToPublicLink"));
    }
    publicLink.SetPropertyValue("Resource",rendition);
    var relation = publicLink.GetRelation<IChildToManyParentsRelation>("AssetToPublicLink");
    if(relation == null)
    {
        MClient.Logger.Error("Unable to create public link: no AssetToPublicLink relation found.");
    }
    relation.Parents.Add(assetId);
    MClient.Logger.Debug($"Saving entity");
    var entityId = await MClient.Entities.SaveAsync(publicLink);

RETRIEVING A PUBLIC LINK

   MClient.Logger.Debug($"Fetching saved asset id: {entityId}");
   var entity = await MClient.Entities.GetAsync(entityId);
   MClient.Logger.Debug($"Fetching RelativeUrl");
   var relativeUrl = await entity.GetPropertyValueAsync<string>("RelativeUrl");
   MClient.Logger.Debug($"Fetching VersionHash");
   var versionHash = await entity.GetPropertyValueAsync<string>("VersionHash");
   MClient.Logger.Info($"Created public link for asset with asset id: {assetId}");
   MClient.Logger.Info($"Public link is: https://alpha-
mock01.stylelabs.io/api/public/content/{
relativeUrl}?v={versionHash}");
    
}