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); }
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); } }
private IContentLibraryMultimediaItem GetEclItem(string eclStubComponentId, out IContentLibraryContext eclContext) { _log.Debug("Retrieving ECL item for ECL Stub Component: " + eclStubComponentId); IEclUri eclUri = _eclSession.TryGetEclUriFromTcmUri(eclStubComponentId); if (eclUri == null) { throw new Exception("Unable to get ECL URI for ECL Stub Component: " + eclStubComponentId); } eclContext = _eclSession.GetContentLibrary(eclUri); // This is done this way to not have an exception thrown through GetItem, as stated in the ECL API doc. // The reason to do this, is because if there is an exception, the ServiceChannel is going into the aborted state. // GetItems allows up to 20 (depending on config) connections. IList <IContentLibraryItem> eclItems = eclContext.GetItems(new[] { eclUri }); IContentLibraryMultimediaItem eclItem = (eclItems == null) ? null : eclItems.OfType <IContentLibraryMultimediaItem>().FirstOrDefault(); if (eclItem == null) { eclContext.Dispose(); throw new Exception(string.Format("ECL item '{0}' not found (TCM URI: '{1}')", eclUri, eclStubComponentId)); } _log.Debug(string.Format("Retrieved ECL item for ECL Stub Component '{0}': {1}", eclStubComponentId, eclUri)); return(eclItem); }
/// <summary> /// Get 'current' PublishTransaction. It tries to identify a PublishTransaction from the publish queue that is on the /// given TcmUri, Publication, User, etc. /// </summary> /// <param name="engine">Engine object</param> /// <param name="tcmUri">String representing the tcmuri of the item to check</param> /// <returns>PublishTransaction if found; or null, otherwise</returns> private static PublishTransaction FindPublishTransaction(Engine engine, String tcmUri) { Log.Debug(String.Format("Find PublishTransaction for item '{0}'", tcmUri)); PublishTransaction result = null; Session session = engine.GetSession(); PublishTransactionsFilter filter = new PublishTransactionsFilter(session); filter.PublishTransactionState = PublishTransactionState.Resolving; RepositoryLocalObject item = engine.GetObject(tcmUri) as RepositoryLocalObject; if (item != null) { filter.ForRepository = item.ContextRepository; } PublicationTarget publicationTarget = engine.PublishingContext.PublicationTarget; if (publicationTarget != null) { filter.PublicationTarget = publicationTarget; } XmlElement element = PublishEngine.GetListPublishTransactions(filter); XmlNamespaceManager namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("tcm", "http://www.tridion.com/ContentManager/5.0"); String xPath = String.Format("tcm:ListPublishTransactions/tcm:Item[@ItemID='{0}']", tcmUri); XmlNodeList nodeList = element.SelectNodes(xPath, namespaceManager); String transactionId; if (nodeList != null && nodeList.Count == 1) { transactionId = nodeList[0].Attributes["ID"].Value; TcmUri transactionUri = new TcmUri(transactionId); result = new PublishTransaction(transactionUri, session); } else { foreach (XmlNode node in element.ChildNodes) { transactionId = node.Attributes["ID"].Value; TcmUri transactionUri = new TcmUri(transactionId); result = new PublishTransaction(transactionUri, session); if (IsPublishTransactionForTcmUri(result, tcmUri)) { break; } result = null; } } Log.Debug("Returning PublishTransaction " + result); return(result); }
/// <summary> /// Compiles the razor code. /// </summary> /// <param name="revisionDate">The date the template has been modified. If the revision date is newer than what's in the cache, will update. Otherwise, will not compile and use what's in cache.</param> private void Compile(DateTime revisionDate) { bool loaded = typeof(Microsoft.CSharp.RuntimeBinder.Binder).Assembly != null; ImportIncludes(); CleanupExtraImports(); _generator.ClearCache(); if (_generator.IsTemplateUpdated <TridionRazorTemplate>(_templateID, revisionDate)) { if (_config.ImportSettings.IncludeImportWhereUsed && _config.ImportSettings.IncludeConfigWhereUsed) { _logger.Debug("Clearing Where Used..."); _generator.ClearWhereUsed((TemplateBuildingBlock)Template); } else { // If there are no Where Used references, we don't know what references need to be updated, so we clear them all. _logger.Debug("Clearing all..."); _generator.ClearAllCache(); } } _generator.RegisterTemplate <TridionRazorTemplate>(_templateID, _templateContent, _namespaces, revisionDate); try { _generator.CompileTemplates(_assemblies); } catch (TemplateCompileException ex) { string errorMessage = String.Empty; foreach (CompilerError error in ex.Errors) { if (error.IsWarning == false) { errorMessage += String.Format( "{0}{6}: {1} {2}Line {3} Column {4}: {5} {2}", error.ErrorNumber, error.ErrorText, Environment.NewLine, error.Line, error.Column, ex.GetSourceLine(error.Line), error.IsWarning ? " (Warning)" : String.Empty); } } errorMessage += "Stack Trace: " + Environment.NewLine + ex.StackTrace; _generator.RemoveTemplate(_templateID); throw new Exception("TemplateCompileException: " + errorMessage); } }
public static string RetrieveSearchData(string renderedContent) { var matches = search_directive_pattern.Match(renderedContent); if (!matches.Success) { return(string.Empty); } log.Debug("found search data."); return(matches.Value); }
private StructureGroup GetSG(string sgWebDav, string Start_SG_Images, Publication pub, Engine engine) { String rootSGwebdav = pub.RootStructureGroup.WebDavUrl + "/" + Start_SG_Images + "/" + sgWebDav; StructureGroup result = engine.GetObject(rootSGwebdav) as StructureGroup; if (result == null) // SG not found, creating it { FindOrCreateSG(engine, rootSGwebdav); result = engine.GetObject(rootSGwebdav) as StructureGroup; } else { log.Debug(string.Format("SG '{0}' exists", rootSGwebdav)); } return(result); }
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> /// 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))); } }
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 from XML to java"); return; } } Item outputItem = package.GetByName("Output"); String inputValue = package.GetValue("Output"); if (inputValue == null || inputValue.Length == 0) { log.Warning("Could not find 'Output' in the package, nothing to transform"); return; } String minimizeSettings = package.GetValue("MinimizeSettings"); string outputValue = XmlMinimizer.Convert(inputValue, minimizeSettings); // replace the Output item in the package package.Remove(outputItem); outputItem.SetAsString(outputValue); package.PushItem("Output", outputItem); }
/// <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 static void TimedLog(string message) { DateTime currentTime = DateTime.Now; TimeSpan duration = currentTime - startTime; log.Debug(duration.TotalMilliseconds + " - " + message); }
/// <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)); } }
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); }
/// <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 DxaBuildManager(Package package, Engine engine) : base(package, engine) { // Minimize the amount of unneeded data in the DD4T JSON: BuildProperties.OmitFolders = true; BuildProperties.OmitCategories = true; BuildProperties.OmitContextPublications = true; BuildProperties.OmitOwningPublications = true; BuildProperties.OmitValueLists = true; BuildProperties.ECLEnabled = true; // ECL is only used for ECL Stubs string expandLinkDepth = package.GetValue("expandLinkDepth"); _logger.Debug(string.Format("expandLinkDepth: {0}", expandLinkDepth)); if (!string.IsNullOrEmpty(expandLinkDepth)) { BuildProperties.LinkLevels = Convert.ToInt32(expandLinkDepth); } }
public void Debug(string msg) { _log.Debug(msg); if (string.IsNullOrEmpty(_logFile)) { return; } using (var sw = File.AppendText(_logFile)) { sw.WriteLine(msg); } }
private void AddExtensionData(Dd4tComponentPresentation dd4tComponentPresentation, TcmComponentPresentation tcmComponentPresentation) { if (!tcmComponentPresentation.Conditions.Any()) { return; } _logger.Debug("ComponentPresentation has Conditions"); string[] includeContextExpressions = ContextExpressionManager.GetContextExpressions(tcmComponentPresentation.Conditions.Where(c => !c.Negate).Select(c => c.TargetGroup)); string[] excludeContextExpressions = ContextExpressionManager.GetContextExpressions(tcmComponentPresentation.Conditions.Where(c => c.Negate).Select(c => c.TargetGroup)); if (includeContextExpressions.Any()) { _logger.Debug("Adding Context Expression Conditions (Include): " + string.Join(", ", includeContextExpressions)); dd4tComponentPresentation.AddExtensionProperty(ContextExpressionSectionName, "Include", includeContextExpressions); } if (excludeContextExpressions.Any()) { _logger.Debug("Adding Context Expression Conditions (Exclude): " + string.Join(", ", excludeContextExpressions)); dd4tComponentPresentation.AddExtensionProperty(ContextExpressionSectionName, "Exclude", excludeContextExpressions); } }
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 from XML to java"); return; } } Item outputItem = package.GetByName("Output"); String inputValue = package.GetValue("Output"); if (inputValue == null || inputValue.Length == 0) { log.Warning("Could not find 'Output' in the package, nothing to transform"); return; } //load the Xml doc StringReader xmlReader = new StringReader(inputValue); XPathDocument myXPathDoc = new XPathDocument(xmlReader); XslCompiledTransform xslTransformer = new XslCompiledTransform(); //load the Xsl from the assembly Stream xslStream = IOUtils.LoadResourceAsStream("Tridion.Extensions.DynamicDelivery.Templates.Resources.ConvertToJava.xslt"); xslTransformer.Load(XmlReader.Create(xslStream)); //create the output stream MemoryStream outputStream = new MemoryStream(); //do the actual transform of Xml xslTransformer.Transform(myXPathDoc, null, outputStream); // read output into a string outputStream.Seek(0, SeekOrigin.Begin); StreamReader outputReader = new StreamReader(outputStream); string outputValue = outputReader.ReadToEnd(); // replace the Output item in the package package.Remove(outputItem); outputItem.SetAsString(outputValue); package.PushItem("Output", outputItem); }
public string PublishBinariesInRichTextField(string xhtml) { // rich text field is well-formed, except that it does not always have a root element // to be sure it can be parsed, we will add a root and remove it afterwards TridionXml xml = new TridionXml(); xml.LoadXml("<tmproot>" + xhtml + "</tmproot>"); foreach (XmlElement img in xml.SelectNodes("//xhtml:img[@xlink:href[starts-with(string(.),'tcm:')]]", xml.NamespaceManager)) { log.Debug("found img node " + img.OuterXml); XmlAttribute link = (XmlAttribute)img.SelectSingleNode("@xlink:href", xml.NamespaceManager); log.Debug("about to publish binary with uri " + link.Value); string path = PublishMultimediaComponent(link.Value); log.Debug("binary will be published to path " + path); img.SetAttribute("src", path); } return(xml.DocumentElement.InnerXml); }
public static bool TryGetParameter <T>(this Package package, string name, out T value, TemplatingLogger logger = null) { string paramValue = package.GetValue(name); logger?.Debug($"{name}: '{paramValue}'"); if (string.IsNullOrEmpty(paramValue)) { value = default(T); return(false); } value = (T)Convert.ChangeType(paramValue, typeof(T)); return(true); }
public string RenderRegion(string regionName) { _Log.Debug("Render region: " + regionName + " called"); string output = string.Empty; Page page = (Page)_Engine.GetObject(_Package.GetByName(Package.PageName)); var regions = page.GetRegions(); if (regions.ContainsKey(regionName)) { output = GenerateRegionOutput(regionName, output, regions); } return(output); }
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 from XML to java"); return; } } Item outputItem = package.GetByName("Output"); String inputValue = package.GetValue("Output"); if (inputValue == null || inputValue.Length == 0) { log.Warning("Could not find 'Output' in the package, nothing to transform"); return; } // Combine the 'to lower' and 'to java' functions, since there is no reason to have one without the other. // Note: it is still possible (for backwards compatibility) to have a separate ToLower TBB in your templates. // In that case, the first letter of each element will be converted into lower case twice, which doesn't do any harm. string outputValue = LowerCaseConverter.Convert(inputValue); outputValue = XmlToJavaConverter.Convert(outputValue); // outputValue = XmlMinimizer.Convert(outputValue); // replace the Output item in the package package.Remove(outputItem); outputItem.SetAsString(outputValue); package.PushItem("Output", outputItem); }
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; } } }
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) { _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; } } }
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; }
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); }
public void Debug(string message) { _logger.Debug(message); }
private void Init() { AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve); currentTemplate = engine.PublishingContext.ResolvedItem.Template; buildProperties = new BuildProperties(package); if (!string.IsNullOrWhiteSpace(buildProperties.BinaryPathProvider)) { log.Debug($"Found class to override the binary path provider: {buildProperties.BinaryPathProvider}"); if (buildProperties.BinaryPathProvider.Contains("|")) { var t = buildProperties.BinaryPathProvider.Split('|').Select(a => a.Trim()).ToArray <string>(); log.Debug("Assembly:" + t[0]); log.Debug("Class:" + t[1]); object[] parameters = new object[2] { engine, package }; binaryPathProvider = (IBinaryPathProvider)Activator.CreateInstance(t[0], t[1], parameters).Unwrap(); } else { var type = Type.GetType(buildProperties.BinaryPathProvider); if (type == null) { log.Warning($"Could not find class {buildProperties.BinaryPathProvider}"); binaryPathProvider = null; } else { log.Debug($"Found type {type.FullName}"); binaryPathProvider = (IBinaryPathProvider)Activator.CreateInstance(type, engine, package); log.Debug($"Instantiated class {binaryPathProvider.GetType().FullName}"); } } } if (binaryPathProvider == null) { binaryPathProvider = new DefaultBinaryPathProvider(engine, package); } }
public static Dynamic.Field BuildField(TCM.Fields.ItemField tcmItemField, int currentLinkLevel, BuildManager manager) { Dynamic.Field f = new Dynamic.Field(); if (tcmItemField == null && manager.BuildProperties.PublishEmptyFields) { f.Values.Add(""); return(f); } else if (tcmItemField == null && !manager.BuildProperties.PublishEmptyFields) { throw new FieldHasNoValueException(); } f.Name = tcmItemField.Name; if (tcmItemField is TCM.Fields.XhtmlField) { TCM.Fields.XhtmlField sField = (TCM.Fields.XhtmlField)tcmItemField; if (sField.Values.Count == 0 && manager.BuildProperties.PublishEmptyFields) { f.Values.Add(""); } else if (sField.Values.Count == 0 && !manager.BuildProperties.PublishEmptyFields) { throw new FieldHasNoValueException(); } else { foreach (string v in sField.Values) { f.Values.Add(manager.PublishBinariesInRichTextField(v)); } } f.FieldType = FieldType.Xhtml; return(f); } if (tcmItemField is TCM.Fields.MultiLineTextField) { TCM.Fields.TextField sField = (TCM.Fields.MultiLineTextField)tcmItemField; if (sField.Values.Count == 0 && manager.BuildProperties.PublishEmptyFields) { f.Values.Add(""); } else if (sField.Values.Count == 0 && !manager.BuildProperties.PublishEmptyFields) { throw new FieldHasNoValueException(); } else { foreach (string v in sField.Values) { f.Values.Add(v); } } f.FieldType = FieldType.MultiLineText; return(f); } if (tcmItemField is TCM.Fields.TextField) { TCM.Fields.TextField sField = (TCM.Fields.TextField)tcmItemField; if (sField.Values.Count == 0 && manager.BuildProperties.PublishEmptyFields) { f.Values.Add(""); } else if (sField.Values.Count == 0 && !manager.BuildProperties.PublishEmptyFields) { throw new FieldHasNoValueException(); } else { foreach (string v in sField.Values) { f.Values.Add(v); } } f.FieldType = FieldType.Text; return(f); } if (tcmItemField is TCM.Fields.KeywordField) { TCM.Fields.KeywordField sField = (TCM.Fields.KeywordField)tcmItemField; if (sField.Values.Count == 0 && manager.BuildProperties.PublishEmptyFields) { f.Values.Add(""); } else if (sField.Values.Count == 0 && !manager.BuildProperties.PublishEmptyFields) { throw new FieldHasNoValueException(); } else { // add keyword values f.Keywords = new List <Keyword>(); // we will wrap each linked component in a ContentModel component foreach (TCM.Keyword kw in sField.Values) { f.Keywords.Add(manager.BuildKeyword(kw)); } if (!manager.BuildProperties.OmitValueLists) { f.Values = new List <string>(); foreach (TCM.Keyword kw in sField.Values) { f.Values.Add(kw.Title); } } KeywordFieldDefinition fieldDef = (KeywordFieldDefinition)sField.Definition; f.CategoryId = fieldDef.Category.Id; f.CategoryName = fieldDef.Category.Title; } f.FieldType = FieldType.Keyword; return(f); } if (tcmItemField is TCM.Fields.NumberField) { TCM.Fields.NumberField sField = (TCM.Fields.NumberField)tcmItemField; if (sField.Values.Count == 0 && manager.BuildProperties.PublishEmptyFields) { f.Values.Add(""); } else if (sField.Values.Count == 0 && !manager.BuildProperties.PublishEmptyFields) { throw new FieldHasNoValueException(); } else { f.NumericValues = (List <double>)sField.Values; if (!manager.BuildProperties.OmitValueLists) { f.Values = new List <string>(); foreach (double d in f.NumericValues) { f.Values.Add(Convert.ToString(d)); } } } f.FieldType = FieldType.Number; return(f); } if (tcmItemField is TCM.Fields.DateField) { TCM.Fields.DateField sField = (TCM.Fields.DateField)tcmItemField; if (sField.Values.Count == 0 && manager.BuildProperties.PublishEmptyFields) { f.Values.Add(""); } else if (sField.Values.Count == 0 && !manager.BuildProperties.PublishEmptyFields) { throw new FieldHasNoValueException(); } else { f.DateTimeValues = (List <DateTime>)sField.Values; if (!manager.BuildProperties.OmitValueLists) { f.Values = new List <string>(); foreach (DateTime dt in f.DateTimeValues) { f.Values.Add(Convert.ToString(dt)); } } } f.FieldType = FieldType.Date; return(f); } if (tcmItemField is TCM.Fields.MultimediaLinkField) { TCM.Fields.MultimediaLinkField sField = (TCM.Fields.MultimediaLinkField)tcmItemField; if (sField.Values.Count == 0 && manager.BuildProperties.PublishEmptyFields) { f.Values.Add(tcmItemField.Name); } else if (sField.Values.Count == 0 && !manager.BuildProperties.PublishEmptyFields) { throw new FieldHasNoValueException(); } else { // we will wrap each linked component in a ContentModel component f.LinkedComponentValues = new List <Dynamic.Component>(); int nextLinkLevel = currentLinkLevel - 1; if (MustFollowField(sField, manager)) { log.Debug(string.Format("found component link field named {0} with global followLinksPerField property set to false OR followLink set to true for this field", sField.Name)); } else { log.Debug(string.Format("found component link field named {0} with followLink set to false for this field", sField.Name)); nextLinkLevel = 0; } foreach (TCM.Component comp in sField.Values) { f.LinkedComponentValues.Add(manager.BuildComponent(comp, nextLinkLevel)); } if (!manager.BuildProperties.OmitValueLists) { f.Values = new List <string>(); foreach (Dynamic.Component c in f.LinkedComponentValues) { f.Values.Add(c.Id); } } } f.FieldType = FieldType.MultiMediaLink; return(f); } if (tcmItemField is TCM.Fields.ComponentLinkField) { TCM.Fields.ComponentLinkField sField = (TCM.Fields.ComponentLinkField)tcmItemField; if (sField.Values.Count == 0 && manager.BuildProperties.PublishEmptyFields) { f.Values.Add(tcmItemField.Name); } else if (sField.Values.Count == 0 && !manager.BuildProperties.PublishEmptyFields) { throw new FieldHasNoValueException(); } else { // we will wrap each linked component in a ContentModel component f.LinkedComponentValues = new List <Dynamic.Component>(); int nextLinkLevel = currentLinkLevel - 1; if (MustFollowField(sField, manager)) { log.Debug(string.Format("found component link field named {0} with global followLinksPerField property set to false OR followLink set to true for this field", sField.Name)); } else { log.Debug(string.Format("found component link field named {0} with followLink set to false for this field", sField.Name)); nextLinkLevel = 0; } foreach (TCM.Component comp in sField.Values) { f.LinkedComponentValues.Add(manager.BuildComponent(comp, nextLinkLevel)); } if (!manager.BuildProperties.OmitValueLists) { f.Values = new List <string>(); foreach (Dynamic.Component c in f.LinkedComponentValues) { f.Values.Add(c.Id); } } } f.FieldType = FieldType.ComponentLink; return(f); } if (tcmItemField is TCM.Fields.EmbeddedSchemaField) { TCM.Fields.EmbeddedSchemaField sField = (TCM.Fields.EmbeddedSchemaField)tcmItemField; f.FieldType = FieldType.Embedded; f.EmbeddedValues = new List <Dynamic.FieldSet>(); bool hasValues = CheckIfEmbeddedFieldHasValues(sField); if (!hasValues && manager.BuildProperties.PublishEmptyFields) { Dynamic.FieldSet fields = new FieldSet(); Dynamic.Field fe = new Dynamic.Field(); f.EmbeddedSchema = manager.BuildSchema(((EmbeddedSchemaFieldDefinition)sField.Definition).EmbeddedSchema); EmbeddedSchemaFieldDefinition linksFieldDefinition = sField.Definition as EmbeddedSchemaFieldDefinition; ItemFields newItemField = new ItemFields(linksFieldDefinition.EmbeddedSchema); for (int i = 0; i < newItemField.Count; i++) { if (newItemField[i] is TCM.Fields.EmbeddedSchemaField) { TCM.Fields.EmbeddedSchemaField innerField = (TCM.Fields.EmbeddedSchemaField)newItemField[i]; if (innerField.Values.Count == 0) { Dynamic.FieldSet fieldsinner = new FieldSet(); Dynamic.Field fin = new Dynamic.Field(); fe.EmbeddedSchema = manager.BuildSchema(((EmbeddedSchemaFieldDefinition)innerField.Definition).EmbeddedSchema); EmbeddedSchemaFieldDefinition inlinksFieldDefinition = innerField.Definition as EmbeddedSchemaFieldDefinition; ItemFields newinItemField = new ItemFields(inlinksFieldDefinition.EmbeddedSchema); for (int n = 0; n < newinItemField.Count; n++) { fin.Name = newItemField[n].Name; fieldsinner.Add(newinItemField[n].Name, fin); } fe.EmbeddedValues.Add(fieldsinner); fe.Values.Add(""); } fe.Name = newItemField[i].Name; fields.Add(newItemField[i].Name, fe); } else { Dynamic.Field fein = manager.BuildField(newItemField[i], currentLinkLevel); fein.Values.Clear(); fields.Add(newItemField[i].Name, fein); } } f.EmbeddedValues.Add(fields); f.Values.Add(""); } else if (!hasValues && !manager.BuildProperties.PublishEmptyFields) { throw new FieldHasNoValueException(); } else { // we will wrap each linked component in a ContentModel component f.EmbeddedValues = new List <Dynamic.FieldSet>(); f.EmbeddedSchema = manager.BuildSchema(((EmbeddedSchemaFieldDefinition)sField.Definition).EmbeddedSchema); foreach (TCM.Fields.ItemFields embeddedFields in sField.Values) { f.EmbeddedValues.Add(manager.BuildFields(embeddedFields, currentLinkLevel)); } } return(f); } throw new FieldTypeNotDefinedException(); }
public void Transform(Engine engine, Package package) { _log.Debug("GetAllComponentTemplates: start Transform"); Stopwatch watch = new Stopwatch(); watch.Start(); Session session = engine.GetSession(); ICache cache = session.Cache; String componentTemplateName = String.Empty; if (package.GetValue("ComponentTemplateName") != null) { componentTemplateName = package.GetValue("ComponentTemplateName"); } if (!(String.IsNullOrEmpty(componentTemplateName)) && (package.GetByName(componentTemplateName) != null)) { // Component Template found in Package return; } RepositoryLocalObject context; if (package.GetByName(Package.ComponentName) != null) { context = engine.GetObject(package.GetByName(Package.ComponentName)) as RepositoryLocalObject; } else { context = engine.GetObject(package.GetByName(Package.PageName)) as RepositoryLocalObject; } if (context != null) { Repository contextPublication = context.ContextRepository; RepositoryItemsFilter filter = new RepositoryItemsFilter(session) { ItemTypes = new[] { ItemType.ComponentTemplate }, Recursive = true, BaseColumns = ListBaseColumns.IdAndTitle }; XmlNamespaceManager nm = new XmlNamespaceManager(new NameTable()); nm.AddNamespace(Constants.TcmPrefix, Constants.TcmNamespace); XmlNodeList allComponentTemplates; if (cache.Get("ComponentTemplate", "listcts") != null) { allComponentTemplates = (XmlNodeList)cache.Get("ComponentTemplate", "listcts"); _log.Debug("GetAllComponentTemplates: list already in cache"); } else { allComponentTemplates = contextPublication.GetListItems(filter).SelectNodes("/tcm:ListItems/tcm:Item", nm); cache.Add("ComponentTemplate", "listcts", allComponentTemplates); _log.Debug("GetAllComponentTemplates: list created in cache"); } if (allComponentTemplates != null) { foreach (XmlNode ct in allComponentTemplates) { if (ct.Attributes != null) { String ctName = ct.Attributes["Title"].Value.Replace(" ", "").Replace("-", ""); // Avoid duplicates in Package // Possible performance impact, but could be needed if ComponentTemplateName is set to an empty String if (package.GetByName(ctName) == null) { package.PushItem(ctName, package.CreateStringItem(ContentType.Text, ct.Attributes["ID"].Value)); } } } } } watch.Stop(); _log.Debug("Template finished in " + watch.ElapsedMilliseconds + " milliseconds."); }