public static void AddXpathToFields(Dynamic.FieldSet fieldSet, string baseXpath)
        {
            // add XPath properties to all fields

            if (fieldSet == null)
            {
                log.Error("fieldSet == null");
                return;
            }
            if (fieldSet.Values == null)
            {
                log.Error("fieldSet.Values == null");
                return;
            }
            try
            {
                foreach (Field f in fieldSet.Values)
                {
                    f.XPath = string.Format("{0}/custom:{1}", baseXpath, f.Name);
                    int i = 1;
                    if (f.EmbeddedValues != null)
                    {
                        foreach (FieldSet subFields in f.EmbeddedValues)
                        {
                            AddXpathToFields(subFields, string.Format("{0}/custom:{1}[{2}]", baseXpath, f.Name, i++));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                log.Error("Exception adding xpath to fields", e);
            }
        }
        private IFieldSet BuildExternalMetadataFieldSet(IContentLibraryItem eclItem)
        {
            string externalMetadataXml = eclItem.MetadataXml;

            if (string.IsNullOrEmpty(externalMetadataXml))
            {
                // No external metadata available; nothing to do.
                return(null);
            }

            ISchemaDefinition externalMetadataSchema = eclItem.MetadataXmlSchema;

            if (externalMetadataSchema == null)
            {
                _log.Warning(string.Format("ECL Item '{0}' has external metadata, but no schema defining it.", eclItem.Id));
                return(null);
            }

            try
            {
                XmlDocument externalMetadataDoc = new XmlDocument();
                externalMetadataDoc.LoadXml(externalMetadataXml);
                IFieldSet result = CreateExternalMetadataFieldSet(externalMetadataSchema.Fields, externalMetadataDoc.DocumentElement);

                _log.Debug(string.Format("ECL Item '{0}' has external metadata: {1}", eclItem.Id, string.Join(", ", result.Keys)));
                return(result);
            }
            catch (Exception ex)
            {
                _log.Error("An error occurred while parsing the external metadata for ECL Item " + eclItem.Id);
                _log.Error(ex.Message);
                return(null);
            }
        }
Example #3
0
        /// <summary>
        /// Passes the LESS source (and any @import-ed files) to the LESS Compiler and
        /// transforms it to CSS.
        /// </summary>
        private string CompileLess(string source, IFile file)
        {
            try
            {
                var compiler = new LessCompiler(_lessLog);
                var css      = compiler.Compile(source, file);

                return(css);
            }
            catch (Exception ex)
            {
                _log.Error("An error occurred in ProcessLess.CompileLess: {0}".FormatWith(ex.Message), ex);
                return(string.Empty);
            }
        }
Example #4
0
 /// <summary>
 /// Log an error message
 /// </summary>
 /// <param name="message">The message to log</param>
 /// <param name="ex">Associated exception to output</param>
 public static void Error(this TemplatingLogger logger, String message, Exception ex)
 {
     if (logger != null)
     {
         logger.Error(String.Format("{0}\n{1}", message, TraceException(ex)));
     }
 }
        /// <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 #6
0
 /// <summary>
 /// Log an error message
 /// </summary>
 /// <param name="format">Message format string</param>
 /// <param name="args">Format string parameters</param>
 public static void Error(this TemplatingLogger logger, String format, params Object[] args)
 {
     if (logger != null)
     {
         logger.Error(String.Format(format, args));
     }
 }
        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);

                }
            }
        }
        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);
        }
        public void Transform(Engine engine, Package package)
        {
            this.package = package;
            this.engine  = engine;

            if (engine.PublishingContext.RenderContext != null && engine.PublishingContext.RenderContext.ContextVariables.Contains(BasePageTemplate.VariableNameCalledFromDynamicDelivery))
            {
                if (engine.PublishingContext.RenderContext.ContextVariables[BasePageTemplate.VariableNameCalledFromDynamicDelivery].Equals(BasePageTemplate.VariableValueCalledFromDynamicDelivery))
                {
                    log.Debug("template is rendered by a DynamicDelivery page template, will not convert to lower case");
                    return;
                }
            }

            Item   outputItem = package.GetByName("Output");
            String inputValue = package.GetValue("Output");

            if (inputValue == null || inputValue.Length == 0)
            {
                log.Error("Could not find 'Output' in the package. Exiting template.");
                return;
            }

            string convertedValue = LowerCaseConverter.Convert(inputValue);

            package.Remove(outputItem);
            outputItem.SetAsString(convertedValue);
            package.PushItem("Output", outputItem);
        }
Example #10
0
 /// <summary>
 /// Log an error 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 Error(this TemplatingLogger logger, String format, Exception ex, params Object[] args)
 {
     if (logger != null)
     {
         logger.Error(String.Format("{0}\n{1}", String.Format(format, args), TraceException(ex)));
     }
 }
        /// <summary>
        /// Constructor to create a BaseBinaryPathProvider
        /// </summary>
        /// <param name="engine">The SDL Web publish engine</param>
        /// <param name="package">The SDL Web publish package</param>
        public BaseBinaryPathProvider(Engine engine, Package package)
        {
            Engine  = engine;
            Package = package;

            String targetStructureGroupParam = package.GetValue("sg_PublishBinariesTargetStructureGroup");

            if (targetStructureGroupParam != null)
            {
                if (!TcmUri.IsValid(targetStructureGroupParam))
                {
                    log.Error(String.Format("TargetStructureGroup '{0}' is not a valid TCMURI. Exiting template.", targetStructureGroupParam));
                    return;
                }

                Publication publication = TridionUtils.GetPublicationFromContext(package, engine);
                TcmUri      localTargetStructureGroupTcmUri = TridionUtils.GetLocalUri(new TcmUri(publication.Id), new TcmUri(targetStructureGroupParam));
                targetStructureGroupUri = new TcmUri(localTargetStructureGroupTcmUri);
                log.Debug($"targetStructureGroupUri = {targetStructureGroupUri.ToString()}");
            }

            String stripTcmUrisFromBinaryUrlsParam = package.GetValue("stripTcmUrisFromBinaryUrls");

            if (stripTcmUrisFromBinaryUrlsParam != null)
            {
                stripTcmUrisFromBinaryUrls = stripTcmUrisFromBinaryUrlsParam.ToLower() == "yes" || stripTcmUrisFromBinaryUrlsParam.ToLower() == "true";
            }
            log.Debug($"stripTcmUrisFromBinaryUrls = {stripTcmUrisFromBinaryUrls}");
        }
        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 BinaryPublisher(Package package, Engine engine)
        {
            this.package = package;
            this.engine  = engine;

            currentTemplate = engine.PublishingContext.ResolvedItem.Template;

            // Determine (optional) structure group parameter
            String targetStructureGroupParam = package.GetValue("PublishBinariesTargetStructureGroup");

            if (targetStructureGroupParam != null)
            {
                if (!TcmUri.IsValid(targetStructureGroupParam))
                {
                    log.Error(String.Format("TargetStructureGroup '{0}' is not a valid TCMURI. Exiting template.", targetStructureGroupParam));
                    return;
                }

                Publication publication = TridionUtils.GetPublicationFromContext(package, engine);
                TcmUri      localTargetStructureGroupTcmUri = TridionUtils.GetLocalUri(new TcmUri(publication.Id), new TcmUri(targetStructureGroupParam));
                targetStructureGroup = new TcmUri(localTargetStructureGroupTcmUri);
            }
        }
        public void Transform(Engine engine, Package package)
        {
            this.package = package;
            this.engine  = engine;

            if (engine.PublishingContext.RenderContext != null && engine.PublishingContext.RenderContext.ContextVariables.Contains(PageTemplateBase.VariableNameCalledFromDynamicDelivery))
            {
                if (engine.PublishingContext.RenderContext.ContextVariables[PageTemplateBase.VariableNameCalledFromDynamicDelivery].Equals(PageTemplateBase.VariableValueCalledFromDynamicDelivery))
                {
                    log.Debug("template is rendered by a DynamicDelivery page template, will not convert to lower case");
                    return;
                }
            }

            Item   outputItem = package.GetByName("Output");
            String inputValue = package.GetValue("Output");

            if (inputValue == null || inputValue.Length == 0)
            {
                log.Error("Could not find 'Output' in the package. Exiting template.");
                return;
            }

            StringReader srXml     = new StringReader(inputValue);
            XmlReader    readerXml = new XmlTextReader(srXml);

            // Load the style sheet.
            XslCompiledTransform xslTransformer = new XslCompiledTransform();

            //load the Xsl from the assembly
            Stream xslStream = IOUtils.LoadResourceAsStream("Tridion.Extensions.DynamicDelivery.Templates.Resources.ConvertFirstCharToLowerCase.xslt");

            xslTransformer.Load(XmlReader.Create(xslStream));

            // Execute the transform and output the results to a file.
            StringWriter sw     = new StringWriter();
            XmlWriter    writer = new XmlTextWriter(sw);

            xslTransformer.Transform(readerXml, writer);
            writer.Close();
            sw.Close();

            package.Remove(outputItem);
            outputItem.SetAsString(sw.ToString());
            package.PushItem("Output", outputItem);
        }
Example #15
0
        private string getStructureGroupLocation(string webdav, string ROOT_WEBDAV_URL)
        {
            String sgLocation = String.Empty;
            int    startSG    = 0;
            int    lastSlash  = 0;

            try {
                startSG    = webdav.IndexOf(ROOT_WEBDAV_URL) + ROOT_WEBDAV_URL.Length + 1;
                sgLocation = "/" + webdav.Substring(startSG).Replace("%20", " ");
                sgLocation = sgLocation.Substring(1);
                lastSlash  = sgLocation.LastIndexOf("/");
            } catch (Exception ex) {
                log.Error("Error performing Get Structure Group Location. Full message: " + ex.Message + " \nStack Trace: " + ex.StackTrace);
            }

            return(sgLocation.Remove(lastSlash));
        }
Example #16
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);
            }
        }
        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);
                }
            }
        }
        /// <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 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 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));
        }
Example #21
0
        private static void addFromItemFields(ItemFields tcmFields, Dictionary <string, Dynamic.Category> categories, BuildManager manager)
        {
            foreach (ItemField f in tcmFields)
            {
                if (f is KeywordField)
                {
                    string           categoryId = ((KeywordFieldDefinition)f.Definition).Category.Id;
                    Dynamic.Category dc;
                    if (!categories.ContainsKey(categoryId))
                    {
                        // create category since it doesn't exist yet
                        dc          = new Dynamic.Category();
                        dc.Id       = ((KeywordFieldDefinition)f.Definition).Category.Id;
                        dc.Title    = ((KeywordFieldDefinition)f.Definition).Category.Title;
                        dc.Keywords = new List <Dynamic.Keyword>();
                        categories.Add(dc.Id, dc);
                    }
                    else
                    {
                        dc = categories[categoryId];
                    }
                    foreach (Keyword keyword in ((KeywordField)f).Values)
                    {
                        bool alreadyThere = false;
                        foreach (Dynamic.Keyword dk in dc.Keywords)
                        {
                            if (dk.Id.Equals(keyword.Id))
                            {
                                alreadyThere = true;
                                break;
                            }
                        }
                        if (!alreadyThere)
                        {
                            dc.Keywords.Add(manager.BuildKeyword(keyword));
                        }
                    }
                }

                if (f is EmbeddedSchemaField)
                {
                    try
                    {
                        IList <ItemFields> embeddedFieldsCollection = ((EmbeddedSchemaField)f).Values;
                        foreach (ItemFields embeddedFields in embeddedFieldsCollection)
                        {
                            foreach (ItemField embeddedField in embeddedFields)
                            {
                                if (embeddedField is KeywordField)
                                {
                                    string categoryId = ((KeywordFieldDefinition)embeddedField.Definition).Category.Id;

                                    Dynamic.Category dc;
                                    if (!categories.ContainsKey(categoryId))
                                    {
                                        // create category since it doesn't exist yet
                                        dc          = new Dynamic.Category();
                                        dc.Id       = ((KeywordFieldDefinition)embeddedField.Definition).Category.Id;
                                        dc.Title    = ((KeywordFieldDefinition)embeddedField.Definition).Category.Title;
                                        dc.Keywords = new List <Dynamic.Keyword>();
                                        categories.Add(dc.Id, dc);
                                    }
                                    else
                                    {
                                        dc = categories[categoryId];
                                    }
                                    foreach (Keyword keyword in ((KeywordField)embeddedField).Values)
                                    {
                                        bool alreadyThere = false;
                                        foreach (Dynamic.Keyword dk in dc.Keywords)
                                        {
                                            if (dk.Id.Equals(keyword.Id))
                                            {
                                                alreadyThere = true;
                                                break;
                                            }
                                        }
                                        if (!alreadyThere)
                                        {
                                            dc.Keywords.Add(manager.BuildKeyword(keyword));
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error(ex.Message, ex);
                    }
                }
            }
        }
 /// <summary>
 /// Logs a Error message
 /// </summary>
 /// <param name="message">Message</param>
 public void Error(String message)
 {
     mTemplatingLogger.Error(message);
 }
 public void Error(string message) => _logger.Error(message);
        protected virtual void PublishItem(Item item, TcmUri itemUri)
        {
            log.Debug($"PublishItem called on {itemUri}");

            Stream itemStream = null;
            // See if some template set itself as the applied template on this item
            TcmUri appliedTemplateUri = null;

            if (item.Properties.ContainsKey(Item.ItemPropertyTemplateUri))
            {
                appliedTemplateUri = new TcmUri(item.Properties[Item.ItemPropertyTemplateUri]);
            }
            Component mmComp   = (Component)engine.GetObject(item.Properties[Item.ItemPropertyTcmUri]);
            string    fileName = binaryPathProvider.GetFilename(mmComp, currentTemplate.Id);

            try
            {
                string publishedPath;
                if (fileName == DefaultBinaryPathProvider.USE_DEFAULT_BINARY_PATH)
                {
                    log.Debug("no structure group defined, publishing binary with default settings");
                    // Note: it is dangerous to specify the CT URI as variant ID without a structure group, because it will fail if you publish the same MMC from two or more CTs!
                    // So I removed the variant ID altogether (QS, 20-10-2011)
                    log.Debug(string.Format("publishing mm component {0} without variant id", mmComp.Id));
                    Binary binary = engine.PublishingContext.RenderedItem.AddBinary(mmComp);
                    publishedPath = binary.Url;
                    log.Debug(string.Format("binary is published to url {0}", publishedPath));
                }
                else
                {
                    string         targetSGuri = binaryPathProvider.GetTargetStructureGroupUri(mmComp.Id.ToString());
                    StructureGroup targetSG    = null;
                    if (targetSGuri != null)
                    {
                        targetSG = (StructureGroup)engine.GetObject(targetSGuri);
                    }

                    itemStream = item.GetAsStream();
                    if (itemStream == null)
                    {
                        // All items can be converted to a stream?
                        log.Error(String.Format("Cannot get item '{0}' as stream", itemUri.ToString()));
                    }
                    Binary b;
                    if (targetSG == null)
                    {
                        var variantId = GetVariantId(fileName);
                        log.Debug(string.Format("publishing mm component {0} with variant id {1} and filename {2}", mmComp.Id, variantId, fileName));
                        b = engine.PublishingContext.RenderedItem.AddBinary(itemStream, fileName, variantId, mmComp, mmComp.BinaryContent.MultimediaType.MimeType);
                    }
                    else
                    {
                        var variantId = GetVariantId(targetSG.Id.ToString(), fileName);
                        log.Debug(string.Format("publishing mm component {0} to structure group {1} with variant id {2} and filename {3}", mmComp.Id, targetSGuri, variantId, fileName));
                        b = engine.PublishingContext.RenderedItem.AddBinary(itemStream, fileName, targetSG, variantId, mmComp, mmComp.BinaryContent.MultimediaType.MimeType);
                    }
                    publishedPath = b.Url;
                    log.Debug(string.Format("binary is published to url {0}", publishedPath));
                }
                log.Debug("binary published, published path = " + publishedPath);
                item.Properties[Item.ItemPropertyPublishedPath] = publishedPath;
            }
            finally
            {
                if (itemStream != null)
                {
                    itemStream.Close();
                }
            }
        }
        string HttpPost(string uri, string parameters)
        {
#if DEBUG
            log.Debug("About to post to " + uri);
#endif
            WebRequest webRequest = WebRequest.Create(uri);
            //string ProxyString =
            //   System.Configuration.ConfigurationManager.AppSettings
            //   [GetConfigKey("proxy")];
            //webRequest.Proxy = new WebProxy (ProxyString, true);
            //Commenting out above required change to App.Config
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Method      = "POST";
            byte[] bytes = Encoding.UTF8.GetBytes(parameters);
            Stream os    = null;
            try
            {                                            // send the Post
                webRequest.ContentLength = bytes.Length; //Count bytes to send
#if DEBUG
                log.Debug("content length " + bytes.Length);
#endif
                os = webRequest.GetRequestStream();
                os.Write(bytes, 0, bytes.Length);        //Send it
            }
            catch (WebException ex)
            {
                log.Error("HTTP Response error", ex);
            }
            finally
            {
                if (os != null)
                {
                    os.Close();
                }
            }

            StreamReader sr     = null;
            string       result = null;
            try
            { // get the response
                WebResponse webResponse = webRequest.GetResponse();
                if (webResponse == null)
                {
                    return(null);
                }
                sr     = new StreamReader(webResponse.GetResponseStream());
                result = sr.ReadToEnd().Trim();
            }
            catch (WebException ex)
            {
                log.Error("HTTP Response error", ex);
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                }
            }
            return(result);
        }
Example #26
0
 public void Error(string message)
 {
     _errors.Add(message);
     _logger.Error(message);
 }