Friday, 11 September 2020

Sitecore Content Hub for Developers, Where to write code logic?

 In the previous post I gave an introduction for the different sections you as developer will deal with when using Sitecore Content Hub, In this post I will show you a simple scenario when you need to write a custom code for updating an asset an example, and where you can add this code, mainly there are two places where you can have this logic, you can create a new Content Hub script or create an azure function on your function app azure resource. 



As I explained in the previous post, Sitecore Content Hub gives you the ability to create a C# script blocks that can be triggered when an Entity get created, updated or deleted, the C# script can use the SDK to create, edit, delete and query Sitecore Content Hub entities, so lets assume that you want to update a specific asset member field with a specific value, where you should add this code and how it should look like? 


Using Content Hub Scripts

One of the approaches you can use is to access content hub admin section, then scripts, then create new script, in the available editor you can add your code as you can see from the following screenshot: 




You can see from the above screenshot that you already have references added for the stylelabs sdk which will help you access and manipulate content hub entities. following is a sample code of how you can get a specific asset/entity and update a member field in a content hub script:


In the above script it started with the entity load configuration, which defines the members and the culture that we wish to retrieve for this asset., then we call "GetAsync" method which will retrieve the entity, then we update the display name member using "SetPropertyValue"  then calling the "SaveAsync" method to save the change. simple enough! :) 



Using Azure Functions

In another approach and using the same example above, we can use azure function to have our code, and with using azure function we also have two approaches:

  1. Use azure function code to do a post request to your CH script, [we would need authentication token to be passed with request header for this one].
  2. Use Stylelabs SDK to connect to Content Hub, and use the SDK API as we discussed above to manipulate asset/entity as example.

In the following example you will find an example of a post request to to trigger a script in content hub, you will need to have the script Url which you can get from CH, in the scripts section, and authentication token. 


Hope the above help, please feel free to reach out to me with any questions, in the comments, twitter or though email. 



No comments:

Post a Comment