private Binary PublishLocalizationData(IEnumerable <Binary> binaries, Component relatedComponent)
        {
            ComponentTemplatesFilter ctFilter = new ComponentTemplatesFilter(Session)
            {
                AllowedOnPage = false,
                BaseColumns   = ListBaseColumns.IdAndTitle
            };
            const string      dataPresentationTemplateTitle = "Generate Data Presentation";
            ComponentTemplate dataPresentationTemplate      = Publication.GetComponentTemplates(ctFilter).FirstOrDefault(ct => ct.Title == dataPresentationTemplateTitle);
            string            dataPresentationUri           = dataPresentationTemplate?.Id ?? string.Empty;

            string localizationId = Publication.Id.ItemId.ToString();

            List <SiteLocalizationData> siteLocalizations = DetermineSiteLocalizations(Publication);

            LocalizationData localizationData = new LocalizationData
            {
                IsDefaultLocalization       = siteLocalizations.First(p => p.Id == localizationId).IsMaster,
                IsXpmEnabled                = IsXpmEnabled,
                MediaRoot                   = Publication.MultimediaUrl,
                SiteLocalizations           = siteLocalizations.ToArray(),
                ConfigStaticContentUrls     = binaries.Select(b => b.Url).ToArray(),
                DataPresentationTemplateUri = dataPresentationUri
            };

            return(AddJsonBinary(localizationData, relatedComponent, _configStructureGroup, "_all", variantId: "config-bootstrap"));
        }
Beispiel #2
0
        private void FindDataPresentationTemplate()
        {
            RepositoryLocalObject sourceItem         = (RepositoryLocalObject)RenderedItem.ResolvedItem.Item;
            Publication           contextPublication = (Publication)sourceItem.ContextRepository;

            ComponentTemplatesFilter ctFilter = new ComponentTemplatesFilter(Session)
            {
                AllowedOnPage = false,
                BaseColumns   = ListBaseColumns.IdAndTitle
            };

            // TODO: use marker App Data instead of the CTs Title.
            const string dataPresentationTemplateTitle = "Generate Data Presentation";

            _dataPresentationTemplate = contextPublication.GetComponentTemplates(ctFilter).FirstOrDefault(ct => ct.Title == dataPresentationTemplateTitle);

            if (_dataPresentationTemplate == null)
            {
                Logger.Warning($"Component Template '{dataPresentationTemplateTitle}' not found.");
                _dataPresentationTemplateNotFound = true;
            }
            else
            {
                Logger.Debug($"Found Data Presentation Template: {_dataPresentationTemplate.FormatIdentifier()}");
            }
        }
Beispiel #3
0
        public override void Transform(Engine engine, Package package)
        {
            base.Initialize(engine, package);

            Item   outputItem = package.GetByName(Package.OutputName);
            string output     = outputItem.GetAsString();

            var templateNames = GetTemplateNames(output);

            var filter = new ComponentTemplatesFilter(engine.GetSession());

            _templates = GetPublication().GetListComponentTemplates(filter);

            if (_templates == null)
            {
                Logger.Info("there were not Component Templates.");
            }

            foreach (var item in templateNames)
            {
                var templateTcmid = GetTemplateTcmId(item.Item2);

                if (string.IsNullOrEmpty(templateTcmid))
                {
                    return;
                }

                var cpContent = m_Engine.RenderComponentPresentation(new TcmUri(item.Item1), new TcmUri(templateTcmid));
                output = output.Replace(item.Item3, cpContent);
                Logger.Info(string.Format("replaced {0} by {1}", item.Item2, templateTcmid));
            }

            //Save the changes in output.
            outputItem.SetAsString(output);
        }
        private Dictionary <string, List <string> > BuildRegionMappings()
        {
            // format:  region { schema, template }
            Dictionary <string, List <string> > regions = new Dictionary <string, List <string> >();

            ComponentTemplatesFilter templateFilter = new ComponentTemplatesFilter(Engine.GetSession())
            {
                BaseColumns = ListBaseColumns.Extended
            };

            foreach (ComponentTemplate template in GetPublication().GetComponentTemplates(templateFilter))
            {
                string regionName = GetRegionName(template);

                if (!regions.ContainsKey(regionName))
                {
                    regions.Add(regionName, new List <string>());
                }

                StringBuilder allowedComponentTypes = new StringBuilder();
                bool          first = true;
                foreach (Schema schema in template.RelatedSchemas)
                {
                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        allowedComponentTypes.Append(",");
                    }
                    allowedComponentTypes.AppendFormat("{{\"Schema\":{0},\"Template\":{1}}}", JsonEncode(schema.Id.GetVersionlessUri().ToString()), JsonEncode(template.Id.GetVersionlessUri().ToString()));
                }

                // do not append empty strings (template.RelatedSchemas can be empty)
                if (allowedComponentTypes.Length > 0)
                {
                    regions[regionName].Add(allowedComponentTypes.ToString());
                }
            }
            return(regions);
        }
        public void Resolve(IdentifiableObject item, ResolveInstruction instruction, PublishContext context,
                            ISet <ResolvedItem> resolvedItems)
        {
            if (instruction.Purpose != ResolvePurpose.Publish && instruction.Purpose != ResolvePurpose.RePublish)
            {
                return;
            }
            var sourceItem         = (RepositoryLocalObject)item;
            var contextPublication = (Publication)sourceItem.ContextRepository;
            var filter             = new ComponentTemplatesFilter(item.Session)
            {
                AllowedOnPage = false,
                BaseColumns   = ListBaseColumns.IdAndTitle
            };
            const string dataPresentationTemplateTitle = "Generate Data Presentation";
            var          dataPresentationTemplate      = contextPublication.GetComponentTemplates(filter).FirstOrDefault(
                ct => ct.Title == dataPresentationTemplateTitle);
            var resolvedItemList = resolvedItems.ToArray();

            foreach (var resolvedItem in resolvedItemList)
            {
                if (!(resolvedItem.Item is Page))
                {
                    continue;
                }
                var page = (Page)resolvedItem.Item;
                if (page.ComponentPresentations.Count <= 0)
                {
                    continue;
                }
                // for each component lets resolve it with our data presentation template
                foreach (var cp in page.ComponentPresentations.Where(
                             cp =>
                             dataPresentationTemplate != null &&
                             dataPresentationTemplate.RelatedSchemas.Contains(cp.Component.Schema)))
                {
                    resolvedItems.Add(new ResolvedItem(cp.Component, dataPresentationTemplate));
                }
            }
        }
 protected virtual Dictionary<string, List<string>> ReadTemplateData()
 {
     //Generate a list of dynamic CT + id, separated by module
     Dictionary<string, List<string>> res = new Dictionary<string, List<string>>();
     ComponentTemplatesFilter templateFilter = new ComponentTemplatesFilter(Engine.GetSession()) { BaseColumns = ListBaseColumns.Extended };
     foreach (XmlElement item in GetPublication().GetListComponentTemplates(templateFilter).ChildNodes)
     {
         string id = item.GetAttribute("ID");
         ComponentTemplate template = (ComponentTemplate)Engine.GetObject(id);
         //Only consider dynamic CTs
         if (template.IsRepositoryPublishable)
         {
             string module = GetModuleNameFromItem(template, _moduleRoot);
             if (module != null)
             {
                 string key = module + "." + TemplateConfigName;
                 if (!res.ContainsKey(key))
                 {
                     res.Add(key, new List<string>());
                 }
                 res[key].Add(String.Format("{0}:{1}", JsonEncode(Utility.GetKeyFromTemplate(template)), JsonEncode(template.Id.ItemId)));
             }
         }
     }
     return res;
 }
        /// <summary>
        /// Entry point for resolver.
        /// </summary>
        /// <param name="item">Item to resolve</param>
        /// <param name="instruction">Resolve instruction</param>
        /// <param name="context">Publish context</param>
        /// <param name="resolvedItems">Final items to resolve</param>
        public void Resolve(IdentifiableObject item, ResolveInstruction instruction, PublishContext context,
                            Tridion.Collections.ISet <ResolvedItem> resolvedItems)
        {
            if (instruction.Purpose != ResolvePurpose.Publish && instruction.Purpose != ResolvePurpose.RePublish ||
                _maxRecurseDepth == 0)
            {
                return;
            }
            _log.Debug("DXA Custom Resolver started...");
            _log.Debug("Loading global app data:");
            const string appId = "dxa:CustomResolver";

            try
            {
                var appData = context.Session.SystemManager.LoadGlobalApplicationData(appId);
                if (appData != null)
                {
                    _log.Debug("Found configuration for custom resolver in global app data. Attempting to parse.");
                    string xml = string.Empty;
                    if (appData.TypeId?.StartsWith("XmlElement:") ?? false)
                    {
                        _log.Debug($"Found configuration using XElement appData type.");
                        string      @string     = Encoding.UTF8.GetString(appData.Data);
                        XmlDocument xmlDocument = new XmlDocument();
                        xmlDocument.LoadXml(@string);
                        xml = xmlDocument.DocumentElement?.OuterXml;
                    }
                    if (string.IsNullOrEmpty(xml))
                    {
                        _log.Debug("Assuming string content for xml.");
                        xml = Encoding.Unicode.GetString(appData.Data);
                    }
                    _log.Debug($"xml={xml}");
                    XElement parsedXml = XElement.Parse(xml);
                    foreach (XElement xe in parsedXml.Elements())
                    {
                        if (!xe.Name.LocalName.Equals("RecurseDepth"))
                        {
                            continue;
                        }
                        _log.Debug($"Found RecurseDepth value of '{xe.Value}'.");
                        _maxRecurseDepth = int.Parse(xe.Value);
                        break; // only one setting at moment
                    }
                }
                else
                {
                    _log.Debug(
                        $"Custom resolver configuration not found in global app data for '{appId}'. Using default settings.");
                    _maxRecurseDepth = -1;
                }
            }
            catch (Exception e)
            {
                _log.Debug(
                    $"Exception occured when reading global app data for application id '{appId}'. Using default settings.");
                _log.Debug(e.Message);
                _maxRecurseDepth = -1;
            }

            _log.Debug($"Using _maxRecurseDepth={_maxRecurseDepth}");

            try
            {
                var sourceItem = (RepositoryLocalObject)item;

                _log.Debug($"Analyzing source item of type: {item.GetType().Name} with id: {item.Id} and title: {item.Title}");

                var contextPublication = (Publication)sourceItem.ContextRepository;
                var filter             = new ComponentTemplatesFilter(item.Session)
                {
                    AllowedOnPage = false,
                    BaseColumns   = ListBaseColumns.IdAndTitle
                };
                const string dataPresentationTemplateTitle = "Generate Data Presentation";
                var          dataPresentationTemplate      = contextPublication.GetComponentTemplates(filter).FirstOrDefault(
                    ct => ct.Title == dataPresentationTemplateTitle);
                if (dataPresentationTemplate == null)
                {
                    _log.Debug("No 'Generate Data Presentation' component template found. Skipping custom resolver.");
                    return;
                }
                var       resolved = new HashSet <IdentifiableObject>();
                Stopwatch t        = new Stopwatch();
                t.Start();

                HashSet <TcmUri> alreadyResolved = new HashSet <TcmUri>();
                foreach (var x in resolvedItems)
                {
                    alreadyResolved.Add(x.Item.Id);
                }

                List <ResolvedItem> resolvedItemsCopy = new List <ResolvedItem>(resolvedItems);
                foreach (var resolvedItem in resolvedItemsCopy)
                {
                    foreach (var dataPresentation in ResolveDataPresentations(resolvedItem.Item, dataPresentationTemplate, resolved, 0))
                    {
                        if (alreadyResolved.Contains(dataPresentation.Item.Id))
                        {
                            _log.Debug($"  > Already resolved item '{dataPresentation.Item.Title}' with id: {dataPresentation.Item.Id}");
                            continue;
                        }
                        _log.Debug($"  > Resolved item '{dataPresentation.Item.Title}' with id: {dataPresentation.Item.Id}");
                        alreadyResolved.Add(dataPresentation.Item.Id);
                        resolvedItems.Add(dataPresentation);
                    }
                }

                t.Stop();
                _log.Debug($"DXA Custom Resolver took {t.ElapsedMilliseconds}ms to complete.");
            }
            catch (Exception e)
            {
                _log.Debug($"Exception occured: {e.Message}");
                _log.Debug($"Stacktrace: {e.StackTrace}");
                throw;
            }
        }
        private Dictionary<string, List<string>> BuildRegionMappings()
        {
            // format:  region { schema, template }
            Dictionary<string, List<string>> regions = new Dictionary<string, List<string>>();

            ComponentTemplatesFilter templateFilter = new ComponentTemplatesFilter(Engine.GetSession()) { BaseColumns = ListBaseColumns.Extended };
            foreach (ComponentTemplate template in GetPublication().GetComponentTemplates(templateFilter))
            {
                string regionName = GetRegionName(template);

                if (!regions.ContainsKey(regionName))
                {
                    regions.Add(regionName, new List<string>());
                }

                StringBuilder allowedComponentTypes = new StringBuilder();
                bool first = true;
                foreach (Schema schema in template.RelatedSchemas)
                {
                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        allowedComponentTypes.Append(",");
                    }
                    allowedComponentTypes.AppendFormat("{{\"Schema\":{0},\"Template\":{1}}}", JsonEncode(schema.Id.GetVersionlessUri().ToString()), JsonEncode(template.Id.GetVersionlessUri().ToString()));
                }

                // do not append empty strings (template.RelatedSchemas can be empty)
                if (allowedComponentTypes.Length > 0)
                {
                    regions[regionName].Add(allowedComponentTypes.ToString());
                }
            }
            return regions;
        }
Beispiel #9
0
        private Dictionary<string, List<string>> BuildRegionMappings()
        {
            // format:  region { schema, template }
            Dictionary<string, List<string>> regions = new Dictionary<string, List<string>>();

            var templateFilter = new ComponentTemplatesFilter(Engine.GetSession()) { BaseColumns = ListBaseColumns.Extended };
            foreach (XmlElement item in GetPublication().GetListComponentTemplates(templateFilter).ChildNodes)
            {
                var id = item.GetAttribute("ID");
                var template = (ComponentTemplate)Engine.GetObject(id);
                var region = GetRegionFromTemplate(template);

                if (!regions.ContainsKey(region))
                {
                    regions.Add(region, new List<string>());
                }

                StringBuilder allowedComponentTypes = new StringBuilder();
                bool first = true;
                foreach (var schema in template.RelatedSchemas)
                {
                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        allowedComponentTypes.Append(",");
                    }
                    allowedComponentTypes.AppendFormat("{{\"Schema\":{0},\"Template\":{1}}}", JsonEncode(schema.Id.GetVersionlessUri().ToString()), JsonEncode(template.Id.GetVersionlessUri().ToString()));
                }

                // do not append empty strings (template.RelatedSchemas can be empty)
                if (allowedComponentTypes.Length > 0)
                {
                    regions[region].Add(allowedComponentTypes.ToString());
                }
            }
            return regions;
        }