public override object ConvertIntermediateToObject(
            IPublishedElement owner,
            IPublishedPropertyType propertyType,
            PropertyCacheLevel referenceCacheLevel,
            object inter,
            bool preview)
        {
            var md = (string)inter;

            return(new HtmlString((inter == null) ? string.Empty : Markdown.ToHtml(md, MarkdownPipeline)));
        }
示例#2
0
        public object ConvertIntermediateToObject(
            IPublishedElement owner,
            IPublishedPropertyType propertyType,
            PropertyCacheLevel referenceCacheLevel,
            object inter,
            bool preview)
        {
            var publishedSnapshot = _publishedSnapshotAccessor.GetRequiredPublishedSnapshot();

            return(publishedSnapshot.Content.GetById((int)inter));
        }
        /// <summary>
        /// Converts the intermediate value into the object value.
        /// </summary>
        /// <param name="owner">The published element owning the property.</param>
        /// <param name="referenceCacheLevel">The reference cache level.</param>
        /// <param name="inter">The intermediate value.</param>
        /// <param name="preview">A value indicating whether content should be considered draft.</param>
        /// <returns>The object value.</returns>
        public object ConvertInterToObject(IPublishedElement owner, PropertyCacheLevel referenceCacheLevel, object inter, bool preview)
        {
            if (!_initialized)
            {
                Initialize();
            }

            // use the converter if any, else just return the inter value
            return(_converter != null
                ? _converter.ConvertIntermediateToObject(owner, this, referenceCacheLevel, inter, preview)
                : inter);
        }
 public object ConvertIntermediateToObject(IPublishedElement owner, IPublishedPropertyType propertyType,
                                           PropertyCacheLevel referenceCacheLevel, object inter, bool preview)
 {
     if (inter == null)
     {
         return("");
     }
     else
     {
         return((string)inter);
     }
 }
        public void CacheLevelTest(PropertyCacheLevel cacheLevel, int interConverts)
        {
            var converter = new CacheConverter1(cacheLevel);

            var converters = new PropertyValueConverterCollection(new IPropertyValueConverter[]
            {
                converter,
            });

            var dataTypeService = new TestObjects.TestDataTypeService(
                new DataType(new VoidEditor(Mock.Of <ILogger>()))
            {
                Id = 1
            });

            var publishedContentTypeFactory = new PublishedContentTypeFactory(Mock.Of <IPublishedModelFactory>(), converters, dataTypeService);

            IEnumerable <IPublishedPropertyType> CreatePropertyTypes(IPublishedContentType contentType)
            {
                yield return(publishedContentTypeFactory.CreatePropertyType(contentType, "prop1", 1));
            }

            var setType1 = publishedContentTypeFactory.CreateContentType(1000, "set1", CreatePropertyTypes);

            // PublishedElementPropertyBase.GetCacheLevels:
            //
            //   if property level is > reference level, or both are None
            //     use None for property & new reference
            //   else
            //     use Content for property, & keep reference
            //
            // PublishedElement creates properties with reference being None
            // if converter specifies None, keep using None
            // anything else is not > None, use Content
            //
            // for standalone elements, it's only None or Content

            var set1 = new PublishedElement(setType1, Guid.NewGuid(), new Dictionary <string, object> {
                { "prop1", "1234" }
            }, false);

            Assert.AreEqual(1234, set1.Value("prop1"));
            Assert.AreEqual(1, converter.SourceConverts);
            Assert.AreEqual(1, converter.InterConverts);

            // source is always converted once and cached per content
            // inter conversion depends on the specified cache level

            Assert.AreEqual(1234, set1.Value("prop1"));
            Assert.AreEqual(1, converter.SourceConverts);
            Assert.AreEqual(interConverts, converter.InterConverts);
        }
示例#6
0
            public override object ConvertIntermediateToObject(
                IPublishedElement owner,
                IPublishedPropertyType propertyType,
                PropertyCacheLevel referenceCacheLevel,
                object inter,
                bool preview)
            {
                var publishedSnapshot = _publishedSnapshotAccessor.GetRequiredPublishedSnapshot();

                return(((int[])inter).Select(x =>
                                             (PublishedSnapshotTestObjects.TestContentModel1)publishedSnapshot.Content
                                             .GetById(x)).ToArray());
            }
    // default ConvertSourceToObject just returns source ie a DateTime value
    public override object?ConvertIntermediateToXPath(
        IPublishedElement owner,
        IPublishedPropertyType propertyType,
        PropertyCacheLevel referenceCacheLevel,
        object?inter,
        bool preview)
    {
        // source should come from ConvertSource and be a DateTime already
        if (inter is null)
        {
            return(null);
        }

        return(XmlConvert.ToString((DateTime)inter, XmlDateTimeSerializationMode.Unspecified));
    }
示例#8
0
        private CacheValues GetCacheValues(PropertyCacheLevel cacheLevel)
        {
            CacheValues        cacheValues;
            IPublishedSnapshot publishedSnapshot;
            IAppCache          cache;

            switch (cacheLevel)
            {
            case PropertyCacheLevel.None:
                // never cache anything
                cacheValues = new CacheValues();
                break;

            case PropertyCacheLevel.Element:
                // cache within the property object itself, ie within the content object
                cacheValues = _cacheValues ?? (_cacheValues = new CacheValues());
                break;

            case PropertyCacheLevel.Elements:
                // cache within the elements cache, unless previewing, then use the snapshot or
                // elements cache (if we don't want to pollute the elements cache with short-lived
                // data) depending on settings
                // for members, always cache in the snapshot cache - never pollute elements cache
                publishedSnapshot = _publishedSnapshotAccessor.GetRequiredPublishedSnapshot();
                cache             = publishedSnapshot == null
                        ? null
                        : ((_isPreviewing == false || PublishedSnapshotService.FullCacheWhenPreviewing) && (_isMember == false)
                            ? publishedSnapshot.ElementsCache
                            : publishedSnapshot.SnapshotCache);
                cacheValues = GetCacheValues(cache);
                break;

            case PropertyCacheLevel.Snapshot:
                // cache within the snapshot cache
                publishedSnapshot = _publishedSnapshotAccessor.GetRequiredPublishedSnapshot();
                cache             = publishedSnapshot?.SnapshotCache;
                cacheValues       = GetCacheValues(cache);
                break;

            default:
                throw new InvalidOperationException("Invalid cache level.");
            }

            return(cacheValues);
        }
        private IEnumerable <SimpleTreeItem> convertToItem(List <JObject> objects, PropertyCacheLevel referenceCacheLevel, bool preview)
        {
            if (!objects.Any())
            {
                return(Enumerable.Empty <SimpleTreeItem>());
            }

            var items = new List <SimpleTreeItem>();

            foreach (var sourceObject in objects)
            {
                var elementObject = sourceObject["properties"]?.ToObject <JObject>() ?? new JObject();

                elementObject["ncContentTypeAlias"] = sourceObject["contentTypeAlias"]?.ToObject <string>() ?? "menuNode";
                elementObject["name"] = sourceObject["name"]?.ToObject <string>();
                elementObject["key"]  = sourceObject["key"]?.ToObject <string>() ?? Guid.NewGuid().ToString();

                var element = ConvertToElement(elementObject, referenceCacheLevel, preview);

                if (element == null)
                {
                    continue;
                }

                var item = new SimpleTreeItem()
                {
                    Item = element,
                    Name = sourceObject["name"]?.ToObject <string>()
                };

                var children = sourceObject["items"]?.ToObject <List <JObject> >();

                if (children != null && children.Any())
                {
                    item.Items = convertToItem(children, referenceCacheLevel, preview);
                }

                items.Add(item);
            }

            return(items);
        }
示例#10
0
        public override object GetXPathValue(string culture = null, string segment = null)
        {
            _content.VariationContextAccessor.ContextualizeVariation(_variations, _content.Id, ref culture, ref segment);

            lock (_locko)
            {
                var cacheValues = GetCacheValues(PropertyType.CacheLevel).For(culture, segment);

                // initial reference cache level always is .Content
                const PropertyCacheLevel initialCacheLevel = PropertyCacheLevel.Element;

                if (cacheValues.XPathInitialized)
                {
                    return(cacheValues.XPathValue);
                }
                cacheValues.XPathValue       = PropertyType.ConvertInterToXPath(_content, initialCacheLevel, GetInterValue(culture, segment), _isPreviewing);
                cacheValues.XPathInitialized = true;
                return(cacheValues.XPathValue);
            }
        }
        private void InitializeConverters()
        {
            var converters = PropertyValueConvertersResolver.Current.Converters.ToArray();

            // todo: remove Union() once we drop IPropertyEditorValueConverter support.
            _converter = null;
            foreach (var converter in converters.Union(GetCompatConverters()).Where(x => x.IsConverter(this)))
            {
                if (_converter == null)
                {
                    _converter = converter;
                }
                else
                {
                    throw new InvalidOperationException(string.Format("More than one converter for property type {0}.{1}",
                                                                      ContentType.Alias, PropertyTypeAlias));
                }
            }

            // get the cache levels, quietely fixing the inconsistencies (no need to throw, really)
            _sourceCacheLevel = GetCacheLevel(_converter, PropertyCacheValue.Source);
            _objectCacheLevel = GetCacheLevel(_converter, PropertyCacheValue.Object);
            _objectCacheLevel = GetCacheLevel(_converter, PropertyCacheValue.XPath);
            if (_objectCacheLevel < _sourceCacheLevel)
            {
                _objectCacheLevel = _sourceCacheLevel;
            }
            if (_xpathCacheLevel < _sourceCacheLevel)
            {
                _xpathCacheLevel = _sourceCacheLevel;
            }

            if (_converter != null)
            {
                var attr = _converter.GetType().GetCustomAttribute <PropertyValueTypeAttribute>(false);
                if (attr != null)
                {
                    _clrType = attr.Type;
                }
            }
        }
        public override object ConvertIntermediateToObject(IPublishedElement owner, IPublishedPropertyType propertyType,
                                                           PropertyCacheLevel referenceCacheLevel, object inter, bool preview)
        {
            var maxNumber = GetMaxNumber(propertyType.DataType.Configuration);

            if (inter == null)
            {
                return(maxNumber == 1 ? null : Enumerable.Empty <FaIcon>());
            }
            var faIcons = JsonConvert.DeserializeObject <IEnumerable <FaIcon> >(inter.ToString()).ToList();

            if (maxNumber == 1)
            {
                return(faIcons.FirstOrDefault());
            }
            if (maxNumber > 0)
            {
                return(faIcons.Take(maxNumber));
            }
            return(faIcons);
        }
示例#13
0
        // validates the cache level
        private static void ValidateCacheLevel(PropertyCacheLevel cacheLevel, bool validateUnknown)
        {
            switch (cacheLevel)
            {
            case PropertyCacheLevel.Element:
            case PropertyCacheLevel.Elements:
            case PropertyCacheLevel.Snapshot:
            case PropertyCacheLevel.None:
                break;

            case PropertyCacheLevel.Unknown:
                if (!validateUnknown)
                {
                    goto default;
                }
                break;

            default:
                throw new Exception($"Invalid cache level \"{cacheLevel}\".");
            }
        }
示例#14
0
    public override object?ConvertIntermediateToObject(
        IPublishedElement owner,
        IPublishedPropertyType propertyType,
        PropertyCacheLevel cacheLevel,
        object?source,
        bool preview)
    {
        var isMultiple = IsMultipleDataType(propertyType.DataType);

        var udis       = (Udi[]?)source;
        var mediaItems = new List <IPublishedContent>();

        if (source == null)
        {
            return(isMultiple ? mediaItems : null);
        }

        if (udis?.Any() ?? false)
        {
            IPublishedSnapshot publishedSnapshot = _publishedSnapshotAccessor.GetRequiredPublishedSnapshot();
            foreach (Udi udi in udis)
            {
                if (udi is not GuidUdi guidUdi)
                {
                    continue;
                }

                IPublishedContent?item = publishedSnapshot?.Media?.GetById(guidUdi.Guid);
                if (item != null)
                {
                    mediaItems.Add(item);
                }
            }

            return(isMultiple ? mediaItems : FirstOrDefault(mediaItems));
        }

        return(source);
    }
示例#15
0
        public override object ConvertIntermediateToObject(IPublishedElement owner, IPublishedPropertyType propertyType,
                                                           PropertyCacheLevel referenceCacheLevel, object inter, bool preview)
        {
            var allowMultiple = GetAllowMultiple(propertyType.DataType.Configuration);

            if (inter == null)
            {
                return(allowMultiple ? new string[] { } : null);
            }
            var values = JsonConvert.DeserializeObject <string[]>(inter.ToString());

            if (allowMultiple)
            {
                return(values);
            }
            if (!allowMultiple)
            {
                return(values.FirstOrDefault());
            }

            return(values);
        }
        /// <inheritdoc />
        public override object ConvertIntermediateToObject(
            IPublishedElement owner,
            IPublishedPropertyType propertyType,
            PropertyCacheLevel referenceCacheLevel,
            object inter,
            bool preview)
        {
            var allowMultiple = propertyType.DataType.ConfigurationAs <OEmbedPickerConfiguration>().AllowMultiple;

            if (string.IsNullOrWhiteSpace(inter?.ToString()))
            {
                return(allowMultiple ? Enumerable.Empty <OEmbedItem>() : null);
            }

            var items = JsonConvert.DeserializeObject <List <OEmbedItem> >(inter.ToString() ?? string.Empty);

            if (allowMultiple)
            {
                return(items);
            }

            return(items?.FirstOrDefault());
        }
        public override object ConvertIntermediateToObject(IPublishedElement owner, PublishedPropertyType propertyType,
                                                           PropertyCacheLevel cacheLevel, object source, bool preview)
        {
            var isMultiple   = IsMultipleDataType(propertyType.DataType);
            var isOnlyImages = IsOnlyImagesDataType(propertyType.DataType);

            var udis       = (Udi[])source;
            var mediaItems = isOnlyImages
                ? _publishedModelFactory.CreateModelList(ImageTypeAlias)
                : new List <IPublishedContent>();

            if (source == null)
            {
                return(isMultiple ? mediaItems : null);
            }

            if (udis.Any())
            {
                foreach (var udi in udis)
                {
                    var guidUdi = udi as GuidUdi;
                    if (guidUdi == null)
                    {
                        continue;
                    }
                    var item = _publishedSnapshotAccessor.PublishedSnapshot.Media.GetById(guidUdi.Guid);
                    if (item != null)
                    {
                        mediaItems.Add(item);
                    }
                }

                return(isMultiple ? mediaItems : FirstOrDefault(mediaItems));
            }

            return(source);
        }
        /// <summary>
        /// Converts the intermediate value into the XPath value.
        /// </summary>
        /// <param name="owner">The published element owning the property.</param>
        /// <param name="referenceCacheLevel">The reference cache level.</param>
        /// <param name="inter">The intermediate value.</param>
        /// <param name="preview">A value indicating whether content should be considered draft.</param>
        /// <returns>The XPath value.</returns>
        /// <remarks>
        /// <para>The XPath value can be either a string or an XPathNavigator.</para>
        /// </remarks>
        public object ConvertInterToXPath(IPublishedElement owner, PropertyCacheLevel referenceCacheLevel, object inter, bool preview)
        {
            if (!_initialized)
            {
                Initialize();
            }

            // use the converter if any
            if (_converter != null)
            {
                return(_converter.ConvertIntermediateToXPath(owner, this, referenceCacheLevel, inter, preview));
            }

            // else just return the inter value as a string or an XPathNavigator
            if (inter == null)
            {
                return(null);
            }
            if (inter is XElement xElement)
            {
                return(xElement.CreateNavigator());
            }
            return(inter.ToString().Trim());
        }
        public override object ConvertIntermediateToObject(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview)
        {
            var jsonObject = JsonConvert.DeserializeObject <JObject>((string)inter);

            if (jsonObject == null)
            {
                return(null);
            }

            jsonObject["ncContentTypeAlias"] = jsonObject["elementType"]?.ToObject <string>();

            return(_nestedContentSingleValueConverter.ConvertIntermediateToObject(owner, propertyType, referenceCacheLevel, "[" + jsonObject?.ToString() + "]", preview) as IPublishedElement);
        }
示例#20
0
        public override object ConvertIntermediateToObject(IPublishedElement owner, PublishedPropertyType propertyType, PropertyCacheLevel cacheLevel, object source, bool preview)
        {
            if (source == null)
            {
                return(null);
            }

            if (IsRangeDataType(propertyType.DataType.Id))
            {
                var rangeRawValues = source.ToString().Split(',');
                var minimumAttempt = rangeRawValues[0].TryConvertTo <decimal>();
                var maximumAttempt = rangeRawValues[1].TryConvertTo <decimal>();

                if (minimumAttempt.Success && maximumAttempt.Success)
                {
                    return(new Range <decimal> {
                        Maximum = maximumAttempt.Result, Minimum = minimumAttempt.Result
                    });
                }
            }

            var valueAttempt = source.ToString().TryConvertTo <decimal>();

            if (valueAttempt.Success)
            {
                return(valueAttempt.Result);
            }

            // Something failed in the conversion of the strings to decimals
            return(null);
        }
 public override object ConvertIntermediateToXPath(IPublishedElement owner, PublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview)
 {
     // source should come from ConvertSource and be a string (or null) already
     return(inter);
 }
        public object ConvertIntermediateToXPath(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview)
        {
            if (inter == null)
            {
                return(null);
            }

            return(inter.ToString());
        }
 public object ConvertIntermediateToObject(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview)
 {
     return(inter);
 }
示例#24
0
        public override object ConvertIntermediateToObject(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview)
        {
            if (inter != null)
            {
                return(JsonConvert.DeserializeObject <GmapsModel>(inter.ToString()));
            }

            return(null);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="PropertyValueCacheAttribute"/> class with a cacheable value and a cache level.
 /// </summary>
 /// <param name="value">The cacheable value.</param>
 /// <param name="level">The cache level.</param>
 public PropertyValueCacheAttribute(PropertyCacheValue value, PropertyCacheLevel level)
 {
     Value = value;
     Level = level;
 }
        /// <inheritdoc />
        public override object ConvertIntermediateToObject(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview)
        {
            // NOTE: The intermediate object is just a json string, we don't actually convert from source -> intermediate since source is always just a json string

            using (_proflog.DebugDuration <BlockListPropertyValueConverter>($"ConvertPropertyToBlockList ({propertyType.DataType.Id})"))
            {
                var configuration            = propertyType.DataType.ConfigurationAs <BlockListConfiguration>();
                var blockConfigMap           = configuration.Blocks.ToDictionary(x => x.ContentElementTypeKey);
                var validSettingElementTypes = blockConfigMap.Values.Select(x => x.SettingsElementTypeKey).Where(x => x.HasValue).Distinct().ToList();

                var contentPublishedElements  = new Dictionary <Guid, IPublishedElement>();
                var settingsPublishedElements = new Dictionary <Guid, IPublishedElement>();

                var layout = new List <BlockListItem>();

                var value = (string)inter;
                if (string.IsNullOrWhiteSpace(value))
                {
                    return(BlockListModel.Empty);
                }

                var converted = _blockListEditorDataConverter.Deserialize(value);
                if (converted.BlockValue.ContentData.Count == 0)
                {
                    return(BlockListModel.Empty);
                }

                var blockListLayout = converted.Layout.ToObject <IEnumerable <BlockListLayoutItem> >();

                // convert the content data
                foreach (var data in converted.BlockValue.ContentData)
                {
                    if (!blockConfigMap.ContainsKey(data.ContentTypeKey))
                    {
                        continue;
                    }

                    var element = _blockConverter.ConvertToElement(data, referenceCacheLevel, preview);
                    if (element == null)
                    {
                        continue;
                    }
                    contentPublishedElements[element.Key] = element;
                }
                // convert the settings data
                foreach (var data in converted.BlockValue.SettingsData)
                {
                    if (!validSettingElementTypes.Contains(data.ContentTypeKey))
                    {
                        continue;
                    }

                    var element = _blockConverter.ConvertToElement(data, referenceCacheLevel, preview);
                    if (element == null)
                    {
                        continue;
                    }
                    settingsPublishedElements[element.Key] = element;
                }

                // if there's no elements just return since if there's no data it doesn't matter what is stored in layout
                if (contentPublishedElements.Count == 0)
                {
                    return(BlockListModel.Empty);
                }

                foreach (var layoutItem in blockListLayout)
                {
                    // get the content reference
                    var contentGuidUdi = (GuidUdi)layoutItem.ContentUdi;
                    if (!contentPublishedElements.TryGetValue(contentGuidUdi.Guid, out var contentData))
                    {
                        continue;
                    }

                    // get the setting reference
                    IPublishedElement settingsData = null;
                    var settingGuidUdi             = layoutItem.SettingsUdi != null ? (GuidUdi)layoutItem.SettingsUdi : null;
                    if (settingGuidUdi != null)
                    {
                        settingsPublishedElements.TryGetValue(settingGuidUdi.Guid, out settingsData);
                    }

                    if (!contentData.ContentType.TryGetKey(out var contentTypeKey))
                    {
                        throw new InvalidOperationException("The content type was not of type " + typeof(IPublishedContentType2));
                    }

                    if (!blockConfigMap.TryGetValue(contentTypeKey, out var blockConfig))
                    {
                        continue;
                    }

                    // this can happen if they have a settings type, save content, remove the settings type, and display the front-end page before saving the content again
                    // we also ensure that the content type's match since maybe the settings type has been changed after this has been persisted.
                    if (settingsData != null)
                    {
                        if (!settingsData.ContentType.TryGetKey(out var settingsElementTypeKey))
                        {
                            throw new InvalidOperationException("The settings element type was not of type " + typeof(IPublishedContentType2));
                        }

                        if (!blockConfig.SettingsElementTypeKey.HasValue || settingsElementTypeKey != blockConfig.SettingsElementTypeKey)
                        {
                            settingsData = null;
                        }
                    }

                    var layoutType = typeof(BlockListItem <,>).MakeGenericType(contentData.GetType(), settingsData?.GetType() ?? typeof(IPublishedElement));
                    var layoutRef  = (BlockListItem)Activator.CreateInstance(layoutType, contentGuidUdi, contentData, settingGuidUdi, settingsData);

                    layout.Add(layoutRef);
                }

                var model = new BlockListModel(layout);
                return(model);
            }
        }
示例#27
0
        public override object ConvertIntermediateToObject(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview)
        {
            TryGetPropertyTypeConfiguration(propertyType, out var hasMultipleValues, out var valueType, out var converter);

            if (inter is string value)
            {
                return(converter != null
                    ? converter(valueType, value)
                    : value);
            }

            if (inter is IEnumerable <string> items)
            {
                if (hasMultipleValues == true)
                {
                    var objects = new List <object>();

                    foreach (var item in items)
                    {
                        var obj = converter != null
                            ? converter(valueType, item)
                            : item;

                        if (obj != null)
                        {
                            objects.Add(obj);
                        }
                    }

                    var result = Array.CreateInstance(valueType, objects.Count);
                    for (var i = 0; i < objects.Count; i++)
                    {
                        var attempt = objects[i].TryConvertTo(valueType);
                        if (attempt.Success == true)
                        {
                            result.SetValue(attempt.Result, i);
                        }
                        else
                        {
                            // NOTE: At this point `TryConvertTo` can't convert to the `valueType`.
                            // This may be a case where the `valueType` is an interface.
                            // We can attempt to cast it directly, as a last resort.
                            if (valueType.IsInstanceOfType(objects[i]) == true)
                            {
                                result.SetValue(objects[i], i);
                            }
                        }
                    }

                    return(result);
                }
                else
                {
                    // NOTE: When the `inter` is enumerable, but `hasMultipleValues` is false, take the first item value.
                    foreach (var item in items)
                    {
                        return(converter != null
                            ? converter(valueType, item)
                            : item);
                    }
                }

                // NOTE: This is the last resort. Comma-separated string.
                return(string.Join(",", items));
            }

            return(base.ConvertIntermediateToObject(owner, propertyType, referenceCacheLevel, inter, preview));
        }
示例#28
0
    public override object ConvertIntermediateToObject(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object?inter, bool preview) =>

    // source should come from ConvertSource and be a string (or null) already
    new HtmlEncodedString(inter == null ? string.Empty : (string)inter);
        private void InitializeConverters()
        {
            var converters = PropertyValueConvertersResolver.Current.Converters.ToArray();

            // todo: remove Union() once we drop IPropertyEditorValueConverter support.
            _converter = null;
            foreach (var converter in converters.Union(GetCompatConverters()).Where(x => x.IsConverter(this)))
            {
                if (_converter == null)
                {
                    _converter = converter;
                }
                else
                {
                    throw new InvalidOperationException(string.Format("More than one converter for property type {0}.{1}",
                        ContentType.Alias, PropertyTypeAlias));
                }
            }

            // get the cache levels, quietely fixing the inconsistencies (no need to throw, really)
            _sourceCacheLevel = GetCacheLevel(_converter, PropertyCacheValue.Source);
            _objectCacheLevel = GetCacheLevel(_converter, PropertyCacheValue.Object);
            _objectCacheLevel = GetCacheLevel(_converter, PropertyCacheValue.XPath);
            if (_objectCacheLevel < _sourceCacheLevel) _objectCacheLevel = _sourceCacheLevel;
            if (_xpathCacheLevel < _sourceCacheLevel) _xpathCacheLevel = _sourceCacheLevel;

            if (_converter != null)
            {
                var attr = _converter.GetType().GetCustomAttribute<PropertyValueTypeAttribute>(false);
                if (attr != null)
                    _clrType = attr.Type;
            }
        }
        private void InitializeConverters()
        {
            var converters = PropertyValueConvertersResolver.Current.Converters.ToArray();

            var defaultConverters = converters
                .Where(x => x.GetType().GetCustomAttribute<DefaultPropertyValueConverterAttribute>(false) != null)
                .ToArray();

            _converter = null;
            
            //get all converters for this property type
            // todo: remove Union() once we drop IPropertyEditorValueConverter support.
            var foundConverters = converters.Union(GetCompatConverters()).Where(x => x.IsConverter(this)).ToArray();
            if (foundConverters.Length == 1)
            {
                _converter = foundConverters[0];
            }
            else if (foundConverters.Length > 1)
            {
                //more than one was found, we need to first figure out if one of these is an Umbraco default value type converter
                var nonDefault = foundConverters.Except(defaultConverters).ToArray();
                if (nonDefault.Length > 1)
                {
                    //this is not allowed, there cannot be more than 1 custom converter
                    throw new InvalidOperationException(
                        string.Format("Type '{2}' cannot be an IPropertyValueConverter"
                                      + " for property '{1}' of content type '{0}' because type '{3}' has already been detected as a converter"
                                      + " for that property, and only one converter can exist for a property.",
                                      ContentType.Alias, PropertyTypeAlias,
                                      nonDefault[1].GetType().FullName, nonDefault[0].GetType().FullName));
                }

                //there's only 1 custom converter registered that so use it
                _converter = nonDefault[0];
            }
            
            // get the cache levels, quietely fixing the inconsistencies (no need to throw, really)
            _sourceCacheLevel = GetCacheLevel(_converter, PropertyCacheValue.Source);
            _objectCacheLevel = GetCacheLevel(_converter, PropertyCacheValue.Object);
            _objectCacheLevel = GetCacheLevel(_converter, PropertyCacheValue.XPath);
            if (_objectCacheLevel < _sourceCacheLevel) _objectCacheLevel = _sourceCacheLevel;
            if (_xpathCacheLevel < _sourceCacheLevel) _xpathCacheLevel = _sourceCacheLevel;

            if (_converter != null)
            {
                var attr = _converter.GetType().GetCustomAttribute<PropertyValueTypeAttribute>(false);
                if (attr != null)
                    _clrType = attr.Type;
            }
        }
示例#31
0
        public override object ConvertIntermediateToObject(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview)
        {
            if (inter is IEnumerable <ContentBlock> items)
            {
                var elements = new List <IPublishedElement>();

                foreach (var item in items)
                {
                    if (item == null || item.ElementType.Equals(Guid.Empty))
                    {
                        continue;
                    }

                    // NOTE: [LK:2019-09-03] Why `IPublishedCache` doesn't support Guids or UDIs, I do not know!?
                    // Thought v8 was meant to be "GUID ALL THE THINGS!!1"? ¯\_(ツ)_/¯
                    if (ContentTypeCacheHelper.TryGetAlias(item.ElementType, out var alias, _contentTypeService) == false)
                    {
                        continue;
                    }

                    var contentType = _publishedSnapshotAccessor.PublishedSnapshot.Content.GetContentType(alias);
                    if (contentType == null || contentType.IsElement == false)
                    {
                        continue;
                    }

                    var properties = new List <IPublishedProperty>();

                    foreach (var thing in item.Value)
                    {
                        var propType = contentType.GetPropertyType(thing.Key);
                        if (propType != null)
                        {
                            properties.Add(new DetachedPublishedProperty(propType, owner, thing.Value, preview));
                        }
                    }

                    elements.Add(_publishedModelFactory.CreateModel(new DetachedPublishedElement(item.Key, contentType, properties)));
                }

                return(elements);
            }

            return(base.ConvertIntermediateToObject(owner, propertyType, referenceCacheLevel, inter, preview));
        }
示例#32
0
        public override object ConvertIntermediateToObject(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview)
        {
            var converted = Convert(inter, preview);

            return(new HtmlEncodedString(converted == null ? string.Empty : converted));
        }
示例#33
0
        public override object ConvertIntermediateToXPath(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview)
        {
            var d = new XmlDocument();
            var e = d.CreateElement("values");

            d.AppendChild(e);

            var values = (IEnumerable <string>)inter;

            foreach (var value in values)
            {
                var ee = d.CreateElement("value");
                ee.InnerText = value;
                e.AppendChild(ee);
            }

            return(d.CreateNavigator());
        }