Skip to main content

Read Configuration Items TBB

This week's TBB is Read Configuration Items TBB. It is a very generic TBB that reads values from a multi-value Name-Value-Pair embeddable field and creates Package items for each pair. The TBB does a bit more, for example localizes a TcmUri to the current Publication context and pushes also the Publication properties PublicationPath and PublicationUrl.

Schemas

Global Configuration Schema

Name
Global Configuration
Description
Use as container of Name-Value pairs
Root Element Name
GlobalConfiguration
Type
System
Field Name
Type
Mandatory
Properties
SystemValues
Embedded
No
Multi-value, Schema “Name-Value Pair”

Name-Value Pair Schema

Name
Name-Value Pair
Description
Used to hold Name/Value configuration pairs
Root Element Name
NameValuePair
Type
System
Field Name
Type
Mandatory
Properties
Name
Text
Yes
Single line, no-repeat
Value
Text
No
Single line, no-repeat

Read Configuration Items Parameter Schema

Name
Read Configuration Items Parameter Schema
Description
Read Configuration Items Parameter Schema
Type
Parameter Schema
Field Name
Type
Mandatory
Properties
ConfigurationComponentFieldName
Text
No


Read Configuration Items TBB

Name
Read Configuration Items TBB
Type
·    Template in .NET Assembly
Description
Used to:
·    Read the configuration Component from the Publication metadata;
·    Create package items for each found configuration name/value pair;
Notes:
This is a very generic TBB that reads all fields from the Configuration Component.
The logic reads the field name “ConfigurationComponentFieldName” from the TBB Parameter. It reads then the Configuration Component linked from the Publication metadata field specified by “ConfigurationComponentFieldName”.
From the Configuration Component, read all fields and create package items for each field. Name of package item is the name of the field in the Component (sanitized to remove the whitespace) and the value is the value of the field. It uses the Name/Value Pair Schema to read and create all values from the System Values Configuration Component.
Parameters
Uses Parameter Schema “Read Configuration Items Parameter Schema” to read the field name from the Publication metadata Schema that contains the Component Link to the Configuration Component
Applicable to
Component Templates and Page Templates

The Code

[TcmTemplateTitle("Read Configuration Items TBB")]
public class ReadConfigurationItems : ITemplate {

    TemplatingLogger log = TemplatingLogger.GetLogger(typeof(ReadConfigurationItems));

    public void Transform(Engine engine, Package package) {
        GenericUtils utils = new GenericUtils();
        Publication publication = utils.GetContextPublication(engine, package);
        if (publication.Metadata == null || publication.MetadataSchema == null) {
            log.Debug(string.Format("Publication '{0}' does not have a Metadata Schema", publication.Title));
            return;
        }

        ItemFields pubMetaFields = new ItemFields(publication.Metadata, publication.MetadataSchema);
        ComponentLinkField configLinkField = pubMetaFields["Configuration"] as ComponentLinkField;
        foreach (Component configComponent in configLinkField.Values) {
            log.Debug("Identified Configuration Component " + configComponent.WebDavUrl);
            CreateItemsFromConfiguration(configComponent, package, publication);
        }

        AddPublicationUrlPath(package, publication);
    }

    private void AddPublicationUrlPath(Package package, Publication publication) {
        string path = publication.PublicationPath;
        if (path.EndsWith("/") || path.EndsWith("\\")) {
            path = path.Substring(0, path.Length - 1);
        }
        package.PushItem("PublicationPath", package.CreateStringItem(ContentType.Text, path));

        path = publication.PublicationUrl;
        if (path.EndsWith("/") || path.EndsWith("\\")) {
            path = path.Substring(0, path.Length - 1);
        }
        package.PushItem("PublicationUrl", package.CreateStringItem(ContentType.Text, path));
    }

    private void CreateItemsFromConfiguration(Component component, Package package, Publication publication) {
        GenericUtils utils = new GenericUtils();
        ItemFields fields = new ItemFields(component.Content, component.Schema);
        foreach (ItemField field in fields) {
            if (field is ComponentLinkField) {
                string name = Regex.Replace(field.Name, "\\W", string.Empty);
                Component value = ((ComponentLinkField)field).Value;
                Item item = package.GetByName(name);
                if (item == null) {
                    log.Debug(string.Format("Add Component {0} = {1} to package", name, value.Id));
                    package.PushItem(name, package.CreateTridionItem(ContentType.Component, value));
                } else {
                    log.Debug(string.Format("Update Component {0} = {1} in package", name, value.Id));
                    item.SetAsXmlDocument(value.Content.OwnerDocument);
                }
            } else if (field is EmbeddedSchemaField && field.Name == "SystemValues") {
                foreach (ItemFields embeddedFields in ((EmbeddedSchemaField)field).Values) {
                    string name = Regex.Replace(((TextField)embeddedFields["Name"]).Value, "\\W", string.Empty);
                    string value = ((TextField)embeddedFields["Value"]).Value;
                    value = utils.LocalizeUri(value, publication.Id.ItemId);

                    Item item = package.GetByName(name);
                    if (item == null) {
                        log.Debug(string.Format("Add {0} = {1} to package", name, value));
                        package.PushItem(name, package.CreateStringItem(ContentType.Text, value));
                    } else {
                        log.Debug(string.Format("Update {0} = {1} in package", name, value));
                        item.SetAsString(value);
                    }
                }
            }
        }
    }
}

Where the GenericUtils methods are:

public Publication GetContextPublication(Engine engine, Package package) {
    Item item = GetPageOrComponentItem(package);
    RepositoryLocalObject respositoryLocalObject = engine.GetObject(item) as RepositoryLocalObject;
    return respositoryLocalObject.ContextRepository as Publication;
}

public string LocalizeUri(string tcmUri, int publicationId) {
    if (TcmUri.IsValid(tcmUri)) {
        TcmUri uri = new TcmUri(tcmUri);
        tcmUri = new TcmUri(uri.ItemId, uri.ItemType, publicationId).ToString();
    }

    return tcmUri;
}

public string LocalizeUri(Engine engine, string tcmUri) {
    if (TcmUri.IsValid(tcmUri)) {
        return engine.LocalizeUri(new TcmUri(tcmUri));
    } else {
        return tcmUri;
    }
}


Comments

Popular posts from this blog

Toolkit - Dynamic Content Queries

This post if part of a series about the  File System Toolkit  - a custom content delivery API for SDL Tridion. This post presents the Dynamic Content Query capability. The requirements for the Toolkit API are that it should be able to provide CustomMeta queries, pagination, and sorting -- all on the file system, without the use third party tools (database, search engines, indexers, etc). Therefore I had to implement a simple database engine and indexer -- which is described in more detail in post Writing My Own Database Engine . The querying logic does not make use of cache. This means the query logic is executed every time. When models are requested, the models are however retrieved using the ModelFactory and those are cached. Query Class This is the main class for dynamic content queries. It is the entry point into the execution logic of a query. The class takes as parameter a Criterion (presented below) which triggers the execution of query in all sub-criteria of a Criterio

A DD4T.net Implementation - Custom Binary Publisher

The default way to publish binaries in DD4T is implemented in class DD4T.Templates.Base.Utils.BinaryPublisher and uses method RenderedItem.AddBinary(Component) . This produces binaries that have their TCM URI as suffix in their filename. In my recent project, we had a requirement that binary file names should be clean (without the TCM URI suffix). Therefore, it was time to modify the way DD4T was publishing binaries. The method in charge with publishing binaries is called PublishItem and is defined in class BinaryPublisher . I therefore extended the BinaryPublisher and overrode method PublishItem. public class CustomBinaryPublisher : BinaryPublisher { private Template currentTemplate; private TcmUri structureGroupUri; In its simplest form, method PublishItem just takes the item and passes it to the AddBinary. In order to accomplish the requirement, we must specify a filename while publishing. This is the file name part of the binary path of Component.BinaryConten

Scaling Policies

This post is part of a bigger topic Autoscaling Publishers in AWS . In a previous post we talked about the Auto Scaling Groups , but we didn't go into details on the Scaling Policies. This is the purpose of this blog post. As defined earlier, the Scaling Policies define the rules according to which the group size is increased or decreased. These rules are based on instance metrics (e.g. CPU), CloudWatch custom metrics, or even CloudWatch alarms and their states and values. We defined a Scaling Policy with Steps, called 'increase_group_size', which is triggered first by the CloudWatch Alarm 'Publish_Alarm' defined earlier. Also depending on the size of the monitored CloudWatch custom metric 'Waiting for Publish', the Scaling Policy with Steps can add a difference number of instances to the group. The scaling policy sets the number of instances in group to 1 if there are between 1000 and 2000 items Waiting for Publish in the queue. It also sets the