protected IPublishedElement?ConvertToElement(JObject sourceObject, PropertyCacheLevel referenceCacheLevel, bool preview)
    {
        var elementTypeAlias =
            sourceObject[NestedContentPropertyEditor.ContentTypeAliasPropertyKey]?.ToObject <string>();

        if (string.IsNullOrEmpty(elementTypeAlias))
        {
            return(null);
        }

        IPublishedSnapshot publishedSnapshot = _publishedSnapshotAccessor.GetRequiredPublishedSnapshot();

        // Only convert element types - content types will cause an exception when PublishedModelFactory creates the model
        IPublishedContentType?publishedContentType = publishedSnapshot.Content?.GetContentType(elementTypeAlias);

        if (publishedContentType is null || publishedContentType.IsElement == false)
        {
            return(null);
        }

        Dictionary <string, object?>?propertyValues = sourceObject.ToObject <Dictionary <string, object?> >();

        if (propertyValues is null || !propertyValues.TryGetValue("key", out var keyo) ||
            !Guid.TryParse(keyo?.ToString(), out Guid key))
        {
            key = Guid.Empty;
        }

        IPublishedElement element = new PublishedElement(publishedContentType, key, propertyValues, preview, referenceCacheLevel, _publishedSnapshotAccessor);

        element = PublishedModelFactory.CreateModel(element);

        return(element);
    }
        /// <summary>
        /// Setup mocks for IPublishedSnapshotAccessor
        /// </summary>
        private IPublishedSnapshotAccessor GetPublishedSnapshotAccessor()
        {
            IPublishedContentType test1ContentType = Mock.Of <IPublishedContentType>(x =>
                                                                                     x.IsElement == true &&
                                                                                     x.Key == _contentKey1 &&
                                                                                     x.Alias == ContentAlias1);
            IPublishedContentType test2ContentType = Mock.Of <IPublishedContentType>(x =>
                                                                                     x.IsElement == true &&
                                                                                     x.Key == _contentKey2 &&
                                                                                     x.Alias == ContentAlias2);
            IPublishedContentType test3ContentType = Mock.Of <IPublishedContentType>(x =>
                                                                                     x.IsElement == true &&
                                                                                     x.Key == _settingKey1 &&
                                                                                     x.Alias == SettingAlias1);
            IPublishedContentType test4ContentType = Mock.Of <IPublishedContentType>(x =>
                                                                                     x.IsElement == true &&
                                                                                     x.Key == _settingKey2 &&
                                                                                     x.Alias == SettingAlias2);
            var contentCache = new Mock <IPublishedContentCache>();

            contentCache.Setup(x => x.GetContentType(_contentKey1)).Returns(test1ContentType);
            contentCache.Setup(x => x.GetContentType(_contentKey2)).Returns(test2ContentType);
            contentCache.Setup(x => x.GetContentType(_settingKey1)).Returns(test3ContentType);
            contentCache.Setup(x => x.GetContentType(_settingKey2)).Returns(test4ContentType);
            IPublishedSnapshot         publishedSnapshot         = Mock.Of <IPublishedSnapshot>(x => x.Content == contentCache.Object);
            IPublishedSnapshotAccessor publishedSnapshotAccessor = Mock.Of <IPublishedSnapshotAccessor>(x => x.TryGetPublishedSnapshot(out publishedSnapshot));

            return(publishedSnapshotAccessor);
        }
 /// <summary>
 ///     Initializes a new instance of the <see cref="PublishedContentQuery" /> class.
 /// </summary>
 public PublishedContentQuery(IPublishedSnapshot publishedSnapshot,
                              IVariationContextAccessor variationContextAccessor, IExamineManager examineManager)
 {
     _publishedSnapshot        = publishedSnapshot ?? throw new ArgumentNullException(nameof(publishedSnapshot));
     _variationContextAccessor = variationContextAccessor ??
                                 throw new ArgumentNullException(nameof(variationContextAccessor));
     _examineManager = examineManager ?? throw new ArgumentNullException(nameof(examineManager));
 }
    public override object?ConvertIntermediateToObject(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel cacheLevel, object?source, bool preview)
    {
        if (source == null)
        {
            return(null);
        }

        IPublishedContent? member;
        IPublishedSnapshot publishedSnapshot = _publishedSnapshotAccessor.GetRequiredPublishedSnapshot();

        if (source is int id)
        {
            IMember?m = _memberService.GetById(id);
            if (m == null)
            {
                return(null);
            }

            member = publishedSnapshot?.Members?.Get(m);
            if (member != null)
            {
                return(member);
            }
        }
        else
        {
            if (source is not GuidUdi sourceUdi)
            {
                return(null);
            }

            IMember?m = _memberService.GetByKey(sourceUdi.Guid);
            if (m == null)
            {
                return(null);
            }

            member = publishedSnapshot?.Members?.Get(m);

            if (member != null)
            {
                return(member);
            }
        }

        return(source);
    }
Ejemplo n.º 5
0
    public override object?ConvertIntermediateToObject(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object?inter, bool preview)
    {
        var isMultiple = IsMultipleDataType(propertyType.DataType);

        if (string.IsNullOrEmpty(inter?.ToString()))
        {
            // Short-circuit on empty value
            return(isMultiple ? Enumerable.Empty <MediaWithCrops>() : null);
        }

        var mediaItems = new List <MediaWithCrops>();
        IEnumerable <MediaPicker3PropertyEditor.MediaPicker3PropertyValueEditor.MediaWithCropsDto> dtos =
            MediaPicker3PropertyEditor.MediaPicker3PropertyValueEditor.Deserialize(_jsonSerializer, inter);
        MediaPicker3Configuration?configuration     = propertyType.DataType.ConfigurationAs <MediaPicker3Configuration>();
        IPublishedSnapshot        publishedSnapshot = _publishedSnapshotAccessor.GetRequiredPublishedSnapshot();

        foreach (MediaPicker3PropertyEditor.MediaPicker3PropertyValueEditor.MediaWithCropsDto dto in dtos)
        {
            IPublishedContent?mediaItem = publishedSnapshot.Media?.GetById(preview, dto.MediaKey);
            if (mediaItem != null)
            {
                var localCrops = new ImageCropperValue
                {
                    Crops      = dto.Crops,
                    FocalPoint = dto.FocalPoint,
                    Src        = mediaItem.Url(_publishedUrlProvider),
                };

                localCrops.ApplyConfiguration(configuration);

                // TODO: This should be optimized/cached, as calling Activator.CreateInstance is slow
                Type mediaWithCropsType = typeof(MediaWithCrops <>).MakeGenericType(mediaItem.GetType());
                var  mediaWithCrops     = (MediaWithCrops)Activator.CreateInstance(mediaWithCropsType, mediaItem, _publishedValueFallback, localCrops) !;

                mediaItems.Add(mediaWithCrops);

                if (!isMultiple)
                {
                    // Short-circuit on single item
                    break;
                }
            }
        }

        return(isMultiple ? mediaItems : mediaItems.FirstOrDefault());
    }
Ejemplo n.º 6
0
    public IPublishedContent?GetPublishedMember(MemberIdentityUser?user)
    {
        if (user == null)
        {
            return(null);
        }

        IMember?member = _memberService.GetByKey(user.Key);

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

        IPublishedSnapshot publishedSnapshot = _publishedSnapshotAccessor.GetRequiredPublishedSnapshot();

        return(publishedSnapshot.Members?.Get(member));
    }
Ejemplo n.º 7
0
    /// <summary>
    ///     Creates an <see cref="IEnumerable{PublishedSearchResult}" /> containing all content, media or members from the
    ///     <paramref name="snapshot" />.
    /// </summary>
    /// <param name="results">The search results.</param>
    /// <param name="snapshot">The snapshot.</param>
    /// <returns>
    ///     An <see cref="IEnumerable{PublishedSearchResult}" /> containing all content, media or members.
    /// </returns>
    /// <exception cref="ArgumentNullException">snapshot</exception>
    /// <remarks>
    ///     Search results are skipped if it can't be fetched from the respective cache by its integer id.
    /// </remarks>
    public static IEnumerable <PublishedSearchResult> ToPublishedSearchResults(
        this IEnumerable <ISearchResult> results,
        IPublishedSnapshot snapshot)
    {
        if (snapshot == null)
        {
            throw new ArgumentNullException(nameof(snapshot));
        }

        var publishedSearchResults = new List <PublishedSearchResult>();

        foreach (ISearchResult result in results)
        {
            if (int.TryParse(result.Id, NumberStyles.Integer, CultureInfo.InvariantCulture, out var contentId) &&
                result.Values.TryGetValue(ExamineFieldNames.CategoryFieldName, out var indexType))
            {
                IPublishedContent?content;
                switch (indexType)
                {
                case IndexTypes.Content:
                    content = snapshot.Content?.GetById(contentId);
                    break;

                case IndexTypes.Media:
                    content = snapshot.Media?.GetById(contentId);
                    break;

                case IndexTypes.Member:
                    throw new NotSupportedException("Cannot convert search results to member instances");

                default:
                    continue;
                }

                if (content != null)
                {
                    publishedSearchResults.Add(new PublishedSearchResult(content, result.Score));
                }
            }
        }

        return(publishedSearchResults);
    }
Ejemplo n.º 8
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);
    }
Ejemplo n.º 9
0
    // looks safer but probably useless... ppl should not call these methods directly
    // and if they do... they have to take care about not doing stupid things

    // public static PublishedPropertyType GetModelPropertyType2<T>(Expression<Func<T, object>> selector)
    //    where T : PublishedContentModel
    // {
    //    var type = typeof (T);
    //    var s1 = type.GetField("ModelTypeAlias", BindingFlags.Public | BindingFlags.Static);
    //    var alias = (s1.IsLiteral && s1.IsInitOnly && s1.FieldType == typeof(string)) ? (string)s1.GetValue(null) : null;
    //    var s2 = type.GetField("ModelItemType", BindingFlags.Public | BindingFlags.Static);
    //    var itemType = (s2.IsLiteral && s2.IsInitOnly && s2.FieldType == typeof(PublishedItemType)) ? (PublishedItemType)s2.GetValue(null) : 0;

    // var contentType = PublishedContentType.Get(itemType, alias);
    //    // etc...
    // }
    public static IPublishedContentType?GetModelContentType(
        IPublishedSnapshotAccessor publishedSnapshotAccessor,
        PublishedItemType itemType,
        string alias)
    {
        IPublishedSnapshot publishedSnapshot = publishedSnapshotAccessor.GetRequiredPublishedSnapshot();

        switch (itemType)
        {
        case PublishedItemType.Content:
            return(publishedSnapshot.Content?.GetContentType(alias));

        case PublishedItemType.Media:
            return(publishedSnapshot.Media?.GetContentType(alias));

        case PublishedItemType.Member:
            return(publishedSnapshot.Members?.GetContentType(alias));

        default:
            throw new ArgumentOutOfRangeException(nameof(itemType));
        }
    }
        public void Verifies_Variant_Data()
        {
            // this test implements a full standalone NuCache (based upon a test IDataSource, does not
            // use any local db files, does not rely on any database) - and tests variations

            // get a snapshot, get a published content
            IPublishedSnapshot snapshot         = GetPublishedSnapshot();
            IPublishedContent  publishedContent = snapshot.Content.GetById(1);

            Assert.IsNotNull(publishedContent);
            Assert.AreEqual("val1", publishedContent.Value <string>(Mock.Of <IPublishedValueFallback>(), "prop"));
            Assert.AreEqual("val-fr1", publishedContent.Value <string>(Mock.Of <IPublishedValueFallback>(), "prop", "fr-FR"));
            Assert.AreEqual("val-uk1", publishedContent.Value <string>(Mock.Of <IPublishedValueFallback>(), "prop", "en-UK"));

            Assert.IsNull(publishedContent.Name(VariationContextAccessor)); // no invariant name for varying content
            Assert.AreEqual("name-fr1", publishedContent.Name(VariationContextAccessor, "fr-FR"));
            Assert.AreEqual("name-uk1", publishedContent.Name(VariationContextAccessor, "en-UK"));

            var draftContent = snapshot.Content.GetById(true, 1);

            Assert.AreEqual("val2", draftContent.Value <string>(Mock.Of <IPublishedValueFallback>(), "prop"));
            Assert.AreEqual("val-fr2", draftContent.Value <string>(Mock.Of <IPublishedValueFallback>(), "prop", "fr-FR"));
            Assert.AreEqual("val-uk2", draftContent.Value <string>(Mock.Of <IPublishedValueFallback>(), "prop", "en-UK"));

            Assert.IsNull(draftContent.Name(VariationContextAccessor)); // no invariant name for varying content
            Assert.AreEqual("name-fr2", draftContent.Name(VariationContextAccessor, "fr-FR"));
            Assert.AreEqual("name-uk2", draftContent.Name(VariationContextAccessor, "en-UK"));

            // now french is default
            VariationContextAccessor.VariationContext = new VariationContext("fr-FR");
            Assert.AreEqual("val-fr1", publishedContent.Value <string>(Mock.Of <IPublishedValueFallback>(), "prop"));
            Assert.AreEqual("name-fr1", publishedContent.Name(VariationContextAccessor));
            Assert.AreEqual(new DateTime(2018, 01, 01, 01, 00, 00), publishedContent.CultureDate(VariationContextAccessor));

            // now uk is default
            VariationContextAccessor.VariationContext = new VariationContext("en-UK");
            Assert.AreEqual("val-uk1", publishedContent.Value <string>(Mock.Of <IPublishedValueFallback>(), "prop"));
            Assert.AreEqual("name-uk1", publishedContent.Name(VariationContextAccessor));
            Assert.AreEqual(new DateTime(2018, 01, 02, 01, 00, 00), publishedContent.CultureDate(VariationContextAccessor));

            // invariant needs to be retrieved explicitly, when it's not default
            Assert.AreEqual("val1", publishedContent.Value <string>(Mock.Of <IPublishedValueFallback>(), "prop", culture: ""));

            // but,
            // if the content type / property type does not vary, then it's all invariant again
            // modify the content type and property type, notify the snapshot service
            _contentType.Variations  = ContentVariation.Nothing;
            _propertyType.Variations = ContentVariation.Nothing;
            SnapshotService.Notify(new[] { new ContentTypeCacheRefresher.JsonPayload("IContentType", publishedContent.ContentType.Id, ContentTypeChangeTypes.RefreshMain) });

            // get a new snapshot (nothing changed in the old one), get the published content again
            var anotherSnapshot = SnapshotService.CreatePublishedSnapshot(previewToken: null);
            var againContent    = anotherSnapshot.Content.GetById(1);

            Assert.AreEqual(ContentVariation.Nothing, againContent.ContentType.Variations);
            Assert.AreEqual(ContentVariation.Nothing, againContent.ContentType.GetPropertyType("prop").Variations);

            // now, "no culture" means "invariant"
            Assert.AreEqual("It Works1!", againContent.Name(VariationContextAccessor));
            Assert.AreEqual("val1", againContent.Value <string>(Mock.Of <IPublishedValueFallback>(), "prop"));
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Creates an <see cref="IEnumerable{PublishedSearchResult}" /> containing all content, media or members from the <paramref name="snapshot" />.
        /// </summary>
        /// <param name="results">The search results.</param>
        /// <param name="snapshot">The snapshot.</param>
        /// <returns>
        /// An <see cref="IEnumerable{PublishedSearchResult}" /> containing all content, media or members.
        /// </returns>
        /// <exception cref="ArgumentNullException">snapshot</exception>
        /// <remarks>
        /// Search results are skipped if it can't be fetched from the respective cache by its integer id.
        /// </remarks>
        public static IEnumerable <PublishedSearchResult> ToPublishedSearchResults(this IEnumerable <ISearchResult> results, IPublishedSnapshot snapshot)
        {
            if (snapshot == null)
            {
                throw new ArgumentNullException(nameof(snapshot));
            }

            var publishedSearchResults = new List <PublishedSearchResult>();

            foreach (var result in results)
            {
                if (int.TryParse(result.Id, out var contentId) &&
                    result.Values.TryGetValue(LuceneIndex.CategoryFieldName, out var indexType))
                {
                    IPublishedContent content;
                    switch (indexType)
                    {
                    case IndexTypes.Content:
                        content = snapshot.Content.GetById(contentId);
                        break;

                    case IndexTypes.Media:
                        content = snapshot.Media.GetById(contentId);
                        break;

                    case IndexTypes.Member:
                        content = snapshot.Members.GetById(contentId);
                        break;

                    default:
                        continue;
                    }

                    if (content != null)
                    {
                        publishedSearchResults.Add(new PublishedSearchResult(content, result.Score));
                    }
                }
            }

            return(publishedSearchResults);
        }
    public override object?ToEditor(IProperty property, string?culture = null, string?segment = null)
    {
        var value = property.GetValue(culture, segment)?.ToString();

        if (string.IsNullOrEmpty(value))
        {
            return(Enumerable.Empty <object>());
        }

        try
        {
            List <LinkDto>?links = JsonConvert.DeserializeObject <List <LinkDto> >(value);

            List <LinkDto>?documentLinks = links?.FindAll(link =>
                                                          link.Udi != null && link.Udi.EntityType == Constants.UdiEntityType.Document);
            List <LinkDto>?mediaLinks = links?.FindAll(link =>
                                                       link.Udi != null && link.Udi.EntityType == Constants.UdiEntityType.Media);

            var entities = new List <IEntitySlim>();
            if (documentLinks?.Count > 0)
            {
                entities.AddRange(
                    _entityService.GetAll(
                        UmbracoObjectTypes.Document,
                        documentLinks.Select(link => link.Udi !.Guid).ToArray()));
            }

            if (mediaLinks?.Count > 0)
            {
                entities.AddRange(
                    _entityService.GetAll(UmbracoObjectTypes.Media, mediaLinks.Select(link => link.Udi !.Guid).ToArray()));
            }

            var result = new List <LinkDisplay>();
            if (links is null)
            {
                return(result);
            }

            foreach (LinkDto dto in links)
            {
                GuidUdi?udi       = null;
                var     icon      = "icon-link";
                var     published = true;
                var     trashed   = false;
                var     url       = dto.Url;

                if (dto.Udi != null)
                {
                    IUmbracoEntity?entity = entities.Find(e => e.Key == dto.Udi.Guid);
                    if (entity == null)
                    {
                        continue;
                    }

                    IPublishedSnapshot publishedSnapshot = _publishedSnapshotAccessor.GetRequiredPublishedSnapshot();
                    if (entity is IDocumentEntitySlim documentEntity)
                    {
                        icon      = documentEntity.ContentTypeIcon;
                        published = culture == null
                            ? documentEntity.Published
                            : documentEntity.PublishedCultures.Contains(culture);
                        udi     = new GuidUdi(Constants.UdiEntityType.Document, documentEntity.Key);
                        url     = publishedSnapshot.Content?.GetById(entity.Key)?.Url(_publishedUrlProvider) ?? "#";
                        trashed = documentEntity.Trashed;
                    }
                    else if (entity is IContentEntitySlim contentEntity)
                    {
                        icon      = contentEntity.ContentTypeIcon;
                        published = !contentEntity.Trashed;
                        udi       = new GuidUdi(Constants.UdiEntityType.Media, contentEntity.Key);
                        url       = publishedSnapshot.Media?.GetById(entity.Key)?.Url(_publishedUrlProvider) ?? "#";
                        trashed   = contentEntity.Trashed;
                    }
                    else
                    {
                        // Not supported
                        continue;
                    }
                }

                result.Add(new LinkDisplay
                {
                    Icon        = icon,
                    Name        = dto.Name,
                    Target      = dto.Target,
                    Trashed     = trashed,
                    Published   = published,
                    QueryString = dto.QueryString,
                    Udi         = udi,
                    Url         = url ?? string.Empty,
                });
            }

            return(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error getting links");
        }

        return(base.ToEditor(property, culture, segment));
    }
Ejemplo n.º 13
0
        private IPublishedContent GetMemberByGuidUdi(GuidUdi udi, IPublishedSnapshot snapshot)
        {
            IMember member = _memberService.GetByKey(udi.Guid);

            return(member == null ? null : snapshot.Members.Get(member));
        }
Ejemplo n.º 14
0
 public void SetCurrent(IPublishedSnapshot snapshot) => _snapshot = snapshot;
Ejemplo n.º 15
0
 public bool TryGetPublishedSnapshot(out IPublishedSnapshot publishedSnapshot)
 {
     publishedSnapshot = _snapshot;
     return(_snapshot != null);
 }
Ejemplo n.º 16
0
 public PublishedContentQuery(IPublishedSnapshot publishedSnapshot, IVariationContextAccessor variationContextAccessor)
     : this(publishedSnapshot, variationContextAccessor, ExamineManager.Instance)
 {
 }
 public bool TryGetPublishedSnapshot(out IPublishedSnapshot publishedSnapshot)
 {
     publishedSnapshot = null;
     return(false);
 }