public async Task <ActionResult> Index() { if (Session["username"] != null) { ViewBag.Session = Session["username"].ToString(); } else { ViewBag.Session = "Contentful"; } HttpClient httpClient = new HttpClient(); var options = new ContentfulOptions { DeliveryApiKey = "4df4c5c7ed276605d36b9d880f1455aea05fe9b47e2da6acf518c0771d300625", PreviewApiKey = "3aaec008db04a17e144539715f539354ff73cf8d82c2548c3045bbcfc2ee32a2", SpaceId = "bda2gc49gm0w" }; var client = new ContentfulClient(httpClient, options); var AllCategories = await client.GetEntries(QueryBuilder <Category> .New.ContentTypeIs("category")); var AllCategoryItems = await client.GetEntries(QueryBuilder <Product> .New.ContentTypeIs("categoryItems")); Homepage model = new Homepage(); model.Kategori = AllCategories.Items.ToList(); model.Urun = AllCategoryItems.Items.ToList(); return(View(model)); }
public static IGraph GetConcept(string id) { var conceptQuery = QueryBuilder <Concept> .New.ContentTypeIs(Concept.ContentTypeName).FieldMatches(t => t.ParliamentId, id); var concepts = Engine.client.GetEntries(conceptQuery).Result; if (!concepts.Any()) { throw new EntryNotFoundException(); } var concept = concepts.Single(); concept.Description = null; foreach (var broaderConcept in concept.BroaderConcept ?? Enumerable.Empty <Concept>()) { broaderConcept.Description = null; } var indexedArticleQuery = QueryBuilder <Article> .New.ContentTypeIs(Article.ContentTypeName).LinksToEntry(concept.Sys.Id); concept.IndexedArticles = client.GetEntries(indexedArticleQuery).Result; foreach (var indexedArticle in concept.IndexedArticles) { indexedArticle.ArticleType = null; indexedArticle.Body = null; indexedArticle.RelatedArticle = null; indexedArticle.Summary = null; indexedArticle.Topic = null; } var narrowerConceptQuery = QueryBuilder <Concept> .New.ContentTypeIs(Concept.ContentTypeName).LinksToEntry(concept.Sys.Id); concept.NarrowerConcepts = client.GetEntries(narrowerConceptQuery).Result; foreach (var narrowerConcept in concept.NarrowerConcepts) { narrowerConcept.BroaderConcept = null; narrowerConcept.Definition = null; narrowerConcept.Description = null; } return(new Processor(concept).Graph); }
/// <summary> /// Publishes the content items referenced by the project. /// </summary> /// <param name="slug">The slug identifying the project</param> /// <returns></returns> public async Task <List <string> > PublishProject(string slug) { _logger.LogTrace($"ContentfulContentRepository.PublishProject({slug})"); if (string.IsNullOrWhiteSpace(slug)) { throw new ArgumentException("Missing required parameter", nameof(slug)); } try { var cful = new ContentfulClient(_httpClient, _options); var managementClient = new ContentfulManagementClient(_httpClient, _options); var facetQuery = new QueryBuilder <Project>() .ContentTypeIs("project") .FieldEquals("fields.slug", slug) .Include(8); _logger.LogInformation($"executing CMS call with query: {facetQuery.Build()}"); // Retrieve the entire content tree by starting at the project and pulling includes // an arbitrary depth of 8 var entrySet = await cful.GetEntries(facetQuery); // todo: determine if our process will already have the actual project published or not. // var projectId = entrySet.Items.FirstOrDefault().Sys.Id; var includedEntryIds = entrySet.IncludedEntries.Select(x => x.SystemProperties.Id); // todo: publish assets, too. // var includedAssetIds = entrySet.IncludedAssets.Select(x => x.SystemProperties.Id); foreach (var entry in entrySet.IncludedEntries) { var id = entry.SystemProperties.Id; // Retrieve the item from mgmt API. Version is not included from delivery API so we get it again. var mgmtEntry = await managementClient.GetEntry(id); var latestVersion = mgmtEntry.SystemProperties.Version.GetValueOrDefault(); var result = await managementClient.PublishEntry(id, latestVersion); } return(null); } catch (Contentful.Core.Errors.ContentfulException ex) { var msg = "Error retrieving content: " + ex; _logger.LogError(msg); throw new ContentException(msg, ex); } catch (Exception ex) { var msg = "Unable to retrieve content: " + ex; _logger.LogError(msg); throw new ProcessException(msg, ex); } }
/// <summary> /// Invokes the view component and returns the result. /// </summary> /// <param name="sys">They system properties of the entry to display status for.</param> /// <returns>The view.</returns> public async Task <IViewComponentResult> InvokeAsync(IEnumerable <SystemProperties> sys) { // Create a new client with preview set to false to always get the entry from the delivery API. var client = new ContentfulClient(_httpClient, _options.DeliveryApiKey, _options.PreviewApiKey, _options.SpaceId, false); IEnumerable <EntryStateModel> entries = null; var model = new EntryStateModel(); try { // Try getting the entry by the specified Id. If it throws or returns null the entry is not published. entries = await client.GetEntries <EntryStateModel>($"?sys.id[in]={string.Join(",", sys.Select(c => c.Id))}"); } catch { } if (entries == null || (entries.Any() == false || sys.Select(c => c.Id).Except(entries.Select(e => e.Sys.Id)).Any())) { // One of the entries are not published, thus it is in draft mode. model.Draft = true; } if (entries != null && AnySystemPropertiesNotMatching(entries.Select(c => c.Sys), sys)) { // The entry is published but the UpdatedAt dates do not match, thus it must have pending changes. model.PendingChanges = true; } return(View(model)); bool AnySystemPropertiesNotMatching(IEnumerable <SystemProperties> published, IEnumerable <SystemProperties> preview) { foreach (var publishedEntry in published) { var previewEntry = preview.FirstOrDefault(c => c.Id == publishedEntry.Id); if (TrimMilliseconds(publishedEntry.UpdatedAt) != TrimMilliseconds(previewEntry?.UpdatedAt)) { // At least one of the entries have UpdatedAt that does not match, thus it has pending changes. return(true); } } return(false); } DateTime?TrimMilliseconds(DateTime?dateTime) { if (!dateTime.HasValue) { return(dateTime); } return(new DateTime(dateTime.Value.Year, dateTime.Value.Month, dateTime.Value.Day, dateTime.Value.Hour, dateTime.Value.Minute, dateTime.Value.Second, 0)); } }
public async Task <ActionResult> Category(string categoryID) { HttpClient httpClient = new HttpClient(); var options = new ContentfulOptions { DeliveryApiKey = "4df4c5c7ed276605d36b9d880f1455aea05fe9b47e2da6acf518c0771d300625", PreviewApiKey = "3aaec008db04a17e144539715f539354ff73cf8d82c2548c3045bbcfc2ee32a2", SpaceId = "bda2gc49gm0w" }; var client = new ContentfulClient(httpClient, options); var AllItems = await client.GetEntries(QueryBuilder <Product> .New.ContentTypeIs("categoryItems")); var FilterCategoryItems = AllItems.Where(c => c.categoryRef.Any(x => string.Equals(x["$ref"].ToString(), categoryID))); var AllCategories = await client.GetEntries(QueryBuilder <Category> .New.ContentTypeIs("category")); var model = new Homepage(); model.Urun = FilterCategoryItems.ToList(); model.Kategori = AllCategories.ToList(); return(View("Index", model)); }
public async Task <ActionResult> ProductDetails(string productID) { HttpClient httpClient = new HttpClient(); var options = new ContentfulOptions { DeliveryApiKey = "4df4c5c7ed276605d36b9d880f1455aea05fe9b47e2da6acf518c0771d300625", PreviewApiKey = "3aaec008db04a17e144539715f539354ff73cf8d82c2548c3045bbcfc2ee32a2", SpaceId = "bda2gc49gm0w" }; var client = new ContentfulClient(httpClient, options); var ProductDetail = await client.GetEntries(QueryBuilder <Product> .New.ContentTypeIs("categoryItems").FieldEquals(f => f.Sys.Id, productID)); return(View(ProductDetail.ToList())); }
public async Task <ActionResult> Lesson(string slug) { // slug is being passed in by the actionLink in /Lessons ViewData["slug"] = slug; var httpClient = new System.Net.Http.HttpClient(); var client = new ContentfulClient(httpClient, "TJUTn86tuAZZ0L4Aw1LmA2HUBWNoU2TBHeCghBWJTac", "XsWxHVfA6Mu5yO2rlMf_IlrmIxfy5nAnFPraPg5LGc0", "dgv1c069l5im"); // if you had the entry id you could just return the single entry without having to do a forEach in the view var entry = await client.GetEntries <Lesson>($"?content_type=lesson&fields.slug={slug}"); // logs the total number of entries returned // Console.WriteLine(entries.Total.ToString()); return(View(entry)); }
public async Task <ActionResult> UserControl(string username, string password) { HttpClient httpClient = new HttpClient(); var options = new ContentfulOptions { DeliveryApiKey = "4df4c5c7ed276605d36b9d880f1455aea05fe9b47e2da6acf518c0771d300625", PreviewApiKey = "3aaec008db04a17e144539715f539354ff73cf8d82c2548c3045bbcfc2ee32a2", SpaceId = "bda2gc49gm0w" }; var client = new ContentfulClient(httpClient, options); var AllItems = await client.GetEntries(QueryBuilder <User> .New.ContentTypeIs("users")); foreach (var item in AllItems) { if (item.Username.ToLower() == username.ToLower() && item.Password.ToLower() == password.ToLower() && username != null && password != null) { Session["username"] = username; return(RedirectToAction("Index", "Home")); } } return(RedirectToAction("Index", "State")); }
public async Task <Project> GetProject(string slug, bool usePreview = false) { _logger.LogTrace($"ContentfulContentRepository.GetProject({slug}, {usePreview})"); if (string.IsNullOrWhiteSpace(slug)) { throw new ArgumentException("Missing required parameter", nameof(slug)); } try { _options.UsePreviewApi = usePreview; var cful = new ContentfulClient(_httpClient, _options); var facetQuery = new QueryBuilder <Project>() .ContentTypeIs("project") .FieldEquals("fields.slug", slug) .Include(10); _logger.LogDebug($"executing CMS call with query: {facetQuery.Build()}"); // The GetEntry method (/entry endpoint) doesn't support including the referenced // targeted content items. We must use a list/search instead. var entrySet = await cful.GetEntries(facetQuery); var entryCount = entrySet.Items.Count(); if (entryCount > 0) { // We assume the slug is unique so there should be only one item. // Log so we can notify the content managers of naming conflicts. if (entryCount > 1) { _logger.LogWarning("GetProject({slug}). Multiple pieces of targetable content found with the same slug: ", slug); } var project = entrySet.First(); project.IncludedAssets = entrySet.IncludedAssets; project.IncludedEntries = entrySet.IncludedEntries; return(project); } else if (entryCount == 0) { _logger.LogWarning("GetProject({slug}). No pieces of targetable content found with the slug: ", slug); return(null); } } catch (Contentful.Core.Errors.ContentfulException ex) { _logger.LogError(ex, "GetHtmlBlock({slug}).", slug); var msg = "Error retrieving content: " + ex; throw new ContentException(msg, ex); } catch (Exception ex) { _logger.LogError(ex, "GetHtmlBlock({slug}).", slug); var msg = "Unable to retrieve content: " + ex; throw new ProcessException(msg, ex); } return(null); }
public async Task GetEntriesShouldSerializeCorrectlyToAnEnumerableOfArbitraryType() { //Arrange _handler.Response = GetResponseFromFile(@"EntriesCollection.json"); //Act var res = await _client.GetEntries <TestEntryModel>(); //Assert Assert.Equal(9, res.Count()); Assert.Equal("Home & Kitchen", res.First().Title); }
public async Task <List <T> > GetEntriesByType <T>() where T : IContentType { var builder = new QueryBuilder <T>().ContentTypeIs(typeof(T).Name.FirstCharacterToLower()).Include(1); return((await _contentfulClient.GetEntries(builder)).ToList()); }