Exemplo n.º 1
0
        private IDeliveryClient CreateClient()
        {
            var builder = DeliveryClientBuilder
                          .WithOptions(options =>
            {
                var opt2 = options.WithProjectId(ProjectId);

                if (!string.IsNullOrWhiteSpace(PreviewApiKey))
                {
                    return(opt2.UsePreviewApi(PreviewApiKey).Build());
                }

                if (!string.IsNullOrEmpty(ProductionApiKey))
                {
                    return(opt2.UseProductionApi(ProductionApiKey).Build());
                }

                return(opt2.UseProductionApi().Build());
            });

            foreach (var action in ConfigureClientActions)
            {
                action(builder);
            }

            return(builder.Build());
        }
Exemplo n.º 2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Adds services required for using options.
            services.AddOptions();

            // Register the IConfiguration instance which ProjectOptions binds against.
            services.Configure <ProjectOptions>(Configuration);

            var deliveryOptions = new DeliveryOptions();

            Configuration.GetSection(nameof(DeliveryOptions)).Bind(deliveryOptions);

            IDeliveryClient BuildBaseClient(IServiceProvider sp) => DeliveryClientBuilder
            .WithOptions(_ => deliveryOptions)
            .WithTypeProvider(new CustomTypeProvider())
            .WithContentLinkUrlResolver(new CustomContentLinkUrlResolver())
            .Build();

            // Use cached client version based on the use case
            services.AddCachingClient(BuildBaseClient, options =>
            {
                options.StaleContentExpiration = TimeSpan.FromSeconds(2);
                options.DefaultExpiration      = TimeSpan.FromMinutes(10);
            });
            //services.AddWebhookInvalidatedCachingClient(BuildBaseClient, options =>
            //{
            //    options.StaleContentExpiration = TimeSpan.FromSeconds(2);
            //    options.DefaultExpiration = TimeSpan.FromHours(24);
            //});

            HtmlHelperExtensions.ProjectOptions = Configuration.Get <ProjectOptions>();

            services.AddControllersWithViews();
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Adds services required for using options.
            services.AddOptions();

            // Register the IConfiguration instance which ProjectOptions binds against.
            services.Configure <ProjectOptions>(Configuration);

            var deliveryOptions = new DeliveryOptions();

            Configuration.GetSection(nameof(DeliveryOptions)).Bind(deliveryOptions);

            services.AddSingleton <IWebhookListener>(sp => new WebhookListener());
            services.AddSingleton <IDependentTypesResolver>(sp => new DependentFormatResolver());
            services.AddSingleton <ICacheManager>(sp => new ReactiveCacheManager(
                                                      sp.GetRequiredService <IOptions <ProjectOptions> >(),
                                                      sp.GetRequiredService <IMemoryCache>(),
                                                      sp.GetRequiredService <IDependentTypesResolver>(),
                                                      sp.GetRequiredService <IWebhookListener>()));
            services.AddScoped <KenticoCloudSignatureActionFilter>();

            services.AddSingleton <IDeliveryClient>(sp => new CachedDeliveryClient(
                                                        sp.GetRequiredService <IOptions <ProjectOptions> >(),
                                                        sp.GetRequiredService <ICacheManager>(),
                                                        DeliveryClientBuilder.WithOptions(_ => deliveryOptions)
                                                        .WithCodeFirstTypeProvider(new CustomTypeProvider())
                                                        .WithContentLinkUrlResolver(new CustomContentLinkUrlResolver())
                                                        .Build())
                                                    );

            HtmlHelperExtensions.ProjectOptions = services.BuildServiceProvider().GetService <IOptions <ProjectOptions> >();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Constructs delivery client
        /// </summary>
        private IDeliveryClient GetDeliveryClient(string projectId, bool usePreview, string previewApiKey)
        {
            var client = DeliveryClientBuilder.WithOptions(
                    builder =>
                    {
                        var config = builder
                            .WithProjectId(projectId);

                        if (!usePreview)
                        {
                            // do not use preview
                            return
                                config.UseProductionApi.WaitForLoadingNewContent
                                .Build();
                        }

                        if (string.IsNullOrEmpty(previewApiKey))
                        {
                            throw new ArgumentNullException($"Preview api key is not set for project '{projectId}'");
                        }

                        // use preview
                        return
                            config.UsePreviewApi(previewApiKey).WaitForLoadingNewContent
                                .Build();
                    })
                .WithInlineContentItemsResolver(new DefaultContentItemResolver())
                .WithTypeProvider(new CustomTypeProvider())
                .Build();


            return client;
        }
Exemplo n.º 5
0
        public static IServiceCollection AddKenticoDelivery(this IServiceCollection services, IConfiguration configuration)
        {
            services.Configure <KenticoOptions>(configuration.GetSection("KenticoOptions"))

            .AddSingleton <ICacheManager, CacheManager>()
            .AddTransient <IDependencyResolver, DependencyResolver>()
            .AddTransient <ICodeFirstTypeProvider, ContentTypeProvider>()
            .AddTransient <IContentLinkUrlResolver, ContentLinkUrlResolver>()

            .AddDeliveryClient(configuration)

            .AddScoped <IDeliveryClient>(sp => new CachedDeliveryClient(
                                             sp.GetRequiredService <ICacheManager>(),
                                             DeliveryClientBuilder
                                             .WithOptions(_ => sp.GetRequiredService <IOptionsSnapshot <KenticoOptions> >().Value)
                                             .WithCodeFirstTypeProvider(sp.GetRequiredService <ICodeFirstTypeProvider>())
                                             .WithContentLinkUrlResolver(sp.GetRequiredService <IContentLinkUrlResolver>())
                                             .Build(),
                                             CreatePreviewDeliveryClientOrNull(sp),
                                             sp.GetRequiredService <IDependencyResolver>()
                                             ));

            var kenticoOptions = services.BuildServiceProvider().GetRequiredService <IOptionsSnapshot <KenticoOptions> >().Value;

            HtmlHelperExtensions.ResponsiveImagesEnabled = kenticoOptions.ResponsiveImagesEnabled;
            HtmlHelperExtensions.ResponsiveWidths        = kenticoOptions.ResponsiveWidths;

            return(services);
        }
Exemplo n.º 6
0
        private CachedDeliveryClient GetCachedDeliveryClient(Action mockAction = null, Func <RequestCount, RequestCount> mockFunc = null, RequestCount actualHttpRequests = null)
        {
            HttpClient      httpClient      = null;
            DeliveryOptions deliveryOptions = null;

            if (mockAction != null)
            {
                InitClientPrerequisites(out httpClient, out deliveryOptions, mockAction: mockAction);
            }
            else if (mockFunc != null && actualHttpRequests != null)
            {
                InitClientPrerequisites(out httpClient, out deliveryOptions, mockFunc: mockFunc, actualHttpRequests: actualHttpRequests);
            }

            var projectOptions = Options.Create(new ProjectOptions
            {
                CacheTimeoutSeconds = 60,
                DeliveryOptions     = deliveryOptions
            });

            var memoryCacheOptions = Options.Create(new MemoryCacheOptions
            {
                Clock = new TestClock(),
                ExpirationScanFrequency = new TimeSpan(0, 0, 5)
            });

            var cacheManager = new ReactiveCacheManager(projectOptions, new MemoryCache(memoryCacheOptions), new DependentFormatResolver(), new WebhookListener());

            return(new CachedDeliveryClient(projectOptions, cacheManager
                                            , DeliveryClientBuilder.WithOptions(o => deliveryOptions).WithCodeFirstTypeProvider(new Models.CustomTypeProvider()).WithHttpClient(httpClient).Build()));
        }
        private IDeliveryClient GetCachedDeliveryClient()
        {
            mockHttp.When($"{baseUrl}/items")
            .WithQueryString(new[] { new KeyValuePair <string, string>("system.type", Article.Codename), new KeyValuePair <string, string>("limit", "3"), new KeyValuePair <string, string>("depth", "0"), new KeyValuePair <string, string>("order", "elements.post_date[asc]") })
            .Respond("application/json", File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "Fixtures\\CachedDeliveryClient\\articles.json")));

            var httpClient = mockHttp.ToHttpClient();

            var projectOptions = Options.Create(new ProjectOptions
            {
                CacheTimeoutSeconds = 60,
                DeliveryOptions     = new DeliveryOptions
                {
                    ProjectId = guid
                }
            });

            var memoryCacheOptions = Options.Create(new MemoryCacheOptions
            {
                Clock = new TestClock(),
                ExpirationScanFrequency = new TimeSpan(0, 0, 5)
            });

            var cacheManager = new ReactiveCacheManager(projectOptions, new MemoryCache(memoryCacheOptions), new DependentFormatResolver(), new WebhookListener());

            return(new CachedDeliveryClient(projectOptions, cacheManager, DeliveryClientBuilder.WithOptions(o => projectOptions.Value.DeliveryOptions).WithCodeFirstTypeProvider(new Models.CustomTypeProvider()).WithHttpClient(httpClient).Build()));
        }
Exemplo n.º 8
0
        public Scenario(IMemoryCache memoryCache, HttpClient httpClient, DeliveryOptions deliveryOptions, Dictionary <string, int> requestCounter)
        {
            _requestCounter = requestCounter;
            _cacheManager   = new CacheManager(memoryCache, Options.Create(new CacheOptions()));
            var baseClient = DeliveryClientBuilder.WithOptions(_ => deliveryOptions).WithHttpClient(httpClient).Build();

            CachingClient = new CachingDeliveryClient(_cacheManager, baseClient);
        }
Exemplo n.º 9
0
        public Scenario(IDistributedCache distributedCache, HttpClient httpClient, DeliveryOptions deliveryOptions, Dictionary <string, int> requestCounter)
        {
            _requestCounter = requestCounter;
            _cacheManager   = new DistributedCacheManager(distributedCache, Options.Create(new DeliveryCacheOptions()));
            var baseClient = DeliveryClientBuilder.WithOptions(_ => deliveryOptions).WithDeliveryHttpClient(new DeliveryHttpClient(httpClient)).Build();

            CachingClient = new DeliveryClientCache(_cacheManager, baseClient);
        }
Exemplo n.º 10
0
 public MovieListing(KontentKeys keys)
 {
     client = DeliveryClientBuilder
              .WithOptions(builder => builder
                           .WithProjectId(keys.ProjectId)
                           .UsePreviewApi(keys.PreviewApiKey)
                           .Build())
              .Build();
 }
Exemplo n.º 11
0
 private IDeliveryClient GetDeliveryClient()
 => DeliveryClientBuilder
 .WithOptions(builder => builder
              .WithProjectId(coreContext.Region.ProjectId)
              .UseProductionApi(coreContext.Region.DeliveryApiSecureAccessKey)
              .Build())
 .WithInlineContentItemsResolver(new Field())
 .WithTypeProvider(new KenticoKontentTypeProvider())
 .Build();
Exemplo n.º 12
0
        public Scenario(IMemoryCache memoryCache, CacheExpirationType cacheExpirationType, HttpClient httpClient, DeliveryOptions deliveryOptions, Dictionary <string, int> requestCounter)
        {
            _requestCounter = requestCounter;
            _cacheManager   = new MemoryCacheManager(memoryCache, Options.Create(new DeliveryCacheOptions {
                DefaultExpirationType = cacheExpirationType
            }));
            var baseClient = DeliveryClientBuilder.WithOptions(_ => deliveryOptions).WithDeliveryHttpClient(new DeliveryHttpClient(httpClient)).Build();

            CachingClient = new DeliveryClientCache(_cacheManager, baseClient);
        }
 public BaseController()
 {
     Client = DeliveryClientBuilder
              .WithOptions(builder => builder
                           .WithProjectId("09fc0115-dd4d-00c7-5bd9-5f73836aee81")
                           .UseProductionApi
                           .WithMaxRetryAttempts(5)
                           .Build())
              .Build();
 }
        public static IDeliveryClient CreateDeliveryClient()
        {
            // Use the provider to get environment variables
            ConfigurationManagerProvider provider = new ConfigurationManagerProvider();

            // Build DeliveryOptions with default or explicit values
            var options = provider.GetDeliveryOptions();

            options.ProjectId = options.ProjectId ?? AppSettingProvider.DefaultProjectId.ToString();
            var clientInstance = DeliveryClientBuilder.WithOptions(o => options)
                                 .WithTypeProvider(new CustomTypeProvider())
                                 .WithContentLinkUrlResolver(new CustomContentLinkUrlResolver()).Build();

            return(clientInstance);
        }
Exemplo n.º 15
0
        public void BuildWithDeliveryOptions_ReturnsDeliveryClientWithDeliveryOptions()
        {
            var guid = new Guid(ProjectId);

            var deliveryClient = (Delivery.DeliveryClient)DeliveryClientBuilder
                                 .WithOptions(builder => builder
                                              .WithProjectId(guid)
                                              .UsePreviewApi(PreviewApiKey)
                                              .WithCustomEndpoint(PreviewEndpoint)
                                              .Build()
                                              ).Build();

            Assert.Equal(ProjectId, deliveryClient.DeliveryOptions.ProjectId);
            Assert.True(deliveryClient.DeliveryOptions.UsePreviewApi);
            Assert.Equal(PreviewEndpoint, deliveryClient.DeliveryOptions.PreviewEndpoint);
        }
Exemplo n.º 16
0
        private static void InitKontent(KontentConfig config)
        {
            ContentManagementOptions cmoptions = new ContentManagementOptions
            {
                ProjectId = config.ProjectID,
                ApiKey    = config.ApiKey
            };

            KontentHelper.Init(
                DeliveryClientBuilder
                .WithOptions(builder => builder
                             .WithProjectId(config.ProjectID)
                             .UsePreviewApi(config.PreviewKey)
                             .Build())
                .Build(),
                new ContentManagementClient(cmoptions));
        }
Exemplo n.º 17
0
        private static IDeliveryClient CreatePreviewDeliveryClientOrNull(IServiceProvider sp)
        {
            var kenticoOptions = sp.GetRequiredService <IOptionsSnapshot <KenticoOptions> >().Value;

            if (!string.IsNullOrEmpty(kenticoOptions.PreviewApiKey))
            {
                kenticoOptions.UsePreviewApi           = true;
                kenticoOptions.UseSecuredProductionApi = false;

                return(DeliveryClientBuilder
                       .WithOptions(_ => kenticoOptions)
                       .WithCodeFirstTypeProvider(sp.GetRequiredService <ICodeFirstTypeProvider>())
                       .WithContentLinkUrlResolver(sp.GetRequiredService <IContentLinkUrlResolver>())
                       .Build());
            }

            return(null);
        }
        private static IDeliveryClient MockDeliveryClient(DeliveryOptions deliveryOptions, IDeliveryHttpClient deliveryHttpClient)
        {
            var contentLinkUrlResolver = A.Fake <IContentLinkUrlResolver>();
            var retryPolicy            = A.Fake <IRetryPolicy>();
            var retryPolicyProvider    = A.Fake <IRetryPolicyProvider>();

            A.CallTo(() => retryPolicyProvider.GetRetryPolicy())
            .Returns(retryPolicy);
            A.CallTo(() => retryPolicy.ExecuteAsync(A <Func <Task <HttpResponseMessage> > > ._))
            .ReturnsLazily(c => c.GetArgument <Func <Task <HttpResponseMessage> > >(0)());

            var client = DeliveryClientBuilder
                         .WithOptions(_ => deliveryOptions)
                         .WithDeliveryHttpClient(deliveryHttpClient)
                         .WithContentLinkUrlResolver(contentLinkUrlResolver)
                         .WithRetryPolicyProvider(retryPolicyProvider)
                         .WithTypeProvider(new CustomTypeProvider())
                         .Build();

            return(client);
        }
Exemplo n.º 19
0
        private static IDeliveryClient MockDeliveryClient(DeliveryOptions deliveryOptions, HttpClient httpClient)
        {
            var contentLinkUrlResolver   = A.Fake <IContentLinkUrlResolver>();
            var modelProvider            = A.Fake <IModelProvider>();
            var resiliencePolicyProvider = A.Fake <IResiliencePolicyProvider>();

            A.CallTo(() => resiliencePolicyProvider.Policy)
            .Returns(Policy
                     .HandleResult <HttpResponseMessage>(result => true)
                     .RetryAsync(deliveryOptions.MaxRetryAttempts));

            var client = DeliveryClientBuilder
                         .WithOptions(_ => deliveryOptions)
                         .WithHttpClient(httpClient)
                         .WithContentLinkUrlResolver(contentLinkUrlResolver)
                         .WithModelProvider(modelProvider)
                         .WithResiliencePolicyProvider(resiliencePolicyProvider)
                         .Build();

            return(client);
        }
        public void OnPost()
        {
            var projectId = Request.Form["ProjectId"];

            _logger.Log(LogLevel.Information, projectId);

            if (!Guid.TryParse(projectId, out Guid projectGuid))
            {
                // Invalid project ID
                return;
            }

            var client = DeliveryClientBuilder
                         .WithOptions(builder => builder
                                      .WithProjectId(projectId)
                                      .UseProductionApi()
                                      .Build())
                         .Build();

            var typesResult = client.GetTypesAsync();

            Types = typesResult.Result.Types;
        }
Exemplo n.º 21
0
        private static IDeliveryClient CreateMockDeliveryClient(DeliveryOptions deliveryOptions, HttpClient httpClient, Func <IOptionalClientSetup, IOptionalClientSetup> configureClient)
        {
            //var contentLinkUrlResolver = A.Fake<IContentLinkUrlResolver>();
            //var modelProvider = A.Fake<IModelProvider>();
            var retryPolicy         = A.Fake <IRetryPolicy>();
            var retryPolicyProvider = A.Fake <IRetryPolicyProvider>();

            A.CallTo(() => retryPolicyProvider.GetRetryPolicy())
            .Returns(retryPolicy);
            A.CallTo(() => retryPolicy.ExecuteAsync(A <Func <Task <HttpResponseMessage> > > ._))
            .ReturnsLazily(c => c.GetArgument <Func <Task <HttpResponseMessage> > >(0)());

            var client = DeliveryClientBuilder
                         .WithOptions(_ => deliveryOptions)
                         .WithDeliveryHttpClient(new DeliveryHttpClient(httpClient))
                         //.WithContentLinkUrlResolver(contentLinkUrlResolver)
                         //.WithModelProvider(modelProvider)
                         .ApplyIfNotNull(configureClient)
                         .WithRetryPolicyProvider(retryPolicyProvider)
                         .Build();

            return(client);
        }
Exemplo n.º 22
0
        private IDeliveryClient GetDeliveryClient(Action mockAction)
        {
            InitClientPrerequisites(out HttpClient httpClient, out DeliveryOptions deliveryOptions, mockAction);

            return(DeliveryClientBuilder.WithOptions(o => deliveryOptions).WithCodeFirstTypeProvider(new Models.CustomTypeProvider()).WithHttpClient(httpClient).Build());
        }