/// <summary>
        /// Get an entity via an id that can be either an integer, Guid or UDI
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <remarks>
        /// This object has it's own contextual cache for these lookups
        /// </remarks>
        internal IEntitySlim GetEntityFromId(string id)
        {
            return(_entityCache.GetOrAdd(id, s =>
            {
                IEntitySlim entity;

                if (Guid.TryParse(s, out var idGuid))
                {
                    entity = Services.EntityService.Get(idGuid, UmbracoObjectType);
                }
                else if (int.TryParse(s, out var idInt))
                {
                    entity = Services.EntityService.Get(idInt, UmbracoObjectType);
                }
                else if (Udi.TryParse(s, out var idUdi))
                {
                    var guidUdi = idUdi as GuidUdi;
                    entity = guidUdi != null ? Services.EntityService.Get(guidUdi.Guid, UmbracoObjectType) : null;
                }
                else
                {
                    entity = null;
                }

                return entity;
            }));
        }
        /// <summary>
        /// Get an entity via an id that can be either an integer, Guid or UDI
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        internal IUmbracoEntity GetEntityFromId(string id)
        {
            IUmbracoEntity entity;

            Guid idGuid;
            int  idInt;
            Udi  idUdi;

            if (Guid.TryParse(id, out idGuid))
            {
                entity = Services.EntityService.GetByKey(idGuid, UmbracoObjectType);
            }
            else if (int.TryParse(id, out idInt))
            {
                entity = Services.EntityService.Get(idInt, UmbracoObjectType);
            }
            else if (Udi.TryParse(id, out idUdi))
            {
                var guidUdi = idUdi as GuidUdi;
                entity = guidUdi != null?Services.EntityService.GetByKey(guidUdi.Guid, UmbracoObjectType) : null;
            }
            else
            {
                return(null);
            }

            return(entity);
        }
Beispiel #3
0
        private IEnumerable <(int?intId, GuidUdi udi, string tagValue)> FindLocalLinkIds(string text)
        {
            // Parse internal links
            var tags = LocalLinkPattern.Matches(text);

            foreach (Match tag in tags)
            {
                if (tag.Groups.Count > 0)
                {
                    var id = tag.Groups[1].Value; //.Remove(tag.Groups[1].Value.Length - 1, 1);

                    //The id could be an int or a UDI
                    if (Udi.TryParse(id, out var udi))
                    {
                        var guidUdi = udi as GuidUdi;
                        if (guidUdi != null)
                        {
                            yield return(null, guidUdi, tag.Value);
                        }
                    }

                    if (int.TryParse(id, out var intId))
                    {
                        yield return(intId, null, tag.Value);
                    }
                }
            }
        }
        /// <summary>
        /// this will parse the string into either a GUID or INT
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        internal Tuple <Guid?, int?> GetIdentifierFromString(string id)
        {
            Guid idGuid;
            int  idInt;
            Udi  idUdi;

            if (Guid.TryParse(id, out idGuid))
            {
                return(new Tuple <Guid?, int?>(idGuid, null));
            }
            if (int.TryParse(id, out idInt))
            {
                return(new Tuple <Guid?, int?>(null, idInt));
            }
            if (Udi.TryParse(id, out idUdi))
            {
                var guidUdi = idUdi as GuidUdi;
                if (guidUdi != null)
                {
                    return(new Tuple <Guid?, int?>(guidUdi.Guid, null));
                }
            }

            return(null);
        }
        protected override void AddSingleValue(Document doc, object value)
        {
            base.AddSingleValue(doc, value);

            if (value is string valueString)
            {
                var ids = valueString.Split(',');

                foreach (var id in ids)
                {
                    if (Udi.TryParse(id, out Udi udi) == true)
                    {
                        var content = _publishedContentHelper.GetByUdi(udi);

                        if (content != null)
                        {
                            if (content.UrlSegment != null)
                            {
                                doc.Add(new Field(_aliasPrefix + FieldName, content.UrlSegment, Field.Store.YES, Field.Index.ANALYZED));
                            }
                        }
                    }
                }
            }
        }
        private void AppendPath(StringBuilder sb, UmbracoObjectTypes objectType, int[] startNodeIds, string searchFrom, bool ignoreUserStartNodes, IEntityService entityService)
        {
            if (sb == null)
            {
                throw new ArgumentNullException("sb");
            }
            if (entityService == null)
            {
                throw new ArgumentNullException("entityService");
            }

            Udi udi;

            Udi.TryParse(searchFrom, true, out udi);
            searchFrom = udi == null ? searchFrom : entityService.GetIdForUdi(udi).Result.ToString();

            int searchFromId;
            var entityPath = int.TryParse(searchFrom, out searchFromId) && searchFromId > 0
                ? entityService.GetAllPaths(objectType, searchFromId).FirstOrDefault()
                : null;

            if (entityPath != null)
            {
                // find... only what's underneath
                sb.Append("+__Path:");
                AppendPath(sb, entityPath.Path, false);
                sb.Append(" ");
            }
            else if (startNodeIds.Length == 0)
            {
                // make sure we don't find anything
                sb.Append("+__Path:none ");
            }
            else if (startNodeIds.Contains(-1) == false && ignoreUserStartNodes == false) // -1 = no restriction
            {
                var entityPaths = entityService.GetAllPaths(objectType, startNodeIds);

                // for each start node, find the start node, and what's underneath
                // +__Path:(-1*,1234 -1*,1234,* -1*,5678 -1*,5678,* ...)
                sb.Append("+__Path:(");
                var first = true;
                foreach (var ep in entityPaths)
                {
                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        sb.Append(" ");
                    }
                    AppendPath(sb, ep.Path, true);
                }
                sb.Append(") ");
            }
        }
 protected override void AddSingleValue(Document doc, object value)
 {
     if (value is string valueString)
     {
         if (Udi.TryParse(valueString, out Udi udi) == true)
         {
             doc.Add(new Field(FieldName, udi.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
         }
     }
 }
        // TODO: Replace mediaCache with media url provider
        internal static string ParseInternalLinks(string text, UrlProvider urlProvider, IPublishedMediaCache mediaCache)
        {
            if (urlProvider == null)
            {
                throw new ArgumentNullException(nameof(urlProvider));
            }
            if (mediaCache == null)
            {
                throw new ArgumentNullException(nameof(mediaCache));
            }

            // Parse internal links
            var tags = LocalLinkPattern.Matches(text);

            foreach (Match tag in tags)
            {
                if (tag.Groups.Count > 0)
                {
                    var id = tag.Groups[1].Value; //.Remove(tag.Groups[1].Value.Length - 1, 1);

                    //The id could be an int or a UDI
                    if (Udi.TryParse(id, out var udi))
                    {
                        var guidUdi = udi as GuidUdi;
                        if (guidUdi != null)
                        {
                            var newLink = "#";
                            if (guidUdi.EntityType == Constants.UdiEntityType.Document)
                            {
                                newLink = urlProvider.GetUrl(guidUdi.Guid);
                            }
                            else if (guidUdi.EntityType == Constants.UdiEntityType.Media)
                            {
                                newLink = mediaCache.GetById(guidUdi.Guid)?.Url;
                            }

                            if (newLink == null)
                            {
                                newLink = "#";
                            }

                            text = text.Replace(tag.Value, "href=\"" + newLink);
                        }
                    }

                    if (int.TryParse(id, out var intId))
                    {
                        var newLink = urlProvider.GetUrl(intId);
                        text = text.Replace(tag.Value, "href=\"" + newLink);
                    }
                }
            }

            return(text);
        }
        /// <summary>
        /// Get paged child entities by id
        /// </summary>
        /// <param name="id"></param>
        /// <param name="type"></param>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <param name="orderBy"></param>
        /// <param name="orderDirection"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public PagedResult <EntityBasic> GetPagedChildren(
            string id,
            UmbracoEntityTypes type,
            int pageNumber,
            int pageSize,
            string orderBy           = "SortOrder",
            Direction orderDirection = Direction.Ascending,
            string filter            = "",
            Guid?dataTypeId          = null)
        {
            int intId;

            if (int.TryParse(id, out intId))
            {
                return(GetPagedChildren(intId, type, pageNumber, pageSize, orderBy, orderDirection, filter));
            }

            Guid guidId;

            if (Guid.TryParse(id, out guidId))
            {
                //Not supported currently
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            Udi udiId;

            if (Udi.TryParse(id, out udiId))
            {
                //Not supported currently
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            //so we don't have an INT, GUID or UDI, it's just a string, so now need to check if it's a special id or a member type
            if (id == Constants.Conventions.MemberTypes.AllMembersListId)
            {
                //the EntityService can search paged members from the root

                intId = -1;
                return(GetPagedChildren(intId, type, pageNumber, pageSize, orderBy, orderDirection, filter, dataTypeId));
            }

            //the EntityService cannot search members of a certain type, this is currently not supported and would require
            //quite a bit of plumbing to do in the Services/Repository, we'll revert to a paged search

            long total;
            var  searchResult = _treeSearcher.ExamineSearch(Umbraco, filter ?? "", type, pageSize, pageNumber - 1, out total, id);

            return(new PagedResult <EntityBasic>(total, pageNumber, pageSize)
            {
                Items = searchResult
            });
        }
Beispiel #10
0
            public GuidUdi GetShareImageUdi(
                //IContentService _contentService
                )
            {
                Udi udi;

                if (Udi.TryParse(ShareImage, out udi))
                {
                    return(udi as GuidUdi);
                    // return _contentService.GetById(guidUdi.Guid);
                }
                return(null);
            }
Beispiel #11
0
            public IEnumerable <UmbracoEntityReference> GetReferences(object value)
            {
                var asString = value is string str ? str : value?.ToString();

                if (string.IsNullOrEmpty(asString))
                {
                    yield break;
                }

                if (Udi.TryParse(asString, out var udi))
                {
                    yield return(new UmbracoEntityReference(udi));
                }
            }
            public IEnumerable <UmbracoEntityReference> GetReferences(object value)
            {
                var asString = value == null ? string.Empty : value is string str ? str : value.ToString();

                var udiPaths = asString.Split(Constants.CharArrays.Comma);

                foreach (var udiPath in udiPaths)
                {
                    if (Udi.TryParse(udiPath, out var udi))
                    {
                        yield return(new UmbracoEntityReference(udi));
                    }
                }
            }
        private ElementsImage GetImageFromCache(string id, int width, int height)
        {
            IPublishedContent media = null;

            if (Udi.TryParse(id, out Udi udi))
            {
                media = Umbraco.Media(udi);
            }
            else if (int.TryParse(id, out int numericId))
            {
                media = Umbraco.Media(numericId);
            }

            return(media == null ? null : new ElementsImage(media, width, height));
        }
        private ElementsImage GetImageFromService(string id, int width, int height)
        {
            IMedia media = null;

            if (Udi.TryParse(id, out Udi udi) && udi is GuidUdi guidUdi)
            {
                media = Services.MediaService.GetById(guidUdi.Guid);
            }
            else if (int.TryParse(id, out int numericId))
            {
                media = Services.MediaService.GetById(numericId);
            }

            return(media == null ? null : new ElementsImage(media, width, height));
        }
Beispiel #15
0
        protected override void AddSingleValue(Document doc, object value)
        {
            if (value is string valueString)
            {
                var ids = valueString.Split(new[] { Separator }, StringSplitOptions.RemoveEmptyEntries);

                foreach (var id in ids)
                {
                    if (Udi.TryParse(id, out Udi udi) == true)
                    {
                        doc.Add(new Field(FieldName, udi.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
                    }
                }
            }
        }
Beispiel #16
0
        /// <summary>
        /// Get paged child entities by id
        /// </summary>
        /// <param name="id"></param>
        /// <param name="type"></param>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <param name="orderBy"></param>
        /// <param name="orderDirection"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public PagedResult <EntityBasic> GetPagedChildren(
            string id,
            UmbracoEntityTypes type,
            int pageNumber,
            int pageSize,
            string orderBy           = "SortOrder",
            Direction orderDirection = Direction.Ascending,
            string filter            = "")
        {
            if (int.TryParse(id, out var intId))
            {
                return(GetPagedChildren(intId, type, pageNumber, pageSize, orderBy, orderDirection, filter));
            }

            if (Guid.TryParse(id, out _))
            {
                //Not supported currently
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            if (Udi.TryParse(id, out _))
            {
                //Not supported currently
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            //so we don't have an INT, GUID or UDI, it's just a string, so now need to check if it's a special id or a member type
            if (id == Constants.Conventions.MemberTypes.AllMembersListId)
            {
                //the EntityService can search paged members from the root

                intId = -1;
                return(GetPagedChildren(intId, type, pageNumber, pageSize, orderBy, orderDirection, filter));
            }

            //the EntityService cannot search members of a certain type, this is currently not supported and would require
            //quite a bit of plumbing to do in the Services/Repository, we'll revert to a paged search

            //TODO: We should really fix this in the EntityService but if we don't we should allow the ISearchableTree for the members controller
            // to be used for this search instead of the built in/internal searcher

            var searchResult = _treeSearcher.ExamineSearch(filter ?? "", type, pageSize, pageNumber - 1, out long total, id);

            return(new PagedResult <EntityBasic>(total, pageNumber, pageSize)
            {
                Items = searchResult
            });
        }
Beispiel #17
0
                public IEnumerable <UmbracoEntityReference> GetReferences(object value)
                {
                    // This is the same as the media picker, it will just try to parse the value directly as a UDI

                    var asString = value is string str ? str : value?.ToString();

                    if (string.IsNullOrEmpty(asString))
                    {
                        yield break;
                    }

                    if (Udi.TryParse(asString, out var udi))
                    {
                        yield return(new UmbracoEntityReference(udi));
                    }
                }
        /// <remarks>Had to change to internal for testing.</remarks>
        internal static bool ConvertIdObjectToUdi(object id, out Udi guidId)
        {
            switch (id)
            {
            case string s:
                return(Udi.TryParse(s, out guidId));

            case Udi u:
                guidId = u;
                return(true);

            default:
                guidId = default;
                return(false);
            }
        }
            public IEnumerable <UmbracoEntityReference> GetReferences(object value)
            {
                var asString = value is string str ? str : value?.ToString();

                if (string.IsNullOrEmpty(asString))
                {
                    yield break;
                }

                foreach (var udiStr in asString.Split(Constants.CharArrays.Comma))
                {
                    if (Udi.TryParse(udiStr, out var udi))
                    {
                        yield return(new UmbracoEntityReference(udi));
                    }
                }
            }
        /// <summary>
        /// Parses out media UDIs from an html string based on 'data-udi' html attributes
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public IEnumerable <Udi> FindUdisFromDataAttributes(string text)
        {
            var matches = DataUdiAttributeRegex.Matches(text);

            if (matches.Count == 0)
            {
                yield break;
            }

            foreach (Match match in matches)
            {
                if (match.Groups.Count == 2 && Udi.TryParse(match.Groups[1].Value, out var udi))
                {
                    yield return(udi);
                }
            }
        }
        /// <inheritdoc/>
        public async Task <IImageResolver> GetAsync(HttpContext context)
        {
            if (!Udi.TryParse(context.Request.Host + context.Request.Path, out Udi udi) ||
                udi.EntityType != Constants.UdiEntityTypes.MediaFile ||
                udi.EntityType.Type != UdiType.ClosedString)
            {
                return(null);
            }

            IFileSystemEntry file = await this.fileSystem.GetFileAsync(udi.Id, default);

            if (file is null)
            {
                return(null);
            }

            return(new FileSystemImageResolver(file));
        }
Beispiel #22
0
        public IPublishedContent GetByString(string id)
        {
            if (int.TryParse(id, out int intId) == true)
            {
                return(GetByInt(intId));
            }

            if (Guid.TryParse(id, out Guid guidId) == true)
            {
                return(GetByGuid(guidId));
            }

            if (Udi.TryParse(id, out Udi udi) == true)
            {
                return(GetByUdi(udi));
            }

            return(null);
        }
Beispiel #23
0
        private void InitPublishedContent()
        {
            if (!_publishedContentInitialized)
            {
                _publishedContentInitialized = true;

                if (UmbracoContext.Current == null)
                {
                    return;
                }

                if (Udi.TryParse(_linkItem.Value <string>("udi"), out _udi))
                {
                    _content = _udi.ToPublishedContent();
                    _id      = _content?.Id;
                }
                else
                {
                    var helper = new UmbracoHelper(UmbracoContext.Current);

                    // there were no Udi so let's try the legacy way
                    _id = _linkItem.Value <int?>("id");

                    if (_id.HasValue)
                    {
                        bool isMedia = _linkItem.Value <bool>("isMedia");

                        if (_linkItem.Value <bool>("isMedia"))
                        {
                            _content = helper.TypedMedia(_id.Value);
                        }
                        else
                        {
                            _content = helper.TypedContent(_id.Value);
                        }
                        SetUdi();
                    }
                }
            }
        }
Beispiel #24
0
        public void RangeTest()
        {
            // can parse open string udi
            var stringUdiString = "umb://" + Constants.UdiEntityType.AnyString;
            Udi stringUdi;

            Assert.IsTrue(Udi.TryParse(stringUdiString, out stringUdi));
            Assert.AreEqual(string.Empty, ((StringUdi)stringUdi).Id);

            // can parse open guid udi
            var guidUdiString = "umb://" + Constants.UdiEntityType.AnyGuid;
            Udi guidUdi;

            Assert.IsTrue(Udi.TryParse(guidUdiString, out guidUdi));
            Assert.AreEqual(Guid.Empty, ((GuidUdi)guidUdi).Guid);

            // can create a range
            var range = new UdiRange(stringUdi, Constants.DeploySelector.ChildrenOfThis);

            // cannot create invalid ranges
            Assert.Throws <ArgumentException>(() => new UdiRange(guidUdi, "x"));
        }
        /// <summary>
        /// Parses the string looking for the {localLink} syntax and updates them to their correct links.
        /// </summary>
        /// <param name="text"></param>
        /// <param name="urlProvider"></param>
        /// <returns></returns>
        public static string ParseInternalLinks(string text, UrlProvider urlProvider)
        {
            if (urlProvider == null)
            {
                throw new ArgumentNullException("urlProvider");
            }

            // Parse internal links
            var tags = LocalLinkPattern.Matches(text);

            foreach (Match tag in tags)
            {
                if (tag.Groups.Count > 0)
                {
                    var id = tag.Groups[1].Value; //.Remove(tag.Groups[1].Value.Length - 1, 1);

                    //The id could be an int or a UDI
                    Udi udi;
                    if (Udi.TryParse(id, out udi))
                    {
                        var guidUdi = udi as GuidUdi;
                        if (guidUdi != null)
                        {
                            var newLink = urlProvider.GetUrl(guidUdi.Guid);
                            text = text.Replace(tag.Value, "href=\"" + newLink);
                        }
                    }
                    int intId;
                    if (int.TryParse(id, out intId))
                    {
                        var newLink = urlProvider.GetUrl(intId);
                        text = text.Replace(tag.Value, "href=\"" + newLink);
                    }
                }
            }

            return(text);
        }
Beispiel #26
0
        public void KnownTypes()
        {
            Udi udi;

            // cannot parse an unknown type, udi is null
            // this will scan
            Assert.IsFalse(Udi.TryParse("umb://whatever/1234", out udi));
            Assert.IsNull(udi);

            Udi.ResetUdiTypes();

            // unless we want to know
            Assert.IsFalse(Udi.TryParse("umb://whatever/1234", true, out udi));
            Assert.AreEqual(Constants.UdiEntityType.Unknown, udi.EntityType);
            Assert.AreEqual("Umbraco.Core.Udi+UnknownTypeUdi", udi.GetType().FullName);

            Udi.ResetUdiTypes();

            // not known
            Assert.IsFalse(Udi.TryParse("umb://foo/A87F65C8D6B94E868F6949BA92C93045", true, out udi));
            Assert.AreEqual(Constants.UdiEntityType.Unknown, udi.EntityType);
            Assert.AreEqual("Umbraco.Core.Udi+UnknownTypeUdi", udi.GetType().FullName);

            // scanned
            Assert.IsTrue(Udi.TryParse("umb://foo/A87F65C8D6B94E868F6949BA92C93045", out udi));
            Assert.IsInstanceOf <GuidUdi>(udi);

            // known
            Assert.IsTrue(Udi.TryParse("umb://foo/A87F65C8D6B94E868F6949BA92C93045", true, out udi));
            Assert.IsInstanceOf <GuidUdi>(udi);

            // can get method for Deploy compatibility
            var method = typeof(Udi).GetMethod("Parse", BindingFlags.Static | BindingFlags.Public, null, new[] { typeof(string), typeof(bool) }, null);

            Assert.IsNotNull(method);
        }
Beispiel #27
0
        /// <inheritdoc/>
        public override string GetValue(GridValue.GridControl control, Property property, ICollection <ArtifactDependency> dependencies)
        {
            // cancel if there's no values
            if (control.Value == null || control.Value.HasValues == false)
            {
                return(null);
            }

            // Often there is only one entry in cell.Value, but with LeBlender
            // min/max you can easily get 2+ entries so we'll walk them all
            var newItemValue = new List <object>();

            foreach (var properties in control.Value)
            {
                // create object to store resolved properties
                var resolvedProperties = new JObject();
                foreach (var leBlenderPropertyWrapper in properties)
                {
                    if (leBlenderPropertyWrapper.HasValues == false)
                    {
                        continue;
                    }

                    var leBlenderProperty = leBlenderPropertyWrapper.First.ToObject <LeBlenderGridCellValue>();

                    // get the data type of the property
                    var dataType = _dataTypeService.GetDataTypeDefinitionById(leBlenderProperty.DataTypeGuid);
                    if (dataType == null)
                    {
                        throw new ArgumentNullException(
                                  $"Unable to find the data type for editor '{leBlenderProperty.EditorName}' ({leBlenderProperty.EditorAlias} {leBlenderProperty.DataTypeGuid}) referenced by '{property.Alias}'.");
                    }

                    // add the datatype as a dependency
                    dependencies.Add(new ArtifactDependency(dataType.GetUdi(), false, ArtifactDependencyMode.Exist));

                    // if it's null or undefined value there is no need to do any more processing
                    if (leBlenderProperty.Value.Type == JTokenType.Null || leBlenderProperty.Value.Type == JTokenType.Undefined)
                    {
                        resolvedProperties.Add(leBlenderProperty.EditorAlias, JObject.FromObject(leBlenderProperty));
                        continue;
                    }

                    Udi udi;
                    // if the value is an Udi then add it as a dependency
                    if (Udi.TryParse(leBlenderProperty.Value.ToString(), out udi))
                    {
                        dependencies.Add(new ArtifactDependency(udi, false, ArtifactDependencyMode.Exist));
                        resolvedProperties.Add(leBlenderProperty.EditorAlias, JObject.FromObject(leBlenderProperty));
                        continue;
                    }

                    var tempDependencies = new List <Udi>();
                    // try to convert the value with the macro parser - this is mainly for legacy editors
                    var value = _macroParser.ReplaceAttributeValue(leBlenderProperty.Value.ToString(), dataType.PropertyEditorAlias, tempDependencies, Direction.ToArtifact);
                    foreach (var dependencyUdi in tempDependencies)
                    {
                        // if the macro parser was able to convert the value it will mark the Udi as dependency
                        // and we want that added as a artifact dependency
                        dependencies.Add(new ArtifactDependency(dependencyUdi, false, ArtifactDependencyMode.Exist));
                    }

                    // test if the macroparser converted the value to an Udi
                    if (Udi.TryParse(value, out udi))
                    {
                        leBlenderProperty.Value = value;
                        resolvedProperties.Add(leBlenderProperty.EditorAlias, JObject.FromObject(leBlenderProperty));
                        continue;
                    }

                    // if the macro parser didn't convert the value then try to find a value connector that can and convert it
                    var propertyType = new PropertyType(dataType.PropertyEditorAlias, dataType.DatabaseType);
                    propertyType.DataTypeDefinitionId = dataType.Id;
                    var propValueConnector = ValueConnectors.Get(propertyType);
                    if (leBlenderProperty.Value.Type == JTokenType.Array)
                    {
                        // if the value is an array then we should try and convert each item instead of the whole array
                        var array = new JArray();
                        foreach (var child in leBlenderProperty.Value)
                        {
                            var mockProperty   = new Property(propertyType, child.Value <object>());
                            var convertedValue = propValueConnector.GetValue(mockProperty, dependencies);
                            array.Add(new JValue(convertedValue));
                        }
                        leBlenderProperty.Value = array;
                    }
                    else
                    {
                        var mockProperty = new Property(propertyType, leBlenderProperty.Value);
                        value = propValueConnector.GetValue(mockProperty, dependencies);
                        leBlenderProperty.Value = value;
                    }

                    resolvedProperties.Add(leBlenderProperty.EditorAlias, JObject.FromObject(leBlenderProperty));
                }
                newItemValue.Add(resolvedProperties);
            }

            return(JsonConvert.SerializeObject(newItemValue));
        }
Beispiel #28
0
        public string GetValue(Property property, ICollection <ArtifactDependency> dependencies)
        {
            if (property.Value == null)
            {
                return(null);
            }

            var value = property.Value.ToString();

            var      prevalues = _dataTypeService.GetPreValuesCollectionByDataTypeId(property.PropertyType.DataTypeDefinitionId).PreValuesAsDictionary;
            PreValue prevalue;

            //Fetch the Prevalues for the current Property's DataType (if its an 'Archetype config')
            if (!prevalues.TryGetValue("archetypeconfig", out prevalue) && !prevalues.TryGetValue("archetypeConfig", out prevalue))
            {
                throw new InvalidOperationException("Could not find Archetype configuration.");
            }
            var archetypePreValue = prevalue == null
                ? null
                : JsonConvert.DeserializeObject <ArchetypePreValue>(prevalue.Value);

            RetrieveAdditionalProperties(ref archetypePreValue);

            var archetype = JsonConvert.DeserializeObject <ArchetypeModel>(value);

            RetrieveAdditionalProperties(ref archetype, archetypePreValue);

            if (archetype == null)
            {
                throw new InvalidOperationException("Could not parse Archetype value.");
            }

            var properties = archetype.Fieldsets.SelectMany(x => x.Properties);

            foreach (var archetypeProperty in properties)
            {
                if (archetypeProperty.DataTypeGuid == null)
                {
                    continue;
                }
                // get the data type of the property
                var dataType = _dataTypeService.GetDataTypeDefinitionById(Guid.Parse(archetypeProperty.DataTypeGuid));
                if (dataType == null)
                {
                    throw new ArgumentNullException(
                              $"Unable to find the data type for editor '{archetypeProperty.PropertyEditorAlias}' ({archetypeProperty.DataTypeGuid}) referenced by '{property.Alias}'.");
                }
                // add the datatype as a dependency
                dependencies.Add(new ArtifactDependency(new GuidUdi(Constants.UdiEntityType.DataType, dataType.Key), false, ArtifactDependencyMode.Exist));

                // if it's null or undefined value there is no need to do any more processing
                if (archetypeProperty.Value == null || archetypeProperty.Value.ToString() == string.Empty)
                {
                    continue;
                }

                Udi udi;
                // if the value is an Udi then add it as a dependency and continue
                if (Udi.TryParse(archetypeProperty.Value.ToString(), out udi))
                {
                    dependencies.Add(new ArtifactDependency(udi, false, ArtifactDependencyMode.Exist));
                    continue;
                }

                var tempDependencies = new List <Udi>();
                // try to convert the value with the macro parser - this is mainly for legacy editors
                var archetypeValue = archetypeProperty.Value != null
                    ? _macroParser.ReplaceAttributeValue(archetypeProperty.Value.ToString(), dataType.PropertyEditorAlias, tempDependencies, Direction.ToArtifact)
                    : null;

                foreach (var dependencyUdi in tempDependencies)
                {
                    // if the macro parser was able to convert the value it will mark the Udi as dependency
                    // and we want that added as a artifact dependency
                    dependencies.Add(new ArtifactDependency(dependencyUdi, false, ArtifactDependencyMode.Exist));
                }

                // test if the macroparser converted the value to an Udi so we can just continue
                if (Udi.TryParse(archetypeValue, out udi))
                {
                    archetypeProperty.Value = archetypeValue;
                    continue;
                }

                // if the macro parser didn't convert the value then try to find a value connector that can and convert it
                var propertyType = new PropertyType(dataType.PropertyEditorAlias, dataType.DatabaseType);
                propertyType.DataTypeDefinitionId = dataType.Id;
                var propValueConnector = ValueConnectors.Get(propertyType);

                var mockProperty = new Property(propertyType, archetypeProperty.Value);

                archetypeValue          = propValueConnector.GetValue(mockProperty, dependencies);
                archetypeProperty.Value = archetypeValue;
            }
            value = archetype.SerializeForPersistence();
            return(value);
        }
Beispiel #29
0
        public override string GetValue(GridValue.GridControl control, Property property, ICollection <ArtifactDependency> dependencies)
        {
            // cancel if there's no values
            if (control.Value == null || control.Value.HasValues == false)
            {
                return(null);
            }

            var docTypeGridEditorContent = JsonConvert.DeserializeObject <DocTypeGridEditorValue>(control.Value.ToString());

            // if an 'empty' dtge item has been added - it has no ContentTypeAlias set .. just return and don't throw.
            if (docTypeGridEditorContent == null || string.IsNullOrWhiteSpace(docTypeGridEditorContent.ContentTypeAlias))
            {
                return(null);
            }

            // check if the doc type exist - else abort packaging
            var contentType = _contentTypeService.GetContentType(docTypeGridEditorContent.ContentTypeAlias);

            if (contentType == null)
            {
                throw new InvalidOperationException(
                          $"Could not resolve the Content Type for the Doc Type Grid Editor property: {docTypeGridEditorContent.ContentTypeAlias}");
            }

            // add content type as a dependency
            dependencies.Add(new ArtifactDependency(contentType.GetUdi(), false, ArtifactDependencyMode.Match));

            // find all properties
            var propertyTypes = contentType.CompositionPropertyTypes;

            foreach (var propertyType in propertyTypes)
            {
                // test if there's a value for the given property
                object value;
                if (!docTypeGridEditorContent.Value.TryGetValue(propertyType.Alias, out value) || value == null)
                {
                    continue;
                }

                Udi udi;
                // if the value is an Udi then add it as a dependency
                if (Udi.TryParse(value.ToString(), out udi))
                {
                    dependencies.Add(new ArtifactDependency(udi, false, ArtifactDependencyMode.Match));
                    continue;
                }

                // throws if not found - no need for a null check
                var propValueConnector = ValueConnectors.Get(propertyType);

                var mockProperty = new Property(propertyType, value);
                var parsedValue  = propValueConnector.GetValue(mockProperty, dependencies);
                // test if the value is a json object (thus could be a nested complex editor)
                // if that's the case we'll need to add it as a json object instead of string to avoid it being escaped
                var jtokenValue = parsedValue != null && parsedValue.DetectIsJson() ? JToken.Parse(parsedValue) : null;
                if (jtokenValue != null)
                {
                    docTypeGridEditorContent.Value[propertyType.Alias] = jtokenValue;
                }
                else
                {
                    docTypeGridEditorContent.Value[propertyType.Alias] = parsedValue;
                }
            }

            var resolvedValue = JsonConvert.SerializeObject(docTypeGridEditorContent);

            return(resolvedValue);
        }
Beispiel #30
0
        public void SetValue(IContentBase content, string alias, string value)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                content.SetValue(alias, value);
                return;
            }

            if (value.DetectIsJson() == false)
            {
                return;
            }

            var property = content.Properties[alias];

            if (property == null)
            {
                throw new NullReferenceException($"Property not found: '{alias}'.");
            }

            var prevalues = _dataTypeService.GetPreValuesCollectionByDataTypeId(property.PropertyType.DataTypeDefinitionId).FormatAsDictionary();

            PreValue prevalue = null;

            //Fetch the Prevalues for the current Property's DataType (if its an 'Archetype config')
            if (!prevalues.TryGetValue("archetypeconfig", out prevalue) && !prevalues.TryGetValue("archetypeConfig", out prevalue))
            {
                throw new InvalidOperationException("Could not find Archetype configuration.");
            }
            var archetypePreValue = prevalue == null
                ? null
                : JsonConvert.DeserializeObject <ArchetypePreValue>(prevalue.Value);

            RetrieveAdditionalProperties(ref archetypePreValue);

            var archetype = JsonConvert.DeserializeObject <ArchetypeModel>(value);

            if (archetype == null)
            {
                throw new InvalidOperationException("Could not parse Archetype value.");
            }

            RetrieveAdditionalProperties(ref archetype, archetypePreValue);

            var properties = archetype.Fieldsets.SelectMany(x => x.Properties);

            foreach (var archetypeProperty in properties)
            {
                if (archetypeProperty.Value == null || string.IsNullOrEmpty(archetypeProperty.DataTypeGuid))
                {
                    continue;
                }

                // get the data type of the property
                var dataType = _dataTypeService.GetDataTypeDefinitionById(Guid.Parse(archetypeProperty.DataTypeGuid));
                if (dataType == null)
                {
                    throw new ArgumentNullException(
                              $"Unable to find the data type for editor '{archetypeProperty.PropertyEditorAlias}' ({archetypeProperty.DataTypeGuid}) referenced by '{property.Alias}'.");
                }

                // try to convert the value with the macro parser - this is mainly for legacy editors
                var archetypeValue = _macroParser.ReplaceAttributeValue(archetypeProperty.Value.ToString(), dataType.PropertyEditorAlias, null, Direction.FromArtifact);

                Udi udi;
                // test if the macroparser converted the value to an Udi
                if (Udi.TryParse(archetypeValue, out udi))
                {
                    archetypeProperty.Value = archetypeValue;
                    continue;
                }

                // if the macro parser didn't convert the value then try to find a value connector that can and convert it
                var propertyType = new PropertyType(dataType.PropertyEditorAlias, dataType.DatabaseType, "mockPropertyTypeAlias");
                propertyType.DataTypeDefinitionId = dataType.Id;
                var propValueConnector = ValueConnectors.Get(propertyType);
                var mockProperty       = new Property(propertyType);
                var mockContent        = new Content("mockContent", -1, new ContentType(-1), new PropertyCollection(new List <Property> {
                    mockProperty
                }));
                propValueConnector.SetValue(mockContent, mockProperty.Alias, archetypeProperty.Value.ToString());
                archetypeProperty.Value = mockContent.GetValue(mockProperty.Alias);
            }
            value = archetype.SerializeForPersistence();
            content.SetValue(alias, value);
        }