Ejemplo n.º 1
0
        protected static IContentEntity CreateContent(Guid id, Guid refId, Guid assetId, NamedContentData data = null, NamedContentData dataDraft = null)
        {
            var now = SystemClock.Instance.GetCurrentInstant();

            data = data ??
                   new NamedContentData()
                   .AddField("my-string",
                             new ContentFieldData()
                             .AddValue("de", "value"))
                   .AddField("my-assets",
                             new ContentFieldData()
                             .AddValue("iv", JsonValue.Array(assetId.ToString())))
                   .AddField("my-number",
                             new ContentFieldData()
                             .AddValue("iv", 1.0))
                   .AddField("my-boolean",
                             new ContentFieldData()
                             .AddValue("iv", true))
                   .AddField("my-datetime",
                             new ContentFieldData()
                             .AddValue("iv", now))
                   .AddField("my-tags",
                             new ContentFieldData()
                             .AddValue("iv", JsonValue.Array("tag1", "tag2")))
                   .AddField("my-references",
                             new ContentFieldData()
                             .AddValue("iv", JsonValue.Array(refId.ToString())))
                   .AddField("my-geolocation",
                             new ContentFieldData()
                             .AddValue("iv", JsonValue.Object().Add("latitude", 10).Add("longitude", 20)))
                   .AddField("my-json",
                             new ContentFieldData()
                             .AddValue("iv", JsonValue.Object().Add("value", 1)))
                   .AddField("my-localized",
                             new ContentFieldData()
                             .AddValue("de-DE", "de-DE"))
                   .AddField("my-array",
                             new ContentFieldData()
                             .AddValue("iv", JsonValue.Array(
                                           JsonValue.Object()
                                           .Add("nested-boolean", true)
                                           .Add("nested-number", 1),
                                           JsonValue.Object()
                                           .Add("nested-boolean", false)
                                           .Add("nested-number", 2))));

            var content = new ContentEntity
            {
                Id             = id,
                Version        = 1,
                Created        = now,
                CreatedBy      = new RefToken(RefTokenType.Subject, "user1"),
                LastModified   = now,
                LastModifiedBy = new RefToken(RefTokenType.Subject, "user2"),
                Data           = data,
                DataDraft      = dataDraft
            };

            return(content);
        }
Ejemplo n.º 2
0
        public async Task Should_add_error_if_array_item_field_is_defined()
        {
            var schema =
                new Schema("my-schema")
                .AddArray(1, "my-array", Partitioning.Invariant, array => array
                          .AddUI(101, "my-ui"));

            var data =
                new ContentData()
                .AddField("my-array", new ContentFieldData()
                          .AddJsonValue(
                              JsonValue.Array(
                                  JsonValue.Object()
                                  .Add("my-ui", null))));

            var dataErrors = new List <ValidationError>();

            await data.ValidateAsync(x => InvariantPartitioning.Instance, dataErrors, schema);

            dataErrors.Should().BeEquivalentTo(
                new[]
            {
                new ValidationError("Value must not be defined.", "my-array.iv[1].my-ui")
            });
        }
        private (TemplateVars, IAssetEntity) SetupAssetVars(int fileSize = 100)
        {
            var assetId = DomainId.NewGuid();
            var asset   = CreateAsset(assetId, 1, fileSize);

            var @event = new EnrichedContentEvent
            {
                Data =
                    new ContentData()
                    .AddField("assets",
                              new ContentFieldData()
                              .AddInvariant(JsonValue.Array(assetId))),
                AppId = appId
            };

            A.CallTo(() => assetQuery.FindAsync(A <Context> ._, assetId, EtagVersion.Any, A <CancellationToken> ._))
            .Returns(asset);

            SetupText(@event.Id, Encoding.UTF8.GetBytes("Hello Asset"));

            var vars = new TemplateVars
            {
                ["event"] = @event
            };

            return(vars, asset);
        }
Ejemplo n.º 4
0
        private (ScriptVars, IAssetEntity[]) SetupAssetsVars(int fileSize = 100)
        {
            var assetId1 = DomainId.NewGuid();
            var asset1   = CreateAsset(assetId1, 1, fileSize);
            var assetId2 = DomainId.NewGuid();
            var asset2   = CreateAsset(assetId1, 2, fileSize);

            var user = new ClaimsPrincipal();

            var data =
                new ContentData()
                .AddField("assets",
                          new ContentFieldData()
                          .AddInvariant(JsonValue.Array(assetId1, assetId2)));

            A.CallTo(() => assetQuery.QueryAsync(
                         A <Context> .That.Matches(x => x.App.Id == appId.Id && x.User == user), null, A <Q> .That.HasIds(assetId1, assetId2), A <CancellationToken> ._))
            .Returns(ResultList.CreateFrom(2, asset1, asset2));

            var vars = new ScriptVars
            {
                ["data"]    = data,
                ["appId"]   = appId.Id,
                ["appName"] = appId.Name,
                ["user"]    = user
            };

            return(vars, new[] { asset1, asset2 });
        }
Ejemplo n.º 5
0
        private (ScriptVars, IContentEntity[]) SetupReferenceVars(int count)
        {
            var references   = Enumerable.Range(0, count).Select((x, i) => CreateReference(i + 1)).ToArray();
            var referenceIds = references.Select(x => x.Id);

            var user = new ClaimsPrincipal();

            var data =
                new ContentData()
                .AddField("references",
                          new ContentFieldData()
                          .AddInvariant(JsonValue.Array(referenceIds)));

            A.CallTo(() => contentQuery.QueryAsync(
                         A <Context> .That.Matches(x => x.App.Id == appId.Id && x.User == user), A <Q> .That.HasIds(referenceIds), A <CancellationToken> ._))
            .Returns(ResultList.CreateFrom(2, references));

            var vars = new ScriptVars
            {
                ["appId"]   = appId.Id,
                ["data"]    = data,
                ["dataOld"] = null,
                ["user"]    = user
            };

            return(vars, references);
        }
        private (TemplateVars, IAssetEntity[]) SetupAssetsVars(int fileSize = 100)
        {
            var assetId1 = DomainId.NewGuid();
            var asset1   = CreateAsset(assetId1, 1, fileSize);
            var assetId2 = DomainId.NewGuid();
            var asset2   = CreateAsset(assetId2, 2, fileSize);

            var @event = new EnrichedContentEvent
            {
                Data =
                    new ContentData()
                    .AddField("assets",
                              new ContentFieldData()
                              .AddInvariant(JsonValue.Array(assetId1, assetId2))),
                AppId = appId
            };

            A.CallTo(() => assetQuery.FindAsync(A <Context> ._, assetId1, EtagVersion.Any, A <CancellationToken> ._))
            .Returns(asset1);

            A.CallTo(() => assetQuery.FindAsync(A <Context> ._, assetId2, EtagVersion.Any, A <CancellationToken> ._))
            .Returns(asset2);

            var vars = new TemplateVars
            {
                ["event"] = @event
            };

            return(vars, new[] { asset1, asset2 });
        }
Ejemplo n.º 7
0
        public async Task Should_add_error_if_array_item_field_is_defined()
        {
            var schema =
                new Schema("my-schema")
                .AddArray(1, "my-array", Partitioning.Invariant, array => array
                          .AddUI(101, "my-ui"));

            var data =
                new NamedContentData()
                .AddField("my-array", new ContentFieldData()
                          .AddJsonValue(
                              JsonValue.Array(
                                  JsonValue.Object()
                                  .Add("my-ui", null))));

            var validationContext =
                new ValidationContext(
                    Guid.NewGuid(),
                    Guid.NewGuid(),
                    (c, s) => null !,
                    (s) => null !,
                    (c) => null !);

            var validator = new ContentValidator(schema, x => InvariantPartitioning.Instance, validationContext);

            await validator.ValidateAsync(data);

            validator.Errors.Should().BeEquivalentTo(
                new[] { new ValidationError("Value must not be defined.", "my-array[1].my-ui") });
        }
Ejemplo n.º 8
0
        public async Task Should_add_error_if_array_field_has_required_nested_field()
        {
            schema = schema.AddArray(1, "my-field", Partitioning.Invariant, f => f.
                                     AddNumber(2, "my-nested", new NumberFieldProperties {
                IsRequired = true
            }));

            var data =
                new ContentData()
                .AddField("my-field",
                          new ContentFieldData()
                          .AddInvariant(
                              JsonValue.Array(
                                  JsonValue.Object(),
                                  JsonValue.Object().Add("my-nested", 1),
                                  JsonValue.Object())));

            await data.ValidatePartialAsync(languagesConfig.ToResolver(), errors, schema);

            errors.Should().BeEquivalentTo(
                new List <ValidationError>
            {
                new ValidationError("Field is required.", "my-field.iv[1].my-nested"),
                new ValidationError("Field is required.", "my-field.iv[3].my-nested")
            });
        }
Ejemplo n.º 9
0
        private (ScriptVars, IAssetEntity[]) SetupAssetsVars(int count, int fileSize = 100, AssetType type = AssetType.Image)
        {
            var assets = Enumerable.Range(0, count).Select(x => CreateAsset(1, fileSize, type)).ToArray();
            var assetIds = assets.Select(x => x.Id);

            var user = new ClaimsPrincipal();

            var data =
                new ContentData()
                    .AddField("assets",
                        new ContentFieldData()
                            .AddInvariant(JsonValue.Array(assetIds)));

            A.CallTo(() => assetQuery.QueryAsync(
                    A<Context>.That.Matches(x => x.App.Id == appId.Id && x.User == user), null, A<Q>.That.HasIds(assetIds), A<CancellationToken>._))
                .Returns(ResultList.CreateFrom(2, assets));

            var vars = new ScriptVars
            {
                ["data"] = data,
                ["appId"] = appId.Id,
                ["appName"] = appId.Name,
                ["user"] = user
            };

            return (vars, assets);
        }
Ejemplo n.º 10
0
        public void Should_convert_name_to_name()
        {
            var field =
                Fields.Array(1, "1", Partitioning.Invariant,
                             Fields.Number(1, "field1"),
                             Fields.Number(2, "field2").Hide());

            var input =
                new ContentFieldData()
                .AddJsonValue(
                    JsonValue.Array(
                        JsonValue.Object()
                        .Add("field1", 100)
                        .Add("field2", 200)
                        .Add("invalid", 300)));

            var actual = FieldConverters.ForNestedName2Name(ValueConverters.ExcludeHidden())(input, field);

            var expected =
                new ContentFieldData()
                .AddJsonValue(
                    JsonValue.Array(
                        JsonValue.Object()
                        .Add("field1", 100)));

            Assert.Equal(expected, actual);
        }
Ejemplo n.º 11
0
        public async Task HandleAsync(CommandContext context, NextDelegate next)
        {
            await next(context);

            if (context.Command is UpdateContent update && context.IsCompleted && update.SchemaId.Name == "source")
            {
                // After a change is made, the content is put to the command context.
                var content = context.Result <IContentEntity>();

                var contentPrevious =
                    await contentLoader.GetAsync(
                        content.AppId.Id,
                        content.Id,
                        content.Version - 1);

                // The data might have been changed within the domain object. Therefore we do not use the data fro mthe command.
                var oldReferenceId = GetReference(contentPrevious?.Data);
                var newReferenceId = GetReference(content.Data);

                // If nothing has been changed we can just stop here.
                if (newReferenceId == oldReferenceId)
                {
                    return;
                }

                if (oldReferenceId != null)
                {
                    var oldReferenced = await contentLoader.GetAsync(content.AppId.Id, DomainId.Create(oldReferenceId));

                    if (oldReferenced != null)
                    {
                        var data = oldReferenced.Data.Clone();

                        // Remove the reference from the old referenced content.
                        data.Remove("referencing");

                        await UpdateReferencing(context, oldReferenced, data);
                    }
                }

                if (newReferenceId != null)
                {
                    var newReferenced = await contentLoader.GetAsync(content.AppId.Id, DomainId.Create(newReferenceId));

                    if (newReferenced != null)
                    {
                        var data = newReferenced.Data.Clone();

                        // Add the reference to the new referenced content.
                        data["referencing"] = new ContentFieldData
                        {
                            ["iv"] = JsonValue.Array(content.Id)
                        };

                        await UpdateReferencing(context, newReferenced, data);
                    }
                }
            }
        }
Ejemplo n.º 12
0
        public void Should_get_default_value_from_assets_field()
        {
            var field =
                Fields.Assets(1, "1", Partitioning.Invariant,
                              new AssetsFieldProperties());

            Assert.Equal(JsonValue.Array(), DefaultValueFactory.CreateDefaultValue(field, now));
        }
Ejemplo n.º 13
0
        public IJsonValue Visit(IField <ReferencesFieldProperties> field)
        {
            if (oldReferences?.Contains(field.Properties.SingleId()) == true)
            {
                return(JsonValue.Array());
            }

            return(CleanIds());
        }
Ejemplo n.º 14
0
        public async Task Should_add_error_if_component_is_not_valid()
        {
            var(_, sut) = Field(new ComponentsFieldProperties());

            await sut.ValidateAsync(JsonValue.Array(JsonValue.Create("Invalid")), errors);

            errors.Should().BeEquivalentTo(
                new[] { "Invalid json object, expected object with 'schemaId' field." });
        }
Ejemplo n.º 15
0
        public IJsonValue Visit(IField <ReferencesFieldProperties> field)
        {
            if (oldReferences.Contains(field.Properties.SchemaId))
            {
                return(JsonValue.Array());
            }

            return(CleanIds());
        }
Ejemplo n.º 16
0
        public void Should_format_references_field_with_multiple_items()
        {
            var value = JsonValue.Array(JsonValue.Object(), JsonValue.Object());

            var field = Fields.References(1, "field", Partitioning.Invariant);

            var formatted = StringFormatter.Format(field, value);

            Assert.Equal("2 References", formatted);
        }
Ejemplo n.º 17
0
        public void Should_format_assets_field_with_single_item()
        {
            var value = JsonValue.Array(JsonValue.Object());

            var field = Fields.Assets(1, "field", Partitioning.Invariant);

            var formatted = StringFormatter.Format(value, field);

            Assert.Equal("1 Asset", formatted);
        }
Ejemplo n.º 18
0
        public void Should_format_array_field_with_multiple_items()
        {
            var value = JsonValue.Array(JsonValue.Object(), JsonValue.Object());

            var field = Fields.Array(1, "field", Partitioning.Invariant);

            var formatted = StringFormatter.Format(value, field);

            Assert.Equal("2 Items", formatted);
        }
Ejemplo n.º 19
0
        public void Should_format_tags_field()
        {
            var value = JsonValue.Array("hello", "squidex", "and", "team");

            var field = Fields.Tags(1, "field", Partitioning.Invariant);

            var formatted = StringFormatter.Format(value, field);

            Assert.Equal("hello, squidex, and, team", formatted);
        }
Ejemplo n.º 20
0
        public void Should_format_assets_field_without_items()
        {
            var value = JsonValue.Array();

            var field = Fields.Assets(1, "field", Partitioning.Invariant);

            var formatted = StringFormatter.Format(value, field);

            Assert.Equal("0 Assets", formatted);
        }
Ejemplo n.º 21
0
        public void Should_not_throw_exceptions_when_changing_arrays()
        {
            var original =
                new NamedContentData()
                .AddField("obj",
                          new ContentFieldData()
                          .AddJsonValue(JsonValue.Array()));

            ExecuteScript(original, "data.obj.iv[0] = 1");
        }
Ejemplo n.º 22
0
        public async Task Should_add_error_if_tag_value_is_null()
        {
            var sut = Field(new TagsFieldProperties {
                IsRequired = true
            });

            await sut.ValidateAsync(JsonValue.Array(JsonValue.Null), errors);

            errors.Should().BeEquivalentTo(
                new[] { "[1]: Field is required." });
        }
Ejemplo n.º 23
0
 private static IJsonValue Array(string[]?values)
 {
     if (values != null)
     {
         return(JsonValue.Array(values));
     }
     else
     {
         return(JsonValue.Array());
     }
 }
Ejemplo n.º 24
0
        public static JsonArray ToJsonArray(this HashSet <Guid> ids)
        {
            var result = JsonValue.Array();

            foreach (var id in ids)
            {
                result.Add(JsonValue.Create(id.ToString()));
            }

            return(result);
        }
Ejemplo n.º 25
0
 private static IJsonValue Array(IEnumerable <string>?values)
 {
     if (values != null)
     {
         return(JsonValue.Array(values));
     }
     else
     {
         return(JsonValue.Array());
     }
 }
Ejemplo n.º 26
0
        public async Task Should_add_error_if_tag_value_is_null()
        {
            var sut = Field(new TagsFieldProperties {
                IsRequired = true
            });

            await sut.ValidateAsync(JsonValue.Array(JsonValue.Null), errors);

            errors.Should().BeEquivalentTo(
                new[] { "Invalid json type, expected array of strings." });
        }
Ejemplo n.º 27
0
        public void Should_not_convert_asset_ids_if_field_name_does_not_match(string path)
        {
            var field = Fields.Assets(1, "assets", Partitioning.Invariant);

            var source = JsonValue.Array(id1, id2);

            var expected = source;

            var result = ValueConverters.ResolveAssetUrls(appId, HashSet.Of(path), urlGenerator)(source, field, null);

            Assert.Equal(expected, result);
        }
Ejemplo n.º 28
0
        public void Should_not_convert_nested_asset_ids_when_field_name_does_not_match(string path)
        {
            var field = Fields.Array(1, "parent", Partitioning.Invariant, Fields.Assets(11, "assets"));

            var source = JsonValue.Array(id1, id2);

            var expected = source;

            var result = ValueConverters.ResolveAssetUrls(HashSet.Of(path), urlGenerator)(source, field.Fields[0], field);

            Assert.Equal(expected, result);
        }
Ejemplo n.º 29
0
        public void Should_convert_asset_ids_to_urls(string path)
        {
            var field = Fields.Assets(1, "assets", Partitioning.Invariant);

            var source = JsonValue.Array(id1, id2);

            var expected = JsonValue.Array($"url/to/{id1}", $"url/to/{id2}");

            var result = ValueConverters.ResolveAssetUrls(HashSet.Of(path), urlGenerator)(source, field);

            Assert.Equal(expected, result);
        }
Ejemplo n.º 30
0
        public void Should_not_throw_exceptions_if_changing_arrays()
        {
            var original =
                new ContentData()
                .AddField("obj",
                          new ContentFieldData()
                          .AddInvariant(JsonValue.Array()));

            const string script = @"
                data.obj.iv[0] = 1
            ";

            ExecuteScript(original, script);
        }