Reading Component Field Values in .Net Assemblies, C# TBBs Using TOM.NET API

Below you can find a plethora of ways to read your Component field values in C# TBB or while  developing .Net Assemblies.

Before starting, note the different ways of getting a Component in C# TBB and in .Net Assemblies :

// Normally use below line in .Net Assemblies
// the componentURI can be either the TCMURI or a WebDav URL 
Component component = (Component)_engine.GetObject(componentURI);

// In a C# TBB you can use below sample for getting the Component 
// The C# TBB must be used inside a ComponentTemplate
Item componentItem = package.GetByType(ContentType.Component);
Component component= engine.GetObject(componentItem.GetAsSource().GetValue("ID")) 
                     as Component;
// You may need to import below namespaces in a C# TBB
<%@ Import Namespace="Tridion.ContentManager.ContentManagement.Fields"%>
<%@ Import Namespace="System.Collections.Generic"%>

// Same Namespaces should be there in your .Net Assemblies
using Tridion.ContentManager.ContentManagement.Fields;
using System.Collections.Generic;

Let’s get movin’…

Reading a Text Field:

// Get the Component first as shown above.
// Now get the fields
ItemFields fields = new ItemFields(component.Content, component.Schema);
TextField text = fields["ShortDescription"] as TextField;
// Get the value of 'ShortDescription' field in component
string description = text.Value;

Reading a Component Link Field :

Component component = (Component)_engine.GetObject(componentURI);
 ItemFields componentFields = new ItemFields(component.Content, component.Schema);
// Use ComponentLinkField class to read a field of component linking to 
// another component
 ComponentLinkField field = componentFields["Summary"] as ComponentLinkField;
// Get the Linked Component
Component component = field.Value;
// Now we have the linked component. Use any property of the Component class now 
// such as Id, Metadata , Schema, Title, Version, Path, OrganizationalItem etc..
// OR we can read the fields of this linked component as already shown

Reading a Multimedia Link Field :

Component component = (Component)_engine.GetObject(componentURI);
 ItemFields componentFields = new ItemFields(component.Content, component.Schema);
// Use MultimediaLinkField class to read a field of component that links to 
// a multimedia component
 MultimediaLinkField mmfield = componentFields["SiteLogo"] as MultimediaLinkField ;
 Component mmComponent = mmfield.Value;  

Reading MultiMedia Component’s Metadata

    // Get the Multimedia Component as shown above
    // Now read the Metadata fields like: AltText, AltTitle 
    ItemFields metaFields = new ItemFields(mmComponent.Metadata, mmComponent.MetadataSchema);
    TextField altText= metafields["AltText"] as TextField;
    string alternateTextValue = altTtext.Value;

Reading a Keyword Field & its Category:

Component component = (Component)_engine.GetObject(componentURI);
ItemFields componentFields = new ItemFields(component.Content, component.Schema);
// Use KeywordField class to read Keyword fields of a component
KeywordField _keywordfield = componentFields["RecipeCategory"] as KeywordField ;
if(_keywordfield ! = null )
 // Get the Keyword
 Keyword keyword= _keywordfield.Value;
 // Get the Category to which this Keyword belongs
 Category category = _keywordfield.Value.OrganizationalItem;

Reading Component’s Metadata Field:

Component component = (Component)_engine.GetObject(componentURI);
ItemFields metaFields = new ItemFields(component.Metadata, component.MetadataSchema);
TextField text = metafields["MetaDescription"] as TextField;
string description = text.Value;

Going  the XML’s way:

 Component component = (Component)_engine.GetObject(componentURI);
 string getfieldName = "MetaDescription";
 string fieldValue = string.Empty;
 if (component != null)
  {
             foreach (XmlNode node in component.Metadata.ChildNodes)
               {
               if (node.Name.ToLower() == getfieldName.ToLower())
                       {
                          fieldValue = node.InnerText;
                          break;
                        }
                }
   }

NOTE:

  1. The above code snippet can be used to read Metadata field values of Multimedia Components to fill the ‘alt’ and ‘title’ attributes etc…, Just pass the Multimedia Component URI in componentURI variable.
  2. In case of a Component, Component.MetadataSchema and Component.Schema means the same thing

Reading Embedded Field Values :

Most of the time we struggle to read an Embbeded Field value from component. Specially when that EmbeddedField is repeating.  However using simple classes from TOM.NET API , we can read these values .

Consider, we have an EmbeddedField  : ” Link ” in one of our Components as seen below. This embeded field is repeating and has sub fields: LinkText, ExternalURL, InternalUrl, LinkType and LinkInfo .
EmbeddedField

Below is what the Source looks like:

Source

Below Code Snippet reads these field values and , just for example , pushes them to package

   ItemFields componentFields = new ItemFields(component.Content, component.Schema);
    if (componentFields.Contains("Link")) 
     {
       EmbeddedSchemaField LinkField = componentFields["Link"] as EmbeddedSchemaField;
         if (LinkField != null) 
            {               
               IList<ItemFields> linkFieldValues = LinkField.Values;
                foreach (ItemFields innerFields in linkFieldValues) 
                 {
                   if (innerFields.Contains("LinkText"))
                    {
                    // get the "LinkText" field for example
                     TextField text = innerFields["LinkText"] as TextField;
                     // Add to package as an Example 
                      package.PushItem(text.Name,
                        package.CreateStringItem(ContentType.Text, text.Value)); 
                     }
                  }
             }
       }

NOTE

  1. Here the Embedded Schema Field “Link” is repeating more than once, So we should use the Values property as in: LinkField.Values
  2.  In case the Embedded Schema Field occurs just one time, we can use Value property, Although using Values property is still safe, in that case your IList<ItemFields> will have a single item.[Count equals 1]
  3. Even if the Embedded Schema Field “Link” is repeating more than once, we can use the Value property, Although, in this case we will  directly & only get the FIRST item in collection.

Hope you enjoyed this post. Comments and Suggestions are welcome…


11 thoughts on “Reading Component Field Values in .Net Assemblies, C# TBBs Using TOM.NET API

  1. This seems more than sufficient ways of reading component fields. This article was too much for me to be consumed in a single reading. with few sittings i was able to grasp the implementations.

    Why you have limited this article only to Assemblies and C# TBB ? It would be great if you can also share some implementation examples in DWT .

    Like

  2. This is really great great information . All the possible ways of reading fields seems to be covered.

    Thank you for your time on writing such a post. This helped me a lot to write and process Components data in .Net Assemblies without much difficulty. Many of the above snippets I just copy pasted and they work straightaway, of course with my own TCM Uris :)

    Like

  3. Thank you for this amazing article. All of the above code worked like a charm. Special thanks for sharing the way to read Embedded field using TOM.NET API. I used to be stuck most of the time reading Embedded fields with no idea on how to read Lists / index of such fields. This post gives an excellent clarity and approach to reading such fields.

    Like

  4. More than Tridion’s own documentation, it is the various blogs on Tridion that has made learning much easier.

    Thanks for sharing such an excellent technical post on reading fields using Tom.NET API. This way you listed all possible ways of reading different kinds of Fields is superb.

    I now look forward to more of such articles on Tridion from this blog.

    Liked by 1 person

  5. A very well written, concise and wonderful article. I actually enjoyed learning the topics one by one.

    This post explores the various classes and namespaces of TOM.NET API perfectly and helped me get started a lot. Just one suggestion that can you also share examples on various conditionings, Repeating Regions and other in DWTs ? That will be great.

    Like

  6. Great Post Nitesh. The classes in Tom.Net API are very well explored and illustrated.

    The part illustrating Metadata access for Multimedia and the part illustrating Embedded Field access are specially notable ones and are just EXCELLENT!

    I was having hard time reading metadata from images and reading embedded fields, after goggling a lot and going through forums, I landed up here. Keep up the good work!!

    Like

  7. Hi: thanks for this post: clear and simple, well done!!

    I`ve got one question: would it be possible to access to the URL of the page that contains the Component obtained in my .NET assembly?

    Thanks and greetings.

    Like

      1. Hi, Nitesh:

        I finally could manage to solve it in the following way, taken the String sUri as the tcm of the Tridion Component:

        String strParentLink = “”;
        Component component = engine.GetObject(sUri) as Component;
        XmlElement xUrls = component.GetListUsingItems();
        XmlNodeList elemList = xUrls.GetElementsByTagName(“tcm:Item”);
        String id;
        foreach (XmlNode node in elemList){
        id = node.Attributes[“ID”].Value;
        if (null != id && node.Attributes[“Type”].Value == “64”){
        Page page = engine.GetObject(id) as Page;
        strParentLink = page.PublishLocationUrl;
        }
        }

        Check if you agree. Greetings.

        Liked by 1 person

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s