Content Hub: Add public link for asset via Web SDK Client

We found out how to query a specific asset and retrieve it’s public links, which is shown in the last posts. Now we want to add a new public link for a specific asset using the Web SDK Client.

First we setup the configuration.

// Your Sitecore Content Hub endpoint to connect to
Uri endpoint = new Uri("https://yourcontenthuburl");

// Enter your credentials here         
OAuthPasswordGrant oauth = new OAuthPasswordGrant         
{             
  ClientId = "yourclientid",             
  ClientSecret = "yourclientsecret",             
  UserName = "yoursuperusername",             
  Password = "youruserpassword"         };         

// Create the Web SDK client         
IWebMClient client = MClientFactory.CreateMClient(endpoint, oauth);         client.TestConnectionAsync().Wait();

Now we use the client to create a public link for the “downloadOriginal” rendition.

private static async Task<long> CreatePublicLink(
IWebMClient client, string rendition, long assetId, string relativeUrl = null)     
{         
CultureInfo enUs = CultureInfo.GetCultureInfo("en-US"); 
IMClient mClient = client;    
     
IEntityDefinition publicLinkDefinition = await client.EntityDefinitions.GetAsync(PublicLink.DefinitionName);    

IEntity publicLink = await mClient.EntityFactory.CreateAsync(publicLinkDefinition, new CultureLoadOption(enUs));         

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

if (!string.IsNullOrEmpty(relativeUrl))         
{             
  string fixedUrlName = UrlSlugHelper.RemoveDiacritics(relativeUrl); 
  publicLink.SetPropertyValue("RelativeUrl", fixedUrlName);         
}         

publicLink.SetPropertyValue(PublicLink.Resource, rendition); 

IChildToManyParentsRelation relation = publicLink.GetRelation<IChildToManyParentsRelation>(PublicLink.AssetToPublicLink);         

if (relation == null)         
{             
  client.Logger.Error("Unable to create public link: no  AssetToPublicLink relation found.");         
}         
relation.Parents.Add(assetId);         
client.Logger.Debug($"Saving entity");         
long entityId = await client.Entities.SaveAsync(publicLink); 

return entityId;     
}

If we retrieve now all public links for the asset we get a list including our created public link.

Help: For getting a correct url we use a helper we created in our testproject which looks like the following.

namespace ContentHubApiTest
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;

public sealed class UrlSlugHelper {     

private static Dictionary<char, string> converter = new Dictionary<char, string>()     
{         
  {  'ä', "ae" },         
  {  'Ä', "Ae" },         
  {  'ö', "oe" },         
  {  'Ö', "Oe" },         
  {  'ü', "ue" },         
  {  'Ü', "Ue" },         
  {  'ß', "ss" }     
};     

public static string RemoveDiacritics(string value)     
{         
 if (string.IsNullOrWhiteSpace(value))         
 {             
  return null;         
 }         

string normalizedString = value.Normalize();         

foreach (KeyValuePair<char, string> item in UrlSlugHelper.converter)         {             
 string temp = normalizedString;             
 normalizedString = temp.Replace(item.Key.ToString(), item.Value);         }         

StringBuilder stringBuilder = new StringBuilder();         

for (int i = 0; i < normalizedString.Length; i++)         
{             
  normalizedString = normalizedString.Normalize(NormalizationForm.FormD); 

  string c = normalizedString[i].ToString();             
  if (CharUnicodeInfo.GetUnicodeCategory(Convert.ToChar(c)) != UnicodeCategory.NonSpacingMark)             
  {                 
   stringBuilder.Append(c);             
  }         
 }         
 return stringBuilder.ToString();     
}     

public static string ToUrlSlug(string value)     
{         
 //First to lower case         
 value = value.ToLowerInvariant();         

 //Remove all accents         
 var bytes = Encoding.GetEncoding("Cyrillic").GetBytes(value);  
 value = Encoding.ASCII.GetString(bytes);         

 //Replace spaces         
 value = Regex.Replace(value, @"\s", "-", RegexOptions.Compiled); 

 //Remove invalid chars         
 value = Regex.Replace(value, @"[^a-z0-9\s-_]", "", RegexOptions.Compiled);         

 //Trim dashes from end         
 value = value.Trim('-', '_');         

 //Replace double occurences of - or _         
 value = Regex.Replace(value, @"([-_]){2,}", "$1", RegexOptions.Compiled);         

 return value;     
}     

public bool HasUmlaut(string value)     
{         
 if (string.IsNullOrWhiteSpace(value))         
 {             
  return false;         
 }         

 foreach (KeyValuePair<char, string> item in UrlSlugHelper.converter)           {         
if (value.Contains(item.Key.ToString()))             
  {                 
    return true;             
  }         
 }         
 return false;     
 } 
}
}

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.