public async void GetItemsAsync_SerializeAndDeserialize()
        {
            // Arrange
            string url = $"{_baseUrl}/items";

            _mockHttp
            .When(url)
            .WithQueryString("system.type=article")
            .Respond("application/json",
                     await File.ReadAllTextAsync(Path.Combine(Environment.CurrentDirectory, $"Fixtures{Path.DirectorySeparatorChar}full_articles.json")));

            var client = DeliveryClientBuilder.WithProjectId(_projectId).WithTypeProvider(new CustomTypeProvider()).WithDeliveryHttpClient(new DeliveryHttpClient(_mockHttp.ToHttpClient())).Build();

            // Act
            var response = await client.GetItemsAsync <Article>();

            var serializedResponse   = response.ToBson();
            var deserializedResponse = serializedResponse.FromBson <DeliveryItemListingResponse <Article> >();

            // Assert item equality
            response.Should().BeEquivalentTo(deserializedResponse, o => o.IgnoringCyclicReferences().DateTimesBsonCorrection());

            // Assert the first item - check collections and DateTimes
            var firstItem             = response.Items.FirstOrDefault();
            var firstDeserializedItem = deserializedResponse.Items.FirstOrDefault();

            Assert.NotEmpty(firstDeserializedItem.TeaserImage);
            Assert.NotEmpty(firstDeserializedItem.Personas);
            Assert.Equal(firstItem.PostDate, firstDeserializedItem.PostDate);
        }
Exemplo n.º 2
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;
        }
        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()));
        }
        // 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.º 5
0
        public async Task <ActionResult> Index()
        {
            IDeliveryClient c = DeliveryClientBuilder.WithProjectId("975bf280-fd91-488c-994c-2f04416e5ee3").Build();
            var             i = await c.GetItemAsync("on_roasts");

            return(View());
        }
Exemplo n.º 6
0
        public void BuildWithOptionalSteps_ReturnsDeliveryClientWithSetInstances()
        {
            var mockModelProvider                         = A.Fake <IModelProvider>();
            var mockRetryPolicyProvider                   = A.Fake <IRetryPolicyProvider>();
            var mockPropertyMapper                        = A.Fake <IPropertyMapper>();
            var mockContentLinkUrlResolver                = A.Fake <IContentLinkUrlResolver>();
            var mockInlineContentItemsProcessor           = A.Fake <IInlineContentItemsProcessor>();
            var mockDefaultInlineContentItemsResolver     = A.Fake <IInlineContentItemsResolver <object> >();
            var mockUnretrievedInlineContentItemsResolver = A.Fake <IInlineContentItemsResolver <UnretrievedContentItem> >();
            var mockAnContentItemsResolver                = A.Fake <IInlineContentItemsResolver <CompleteContentItemModel> >();
            var mockTypeProvider       = A.Fake <ITypeProvider>();
            var mockDeliveryHttpClient = new DeliveryHttpClient(new MockHttpMessageHandler().ToHttpClient());

            var deliveryClient = (Delivery.DeliveryClient)DeliveryClientBuilder
                                 .WithProjectId(ProjectId)
                                 .WithDeliveryHttpClient(mockDeliveryHttpClient)
                                 .WithContentLinkUrlResolver(mockContentLinkUrlResolver)
                                 .WithInlineContentItemsProcessor(mockInlineContentItemsProcessor)
                                 .WithInlineContentItemsResolver(mockDefaultInlineContentItemsResolver)
                                 .WithInlineContentItemsResolver(mockUnretrievedInlineContentItemsResolver)
                                 .WithInlineContentItemsResolver(mockAnContentItemsResolver)
                                 .WithModelProvider(mockModelProvider)
                                 .WithPropertyMapper(mockPropertyMapper)
                                 .WithRetryPolicyProvider(mockRetryPolicyProvider)
                                 .WithTypeProvider(mockTypeProvider)
                                 .Build();

            Assert.Equal(ProjectId, deliveryClient.DeliveryOptions.CurrentValue.ProjectId);
            Assert.Equal(mockModelProvider, deliveryClient.ModelProvider);
            Assert.Equal(mockRetryPolicyProvider, deliveryClient.RetryPolicyProvider);
            Assert.Equal(mockTypeProvider, deliveryClient.TypeProvider);
            Assert.Equal(mockDeliveryHttpClient, deliveryClient.DeliveryHttpClient);
        }
Exemplo n.º 7
0
        public async Task IntegrationTest(bool cmApi)
        {
            var mockHttp = new MockHttpMessageHandler();

            mockHttp.When("https://deliver.kontent.ai/*")
            .Respond("application/json", File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures/types.json")));
            var httpClient = mockHttp.ToHttpClient();

            var mockOptions = new Mock <IOptions <CodeGeneratorOptions> >();

            mockOptions.Setup(x => x.Value).Returns(new CodeGeneratorOptions
            {
                Namespace            = "CustomNamespace",
                OutputDir            = TEMP_DIR,
                ContentManagementApi = cmApi
            });

            var client = DeliveryClientBuilder.WithProjectId(PROJECT_ID).WithDeliveryHttpClient(new DeliveryHttpClient(httpClient)).Build();

            var codeGenerator = new CodeGenerator(mockOptions.Object, client);

            await codeGenerator.GenerateContentTypeModels();

            await codeGenerator.GenerateTypeProvider();

            Assert.True(Directory.GetFiles(Path.GetFullPath(TEMP_DIR)).Length > 10);

            foreach (var filepath in Directory.EnumerateFiles(Path.GetFullPath(TEMP_DIR)))
            {
                Assert.DoesNotContain(".Generated.cs", Path.GetFileName(filepath));
            }

            // Cleanup
            Directory.Delete(TEMP_DIR, true);
        }
Exemplo n.º 8
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();
        }
Exemplo n.º 9
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);
        }
        public async void InitializeMultipleInlineContentItemsResolvers()
        {
            string       url               = $"{_baseUrl}/items/";
            const string tweetPrefix       = "Tweet resolver: ";
            const string hostedVideoPrefix = "Video resolver: ";

            _mockHttp
            .When($"{url}{"coffee_beverages_explained"}")
            .Respond("application/json", File.ReadAllText(Path.Combine(Environment.CurrentDirectory, $"Fixtures{Path.DirectorySeparatorChar}DeliveryClient{Path.DirectorySeparatorChar}coffee_beverages_explained.json")));

            var deliveryClient = DeliveryClientBuilder
                                 .WithProjectId(_guid)
                                 .WithInlineContentItemsResolver(InlineContentItemsResolverFactory.Instance
                                                                 .ResolveTo <Tweet>(tweet => tweetPrefix + tweet.TweetLink))
                                 .WithInlineContentItemsResolver(InlineContentItemsResolverFactory.Instance
                                                                 .ResolveTo <HostedVideo>(video => hostedVideoPrefix + video.VideoHost.First().Name))
                                 .WithTypeProvider(new CustomTypeProvider())
                                 .WithHttpClient(_mockHttp.ToHttpClient())
                                 .Build();

            var article = await deliveryClient.GetItemAsync <Article>("coffee_beverages_explained");

            Assert.Contains(tweetPrefix, article.Item.BodyCopy);
            Assert.Contains(hostedVideoPrefix, article.Item.BodyCopy);
        }
Exemplo n.º 11
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()));
        }
Exemplo n.º 12
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.º 13
0
        public async Task Index_ReturnsAViewResult_WithAnArticle()
        {
            // Arrange
            var config = new Mock <IConfiguration>();

            MockHttpMessageHandler mockHttp = new MockHttpMessageHandler();

            mockHttp.When($"https://deliver.kontent.ai/975bf280-fd91-488c-994c-2f04416e5ee3/items?elements.url_pattern=on_roasts&depth=1&language={CultureInfo.CurrentCulture}&system.type=article")
            .Respond("application/json", File.ReadAllText(Path.Combine(Environment.CurrentDirectory, $"on_roasts.json")));
            IDeliveryClient client  = DeliveryClientBuilder.WithProjectId("975bf280-fd91-488c-994c-2f04416e5ee3").WithDeliveryHttpClient(new DeliveryHttpClient(mockHttp.ToHttpClient())).WithTypeProvider(new CustomTypeProvider()).Build();
            var             factory = new Mock <IDeliveryClientFactory>();

            factory.Setup(m => m.Get()).Returns(client);

            ArticlesController controller = new ArticlesController(config.Object, factory.Object);

            // Act
            var result = await controller.Show("on_roasts");

            // Assert
            var viewResult = Assert.IsType <ViewResult>(result);
            var viewModel  = Assert.IsType <Article>(viewResult.ViewData.Model);

            Assert.Equal("On Roasts", viewModel.Title);
        }
Exemplo n.º 14
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.º 15
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.º 16
0
        public static async Task <Song> GetSong(string kontentProjectId, int trackNumber)
        {
            IDeliveryClient client = DeliveryClientBuilder.WithProjectId(kontentProjectId).Build();

            DeliveryItemListingResponse <Song> song = await client.GetItemsAsync <Song>(new EqualsFilter("elements.track_number", trackNumber.ToString()));

            return(song.Items[0]);
        }
Exemplo n.º 17
0
 public MovieListing(KontentKeys keys)
 {
     client = DeliveryClientBuilder
              .WithOptions(builder => builder
                           .WithProjectId(keys.ProjectId)
                           .UsePreviewApi(keys.PreviewApiKey)
                           .Build())
              .Build();
 }
Exemplo n.º 18
0
 private IDeliveryClient GetDeliveryClient()
 => DeliveryClientBuilder
 .WithOptions(builder => builder
              .WithProjectId(coreContext.Region.ProjectId)
              .UseProductionApi(coreContext.Region.DeliveryApiSecureAccessKey)
              .Build())
 .WithInlineContentItemsResolver(new Field())
 .WithTypeProvider(new KenticoKontentTypeProvider())
 .Build();
 public BaseController()
 {
     Client = DeliveryClientBuilder
              .WithOptions(builder => builder
                           .WithProjectId("09fc0115-dd4d-00c7-5bd9-5f73836aee81")
                           .UseProductionApi
                           .WithMaxRetryAttempts(5)
                           .Build())
              .Build();
 }
        public IDeliveryClient GetDeliveryClient()
        {
            if (_deliveryClient == null)
            {
                var projectId = _configuration.GetValue <string>("DeliveryOptions:ProjectId");
                _deliveryClient = DeliveryClientBuilder.WithProjectId(projectId).WithHttpClient(_httpClient).WithTypeProvider(_typeProvider).Build();
            }

            return(_deliveryClient);
        }
Exemplo n.º 21
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);
        }
Exemplo n.º 22
0
        public void BuildWithOptionalStepsAndCustomProvider_ReturnsDeliveryClientWithSetInstances()
        {
            var modelProvider = new FakeModelProvider();

            var deliveryClient = (Delivery.DeliveryClient)DeliveryClientBuilder
                                 .WithProjectId(ProjectId)
                                 .WithModelProvider(modelProvider)
                                 .Build();

            Assert.Equal(modelProvider, deliveryClient.ModelProvider);
        }
Exemplo n.º 23
0
        public static async Task Main(string[] args)
        {
            IDeliveryClient client   = DeliveryClientBuilder.WithProjectId(ProjectId).WithTypeProvider(new CustomTypeProvider()).Build();
            var             articles = await client.GetItemsAsync <Article>();

            foreach (var article in articles.Items)
            {
                Console.WriteLine($"The article '{article.Title}' was posted on {article.PostDate.Value.ToShortDateString()}.");
            }
            Console.ReadLine();
        }
Exemplo n.º 24
0
        public async Task <ViewResult> Index()
        {
            IDeliveryClient client = DeliveryClientBuilder
                                     .WithProjectId("<ProjectID>")
                                     .Build();

            var response = await client.GetItemAsync <Homepage>(
                "employers",
                new DepthParameter(3)
                );

            return(View(response.Item));
        }
        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.º 26
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.º 27
0
        public async Task IntegrationTest_RunAsync_GeneratePartials_CorrectFiles()
        {
            var mockHttp = new MockHttpMessageHandler();

            mockHttp.When("https://deliver.kontent.ai/*")
            .Respond("application/json", await File.ReadAllTextAsync(Path.Combine(AppContext.BaseDirectory, "Fixtures/delivery_types.json")));
            var httpClient = mockHttp.ToHttpClient();

            const string transformFilename = "Generated";

            var mockOptions = new Mock <IOptions <CodeGeneratorOptions> >();

            mockOptions.Setup(x => x.Value).Returns(new CodeGeneratorOptions
            {
                DeliveryOptions = new DeliveryOptions {
                    ProjectId = ProjectId
                },
                Namespace        = "CustomNamespace",
                OutputDir        = TempDir,
                FileNameSuffix   = transformFilename,
                GeneratePartials = true,
                WithTypeProvider = false,
                StructuredModel  = false,
                ManagementApi    = false
            });

            var deliveryClient = DeliveryClientBuilder.WithProjectId(ProjectId)
                                 .WithDeliveryHttpClient(new DeliveryHttpClient(httpClient)).Build();

            var codeGenerator = new DeliveryCodeGenerator(mockOptions.Object, new FileSystemOutputProvider(mockOptions.Object), deliveryClient);

            await codeGenerator.RunAsync();

            var allFilesCount  = Directory.GetFiles(Path.GetFullPath(TempDir), "*.cs").Length;
            var generatedCount = Directory.GetFiles(Path.GetFullPath(TempDir), $"*.{transformFilename}.cs").Length;

            Assert.Equal(allFilesCount, generatedCount * 2);

            foreach (var filepath in Directory.EnumerateFiles(Path.GetFullPath(TempDir), $"*.{transformFilename}.cs"))
            {
                var customFileExists = File.Exists(filepath.Replace($".{transformFilename}", ""));
                Assert.True(customFileExists);
            }

            // Cleanup
            Directory.Delete(TempDir, true);
        }
Exemplo n.º 28
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.º 29
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
            ILogger log, ExecutionContext context)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();

            IDeliveryClient client = DeliveryClientBuilder.WithProjectId(config["KontentProjectId"]).Build();

            DeliveryItemListingResponse <Song> listingResponse = await client.GetItemsAsync <Song>();

            var songs = listingResponse.Items.Select(x => x.Title).ToArray();

            string API_KEY    = config["NEXMO_API_KEY"];
            string API_SECRET = config["NEXMO_API_SECRET"];

            var nexmoClient = new Client(creds: new Nexmo.Api.Request.Credentials(
                                             nexmoApiKey: API_KEY, nexmoApiSecret: API_SECRET));

            var results = nexmoClient.SMS.Send(new SMS.SMSRequest
            {
                from = req.Query["to"],
                to   = req.Query["msisdn"],
                text = ConvertToNumberedList(songs)
            });


            return(new OkObjectResult(songs));

            string ConvertToNumberedList(IEnumerable <string> songs)
            {
                StringBuilder sb         = new StringBuilder();
                int           songNumber = 1;

                foreach (var s in songs)
                {
                    sb.AppendLine($"{songNumber++} - {s}");
                }
                return(sb.ToString());
            }
        }
Exemplo n.º 30
0
        public async Task Setup()
        {
            var projectId = Guid.NewGuid();
            var baseUrl   = $"https://deliver.kontent.ai/{projectId}";
            var mockHttp  = new MockHttpMessageHandler();

            mockHttp
            .When($"{baseUrl}/items/on_roasts")
            .Respond("application/json", await File.ReadAllTextAsync(Path.Combine(Environment.CurrentDirectory, $"Fixtures{Path.DirectorySeparatorChar}on_roasts.json")));

            mockHttp
            .When($"{baseUrl}/items")
            .WithQueryString("system.type=article")
            .Respond("application/json",
                     await File.ReadAllTextAsync(Path.Combine(Environment.CurrentDirectory, $"Fixtures{Path.DirectorySeparatorChar}full_articles.json")));

            _client = DeliveryClientBuilder.WithProjectId(projectId).WithTypeProvider(new CustomTypeProvider()).WithDeliveryHttpClient(new DeliveryHttpClient(mockHttp.ToHttpClient())).Build();
        }