Scripting SDK clients

Scripting SDK clients can simplify your interactions with your service or platform by offering predefined scripts and functions. This facilitates handling requests and responses, letting you integrate and automate the service within your scripts.

Sitecore Content Hub offers the following clients:

Assets

The Assets client can be used to manage the final life cycle status of an asset using the FinalLifeCycleManager, with the following methods:

  • ApproveAsync - moves the asset to the approved state.

  • ArchiveAsync - moves the asset to the archived state.

  • DirectPublishAsync - moves the asset to the approved state.

  • RejectAsync - moves the asset to the rejected state (with an optional reason for rejection).

  • RestoreAsync - moves the asset to the approved state.

  • SubmitAsync - moves the asset to the underreview state.

These methods require the ID of an existing asset. If the provided ID is not that of an asset entity, or if the transition from the current state to the requested state is not allowed, the client throws a ForbiddenException.

For example, to approve the asset with the ID 1000:

RequestResponse
await MClient.Assets.FinalLifeCycleManager.ApproveAsync(1000);

Additionally, you can get the entity ID of a final life cycle status entity (this works with an enum constant or with the status string value):

RequestResponse
long? id = await MClient.Assets.FinalLifeCycleManager.GetFinalLifeCycleStatusIdAsync(FinalLifeCycleStatus.StatusValues.Approved);

Commands

The Commands client can be used to execute commands that are publicly registered in Content Hub.

Namespace

Command name

Arguments

external.action 

external.action 

RequestResponse
new JObject(
    new JProperty("entity_id", <ENTITY_ID>),
    new JProperty("action_id", <ACTION_ID>),
    new JProperty("properties", new JArray()),
    new JProperty("relations", new JArray()),
    new JProperty("action_execution_source", "ExternalAction"),
    new JProperty("extra_data", new JObject())

m.security 

applyuserrole 

RequestResponse
new JObject(
        new JProperty("user_id", <USER_ID>),
        new JProperty("role", <ROLE>),
        new JProperty("target_id",  <TARGET_ID>))

m.security

updateuserroles

RequestResponse
new JObject(
	new JProperty("role",  <ROLE>),
	new JProperty("target_id", <TARGET_ID>),
	new JProperty("added_users", new JArray()),
	new JProperty("removed_users", new JArray())
	)

m.asset 

setmaster 

RequestResponse
new JObject(
        new JProperty("new_master_id", <NEW_MASTER_ID>),
        new JProperty("entity_id", <ENTITY_ID>),
        new JProperty("master_relation", <MASTER_RELATION>))

To run an asynchronous command through the SDK:

RequestResponse
await MClient.Commands.ExecuteCommandAsync(<NAMESPACE>, <NAME>, <ARGS>);

Culture

The Culture client can be used to fetch culture-related information from Content Hub.

To get the default culture:

RequestResponse
CultureInfo defaultCulture = await MClient.Cultures.GetDefaultCultureAsync();

To get all registered cultures:

RequestResponse
IList CultureInfo cultures = await MClient.Cultures.GetAllCulturesAsync();

Data source

The Data source client can be used to perform CRUD operations on data sources, also called option lists.

Get data sources

A data source can be retrieved by name:

RequestResponse
IDataSource result = await MClient.DataSources.GetAsync(<NAME>);

This returns an IDataSource object. However, we recommend that you downcast it to the correct data source type as follows:

RequestResponse
IHierarchicalDataSource hierachicalDataSource = await MClient.DataSources.GetAsync(name) as IHierarchicalDataSource;

This lets you change the value of the data source.

RequestResponse
IFlatDataSource flatDataSource = await MClient.DataSources.GetAsync(<NAME>) as IFlatDataSource;
Note

The Type property on IDataSource identifies the correct data source type at runtime.

Create data sources

To create a hierarchical data source, use the factory to create an instance and then save the instance in the data source client.

For example, you can do this for media types, so that each type of media can have multiple subvalues.

In this example, mp4 is added as a subtype of a video media type.

RequestResponse
var dataSource = MClient.DataSourceFactory.CreateHierarchicalDataSource("MediaType");
dataSource.Labels.Add(enUs, "Media type");

var video = new HierarchicalDataSourceValue("Video")
{
  Labels = { { enUs, "Video" } }
};

var mp4 = new HierarchicalDataSourceValue("MP4")
{
  Labels = { { enUs, "mp4" } }
};
video.Values.Add(mp4);

var image = new HierarchicalDataSourceValue("Image")
{
  Labels = { { enUs, "Image" } }
};

dataSource.Values.Add(video);
dataSource.Values.Add(image);

await MClient.DataSources.CreateAsync(dataSource);

Update data sources

In the following example, a flat colors data source is extended with the color red:

RequestResponse
var dataSource = await MClient.DataSources.GetAsync("Colors") as IFlatDataSource;

var red = new FlatDataSourceValue("Red")
{
  Labels = { { enUs, "Red" } }
};
dataSource.Values.Add(red);

await MClient.DataSources.UpdateAsync(dataSource);

Delete data sources

In the following example, the MediaType data source is deleted:

RequestResponse
await MClient.DataSources.DeleteAsync("MediaType");

Entities

The Entities client can be used to perform CRUD operations on entities.

Get entities

The following method gets an entity by ID:

RequestResponse
IEntity entity = await MClient.Entities.GetAsync(<ENTITY_ID>);

If the entity doesn't exist or the user doesn't have permission to read it, the method returns null.

Note

There are many options to load entities by ID, by identifier, or by definition. For more information about loading configurations, please refer to the load configurations section.

Create entities

You can only create an entity with the CreateAsync method.

In the following code snippet, an Asset entity is created locally.

RequestResponse
IEntity asset = await MClient.EntityFactory.CreateAsync("M.Asset");

In the following code snippet, the locally created Asset entity is sent to the server to be validated and persisted.

RequestResponse
long id = await MClient.Entities.SaveAsync(asset);

The returned id is the ID of the newly created entity. You can use this ID to get the latest version of the entity from the server.

Update entities

Use the SaveAsync method on the entities client after making a change.

RequestResponse
long id = await MClient.Entities.SaveAsync(<ASSET>);

The returned id is the same ID of the entity. To get the latest version of this entity, use the ID to get it from the server again.

Delete entities

You can delete an entity with the DeleteAsync method and the entity ID.

RequestResponse
await MClient.Entities.DeleteAsync(<ENTITY_ID>);

Entity definitions

The Entity definitions client can be used to perform CRUD operations on entity definitions.

Warning

Use extreme caution. Adding, removing, or deleting entity definitions can have serious consequences.

Get entity definitions

Entity definitions can be retrieved by name or id:

RequestResponse
IEntityDefinition assetDefinition = await MClient.EntityDefinitions.GetAsync("M.Asset");
RequestResponse
IEntityDefinition assetDefinition = await MClient.EntityDefinitions.GetAsync(<ASSET_DEFINITION_ID>);

If the entity definition does not exist, the method returns null.

Note

There are many more overloads for retrieving entity definitions. It's also possible to resolve names to IDs and vice versa. See the API docs for a complete overview.

Create entity definitions

The SDK lets you create entity definition objects directly, without a factory. A very simple entity definition can be created as follows:

RequestResponse
IEntityDefinition definition = new EntityDefinition
{
  Name = "M.Demo.Definition",
  DisplayTemplate = "{M.Demo.Definition.Name}"
};

var defaultGroup = new MemberGroup { Name = "Default" };
defaultGroup.MemberDefinitions.Add(new StringPropertyDefinition
{
  Name = "M.Demo.Definition.Name",
  IsUnique = true
});

definition.MemberGroups.Add(<DEFAULT_GROUP>);

long id = await MClient.EntityDefinitions.SaveAsync(<DEFINITION>);

The returned id is the ID of the newly created entity definition.

Note

The EntityDefinition can be imported from Stylelabs.M.Sdk.Models.Base, and the property member definitions from Stylelabs.M.Sdk.Models.Base.PropertyDefinitions.

Update entity definitions

Use the save method on the entity definitions client after making a change.

RequestResponse
long id = await MClient.EntityDefinitions.SaveAsync(<DEFINITION>);

This returns the ID of the updated entity definition.

Delete entity definitions

Entity definitions can be deleted by name or by id:

RequestResponse
await MClient.EntityDefinitions.DeleteAsync(<DEFINITION_ID>);
RequestResponse
await MClient.EntityDefinitions.DeleteAsync("M.Demo.Definition");

Legacy Jobs client

Note

The legacy Jobs client will be deprecated in the future. You can switch from the Entities client to the Jobs client to start using the Jobs client.

The legacy Jobs client can be used to create many kinds of fetch jobs.

Available fetch jobs

The fetch job models are located in: Stylelabs.M.Sdk.Models.Jobs.

The available models are:

  • AzureFetchJobRequest - fetches one or more files from Azure blob storage.

  • FileFetchJobRequest - fetches one or more files from a directory on the web server.

  • WebFetchJobRequest - fetches one or more files over HTTP or HTTPS.

When creating a fetch job, the following arguments are always required:

  • Description - a description of the job.

  • Asset id - the asset to link the fetched files on.

Create a fetch job

To create a fetch job, pass the fetch job model to the CreateFetchJobAsync method of the jobs client. This returns the ID of the newly created job.

The following example will fetch an image from a public URL and link it to an asset with ID 1000:

RequestResponse
var webFetchJob = new WebFetchJobRequest("Fetches an example image from the web.", 1000)
{
  Urls = new[] { "https://picsum.photos/200" }
};

long jobId = await MClient.Jobs.CreateFetchJobAsync(webFetchJob);

Notifications

The Notifications client can be used to manage and send notifications.

Note

The client variable in the following code examples refers to the IMClient instance. When using the Web SDK, the variable name can be chosen freely, but it is also called client at instantiation in the documentation.

Email templates

Email template entities contain the templates for sending emails. The variables can be resolved at runtime.

IMailTemplateEntity is a subtype of IEntity. It provides C# properties and methods for the members on the M.Mailing.Template entity definition.

To get these email templates, the client provides extra getters that are not available on the entities client. It allows fetching email templates by name. However, every operation on an IEntity still applies to IMailTemplateEntity. Saving and deleting IMailTemplateEntity objects is still done through the entities client.

Create an email template

A simple hello world template could look like this:

RequestResponse
CultureInfo enUs = CultureInfo.GetCultureInfo("en-US");
var entity = await client.EntityFactory.CreateAsync(Constants.MailTemplate.DefinitionName);
var template = client.TypedEntityFactory.FromEntity <IMailTemplateEntity>(<ENTITY>);
template.Name = "Hello world template";
template.Subject[enUs] = "Hello there!";
template.Description[enUs] = "Hello";
template.Body[enUs] = "Hello {{Username}}!";
template.SetPropertyValue("M.Mailing.TemplateLabel", enUs, "Hello world template");

var templateVariable = new TemplateVariable
{
  Name = "Username",
  VariableType = TemplateVariableType.String
};
template.SetTemplateVariables(new[] { templateVariable });

await client.Entities.SaveAsync(<TEMPLATE>);

Send email notifications

Emails can be sent to users by username, user ID, or by a broadcast. There are three respective overloads to the SendEmailNotificationAsync with the following input:

  • MailRequestById - for specifying users by ID.

  • MailRequestByUsername - for specifying users by username.

  • MailRequestBroadcast - sends to all users.

An email broadcast could be sent using the template:

RequestResponse
var request = new MailRequestBroadcast
{
  MailTemplateName = "Hello world template"
};
request.Variables.Add("Username", "world");

await client.Notifications.SendEmailNotificationAsync(<REQUEST>);

This would send an e-mail containing "Hello world!", to everyone.

Send real-time notifications

Real-time notifications can be sent to users by username, user ID, or by a broadcast. There are three respective overloads to the SendRealTimeNotificationAsync with the following input:

  • RealtimeRequestById - for specifying users by ID.

  • RealtimeRequestByUsername - for specifying users by username.

  • RealtimeRequestBroadcast - sends to all users.

Here's an example of a real-time notification sent to the DemoUser:

RequestResponse
var request = new RealtimeRequestByUsername()
{
  Title = "Your notification title",
  Link = new System.Uri("https://example.com")
};
request.Recipients.Add("DemoUser");
request.SetBody("Your description");
request.SetIcon("https://example.com/image.png");

await client.Notifications.SendRealTimeNotificationAsync(<REQUEST>);

The link is opened when the user clicks the notification.

This real-time request interface is built on the standard notifications API, which uses an options object that contains all the notification information. This object is directly passed from the IRealtimeRequest.Options property. Some helper methods have been provided to help configure this options object, for example, the body and the icon of the notification.

Send confirmation emails

Important

For SendConfirmationEmailAsync to work, you must set EnableConfirmationMail to true in the settings.

Sending confirmation emails to users can be done using IDs or usernames:

RequestResponse
await client.Notifications.SendConfirmationEmailAsync("DemoUser");

This will send an email to the specified user, containing a secure link to activate their account.

Policies

The Policies client can be used to provide read and update operations on policies. These policies can only be created and deleted from inside Content Hub. From outside, they can only be retrieved or modified.

Get user policies

To get a user's policy, use GetUserPolicyAsync:

RequestResponse
var policy = await MClient.Policies.GetUserPolicyAsync(<USER_ID>);

Get user group policies

To get a user group's policy, use GetUserGroupPolicyAsync:

RequestResponse
var policy = await MClient.Policies.GetUserGroupPolicyAsync(<USERGROUP_ID>);

Update policies

After making changes to a policy, you can update it as follows:

RequestResponse
await MClient.Policies.UpdateAsync(<POLICY>);

Querying

The Querying client can be used to execute queries.

Warning

If multiple items match a query, an InvalidOperationException is thrown. When the iterator goes beyond the configured maximum number of results, the server throws an exception. In this case, a scroll is necessary.

Note

You can also search for specific entities in Content Hub using a SearchAfterQuery query.

Create a query

You can use the Querying client to create queries and then run any of the following queries or iterate on results.

View query results

After running a query, an IQueryResult is returned. This result has the following properties:

  • Items - the entities or IDs that matched the query, which can be a subset of the total results.

  • TotalNumberOfResults - the number of items that matched the query in Sitecore Content Hub (even if not all of them are in Items).

  • Offset - the number of items that were skipped.

Query for a single entity

When it is certain that a query only matches a single entity, use the SingleAsync method.

RequestResponse
IEntity entity = await MClient.Querying.SingleAsync(<QUERY>);

Query for a single entity ID

When it is certain that a query only matches a single entity, use the SingleIdAsync method.

RequestResponse
long? entityId = await MClient.Querying.SingleIdAsync(<QUERY>);

Query for one or more entities

To query for one or more entities:

RequestResponse
IEntityQueryResult queryResult = await MClient.Querying.QueryAsync(<QUERY>);

The IEntityQueryResult.Items contains the returned entities.

Query for one or more entity IDs

To query for one or more entity ids:

RequestResponse
IIdQueryResult queryResult = await MClient.Querying.QueryIdsAsync(<QUERY>);

The IIdQueryResult.Items method contains the returned IDs (in long format).

Iterate query result entities

When the query returns a small to medium size of results (the default configuration is 10,000 results maximum), it is easy to batch process the entities using an iterator.

In the following code snippet, an iterator is created:

RequestResponse
IEntityIterator iterator = MClient.Querying.CreateEntityIterator(<QUERY>);

In the following code snippet, the iterator is used to batch process entities:

RequestResponse
while (await iterator.MoveNextAsync())
{
  var entities = iterator.Current.Items;
  // Do something with the entities
}

The while loop automatically ends when the iterator has finished processing all the batches of entities.

Iterate query result entity IDs

When the query returns a small to medium size of results (the default configuration is 10,000 results maximum), it is easy to batch process the entity IDs using an iterator.

In the following snippet, an iterator is created:

RequestResponse
IIdIterator iterator = MClient.Querying.CreateIdIterator(<QUERY>);

In the following code snippet, the iterator is used to batch process entity IDs:

RequestResponse
while (await iterator.MoveNextAsync())
{
  var ids = iterator.Current.Items;
  // Do something with the ids
}

The while loop automatically ends when the iterator has finished processing all the batches of entities.

Warning

When the iterator goes beyond the configured maximum number of results, the server throws an exception. In that case, a scroll is necessary.

Deprecation notes

On the Query class it is possible to set the EntityLoadOptions property and the LoadConfiguration property. The first property was used by the old WebApiClient SDK and was deprecated in 3.0. In 3.1 the Query class and the load configurations were separated. We recommend that you do not use these properties, but pass the load configuration as an extra parameter when passing the query object, when applicable.

Settings

The Settings client can be used to provide some extra utilities for retrieving settings.

Settings are entities that can be used with the Querying client and the Entities client. This client is useful because it provides common queries that would otherwise have to be written by hand.

Get the category ID

The following example snippet gets the ID of the PortalConfiguration category:

RequestResponse
long? id = await MClient.Settings.GetCategoryIdAsync("PortalConfiguration");

Get a setting

The following example retrieves a setting called Authentication from the PortalConfiguration category:

RequestResponse
IEntity setting = await MClient.Settings.GetSettingAsync("PortalConfiguration", "Authentication");
Note

You can pass an entity load configuration to the client.

Get all the settings for a category

You can also get all the settings for a category. For example, the following snippet gets all the rendition settings:

RequestResponse
IList IEntity renditionSettings = await MClient.Settings.GetSettingsForCategoryAsync("Renditions");
Note

You can pass an entity load configuration.

Users

The Users client can be used to fetch users and user groups by name, and also features some password management operations.

Users and user groups are entities that can be used with the Querying client and the Entities client.

Get users

The GetUserAsync method gets a user by username.

The following example fetches the user entity named superuser:

RequestResponse
IEntity superuser = await MClient.Users.GetUserAsync("superuser");

Get user groups

The GetUserGroupAsync method gets a user group by name.

The following example fetches the user group entity named superusers.

RequestResponse
IEntity superusersGroup = await MClient.Users.GetUserGroupAsync("superusers");

Do you have some feedback for us?

If you have suggestions for improving this article,