Skip to main content

Get Linked Components TBB

This weeks "TBB of the Week" is Get Linked Components TBB. I don't know who exactly wrote it, so I'm not taking credit for it. It is part of the Templating Base project, IIRC.

Name
Get Linked Components TBB
Type
·    Template in .NET Assembly
Description
Used to:
·    Extract Component links from Page metadata or from Component fields;
·    Create Package items from the identified Components;
Notes:
When placed on a Page Template, this generic TBB identifies Component Links from the Page’s Metadata section.
When placed on a Component Template, it identifies Component Links in the current Component’s fields (including RTF and Component Link fields) and metadata fields.
The TBB pushes each identified Component into the Package.
Parameters
n/a
Applicable to
Component Templates and Page Templates

This is a very powerful TBB that I use in almost all my projects. The issue it solves is the following: whenever there a Component Link appears in Component's RTF or link field (or Page metadata), it is impossible using Dreamweaver syntax alone, to access the linked Component fields directly. Instead, this TBB should be used to place the linked Component in the Package and then access its fields.

The Code

[TcmTemplateTitle("Get Linked Components TBB")]
public class GetLinkedComponents : ITemplate {

    private Engine _engine = null;
    private Package _package = null;
    private TemplatingLogger _log = null;
    //-1 = not set, 0 = component, 1 = page
    private int _renderContext = -1;

    /// <summary>
    /// Executes the transformation
    /// </summary>
    /// <param name="engine">Templating engine (context for the template code)</param>
    /// <param name="package">Transformation context (contains both the inputs and the outputs of the transformation)</param>
    void ITemplate.Transform(Engine engine, Package package) {
        _engine = engine;
        _package = package;
        _log = TemplatingLogger.GetLogger(this.GetType());

        if (IsPage) {
            //Add linked components from metadata
            _log.Info("Scanning Page Metadata for link fields...");
            AddLinkedComponents(GetContextItemFields("meta"), "MetaData.", 0);
        } else {
            //Add both linked components from standard schema and metadata fields
            //_log.Info("Scanning Component for link fields...");
            AddLinkedComponents(GetContextItemFields("link"), string.Empty, 0);
            //_log.Info("Scanning Component Metadata for link fields...");
            AddLinkedComponents(GetContextItemFields("meta"), "MetaData.", 0);
            //Fix for RenderComponentField
            Item MainComponent = _package.GetByName("Component");
            _package.Remove(MainComponent);
            _package.PushItem("Component", MainComponent);
        }
    }

    /// <summary>
    /// Add linked components to the package from the given fields
    /// </summary>
    /// <param name="fields">The ItemFields to search for component links</param>
    /// <param name="packageKeyPostfix">Postfix to add to package item name</param>
    private void AddLinkedComponents(ItemFields fields, string packageKeyPrefix, int depth) {
        if (fields != null) {
            Hashtable itemFieldCounter = new Hashtable();
            foreach (ItemField itemField in fields) {
                String itemFieldName = itemField.Name.ToString();

                if (!itemFieldCounter.ContainsKey(itemFieldName)) {
                    itemFieldCounter[itemFieldName] = 0;
                } else {
                    itemFieldCounter[itemFieldName] = (int)itemFieldCounter[itemFieldName] + 1;
                }

                if (itemField is ComponentLinkField) {
                    ComponentLinkField field = itemField as ComponentLinkField;

                    if (depth > 0) {
                        _log.Info("Found 1 deep: " + field.Name);
                    }

                    if (field != null && ((field.Definition.MaxOccurs == 1 && field.Value != null) || field.Values != null)) {
                        // --------------------------
                        Item item = null;
                        if (field.Definition.MaxOccurs == 1 && field.Value != null) {
                            //If the field is single value, add it to the package as a component
                            //_log.Info("Found single value link field: " + field.Name);
                            item = _package.CreateTridionItem(ContentType.Component, field.Value.Id);
                        } else {
                            //Otherwise create a uri list of all values
                            IList<TcmUri> uriList = new List<TcmUri>();
                            foreach (Component linkedComp in field.Values) {
                                uriList.Add(linkedComp.Id);
                            }
                            if (uriList.Count > 0) {
                                //_log.Info("Found multivalue link field: " + field.Name);
                                item = _package.CreateComponentUriListItem(ContentType.ComponentArray, uriList);
                            }

                        }
                        if (item != null) {
                            _package.PushItem(packageKeyPrefix + field.Name, item);
                        }
                        // --------------------------
                    }
                }
                    /* */
                else if (itemField is EmbeddedSchemaField) {
                    EmbeddedSchemaField field = itemField as EmbeddedSchemaField;
                    ItemFields fieldValues = field.Values as ItemFields;
                    /* * /
                    if (field.Definition.MaxOccurs == 1 && field.Value != null)
                    {
                        //If the field is single value, add it to the package as a component
                        //_log.Info("Found single value Embedded field: " + field.Name + " -- " + field.Value.ToString());
                        //item = _package.CreateTridionItem(ContentType.Component, field.Value);
                    }
                    else
                    /* */
                    if (field.Values.Count > 0) {
                        //Otherwise create a uri list of all values
                        foreach (ItemFields linkedComp in field.Values) {
                            foreach (ItemField iField in linkedComp) {
                                String lItemFieldName = itemFieldName + "." + iField.Name.ToString();

                                if (!itemFieldCounter.ContainsKey(lItemFieldName)) {
                                    itemFieldCounter[lItemFieldName] = 0;
                                } else {
                                    itemFieldCounter[lItemFieldName] = (int)itemFieldCounter[lItemFieldName] + 1;
                                }

                                String newPackageKeyPrefix = packageKeyPrefix + lItemFieldName + itemFieldCounter[lItemFieldName];

                                // pass the fieldValues if its not null, and go only 1 deep
                                //_log.Info("Possible: " + newPackageKeyPrefix);
                                //_log.Info("???: " + field.Values.ToString());
                                //_log.Info("Found object: " + itemField.GetType().ToString());

                                if (iField is ComponentLinkField) {
                                    ComponentLinkField convIField = iField as ComponentLinkField;

                                    if (convIField != null && ((convIField.Definition.MaxOccurs == 1 && convIField.Value != null) || convIField.Values != null)) {
                                        Item convItem = null;
                                        if (convIField.Definition.MaxOccurs == 1 && convIField.Value != null) {
                                            //If the field is single value, add it to the package as a component
                                            //_log.Info("Found single value link field: " + field.Name);
                                            convItem = _package.CreateTridionItem(ContentType.Component, convIField.Value.Id);
                                        } else {
                                            //Otherwise create a uri list of all values
                                            IList<TcmUri> convUriList = new List<TcmUri>();
                                            foreach (Component convLinkedComp in convIField.Values) {
                                                if (convLinkedComp != null) {
                                                    convUriList.Add(convLinkedComp.Id);
                                                    _log.Info("Found multivalue link field: " + convLinkedComp);
                                                }
                                            }
                                            if (convUriList.Count > 0) {
                                                convItem = _package.CreateComponentUriListItem(ContentType.ComponentArray, convUriList);
                                            }

                                        }
                                        if (convItem != null) {
                                            _package.PushItem(newPackageKeyPrefix, convItem);
                                        }
                                    }
                                } else if (iField is EmbeddedSchemaField) {
                                    AddLinkedComponents(((EmbeddedSchemaField)iField).Value, newPackageKeyPrefix, depth + 1);
                                }
                            }
                        }

                    }
                    /* */

                } // end else if (itemField is EmbeddedSchemaField)
                else {
                    //_log.Info("Found itemField: " + itemField.Name.ToString());
                }
            }
        }
    }

    /// <summary>
    /// Get the ItemFields for the context item
    /// </summary>
    /// <returns></returns>
    private ItemFields GetContextItemFields(string type) {
        ItemFields fields = null;
        if (IsPage) {
            Item item = _package.GetByName("Page");
            if (item != null) {
                string pid = item.GetValue("ID");
                Page page = _engine.GetObject(pid) as Page;
                if (page.Metadata != null)
                    fields = new ItemFields(page.Metadata, page.MetadataSchema);
            }
        } else {
            Item item = _package.GetByName("Component");
            if (item != null) {
                string cid = item.GetValue("ID");
                Component comp = _engine.GetObject(cid) as Component;
                if (type == "meta" && comp.Metadata != null) {
                    fields = new ItemFields(comp.Metadata, comp.MetadataSchema);
                } else if (type == "link") {
                    fields = new ItemFields(comp.Content, comp.Schema);
                }
            }
        }
        return fields;
    }

    /// <summary>
    /// True if the rendering context is a page, rather than component
    /// </summary>
    private bool IsPage {
        get {
            if (_renderContext == -1) {
                if (_engine.PublishingContext.ResolvedItem.Item is Page)
                    _renderContext = 1;
                else
                    _renderContext = 0;
            }
            if (_renderContext == 1)
                return true;
            else
                return false;
        }
    }
}

Comments

Popular posts from this blog

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

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

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