Unlocking Sitecore Content Hub: A Guide to Utilizing the Web Client SDK - Part 2
The previous blog discussed how to authenticate using the OAuth client. The Web Client SDK includes an Entities client for executing CRUD operations—such as reading, creating, updating, and deleting entities—in Content Hub. For more details, you can visit Sitecore's Web Client SDK documentation. Here are some examples of CRUD operations on entities.
Create Entities
To create the entity, use the EntityFactory to instantiate an Entity, set its properties using SetPropertyValue, and then call the SaveAsync method to save the changes.
public static async Task<long> CreateAssestEntity()
{
IEntity asset = await MClientConnector.Client.EntityFactory.CreateAsync("M.Asset").ConfigureAwait(false);
asset.SetPropertyValue("Title", "This is a test Asset");
return await MClientConnector.Client.Entities.SaveAsync(asset).ConfigureAwait(false);
}
internal class Program
{
static async Task Main(string[] args)
{
try
{
var id=await CreateEntity.CreateAssestEntity();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
Read Entities
In the GetAsync method, the entity ID needs to be passed. GetAsync method will return IEntity.
public static Task<IEntity> GetAssetEntity()
{
long entityId = 1523729;
return MClientConnector.Client.Entities.GetAsync(entityId);
}
internal class Program
{
static async Task Main(string[] args)
{
try
{
var entity=await GetEntity.GetAssetEntity();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
Update Entities
To update the entity, begin by invoking the GetAsync method with the entity ID to retrieve an IEntity. After obtaining the IEntity, modify its properties using SetPropertyValue. Finally, call the SaveAsync method to persist the changes.
public static async Task<long> UpdateAssetEntity()
{
long entityId = 1523729;
IEntity asset = await MClientConnector.Client.Entities.GetAsync(entityId);
asset.SetPropertyValue("Title", "This is a updated test Asset");
return await MClientConnector.Client.Entities.SaveAsync(asset).ConfigureAwait(false);
}
internal class Program
{
static async Task Main(string[] args)
{
try
{
var entity = await UpdateEntity.UpdateAssetEntity();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
Delete Entities
To delete the entity, call the DeleteAsync method with the entity ID.
public static Task DeleteAssetEntity()
{
long entityId = 1523729;
return MClientConnector.Client.Entities.DeleteAsync(entityId);
}
internal class Program
{
static async Task Main(string[] args)
{
try
{
await DeleteEntity.DeleteAssetEntity();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
Comments