Exemple #1
0
        // Common method used by AddFileContent, AddResourceContent and
        // AddAddFileContentWithFallbackToResources methods.
        private static IServiceCollection AddPredefinedContent <TContentSet>(this IServiceCollection services,
                                                                             string fileExtension,
                                                                             Action <IServiceCollection, Type, IList <string> > registrationAction, // Delegate contains all needed params to avoid closures
                                                                             params string[] args)
            where TContentSet : ContentSetBase, new()
        {
            if (string.IsNullOrWhiteSpace(fileExtension))
            {
                throw new ArgumentException(Errors.InvalidFileExtension, nameof(fileExtension));
            }

            registrationAction(services, typeof(TContentSet), args);

            // Register the content set type (TContentSet) with the container.
            services.AddSingleton(sp =>
            {
                IContentSet internalContentSet = sp.GetRequiredService <IContentManager>().GetContentSet(typeof(TContentSet).AssemblyQualifiedName);
                return(new TContentSet
                {
                    ContentSet = internalContentSet,
                });
            });

            return(services);
        }
Exemple #2
0
 public JsonTests(ContentManagerFixture fixture)
 {
     if (fixture is null)
     {
         throw new ArgumentNullException(nameof(fixture));
     }
     _contentSet = fixture.ContentManager.GetContentSet("Json");
 }
Exemple #3
0
        public async Task Able_to_load_embedded_resources()
        {
            IContentSet content = _contentManager.GetContentSet("Text");
            string      value   = await content.GetAsStringAsync("Content")
                                  .ConfigureAwait(false);

            content.ShouldNotBeNull();
            value.ShouldBe("This is the content.");
        }
Exemple #4
0
        public static IEnumerable <T> GetJsonAsList <T>(this IContentSet contentSet, string name,
                                                        Func <T, bool>?predicate = null, JsonSerializerOptions?serializerOptions = null)
        {
            IEnumerable <T> value = contentSet.GetAsJson <IEnumerable <T> >(name, serializerOptions);

            if (predicate != null)
            {
                value = value.Where(predicate);
            }
            return(value);
        }
Exemple #5
0
        public static Task <T> GetAsJsonAsync <T>(this IContentSet contentSet,
                                                  string name,
                                                  JsonSerializerOptions?serializerOptions = null)
        {
            if (contentSet is null)
            {
                throw new ArgumentNullException(nameof(contentSet));
            }

            return(contentSet.GetAsJsonAsyncInternal <T>(name, serializerOptions));
        }
Exemple #6
0
        private static async Task <T> GetJsonAsListEntryInternal <T>(this IContentSet contentSet,
                                                                     string name,
                                                                     Func <T, bool> predicate,
                                                                     JsonSerializerOptions?serializerOptions = null)
        {
            IEnumerable <T> collection = await contentSet.GetAsJson <IEnumerable <T> >(name, serializerOptions)
                                         .ConfigureAwait(false);

            T result = collection.FirstOrDefault(predicate);

            return(result);
        }
Exemple #7
0
        public static Task <T> GetJsonAsListEntry <T>(this IContentSet contentSet,
                                                      string name,
                                                      Func <T, bool> predicate,
                                                      JsonSerializerOptions?serializerOptions = null)
        {
            if (predicate is null)
            {
                throw new ArgumentNullException(nameof(predicate));
            }

            return(contentSet.GetJsonAsListEntryInternal(name, predicate, serializerOptions));
        }
Exemple #8
0
        public static async Task <IEnumerable <T> > GetJsonAsListAsync <T>(this IContentSet contentSet, string name,
                                                                           Func <T, bool>?predicate = null, JsonSerializerOptions?serializerOptions = null)
        {
            IEnumerable <T> value = await contentSet.GetAsJsonAsync <IEnumerable <T> >(name, serializerOptions)
                                    .ConfigureAwait(false);

            if (predicate != null)
            {
                value = value.Where(predicate);
            }
            return(value);
        }
Exemple #9
0
        public static T GetAsJson <T>(this IContentSet contentSet, string name,
                                      JsonSerializerOptions?serializerOptions = null)
        {
            if (contentSet is null)
            {
                throw new ArgumentNullException(nameof(contentSet));
            }

            string json = contentSet.GetAsString(name);

            return(JsonSerializer.Deserialize <T>(json, serializerOptions ?? JsonOptions.SerializerOptions));
        }
Exemple #10
0
        private static async Task <T?> GetJsonAsCustomListEntryInternal <T>(this IContentSet contentSet,
                                                                            string name,
                                                                            params object[] args)
            where T : class
        {
            string json = await contentSet.GetAsString(name).ConfigureAwait(false);

            JsonDocument doc = JsonDocument.Parse(json, new JsonDocumentOptions
            {
                AllowTrailingCommas = true,
                CommentHandling     = JsonCommentHandling.Skip,
            });

            foreach (JsonElement item in doc.RootElement.EnumerateArray())
            {
                if (!item.TryGetProperty("Inputs", out JsonElement inputsProperty))
                {
                    throw new JsonException($"Cannot find Inputs property in the JSON item {item}.");
                }
                if (inputsProperty.ValueKind != JsonValueKind.Array)
                {
                    throw new JsonException($"The Inputs property must be an array in the JSON item {item}.");
                }
                if (inputsProperty.GetArrayLength() != args.Length)
                {
                    throw new JsonException($"Invalid number of arguments in the Inputs property for the JSON item {item}.");
                }

                bool inputsMatch             = true;
                List <JsonElement> inputArgs = inputsProperty.EnumerateArray().ToList();
                for (var i = 0; i < inputArgs.Count; i++)
                {
                    if (!inputArgs[i].ToString().Equals(args[i].ToString(), StringComparison.Ordinal))
                    {
                        inputsMatch = false;
                        break;
                    }
                }

                if (inputsMatch)
                {
                    if (!item.TryGetProperty("Data", out JsonElement dataProperty))
                    {
                        throw new JsonException($"Cannot find Data property in the JSON item {item}.");
                    }
                    T value = JsonSerializer.Deserialize <T>(dataProperty.GetRawText(), JsonOptions.SerializerOptions);
                    return(value);
                }
            }

            return(default);
Exemple #11
0
        public async Task Can_inject_content_manager_and_retrieve_content()
        {
            var manager = _fixture.ServiceProvider.GetService <IContentManager>();

            manager.ShouldNotBeNull();

            IContentSet contentSet = manager.GetContentSet("Text");

            contentSet.ShouldNotBeNull();

            string value = await contentSet.GetAsString("Content").ConfigureAwait(false);

            value.ShouldBe("This is the content.");
        }
Exemple #12
0
        public static T GetJsonAsListEntry <T>(this IContentSet contentSet,
                                               string name,
                                               Func <T, bool> predicate,
                                               JsonSerializerOptions?serializerOptions = null)
        {
            if (predicate is null)
            {
                throw new ArgumentNullException(nameof(predicate));
            }

            IEnumerable <T> collection = contentSet.GetAsJson <IEnumerable <T> >(name, serializerOptions);
            T result = collection.FirstOrDefault(predicate);

            return(result);
        }
Exemple #13
0
        public static Task <T?> GetJsonAsCustomListEntry <T>(this IContentSet contentSet,
                                                             string name,
                                                             params object[] args)
            where T : class
        {
            if (contentSet is null)
            {
                throw new ArgumentNullException(nameof(contentSet));
            }

            //IReadOnlyList<Type> argTypes = args.Select(arg => arg.GetType()).ToList();

            //TODO: Check all arg types are valid JSON types - number, string, boolean

            return(contentSet.GetJsonAsCustomListEntryInternal <T>(name, args));
        }
Exemple #14
0
        private static async Task <T> GetAsJsonAsyncInternal <T>(this IContentSet contentSet,
                                                                 string name,
                                                                 JsonSerializerOptions?serializerOptions = null)
        {
            string json = await contentSet.GetAsStringAsync(name).ConfigureAwait(false);

            using var ms = new MemoryStream();
#pragma warning disable CA2000 // Dispose objects before losing scope
            var writer = new StreamWriter(ms, Encoding.UTF8);
#pragma warning restore CA2000 // Dispose objects before losing scope
            writer.Write(json);
            writer.Flush();
            ms.Position = 0;

            return(await JsonSerializer.DeserializeAsync <T>(ms, serializerOptions ?? JsonOptions.SerializerOptions)
                   .ConfigureAwait(false));
        }
Exemple #15
0
        /// <summary>
        ///     Registers content from one or more sources that can be injected into the application.
        ///     <para/>
        ///     This method associates the content with a specific <see cref="ContentSetBase"/> type, so
        ///     to access it later, you can simply inject the <typeparamref name="TContentSet"/> type
        ///     into your code.
        /// </summary>
        /// <typeparam name="TContentSet">
        ///     The content set class to register with the DI container.
        /// </typeparam>
        /// <param name="services">The services collection.</param>
        /// <param name="name">
        ///     A name that can be used to reference this content when accessing through an injected
        ///     <see cref="IContentManager"/>.
        /// </param>
        /// <param name="sourceBuilder">
        ///     A function used to set up the source for the content, along with any fallback sources.
        /// </param>
        /// <returns>A reference to this instance after the operation has completed.</returns>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if the <paramref name="services"/> or <paramref name="sourceBuilder"/> parameters
        ///     are <c>null</c>.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///     Thrown if the <paramref name="name"/> parameter is <c>null</c>, empty or whitespaces.
        /// </exception>
        public static IServiceCollection AddContent <TContentSet>(this IServiceCollection services,
                                                                  string name,
                                                                  Action <ContentBuilder> sourceBuilder)
            where TContentSet : ContentSetBase, new()
        {
            // Adds the content as normal
            services.AddContent(name, sourceBuilder);

            // Register the content set type (TContentSet) with the container.
            services.AddSingleton(sp =>
            {
                IContentSet internalContentSet = sp.GetRequiredService <IContentManager>().GetContentSet(name);
                return(new TContentSet
                {
                    ContentSet = internalContentSet,
                });
            });

            return(services);
        }