public static IEnumerable <string> GetTextValues(this ItemFields fields, string fieldName) { return (null != fields && fields.Contains(fieldName) ? (fields[fieldName] as TextField).Values : new string[0]); }
public static IEnumerable <ItemFields> GetEmbeddedFields(this ItemFields fields, string fieldName) { return (null != fields && fields.Contains(fieldName) ? (fields[fieldName] as EmbeddedSchemaField).Values : Enumerable.Empty <ItemFields>()); }
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 <Keyword> GetKeywordValues(this ItemFields fields, string fieldName) { return (null != fields && fields.Contains(fieldName) ? (fields[fieldName] as KeywordField).Values : Enumerable.Empty <Keyword>()); }
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]); }
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()); }
public static IEnumerable <Component> GetMultimediaLinks(this ItemFields fields, string fieldName) { return (null != fields && fields.Contains(fieldName) ? (fields[fieldName] as MultimediaLinkField).Values : Enumerable.Empty <Component>()); }
public static IEnumerable <double> GetNumberValues(this ItemFields fields, string fieldName) { return (null != fields && fields.Contains(fieldName) ? (fields[fieldName] as NumberField).Values : new double[0]); }
/// <summary> /// Get the link levels from the template's metadata /// </summary> /// <param name="template"></param> /// <returns></returns> internal static int GetLinkLevels(this Template template) { var templateMeta = new ItemFields(template.Metadata, template.MetadataSchema); return(templateMeta.Contains("link_levels") ? (int)((NumberField)templateMeta["link_levels"]).Value : DefaultLinkLevel); }
static IEnumerable <OUT> IfExists <FIELDTYPE, OUT>(this ItemFields fields, string fieldName, Func <FIELDTYPE, IEnumerable <OUT> > f) where FIELDTYPE : ItemField { return (null != fields && fields.Contains(fieldName) ? f((FIELDTYPE)fields[fieldName]) : Enumerable.Empty <OUT>()); }
/// <summary> /// Retrieves a <see cref="T:Tridion.ContentManager.ContentManagement.Keyword" /> field value. /// </summary> /// <param name="itemFields">The <see cref="T:Tridion.ContentManager.ContentManagement.Fields.ItemFields" /> collection.</param> /// <param name="fieldName">Fieldname to retrieve</param> /// <returns><see cref="T:Tridion.ContentManager.ContentManagement.Keyword" /></returns> public static Keyword KeywordValue(this ItemFields itemFields, String fieldName) { if (itemFields != null && itemFields.Contains(fieldName)) { return(itemFields[fieldName].KeywordValue()); } return(null); }
/// <summary> /// Retrieves an embedded <see cref="T:Tridion.ContentManager.ContentManagement.Component" /> field value. /// </summary> /// <param name="itemFields">The <see cref="T:Tridion.ContentManager.ContentManagement.Fields.ItemFields" /> collection.</param> /// <param name="fieldName">Fieldname to retrieve</param> /// <param name="embeddedFieldName">Embedded field to retrieve</param> /// <returns> /// <see cref="T:Tridion.ContentManager.ContentManagement.Component" /> /// </returns> public static Component ComponentValue(this ItemFields itemFields, String fieldName, String embeddedFieldName) { if (itemFields != null && itemFields.Contains(fieldName)) { return(itemFields.EmbeddedValue(fieldName).ComponentValue(embeddedFieldName)); } return(null); }
/// <summary> /// Retrieves an embedded <see cref="T:System.String" /> XML field value. /// </summary> /// <param name="itemFields">The <see cref="T:Tridion.ContentManager.ContentManagement.Fields.ItemFields" /> collection.</param> /// <param name="fieldName">Fieldname to retrieve</param> /// <param name="embeddedFieldName">Embedded field to retrieve</param> /// <returns> /// <see cref="T:System.String" /> /// </returns> public static String XMLValue(this ItemFields itemFields, String fieldName, String embeddedFieldName) { if (itemFields != null && itemFields.Contains(fieldName)) { return(itemFields.EmbeddedValue(fieldName).XMLValue(embeddedFieldName)); } return(String.Empty); }
/// <summary> /// Retrieves <see cref="T:System.String" /> XML field values. /// </summary> /// <param name="itemFields">The <see cref="T:Tridion.ContentManager.ContentManagement.Fields.ItemFields" /> collection.</param> /// <param name="fieldName">Fieldname to retrieve</param> /// <returns><see cref="T:System.String" /> XML values</returns> public static IList <String> XMLValues(this ItemFields itemFields, String fieldName) { if (itemFields != null && itemFields.Contains(fieldName)) { return(itemFields[fieldName].XMLValues()); } return(new List <String>()); }
/// <summary> /// Retrieves a <see cref="T:System.String" /> XML field value. /// </summary> /// <param name="itemFields">The <see cref="T:Tridion.ContentManager.ContentManagement.Fields.ItemFields" /> collection.</param> /// <param name="fieldName">Fieldname to retrieve</param> /// <returns><see cref="T:System.String" /> XML</returns> public static String XMLValue(this ItemFields itemFields, String fieldName) { if (itemFields != null && itemFields.Contains(fieldName)) { return(itemFields[fieldName].XMLValue()); } return(String.Empty); }
/// <summary> /// Retrieves embedded <see cref="T:System.Double" /> field values. /// </summary> /// <param name="itemFields">The <see cref="T:Tridion.ContentManager.ContentManagement.Fields.ItemFields" /> collection.</param> /// <param name="fieldName">Fieldname to retrieve</param> /// <param name="embeddedFieldName">embedded field to retrieve</param> /// <returns> /// <returns><see cref="T:System.Double" /> values</returns> /// </returns> public static IList <Double> NumberValues(this ItemFields itemFields, String fieldName, String embeddedFieldName) { if (itemFields != null && itemFields.Contains(fieldName)) { return(itemFields.EmbeddedValue(fieldName).NumberValues(embeddedFieldName)); } return(new List <Double>()); }
/// <summary> /// Retrieves an embedded <see cref="T:System.Double" /> field value. /// </summary> /// <param name="itemFields">The <see cref="T:Tridion.ContentManager.ContentManagement.Fields.ItemFields" /> collection.</param> /// <param name="fieldName">Fieldname to retrieve</param> /// <param name="embeddedFieldName">Embedded field to retrieve</param> /// <returns> /// <see cref="T:System.Double" /> /// </returns> public static Double NumberValue(this ItemFields itemFields, String fieldName, String embeddedFieldName) { if (itemFields != null && itemFields.Contains(fieldName)) { return(itemFields.EmbeddedValue(fieldName).NumberValue(embeddedFieldName)); } return(Double.NaN); }
/// <summary> /// Retrieves a <see cref="T:System.Double" /> field value. /// </summary> /// <param name="itemFields">The <see cref="T:Tridion.ContentManager.ContentManagement.Fields.ItemFields" /> collection.</param> /// <param name="fieldName">Fieldname to retrieve</param> /// <returns><see cref="T:System.Double" /></returns> public static Double NumberValue(this ItemFields itemFields, String fieldName) { if (itemFields != null && itemFields.Contains(fieldName)) { return(itemFields[fieldName].NumberValue()); } return(Double.NaN); }
/// <summary> /// Retrieves an embedded <see cref="T:System.DateTime" /> field value. /// </summary> /// <param name="itemFields">The <see cref="T:Tridion.ContentManager.ContentManagement.Fields.ItemFields" /> collection.</param> /// <param name="fieldName">Fieldname to retrieve</param> /// <param name="embeddedFieldName">Embedded field to retrieve</param> /// <returns> /// <see cref="T:System.DateTime" /> /// </returns> public static DateTime DateValue(this ItemFields itemFields, String fieldName, String embeddedFieldName) { if (itemFields != null && itemFields.Contains(fieldName)) { return(itemFields.EmbeddedValue(fieldName).DateValue(embeddedFieldName)); } return(default(DateTime)); }
/// <summary> /// Retrieves a <see cref="T:System.DateTime" /> field value. /// </summary> /// <param name="itemFields">The <see cref="T:Tridion.ContentManager.ContentManagement.Fields.ItemFields" /> collection.</param> /// <param name="fieldName">Fieldname to retrieve</param> /// <returns><see cref="T:System.DateTime" /></returns> public static DateTime DateValue(this ItemFields itemFields, String fieldName) { if (itemFields != null && itemFields.Contains(fieldName)) { return(itemFields[fieldName].DateValue()); } return(default(DateTime)); }
/// <summary> /// Retrieves embedded <see cref="T:System.String" /> field values. /// </summary> /// <param name="itemFields">The <see cref="T:Tridion.ContentManager.ContentManagement.Fields.ItemFields" /> collection.</param> /// <param name="fieldName">Fieldname to retrieve</param> /// <param name="embeddedFieldName">embedded field to retrieve</param> /// <returns> /// <returns><see cref="T:System.String" /> values</returns> /// </returns> public static IList <String> ExternalLinkValues(this ItemFields itemFields, String fieldName, String embeddedFieldName) { if (itemFields != null && itemFields.Contains(fieldName)) { return(itemFields.EmbeddedValue(fieldName).ExternalLinkValues(embeddedFieldName)); } return(new List <String>()); }
/// <summary> /// Retrieves a <see cref="T:Tridion.ContentManager.ContentManagement.Component" /> field value. /// </summary> /// <param name="itemFields">The <see cref="T:Tridion.ContentManager.ContentManagement.Fields.ItemFields" /> collection.</param> /// <param name="fieldName">Fieldname to retrieve</param> /// <returns><see cref="T:Tridion.ContentManager.ContentManagement.Component" /></returns> public static Component ComponentValue(this ItemFields itemFields, String fieldName) { if (itemFields != null && itemFields.Contains(fieldName)) { return(itemFields[fieldName].ComponentValue()); } return(null); }
/// <summary> /// Retrieves embedded <see cref="T:Tridion.ContentManager.ContentManagement.Component" /> field values. /// </summary> /// <param name="itemFields">The <see cref="T:Tridion.ContentManager.ContentManagement.Fields.ItemFields" /> collection.</param> /// <param name="fieldName">Fieldname to retrieve</param> /// <param name="embeddedFieldName">Embedded field to retrieve</param> /// <returns> /// <returns><see cref="T:Tridion.ContentManager.ContentManagement.Component" /> values</returns> /// </returns> public static IList <Component> ComponentValues(this ItemFields itemFields, String fieldName, String embeddedFieldName) { if (itemFields != null && itemFields.Contains(fieldName)) { return(itemFields.EmbeddedValue(fieldName).ComponentValues(embeddedFieldName)); } return(new List <Component>()); }
/// <summary> /// Get a list of strings from a item (text) field. /// </summary> /// <param name="fieldName">the XML field name</param> /// <param name="fields">ItemFields collection</param> /// <returns>IList with string values from the field or null of the field has no values</returns> public static IList <string> GetStringValues(string fieldName, ItemFields fields) { if (!fields.Contains(fieldName)) { return(null); } TextField field = (TextField)fields[fieldName]; return((field.Values.Count > 0) ? field.Values : null); }
protected Component GetComponentValue(String fieldNAme, ItemFields fields) { if (fields.Contains(fieldNAme)) { ComponentLinkField field = fields[fieldNAme] as ComponentLinkField; return(field.Value); } return(null); }
protected IList <string> GetStringValues(string fieldName, ItemFields fields) { if (fields.Contains(fieldName)) { TextField field = (TextField)fields[fieldName]; return((field.Values.Count > 0) ? field.Values : null); } else { return(null); } }
protected IList <double> GetNumberValues(string fieldName, ItemFields fields) { if (fields.Contains(fieldName)) { NumberField field = (NumberField)fields[fieldName]; return((field.Values.Count > 0) ? field.Values : null); } else { return(null); } }
protected IList <Keyword> GetKeywordValues(string fieldName, ItemFields fields) { if (fields.Contains(fieldName)) { KeywordField field = (KeywordField)fields[fieldName]; return((field.Values.Count > 0) ? field.Values : null); } else { return(null); } }
protected IList <DateTime> GetDateValues(string fieldName, ItemFields fields) { if (fields.Contains(fieldName)) { DateField field = (DateField)fields[fieldName]; return((field.Values.Count > 0) ? field.Values : null); } else { return(null); } }
protected IList <Component> GetComponentValues(string fieldName, ItemFields fields) { if (fields.Contains(fieldName)) { ComponentLinkField field = (ComponentLinkField)fields[fieldName]; return((field.Values.Count > 0) ? field.Values : null); } else { return(null); } }
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; }
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); } }
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 static Dictionary<string, Region> GetRegions(this Page page) { PageTemplate pageTemplate = page.PageTemplate; string cacheKey = pageTemplate.Id + "regions"; if (page.Session.Cache.Get("", cacheKey) != null) return (Dictionary<string, Region>)page.Session.Cache.Get("", cacheKey); Dictionary<string, Region> regions = new Dictionary<string, Region>(); Dictionary<string, Keyword> themeKeywords = new Dictionary<string, Keyword>(); if (pageTemplate.Metadata != null) { ItemFields pageTemplateMeta = new ItemFields(pageTemplate.Metadata, pageTemplate.MetadataSchema); if (pageTemplateMeta.Contains("theme")) { KeywordField k = (KeywordField)pageTemplateMeta["theme"]; Keyword theme = k.Value; ChildKeywordsFilter f = new ChildKeywordsFilter(page.Session); foreach (Keyword keyword in theme.GetChildKeywords(f)) { string title = keyword.Title; string themepattern = theme.Title + " - "; string overridenregionname = title.Replace(themepattern, ""); themeKeywords.Add(overridenregionname, keyword); } } } foreach (ComponentPresentation cp in page.ComponentPresentations) { ComponentTemplate ct = cp.ComponentTemplate; if (ct.Metadata != null) { ItemFields metadata = new ItemFields(ct.Metadata, ct.MetadataSchema); if (metadata.Contains("region")) { KeywordField keywordField = (KeywordField)metadata["region"]; if (keywordField.Values.Count > 0) { Keyword regionKeyword = keywordField.Value; string regionName = regionKeyword.Title; if (regions.ContainsKey(regionName)) { regions[regionName].ComponentPresentations.Add(cp); } else { Region region = new Region { Name = regionName, ComponentPresentations = new List<ComponentPresentation> { cp } }; if (themeKeywords.ContainsKey(regionName)) region.RegionDefinitionsKeyword = themeKeywords[regionName]; else region.RegionDefinitionsKeyword = regionKeyword; regions.Add(regionName, region); } } } } } page.Session.Cache.Add("", cacheKey, regions); return regions; }
/// <summary> /// Finds the item field X path and value. /// </summary> /// <param name="parts">The parts.</param> /// <param name="currentIndex">Index of the current.</param> /// <param name="currentXpath">The current xpath.</param> /// <param name="fields">The fields.</param> /// <param name="isMultiValue">if set to <c>true</c> [is multi value].</param> /// <returns>The field's value wrapped in SiteEdit span tags if SiteEdit is set to <c>true</c>.</returns> private string FindItemFieldXPathAndValue(string[] parts, int currentIndex, string currentXpath, ItemFields fields, out bool isMultiValue) { if (_itemType != ItemType.Component) _disableSiteEdit = true; string input = parts[currentIndex]; int num = -1; Match match = PartRegex.Match(input); if (match.Success) { input = match.Groups[1].Value; num = Convert.ToInt32(match.Groups[3].Value); } if (fields != null) { if (fields.Contains(input)) { ItemField field = fields[input]; if ((parts.Length - 1) == currentIndex) { isMultiValue = field.Definition.MaxOccurs != 1; string fieldValue = GetFieldValue(field, ((num == -1) ? 0 : num)); if (_siteEdit && !_disableSiteEdit) if (_siteEditVersion == SiteEditVersion.SiteEdit13) return (String.Format(_siteEditFormatString, ((_isContent) ? "Content" : "Metadata"), (((_isContent) ? _component.Content.LocalName : _component.Metadata.LocalName) + "/" + currentXpath) + "custom:" + field.Name + ((num >= 0) ? ("[" + (num + 1) + "]") : ""), fieldValue)); else return (String.Format(SiteEdit2009FormatString, ((_isContent) ? "Fields" : "MetaData") + "." + currentXpath + field.Name, ((num >= 0) ? num : 0), fieldValue)); else return fieldValue; } EmbeddedSchemaField schema = field as EmbeddedSchemaField; if (schema != null && schema is EmbeddedSchemaField) { return (this.FindItemFieldXPathAndValue(parts, currentIndex + 1, currentXpath + "custom:" + field.Name + ((num >= 0) ? ("[" + (num + 1) + "]") : "") + "/", ((num >= 0) ? (schema.Values[num]) : schema.Value), out isMultiValue)); } else if (field is ComponentLinkField || field is MultimediaLinkField) { Component LinkedComponent = null; if (field is ComponentLinkField) { ComponentLinkField componentLink = field as ComponentLinkField; LinkedComponent = new Component(((num >= 0) ? (componentLink.Values[num].Id) : componentLink.Value.Id), _engine.GetSession()); } else { MultimediaLinkField componentLink = field as MultimediaLinkField; LinkedComponent = new Component(((num >= 0) ? (componentLink.Values[num].Id) : componentLink.Value.Id), _engine.GetSession()); } FieldOutputHandler subHandler = new FieldOutputHandler(LinkedComponent.Id, _engine, _package); subHandler.SiteEdit = false; _disableSiteEdit = true; subHandler.EscapeOutput = _escapeOutput; subHandler.DateFormat = _dateFormat; subHandler.Culture = _culture.ToString(); subHandler.PushBinariesToPackage = _pushBinariesToPackage; String QualifiedFieldName = String.Empty; for (int i = currentIndex + 1; i < parts.Length; i++) { QualifiedFieldName += parts[i]; if (i < (parts.Length - 1)) QualifiedFieldName += "."; } isMultiValue = field.Definition.MaxOccurs != 1; String SubHandlerResult = subHandler.GetStringValue(QualifiedFieldName); return SubHandlerResult; } else if (field is KeywordField) { KeywordField Keyfield = (KeywordField)field; FieldOutputHandler subHandler = new FieldOutputHandler(Keyfield.Values[0].Id, _engine, _package); subHandler.SiteEdit = false; _disableSiteEdit = true; subHandler.EscapeOutput = _escapeOutput; subHandler.DateFormat = _dateFormat; subHandler.Culture = _culture.ToString(); subHandler.PushBinariesToPackage = _pushBinariesToPackage; String QualifiedFieldName = String.Empty; for (int i = currentIndex + 1; i < parts.Length; i++) { QualifiedFieldName += parts[i]; if (i < (parts.Length - 1)) QualifiedFieldName += "."; } isMultiValue = field.Definition.MaxOccurs != 1; String SubHandlerResult = subHandler.GetStringValue(QualifiedFieldName); return SubHandlerResult; } Log.Warning(string.Format("Part {0} in qualified field name was expected to refer to an embedded schema!", field.Name)); } } isMultiValue = false; return null; }
/// <summary> /// Finds the item field. /// </summary> /// <param name="parts">The parts.</param> /// <param name="currentIndex">Index of the current.</param> /// <param name="fields">The fields.</param> /// <param name="isMultiValue">if set to <c>true</c> [is multi value].</param> /// <returns></returns> private ItemField FindItemField(string[] parts, int currentIndex, ItemFields fields, out bool isMultiValue) { string input = parts[currentIndex]; int num = -1; Match match = PartRegex.Match(input); if (match.Success) { input = match.Groups[1].Value; num = Convert.ToInt32(match.Groups[3].Value); } if (fields.Contains(input)) { ItemField field = fields[input]; if ((parts.Length - 1) == currentIndex) { isMultiValue = field.Definition.MaxOccurs != 1; return field; } else { if (field is EmbeddedSchemaField) { EmbeddedSchemaField schema = field as EmbeddedSchemaField; if (schema != null) return (FindItemField(parts, currentIndex + 1, ((num >= 0) ? (schema.Values[num]) : schema.Value), out isMultiValue)); } else if (field is ComponentLinkField || field is MultimediaLinkField) { Component LinkedComponent = null; if (field is ComponentLinkField) { ComponentLinkField componentLink = field as ComponentLinkField; LinkedComponent = new Component(((num >= 0) ? (componentLink.Values[num].Id) : componentLink.Value.Id), _engine.GetSession()); } else { MultimediaLinkField componentLink = field as MultimediaLinkField; LinkedComponent = new Component(((num >= 0) ? (componentLink.Values[num].Id) : componentLink.Value.Id), _engine.GetSession()); } FieldOutputHandler subHandler = new FieldOutputHandler(LinkedComponent.Id, _engine, _package); subHandler.SiteEdit = false; _disableSiteEdit = true; subHandler.EscapeOutput = _escapeOutput; subHandler.DateFormat = _dateFormat; subHandler.Culture = _culture.ToString(); subHandler.PushBinariesToPackage = _pushBinariesToPackage; String QualifiedFieldName = String.Empty; for (int i = currentIndex + 1; i < parts.Length; i++) { QualifiedFieldName += parts[i]; if (i < (parts.Length - 1)) QualifiedFieldName += "."; } isMultiValue = field.Definition.MaxOccurs != 1; if (_returnType == "ComponentLinkField") return subHandler.GetComponentLinkField(QualifiedFieldName); else if (_returnType == "EmbeddedSchemaField") return subHandler.GetEmbeddedSchemaField(QualifiedFieldName); else return null; } Log.Warning(string.Format("Part \"{0}\" in qualified field name was expected to refer to an embedded schema!", field.Name)); } } isMultiValue = false; return null; }
/// <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; }
/// <summary> /// Resolve and possibly publish an ECL item /// </summary> /// <param name="eclItemInPackage">EclItemInPackage object</param> /// <param name="attributes">template atrributes</param> /// <param name="variantId">variant id</param> /// <param name="targetStructureGroup">target Structure Group to publish too (when null, Image Structure Group from Publication will be used</param> /// <returns>tridion publish path or external link</returns> private string ResolveEclItem(EclItemInPackage eclItemInPackage, IList<ITemplateAttribute> attributes, string variantId, StructureGroup targetStructureGroup) { // clear so a simple IsNull check can be used unless we actually set it _metadataEmbedCode = null; Component component = (Component)_engine.GetSession().GetObject(eclItemInPackage.StubUri); // assuming there is a program with and asset in the metadata, checking if that contains channelinfo (assuming that will be the youtube channel) XDocument metadata = XDocument.Parse(eclItemInPackage.EclItem.MetadataXml); if (metadata.Descendants(MmEclNs + "Program").Descendants(MmEclNs + "Asset").Descendants(MmEclNs + "ChannelInfo").Any()) { // get youtube id from ecl metadata string youTubeId = metadata.Descendants(MmEclNs + "Program").Descendants(MmEclNs + "Asset").Descendants(MmEclNs + "ChannelInfo").Descendants(MmEclNs + "Reference").FirstOrDefault().Value; if (!string.IsNullOrEmpty(youTubeId)) { // ToDo: make these configurable via parameters schema values const string YouTubeUrl = "//www.youtube.com/embed/"; const string YouTubeEmbedCode = "<iframe width=\"{1}\" height=\"{2}\" src=\"{0}\" frameborder=\"0\" allowfullscreen></iframe>"; const int DefaultWidth = 640; const int DefaultHeight = 360; const string DefaultLanguage = "us-EN"; // check if we need translated video string owningLanguageCode = string.Empty; string languageCode = string.Empty; ItemFields owningMetadataFields = new ItemFields(component.OwningRepository.Metadata, component.OwningRepository.MetadataSchema); if (owningMetadataFields.Contains(LanguageMetadataField)) { owningLanguageCode = ((KeywordField)owningMetadataFields[LanguageMetadataField]).Value.Title; } ItemFields metadataFields = new ItemFields(component.ContextRepository.Metadata, component.ContextRepository.MetadataSchema); if (metadataFields.Contains(LanguageMetadataField)) { languageCode = ((KeywordField)metadataFields[LanguageMetadataField]).Value.Title; } // check if not default language and context repository and owning repository have the same language codes (indicating the video is localized in the language publication) if (!languageCode.Equals(DefaultLanguage) && owningLanguageCode.Equals(languageCode)) { // get translation folder id string distributionId = string.Format("[{0}]", eclItemInPackage.EclUri.ItemId); // ToDo: reuse IEclSession from Transform method (and correctly dispose it) using (IEclSession eclSession = SessionFactory.CreateEclSession(_engine.GetSession())) { // ToDo: see if IContentLibraryContext can be reused through Transform method (and correctly disposed of) using (IContentLibraryContext context = eclSession.GetContentLibrary(eclItemInPackage.EclUri)) { // loop over all folders where item resides and use the one which begins with "[distributionId]" IFolderContent folderContent = context.GetFolderContent(eclItemInPackage.EclItem.ParentId, 0, EclItemTypes.Folder); foreach (IContentLibraryListItem subFolder in folderContent.ChildItems) { if (subFolder.Title.StartsWith(distributionId)) { // list all distributions in this folder and use the one which begins with "[languageCode]" string language = string.Format("[{0}]", languageCode); folderContent = context.GetFolderContent(subFolder.Id, 0, EclItemTypes.File); foreach (IContentLibraryListItem distribution in folderContent.ChildItems) { if (distribution.Title.StartsWith(language)) { IContentLibraryMultimediaItem translatedItem = (IContentLibraryMultimediaItem)context.GetItem(distribution.Id); // use translated video int width = translatedItem.Width.HasValue ? translatedItem.Width.Value : DefaultWidth; int height = translatedItem.Height.HasValue ? translatedItem.Height.Value : DefaultHeight; metadata = XDocument.Parse(translatedItem.MetadataXml); // assuming there is a program with and asset in the metadata, checking of that contains channelinfo (assuming that will be the youtube channel) if (metadata.Descendants(MmEclNs + "Program").Descendants(MmEclNs + "Asset").Descendants(MmEclNs + "ChannelInfo").Any()) { // get youtube id from ecl metadata youTubeId = metadata.Descendants(MmEclNs + "Program").Descendants(MmEclNs + "Asset").Descendants(MmEclNs + "ChannelInfo").Descendants(MmEclNs + "Reference").FirstOrDefault().Value; if (!string.IsNullOrEmpty(youTubeId)) { _metadataEmbedCode = string.Format(YouTubeEmbedCode, YouTubeUrl + youTubeId, width, height); } } break; } } break; } } } } } else { // use existing video int width = eclItemInPackage.EclItem.Width.HasValue ? eclItemInPackage.EclItem.Width.Value : DefaultWidth; int height = eclItemInPackage.EclItem.Height.HasValue ? eclItemInPackage.EclItem.Height.Value : DefaultHeight; _metadataEmbedCode = string.Format(YouTubeEmbedCode, YouTubeUrl + youTubeId, width, height); } return YouTubeUrl + youTubeId; } } // determine if item is already published or if we should get the content for it and let tridion publish it string publishedPath = eclItemInPackage.EclItem.GetDirectLinkToPublished(attributes); if (string.IsNullOrEmpty(publishedPath)) { // tridion must publish this ecl item as a variant // create a filename with size and a proper extension string filename = ConstructFileName(eclItemInPackage.EclItem.Filename, variantId, eclItemInPackage.EclUri.ToString()); Binary publishedEclItem; // get content as stream Stream contentStream = eclItemInPackage.PackageItem.GetAsStream(); string contentType = eclItemInPackage.EclItem.MimeType; using (contentStream) { // a provider (like the ADAM provider) can return an empty stream when requested without attributes // in that case we should resolve the item with its size taken into consideration // so here we ask for the content again passing width and height in attributes if (contentStream.Length == 0) { using (Stream stream = CreateTemporaryFileStream()) { IContentResult content = eclItemInPackage.EclItem.GetContent(attributes); content.Stream.CopyTo(stream); publishedEclItem = AddBinary(stream, variantId, contentType, filename, component, targetStructureGroup); } } else { publishedEclItem = AddBinary(contentStream, variantId, contentType, filename, component, targetStructureGroup); } } // we could consider updating the package item with the content and the file extension, but to change the content type, we have to recreate it // this won't be of much use other than getting the content stream twice (performance impact) as the package item will (or should) not be used after this anymore // set published path in package item and add to attributes eclItemInPackage.PackageItem.Properties[Item.ItemPropertyPublishedPath] = publishedEclItem.Url; return publishedEclItem.Url; } // ecl item is already published, lets set the uri that can be used from a public website to link directly to the item on the external system eclItemInPackage.PackageItem.Properties[Item.ItemPropertyPublishedPath] = publishedPath; Log.Info(string.Format("resolved ECL item with path {0}", publishedPath)); return publishedPath; }
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); } } } } } } }
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(); }