Exemplo n.º 1
0
        public ArticlesPipeline(IDeliveryClient client)
        {
            InputModules = new ModuleList
            {
                new Kontent <Article>(client)
                .WithItemsFeed()
            };

            ProcessModules = new ModuleList
            {
                new MergeContent(
                    new ReadFiles(patterns: "_Detail.cshtml")
                    ),
                new RenderRazor()
                .WithModel(KontentConfig.As <Article>()),
                new SetDestination(
                    Config.FromDocument((doc, ctx)
                                        => new NormalizedPath($"{doc.AsKontent<Article>().Slug}.html")
                                        )
                    )
            };

            OutputModules = new ModuleList {
                new WriteFiles()
            };
        }
Exemplo n.º 2
0
 public CachedDeliveryClient(ICacheManager cacheManager, IDeliveryClient deliveryClient, IDeliveryClient previewDeliveryClient, IDependencyResolver dependencyResolver)
 {
     _cacheManager          = cacheManager;
     _deliveryClient        = deliveryClient;
     _previewDeliveryClient = previewDeliveryClient;
     _dependencyResolver    = dependencyResolver;
 }
Exemplo n.º 3
0
        public PagesPipeline(IDeliveryClient deliveryClient)
        {
            Dependencies.AddRange(nameof(HomepagePipeline), nameof(SiteMetadataPipeline));
            InputModules = new ModuleList {
                new Kontent <Page>(deliveryClient)
                .WithQuery(new IncludeTotalCountParameter(), new NotEmptyFilter("elements.body")),
                new SetDestination(Config.FromDocument((doc, ctx) => new NormalizedPath($"pages/{doc.AsKontent<Page>().Url}/index.html"))),
            };

            ProcessModules = new ModuleList {
                new MergeContent(new ReadFiles(patterns: "Index.cshtml")),
                new RenderRazor()
                .WithModel(Config.FromDocument((document, context) =>
                {
                    var menuItem = document.AsKontent <Page>();
                    var model    = new HomeViewModel(menuItem,
                                                     new SidebarViewModel(
                                                         context.Outputs.FromPipeline(nameof(HomepagePipeline)).Select(x => x.AsKontent <Homepage>()).FirstOrDefault(),
                                                         context.Outputs.FromPipeline(nameof(SiteMetadataPipeline)).Select(x => x.AsKontent <SiteMetadata>()).FirstOrDefault(),
                                                         false, menuItem.Url));
                    return(model);
                }
                                               ))/*,
                                                  * new KontentImageProcessor()*/
            };

            OutputModules = new ModuleList {
                new WriteFiles(),
            };
        }
Exemplo n.º 4
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.º 5
0
        public void InstantiationTest()
        {
            // Arrange
            var cfmp      = A.Fake <ICodeFirstModelProvider>();
            var clur      = A.Fake <IContentLinkUrlResolver>();
            var cip       = A.Fake <IInlineContentItemsProcessor>();
            var projectId = Guid.NewGuid().ToString();

            // Act
            var serviceProvider = new ServiceCollection()
                                  .AddScoped(c => cfmp)
                                  .AddScoped(c => clur)
                                  .AddScoped(c => cip)
                                  .AddOptions()
                                  .Configure <DeliveryOptions>(o => o.ProjectId = projectId)
                                  .AddScoped <IDeliveryClient, DeliveryClient>()
                                  .BuildServiceProvider();

            IDeliveryClient dc = serviceProvider.GetService <IDeliveryClient>();

            // Assert
            Assert.Equal(cfmp, dc.CodeFirstModelProvider);
            Assert.Equal(clur, dc.ContentLinkUrlResolver);
            Assert.Equal(cip, dc.InlineContentItemsProcessor);
        }
Exemplo n.º 6
0
        public HomePipeline(IDeliveryClient deliveryClient)
        {
            Dependencies.AddRange(nameof(PostsPipeline), nameof(HomepagePipeline), nameof(SiteMetadataPipeline));
            ProcessModules = new ModuleList(
                // pull documents from other pipelines
                new ReplaceDocuments(nameof(PostsPipeline)),
                new PaginateDocuments(4),
                new SetDestination(Config.FromDocument((doc, ctx) => Filename(doc))),
                new MergeContent(new ReadFiles("Index.cshtml")),
                new RenderRazor()
                .WithModel(Config.FromDocument((document, context) =>
            {
                var model = new HomeViewModel(document.AsPagedKontent <Article>(),
                                              new SidebarViewModel(
                                                  context.Outputs.FromPipeline(nameof(HomepagePipeline)).Select(x => x.AsKontent <Homepage>()).FirstOrDefault(),
                                                  context.Outputs.FromPipeline(nameof(SiteMetadataPipeline)).Select(x => x.AsKontent <SiteMetadata>()).FirstOrDefault(),
                                                  true, "/"));
                return(model);
            }
                                               )),
                new KontentImageProcessor()
                );

            OutputModules = new ModuleList {
                new WriteFiles(),
            };
        }
Exemplo n.º 7
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.º 8
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]);
        }
        public Scenario(IMemoryCache memoryCache, HttpClient httpClient, DeliveryOptions deliveryOptions, Dictionary <string, int> requestCounter)
        {
            _requestCounter = requestCounter;
            _cacheManager   = new DeliveryCacheManager(memoryCache, Options.Create(new DeliveryCacheOptions()));
            var baseClient = DeliveryClientBuilder.WithOptions(_ => deliveryOptions).WithDeliveryHttpClient(new DeliveryHttpClient(httpClient)).Build();

            CachingClient = new DeliveryClientCache(_cacheManager, baseClient);
        }
Exemplo n.º 10
0
 public Seo(IDeliveryClient deliveryClient)
 {
     InputModules = new ModuleList
     {
         new Kontent <Kentico.Kontent.Statiq.Memoirs.Models.Home>(deliveryClient)
         .WithQuery(new LimitParameter(1), new DepthParameter(1))
     };
 }
Exemplo n.º 11
0
        public Kontent(IDeliveryClient client)
        {
            if (client == null)
            {
                throw new ArgumentNullException($"{nameof(client)} must not be null");
            }

            Client = new Lazy <IDeliveryClient>(() => client);
        }
Exemplo n.º 12
0
 public MovieListing(KontentKeys keys)
 {
     client = DeliveryClientBuilder
              .WithOptions(builder => builder
                           .WithProjectId(keys.ProjectId)
                           .UsePreviewApi(keys.PreviewApiKey)
                           .Build())
              .Build();
 }
 public BaseController()
 {
     Client = DeliveryClientBuilder
              .WithOptions(builder => builder
                           .WithProjectId("09fc0115-dd4d-00c7-5bd9-5f73836aee81")
                           .UseProductionApi
                           .WithMaxRetryAttempts(5)
                           .Build())
              .Build();
 }
Exemplo n.º 14
0
        public DeliveryCodeGenerator(IOptions <CodeGeneratorOptions> options, IOutputProvider outputProvider, IDeliveryClient deliveryClient)
            : base(options, outputProvider)
        {
            if (options.Value.ManagementApi)
            {
                throw new InvalidOperationException("Cannot create Delivery models with Management API options.");
            }

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

            CachingClient = new DeliveryClientCache(_cacheManager, baseClient);
        }
        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.º 17
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.º 18
0
        public IDeliveryClient GetDeliveryClient()
        {
            if (_deliveryClient == null)
            {
                //var projectId = _configuration.GetValue<string>("DeliveryOptions:ProjectId");
                //_deliveryClient = DeliveryClientBuilder.WithProjectId(projectId).WithDeliveryHttpClient(_httpClient).Build();

                _deliveryClient = _clientFactory.Get("production");
            }

            return(_deliveryClient);
        }
        public ControllerBase()
        {
            var currentCulture = CultureInfo.CurrentUICulture.Name;

            if (currentCulture.Equals(LanguageClient.DEFAULT_LANGUAGE, StringComparison.InvariantCultureIgnoreCase))
            {
                client = baseClient;
            }
            else
            {
                client = new LanguageClient(baseClient, currentCulture);
            }
        }
Exemplo n.º 20
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));
        }
Exemplo n.º 21
0
        /// <summary>
        /// Constructs a new <see cref="NavigationProvider"/>.
        /// </summary>
        /// <param name="options">Environment settings. The NavigationCodename, HomepageToken and RootToken must be set; the MaxDepth must be 2 or greater.</param>
        /// <param name="client">A client to communicate with the Delivery/Preview API</param>
        /// <param name="cache">The in-memory cache. The NavigationCacheExpirationMinutes value must be a positive number.</param>
        public NavigationProvider(IOptions <NavigationOptions> options, IDeliveryClient client, IMemoryCache cache)
        {
            if (options.Value.NavigationCodename == null)
            {
                throw new ArgumentNullException(nameof(options.Value.NavigationCodename));
            }
            else if (options.Value.NavigationCodename.Equals(string.Empty))
            {
                throw new ArgumentOutOfRangeException(nameof(options.Value.NavigationCodename), $"The {nameof(options.Value.NavigationCodename)} parameter must not be an empty string.");
            }

            if (!options.Value.MaxDepth.HasValue)
            {
                throw new ArgumentNullException(nameof(options.Value.MaxDepth));
            }
            else if (options.Value.MaxDepth.Value < 2)
            {
                throw new ArgumentOutOfRangeException(nameof(options.Value.MaxDepth), $"The {nameof(options.Value.MaxDepth)} parameter must be 2 or higher.");
            }

            if (!options.Value.NavigationCacheExpirationMinutes.HasValue)
            {
                throw new ArgumentNullException(nameof(options.Value.NavigationCacheExpirationMinutes));
            }
            else if (options.Value.NavigationCacheExpirationMinutes.Value <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(options.Value.NavigationCacheExpirationMinutes), $"The {nameof(options.Value.NavigationCacheExpirationMinutes)} parameter must be greater than zero.");
            }

            if (options.Value.RootToken == null)
            {
                throw new ArgumentNullException(nameof(options.Value.RootToken));
            }
            else if (options.Value.RootToken.Equals(string.Empty))
            {
                throw new ArgumentOutOfRangeException(nameof(options.Value.RootToken), $"The {nameof(options.Value.RootToken)} parameter must not be an empty string.");
            }

            if (options.Value.HomepageToken == null)
            {
                throw new ArgumentNullException(nameof(options.Value.HomepageToken));
            }

            _client             = client ?? throw new ArgumentNullException(nameof(client));
            _cache              = cache ?? throw new ArgumentNullException(nameof(cache));
            _navigationCodename = options.Value.NavigationCodename;
            _maxDepth           = options.Value.MaxDepth.Value;
            _navigationCacheExpirationMinutes = options.Value.NavigationCacheExpirationMinutes.Value;
            _rootToken     = options.Value.RootToken;
            _homepageToken = options.Value.HomepageToken;
        }
Exemplo n.º 22
0
        public Posts(IDeliveryClient deliveryClient, SiteSettings site)
        {
            Dependencies.Add(nameof(Seo));
            InputModules = new ModuleList {
                new Kontent <Post>(deliveryClient)
                .OrderBy(Post.PostDateCodename, SortOrder.Descending)
                .WithQuery(new DepthParameter(2), new IncludeTotalCountParameter()),
                new SetMetadata(nameof(Post.Tags),
                                KontentConfig.Get <Post, ITaxonomyTerm[]>(post => post.Tags?.ToArray())),
                new SetMetadata(nameof(Post.Categories),
                                KontentConfig.Get <Post, ITaxonomyTerm[]>(post => post.Categories?.ToArray())),
                new SetDestination(KontentConfig.Get((Post post) => new NormalizedPath(post.Url))),
                new SetMetadata(SearchIndex.SearchItemKey, Config.FromDocument((doc, ctx) =>
                {
                    var post = doc.AsKontent <Post>();
                    return(new LunrIndexDocItem(doc, post.Title, post.Body)
                    {
                        Description = post.MetadataMetaDescription,
                        Tags = string.Join(", ", post.Tags.Select(t => t.Name))
                    });
                })),
            };

            ProcessModules = new ModuleList {
                new MergeContent(new ReadFiles(patterns: "post.cshtml")),
                new RenderRazor()
                .WithViewData("SEO", Config.FromDocument((doc, ctx) =>
                {
                    var home = ctx.Outputs.FromPipeline(nameof(Seo)).First().AsKontent <Kentico.Kontent.Statiq.Memoirs.Models.Home>();
                    var post = doc.AsKontent <Post>();

                    return(new SocialSharingMetadata(home, post));
                }))
                .WithViewData("Title", KontentConfig.Get <Post, string>(p => p.Title))
                .WithViewData("Author", KontentConfig.Get <Post, Author>(p => p.Author.OfType <Author>().FirstOrDefault()))
                .WithViewData("SiteMetadata", site)
                .WithModel(KontentConfig.As <Post>()),
                new KontentImageProcessor(),
                new OptimizeHtml(site.OptimizeOutput)
                .WithSettings(settings =>
                {
                    // conflicts with ratings
                    settings.RemoveScriptStyleTypeAttribute = false;
                    settings.MinifyJs = false;
                })
            };

            OutputModules = new ModuleList {
                new WriteFiles(),
            };
        }
Exemplo n.º 23
0
    public YourController(IDeliveryClientFactory deliveryClientFactory)
    {
        // Creates instances of Delivery clients based on their names
        client1 = deliveryClientFactory.Get("first_project");
        client2 = deliveryClientFactory.Get("second_project");

        // Gets content items from both projects
        // Using the generic <object> produces strongly typed objects based on "system.type"
        var response1 = await client1.GetItemsAsync <object>();

        var response2 = await client2.GetItemsAsync <object>();

        // Merges the responses
        IReadOnlyList <object> items = response1.Items.Concat(response2.Items).ToArray();
    }
Exemplo n.º 24
0
        /// <summary>
        /// Constructs a new <see cref="MenuItemGenerator"/>.
        /// </summary>
        /// <param name="options">Environment settings</param>
        /// <param name="client">A client to communicate with the Delivery/Preview API</param>
        /// <param name="cache">The in-memory cache. The NavigationCacheExpirationMinutes value must be a positive number.</param>
        public MenuItemGenerator(IOptions <NavigationOptions> options, IDeliveryClient client, IMemoryCache cache)
        {
            if (!options.Value.NavigationCacheExpirationMinutes.HasValue)
            {
                throw new ArgumentNullException(nameof(options.Value.NavigationCacheExpirationMinutes));
            }
            else if (options.Value.NavigationCacheExpirationMinutes.Value <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(options.Value.NavigationCacheExpirationMinutes), $"The {nameof(options.Value.NavigationCacheExpirationMinutes)} parameter must be greater than zero.");
            }

            _client = client ?? throw new ArgumentNullException(nameof(client));
            _cache  = cache ?? throw new ArgumentNullException(nameof(cache));
            _navigationCacheExpirationMinutes = options.Value.NavigationCacheExpirationMinutes.Value;
            _startingUrls.Add("blog", GenerateNavigationWithBlogItemsAsync);
        }
Exemplo n.º 25
0
        public Pages(IDeliveryClient deliveryClient, SiteSettings site)
        {
            Dependencies.Add(nameof(Seo));
            InputModules = new ModuleList
            {
                new Kontent <Page>(deliveryClient)
                .OrderBy(Post.TitleCodename, SortOrder.Descending)
                .WithQuery(new DepthParameter(2), new IncludeTotalCountParameter()),
                new SetMetadata(nameof(Page.Tags),
                                KontentConfig.Get <Page, ITaxonomyTerm[]>(post => post.Tags?.ToArray())),
                new SetMetadata(nameof(Page.Categories),
                                KontentConfig.Get <Page, ITaxonomyTerm[]>(post => post.Categories?.ToArray())),
                new SetDestination(KontentConfig.Get((Page page) => new NormalizedPath(page.Url))),
                new SetMetadata(SearchIndex.SearchItemKey, Config.FromDocument((doc, ctx) =>
                {
                    var page = doc.AsKontent <Page>();
                    return(new LunrIndexDocItem(doc, page.Title, page.Body)
                    {
                        Description = page.MetadataMetaDescription,
                        //Tags = string.Join(", ", post.Tags.Select( t => t.Name ))
                    });
                })),
            };

            ProcessModules = new ModuleList
            {
                new MergeContent(new ReadFiles("page.cshtml")),
                new RenderRazor()
                .WithViewData("SEO", Config.FromDocument((doc, ctx) =>
                {
                    var home = ctx.Outputs.FromPipeline(nameof(Seo)).First().AsKontent <Kentico.Kontent.Statiq.Memoirs.Models.Home>();
                    var post = doc.AsKontent <Page>();

                    return(new SocialSharingMetadata(home, post));
                }))
                .WithViewData("Title", KontentConfig.Get <Page, string>(p => p.Title))
                .WithViewData("SiteMetadata", site)
                .WithModel(KontentConfig.As <Page>()),
                new KontentImageProcessor(),
                new OptimizeHtml()
            };

            OutputModules = new ModuleList
            {
                new WriteFiles(),
            };
        }
Exemplo n.º 26
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.º 27
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();
        }
 public HeroPipeline(IDeliveryClient client)
 {
     ProcessModules = new ModuleList
     {
         new Kontent <Hero>(client)
         .WithQuery(
             new EqualsFilter("system.codename", "hero"),
             new LimitParameter(1)
             ),
         new MergeContent(
             new ReadFiles(patterns: "_Hero.cshtml")
             ),
         new RenderRazor()
         .WithModel(KontentConfig.As <Hero>()),
         new SetDestination(new NormalizedPath("index.html")),
         new WriteFiles()
     };
 }
Exemplo n.º 29
0
        public TagsPipeline(IDeliveryClient deliveryClient)
        {
            Dependencies.AddRange(nameof(PostsPipeline), nameof(HomepagePipeline), nameof(SiteMetadataPipeline));

            InputModules = new ModuleList
            {
                new ReadFiles(patterns: "Index.cshtml")
            };

            ProcessModules = new ModuleList {
                new MergeDocuments()
                {
                    new ReplaceDocuments(nameof(PostsPipeline)),
                    // Get docs from a different pipeline
                    new GroupDocuments(nameof(Tag)),                                                                                                                                                                    // Group docs by the tag name
                }.Reverse(),
                new SetMetadata("SelectedTag", Config.FromDocument(doc => doc.GetChildren().FirstOrDefault().AsKontent <Article>().TagObjects.FirstOrDefault(t => t.System.Codename == doc.GetString(Keys.GroupKey)))), // Copy group metadata to the group parent page
                new ForEachDocument {                                                                                                                                                                                   // For each tag
                    new ExecuteConfig(Config.FromDocument(groupDoc => new ModuleList
                    {
                        new ReplaceDocuments(Config.FromDocument <IEnumerable <IDocument> >(doc => doc.GetChildren())),
                        new PaginateDocuments(4),     // Create pagination (docs will reside under a parent doc - a page)
                        new MergeContent(new ReadFiles(patterns: "Index.cshtml")),
                        new RenderRazor()
                        .WithModel(Config.FromDocument((document, context) =>
                        {
                            var tag   = groupDoc.Get <Tag>("SelectedTag");
                            var model = new HomeViewModel(document.AsPagedKontent <Article>(),
                                                          new SidebarViewModel(
                                                              context.Outputs.FromPipeline(nameof(HomepagePipeline)).Select(x => x.AsKontent <Homepage>()).FirstOrDefault(),
                                                              context.Outputs.FromPipeline(nameof(SiteMetadataPipeline)).Select(x => x.AsKontent <SiteMetadata>()).FirstOrDefault(),
                                                              false, null), tag);
                            return(model);
                        })),
                        new SetDestination(Config.FromDocument((doc, ctx) => Filename(doc, groupDoc))) // Set output
                    }))
                }
            };

            OutputModules = new ModuleList {
                new WriteFiles(),
            };
        }
Exemplo n.º 30
0
        public CodeGenerator(IOptions <CodeGeneratorOptions> options, IDeliveryClient deliveryClient)
        {
            _options = options.Value;
            _client  = deliveryClient;

            /// Setting OutputDir default value here instead of in the <see cref="Parse"/> method as it would overwrite the JSON value.
            if (string.IsNullOrEmpty(_options.OutputDir))
            {
                _options.OutputDir = "./";
            }

            if (_options.GeneratePartials && string.IsNullOrEmpty(_options.FileNameSuffix))
            {
                _options.FileNameSuffix = "Generated";
            }

            // Resolve relative path to full path
            _options.OutputDir = Path.GetFullPath(_options.OutputDir);
        }