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

Running sp_updatestats on AWS RDS database

Part of the maintenance tasks that I perform on a MSSQL Content Manager database is to run stored procedure sp_updatestats . exec sp_updatestats However, that is not supported on an AWS RDS instance. The error message below indicates that only the sa  account can perform this: Msg 15247 , Level 16 , State 1 , Procedure sp_updatestats, Line 15 [Batch Start Line 0 ] User does not have permission to perform this action. Instead there are several posts that suggest using UPDATE STATISTICS instead: https://dba.stackexchange.com/questions/145982/sp-updatestats-vs-update-statistics I stumbled upon the following post from 2008 (!!!), https://social.msdn.microsoft.com/Forums/sqlserver/en-US/186e3db0-fe37-4c31-b017-8e7c24d19697/spupdatestats-fails-to-run-with-permission-error-under-dbopriveleged-user , which describes a way to wrap the call to sp_updatestats and execute it under a different user: create procedure dbo.sp_updstats with execute as 'dbo' as...

REL Standard Tag Library

The RSTL is a library of REL tags providing standard functionality such as iterating collections, conditionals, imports, assignments, XML XSLT transformations, formatting dates, etc. RSTL distributable is available on my Google Code page under  REL Standard Tag Library . Always use the latest JAR . This post describes each RSTL tag in the library explaining its functionality, attributes and providing examples. For understanding the way expressions are evaluated, please read my post about the  Expression Language used by REL Standard Tag Library . <c:choose> / <c:when> / <c:otherwise> Syntax:     <c:choose>         <c:when test="expr1">             Do something         </c:when>         <c:when test="expr2">             Do something else         </c:when...

Publish Binaries to Mapped Structure Groups

Today's TBB of the Week comes from the high demand in the field to publish binary assets to different mapped Structure Groups. By default SDL Tridion offers two ways of publishing binaries: All binaries publish to a folder defined in your Publication properties; All binaries rendered by a given template publish to a folder corresponding to a given Structure Group; In my view, both cases are terrible, over-simplified and not representing a real use-case. Nobody in the field wants all binaries in one folder and nobody separates binary locations by template. Instead, everybody wants a mapping mechanism that takes a binary and publishes it to a given folder, defined by a Structure Group, and this mapping is done using some kind of metadata. More often than not, the metadata is the TCM Folder location of the Multimedia Component. I have seen this implemented numerous times. So the solution to publish binaries to a given location implies finding a mapping from a TCM Folder to a...