public static IEnumerable <Component> GetMultimediaLinks(this ItemFields fields, string fieldName) { return (null != fields && fields.Contains(fieldName) ? (fields[fieldName] as MultimediaLinkField).Values : Enumerable.Empty <Component>()); }
/// <summary> /// Creates a new configuration instance /// </summary> /// <param name="metadata">ItemFields collection with configuration metadata</param> public ReiConfig(ItemFields metadata) { IsValid = true; try { SchemaUri = GetTcmUri(SchemaUriField, metadata); StructureGroupUri = GetTcmUri(StructureGroupUriField, metadata); // make Page Template URI local to Structure Group PageTemplateUri = GetTcmUri(PageTemplateUriField, metadata, StructureGroupUri); // make Component Template URI local to Structure Group ComponentTemplateUri = GetTcmUri(ComponentTemplateUriField, metadata, StructureGroupUri); IndexPageUri = GetTcmUri(IndexPageUriField, metadata); // make Component Template URI local to index Page IndexComponentTemplateUri = GetTcmUri(IndexCtUriField, metadata, IndexPageUri); TargetTypeUri = GetTcmUri(TargetTypeUriField, metadata); } catch (Exception ex) { Logger.Write(ex, Name, LoggingCategory.General, TraceEventType.Error); IsValid = false; } }
/// <summary> /// Process content /// </summary> /// <param name="htmlDoc"></param> /// <param name="taggedContentList"></param> private static void ProcessContent(HtmlDocument htmlDoc, EmbeddedSchemaField taggedContentList) { Schema taggedContentSchema = ((EmbeddedSchemaFieldDefinition)taggedContentList.Definition).EmbeddedSchema; foreach (var node in htmlDoc.DocumentNode.QuerySelectorAll("[data-content-name]")) { // Add XHTML namespace to all elements in the content markup // foreach (var element in node.QuerySelectorAll("*")) { element.SetAttributeValue("xmlns", "http://www.w3.org/1999/xhtml"); } var taggedContentXml = new StringBuilder(); taggedContentXml.Append("<TaggedContent><name>"); taggedContentXml.Append(node.Attributes["data-content-name"].Value); taggedContentXml.Append("</name><content>"); taggedContentXml.Append(node.InnerHtml); taggedContentXml.Append("</content></TaggedContent>"); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(taggedContentXml.ToString()); ItemFields taggedContent = new ItemFields(xmlDoc.DocumentElement, taggedContentSchema); taggedContentList.Values.Add(taggedContent); } }
private string GetBannerImageTcmId() { var page = GetPage(); string imageTcmId = null; foreach (var cp in page.ComponentPresentations) { //ImageGallery var fields = new ItemFields(cp.Component.Content, cp.Component.Schema); var images = fields.OfType <MultimediaLinkField>(); if (images == null || images.Count() == 0) { //Logger.Info("No Multimedia Link Fields in the context."); continue; } var multimediaLink = images.FirstOrDefault(img => img.Name.ToLowerInvariant().Equals("imagegallery")); if (multimediaLink != null && multimediaLink.Value != null && multimediaLink.Value.ComponentType == ComponentType.Multimedia) { imageTcmId = multimediaLink.Value.Id; break; } } return(imageTcmId); }
public override void Transform(Engine engine, Package package) { Engine = engine; Package = package; var c = IsPageTemplate() ? GetPage().ComponentPresentations[0].Component : GetComponent(); XmlDocument resourceDoc = null; resourceDoc = new XmlDocument(); resourceDoc.LoadXml("<root/>"); var fields = new ItemFields(c.Content, c.Schema); var sourceField = fields["resource"] as EmbeddedSchemaField; foreach (var innerField in sourceField.Values) { var key = innerField["key"] as TextField; var value = innerField["value"] as TextField; var data = resourceDoc.CreateElement("data"); data.SetAttribute("name", key.Value); var v = resourceDoc.CreateElement("value"); v.InnerText = value.Value; data.AppendChild(v); resourceDoc.DocumentElement.AppendChild(data); } package.PushItem(Package.OutputName, package.CreateStringItem(ContentType.Xml, resourceDoc.OuterXml)); }
/// <summary> /// Process field data building up index data in XML format /// </summary> /// <param name="fields">Fields to process</param> /// <param name="settings">Custom settings for this set of fields (if not null overrides default settings)</param> public virtual void ProcessData(ItemFields fields, FieldProcessorSettings settings = null) { if (settings == null) { settings = DefaultSettings; } //use defaults if fields are not explicitly included/excluded if (settings.ExcludeByDefault == null) { settings.ExcludeByDefault = DefaultSettings.ExcludeByDefault; if (settings.ManagedFields == null) { settings.ManagedFields = DefaultSettings.ManagedFields; } } if (settings.ManagedFields == null) { settings.ManagedFields = new List<string>(); } if (settings.FieldMap == null) { settings.FieldMap = DefaultSettings.FieldMap; } if (settings.LinkFieldsToEmbed == null) { settings.LinkFieldsToEmbed = DefaultSettings.LinkFieldsToEmbed; } ProcessFields(fields, settings); }
private static NavigationConfig GetNavigationConfiguration(Component navConfigComponent) { NavigationConfig result = new NavigationConfig { NavType = NavigationType.Simple }; if (navConfigComponent.Metadata == null) { return(result); } ItemFields navConfigComponentMetadataFields = new ItemFields(navConfigComponent.Metadata, navConfigComponent.MetadataSchema); Keyword type = navConfigComponentMetadataFields.GetKeywordValue("navigationType"); switch (type.Key.ToLower()) { case "localizable": result.NavType = NavigationType.Localizable; break; } string navTextFields = navConfigComponentMetadataFields.GetSingleFieldValue("navigationTextFieldPaths"); if (!string.IsNullOrEmpty(navTextFields)) { result.NavTextFieldPaths = navTextFields.Split(',').Select(s => s.Trim()).ToList(); } result.ExternalUrlTemplate = navConfigComponentMetadataFields.GetSingleFieldValue("externalLinkTemplate"); return(result); }
/// <summary> /// Process content /// </summary> /// <param name="htmlDoc"></param> /// <param name="taggedContentList"></param> private static void ProcessContent(HtmlDocument htmlDoc, EmbeddedSchemaField taggedContentList) { Schema taggedContentSchema = ((EmbeddedSchemaFieldDefinition)taggedContentList.Definition).EmbeddedSchema; foreach (var node in htmlDoc.DocumentNode.QuerySelectorAll("[data-content-name]")) { // Add XHTML namespace to all elements in the content markup // foreach (var element in node.QuerySelectorAll("*")) { element.SetAttributeValue("xmlns", "http://www.w3.org/1999/xhtml"); } var contentName = node.Attributes["data-content-name"].Value; if (!IsEntryAlreadyDefined(contentName, taggedContentList)) { //Logger.Write("Adding content with name: " + contentName, "CampaignZipImporter", LogCategory.Custom, System.Diagnostics.TraceEventType.Information); var taggedContentXml = new StringBuilder(); taggedContentXml.Append("<TaggedContent><name>"); taggedContentXml.Append(contentName); taggedContentXml.Append("</name><content>"); taggedContentXml.Append(node.InnerHtml); taggedContentXml.Append("</content></TaggedContent>"); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(taggedContentXml.ToString()); ItemFields taggedContent = new ItemFields(xmlDoc.DocumentElement, taggedContentSchema); taggedContentList.Values.Add(taggedContent); } } }
public override void Transform(Engine engine, Package package) { Initialize(engine, package); var template = engine.PublishingContext.ResolvedItem.Template; if (template.Metadata == null || template.MetadataSchema == null) { return; } var metaFields = new ItemFields(template.Metadata, template.MetadataSchema); //PushFieldsToPackage(metaFields, "CT"); foreach (ItemField field in metaFields) { //One Value if (field.Definition.MaxOccurs == 1 && field.StringValue() != null) { var name = string.Format("ComponentTemplate.Metadata.{0}", field.Name); m_Package.Remove(m_Package.GetByName(name)); m_Package.PushItem(name, m_Package.CreateStringItem(ContentType.Text, field.StringValue())); } else // -- Multi Value { //TODO: No supported. } } }
public bool HasField(ItemFields name) { var fields = DtoOptions.Fields; switch (name) { case ItemFields.ThemeSongIds: case ItemFields.ThemeVideoIds: case ItemFields.ProductionLocations: case ItemFields.Keywords: case ItemFields.Taglines: case ItemFields.ShortOverview: case ItemFields.CustomRating: case ItemFields.DateCreated: case ItemFields.SortName: case ItemFields.Overview: case ItemFields.OfficialRatingDescription: case ItemFields.HomePageUrl: case ItemFields.VoteCount: case ItemFields.DisplayMediaType: //case ItemFields.ServiceName: case ItemFields.Genres: case ItemFields.Studios: case ItemFields.Settings: case ItemFields.OriginalTitle: case ItemFields.Tags: case ItemFields.DateLastMediaAdded: case ItemFields.CriticRatingSummary: return(fields.Count == 0 || fields.Contains(name)); default: return(true); } }
private static NavigationConfig LoadConfig(Component component) { NavigationConfig res = new NavigationConfig { NavType = NavigationType.Simple }; if (component.Metadata != null) { ItemFields meta = new ItemFields(component.Metadata, component.MetadataSchema); Keyword type = meta.GetKeywordValue("navigationType"); switch (type.Key.ToLower()) { case "localizable": res.NavType = NavigationType.Localizable; break; } string navTextFields = meta.GetSingleFieldValue("navigationTextFieldPaths"); if (!String.IsNullOrEmpty(navTextFields)) { res.NavTextFieldPaths = navTextFields.Split(',').Select(s => s.Trim()).ToList(); } res.ExternalUrlTemplate = meta.GetSingleFieldValue("externalLinkTemplate"); } return(res); }
protected virtual List <string> ReadPageTemplateIncludes() { //Generate a list of Page Templates which have includes in the metadata List <string> res = new List <string>(); RepositoryItemsFilter templateFilter = new RepositoryItemsFilter(Engine.GetSession()) { ItemTypes = new List <ItemType> { ItemType.PageTemplate }, Recursive = true }; foreach (XmlElement item in GetPublication().GetListItems(templateFilter).ChildNodes) { string id = item.GetAttribute("ID"); PageTemplate template = (PageTemplate)Engine.GetObject(id); if (template.MetadataSchema != null && template.Metadata != null) { ItemFields meta = new ItemFields(template.Metadata, template.MetadataSchema); IEnumerable <string> values = meta.GetTextValues("includes"); if (values != null) { List <string> includes = new List <string>(); foreach (string val in values) { includes.Add(JsonEncode(val)); } string json = String.Format("\"{0}\":[{1}]", template.Id.ItemId, String.Join(",\n", includes)); res.Add(json); } } } return(res); }
private SiteLocalizationData GetPublicationDetails(Publication pub, bool isMaster = false) { SiteLocalizationData pubData = new SiteLocalizationData { Id = pub.Id.ItemId.ToString(CultureInfo.InvariantCulture), Path = pub.PublicationUrl, IsMaster = isMaster }; if (_localizationConfigurationComponent != null) { TcmUri localUri = new TcmUri(_localizationConfigurationComponent.Id.ItemId, ItemType.Component, pub.Id.ItemId); Component locComp = (Component)Engine.GetObject(localUri); if (locComp != null) { ItemFields fields = new ItemFields(locComp.Content, locComp.Schema); foreach (ItemFields field in fields.GetEmbeddedFields("settings")) { if (field.GetTextValue("name") == "language") { pubData.Language = field.GetTextValue("value"); break; } } } } return(pubData); }
public static DateTime?Date(this ItemFields fields, string fieldName = "date") { return(fields.Dates(fieldName) .Cast <DateTime?>() .DefaultIfEmpty(default(DateTime?)) .FirstOrDefault()); }
/// <summary> /// Process field data building up index data in XML format /// </summary> /// <param name="fields">Fields to process</param> /// <param name="settings">Custom settings for this set of fields (if not null overrides default settings)</param> public virtual void ProcessData(ItemFields fields, FieldProcessorSettings settings = null) { if (settings == null) { settings = DefaultSettings; } //use defaults if fields are not explicitly included/excluded if (settings.ExcludeByDefault == null) { settings.ExcludeByDefault = DefaultSettings.ExcludeByDefault; if (settings.ManagedFields == null) { settings.ManagedFields = DefaultSettings.ManagedFields; } } if (settings.ManagedFields == null) { settings.ManagedFields = new List <string>(); } if (settings.FieldMap == null) { settings.FieldMap = DefaultSettings.FieldMap; } if (settings.LinkFieldsToEmbed == null) { settings.LinkFieldsToEmbed = DefaultSettings.LinkFieldsToEmbed; } ProcessFields(fields, settings); }
protected static string GetRegionName(ComponentTemplate template) { // check CT metadata if (template.MetadataSchema != null && template.Metadata != null) { ItemFields meta = new ItemFields(template.Metadata, template.MetadataSchema); string regionName = meta.GetTextValue("regionName"); if (!string.IsNullOrEmpty(regionName)) { return(regionName); } string regionViewName = meta.GetTextValue("regionView"); if (!string.IsNullOrEmpty(regionViewName)) { // strip module from fully qualified name // since we need just the region name here as the web application can't deal with fully qualified region names yet return(StripModuleFromName(regionViewName)); } } // fallback use template title Match match = Regex.Match(template.Title, @".*?\[(.+?)\]"); if (match.Success) { // strip module from fully qualified name // since we need just the region name here as the web application can't deal with fully qualified region names yet return(StripModuleFromName(match.Groups[1].Value)); } // default region name return("Main"); }
public static IEnumerable <ItemFields> GetEmbeddedFields(this ItemFields fields, string fieldName) { return (null != fields && fields.Contains(fieldName) ? (fields[fieldName] as EmbeddedSchemaField).Values : Enumerable.Empty <ItemFields>()); }
/// <summary> /// Performs the actual transformation logic of this <see cref="T:TcmTemplating.TemplateBase" />. /// </summary> /// <remarks> /// Transform is the main entry-point for template functionality. /// </remarks> protected override void Transform() { if (Component != null && Component.Content != null) { ItemFields fields = Component.Fields(); foreach (ItemField field in fields) { if (field is ComponentLinkField) { IList <Component> values = field.ComponentValues(); if (values.Count > 0) { IList <TcmUri> uris = new List <TcmUri>(); foreach (Component value in values) { uris.Add(value.Id); } Package.AddComponents("Component." + field.Name, uris); } } } } }
private static string GetModuleCustomLess(Component variables, string code) { const string line = "@{0}: {1};"; StringBuilder content = new StringBuilder(); // save less variables to disk (if available) in unpacked zip structure if (variables != null) { // assuming all fields are text fields with a single value ItemFields itemFields = new ItemFields(variables.Content, variables.Schema); foreach (ItemField itemField in itemFields) { string value = ((TextField)itemField).Value; if (!String.IsNullOrEmpty(value)) { content.AppendFormat(line, itemField.Name, ((TextField)itemField).Value); } } } if (code != null) { content.Append(code); } return(content.ToString()); }
protected Dictionary <string, Component> GetActiveModules() { Schema moduleConfigSchema = GetSchema(ModuleConfigurationSchemaRootElementName); Session session = moduleConfigSchema.Session; UsingItemsFilter moduleConfigComponentsFilter = new UsingItemsFilter(session) { ItemTypes = new[] { ItemType.Component }, BaseColumns = ListBaseColumns.Id }; Dictionary <string, Component> results = new Dictionary <string, Component>(); foreach (Component comp in moduleConfigSchema.GetUsingItems(moduleConfigComponentsFilter).Cast <Component>()) { // GetUsingItems returns the items in their Owning Publication, which could be lower in the BluePrint than were we are (so don't exist in our context Repository). Component moduleConfigComponent = (Component)Publication.GetObject(comp.Id); if (!session.IsExistingObject(moduleConfigComponent.Id)) { continue; } ItemFields fields = new ItemFields(moduleConfigComponent.Content, moduleConfigComponent.Schema); string moduleName = fields.GetTextValue("name").Trim().ToLower(); if (fields.GetTextValue("isActive").ToLower() == "yes" && !results.ContainsKey(moduleName)) { results.Add(moduleName, moduleConfigComponent); } } return(results); }
/// <summary> /// Initializes a new instance of the <see cref="ItemQuery"/> class. /// </summary> public ItemQuery() { SortBy = new string[] {}; Filters = new ItemFilter[] {}; Fields = new ItemFields[] {}; MediaTypes = new string[] {}; VideoTypes = new VideoType[] {}; Genres = new string[] { }; Studios = new string[] { }; IncludeItemTypes = new string[] { }; ExcludeItemTypes = new string[] { }; Years = new int[] { }; PersonTypes = new string[] { }; Ids = new string[] { }; Artists = new string[] { }; ImageTypes = new ImageType[] { }; AirDays = new DayOfWeek[] { }; SeriesStatuses = new SeriesStatus[] { }; }
static void InflateKeywords(ItemFields fields, XmlElement element) { var ns = new XmlNamespaceManager(element.OwnerDocument.NameTable); ns.AddNamespace("ns", element.NamespaceURI); fields .OfType <KeywordField>() .ToList() .ForEach(keywordField => element.SelectNodes("./ns:" + keywordField.Name, ns) .OfType <XmlElement>() .ToList() .ForEach(kwelement => { kwelement.SetAttribute("href", "http://www.w3.org/1999/xlink", keywordField.Values.First(v => v.Title.Equals(kwelement.InnerText)).Id); kwelement.SetAttribute("type", "http://www.w3.org/1999/xlink", "simple"); kwelement.SetAttribute("title", "http://www.w3.org/1999/xlink", kwelement.InnerText); }) ); fields .OfType <EmbeddedSchemaField>() .ToList() .ForEach(embedField => element.SelectNodes("./ns:" + embedField.Name, ns) .OfType <XmlElement>() .Select((embedElement, i) => new { Fields = embedField.Values[i], Element = embedElement }) .ToList() .ForEach(a => InflateKeywords(a.Fields, a.Element)) ); }
/// <summary> /// Recursively parses the given /// <see cref="T:Tridion.ContentManager.ContentManagement.Fields.ItemFields" /> into /// <see cref="T:Tridion.ContentManager.Temlating.Package" /> variables /// </summary> /// <param name="extractFields"><see cref="I:System.Collections.Generic.IEnumerable{String}" /> of fieldnames to extract</param> /// <param name="fields"><see cref="T:Tridion.ContentManager.ContentManagement.Fields.ItemFields" /></param> /// <remarks>Extract field format is in the form of "FieldName.EmbeddedField"</remarks> protected void ParseFields(IEnumerable <String> extractFields, ItemFields fields) { if (fields != null && extractFields.Any()) { ParseFields(String.Empty, extractFields, fields); } }
private string ProcessFields(ItemFields fields) { StringBuilder attributesBuilder = new StringBuilder(); if (fields != null) { Logger.Debug(String.Join(", ", _metaFieldNames)); foreach (string fieldname in _metaFieldNames) { Logger.Debug("Processing field: " + fieldname); if (fields.Contains(fieldname)) { string attribute = String.Format(" data-{0}=\"{1}\"", fieldname, System.Net.WebUtility.HtmlEncode(fields.GetSingleFieldValue(fieldname))); Logger.Debug("Attribute:" + attribute); // TODO: XML encode the value attributesBuilder.Append(attribute); } } foreach (ItemField field in fields) { if (field is EmbeddedSchemaField) { attributesBuilder.Append(ProcessFields(((EmbeddedSchemaField)field).Value)); } } } Logger.Debug("attributes:" + attributesBuilder); return(attributesBuilder.ToString()); }
protected String GetSingleStringValue(string fieldName, ItemFields fields) { if (fields.Contains(fieldName)) { // check if the field is a KeywordField or assume it is a TextField if (fields[fieldName].GetType().Equals(typeof(KeywordField))) { KeywordField field = fields[fieldName] as KeywordField; if (field != null) { return(field.Value.Title); } } else { TextField field = fields[fieldName] as TextField; if (field != null) { return(field.Value); } } } return(null); }
public static IEnumerable <DateTime?> GetDateValues(this ItemFields fields, string fieldName = "date") { return (null != fields && fields.Contains(fieldName) ? (fields[fieldName] as DateField).Values.Select(d => d == DateTime.MinValue ? null : (DateTime?)d) : new DateTime?[0]); }
public static IEnumerable <string> GetTextValues(this ItemFields fields, string fieldName) { return (null != fields && fields.Contains(fieldName) ? (fields[fieldName] as TextField).Values : new string[0]); }
/// <summary> /// Process links /// </summary> /// <param name="htmlDoc"></param> /// <param name="taggedLinkList"></param> private static void ProcessLinks(HtmlDocument htmlDoc, EmbeddedSchemaField taggedLinkList) { Schema taggedLinkSchema = ((EmbeddedSchemaFieldDefinition)taggedLinkList.Definition).EmbeddedSchema; foreach (var node in htmlDoc.DocumentNode.QuerySelectorAll("[data-link-name]")) { var linkName = node.Attributes["data-link-name"].Value; if (!IsEntryAlreadyDefined(linkName, taggedLinkList)) { //Logger.Write("Adding link with name: " + linkName, "CampaignZipImporter", LogCategory.Custom, System.Diagnostics.TraceEventType.Information); var taggedLinkXml = new StringBuilder(); taggedLinkXml.Append("<TaggedLink><name>"); taggedLinkXml.Append(linkName); taggedLinkXml.Append("</name>"); var linkValue = node.Attributes["href"]; if (linkValue != null) { taggedLinkXml.Append("<url>"); taggedLinkXml.Append(linkValue.Value); taggedLinkXml.Append("</url>"); } taggedLinkXml.Append("</TaggedLink>"); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(taggedLinkXml.ToString()); ItemFields taggedLinks = new ItemFields(xmlDoc.DocumentElement, taggedLinkSchema); taggedLinkList.Values.Add(taggedLinks); } } }
public void Transform(Engine engine, Package package) { Component component = (Component)engine.GetObject(package.GetByName(Package.ComponentName)); ItemFields fields = new ItemFields(component.Content, component.Schema); TextField code = (TextField)fields["Code"]; package.PushItem(Package.OutputName, package.CreateStringItem(ContentType.Html, code.Value)); }
public static IEnumerable <Keyword> GetKeywordValues(this ItemFields fields, string fieldName) { return (null != fields && fields.Contains(fieldName) ? (fields[fieldName] as KeywordField).Values : Enumerable.Empty <Keyword>()); }
public static IEnumerable <double> GetNumberValues(this ItemFields fields, string fieldName) { return (null != fields && fields.Contains(fieldName) ? (fields[fieldName] as NumberField).Values : new double[0]); }
public void Transform(Engine engine, Package package) { RepositoryLocalObject context; if (package.GetByName(Package.ComponentName) != null) { context = (RepositoryLocalObject)engine.GetObject(package.GetByName(Package.ComponentName)); } else if (package.GetByName(Package.PageName) != null) { context = (RepositoryLocalObject)engine.GetObject(package.GetByName(Package.PageName)); } else { throw new Exception("Could not determine context from package. Did not find page or component in package"); } Repository contextPublication = context.ContextRepository; if (contextPublication.Metadata == null) return; ItemFields metadata = new ItemFields(contextPublication.Metadata, contextPublication.MetadataSchema); ComponentLinkField configuration = (ComponentLinkField)metadata["SiteConfiguration"]; foreach (Component c in configuration.Values) { ItemFields content = new ItemFields(c.Content, c.Schema); foreach (ItemField field in content) { var textField = field as TextField; if (textField != null) { package.PushItem(textField.Name, package.CreateStringItem(ContentType.Text, textField.Value)); } } } }
/// <summary> /// Initializes a new instance of the <see cref="ItemQuery" /> class. /// </summary> public ItemQuery() { LocationTypes = new LocationType[] { }; ExcludeLocationTypes = new LocationType[] { }; SortBy = new string[] { }; Filters = new ItemFilter[] { }; Fields = new ItemFields[] { }; MediaTypes = new string[] { }; VideoTypes = new VideoType[] { }; EnableTotalRecordCount = true; Artists = new string[] { }; Studios = new string[] { }; Genres = new string[] { }; StudioIds = new string[] { }; IncludeItemTypes = new string[] { }; ExcludeItemTypes = new string[] { }; Years = new int[] { }; PersonTypes = new string[] { }; Ids = new string[] { }; ArtistIds = new string[] { }; PersonIds = new string[] { }; ImageTypes = new ImageType[] { }; AirDays = new DayOfWeek[] { }; SeriesStatuses = new SeriesStatus[] { }; EnableImageTypes = new ImageType[] { }; }
/// <summary> /// Initializes a new instance of the <see cref="ItemsByNameQuery"/> class. /// </summary> public ItemsByNameQuery() { Fields = new ItemFields[] {}; Recursive = true; MediaTypes = new string[] { }; SortBy = new string[] { }; ExcludeItemTypes = new string[] { }; IncludeItemTypes = new string[] { }; }
public void Transform(Engine engine, Package p) { Component component = (Component)engine.GetObject(p.GetByName(Package.ComponentName)); ItemFields fields = new ItemFields(component.Content, component.Schema); SingleLineTextField field = (SingleLineTextField) fields["ArticleTitle"]; p.PushItem("AsHtml", p.CreateHtmlItem(System.Security.SecurityElement.Escape(field.Value))); p.PushItem("AsText", p.CreateStringItem(ContentType.Text, System.Security.SecurityElement.Escape(field.Value))); }
protected virtual string ProcessModule(string moduleName, Component module, StructureGroup sg) { Dictionary<string, string> data = new Dictionary<string, string>(); ItemFields fields = new ItemFields(module.Content, module.Schema); foreach (var configComp in fields.GetComponentValues("furtherConfiguration")) { data = MergeData(data, ReadComponentData(configComp)); } return PublishJsonData(data, module, moduleName, "config", sg); }
public override void Transform(Tridion.ContentManager.Templating.Engine engine, Tridion.ContentManager.Templating.Package package) { this.Initialize(engine, package); Component c; if (this.IsPageTemplate()) { c = this.GetPage().ComponentPresentations[0].Component; } else { c = this.GetComponent(); } XmlDocument resourceDoc = null; resourceDoc = new XmlDocument(); resourceDoc.LoadXml("<root/>"); ItemFields fields = new ItemFields(c.Content, c.Schema); foreach (ItemField field in fields) { string name = field.Name; string value = ((TextField)field).Value; XmlElement data = resourceDoc.CreateElement("data"); data.SetAttribute("name", name); XmlElement v = resourceDoc.CreateElement("value"); v.InnerText = value; data.AppendChild(v); resourceDoc.DocumentElement.AppendChild(data); } /* Page p = this.GetPage(); ItemFields fields = new ItemFields(p.Metadata, p.MetadataSchema); EmbeddedSchemaField resourcesField = fields["Resource"] as EmbeddedSchemaField; foreach (ItemFields innerFields in resourcesField.Values) { TextField nameField = innerFields["Name"] as TextField; TextField valueField = innerFields["Resource"] as TextField; XmlElement data = resourceDoc.CreateElement("data"); data.SetAttribute("name", nameField.Value); XmlElement v = resourceDoc.CreateElement("value"); v.InnerText = valueField.Value; data.AppendChild(v); resourceDoc.DocumentElement.AppendChild(data); } * * */ this.CreateStringItem("Output", resourceDoc.OuterXml, ContentType.Xml); }
private Binary PublishModuleResources(string moduleName, Component moduleConfigComponent, StructureGroup structureGroup) { ItemFields moduleConfigComponentFields = new ItemFields(moduleConfigComponent.Content, moduleConfigComponent.Schema); Dictionary<string, string> resources = new Dictionary<string, string>(); foreach (Component resourcesComponent in moduleConfigComponentFields.GetComponentValues("resource")) { resources = MergeData(resources, ExtractKeyValuePairs(resourcesComponent)); } return resources.Count == 0 ? null : AddJsonBinary(resources, moduleConfigComponent, structureGroup, moduleName, variantId: "resources"); }
private InnerRegion GetInnerRegion(Page page, ComponentTemplate template) { if (Region.ExtractRegionIndex(template.Id) == -1 && template.Metadata != null) { ItemFields metadata = new ItemFields(template.Metadata, template.MetadataSchema); if (metadata != null && metadata.Contains("innerRegion") && metadata["innerRegion"] != null) { ComponentLinkField innerRegionField = (ComponentLinkField) metadata["innerRegion"]; return new InnerRegion(page, innerRegionField.Value, ComponentPresentation.Component); } } return null; }
/// <summary> /// Gets the (cached) <see cref="T:Tridion.ContentManager.ContentManagement.Fields.ItemFields"/> for a given /// <see cref="T:Tridion.ContentManager.IdentifiableObject"/> and <see cref="T:Tridion.ContentManager.ContentManagement.Schema" /> /// </summary> /// <param name="identifiableObject"><see cref="T:Tridion.ContentManager.IdentifiableObject"/></param> /// <param name="rootElement">Content <see cref="T:System.Xml.XmlElement" /></param> /// <param name="schema"><see cref="T:Tridion.ContentManager.ContentManagement.Schema" /></param> /// <returns>(Cached) <see cref="T:Tridion.ContentManager.ContentManagement.Fields.ItemFields"/></returns> public static ItemFields Get(IdentifiableObject identifiableObject, XmlElement rootElement, Schema schema) { if (identifiableObject != null && rootElement != null && schema != null) { String key = Key(identifiableObject, rootElement.LocalName, schema); ItemFields result = mCache.Value.Get(key); if (result == null) { result = new ItemFields(rootElement, schema); mCache.Value.Add(key, result); } return result; } return null; }
private void ExtractDataAttributes(ItemFields fields, StringBuilder dataAttributesBuilder) { if (fields == null) { return; } foreach (string fieldname in _dataFieldNames.Where(fn => fields.Contains(fn))) { string dataAttribute = string.Format(" data-{0}=\"{1}\"", fieldname, System.Net.WebUtility.HtmlEncode(fields.GetSingleFieldValue(fieldname))); dataAttributesBuilder.Append(dataAttribute); } // Flatten embedded fields foreach (EmbeddedSchemaField embeddedSchemaField in fields.OfType<EmbeddedSchemaField>()) { ExtractDataAttributes(embeddedSchemaField.Value, dataAttributesBuilder); } }
protected string GetUrl(Page page) { string url; if (page.PageTemplate.Title.Equals(_config.ExternalUrlTemplate, StringComparison.InvariantCultureIgnoreCase) && page.Metadata != null) { // The Page is a "Redirect Page"; obtain the URL from its metadata. ItemFields meta = new ItemFields(page.Metadata, page.MetadataSchema); ItemFields link = meta.GetEmbeddedField("redirect"); url = link.GetExternalLink("externalLink"); if (string.IsNullOrEmpty(url)) { url = link.GetSingleFieldValue("internalLink"); } } else { url = GetExtensionlessUrl(page.PublishLocationUrl); } return url; }
private void ProcessFields(ItemFields fields, XmlElement link) { if (fields!=null) { foreach (var fieldname in _metaFieldNames) { if (fields.Contains(fieldname)) { link.SetAttribute("data-" + fieldname, fields.GetSingleFieldValue(fieldname)); } } foreach (var field in fields) { if (field is EmbeddedSchemaField) { ProcessFields(((EmbeddedSchemaField)field).Value, link); } } } }
public void Transform(Engine engine, Package package) { Component c = (Component)engine.GetObject(package.GetByName(Package.ComponentName)); ItemFields content = new ItemFields(c.Content, c.Schema); KeywordField topic = (KeywordField)content["ContentCategory"]; string topics = string.Empty; int count = 0; if (topic.Values.Count > 0) { topics += "("; foreach (Keyword key in topic.Values) { if (count > 0) topics += ", "; topics += key.Title; count++; } topics += ")"; } package.PushItem("Topics", package.CreateStringItem(ContentType.Text, topics)); }
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)); } } } } }
internal void InitializeContent() { if (Content != null) return; Content = new ItemFields(SourceComponent.Content, SourceComponent.Schema); TcmId = SourceComponent.Id.ItemId; Title = SourceComponent.Title; MajorVersion = SourceComponent.Version; MinorVersion = SourceComponent.Revision; OwningPublication = SourceComponent.OwningRepository.Id.ItemId; SchemaId = SourceComponent.Schema.Id.ItemId; CreationDate = SourceComponent.CreationDate; ModificationDate = SourceComponent.RevisionDate; Multimedia = SourceComponent.Schema.Purpose == SchemaPurpose.Multimedia; PublicationId = SourceComponent.ContextRepository.Id.ItemId; TemplateId = Data.PublishingContext.ResolvedItem.Template.Id.ItemId; OrganizationalItemId = SourceComponent.OrganizationalItem.Id.ItemId; OrganizationalItemTitle = SourceComponent.OrganizationalItem.Title; PublicationDate = DateTime.Now; TemplateModifiedDate = Data.PublishingContext.ResolvedItem.Template.RevisionDate; //Implement others as needed }
public override void Transform(Engine engine, Package package) { Engine = engine; Package = package; if (!HasPackageValue(Package, "EmbeddedFieldName")) throw new Exception("Please specify an embedded field name in the template parameters"); if (!HasPackageValue(Package, "KeyFieldName")) throw new Exception("Please specify a key field name in the template parameters"); if (!HasPackageValue(Package, "ValueFieldName")) throw new Exception("Please specify a value field name in the template parameters"); var c = IsPageTemplate() ? GetPage().ComponentPresentations[0].Component : GetComponent(); XmlDocument resourceDoc = null; resourceDoc = new XmlDocument(); resourceDoc.LoadXml("<root/>"); var fields = new ItemFields(c.Content, c.Schema); var sourceField = fields[EmbeddedFieldName] as EmbeddedSchemaField; foreach (var innerField in sourceField.Values) { var key = innerField[KeyFieldName] as TextField; var value = innerField[ValueFieldName] as TextField; var data = resourceDoc.CreateElement("data"); data.SetAttribute("name", key.Value); var v = resourceDoc.CreateElement("value"); v.InnerText = value.Value; data.AppendChild(v); resourceDoc.DocumentElement.AppendChild(data); } package.PushItem(Package.OutputName, package.CreateStringItem(ContentType.Xml, resourceDoc.OuterXml)); }
protected void ProcessModule(string moduleName, Component moduleComponent) { var designConfig = GetDesignConfigComponent(moduleComponent); if (designConfig!=null) { var fields = new ItemFields(designConfig.Content, designConfig.Schema); var zip = fields.GetComponentValue("design"); var variables = fields.GetComponentValue("variables"); var code = fields.GetTextValue("code"); var customLess = GetModuleCustomLess(variables, code); if (zip != null) { string zipfile = tempFolder + moduleName + "-html-design.zip"; File.WriteAllBytes(zipfile, zip.BinaryContent.GetByteArray()); using (var archive = ZipFile.OpenRead(zipfile)) { archive.ExtractToDirectory(tempFolder, true); } List<string> files = mergeFileLines.Keys.Select(s => s).ToList(); foreach (var mergeFile in files) { var path = tempFolder + mergeFile; if (File.Exists(path)) { foreach (var line in File.ReadAllLines(path)) { if (!mergeFileLines[mergeFile].Contains(line.Trim())) { mergeFileLines[mergeFile].Add(line.Trim()); } } } } if (!String.IsNullOrEmpty(customLess.Trim())) { mergeFileLines["src\\system\\assets\\less\\_custom.less"].Add(customLess); } } } }
/// <summary> /// Prepare index data for any item metadata /// </summary> /// <param name="item">The item to process</param> /// <param name="settings">Field processor settings</param> public virtual void ProcessMetadata(RepositoryLocalObject item, FieldProcessorSettings settings) { if (item.Metadata != null) { ItemFields fields = new ItemFields(item.Metadata, item.MetadataSchema); _processor.ProcessData(fields, settings); } }
/// <summary> /// Initializes a new instance of the <see cref="ItemQuery" /> class. /// </summary> public ItemQuery() { LocationTypes = new LocationType[] { }; ExcludeLocationTypes = new LocationType[] { }; SortBy = new string[] { }; Filters = new ItemFilter[] {}; Fields = new ItemFields[] {}; MediaTypes = new string[] {}; VideoTypes = new VideoType[] {}; Genres = new string[] { }; Studios = new string[] { }; IncludeItemTypes = new string[] { }; ExcludeItemTypes = new string[] { }; Years = new int[] { }; PersonTypes = new string[] { }; Ids = new string[] { }; Artists = new string[] { }; ImageTypes = new ImageType[] { }; AirDays = new DayOfWeek[] { }; SeriesStatuses = new SeriesStatus[] { }; }
public EpisodeQuery() { Fields = new ItemFields[] { }; }
/// <summary> /// Prepare index data for a component /// </summary> /// <param name="comp">The component to process</param> /// <param name="settings">field processor settings</param> public virtual void ProcessComponentData(Component component, FieldProcessorSettings settings) { _processor.SetComponentAsProcessed(component.Id); if (component.IsIndexed()) { if (component.Content != null) { ItemFields fields = new ItemFields(component.Content, component.Schema); _processor.ProcessData(fields, settings); } ProcessMetadata(component, settings); } }
public override void Transform(Engine engine, Package package) { Initialize(engine, package); mergeFileLines.Add("src\\system\\assets\\less\\_custom.less", new List<string>()); mergeFileLines.Add("src\\system\\assets\\less\\_modules.less", new List<string>()); mergeFileLines.Add("src\\templates\\partials\\module-scripts-header.hbs", new List<string>()); mergeFileLines.Add("src\\templates\\partials\\module-scripts-footer.hbs", new List<string>()); StringBuilder publishedFiles = new StringBuilder(); string cleanup = package.GetValue("cleanup") ?? String.Empty; // not using System.IO.Path.GetTempPath() because the paths in our zip are already quite long, // so we need a very short temp path for the extract of our zipfile to succeed // using drive from tridion cm homedir for temp folder tempFolder = ConfigurationSettings.GetTcmHomeDirectory().Substring(0, 3) + "t" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "\\"; try { // read values from Component var config = GetComponent(); var fields = new ItemFields(config.Content, config.Schema); var favicon = fields.GetMultimediaLink("favicon"); var version = fields.GetTextValue("version"); var nodeJs = fields.GetTextValue("nodeJs"); // set defaults if required if (String.IsNullOrEmpty(nodeJs)) { nodeJs = NodejsDefault; } PublishJson(String.Format("{{\"version\":{0}}}", JsonEncode(version)), config, GetPublication().RootStructureGroup, "version", "version"); // create temp folder Directory.CreateDirectory(tempFolder); Log.Debug("Created " + tempFolder); ProcessModules(); // build html design ProcessStartInfo info = new ProcessStartInfo { FileName = "cmd.exe", Arguments = String.Format("/c \"{0}\" start --color=false", nodeJs), WorkingDirectory = tempFolder, CreateNoWindow = true, ErrorDialog = false, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, StandardErrorEncoding = Encoding.UTF8, StandardOutputEncoding = Encoding.UTF8 }; using (Process cmd = new Process {StartInfo = info}) { cmd.Start(); using (StreamReader reader = cmd.StandardOutput) { string output = reader.ReadToEnd(); if (!String.IsNullOrEmpty(output)) { Log.Info(output); // TODO: check for errors in standard output and throw exception } } using (StreamReader reader = cmd.StandardError) { string error = reader.ReadToEnd(); if (!String.IsNullOrEmpty(error)) { string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name; Exception ex = new Exception(error); ex.Data.Add("Filename", info.FileName); ex.Data.Add("Arguments", info.Arguments); ex.Data.Add("User", user); if (error.ToLower().Contains("the system cannot find the path specified")) { throw new Exception(String.Format("Node.js not installed or missing from path for user {0}.", user), ex); } else if (error.ToLower().Contains("mkdir") && error.ToLower().Contains("appdata\\roaming\\npm")) { throw new Exception(String.Format("Node.js cannot access %APPDATA% for user {0}.", user), ex); } throw ex; } } cmd.WaitForExit(); } // publish all binaries from dist folder string dist = tempFolder + "dist\\"; if (Directory.Exists(dist)) { // save favicon to disk (if available) if (favicon != null) { File.WriteAllBytes(dist + "favicon.ico", favicon.BinaryContent.GetByteArray()); Log.Debug("Saved " + dist + "favicon.ico"); } string[] files = Directory.GetFiles(dist, "*.*", SearchOption.AllDirectories); foreach (var file in files) { string filename = file.Substring(file.LastIndexOf('\\') + 1); string extension = filename.Substring(filename.LastIndexOf('.') + 1); Log.Debug("Found " + file); // determine correct structure group (create if not exists) Publication pub = (Publication)config.ContextRepository; string relativeFolderPath = file.Substring(dist.Length - 1, file.LastIndexOf('\\') + 1 - dist.Length); relativeFolderPath = relativeFolderPath.Replace("system", SystemSgName).Replace('\\', '/'); string pubSgWebDavUrl = pub.RootStructureGroup.WebDavUrl; string publishSgWebDavUrl = pubSgWebDavUrl + relativeFolderPath; StructureGroup sg = engine.GetObject(publishSgWebDavUrl) as StructureGroup; if (sg == null) { throw new Exception("Missing Structure Group " + publishSgWebDavUrl); } // add binary to package and publish using (FileStream fs = File.OpenRead(file)) { Item binaryItem = Package.CreateStreamItem(GetContentType(extension), fs); var binary = engine.PublishingContext.RenderedItem.AddBinary(binaryItem.GetAsStream(), filename, sg, "dist-" + filename, config, GetMimeType(extension)); binaryItem.Properties[Item.ItemPropertyPublishedPath] = binary.Url; package.PushItem(filename, binaryItem); if (publishedFiles.Length > 0) { publishedFiles.Append(","); } publishedFiles.AppendFormat("\"{0}\"", binary.Url); Log.Info("Published " + binary.Url); } } } else { throw new Exception("Grunt build failed, dist folder is missing."); } } finally { if (String.IsNullOrEmpty(cleanup) || !cleanup.ToLower().Equals("false")) { // cleanup workfolder Directory.Delete(tempFolder, true); Log.Debug("Removed " + tempFolder); } else { Log.Debug("Did not cleanup " + tempFolder); } } // output json result package.PushItem(Package.OutputName, package.CreateStringItem(ContentType.Text, String.Format(JsonOutputFormat, publishedFiles))); }
private string ResolveXhtml(string input) { XmlDocument xhtml = new XmlDocument(); var nsmgr = new XmlNamespaceManager(xhtml.NameTable); nsmgr.AddNamespace("xlink", XlinkNamespace); xhtml.LoadXml(String.Format("<root>{0}</root>", UnEscape(input))); // locate linked components foreach (XmlElement link in xhtml.SelectNodes("//*[@xlink:href[starts-with(string(.),'tcm:')]]", nsmgr)) { string uri = link.Attributes["xlink:href"].IfNotNull(attr => attr.Value); //string title = img.Attributes["xlink:title"].IfNotNull(attr => attr.Value); //string src = img.Attributes["src"].IfNotNull(attr => attr.Value); if (!string.IsNullOrEmpty(uri)) { Component comp = (Component)Engine.GetObject(uri); // resolve youtube video if (comp != null) { ItemFields fields = new ItemFields(comp.Metadata, comp.MetadataSchema); ProcessFields(fields, link); } } } return Escape(xhtml.DocumentElement.InnerXml); }
private void SetOrUpdateMetadata(Component subject, EventArgs args, EventPhases phase) { // quick first test for ECL stub Component if (!subject.Title.StartsWith("ecl:") || subject.ComponentType != ComponentType.Multimedia) return; using (IEclSession eclSession = SessionFactory.CreateEclSession(subject.Session)) { // determine if subject is an ECL stub Component from the list of available mountpoints IEclUri eclUri = eclSession.TryGetEclUriFromTcmUri(subject.Id); if (eclUri != null && MountPointIds.Contains(eclUri.MountPointId)) { // check if metadata field exists ItemFields metadataFields = new ItemFields(subject.Metadata, subject.MetadataSchema); if (metadataFields.Contains(_metadataXmlFieldName)) { // only set value when update is true or metadata is not set string metadata = ((SingleLineTextField)metadataFields[_metadataXmlFieldName]).Value; if (_update || string.IsNullOrEmpty(metadata)) { using (IContentLibraryContext context = eclSession.GetContentLibrary(eclUri)) { // load actual ECL item so you can access its properties and metadata IContentLibraryMultimediaItem eclItem = (IContentLibraryMultimediaItem) context.GetItem(eclUri); try { // implement your custom code here to set the metadata value // currently this reads the configured ECL metadata field and sets its value in the stub metadata if (!string.IsNullOrEmpty(eclItem.MetadataXml)) { XNamespace ns = GetNamespace(eclItem.MetadataXml); XDocument eclMetadata = XDocument.Parse(eclItem.MetadataXml); XElement field = (from xml in eclMetadata.Descendants(ns + _metadataXmlFieldName) select xml).FirstOrDefault(); if (field != null) { string value = field.Value; // only save value when metadata is empty or update is true and value differs if (string.IsNullOrEmpty(metadata) || (_update && !metadata.Equals(value))) { // update metadata if (_asynchronous) { subject.CheckOut(); } ((SingleLineTextField) metadataFields[_metadataXmlFieldName]).Value = value; subject.Metadata = metadataFields.ToXml(); subject.Save(); if (_asynchronous) { subject.CheckIn(); } Logger.Write(string.Format("added {0} to metadata of {1}", value, eclUri), "EclStubComponentEventHandlerExtension", LoggingCategory.General, TraceEventType.Information); } } } } catch (Exception e) { Logger.Write(e, "EclStubComponentEventHandlerExtension", LoggingCategory.General); } } } } } } }
/// <summary> /// Returns Configuration Components from the given metadata element and Schema /// </summary> private List<Component> GetConfigurationsFromMetadata(XmlElement element, Schema schema) { List<Component> results = new List<Component>(); if (element != null && schema != null) { ItemFields metaFields = new ItemFields(element, schema); foreach (string fieldName in SystemComponentField.Split(',')) { if (metaFields.Contains(fieldName)) { ItemField itemField = metaFields[fieldName]; if (itemField is ComponentLinkField) { results.Add(((ComponentLinkField)itemField).Value); } } } } return results; }
private Component GetDesignConfigComponent(Component moduleComponent) { var fields = new ItemFields(moduleComponent.Content, moduleComponent.Schema); return fields.GetComponentValue("designConfiguration"); }
private string GetModuleCustomLess(Component variables, string code) { const string line = "@{0}: {1};"; StringBuilder content = new StringBuilder(); // save less variables to disk (if available) in unpacked zip structure if (variables != null) { // assuming all fields are text fields with a single value var itemFields = new ItemFields(variables.Content, variables.Schema); foreach (var itemField in itemFields) { string value = ((TextField)itemField).Value; if (!String.IsNullOrEmpty(value)) { content.AppendFormat(line, itemField.Name, ((TextField)itemField).Value); } } } if (code != null) { content.Append(code); } return content.ToString(); }
/// <summary> /// Initializes a new instance of the <see cref="ItemsByNameQuery" /> class. /// </summary> public ItemsByNameQuery() { ImageTypes = new ImageType[] { }; Filters = new ItemFilter[] { }; Fields = new ItemFields[] { }; Recursive = true; MediaTypes = new string[] { }; SortBy = new string[] { }; ExcludeItemTypes = new string[] { }; IncludeItemTypes = new string[] { }; EnableImageTypes = new ImageType[] { }; }