Publishing Components using the Core Service in SDL Tridion 2011

Another quick post to demonstrate the use of the Core Service in SDL Tridion 2011. This time it’s to do with publishing components from a specified folder.

I’ve created a method that accepts a Tcm Id of a Target Type and the Tcm Id of a folder. The code then loops through the folder specified and then publishes each component to the target specified:

[code lang=”c-sharp”]
public static void Publish(string targetTcmId, string folderTcmId)
{
using (var client = new CoreService2010Client())
{
//get the list of components from a specific folder
var components = client.GetListXml(folderTcmId, new OrganizationalItemItemsFilterData { ItemTypes = new[] { ItemType.Component } });

//set the publish instructions to publish to child publications
var pubData = new PublishInstructionData
{
ResolveInstruction = new ResolveInstructionData() { IncludeChildPublications = true },
RenderInstruction = new RenderInstructionData()
};

//loop through each item returned and publish it
foreach (var element in components.Elements())
{
//get the component info
var component = client.Read(element.Attribute(“ID”).Value, null) as ComponentData;
var componentId = component.Id;

//strip out the version number if it contains one
if (component.Id.Contains(“v”))
{
componentId = component.Id.Substring(0, component.Id.LastIndexOf(‘-‘));
}

//publish to the target supplied into this method on low priority
try
{
client.Publish(new[] { componentId }, pubData, new[] { targetTcmId }, PublishPriority.Low, null);
}
catch (Exception ex)
{
Log.Error(“Publish: Unable to publish component”, ex);
}
}
}
}
[/code]

The Publish() method will also take an string array of Tcm Id’s for a list of components. This is useful for when you don’t want to flood the publishing queue with lots of publishing transactions and it will just combine it into one:

[code]
string[] componentIds = new string[] { “tcm:8-1234”, “tcm:8-1235”, “tcm:8-1236”, “tcm:8-1237” };
client.Publish(componentIds, pubData, new[] { targetTcmId }, PublishPriority.Low, null);
[/code]

The publication target type parameter is also a string array which will allow you to publish to multiple target’s if required:

[code]
string[] pubTargetIds = new string[] { “tcm:0-1-65538”, “tcm:0-2-65538” };
client.Publish(componentIds, pubData, pubTargetIds, PublishPriority.Low, null);
[/code]

Building Blocks (part of Dept) is a digital agency based in Manchester (UK), Boston (USA) and Zaragoza (Spain) who help global companies with digital technologies

Author

Want to know more? Get in touch.

Ryan Durkin, I'm the Technical Director at Building...

Ask your question!