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

Content Delivery Monitoring in AWS with CloudWatch

This post describes a way of monitoring a Tridion 9 combined Deployer by sending the health checks into a custom metric in CloudWatch in AWS. The same approach can also be used for other Content Delivery services. Once the metric is available in CloudWatch, we can create alarms in case the service errors out or becomes unresponsive. The overall architecture is as follows: Content Delivery service sends heartbeat (or exposes HTTP endpoint) for monitoring Monitoring Agent checks heartbeat (or HTTP health check) regularly and stores health state AWS lambda function: runs regularly reads the health state from Monitoring Agent pushes custom metrics into CloudWatch I am running the Deployer ( installation docs ) and Monitoring Agent ( installation docs ) on a t2.medium EC2 instance running CentOS on which I also installed the Systems Manager Agent (SSM Agent) ( installation docs ). In my case I have a combined Deployer that I want to monitor. This consists of an Endpoint and a

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

Event System to Create Mapped Structure Groups for Binary Publish

As a continuation of last week's Publish Binaries to Mapped Structure Group , this week's TBB is in fact the Event System part of that solution. Make sure you do check out the previous post first, which explains why and what this Event System does. To reiterate, the Event System intercepts a Multimedia Component save, take its Folder path and create a 1-to-1 mapping of Structure Groups. The original code was written, again, by my colleague Eric Huiza : [ TcmExtension ( "MyEvents" )] public class EventsManager  : TcmExtension {     private Configuration configuration;     private readonly Regex SAFE_DIRNAME_REGEX = new Regex ( @"[\W_]+" );     public EventsManager() {         ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap ();         fileMap.ExeConfigFilename = Path .GetDirectoryName( Assembly .GetExecutingAssembly().Location) + "\\EventSystem.config" ;         configuration = ConfigurationManager