public static Dynamic.ComponentPresentation BuildComponentPresentation(TCM.ComponentPresentation tcmComponentPresentation, Engine engine, BuildManager manager)
        {
            TemplatingLogger logger = TemplatingLogger.GetLogger(typeof(ComponentPresentationBuilder));

            Dynamic.ComponentPresentation cp = new Dynamic.ComponentPresentation();

            logger.Debug(string.Format(">BuildCP {0} ({1})", tcmComponentPresentation.ComponentTemplate.Title, tcmComponentPresentation.ComponentTemplate.IsRepositoryPublishable));
            if (tcmComponentPresentation.ComponentTemplate.IsRepositoryPublishable)
            {
                // call render but ignore the output - render ensures componentlinking will be setup as normal.
                // don't bother with page flags because the end result is dynamically published so it needs to run with DCP settings
                engine.RenderComponentPresentation(tcmComponentPresentation.Component.Id, tcmComponentPresentation.ComponentTemplate.Id);

                // ignore the rendered CP, because it is already available in the broker
                // instead, we will render a very simple version without any links
                cp.Component = manager.BuildComponent(tcmComponentPresentation.Component, 0); // linkLevel = 0 means: only summarize the component
                cp.IsDynamic = true;
            }
            else
            {
                // render the component presentation using its own CT
                // but first, set a parameter in the context so that the CT will know it is beng called
                // from a DynamicDelivery page template
                if (engine.PublishingContext.RenderContext != null && !engine.PublishingContext.RenderContext.ContextVariables.Contains(BasePageTemplate.VariableNameCalledFromDynamicDelivery))
                {
                    engine.PublishingContext.RenderContext.ContextVariables.Add(BasePageTemplate.VariableNameCalledFromDynamicDelivery, BasePageTemplate.VariableValueCalledFromDynamicDelivery);
                }

                string renderedContent = engine.RenderComponentPresentation(tcmComponentPresentation.Component.Id, tcmComponentPresentation.ComponentTemplate.Id);
                renderedContent = TridionUtils.StripTcdlTags(renderedContent);

                // rendered content could contain si4t search data. if that's the case, the value of renderedCotnent is not valid DD4T data.
                // lets remove the si4t search data if that's the case.
                string dd4tData = Si4tUtils.RemoveSearchData(renderedContent);

                try
                {
                    // we cannot be sure the component template uses the same serializer service as the page template
                    // so we will call a factory which can detect the correct service based on the content
                    ISerializerService serializerService = SerializerServiceFactory.FindSerializerServiceForContent(dd4tData);
                    cp = serializerService.Deserialize <Dynamic.ComponentPresentation>(dd4tData);

                    // inital renderedContent could contain si4t search data. we need to preserve the search data.
                    // lets retrieve the si4t search data if that's the case and added to the renderedContent property
                    cp.RenderedContent = Si4tUtils.RetrieveSearchData(renderedContent);
                }
                catch (Exception e)
                {
                    log.Error("exception while deserializing into CP", e);
                    // the component presentation could not be deserialized, this probably not a Dynamic Delivery template
                    // just store the output as 'RenderedContent' on the CP
                    cp.RenderedContent = renderedContent;
                    // because the CT was not a DD4T CT, we will generate the DD4T XML code here
                    cp.Component = manager.BuildComponent(tcmComponentPresentation.Component);
                }
                cp.IsDynamic = false;
            }
            cp.ComponentTemplate = manager.BuildComponentTemplate(tcmComponentPresentation.ComponentTemplate);
            return(cp);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="XsltExtensions"/> class.
 /// </summary>
 /// <param name="engine"><see cref="T:Tridion.ContentManager.Templating.Engine" /></param>
 /// <param name="package"><see cref="T:Tridion.ContentManager.Templating.Package" /></param>
 /// <param name="templateBase"><see cref="T:TcmTemplating.TemplateBase" /></param>
 public XsltExtensions(Engine engine, Package package, TemplateBase templateBase)
 {
     mTemplatingLogger = TemplatingLogger.GetLogger(this.GetType());
     mEngine = engine;
     mPackage = package;
     mTemplateBase = templateBase;
 }
        public void Transform(Engine engine, Package package)
        {
            TemplatingLogger log = TemplatingLogger.GetLogger(GetType());

            if (package.GetByName(Package.PageName) == null)
            {
                log.Info("Do not use this template building block in Component Templates");
                return;
            }

            Page page = (Page)engine.GetObject(package.GetByName(Package.PageName));

            string output;

            if (page.Title.ToLower().Contains("index"))
            {
                output = StripNumbersFromTitle(page.OrganizationalItem.Title);
            }
            else
            {
                output = GetLinkToSgIndexPage((StructureGroup)page.OrganizationalItem, engine.GetSession()) + Separator + StripNumbersFromTitle(page.Title);
            }

            foreach (OrganizationalItem parent in page.OrganizationalItem.GetAncestors())
            {
                output = GetLinkToSgIndexPage((StructureGroup)parent, engine.GetSession()) + Separator + output;
            }

            package.PushItem("breadcrumb", package.CreateStringItem(ContentType.Html, output));
        }
        public void Transform(Engine engine, Package package)
        {
            TemplatingLogger log = TemplatingLogger.GetLogger(GetType());
            if (package.GetByName(Package.ComponentName) == null)
            {
                log.Info("This template should only be used with Component Templates. Could not find component in package, exiting");
                return;
            }
            var c = (Component)engine.GetObject(package.GetByName(Package.ComponentName));
            var container = (Folder)c.OrganizationalItem;
            var filter = new OrganizationalItemItemsFilter(engine.GetSession()) { ItemTypes = new[] { ItemType.Component } };

            // Always faster to use GetListItems if we only need limited elements
            foreach (XmlNode node in container.GetListItems(filter))
            {
                string componentId = node.Attributes["ID"].Value;
                string componentTitle = node.Attributes["Title"].Value;
            }

            // If we need more info, use GetItems instead
            foreach (Component component in container.GetItems(filter))
            {
                // If your filter is messed up, GetItems will return objects that may
                // not be a Component, in which case the code will blow up with an
                // InvalidCastException. Be careful with filter.ItemTypes[]
                Schema componentSchema = component.Schema;
                SchemaPurpose purpose = componentSchema.Purpose;
                XmlElement content = component.Content;
            }


        }
        public void Transform(Engine engine, Package package)
        {
            _log = TemplatingLogger.GetLogger(GetType());

            RepositoryLocalObject context =
                engine.GetObject(package.GetByName(Package.PageName)) as RepositoryLocalObject;
            if (context == null)
            {
                _log.Error("Could not retrieve page from package. Exiting.");
                return;
            }
            string categoryUrl = context.ContextRepository.WebDavUrl + NavigationCategoryWebDavUrl;
            Category navigation = (Category)engine.GetObject(categoryUrl);

            using (MemoryStream ms = new MemoryStream())
            {
                XmlTextWriter w = new XmlTextWriter(ms, new UTF8Encoding(false))
                {
                    Indentation = 4,
                    Formatting = Formatting.Indented
                };

                w.WriteStartDocument();
                w.WriteStartElement(Navigation.RootNodeName);
                KeywordsFilter filter = new KeywordsFilter(engine.GetSession()) { IsRoot = true };
                foreach (XmlNode rootChildren in navigation.GetListKeywords(filter))
                {
                    Keyword rootKeyword = (Keyword)engine.GetObject(rootChildren.Attributes["ID"].Value);
                    w.WriteStartElement(Navigation.NodeName);
                    NavigationNode n = new NavigationNode(rootKeyword);

                }
            }
        }
Example #6
0
 /// <summary>
 /// Log a debug message
 /// </summary>
 /// <param name="format">Message format string</param>
 /// <param name="ex">Associated exception to output</param>
 /// <param name="args">Format string parameters</param>
 public static void Debug(this TemplatingLogger logger, String format, Exception ex, params Object[] args)
 {
     if (logger != null)
     {
         logger.Debug(String.Format("{0}\n{1}", String.Format(format, args), TraceException(ex)));
     }
 }
Example #7
0
        public void Transform(Engine engine, Package package)
        {
            var pageItem = package.GetByType(ContentType.Page);
            var page     = engine.GetObject(pageItem.GetAsSource().GetValue("ID")) as Page;

            if (page == null)
            {
                throw new Exception("No page found in package.");
            }

            var couchPage = new CouchPage
            {
                Id           = page.Id.ToString(),
                Url          = page.PublishLocationUrl,
                PageTemplate = page.PageTemplate.Title
            };

            foreach (var cp in page.ComponentPresentations)
            {
                var cpString   = engine.RenderComponentPresentation(cp.Component.Id, cp.ComponentTemplate.Id);
                var jsonString = XElement.Parse(cpString).Value;

                TemplatingLogger.GetLogger(typeof(RenderPageJson)).Info("CP: " + cpString);
                couchPage.ComponentPresentations.Add(JsonConvert.DeserializeObject <CouchComponentPresentation>(jsonString));
            }
            package.PushItem("CouchPage", package.CreateStringItem(ContentType.Page, JsonConvert.SerializeObject(couchPage)));
        }
Example #8
0
 /// <summary>
 /// Log an information message
 /// </summary>
 /// <param name="format">Message / Message format string</param>
 /// <param name="args">Format string parameters</param>
 public static void Info(this TemplatingLogger logger, String format, params object[] args)
 {
     if (logger != null)
     {
         logger.Info(String.Format(format, args));
     }
 }
Example #9
0
 /// <summary>
 /// Log a debug message
 /// </summary>
 /// <param name="message">The message to log</param>
 /// <param name="ex">Associated exception to output</param>
 public static void Debug(this TemplatingLogger logger, String message, Exception ex)
 {
     if (logger != null)
     {
         logger.Debug(String.Format("{0}\n{1}", message, TraceException(ex)));
     }
 }
        public void Transform(Engine engine, Package package)
        {
            TemplatingLogger      log = TemplatingLogger.GetLogger(GetType());
            RepositoryLocalObject context;

            if (package.GetByName(Package.PageName) != null)
            {
                context = (RepositoryLocalObject)engine.GetObject(package.GetByName(Package.PageName));
                log.Debug("Setting context to page with ID " + context.Id);
            }
            else
            {
                log.Info("This template building block should only run on a page. Exiting.");
                return;
            }

            if (!(context is Page))
            {
                return;
            }

            Page page = (Page)context;

            package.PushItem(SiteEditPageContext, package.CreateStringItem(ContentType.Text, page.OwningRepository.Id));
            package.PushItem(SiteEditPublishContext, package.CreateStringItem(ContentType.Text, page.ContextRepository.Id));

            if (page.ComponentPresentations.Count <= 0)
            {
                return;
            }
            Component component = page.ComponentPresentations[0].Component;

            package.PushItem(SiteEditComponentContext, package.CreateStringItem(ContentType.Text, component.OwningRepository.Id));
        }
        /// <summary>
        /// Initializes the <see cref="WrappedCSharpMediator"/> class.
        /// </summary>
        static WrappedCSharpMediator()
        {
            AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolve;

            mBasePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            mProcessRunTemplateCalls = (ProcessRunTemplateCalls)Delegate.CreateDelegate(typeof(ProcessRunTemplateCalls),
                                                                                        typeof(CSharpSourceCodeMediator).GetMethod("ProcessRunTemplateCalls",
                                                                                                                                   BindingFlags.Static | BindingFlags.NonPublic));

            mLogger = TemplatingLogger.GetLogger(typeof(WrappedCSharpMediator));

            mDebugAssemblies = new List <Assembly>();

            foreach (DebugAssembly debugAssemblyConfig in DebuggerConfig.Instance.Debugging.DebugAssemblies)
            {
                Assembly debugAssembly = LoadAssembly(debugAssemblyConfig.Name + ".dll");

                if (debugAssembly != null)
                {
                    mDebugAssemblies.Add(debugAssembly);
                }
                else
                {
                    mLogger.Error("Failed to load configured debug assembly: \"{0}\".", debugAssemblyConfig.Name);
                }
            }
        }
Example #12
0
 /// <summary>
 /// Log a debug message
 /// </summary>
 /// <param name="format">Message format string</param>
 /// <param name="args">Format string parameters</param>
 public static void Debug(this TemplatingLogger logger, String format, params Object[] args)
 {
     if (logger != null)
     {
         logger.Debug(String.Format(format, args));
     }
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="XsltExtensions"/> class.
 /// </summary>
 /// <param name="engine"><see cref="T:Tridion.ContentManager.Templating.Engine" /></param>
 /// <param name="package"><see cref="T:Tridion.ContentManager.Templating.Package" /></param>
 /// <param name="templateBase"><see cref="T:TcmTemplating.TemplateBase" /></param>
 public XsltExtensions(Engine engine, Package package, TemplateBase templateBase)
 {
     mTemplatingLogger = TemplatingLogger.GetLogger(this.GetType());
     mEngine           = engine;
     mPackage          = package;
     mTemplateBase     = templateBase;
 }
        public void Transform(Engine engine, Package package)
        {
            TemplatingLogger log = TemplatingLogger.GetLogger(GetType());

            if (package.GetByName(Package.OutputName) == null)
            {
                log.Error("Could not find \"Output\" item in Package. This template building block should be the last TBB in your template.");
                return;
            }
            Item output = package.GetByName(Package.OutputName);

            string outputText = output.GetAsString();

            bool outputchanged = false;

            foreach (Match m in TcmUriRegEx.Matches(outputText))
            {
                log.Debug("Found " + m.Value);
                TcmUri uri = new TcmUri(m.Value);
                if (uri.GetVersionlessUri().ToString().Equals(m.Value))
                {
                    continue;
                }
                log.Debug("Found version information on uri " + m.Value + ". Removing.");
                outputText    = outputText.Replace(m.Value, uri.GetVersionlessUri().ToString());
                outputchanged = true;
            }
            if (outputchanged)
            {
                output.SetAsString(outputText);
                package.Remove(output);
                package.PushItem(Package.OutputName, output);
            }
        }
        public static TcmUri GetLocalUri(TcmUri uriPublication, TcmUri uriItem)
        {
            TcmUri           uriReturn = new TcmUri(uriItem.ItemId, uriItem.ItemType, uriPublication.ItemId);
            TemplatingLogger log       = TemplatingLogger.GetLogger(typeof(TemplateUtilities));

            log.Info("(getLocalUri)Old URI was:" + uriItem.ToString());
            log.Info("(getLocalUri)New URI is:" + uriReturn.ToString());
            return(uriReturn);
        }
        /// <summary>
        /// Execute the transformation for the specified template
        /// </summary>
        /// <param name="Engine"><see cref="T:Tridion.ContentManager.Templating.Engine"/>.</param>
        /// <param name="Package"><see cref="T:Tridion.ContentManager.Templating.Package"/></param>
        public void Transform(Engine Engine, Package Package)
        {
            try
            {
                mTicksStart = Environment.TickCount;

                mEngine  = Engine;
                mPackage = Package;

                // Actual template transformation
                PreTransform();
                Transform();
                PostTransform();
            }
            catch (Exception ex)
            {
                String exceptionStack = LoggerExtensions.TraceException(ex);

                Logger.Error("TemplateBase.Transform Exception\n" + exceptionStack);

                StringBuilder sb = new StringBuilder();
                sb.AppendLine(ex.Message);
                sb.AppendFormat("Publisher: {0}\n", Environment.MachineName);
                sb.Append(exceptionStack);

                // Re-throw to ensure Tridion knows what happened
                throw new Exception(sb.ToString(), ex);
            }
            // Ensure we always clean up, no matter what happens during the template transformation
            finally
            {
                Logger.Info("{0}: Render time {1:0.00000} seconds @ {2:dd/MM/yyyy hh:mm:ss tt} ", this.GetType().FullName, ProcessedTime / 1000.0, DateTime.Now);

                // Do not cache objects across template transformations
                ItemFieldsFactory.ClearCache();

                // Clear published binaries list if it was used
                if (mPublishedBinaries.IsValueCreated)
                {
                    mPublishedBinaries.Value.Clear();
                }

                mPackage = null;
                mEngine  = null;
                mLogger  = null;

                mComponent         = null;
                mComponentTemplate = null;
                mPage               = null;
                mPageTemplate       = null;
                mRootStructureGroup = null;
                mPublication        = null;
                mPublishTransaction = null;
                mPublishingUser     = null;
                mPublicationTarget  = null;
            }
        }
 internal NavigationNode(Keyword keyword)
 {
     Keyword      = keyword;
     _keywordMeta = new XmlDocument();
     _keywordMeta.LoadXml(keyword.Metadata.OuterXml);
     _nm = new XmlNamespaceManager(new NameTable());
     _nm.AddNamespace("meta", keyword.MetadataSchema.NamespaceUri);
     _log = TemplatingLogger.GetLogger(GetType());
 }
        /// <summary>
        /// Main transform method called by Tridion
        /// </summary>
        /// <param name="engine"></param>
        /// <param name="package"></param>
        public void Transform(Engine engine, Package package)
        {
            Log = TemplatingLogger.GetLogger(GetType());

            Engine  = engine;
            Package = package;
            Session = engine.GetSession();

            Transform();
        }
Example #19
0
        public TridionLessLogger(TemplatingLogger logger)
        {
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }
            _logger = logger;

            _errors = new List <string>();
        }
        public static Dynamic.ComponentPresentation BuildComponentPresentation(TCM.ComponentPresentation tcmComponentPresentation, Engine engine, int linkLevels, bool resolveWidthAndHeight, BuildManager manager)
        {
            Dynamic.ComponentPresentation cp = new Dynamic.ComponentPresentation();

            if (tcmComponentPresentation.ComponentTemplate.IsRepositoryPublishable)
            {
                // call render but ignore the output - render ensures componentlinking will be setup as normal.
                // don't bother with page flags because the end result is dynamically published so it needs to run with DCP settings
                engine.RenderComponentPresentation(tcmComponentPresentation.Component.Id, tcmComponentPresentation.ComponentTemplate.Id);

                // ignore the rendered CP, because it is already available in the broker
                // instead, we will render a very simple version without any links
                cp.Component = manager.BuildComponent(tcmComponentPresentation.Component, 0, false, false); // linkLevels = 0 means: only summarize the component
                cp.IsDynamic = true;
            }
            else
            {
                // render the component presentation using its own CT
                // but first, set a parameter in the context so that the CT will know it is beng called
                // from a DynamicDelivery page template
                if (engine.PublishingContext.RenderContext != null && !engine.PublishingContext.RenderContext.ContextVariables.Contains(BasePageTemplate.VariableNameCalledFromDynamicDelivery))
                {
                    engine.PublishingContext.RenderContext.ContextVariables.Add(BasePageTemplate.VariableNameCalledFromDynamicDelivery, BasePageTemplate.VariableValueCalledFromDynamicDelivery);
                }

                string renderedContent = engine.RenderComponentPresentation(tcmComponentPresentation.Component.Id, tcmComponentPresentation.ComponentTemplate.Id);
                engine.PublishingContext.RenderContext.ContextVariables.Remove(BasePageTemplate.VariableNameCalledFromDynamicDelivery);

                renderedContent = TridionUtils.StripTcdlTags(renderedContent);

                cp.IsDynamic = false;
                TextReader tr = new StringReader(renderedContent);
                if (serializer == null)
                {
                    serializer = new ComponentSerializer();
                    //serializer = new XmlSerializerFactory().CreateSerializer(typeof(Dynamic.Component));
                }
                try
                {
                    cp.Component = (Dynamic.Component)serializer.Deserialize(tr);
                }
                catch (Exception e)
                {
                    TemplatingLogger.GetLogger(typeof(ComponentPresentationBuilder)).Error("exception while deserializing into CP: " + e.Message);
                    // the component presentation could not be deserialized, this probably not a Dynamic Delivery template
                    // just store the output as 'RenderedContent' on the CP
                    cp.RenderedContent = renderedContent;
                    // because the CT was not a DD4T CT, we will generate the DD4T XML code here
                    cp.Component = manager.BuildComponent(tcmComponentPresentation.Component);
                }
            }
            cp.ComponentTemplate = manager.BuildComponentTemplate(tcmComponentPresentation.ComponentTemplate);
            return(cp);
        }
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="pipeline">The context Model Builder Pipeline.</param>
        protected DataModelBuilder(DataModelBuilderPipeline pipeline)
        {
            Pipeline = pipeline;

            if (pipeline.Logger is TemplatingLoggerAdapter)
            {
                // If the pipeline uses a TemplatingLogger (default), we also use our own.
                Logger = new TemplatingLoggerAdapter(TemplatingLogger.GetLogger(GetType()));
            }
            else
            {
                // If the pipeline uses another logger (unit/integration tests), we use that one.
                Logger = pipeline.Logger;
            }
        }
        /// <summary>
        /// Configure the mediator object, based on the configuration element of the mediator.
        /// </summary>
        /// <param name="configuration">The MediatorElement configuration.</param>
        public void Initialize()
        {
            _logger    = TemplatingLogger.GetLogger(this.GetType());
            _config    = RazorMediatorConfigurationSection.GetConfiguration();
            _generator = new RazorTemplateGenerator();

            foreach (NamespaceElement nameSpace in _config.Namespaces)
            {
                _namespaces.Add(nameSpace.Namespace);
            }

            foreach (AssemblyElement assembly in _config.Assemblies)
            {
                _assemblies.Add(assembly.Assembly);
            }
        }
Example #23
0
        /// <summary>
        /// Extarcts the references to Tridion items from the template content. It is allowed to have values in the result that are not valid Tridion references.
        /// </summary>
        /// <returns></returns>
        public override string[] PerformExtractReferences()
        {
            TemplatingLogger log = TemplatingLogger.GetLogger(this.GetType());

            string[] dwReferences = _dwHandler.PerformExtractReferences();

            RazorHandler handler = new RazorHandler(TemplateId.ToString(), WebDavUrl, Content);

            handler.Initialize();

            List <string> imports    = handler.GetImportReferences();
            List <string> references = dwReferences.ToList();

            foreach (string path in imports)
            {
                if (!path.ToLower().StartsWith("tcm:") && !path.ToLower().StartsWith("/webdav/"))
                {
                    references.Add(GetRelativeImportPath(path));
                }
                else
                {
                    if (path.StartsWith("/webdav/"))
                    {
                        string[] pathParts   = path.Split('/');
                        string[] webDavParts = WebDavUrl.Split('/');

                        if (pathParts[2] != webDavParts[2])
                        {
                            pathParts[2] = webDavParts[2];
                        }

                        references.Add(String.Join("/", pathParts));
                    }
                    else if (TcmUri.IsValid(path))
                    {
                        TcmUri uri = new TcmUri(path);
                        if (uri.PublicationId != TemplateId.PublicationId)
                        {
                            uri = new TcmUri(uri.ItemId, uri.ItemType, TemplateId.PublicationId);
                        }
                        references.Add(uri.ToString());
                    }
                }
            }

            return(references.ToArray());
        }
Example #24
0
        /// <summary>
        /// Transforms the specified engine.
        /// </summary>
        /// <param name="engine">The engine.</param>
        /// <param name="package">The package.</param>
        public void Transform(Engine engine, Package package)
        {
            if (engine.PublishingContext.PublicationTarget == null)
            {
                return;
            }

            TemplatingLogger log    = TemplatingLogger.GetLogger(GetType());
            List <Group>     groups = new List <Group>();

            if (engine.PublishingContext.PublicationTarget.TargetTypes.Count > 0)
            {
                Session    session           = new Session();
                TargetType currentTargetType = (TargetType)session.GetObject(engine.PublishingContext.PublicationTarget.TargetTypes[0].Id);

                foreach (AccessControlEntry accessControlEntry in currentTargetType.AccessControlList.AccessControlEntries)
                {
                    if (accessControlEntry.Trustee is Group)
                    {
                        groups.Add((Group)accessControlEntry.Trustee);
                    }
                    if (accessControlEntry.Trustee is User)
                    {
                        log.Error("Target type " + currentTargetType.Title + " contains a security entry for user " + accessControlEntry.Trustee.Title + ". This is incorrect, only groups should be in this list.");
                    }
                }
            }

            XmlDocument document = new XmlDocument();

            foreach (Group group in groups)
            {
                XmlElement groupInfo = document.CreateElement("GroupInfo");
                groupInfo.SetAttribute("Name", group.Title);
                IEnumerable <User> usersIngroup = GetUsersInGroup(group);
                foreach (User user in usersIngroup)
                {
                    XmlElement userInfo = document.CreateElement("UserInfo");
                    userInfo.SetAttribute("Name", user.Title);
                    userInfo.SetAttribute("Email", user.Description);
                    groupInfo.AppendChild(userInfo);
                }
                engine.PublishingContext.RenderedItem.AddInstruction(InstructionScope.Global, groupInfo);
            }
        }
Example #25
0
        /// <summary>
        /// Releases allocated resources
        /// </summary>
        void IDisposable.Dispose()
        {
            lock (this)
            {
                if (_disposed == false)
                {
                    MPackage = null;
                    MEngine  = null;
                    _logger  = null;
                    _nsm     = null;

                    _disposed = true;
                    // take yourself off the finalization queue
                    // to prevent finalization from executing a second time
                    GC.SuppressFinalize(this);
                }
            }
        }
Example #26
0
        public void Transform(Engine engine, Package package)
        {
            var logger = TemplatingLogger.GetLogger(typeof(PublishFolderMMCsToStructureGroup));
            // Get containing folder of the component
            var componentItem  = package.GetByName(Package.ComponentName);
            var component      = (RepositoryLocalObject)engine.GetObject(componentItem);
            var folder         = component.OrganizationalItem;
            var folderMetadata = new ItemFields(folder.Metadata, folder.MetadataSchema);
            var sgURL          = folderMetadata["sgForBinaryPublish"] as SingleLineTextField;

            if (sgURL == null || sgURL.Value == null)
            {
                logger.Debug("No sgForBinaryPublish configured for this folder. Doing nothing.");
                return;
            }
            IdentifiableObject structureGroup = null;

            try
            {
                structureGroup = engine.GetObject(sgURL.Value);
            }
            catch (InvalidTcmUriException)
            {
                logger.Error("Folder metadata contains invalid value for sgForBinaryPublish.");
            }
            if (structureGroup == null)
            {
                logger.Error("Folder metadata contains a value for sgForBinaryPublish which does not locate an item");
            }

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

            filter.ItemTypes = new ItemType[] { ItemType.Component };
            var components = folder.GetItems(filter).Cast <Component>().Where(c => c.BinaryContent != null);

            foreach (var comp in components)
            {
                engine.AddBinary(comp.Id,
                                 engine.PublishingContext.ResolvedItem.Template.Id,
                                 engine.LocalizeUri(structureGroup.Id),
                                 comp.BinaryContent.GetByteArray(),
                                 comp.Title);
            }
        }
 public LogAdapter(Type theType)
 {
     _log = TemplatingLogger.GetLogger(theType);
     try
     {
         string logging = Environment.GetEnvironmentVariable("DXA_LOGGING");
         if (!string.IsNullOrEmpty(logging))
         {
             FileInfo fi = new FileInfo(logging);
             _logFile = fi.FullName;
             File.Delete(_logFile);
         }
     }
     catch (Exception)
     {
         // invalid so ignore
         _logFile = null;
     }
 }
Example #28
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="renderedItem">A context <see cref="RenderedItem"/> instance which is used to add Binaries and child Rendered Items.</param>
        /// <param name="settings">The Model Builder Settings to use.</param>
        /// <param name="modelBuilderTypeNames">The (qualified) type names of Model Builders to use.</param>
        /// <param name="logger">Optional logger to use. If not specified or <c>null</c>, the Data Model Builder Pipeline creates its own logger.</param>
        public DataModelBuilderPipeline(
            RenderedItem renderedItem,
            DataModelBuilderSettings settings,
            IEnumerable <string> modelBuilderTypeNames,
            ILogger logger = null
            )
        {
            Session      = renderedItem.ResolvedItem.Item.Session;
            RenderedItem = renderedItem;
            Settings     = settings;
            Logger       = logger ?? new TemplatingLoggerAdapter(TemplatingLogger.GetLogger(GetType()));

            foreach (string modelBuilderTypeName in modelBuilderTypeNames)
            {
                string qualifiedTypeName = modelBuilderTypeName.Contains(".") ? modelBuilderTypeName : $"Sdl.Web.Tridion.Data.{modelBuilderTypeName}";
                Type   modelBuilderType  = Type.GetType(qualifiedTypeName, throwOnError: true);
                object modelBuilder      = Activator.CreateInstance(modelBuilderType, new object[] { this });
                IPageModelDataBuilder    pageModelBuilder    = modelBuilder as IPageModelDataBuilder;
                IEntityModelDataBuilder  entityModelBuilder  = modelBuilder as IEntityModelDataBuilder;
                IKeywordModelDataBuilder keywordModelBuilder = modelBuilder as IKeywordModelDataBuilder;
                if ((pageModelBuilder == null) && (entityModelBuilder == null) && (keywordModelBuilder == null))
                {
                    Logger.Warning($"Configured Model Builder type '{modelBuilderType.FullName}' does not implement IPageModelDataBuilder, IEntityModelDataBuilder nor IKeywordModelDataBuilder; skipping.");
                    continue;
                }
                if (pageModelBuilder != null)
                {
                    Logger.Debug($"Using Page Model Builder type '{modelBuilderType.FullName}'.");
                    _pageModelBuilders.Add(pageModelBuilder);
                }
                if (entityModelBuilder != null)
                {
                    Logger.Debug($"Using Entity Model Builder type '{modelBuilderType.FullName}'.");
                    _entityModelBuilders.Add(entityModelBuilder);
                }
                if (keywordModelBuilder != null)
                {
                    Logger.Debug($"Using Keyword Model Builder type '{modelBuilderType.FullName}'.");
                    _keywordModelBuilders.Add(keywordModelBuilder);
                }
            }
        }
        public void Transform(Engine engine, Package package)
        {
            _log = TemplatingLogger.GetLogger(GetType());

            RepositoryLocalObject context =
                engine.GetObject(package.GetByName(Package.PageName)) as RepositoryLocalObject;

            if (context == null)
            {
                _log.Error("Could not retrieve page from package. Exiting.");
                return;
            }
            string   categoryUrl = context.ContextRepository.WebDavUrl + NavigationCategoryWebDavUrl;
            Category navigation  = (Category)engine.GetObject(categoryUrl);

            using (MemoryStream ms = new MemoryStream())
            {
                XmlTextWriter w = new XmlTextWriter(ms, new UTF8Encoding(false))
                {
                    Indentation = 4,
                    Formatting  = Formatting.Indented
                };

                w.WriteStartDocument();
                w.WriteStartElement(Navigation.RootNodeName);
                KeywordsFilter filter = new KeywordsFilter(engine.GetSession())
                {
                    IsRoot = true
                };
                foreach (XmlNode rootChildren in navigation.GetListKeywords(filter))
                {
                    Keyword rootKeyword = (Keyword)engine.GetObject(rootChildren.Attributes["ID"].Value);
                    w.WriteStartElement(Navigation.NodeName);
                    NavigationNode n = new NavigationNode(rootKeyword);
                }
            }
        }
Example #30
0
        void ITemplate.Transform(Engine engine, Package package)
        {
            TemplatingLogger logger = TemplatingLogger.GetLogger(this.GetType());

            Item item = package.GetByType(ContentType.Component);

            if (item.Properties.ContainsKey(Item.ItemPropertyTcmUri))
            {
                Component component = (Component)engine.GetObject(item.Properties[Item.ItemPropertyTcmUri].ToString());

                if (component.ComponentType == ComponentType.Multimedia)
                {
                    if (string.Compare(component.BinaryContent.MultimediaType.MimeType, "text/css", true) == 0)
                    {
                        StructureGroup structureGroup = (StructureGroup)engine.GetObject(STRUCTURE_GROUP_FOR_CSS);

                        string[] filenameParts = component.BinaryContent.Filename.Split(new char[] { '\\' });
                        string   filename      = filenameParts[filenameParts.GetUpperBound(0)];

                        string unMinifiedString = Encoding.Default.GetString(component.BinaryContent.GetByteArray());
                        string minifiedString   = CssCompressor.Compress(unMinifiedString, 0, CssCompressionType.Hybrid);

                        using (MemoryStream memoryStream = new MemoryStream(Encoding.Default.GetBytes(minifiedString)))
                        {
                            engine.PublishingContext.RenderedItem.AddBinary(
                                memoryStream,
                                filename,
                                structureGroup,
                                "mmbyname",
                                component,
                                component.BinaryContent.MultimediaType.MimeType
                                );
                        }
                    }
                }
            }
        }
Example #31
0
        public void Transform(Engine engine, Package package)
        {
            _engine = engine;
            _package = package;
            _log = TemplatingLogger.GetLogger(GetType());
            TemplateType templateType;

            if (package.GetByName(Package.ComponentName) != null)
                templateType = TemplateType.Component;
            else
                templateType = TemplateType.Page;

            Item output = null;
            if (templateType == TemplateType.Page)
            {
                Page page = (Page)engine.GetObject(package.GetByName(Package.PageName));
                page.Load(LoadFlags.KeywordXlinks);
                output = package.CreateXmlDocumentItem(ContentType.Xml, page.ToXml(XmlFormat.R6Native, XmlSections.All).OwnerDocument);

                foreach (ComponentPresentation cp in page.ComponentPresentations)
                {
                    engine.RenderComponentPresentation(cp.Component.Id, cp.ComponentTemplate.Id);
                }
            }
            if (templateType == TemplateType.Component)
            {
                Component component = (Component)engine.GetObject(package.GetByName(Package.ComponentName));
                component.Load(LoadFlags.KeywordXlinks);
                output = package.CreateXmlDocumentItem(ContentType.Xml, component.ToXml(XmlFormat.R6Native, XmlSections.All).OwnerDocument);
                if(component.BinaryContent != null)
                {
                    package.PushItem(package.CreateMultimediaItem(component));
                }
            }
            if (output != null)
                package.PushItem(Package.OutputName, output);
        }
        public static Publication GetPublicationFromContext(Package package, Engine engine)
        {
            TemplatingLogger log           = TemplatingLogger.GetLogger(typeof(TridionUtils));
            Publication      myPublication = null;
            Item             contextItem   = package.GetByName("Page");

            if (contextItem != null)
            {
                log.Info("(GetPublicationFromContext) Retrieving for context publication from the Page");
                TcmUri uriDataSource = new TcmUri(contextItem.GetAsSource().GetValue("ID"));
                Page   mycontextItem = engine.GetObject(uriDataSource) as Page;
                myPublication = (Publication)mycontextItem.ContextRepository;
            }
            else
            {
                log.Info("(GetPublicationFromContext) Retrieving for context publication from the Component");
                contextItem = package.GetByName("Component");
                TcmUri    uriDataSource = new TcmUri(contextItem.GetAsSource().GetValue("ID"));
                Component mycontextItem = engine.GetObject(uriDataSource) as Component;
                myPublication = (Publication)mycontextItem.ContextRepository;
            }
            log.Info("(GetPublicationFromContext) Context publication is:" + myPublication.Title);
            return(myPublication);
        }
        /// <summary>
        /// Initializes the <see cref="WrappedCSharpMediator"/> class.
        /// </summary>
        static WrappedCSharpMediator()
        {
            AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolve;

            mBasePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            mProcessRunTemplateCalls = (ProcessRunTemplateCalls)Delegate.CreateDelegate(typeof(ProcessRunTemplateCalls),
                                            typeof(CSharpSourceCodeMediator).GetMethod("ProcessRunTemplateCalls",
                                            BindingFlags.Static | BindingFlags.NonPublic));

            mLogger = TemplatingLogger.GetLogger(typeof(WrappedCSharpMediator));

            mDebugAssemblies = new List<Assembly>();

            foreach (DebugAssembly debugAssemblyConfig in DebuggerConfig.Instance.Debugging.DebugAssemblies)
            {
                Assembly debugAssembly = LoadAssembly(debugAssemblyConfig.Name + ".dll");

                if (debugAssembly != null)
                    mDebugAssemblies.Add(debugAssembly);
                else
                    mLogger.Error("Failed to load configured debug assembly: \"{0}\".", debugAssemblyConfig.Name);
            }
        }
 public PublishBinariesPage(TemplatingLogger log)
     : base(log)
 {
 }
 static WrappedRazorMediator()
 {
     mLogger = TemplatingLogger.GetLogger(typeof(WrappedRazorMediator));
 }
 public PageTemplateBase(TemplatingLogger log)
     : base(log)
 {
 }
 /// <summary>
 /// Constructor
 /// </summary>
 public RazorMediator()
 {
     _logger = TemplatingLogger.GetLogger(this.GetType());
 }
 internal NavigationNode(Keyword keyword)
 {
     Keyword = keyword;
     _keywordMeta = new XmlDocument();
     _keywordMeta.LoadXml(keyword.Metadata.OuterXml);
     _nm = new XmlNamespaceManager(new NameTable());
     _nm.AddNamespace("meta", keyword.MetadataSchema.NamespaceUri);
     _log = TemplatingLogger.GetLogger(GetType());
 }
Example #39
0
 public DynamicPage(TemplatingLogger log) : base(log) { }
 public ComponentTemplateBase(TemplatingLogger log)
     : base(log)
 {
 }
        public void Transform(Engine engine, Package package)
        {
            _log = TemplatingLogger.GetLogger(GetType());
            _engine = engine;

            string itemName = string.Empty;
            if (package.GetByName(Package.ComponentName) != null) itemName = Package.ComponentName;
            if (package.GetByName(Package.PageName) != null) itemName = Package.PageName;

            if (string.IsNullOrEmpty(itemName))
            {
                _log.Debug("Could not determine template type, exiting");
                return;
            }

            VersionedItem item = (VersionedItem)engine.GetObject(package.GetByName(itemName));
            if (item.LockType.HasFlag(LockType.InWorkflow))
            {
                CurrentMode mode = GetCurrentMode();
                VersionedItem w = item.GetVersion(0);
                switch (mode)
                {
                    case CurrentMode.CmePreview:
                    case CurrentMode.TemplateBuilder:
                    case CurrentMode.SessionPreview:
                        // return workflow object without comparing to Publication Target Minimum Approval Status
                        package.Remove(package.GetByName(itemName));
                        if (itemName.Equals(Package.ComponentName))
                        {
                            package.PushItem(Package.ComponentName, package.CreateTridionItem(ContentType.Component, w));
                        }
                        else if (itemName.Equals(Package.PageName))
                        {
                            package.PushItem(Package.PageName, package.CreateTridionItem(ContentType.Page, w));
                        }
                        break;

                    case CurrentMode.Publish:
                        PublicationTarget target = _engine.PublishingContext.PublicationTarget;
                        ApprovalStatus targetStatus = target.MinApprovalStatus;
                        ApprovalStatus contentStatus = null;
                        if (w is Component)
                        {
                            contentStatus = ((Component)w).ApprovalStatus;
                        }
                        else if (w is Page)
                        {
                            contentStatus = ((Page)w).ApprovalStatus;
                        }
                        if (contentStatus == null)
                        {
                            _log.Debug("Could not determine approval status of content. Exiting.");
                            return;
                        }
                        bool mustUpdate = false;
                        if (targetStatus == null)
                            mustUpdate = true;
                        else
                        {
                            if (contentStatus.Position > targetStatus.Position)
                                mustUpdate = true;
                        }

                        if (mustUpdate)
                        {
                            package.Remove(package.GetByName(itemName));
                            if (itemName.Equals(Package.ComponentName))
                            {
                                package.PushItem(Package.ComponentName, package.CreateTridionItem(ContentType.Component, w));
                            }
                            else if (itemName.Equals(Package.PageName))
                            {
                                package.PushItem(Package.PageName, package.CreateTridionItem(ContentType.Page, w));
                            }
                        }
                        break;
                }
            }
        }
Example #42
0
 public XsltMediator()
 {
     m_Logger = TemplatingLogger.GetLogger(this.GetType());
 }
Example #43
0
 public BaseTemplate(TemplatingLogger log)
 {
     Log = log;
 }
        /// <summary>
        /// Configure the mediator object, based on the configuration element of the mediator. 
        /// </summary>
        /// <param name="configuration">The MediatorElement configuration.</param>
        public void Initialize()
        {
            _logger = TemplatingLogger.GetLogger(this.GetType());
            _config = RazorMediatorConfigurationSection.GetConfiguration();
            _generator = new RazorTemplateGenerator();

            foreach (NamespaceElement nameSpace in _config.Namespaces)
            {
                _namespaces.Add(nameSpace.Namespace);
            }

            foreach (AssemblyElement assembly in _config.Assemblies)
            {
                _assemblies.Add(assembly.Assembly);
            }
        }
 public TcmUriResolver(Engine templateEngine)
 {
     m_Engine = templateEngine;
     m_Logger = TemplatingLogger.GetLogger(this.GetType());
 }
        /// <summary>
        /// Releases allocated resources
        /// </summary>
        void IDisposable.Dispose()
        {
            lock (this)
            {
                if (_disposed) return;
                _package = null;
                _engine = null;
                _logger = null;
                _NSM = null;

                _disposed = true;
                // take yourself off the finalization queue
                // to prevent finalization from executing a second time
                GC.SuppressFinalize(this);
            }
        }
 public void Initialize(Tridion.ContentManager.Templating.Engine engine, Tridion.ContentManager.Templating.Package package)
 {
     this.Engine = engine;
     this.Package = package;
     this.Logger = TemplatingLogger.GetLogger(this.GetType());
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="XmlTcmUriResolver"/> class.
 /// </summary>
 /// <param name="engine"><see cref="T:Tridion.ContentManager.Templating.Engine" /></param>
 public XmlTcmUriResolver(Engine engine)
 {
     mEngine = engine;
     mTemplatingLogger = TemplatingLogger.GetLogger(this.GetType());
 }
 public TemplateBase(TemplatingLogger log)
 {
     Log = log;
 }
 public void Initialize(Engine engine, Package package)
 {
     _Engine = engine;
     _Package = package;
     _Log = TemplatingLogger.GetLogger(GetType());
 }
        public void Transform(Engine engine, Package package)
        {
            _engine = engine;
            Stopwatch watch = new Stopwatch();
            watch.Start();
            // Initialize internal variables
            _log = TemplatingLogger.GetLogger(GetType());
            _log.Debug("Initialized");
            // Check if template should run
            if (package.GetByName(Package.PageName) == null)
            {
                _log.Error("This templating building block must be executed in the context of a page.");
                return;
            }

            // Get the current publishing context
            Page context = (Page)engine.GetObject(package.GetByName(Package.PageName));
            // Get the current publication
            Publication contextPublication = (Publication)context.ContextRepository;
            // Get the Root Structure Group (starting point for the navigation)
            StructureGroup root = contextPublication.RootStructureGroup;

            // Prepare memory stream with Xml document
            using (MemoryStream stream = new MemoryStream())
            {
                // Use XmlTextWriter to write our navigation
                XmlTextWriter writer = new XmlTextWriter(stream, new UTF8Encoding(false)) { Indentation = 4, Formatting = Formatting.Indented };

                writer.WriteStartDocument();
                writer.WriteStartElement(Navigation.RootNodeName);

                // Get Root Structure Group Attributes
                string rootPath = root.PublishLocationUrl;
                string rootTitle = root.Title;
                string rootUri = root.Id;

                if (Navigation.IncludePathAttribute) writer.WriteAttributeString(Navigation.PathAttributeName, rootPath);
                writer.WriteAttributeString(Navigation.TitleAttributeName, rootTitle);
                if (Navigation.IncludeUriAttribute) writer.WriteAttributeString(Navigation.UriAttributeName, rootUri);
                writer.WriteAttributeString(Navigation.TypeAttributeName, root.Id.ItemType.ToString());

                if (Navigation.IncludePublicationMetadata)
                {
                    if (contextPublication.Metadata != null)
                    {
                        ItemFields publicationMetadata = new ItemFields(contextPublication.Metadata, contextPublication.MetadataSchema);
                        AddMetadataAttributes(publicationMetadata, writer);
                    }
                }
                // Add the Root Structure Group to the count
                _countStructureGroups++;
                foreach (RepositoryLocalObject item in root.GetItems())
                {
                    ProcessNavigation(writer, item);
                }

                writer.WriteEndElement();
                if (Navigation.IncludePerformanceMetrics)
                {
                    writer.WriteComment("Navigation rendered in " + watch.ElapsedMilliseconds + " milliseconds");
                    writer.WriteComment(string.Format("Items included: {0} structure groups, {1} pages and {2} Metadata Fields", _countStructureGroups, _countPages, _countFields));
                }

                writer.WriteEndDocument();

                writer.Flush();
                stream.Position = 0;
                package.PushItem(Package.OutputName, package.CreateStringItem(ContentType.Xml, Encoding.UTF8.GetString(stream.ToArray())));
                writer.Close();
            }
            watch.Stop();
            _log.Debug("Navigation created in " + watch.ElapsedMilliseconds + " milliseconds.");
            _log.Debug(string.Format("Navigation created for {0} structure groups, {1} pages and {2} Metadata Fields",
                                     _countStructureGroups, _countPages, _countFields));
        }
		public Binary PublishBinary(Component mComponent, Session session, Package package, Engine engine, TemplatingLogger logger,
			string strFileName) {
			string rootFolderId = package.GetValue("RootFolder");
			string rootSGId = package.GetValue("RootStructureGroup");

			logger.Debug(string.Format("Using root Structure Group with Webdav Url: {0}", rootFolderId));

			Folder rootFolder = session.GetObject(rootFolderId) as Folder;
			StructureGroup parentSG = session.GetObject(rootSGId) as StructureGroup;

			Stack<string> sgNames = new Stack<string>();
			GetStructureGroupToBeCreated(mComponent.OrganizationalItem, rootFolder.Id, sgNames);

			OrganizationalItemItemsFilter sgFilter = new OrganizationalItemItemsFilter(session);
			sgFilter.Recursive = false;
			sgFilter.ItemTypes = new Tridion.ContentManager.ItemType[] { Tridion.ContentManager.ItemType.StructureGroup };

			//string strCoreServicesUrl = package.GetValue("CoreServicesUrl");

			while (sgNames.Count > 0) {
				string sgName = sgNames.Pop();
				IEnumerable<StructureGroup> list = parentSG.GetItems(sgFilter).
					Where(w => w.Title.Equals(sgName)).Select(s => (StructureGroup)s);

				if (list.Count() == 0) {
					/*
					 * TO DO: Enable tha auto creation of the Structure Group
					StructureGroupData newSG = SaveStructureGroup(sgName, parentSG.Id.ToString(), session.User.Title, strCoreServicesUrl);
					parentSG = new StructureGroup(new TcmUri(newSG.Id), session);
					 
					logger.Debug(string.Format("New Structure Group needs {0} created at: {1}", newSG.Title, parentSG.Path));
					 * */
					logger.Info(string.Format("Utilities.PublishBinary New Structure Group needs {0} created at: {1}", parentSG.Title, parentSG.Path));
				} else {
					StructureGroup existingSG = list.First<StructureGroup>();
					logger.Info(string.Format("Utilities.PublishBinary Existing Structure Group {0} found at: {1}", existingSG.Title, existingSG.Path));
					parentSG = existingSG;
				}
			}

			Binary binary = null;
			if (strFileName == null) {
				binary = engine.PublishingContext.RenderedItem.AddBinary(mComponent, parentSG, mComponent.BinaryContent.Filename);
			} else {
				MemoryStream msStream = new MemoryStream();
				mComponent.BinaryContent.WriteToStream(msStream);
				msStream.Seek(0, SeekOrigin.Begin);

				binary = engine.PublishingContext.RenderedItem.AddBinary(msStream, strFileName, parentSG, strFileName.Replace(" ", string.Empty), "text/xml");
			}

			logger.Debug(string.Format("Binary {0} being published to {1}", mComponent.BinaryContent.Filename, parentSG.PublishLocationUrl));
			return binary;
		}
 public DefaultTemplate(TemplatingLogger log)
 {
     Log = log;
 }
 public XsltTemplateHelper(Engine templateEngine)
 {
     m_Logger = TemplatingLogger.GetLogger(this.GetType());
     m_Engine = templateEngine;
 }
 public DynamicComponentPresentation() : base(TemplatingLogger.GetLogger(typeof(DynamicComponentPresentation)))
 {
     ComponentPresentationRenderStyle = ComponentPresentationRenderStyle.ComponentPresentation;
 }
 public BinaryHandler(Engine engine, Package package)
 {
     _engine = engine;
     _package = package;
     _logger = TemplatingLogger.GetLogger(GetType());
 }