public void GetItemAsync_NotFound() { var client = new DeliveryClient(PROJECT_ID); AsyncTestDelegate action = async() => await client.GetItemAsync("unscintillating_hemerocallidaceae_des_iroquois"); Assert.ThrowsAsync <DeliveryException>(action); }
public async Task OnGetAsync() { DeliveryClient Client = new DeliveryClient("ae8a7889-452f-461c-a741-0f4ca3950fab"); DeliveryItemResponse response = await Client.GetItemAsync("home"); homePage = response.Item; }
public async void ResolveLinksInStronglyTypedModel() { var mockHttp = new MockHttpMessageHandler(); string guid = Guid.NewGuid().ToString(); string url = $"https://deliver.kontent.ai/{guid}/items/coffee_processing_techniques"; mockHttp.When(url). Respond("application/json", await File.ReadAllTextAsync(Path.Combine(Environment.CurrentDirectory, $"Fixtures{Path.DirectorySeparatorChar}ContentLinkResolver{Path.DirectorySeparatorChar}coffee_processing_techniques.json"))); var deliveryOptions = DeliveryOptionsFactory.Create(new DeliveryOptions { ProjectId = guid }); var options = DeliveryOptionsFactory.Create(new DeliveryOptions { ProjectId = guid }); var deliveryHttpClient = new DeliveryHttpClient(mockHttp.ToHttpClient()); var resiliencePolicyProvider = new DefaultRetryPolicyProvider(options); var contentLinkUrlResolver = new CustomContentLinkUrlResolver(); var contentItemsProcessor = InlineContentItemsProcessorFactory.Create(); var modelProvider = new ModelProvider(contentLinkUrlResolver, contentItemsProcessor, new CustomTypeProvider(), new PropertyMapper(), new DeliveryJsonSerializer(), new HtmlParser()); var client = new DeliveryClient( deliveryOptions, modelProvider, resiliencePolicyProvider, null, deliveryHttpClient ); string expected = "Check out our <a data-item-id=\"0c9a11bb-6fc3-409c-b3cb-f0b797e15489\" href=\"http://example.org/brazil-natural-barra-grande\">Brazil Natural Barra Grande</a> coffee for a tasty example."; var item = await client.GetItemAsync <Article>("coffee_processing_techniques"); Assert.Contains(expected, item.Item.BodyCopy); }
/// <summary> /// Gets one strongly typed content item by its codename. /// </summary> /// <typeparam name="T">Type of the code-first model. (Or <see cref="object"/> if the return type is not yet known.)</typeparam> /// <param name="codename">The codename of a content item.</param> /// <param name="parameters">A collection of query parameters, for example for projection or depth of linked items.</param> /// <returns>The <see cref="DeliveryItemResponse{T}"/> instance that contains the content item with the specified codename.</returns> public async Task <DeliveryItemResponse <T> > GetItemAsync <T>(string codename, IEnumerable <IQueryParameter> parameters = null) { var queryParameters = parameters?.ToList(); return(await CacheManager.GetOrAddAsync( CacheHelper.GetItemTypedKey(codename, queryParameters), () => DeliveryClient.GetItemAsync <T>(codename, queryParameters), response => response != null)); }
public void GetItemAsync() { var client = new DeliveryClient(PROJECT_ID); var beveragesItem = Task.Run(() => client.GetItemAsync("coffee_beverages_explained")).Result.Item; var barraItem = Task.Run(() => client.GetItemAsync("brazil_natural_barra_grande")).Result.Item; var roastsItem = Task.Run(() => client.GetItemAsync("on_roasts")).Result.Item; Assert.AreEqual("article", beveragesItem.System.Type); Assert.GreaterOrEqual(beveragesItem.System.SitemapLocation.Count, 1); Assert.GreaterOrEqual(roastsItem.GetModularContent("related_articles").Count(), 1); Assert.AreEqual(beveragesItem.Elements.title.value.ToString(), beveragesItem.GetString("title")); Assert.AreEqual(beveragesItem.Elements.body_copy.value.ToString(), beveragesItem.GetString("body_copy")); Assert.AreEqual(DateTime.Parse(beveragesItem.Elements.post_date.value.ToString()), beveragesItem.GetDateTime("post_date")); Assert.AreEqual(beveragesItem.Elements.teaser_image.value.Count, beveragesItem.GetAssets("teaser_image").Count()); Assert.AreEqual(beveragesItem.Elements.personas.value.Count, beveragesItem.GetTaxonomyTerms("personas").Count()); Assert.AreEqual(decimal.Parse(barraItem.Elements.price.value.ToString()), barraItem.GetNumber("price")); Assert.AreEqual(barraItem.Elements.processing.value.Count, barraItem.GetOptions("processing").Count()); }
public async void GetItemAsync_NotFound() { string messsge = "{'message': 'The requested content item unscintillating_hemerocallidaceae_des_iroquois was not found.','request_id': '','error_code': 101,'specific_code': 0}"; mockHttp.When($"{baseUrl}/items/unscintillating_hemerocallidaceae_des_iroquois"). Respond(HttpStatusCode.NotFound, "application/json", messsge); DeliveryClient client = InitializeDeliverClientWithACustomeTypeProvider(); await Assert.ThrowsAsync <DeliveryException>(async() => await client.GetItemAsync("unscintillating_hemerocallidaceae_des_iroquois")); }
public async void ResolveLinksInStronglyTypedModel() { var client = new DeliveryClient("e1167a11-75af-4a08-ad84-0582b463b010"); client.ContentLinkUrlResolver = new CustomContentLinkUrlResolver(); string expected = "<p><a href=\"https://en.wikipedia.org/wiki/Brno\">Brno</a> office is very far from <a data-item-id=\"ee82db8c-de06-4992-9561-1fc642056c2b\" href=\"http://example.org/melbourne-office\">Melbourne</a> office.</p>"; var item = await client.GetItemAsync <Office>("brno_office"); Assert.Equal(expected, item.Item.AboutTheOffice); }
public async static Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, TraceWriter log, ExecutionContext context) { try { var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); string strTranslatorAPIKey = config["TranslatorAPIKey"]; string strLanguageCode = config["KenticoCloudLanguageCode"]; DeliveryClient client = new DeliveryClient(config["KenticoCloudProjectID"], config["KenticoCloudPreviewAPIKey"]); System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; // Get the content Task <string> body = new StreamReader(req.Body).ReadToEndAsync(); string strCodename = body.Result.ToString(); log.Info(strCodename); DeliveryItemResponse responseOriginal = await client.GetItemAsync(strCodename); if (responseOriginal != null) { // Defines the content elements to update ArticleModel NewArticleModel = new ArticleModel { OriginalCodename = responseOriginal.Item.System.Codename, NewArticle = new Article { Title = await GetTranslatedText(strTranslatorAPIKey, responseOriginal.Item.GetString("title"), strLanguageCode), Intro = await GetTranslatedText(strTranslatorAPIKey, responseOriginal.Item.GetString("intro"), strLanguageCode), Body = await GetTranslatedText(strTranslatorAPIKey, responseOriginal.Item.GetString("body"), strLanguageCode) } }; return((ActionResult) new OkObjectResult(JsonConvert.SerializeObject(NewArticleModel))); } else { log.Info("Kentico Cloud item not found!"); } log.Info($"No codename passed!"); } catch (Exception ex) { log.Info(ex.Message); } return(new OkObjectResult("FAILURE")); }
public void CastContentItem() { // Arrange var client2 = new DeliveryClient(SANDBOX_PROJECT_ID); // Act var item = client2.GetItemAsync("complete_content_item").Result.Item; var stronglyTypedResponse = item.CastTo <CompleteContentItemModel>(); // Assert Assert.Equal("Text field value", stronglyTypedResponse.TextField); }
public async void GreeterPropertyValueConverter() { var mockHttp = new MockHttpMessageHandler(); string url = $"{baseUrl}/items/on_roasts"; mockHttp.When(url). Respond("application/json", File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures\\ContentLinkResolver\\on_roasts.json"))); DeliveryClient client = InitializeDeliveryClient(mockHttp); var article = await client.GetItemAsync <Article>("on_roasts"); Assert.Equal("Hello On Roasts!", article.Item.TitleConverted); }
public async void NodaTimePropertyValueConverter() { var mockHttp = new MockHttpMessageHandler(); string url = $"{_baseUrl}/items/on_roasts"; mockHttp.When(url). Respond("application/json", await File.ReadAllTextAsync(Path.Combine(Environment.CurrentDirectory, $"Fixtures{Path.DirectorySeparatorChar}ContentLinkResolver{Path.DirectorySeparatorChar}on_roasts.json"))); DeliveryClient client = InitializeDeliveryClient(mockHttp); var article = await client.GetItemAsync <Article>("on_roasts"); Assert.Equal(new ZonedDateTime(Instant.FromUtc(2014, 11, 7, 0, 0), DateTimeZone.Utc), article.Item.PostDateNodaTime); }
public async void GreeterPropertyValueConverter() { var mockHttp = new MockHttpMessageHandler(); string url = $"{_baseUrl}/items/on_roasts"; mockHttp.When(url). Respond("application/json", await File.ReadAllTextAsync(Path.Combine(Environment.CurrentDirectory, $"Fixtures{Path.DirectorySeparatorChar}ContentLinkResolver{Path.DirectorySeparatorChar}on_roasts.json"))); DeliveryClient client = InitializeDeliveryClient(mockHttp); var article = await client.GetItemAsync <Article>("on_roasts"); Assert.Equal("Hello On Roasts!", article.Item.TitleConverted); }
public async void RecursiveModularContent() { mockHttp.When($"{baseUrl}/items/on_roasts"). WithQueryString("depth=15"). Respond("application/json", File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures\\DeliveryClient\\onroast_deep15.json"))); DeliveryClient client = InitializeDeliverClientWithACustomeTypeProvider(); // Try to get recursive modular content on_roasts -> item -> on_roasts var article = await client.GetItemAsync <Article>("on_roasts", new DepthParameter(15)); Assert.NotNull(article.Item); }
public void CastContentItem() { const string SANDBOX_PROJECT_ID = "e1167a11-75af-4a08-ad84-0582b463b010"; // Arrange var client = new DeliveryClient(SANDBOX_PROJECT_ID); // Act var item = client.GetItemAsync("complete_content_item").Result.Item; var stronglyTypedResponse = item.CastTo <CompleteContentItemModel>(); // Assert Assert.AreEqual("Text field value", stronglyTypedResponse.TextField); }
public async void IgnoredSerializationProperties() { mockHttp.When($"{baseUrl}/items/{"coffee_beverages_explained"}"). Respond("application/json", File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures\\DeliveryClient\\coffee_beverages_explained.json"))); DeliveryClient client = InitializeDeliverClientWithACustomeTypeProvider(); var beveragesItem = (await client.GetItemAsync("coffee_beverages_explained")).Item; var model = beveragesItem.CastTo <Article>(); Assert.NotNull(model.TitleNotIgnored); Assert.Null(model.TitleIgnored); }
public async void GetItemAsync() { string url = $"{_baseUrl}/items/"; _mockHttp.When($"{url}{"coffee_beverages_explained"}") .Respond("application/json", File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "Fixtures\\DeliveryClient\\coffee_beverages_explained.json"))); _mockHttp.When($"{url}{"brazil_natural_barra_grande"}") .Respond("application/json", File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "Fixtures\\DeliveryClient\\brazil_natural_barra_grande.json"))); _mockHttp.When($"{url}{"on_roasts"}"). Respond("application/json", File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "Fixtures\\DeliveryClient\\on_roasts.json"))); var httpClient = _mockHttp.ToHttpClient(); var client = new DeliveryClient(_guid) { HttpClient = httpClient }; var beveragesResponse = (await client.GetItemAsync("coffee_beverages_explained")); var beveragesItem = beveragesResponse.Item; var barraItem = (await client.GetItemAsync("brazil_natural_barra_grande")).Item; var roastsItem = (await client.GetItemAsync("on_roasts")).Item; Assert.Equal("article", beveragesItem.System.Type); Assert.Equal("en-US", beveragesItem.System.Language); Assert.NotEmpty(beveragesItem.System.SitemapLocation); Assert.NotEmpty(roastsItem.GetModularContent("related_articles")); Assert.Equal(beveragesItem.Elements.title.value.ToString(), beveragesItem.GetString("title")); Assert.Equal(beveragesItem.Elements.body_copy.value.ToString(), beveragesItem.GetString("body_copy")); Assert.Equal(DateTime.Parse(beveragesItem.Elements.post_date.value.ToString()), beveragesItem.GetDateTime("post_date")); Assert.Equal(beveragesItem.Elements.teaser_image.value.Count, beveragesItem.GetAssets("teaser_image").Count()); Assert.Equal(beveragesItem.Elements.personas.value.Count, beveragesItem.GetTaxonomyTerms("personas").Count()); Assert.Equal(decimal.Parse(barraItem.Elements.price.value.ToString()), barraItem.GetNumber("price")); Assert.Equal(barraItem.Elements.processing.value.Count, barraItem.GetOptions("processing").Count()); Assert.NotNull(beveragesResponse.ApiUrl); }
public void GetStronglyTypedGenericWithAttributesResponse() { _mockHttp.When($"{_baseUrl}/items/complete_content_item") .Respond("application/json", File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "Fixtures\\DeliveryClient\\complete_content_item.json"))); var httpClient = _mockHttp.ToHttpClient(); var client = new DeliveryClient(_guid) { CodeFirstModelProvider = { TypeProvider = A.Fake <ICodeFirstTypeProvider>() }, HttpClient = httpClient }; // Arrange A.CallTo(() => client.CodeFirstModelProvider.TypeProvider.GetType("complete_content_type")).ReturnsLazily(() => typeof(ContentItemModelWithAttributes)); A.CallTo(() => client.CodeFirstModelProvider.TypeProvider.GetType("homepage")).ReturnsLazily(() => typeof(Homepage)); ContentItemModelWithAttributes item = (ContentItemModelWithAttributes)client.GetItemAsync <object>("complete_content_item").Result.Item; // Assert Assert.Equal("Text field value", item.TextFieldWithADifferentName); Assert.Equal("<p>Rich text field value</p>", item.RichTextFieldWithADifferentName); Assert.Equal(99, item.NumberFieldWithADifferentName); Assert.Single(item.MultipleChoiceFieldAsRadioButtonsWithADifferentName); Assert.Equal("Radio button 1", item.MultipleChoiceFieldAsRadioButtonsWithADifferentName.First().Name); Assert.Equal(2, item.MultipleChoiceFieldAsCheckboxes.Count()); Assert.Equal("Checkbox 1", item.MultipleChoiceFieldAsCheckboxes.First().Name); Assert.Equal("Checkbox 2", item.MultipleChoiceFieldAsCheckboxes.ElementAt(1).Name); Assert.Equal(new DateTime(2017, 2, 23), item.DateTimeFieldWithADifferentName); Assert.Single(item.AssetFieldWithADifferentName); Assert.Equal("Fire.jpg", item.AssetFieldWithADifferentName.First().Name); Assert.Equal(129170, item.AssetFieldWithADifferentName.First().Size); Assert.Equal("https://assets.kenticocloud.com:443/e1167a11-75af-4a08-ad84-0582b463b010/64096741-b658-46ee-b148-b287fe03ea16/Fire.jpg", item.AssetFieldWithADifferentName.First().Url); Assert.Single(item.ModularContentFieldWithADifferentName); Assert.Equal("Homepage", ((Homepage)item.ModularContentFieldWithADifferentName.First()).System.Name); Assert.Equal("Homepage", ((Homepage)item.ModularContentFieldWithACollectionTypeDefined.First()).System.Name); Assert.True(item.ModularContentFieldWithAGenericTypeDefined.First().CallToAction.Length > 0); Assert.Equal(2, item.CompleteTypeTaxonomyWithADifferentName.Count()); Assert.Equal("Option 1", item.CompleteTypeTaxonomyWithADifferentName.First().Name); }
public async void RecursiveModularContent() { var client = new DeliveryClient(PROJECT_ID) { CodeFirstModelProvider = { TypeProvider = A.Fake <ICodeFirstTypeProvider>() } }; A.CallTo(() => client.CodeFirstModelProvider.TypeProvider.GetType("article")).ReturnsLazily(() => typeof(Article)); // Try to get recursive modular content on_roasts -> item -> on_roasts var task = client.GetItemAsync <Article>("on_roasts", new DepthParameter(15)); Assert.NotNull((await task).Item); }
/// <summary> /// Gets one strongly typed content item by its codename. /// </summary> /// <typeparam name="T">Type of the code-first model. (Or <see cref="object"/> if the return type is not yet known.)</typeparam> /// <param name="codename">The codename of a content item.</param> /// <param name="parameters">A collection of query parameters, for example for projection or depth of linked items.</param> /// <returns>The <see cref="DeliveryItemResponse{T}"/> instance that contains the content item with the specified codename.</returns> public async Task <DeliveryItemResponse <T> > GetItemAsync <T>(string codename, IEnumerable <IQueryParameter> parameters = null) { var identifierTokens = new List <string> { KenticoCloudCacheHelper.CONTENT_ITEM_SINGLE_TYPED_IDENTIFIER, codename }; identifierTokens.AddNonNullRange(KenticoCloudCacheHelper.GetIdentifiersFromParameters(parameters)); return(await CacheManager.GetOrCreateAsync( identifierTokens, () => DeliveryClient.GetItemAsync <T>(codename, parameters), response => response == null, GetContentItemSingleDependencies, ProjectOptions.CreateCacheEntriesInBackground)); }
public void RecursiveModularContent() { var client = new DeliveryClient(PROJECT_ID); client.CodeFirstModelProvider.TypeProvider = A.Fake <ICodeFirstTypeProvider>(); A.CallTo(() => client.CodeFirstModelProvider.TypeProvider.GetType("article")).ReturnsLazily(() => typeof(Article)); // Try to get recursive modular content on_roasts -> item -> on_roasts var task = client.GetItemAsync <Article>("on_roasts", new DepthParameter(15)); Assert.DoesNotThrow(() => { var result = Task.Run(() => task).Result.Item; }); }
public void GetStronglyTypedGenericWithAttributesResponse() { const string SANDBOX_PROJECT_ID = "e1167a11-75af-4a08-ad84-0582b463b010"; // Arrange var client = new DeliveryClient(SANDBOX_PROJECT_ID) { CodeFirstModelProvider = { TypeProvider = A.Fake <ICodeFirstTypeProvider>() } }; A.CallTo(() => client.CodeFirstModelProvider.TypeProvider.GetType("complete_content_type")).ReturnsLazily(() => typeof(ContentItemModelWithAttributes)); A.CallTo(() => client.CodeFirstModelProvider.TypeProvider.GetType("homepage")).ReturnsLazily(() => typeof(Homepage)); // Act ContentItemModelWithAttributes item = (ContentItemModelWithAttributes)client.GetItemAsync <object>("complete_content_item").Result.Item; // Assert Assert.Equal("Text field value", item.TextFieldWithADifferentName); Assert.Equal("<p>Rich text field value</p>", item.RichTextFieldWithADifferentName); Assert.Equal(99, item.NumberFieldWithADifferentName); Assert.Equal(1, item.MultipleChoiceFieldAsRadioButtonsWithADifferentName.Count()); Assert.Equal("Radio button 1", item.MultipleChoiceFieldAsRadioButtonsWithADifferentName.First().Name); Assert.Equal(2, item.MultipleChoiceFieldAsCheckboxes.Count()); Assert.Equal("Checkbox 1", item.MultipleChoiceFieldAsCheckboxes.First().Name); Assert.Equal("Checkbox 2", item.MultipleChoiceFieldAsCheckboxes.ElementAt(1).Name); Assert.Equal(new DateTime(2017, 2, 23), item.DateTimeFieldWithADifferentName); Assert.Equal(1, item.AssetFieldWithADifferentName.Count()); Assert.Equal("Fire.jpg", item.AssetFieldWithADifferentName.First().Name); Assert.Equal(129170, item.AssetFieldWithADifferentName.First().Size); Assert.Equal("https://assets.kenticocloud.com:443/e1167a11-75af-4a08-ad84-0582b463b010/64096741-b658-46ee-b148-b287fe03ea16/Fire.jpg", item.AssetFieldWithADifferentName.First().Url); Assert.Equal(1, item.ModularContentFieldWithADifferentName.Count()); Assert.Equal("Homepage", ((Homepage)item.ModularContentFieldWithADifferentName.First()).System.Name); Assert.Equal("Homepage", ((Homepage)item.ModularContentFieldWithACollectionTypeDefined.First()).System.Name); Assert.True(item.ModularContentFieldWithAGenericTypeDefined.First().CallToAction.Length > 0); Assert.Equal(2, item.CompleteTypeTaxonomyWithADifferentName.Count()); Assert.Equal("Option 1", item.CompleteTypeTaxonomyWithADifferentName.First().Name); }
public async void GetItemAsync() { // Arrange var mockHttp = new MockHttpMessageHandler(); mockHttp.When("https://deliver.kenticocloud.com/*").Respond("application/json", File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "Fixtures\\home.json"))); var httpClient = mockHttp.ToHttpClient(); DeliveryClient client = new DeliveryClient(Guid.NewGuid().ToString()) { HttpClient = httpClient }; // Act var contentItem = await client.GetItemAsync("test"); // Assert Assert.Equal("1bd6ba00-4bf2-4a2b-8334-917faa686f66", contentItem.Item.System.Id); }
public void CastResponse() { _mockHttp.When($"{_baseUrl}/items/complete_content_item") .Respond("application/json", File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "Fixtures\\DeliveryClient\\complete_content_item.json"))); var httpClient = _mockHttp.ToHttpClient(); var client = new DeliveryClient(_guid) { HttpClient = httpClient }; var response = client.GetItemAsync("complete_content_item").Result; var stronglyTypedResponse = response.CastTo <CompleteContentItemModel>(); // Assert Assert.Equal("Text field value", stronglyTypedResponse.Item.TextField); }
public void GetStrongTypesWithLimitedDepth() { var client = new DeliveryClient(PROJECT_ID); client.CodeFirstModelProvider.TypeProvider = A.Fake <ICodeFirstTypeProvider>(); A.CallTo(() => client.CodeFirstModelProvider.TypeProvider.GetType("article")).ReturnsLazily(() => typeof(Article)); // Returns on_roasts content item with related_articles modular element to two other articles. // on_roasts // |- coffee_processing_techniques // |- origins_of_arabica_bourbon // |- on_roasts var onRoastsItem = Task.Run(() => client.GetItemAsync <Article>("on_roasts", new DepthParameter(1))).Result.Item; Assert.AreEqual(2, onRoastsItem.RelatedArticles.Count()); Assert.AreEqual(0, ((Article)onRoastsItem.RelatedArticles.First()).RelatedArticles.Count()); Assert.AreEqual(0, ((Article)onRoastsItem.RelatedArticles.ElementAt(1)).RelatedArticles.Count()); }
private static async Task <string> GetDataForPublish(string projectId, string codename) { var deliveryClient = new DeliveryClient(projectId); var response = await deliveryClient.GetItemAsync(codename); var elements = response.Item.Elements; var children = elements.Children(); var str = new StringBuilder("{" + '\n'); foreach (var result in children) { var type = result.First.type.ToString(); var value = result.First.value.ToString(); if (type.Equals("multiple_choice")) { continue; } if (type.Equals("rich_text")) { var strippedText = StripHtml(value); str.Append('"' + result.Name + '"' + ":" + '"' + strippedText + '"'); } else { if (!value[0].ToString().Equals("[")) { str.Append('"' + result.Name + '"' + ":" + '"' + value + '"'); } else { str.Append('"' + result.Name + '"' + ":" + value); } } str.Append(", \n"); } str.Append("}"); return(str.ToString().Remove(str.Length - 4, 2)); }
public async void GetItemAsync() { var beveragesResponse = (await client.GetItemAsync("coffee_beverages_explained")); var beveragesItem = beveragesResponse.Item; var barraItem = (await client.GetItemAsync("brazil_natural_barra_grande")).Item; var roastsItem = (await client.GetItemAsync("on_roasts")).Item; Assert.Equal("article", beveragesItem.System.Type); Assert.Equal("en-US", beveragesItem.System.Language); Assert.NotEmpty(beveragesItem.System.SitemapLocation); Assert.NotEmpty(roastsItem.GetModularContent("related_articles")); Assert.Equal(beveragesItem.Elements.title.value.ToString(), beveragesItem.GetString("title")); Assert.Equal(beveragesItem.Elements.body_copy.value.ToString(), beveragesItem.GetString("body_copy")); Assert.Equal(DateTime.Parse(beveragesItem.Elements.post_date.value.ToString()), beveragesItem.GetDateTime("post_date")); Assert.Equal(beveragesItem.Elements.teaser_image.value.Count, beveragesItem.GetAssets("teaser_image").Count()); Assert.Equal(beveragesItem.Elements.personas.value.Count, beveragesItem.GetTaxonomyTerms("personas").Count()); Assert.Equal(decimal.Parse(barraItem.Elements.price.value.ToString()), barraItem.GetNumber("price")); Assert.Equal(barraItem.Elements.processing.value.Count, barraItem.GetOptions("processing").Count()); Assert.NotNull(beveragesResponse.ApiUrl); }
public async void AssetPropertiesNotEmpty() { mockHttp.When($"{baseUrl}/items/{"coffee_beverages_explained"}"). Respond("application/json", File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures\\DeliveryClient\\coffee_beverages_explained.json"))); DeliveryClient client = InitializeDeliverClientWithACustomeTypeProvider(); var response = await client.GetItemAsync("coffee_beverages_explained"); var beveragesItem = response.Item; var model = beveragesItem.CastTo <Article>(); Assert.NotNull(model.TeaserImage.FirstOrDefault().Description); Assert.NotNull(model.TeaserImage.FirstOrDefault().Name); Assert.NotNull(model.TeaserImage.FirstOrDefault().Type); Assert.NotNull(model.TeaserImage.FirstOrDefault().Url); Assert.NotNull(response.ApiUrl); }
public void CastContentItem() { mockHttp.When($"{baseUrl}/items/complete_content_item"). Respond("application/json", File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures\\DeliveryClient\\complete_content_item.json"))); var httpClient = mockHttp.ToHttpClient(); DeliveryClient client = new DeliveryClient(guid) { HttpClient = httpClient }; var item = client.GetItemAsync("complete_content_item").Result.Item; var stronglyTypedResponse = item.CastTo <CompleteContentItemModel>(); // Assert Assert.Equal("Text field value", stronglyTypedResponse.TextField); }
public async void RichTextViaValueConverter() { var mockHttp = new MockHttpMessageHandler(); string url = $"{_baseUrl}/items/coffee_beverages_explained"; mockHttp.When(url). WithQueryString("depth=15"). Respond("application/json", await File.ReadAllTextAsync(Path.Combine(Environment.CurrentDirectory, $"Fixtures{Path.DirectorySeparatorChar}ContentLinkResolver{Path.DirectorySeparatorChar}coffee_beverages_explained.json"))); DeliveryClient client = InitializeDeliveryClient(mockHttp); // Try to get recursive linked items on_roasts -> item -> on_roasts var article = await client.GetItemAsync <Article>("coffee_beverages_explained", new DepthParameter(15)); var hostedVideo = article.Item.BodyCopyRichText.Blocks.FirstOrDefault(b => (b as IInlineContentItem)?.ContentItem is HostedVideo); var tweet = article.Item.BodyCopyRichText.Blocks.FirstOrDefault(b => (b as IInlineContentItem)?.ContentItem is Tweet); Assert.NotNull(hostedVideo); Assert.NotNull(tweet); }
public async void GetStrongTypesWithLimitedDepth() { mockHttp.When($"{baseUrl}/items/on_roasts"). WithQueryString("depth=1"). Respond("application/json", File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures\\DeliveryClient\\on_roasts.json"))); DeliveryClient client = InitializeDeliverClientWithACustomeTypeProvider(); // Returns on_roasts content item with related_articles modular element to two other articles. // on_roasts // |- coffee_processing_techniques // |- origins_of_arabica_bourbon // |- on_roasts var onRoastsItem = (await client.GetItemAsync <Article>("on_roasts", new DepthParameter(1))).Item; Assert.NotNull(onRoastsItem.TeaserImage.First().Description); Assert.Equal(2, onRoastsItem.RelatedArticles.Count()); Assert.Equal(0, ((Article)onRoastsItem.RelatedArticles.First()).RelatedArticles.Count()); Assert.Equal(0, ((Article)onRoastsItem.RelatedArticles.ElementAt(1)).RelatedArticles.Count()); }