Exemple #1
0
        public void StringEncodingTest()
        {
            // absolute path is unescaped
            var uri = new Uri("umb://" + Constants.UdiEntityType.AnyString + "/this%20is%20a%20test");

            Assert.AreEqual("umb://" + Constants.UdiEntityType.AnyString + "/this is a test", uri.ToString());
            Assert.AreEqual("umb://" + Constants.UdiEntityType.AnyString + "/this%20is%20a%20test", uri.AbsoluteUri);
            Assert.AreEqual("/this%20is%20a%20test", uri.AbsolutePath);

            Assert.AreEqual("/this is a test", Uri.UnescapeDataString(uri.AbsolutePath));
            Assert.AreEqual("%2Fthis%20is%20a%20test", Uri.EscapeDataString("/this is a test"));
            Assert.AreEqual("/this%20is%20a%20test", Uri.EscapeUriString("/this is a test"));

            var udi = UdiParser.Parse("umb://" + Constants.UdiEntityType.AnyString + "/this%20is%20a%20test");

            Assert.AreEqual(Constants.UdiEntityType.AnyString, udi.EntityType);
            Assert.IsInstanceOf <StringUdi>(udi);
            var stringEntityId = udi as StringUdi;

            Assert.IsNotNull(stringEntityId);
            Assert.AreEqual("this is a test", stringEntityId.Id);
            Assert.AreEqual("umb://" + Constants.UdiEntityType.AnyString + "/this%20is%20a%20test", udi.ToString());

            var udi2 = new StringUdi(Constants.UdiEntityType.AnyString, "this is a test");

            Assert.AreEqual(udi, udi2);

            var udi3 = new StringUdi(Constants.UdiEntityType.AnyString, "path to/this is a test.xyz");

            Assert.AreEqual("umb://" + Constants.UdiEntityType.AnyString + "/path%20to/this%20is%20a%20test.xyz", udi3.ToString());
        }
Exemple #2
0
        public void KnownTypes()
        {
            // cannot parse an unknown type, udi is null
            // this will scan
            Assert.IsFalse(UdiParser.TryParse("umb://whatever/1234", out Udi udi));
            Assert.IsNull(udi);

            UdiParser.ResetUdiTypes();

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

            UdiParser.ResetUdiTypes();

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

            // scanned
            UdiParserServiceConnectors.RegisterServiceConnector <FooConnector>(); // this is the equivalent of scanning but we'll just manually register this one
            Assert.IsTrue(UdiParser.TryParse("umb://foo/A87F65C8D6B94E868F6949BA92C93045", out udi));
            Assert.IsInstanceOf <GuidUdi>(udi);

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

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

            Assert.IsNotNull(method);
        }
Exemple #3
0
        public void RootUdiTest()
        {
            var stringUdi = new StringUdi(Constants.UdiEntityType.AnyString, string.Empty);

            Assert.IsTrue(stringUdi.IsRoot);
            Assert.AreEqual("umb://any-string/", stringUdi.ToString());

            var guidUdi = new GuidUdi(Constants.UdiEntityType.AnyGuid, Guid.Empty);

            Assert.IsTrue(guidUdi.IsRoot);
            Assert.AreEqual("umb://any-guid/00000000000000000000000000000000", guidUdi.ToString());

            var udi = UdiParser.Parse("umb://any-string/");

            Assert.IsTrue(udi.IsRoot);
            Assert.IsInstanceOf <StringUdi>(udi);

            udi = UdiParser.Parse("umb://any-guid/00000000000000000000000000000000");
            Assert.IsTrue(udi.IsRoot);
            Assert.IsInstanceOf <GuidUdi>(udi);

            udi = UdiParser.Parse("umb://any-guid/");
            Assert.IsTrue(udi.IsRoot);
            Assert.IsInstanceOf <GuidUdi>(udi);
        }
        /// <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 = _entityService.Get(idGuid, UmbracoObjectType);
                }
                else if (int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out var idInt))
                {
                    entity = _entityService.Get(idInt, UmbracoObjectType);
                }
                else if (UdiParser.TryParse(s, out var idUdi))
                {
                    var guidUdi = idUdi as GuidUdi;
                    entity = guidUdi != null ? _entityService.Get(guidUdi.Guid, UmbracoObjectType) : null;
                }
                else
                {
                    entity = null;
                }

                return entity;
            }));
        }
Exemple #5
0
        public void ValidateUdiEntityType()
        {
            var types = UdiParser.GetKnownUdiTypes();

            foreach (var fi in typeof(Constants.UdiEntityType).GetFields(BindingFlags.Public | BindingFlags.Static))
            {
                // IsLiteral determines if its value is written at
                //   compile time and not changeable
                // IsInitOnly determine if the field can be set
                //   in the body of the constructor
                // for C# a field which is readonly keyword would have both true
                //   but a const field would have only IsLiteral equal to true
                if (fi.IsLiteral && fi.IsInitOnly == false)
                {
                    var value = fi.GetValue(null).ToString();

                    if (types.ContainsKey(value) == false)
                    {
                        Assert.Fail("Error in class Constants.UdiEntityType, type \"{0}\" is not declared by GetTypes.", value);
                    }
                    types.Remove(value);
                }
            }

            Assert.AreEqual(0, types.Count, "Error in class Constants.UdiEntityType, GetTypes declares types that don't exist ({0}).", string.Join(",", types.Keys.Select(x => "\"" + x + "\"")));
        }
 /// <summary>
 /// Attempts to parse a node ID from a string representation found in a querystring value.
 /// </summary>
 /// <param name="argument">Querystring value.</param>
 /// <param name="nodeId">Output parsed Id.</param>
 /// <returns>True of node ID could be parased, false it not.</returns>
 protected bool TryParseNodeId(string argument, out int nodeId)
 {
     // If the argument is an int, it will parse and can be assigned to nodeId.
     // It might be a udi, so check that next.
     // Otherwise treat it as a guid - unlikely we ever get here.
     // Failing that, we can't parse it.
     if (int.TryParse(argument, NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsedId))
     {
         nodeId = parsedId;
         return(true);
     }
     else if (UdiParser.TryParse(argument, true, out Udi udi))
     {
         nodeId = EntityService.GetId(udi).Result;
         return(true);
     }
     else if (Guid.TryParse(argument, out Guid key))
     {
         nodeId = EntityService.GetId(key, UmbracoObjectTypes.Document).Result;
         return(true);
     }
     else
     {
         nodeId = 0;
         return(false);
     }
 }
        public void Convert_Valid_Json()
        {
            BlockListPropertyValueConverter editor       = CreateConverter();
            BlockListConfiguration          config       = ConfigForMany();
            IPublishedPropertyType          propertyType = GetPropertyType(config);
            IPublishedElement publishedElement           = Mock.Of <IPublishedElement>();

            string json      = @"
{
    layout: {
        '" + Constants.PropertyEditors.Aliases.BlockList + @"': [
            {
                'contentUdi': 'umb://element/1304E1DDAC87439684FE8A399231CB3D'
            }
        ]
    },
        contentData: [
        {
            'contentTypeKey': '" + _contentKey1 + @"',
            'udi': 'umb://element/1304E1DDAC87439684FE8A399231CB3D'
        }
    ]
}";
            var    converted = editor.ConvertIntermediateToObject(publishedElement, propertyType, PropertyCacheLevel.None, json, false) as BlockListModel;

            Assert.IsNotNull(converted);
            Assert.AreEqual(1, converted.Count);
            IPublishedElement item0 = converted[0].Content;

            Assert.AreEqual(Guid.Parse("1304E1DD-AC87-4396-84FE-8A399231CB3D"), item0.Key);
            Assert.AreEqual("Test1", item0.ContentType.Alias);
            Assert.IsNull(converted[0].Settings);
            Assert.AreEqual(UdiParser.Parse("umb://element/1304E1DDAC87439684FE8A399231CB3D"), converted[0].ContentUdi);
        }
        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 (UdiParser.TryParse(id, out var udi))
                    {
                        var guidUdi = udi as GuidUdi;
                        if (guidUdi is not null)
                        {
                            yield return(null, guidUdi, tag.Value);
                        }
                    }

                    if (int.TryParse(id, NumberStyles.Integer, CultureInfo.InvariantCulture, out var intId))
                    {
                        yield return(intId, null, tag.Value);
                    }
                }
            }
        }
        /// <summary>
        /// Parses the string looking for Umbraco image tags and updates them to their up-to-date image sources.
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        /// <remarks>Umbraco image tags are identified by their data-udi attributes</remarks>
        public string EnsureImageSources(string text)
        {
            if (_getMediaUrl == null)
            {
                _getMediaUrl = (guid) => _publishedUrlProvider?.GetMediaUrl(guid);
            }

            return(ResolveImgPattern.Replace(text, match =>
            {
                // match groups:
                // - 1 = from the beginning of the image tag until src attribute value begins
                // - 2 = the src attribute value excluding the querystring (if present)
                // - 3 = anything after group 2 and before the data-udi attribute value begins
                // - 4 = the data-udi attribute value
                // - 5 = anything after group 4 until the image tag is closed
                var udi = match.Groups[4].Value;
                if (udi.IsNullOrWhiteSpace() || UdiParser.TryParse <GuidUdi>(udi, out var guidUdi) == false)
                {
                    return match.Value;
                }
                var mediaUrl = _getMediaUrl(guidUdi.Guid);
                if (mediaUrl == null)
                {
                    // image does not exist - we could choose to remove the image entirely here (return empty string),
                    // but that would leave the editors completely in the dark as to why the image doesn't show
                    return match.Value;
                }

                return $"{match.Groups[1].Value}{mediaUrl}{match.Groups[3].Value}{udi}{match.Groups[5].Value}";
            }));
        }
    public override object?ReadJson(JsonReader reader, Type objectType, object?existingValue, JsonSerializer serializer)
    {
        var jo  = JToken.ReadFrom(reader);
        var val = jo.ToObject <string>();

        return(val == null ? null : UdiParser.Parse(val, true));
    }
        /// <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, NumberStyles.Integer, CultureInfo.InvariantCulture, out idInt))
            {
                return(new Tuple <Guid?, int?>(null, idInt));
            }
            if (UdiParser.TryParse(id, out idUdi))
            {
                var guidUdi = idUdi as GuidUdi;
                if (guidUdi != null)
                {
                    return(new Tuple <Guid?, int?>(guidUdi.Guid, null));
                }
            }

            return(null);
        }
        /// <summary>
        /// Parses the string looking for Umbraco image tags and updates them to their up-to-date image sources.
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        /// <remarks>Umbraco image tags are identified by their data-udi attributes</remarks>
        public static string ResolveMediaFromTextString(string text)
        {
            // don't attempt to proceed without a context
            if (Current.UmbracoContext == null || Current.UmbracoContext.Media == null)
            {
                return(text);
            }

            return(ResolveImgPattern.Replace(text, match =>
            {
                // match groups:
                // - 1 = from the beginning of the image tag until src attribute value begins
                // - 2 = the src attribute value excluding the querystring (if present)
                // - 3 = anything after group 2 and before the data-udi attribute value begins
                // - 4 = the data-udi attribute value
                // - 5 = anything after group 4 until the image tag is closed
                var udi = match.Groups[4].Value;
                if (udi.IsNullOrWhiteSpace() || UdiParser.TryParse(udi, out GuidUdi guidUdi) == false)
                {
                    return match.Value;
                }
                var media = Current.UmbracoContext.Media.GetById(guidUdi.Guid);
                if (media == null)
                {
                    // image does not exist - we could choose to remove the image entirely here (return empty string),
                    // but that would leave the editors completely in the dark as to why the image doesn't show
                    return match.Value;
                }

                var url = media.Url;
                return $"{match.Groups[1].Value}{url}{match.Groups[3].Value}{udi}{match.Groups[5].Value}";
            }));
        }
Exemple #13
0
        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(','))
            {
                if (UdiParser.TryParse(udiStr, out Udi? udi))
                {
                    yield return(new UmbracoEntityReference(udi));
                }

                // this is needed to support the legacy case when the multiple media picker parameter editor stores ints not udis
                if (int.TryParse(udiStr, out var id))
                {
                    Attempt <Guid> guidAttempt = _entityService.GetKey(id, UmbracoObjectType);
                    Guid           guid        = guidAttempt.Success ? guidAttempt.Result : Guid.Empty;

                    if (guid != Guid.Empty)
                    {
                        yield return(new UmbracoEntityReference(new GuidUdi(Constants.UdiEntityType.Media, guid)));
                    }
                }
            }
        }
Exemple #14
0
    private void AppendPath(StringBuilder sb, UmbracoObjectTypes objectType, int[]?startNodeIds, string?searchFrom, bool ignoreUserStartNodes, IEntityService entityService)
    {
        if (sb == null)
        {
            throw new ArgumentNullException(nameof(sb));
        }

        if (entityService == null)
        {
            throw new ArgumentNullException(nameof(entityService));
        }

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

        TreeEntityPath?entityPath =
            int.TryParse(searchFrom, NumberStyles.Integer, CultureInfo.InvariantCulture, out var 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
        {
            IEnumerable <TreeEntityPath> 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 (TreeEntityPath ep in entityPaths)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    sb.Append(" ");
                }

                AppendPath(sb, ep.Path, true);
            }

            sb.Append(") ");
        }
    }
Exemple #15
0
        protected uSyncDependency CreateDependency(string udiString, DependencyFlags flags)
        {
            if (UdiParser.TryParse <GuidUdi>(udiString, out GuidUdi udi))
            {
                return(CreateDependency(udi, flags));
            }

            return(null);
        }
        // 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 (UdiParser.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);
        }
    public override object?ConvertFrom(ITypeDescriptorContext?context, CultureInfo?culture, object value)
    {
        if (value is string)
        {
            if (UdiParser.TryParse((string)value, out Udi? udi))
            {
                return(udi);
            }
        }

        return(base.ConvertFrom(context, culture, value));
    }
        /// <summary>
        /// Given a parent id which could be a GUID, UDI or an INT, this will resolve the INT
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="validatePermissions">
        /// If true, this will check if the current user has access to the resolved integer parent id
        /// and if that check fails an unauthorized exception will occur
        /// </param>
        /// <returns></returns>
        private async Task <ActionResult <int?> > GetParentIdAsIntAsync(string parentId, bool validatePermissions)
        {
            int intParentId;

            // test for udi
            if (UdiParser.TryParse(parentId, out GuidUdi parentUdi))
            {
                parentId = parentUdi.Guid.ToString();
            }

            //if it's not an INT then we'll check for GUID
            if (int.TryParse(parentId, NumberStyles.Integer, CultureInfo.InvariantCulture, out intParentId) == false)
            {
                // if a guid then try to look up the entity
                Guid idGuid;
                if (Guid.TryParse(parentId, out idGuid))
                {
                    var entity = _entityService.Get(idGuid);
                    if (entity != null)
                    {
                        intParentId = entity.Id;
                    }
                    else
                    {
                        return(null);
                    }
                }
                else
                {
                    return(ValidationProblem("The request was not formatted correctly, the parentId is not an integer, Guid or UDI"));
                }
            }

            // Authorize...
            //ensure the user has access to this folder by parent id!
            if (validatePermissions)
            {
                var requirement         = new MediaPermissionsResourceRequirement();
                var authorizationResult = await _authorizationService.AuthorizeAsync(User, new MediaPermissionsResource(_mediaService.GetById(intParentId)), requirement);

                if (!authorizationResult.Succeeded)
                {
                    return(ValidationProblem(
                               new SimpleNotificationModel(new BackOfficeNotification(
                                                               _localizedTextService.Localize("speechBubbles", "operationFailedHeader"),
                                                               _localizedTextService.Localize("speechBubbles", "invalidUserPermissionsText"),
                                                               NotificationStyle.Warning)),
                               StatusCodes.Status403Forbidden));
                }
            }

            return(intParentId);
        }
Exemple #19
0
        /// <summary>
        /// Given a parent id which could be a GUID, UDI or an INT, this will resolve the INT
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="validatePermissions">
        /// If true, this will check if the current user has access to the resolved integer parent id
        /// and if that check fails an unauthorized exception will occur
        /// </param>
        /// <returns></returns>
        private int GetParentIdAsInt(string parentId, bool validatePermissions)
        {
            int intParentId;

            // test for udi
            if (UdiParser.TryParse(parentId, out GuidUdi parentUdi))
            {
                parentId = parentUdi.Guid.ToString();
            }

            //if it's not an INT then we'll check for GUID
            if (int.TryParse(parentId, out intParentId) == false)
            {
                // if a guid then try to look up the entity
                Guid idGuid;
                if (Guid.TryParse(parentId, out idGuid))
                {
                    var entity = Services.EntityService.Get(idGuid);
                    if (entity != null)
                    {
                        intParentId = entity.Id;
                    }
                    else
                    {
                        throw new EntityNotFoundException(parentId, "The passed id doesn't exist");
                    }
                }
                else
                {
                    throw new HttpResponseException(
                              Request.CreateValidationErrorResponse("The request was not formatted correctly, the parentId is not an integer, Guid or UDI"));
                }
            }

            //ensure the user has access to this folder by parent id!
            if (validatePermissions && CheckPermissions(
                    new Dictionary <string, object>(),
                    Security.CurrentUser,
                    Services.MediaService,
                    Services.EntityService,
                    intParentId) == false)
            {
                throw new HttpResponseException(Request.CreateResponse(
                                                    HttpStatusCode.Forbidden,
                                                    new SimpleNotificationModel(new Notification(
                                                                                    Services.TextService.Localize("speechBubbles/operationFailedHeader"),
                                                                                    Services.TextService.Localize("speechBubbles/invalidUserPermissionsText"),
                                                                                    NotificationStyle.Warning))));
            }

            return(intParentId);
        }
Exemple #20
0
        public IEnumerable <UmbracoEntityReference> GetReferences(object?value)
        {
            var asString = value is string str ? str : value?.ToString();

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

            if (UdiParser.TryParse(asString, out Udi? udi))
            {
                yield return(new UmbracoEntityReference(udi));
            }
        }
Exemple #21
0
        public void GuidUdiParseTest()
        {
            var guid = Guid.NewGuid();
            var s    = "umb://" + Constants.UdiEntityType.AnyGuid + "/" + guid.ToString("N");
            var udi  = UdiParser.Parse(s);

            Assert.AreEqual(Constants.UdiEntityType.AnyGuid, udi.EntityType);
            Assert.IsInstanceOf <GuidUdi>(udi);
            var gudi = udi as GuidUdi;

            Assert.IsNotNull(gudi);
            Assert.AreEqual(guid, gudi.Guid);
            Assert.AreEqual(s, udi.ToString());
        }
            public IEnumerable <UmbracoEntityReference> GetReferences(object value)
            {
                var asString = value == null ? string.Empty : value is string str ? str : value.ToString();

                var udiPaths = asString.Split(',');

                foreach (var udiPath in udiPaths)
                {
                    if (UdiParser.TryParse(udiPath, out var udi))
                    {
                        yield return(new UmbracoEntityReference(udi));
                    }
                }
            }
Exemple #23
0
        public void StringUdiParseTest()
        {
            var udi = UdiParser.Parse("umb://" + Constants.UdiEntityType.AnyString + "/test-id");

            Assert.AreEqual(Constants.UdiEntityType.AnyString, udi.EntityType);
            Assert.IsInstanceOf <StringUdi>(udi);
            var stringEntityId = udi as StringUdi;

            Assert.IsNotNull(stringEntityId);
            Assert.AreEqual("test-id", stringEntityId.Id);
            Assert.AreEqual("umb://" + Constants.UdiEntityType.AnyString + "/test-id", udi.ToString());

            udi = UdiParser.Parse("umb://" + Constants.UdiEntityType.AnyString + "/DA845952BE474EE9BD6F6194272AC750");
            Assert.IsInstanceOf <StringUdi>(udi);
        }
                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 (UdiParser.TryParse(asString, out Udi udi))
                    {
                        yield return(new UmbracoEntityReference(udi));
                    }
                }
Exemple #25
0
        public static void Converting_Boxed_Udi_To_A_Udi_Returns_Original_Udi_Value()
        {
            // Arrange
            UdiParser.ResetUdiTypes();
            Udi sample = new GuidUdi(Constants.UdiEntityType.AnyGuid, Guid.NewGuid());

            // Act
            bool success = UmbracoHelper.ConvertIdObjectToUdi(
                sample,
                out Udi result
                );

            // Assert
            Assert.IsTrue(success);
            Assert.That(result, Is.EqualTo(sample));
        }
Exemple #26
0
        public RedirectUrlSearchResult RedirectUrlsForContentItem(string contentUdi)
        {
            var redirectsResult = new RedirectUrlSearchResult();

            if (UdiParser.TryParse(contentUdi, out GuidUdi? guidIdi))
            {
                var redirects = _redirectUrlService.GetContentRedirectUrls(guidIdi !.Guid);
                var mapped    = _umbracoMapper.MapEnumerable <IRedirectUrl, ContentRedirectUrl>(redirects).WhereNotNull().ToList();
                redirectsResult.SearchResults = mapped;
                //not doing paging 'yet'
                redirectsResult.TotalCount  = mapped.Count;
                redirectsResult.CurrentPage = 1;
                redirectsResult.PageCount   = 1;
            }
            return(redirectsResult);
        }
        private static bool ConvertIdObjectToUdi(object id, out Udi guidId)
        {
            switch (id)
            {
            case string s:
                return(UdiParser.TryParse(s, out guidId));

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

            default:
                guidId = default;
                return(false);
            }
        }
    public void Returns_Udis_From_Data_Udi_Html_Attributes()
    {
        var input = @"<p>
    <div>
        <img src='/media/12312.jpg' data-udi='umb://media/D4B18427A1544721B09AC7692F35C264' />
    </div>
</p><p><img src='/media/234234.jpg' data-udi=""umb://media-type/B726D735E4C446D58F703F3FBCFC97A5"" /></p>";

        var imageSourceParser = new HtmlImageSourceParser(Mock.Of <IPublishedUrlProvider>());

        var result = imageSourceParser.FindUdisFromDataAttributes(input).ToList();

        Assert.AreEqual(2, result.Count);
        Assert.AreEqual(UdiParser.Parse("umb://media/D4B18427A1544721B09AC7692F35C264"), result[0]);
        Assert.AreEqual(UdiParser.Parse("umb://media-type/B726D735E4C446D58F703F3FBCFC97A5"), result[1]);
    }
Exemple #29
0
        public static void Converting_Unsupported_Object_To_A_Udi_Returns_False()
        {
            // Arrange
            UdiParser.ResetUdiTypes();

            var clearlyWillNotConvertToGuid = new StringBuilder(0);

            // Act
            bool success = UmbracoHelper.ConvertIdObjectToUdi(
                clearlyWillNotConvertToGuid,
                out Udi result
                );

            // Assert
            Assert.IsFalse(success);
            Assert.That(result, Is.Null);
        }
Exemple #30
0
        public void Converting_Hello_To_A_Udi_Returns_False()
        {
            // Arrange
            SetUpDependencyContainer();
            UdiParser.ResetUdiTypes();
            const string sample = "Hello";

            // Act
            bool success = UmbracoHelper.ConvertIdObjectToUdi(
                sample,
                out Udi result
                );

            // Assert
            Assert.IsFalse(success);
            Assert.That(result, Is.Null);
        }