Thursday 19 March 2015

Get Item Type, ID and Publication from a Tridion TCM

A quick and easy way to get itemId Type and Publication from a Tridion TCM, works with TCMs in the following formats


  • tcm:0-0-0
  • tcm:122-111-111
  • tcm:112-1132-44-v22
  • tcm:0-0
  • 12-23
  • 12-32-234
  • tcm:10-11
  • tcm:10-11-v44
  • tcm:10-11-16
  • tcm:10-11-16-v44

Usage


const string tcmString = "tcm:123-45-16";
var tridionTcm = new TridionTcm(tcmString);
var tcm = tridionTcm.Tcm;
var version = tridionTcm.Version;
var publicationId = tridionTcm.PublicationId;

Validate Tridion TCM using Regex

var isValid = TridionTcm.IsValidTcm("tcm:foo-bar");



    public class TridionTcm
    {
        private const string TridionRegPatern = @"(?tcm:)?(?[0-9]+)-(?[0-9]+)(?:-(?[0-9]+))?(?:-v(?[0-9]+))?";
        public int Id { get; private set; }
        public int PublicationId { get; private set; }
        public int TypeId { get; private set; }
        public String Tcm { get; private set; }
        public int? Version { get; private set; }


        public TridionTcm(string tcm)
        {
            tcm = tcm.ToLower();
            var rgx = new Regex(TridionRegPatern);
            var match = rgx.Match(tcm);
            PublicationId = int.Parse(match.Groups["publicationid"].Value);
            Id = int.Parse(match.Groups["itemid"].Value);
            TypeId = String.IsNullOrEmpty(match.Groups["typeid"].Value) ? 16 : int.Parse(match.Groups["typeid"].Value);
            Version = String.IsNullOrEmpty(match.Groups["version"].Value) ? (int?) null : int.Parse(match.Groups["version"].Value);
            Tcm = string.Format("tcm:{0}-{1}-{2}",PublicationId,Id,TypeId);

            if (!IsValidTcm(Tcm))
            {
                throw new Exception("I just created an invalid TCM, sorry.");
            }
        }



        public static Boolean IsValidTcm(string tcm)
        {
            tcm = tcm.ToLower();
            var rgx = new Regex(TridionRegPatern);
            return rgx.IsMatch(tcm);
        }


    }