using System;
using Tridion.ContentManager;
using Tridion.ContentManager.CommunicationManagement;
using Tridion.ContentManager.Templating;
using Tridion.ContentManager.Templating.Assembly;
namespace Test.JsonTemplates
{
[TcmTemplateTitle("Publish JSON package items as Variants")]
public class PublishJsonFiles : ITemplate
{
public void Transform(Engine engine, Package package)
{
//Get all items of unknown type from the package
var items = package.GetAllByType(ContentType.Unknown);
//Remove all items that are NOT JSON files
foreach (var item in items)
{
if (!item.Properties[Item.ItemPropertyFileNameExtension].Equals("json", StringComparison.OrdinalIgnoreCase))
{
items.Remove(item);
}
}
//Check the package values for an optional structure group ID to publish to
var optionalStructureGroupId = package.GetValue("jsonStructureGroup");
StructureGroup jsonStructureGroup = null;
//Go get the structure group from Tridion if an Id has been specified
if (!String.IsNullOrWhiteSpace(optionalStructureGroupId))
{
var structureGroupTcmUri = new TcmUri(
Convert.ToInt32(optionalStructureGroupId),
ItemType.StructureGroup,
engine.PublishingContext.RenderedItem.ResolvedItem.Item.Id.PublicationId);
jsonStructureGroup = (StructureGroup)engine.GetObject(structureGroupTcmUri);
}
//Publish out the JSON files
foreach (var item in items)
{
var filename = item.Properties[Item.ItemPropertyFileName] + "." + item.Properties[Item.ItemPropertyFileNameExtension];
//If no structure group has been specified, publish to the default images directory configured for the publication
if (jsonStructureGroup == null)
{
engine.PublishingContext.RenderedItem.AddBinary(
item.GetAsStream(),
filename,
filename,
null,
"application/json");
}
else
{
engine.PublishingContext.RenderedItem.AddBinary(
item.GetAsStream(),
filename,
jsonStructureGroup,
filename,
null,
"application/json");
}
}
}
}
}
using Tridion.ContentManager.Templating;
using Tridion.ContentManager.Templating.Assembly;
namespace Test.JsonTemplates
{
class CreateTestData : ITemplate
{
public void Transform(Engine engine, Package package)
{
string JSON = "{\"h3title\":\"09/04/2013\"}";
var jsonItem = package.CreateStringItem(ContentType.Unknown, JSON);
jsonItem.Properties.Add(Item.ItemPropertyFileName, "test");
jsonItem.Properties.Add(Item.ItemPropertyFileNameExtension, "json");
package.PushItem("test.json", jsonItem);
}
}
}