public FooterLinkGroupViewModel(IPublishedElement content) { Title = content.Value <string>("title"); var linkTitle = ""; var linkUrl = ""; Links = new List <Links>(); content.Value <IEnumerable <IPublishedElement> >("footerLinks").ToList().ForEach( item => { if (item.HasValue("internalLink")) { var itemContent = item.Value <List <IPublishedContent> >("internalLink").First(); linkTitle = itemContent.Name; linkUrl = itemContent.Url; } else if (item.HasValue("externalLinkText") && item.HasValue("externalLinkUrl")) { linkTitle = item.Value <string>("externalLinkText"); linkUrl = item.Value <string>("externalLinkUrl"); } if (!string.IsNullOrEmpty(linkTitle) && !string.IsNullOrEmpty(linkUrl)) { Links.Add(new Links() { Title = linkTitle, URL = linkUrl }); } } ); }
private Teaser GetTeaser(IPublishedElement element) { var teaser = new Teaser(element); if (teaser.UseArticleData) { var article = teaser.Link?.Udi != null ? new ArticlePage(Helper.Content(teaser.Link.Udi)) : null; if (article == null) { throw new Exception($"Please make sure that you have a linked article page when using article data."); } } else { teaser.Images = element.HasValue(DocumentTypes.Teaser.Fields.Images) ? _imageService.GetImages( element.Value <IEnumerable <IPublishedContent> >(DocumentTypes.Teaser.Fields.Images)) : null; teaser.TeaserText = element.HasValue(DocumentTypes.Teaser.Fields.TeaserText) ? element.Value <string>(DocumentTypes.Teaser.Fields.TeaserText) : null; teaser.TeaserTitle = element.HasValue(DocumentTypes.Teaser.Fields.TeaserTitle) ? element.Value <string>(DocumentTypes.Teaser.Fields.TeaserTitle) : null; } return(teaser); }
/// <summary> /// Gets the value of a content's property identified by its alias, converted to a specified type. /// </summary> /// <typeparam name="T">The target property type.</typeparam> /// <param name="content">The content.</param> /// <param name="alias">The property alias.</param> /// <param name="culture">The variation language.</param> /// <param name="segment">The variation segment.</param> /// <param name="fallback">Optional fallback strategy.</param> /// <param name="defaultValue">The default value.</param> /// <returns>The value of the content's property identified by the alias, converted to the specified type.</returns> /// <remarks> /// <para> /// The value comes from <c>IPublishedProperty</c> field <c>Value</c> ie it is suitable for use when rendering /// content. /// </para> /// <para> /// If no property with the specified alias exists, or if the property has no value, or if it could not be /// converted, returns <c>default(T)</c>. /// </para> /// <para> /// If eg a numeric property wants to default to 0 when value source is empty, this has to be done in the /// converter. /// </para> /// <para>The alias is case-insensitive.</para> /// </remarks> public static T?Value <T>( this IPublishedElement content, string alias, string?culture = null, string?segment = null, Fallback fallback = default, T?defaultValue = default) => content.Value(PublishedValueFallback, alias, culture, segment, fallback, defaultValue);
/// <summary> /// Gets the value of a content's property identified by its alias. /// </summary> /// <param name="content">The content.</param> /// <param name="alias">The property alias.</param> /// <param name="culture">The variation language.</param> /// <param name="segment">The variation segment.</param> /// <param name="fallback">Optional fallback strategy.</param> /// <param name="defaultValue">The default value.</param> /// <returns>The value of the content's property identified by the alias, if it exists, otherwise a default value.</returns> /// <remarks> /// <para>The value comes from <c>IPublishedProperty</c> field <c>Value</c> ie it is suitable for use when rendering content.</para> /// <para>If no property with the specified alias exists, or if the property has no value, returns <paramref name="defaultValue"/>.</para> /// <para>If eg a numeric property wants to default to 0 when value source is empty, this has to be done in the converter.</para> /// <para>The alias is case-insensitive.</para> /// </remarks> public static object Value( this IPublishedElement content, string alias, string culture = null, string segment = null, Fallback fallback = default, object defaultValue = default) => content.Value(PublishedValueFallback, alias, culture, segment, fallback, defaultValue);
public static IEnumerable <Image> GetImages(this IPublishedElement element, string field, int?width = null, int?height = null, ImageCropMode imageCropMode = ImageCropMode.Crop) { var imageService = (IImageService)DependencyResolver.Current.GetService(typeof(IImageService)); return(element.HasValue(field) ? imageService.GetImages(element.Value <IEnumerable <IPublishedContent> >(field), width, height, imageCropMode) : null); }
/// <summary> /// Native mapper for mapping a media picker property /// </summary> /// <param name="mapper">The mapper</param> /// <param name="contentToMapFrom">Umbraco content item to map from</param> /// <param name="propName">Name of the property to map</param> /// <param name="fallback">Fallback method(s) to use when content not found</param> /// <returns>MediaFile instance</returns> public static object MapMediaFile(IUmbracoMapper mapper, IPublishedElement contentToMapFrom, string propName, Fallback fallback) { // With V8 will get IPublishedContent var media = contentToMapFrom.Value <IPublishedContent>(propName, fallback: fallback); return(media != null?GetMediaFile(media, mapper.AssetsRootUrl) : null); }
private dynamic Resolve(IPublishedElement content, string[] aliases) { var res = content.Properties .Where(s => aliases == null || aliases.Contains(s.PropertyType.Alias, propertyNameComparer)) .ToDictionary( k => k.PropertyType.Alias, v => ResolveProperty(content.Value <dynamic>(v.PropertyType.Alias), v.PropertyType.Alias)); return(res.ToDynamicObject()); }
public CompanyLogoViewModel(IPublishedElement element) { Title = element.Value <string>("title"); var img = element.Value <IPublishedContent>("image"); Image = img; Svg = ""; if (img != null) { IsSvg = Path.GetExtension(img.Url) == ".svg"; var imgAbsolutePath = IOHelper.MapPath(img.Url); if (File.Exists(imgAbsolutePath)) { Svg = File.ReadAllText(imgAbsolutePath); } } Link = element.Value <string>("link"); }
public virtual object GetPropertyValue(IPublishedElement content, string alias, string culture, string segment, Fallback fallback) { // We need to cast to IPublishedContent if that's what we are mapping from, such that the fallback methods are // handled correctly. var publishedContent = content as IPublishedContent; var cultureOrNull = string.IsNullOrEmpty(culture) ? null : culture; return(publishedContent != null ? publishedContent.Value(alias, cultureOrNull, segment, fallback) : content.Value(alias, cultureOrNull, segment, fallback)); }
/// <summary> /// Native mapper for mapping a multiple media picker property /// </summary> /// <param name="mapper">The mapper</param> /// <param name="contentToMapFrom">Umbraco content item to map from</param> /// <param name="propName">Name of the property to map</param> /// <param name="fallback">Fallback method(s) to use when content not found</param> /// <returns>MediaFile instance</returns> public static object MapMediaFileCollection(IUmbracoMapper mapper, IPublishedElement contentToMapFrom, string propName, Fallback fallback) { // With V8 will get IPublishedContent var mediaCollection = contentToMapFrom.Value <IEnumerable <IPublishedContent> >(propName, fallback: fallback); if (mediaCollection == null) { // Also check for single IPublishedContent (which could get if multiple media disabled) var media = contentToMapFrom.Value <IPublishedContent>(propName, fallback: fallback); if (media != null) { mediaCollection = new List <IPublishedContent> { media }; } } return(mediaCollection != null?GetMediaFileCollection(mediaCollection, mapper.AssetsRootUrl) : null); }
public static IEnumerable <T> GetValueAsViewModels <T>(this IPublishedElement content, string propAlias, string language = "") { var items = content.Value <IEnumerable <IPublishedContent> >(propAlias, culture: string.IsNullOrEmpty(language) ? null : language, fallback: Fallback.ToLanguage); if (items != null && items.Any()) { return(items.Select(c => (T)Activator.CreateInstance(typeof(T), c))); } return(Enumerable.Empty <T>()); }
// tries to get a value, falling back onto other languages private bool TryGetValueWithLanguageFallback <T>(IPublishedElement content, string alias, string culture, string segment, out T value, bool includeFallbackLanguage) { value = default; if (culture.IsNullOrWhiteSpace()) { return(false); } var visited = new HashSet <int>(); var language = _localizationService.GetLanguageByIsoCode(culture); if (language == null) { return(false); } while (true) { if (language.FallbackLanguageId == null) { return(false); } var language2Id = language.FallbackLanguageId.Value; if (visited.Contains(language2Id)) { return(false); } visited.Add(language2Id); var language2 = _localizationService.GetLanguageById(language2Id); if (language2 == null) { return(false); } var culture2 = language2.IsoCode; if (content.HasValue(alias, culture2, segment)) { value = content.Value <T>(alias, culture2, segment); if (includeFallbackLanguage && culture2 != culture) { value = GetMarkUpForFallbackLanguage(culture2, value); } return(true); } language = language2; } }
public static T GetValueAsViewModel <T, U>(this IPublishedElement content, string propAlias, string language = "") where T : class where U : IPublishedElement { var element = content.Value <IEnumerable <IPublishedElement> >(propAlias, culture: string.IsNullOrEmpty(language) ? null : language, fallback: Fallback.ToLanguage).FirstOrDefault(); if (element != null) { return((T)Activator.CreateInstance(typeof(T), element)); } return(null); }
// tries to get a value, falling back onto other languages private bool TryGetValueWithLanguageFallback <T>(IPublishedElement content, string alias, string?culture, string?segment, out T?value) { value = default; if (culture.IsNullOrWhiteSpace()) { return(false); } var visited = new HashSet <int>(); ILanguage?language = culture is not null?_localizationService?.GetLanguageByIsoCode(culture) : null; if (language == null) { return(false); } while (true) { if (language.FallbackLanguageId == null) { return(false); } var language2Id = language.FallbackLanguageId.Value; if (visited.Contains(language2Id)) { return(false); } visited.Add(language2Id); ILanguage?language2 = _localizationService?.GetLanguageById(language2Id); if (language2 == null) { return(false); } var culture2 = language2.IsoCode; if (content.HasValue(alias, culture2, segment)) { value = content.Value <T>(this, alias, culture2, segment); return(true); } language = language2; } }
/// <summary> /// Gets the list of personalisation group content items associated with the current content item /// </summary> /// <param name="content">Instance of IPublished content</param> /// <returns>List of personalisation group content items</returns> public IList <IPublishedContent> GetPickedGroups(IPublishedElement content) { var propertyAlias = _config.GroupPickerAlias; if (content.HasProperty(propertyAlias)) { var rawValue = content.Value(propertyAlias); switch (rawValue) { case IEnumerable <IPublishedContent> list: return(list.ToList()); case IPublishedContent group: return(new List <IPublishedContent> { group }); } } return(new List <IPublishedContent>()); }
public PictureLink(IPublishedElement content) : base(content) { Link = content.Value <Umbraco.Web.Models.Link>(DocumentTypes.PictureLink.Fields.Link); }
/// <inheritdoc /> public override object ConvertIntermediateToObject(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview) { IPublishedElement element = (IPublishedElement)base.ConvertIntermediateToObject(owner, propertyType, referenceCacheLevel, inter, preview); return(element == null || (element.HasValue("uNestingHide") && element.Value <bool>("uNestingHide")) ? null : element); }
public FooterContactArea(IPublishedElement content) : base(content) { Headline = content.HasValue(DocumentTypes.FooterContact.Headline) ? content.Value <string>(DocumentTypes.FooterContact.Headline) : string.Empty; AddressBlock = content.HasValue(DocumentTypes.FooterContact.AddressBlock) ? content.Value <string>(DocumentTypes.FooterContact.AddressBlock) : string.Empty; }
public void SimpleConverter3Test() { var register = new ServiceCollection(); var composition = new UmbracoBuilder(register, Mock.Of <IConfiguration>(), TestHelper.GetMockedTypeLoader()); composition.WithCollectionBuilder <PropertyValueConverterCollectionBuilder>() .Append <SimpleConverter3A>() .Append <SimpleConverter3B>(); IPublishedModelFactory factory = new PublishedModelFactory( new[] { typeof(PublishedSnapshotTestObjects.TestElementModel1), typeof(PublishedSnapshotTestObjects.TestElementModel2), typeof(PublishedSnapshotTestObjects.TestContentModel1), typeof(PublishedSnapshotTestObjects.TestContentModel2) }, Mock.Of <IPublishedValueFallback>()); register.AddTransient(f => factory); var cacheMock = new Mock <IPublishedContentCache>(); var cacheContent = new Dictionary <int, IPublishedContent>(); cacheMock.Setup(x => x.GetById(It.IsAny <int>())).Returns <int>(id => cacheContent.TryGetValue(id, out IPublishedContent content) ? content : null); var publishedSnapshotMock = new Mock <IPublishedSnapshot>(); publishedSnapshotMock.Setup(x => x.Content).Returns(cacheMock.Object); var publishedSnapshotAccessorMock = new Mock <IPublishedSnapshotAccessor>(); var localPublishedSnapshot = publishedSnapshotMock.Object; publishedSnapshotAccessorMock.Setup(x => x.TryGetPublishedSnapshot(out localPublishedSnapshot)).Returns(true); register.AddTransient(f => publishedSnapshotAccessorMock.Object); IServiceProvider registerFactory = composition.CreateServiceProvider(); PropertyValueConverterCollection converters = registerFactory.GetRequiredService <PropertyValueConverterCollection>(); var serializer = new ConfigurationEditorJsonSerializer(); var dataTypeServiceMock = new Mock <IDataTypeService>(); var dataType1 = new DataType( new VoidEditor( Mock.Of <IDataValueEditorFactory>()), serializer) { Id = 1 }; var dataType2 = new DataType( new VoidEditor( "2", Mock.Of <IDataValueEditorFactory>()), serializer) { Id = 2 }; dataTypeServiceMock.Setup(x => x.GetAll()).Returns(new[] { dataType1, dataType2 }); var contentTypeFactory = new PublishedContentTypeFactory(factory, converters, dataTypeServiceMock.Object); IEnumerable <IPublishedPropertyType> CreatePropertyTypes(IPublishedContentType contentType, int i) { yield return(contentTypeFactory.CreatePropertyType(contentType, "prop" + i, i)); } IPublishedContentType elementType1 = contentTypeFactory.CreateContentType(Guid.NewGuid(), 1000, "element1", t => CreatePropertyTypes(t, 1)); IPublishedContentType elementType2 = contentTypeFactory.CreateContentType(Guid.NewGuid(), 1001, "element2", t => CreatePropertyTypes(t, 2)); IPublishedContentType contentType1 = contentTypeFactory.CreateContentType(Guid.NewGuid(), 1002, "content1", t => CreatePropertyTypes(t, 1)); IPublishedContentType contentType2 = contentTypeFactory.CreateContentType(Guid.NewGuid(), 1003, "content2", t => CreatePropertyTypes(t, 2)); var element1 = new PublishedElement( elementType1, Guid.NewGuid(), new Dictionary <string, object> { { "prop1", "val1" } }, false); var element2 = new PublishedElement( elementType2, Guid.NewGuid(), new Dictionary <string, object> { { "prop2", "1003" } }, false); var cnt1 = new InternalPublishedContent(contentType1) { Id = 1003, Properties = new[] { new InternalPublishedProperty { Alias = "prop1", SolidHasValue = true, SolidValue = "val1" } } }; var cnt2 = new InternalPublishedContent(contentType1) { Id = 1004, Properties = new[] { new InternalPublishedProperty { Alias = "prop2", SolidHasValue = true, SolidValue = "1003" } } }; IPublishedModelFactory publishedModelFactory = registerFactory.GetRequiredService <IPublishedModelFactory>(); cacheContent[cnt1.Id] = cnt1.CreateModel(publishedModelFactory); cacheContent[cnt2.Id] = cnt2.CreateModel(publishedModelFactory); // can get the actual property Clr type // ie ModelType gets properly mapped by IPublishedContentModelFactory // must test ModelClrType with special equals 'cos they are not ref-equals Assert.IsTrue(ModelType.Equals( typeof(IEnumerable <>).MakeGenericType(ModelType.For("content1")), contentType2.GetPropertyType("prop2").ModelClrType)); Assert.AreEqual( typeof(IEnumerable <PublishedSnapshotTestObjects.TestContentModel1>), contentType2.GetPropertyType("prop2").ClrType); // can create a model for an element IPublishedElement model1 = factory.CreateModel(element1); Assert.IsInstanceOf <PublishedSnapshotTestObjects.TestElementModel1>(model1); Assert.AreEqual("val1", ((PublishedSnapshotTestObjects.TestElementModel1)model1).Prop1); // can create a model for a published content IPublishedElement model2 = factory.CreateModel(element2); Assert.IsInstanceOf <PublishedSnapshotTestObjects.TestElementModel2>(model2); var mmodel2 = (PublishedSnapshotTestObjects.TestElementModel2)model2; // and get direct property Assert.IsInstanceOf <PublishedSnapshotTestObjects.TestContentModel1[]>( model2.Value(Mock.Of <IPublishedValueFallback>(), "prop2")); Assert.AreEqual( 1, ((PublishedSnapshotTestObjects.TestContentModel1[])model2.Value(Mock.Of <IPublishedValueFallback>(), "prop2")).Length); // and get model property Assert.IsInstanceOf <IEnumerable <PublishedSnapshotTestObjects.TestContentModel1> >(mmodel2.Prop2); Assert.IsInstanceOf <PublishedSnapshotTestObjects.TestContentModel1[]>(mmodel2.Prop2); PublishedSnapshotTestObjects.TestContentModel1 mmodel1 = mmodel2.Prop2.First(); // and we get what we want Assert.AreSame(cacheContent[mmodel1.Id], mmodel1); }
/// <summary> /// Gets a value indicating whether the content is visible. /// </summary> /// <param name="content">The content.</param> /// <returns>A value indicating whether the content is visible.</returns> /// <remarks>A content is not visible if it has an umbracoNaviHide property with a value of "1". Otherwise, /// the content is visible.</remarks> public static bool IsVisible(this IPublishedElement content) { // rely on the property converter - will return default bool value, ie false, if property // is not defined, or has no value, else will return its value. return(content.Value <bool>(Constants.Conventions.Content.NaviHide) == false); }
public virtual object GetPropertyValue(IPublishedElement content, string alias, string culture, string segment, Fallback fallback) { return(content.Value(alias, string.IsNullOrEmpty(culture) ? null : culture, segment, fallback)); }
public PredefinedAmount(IPublishedElement content) { Currency = content.Value <string>("currency"); Amounts = content.Value <string[]>("amounts"); }
/// <summary> /// Returns value of the property with given <paramref name="propertyName"/> from the <paramref name="source"/>. /// </summary> /// <remarks> /// This method is exactly the same as Umbraco's own <see cref="Umbraco.Web.PublishedElementExtensions.Value{T}(IPublishedElement,string,string,string,Fallback,T)"/>, /// except this one will deduce property name from the caller's context, if name is omitted. /// </remarks> /// <typeparam name="T">Expected type of the property value.</typeparam> /// <param name="source">The source.</param> /// <param name="propertyName">Property name.</param> /// <returns>Value of the property with given <paramref name="propertyName"/>.</returns> public static T GetPropertyValue <T>(this IPublishedElement source, [CallerMemberName] string propertyName = null) => source.Value <T>(propertyName);
/// <summary> /// Returns value of the property with given <paramref name="propertyName"/> from the <paramref name="source"/>, /// or creates default value by using provided <paramref name="defaultValueFactory"/> if property is not found or value is not assigned to it. /// </summary> /// <typeparam name="T">Expected type of the property value.</typeparam> /// <param name="source">The source.</param> /// <param name="defaultValueFactory">Default value factory that will be used if property or its value are not found.</param> /// <param name="propertyName">Property name.</param> /// <returns>Value of the property with given <paramref name="propertyName"/> or value returned by <paramref name="defaultValueFactory"/> if property or its value are not found.</returns> public static T GetPropertyWithDefaultValue <T>(this IPublishedElement source, Func <T> defaultValueFactory, [CallerMemberName] string propertyName = null) => source.HasValue(propertyName) ? source.Value <T>(propertyName) : defaultValueFactory();