public async Task <HttpResponse> Get()
        {
            var builder = new QueryBuilder <ContentfulCommsHomepage>().ContentTypeIs("commsHomepage").Include(1);
            var entries = await _client.GetEntries(builder);

            var entry = entries.FirstOrDefault();

            if (entry != null && entry.WhatsOnInStockportEvent == null)
            {
                var sortOrder = SortOrderBuilder <ContentfulEvent> .New(f => f.EventDate);

                var eventQueryBuilder = new QueryBuilder <ContentfulEvent>()
                                        .FieldGreaterThan(f => f.EventDate, DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssK"))
                                        .ContentTypeIs("events")
                                        .OrderBy(sortOrder.Build())
                                        .Limit(1);
                var eventEntry = await _client.GetEntries(eventQueryBuilder);

                entry.WhatsOnInStockportEvent = eventEntry.FirstOrDefault();
            }

            return(entry == null
                ? HttpResponse.Failure(HttpStatusCode.NotFound, "No comms homepage found")
                : HttpResponse.Successful(_commsHomepageFactory.ToModel(entry)));
        }
Beispiel #2
0
        public async Task <PagedPostCollection> GetPagedPostsAsync(int page, int postsPerPage)
        {
            var builder = new QueryBuilder <BlogPostEntry>()
                          .ContentTypeIs("blogPost")
                          .Skip(postsPerPage * page)
                          .Limit(postsPerPage);

            ContentfulCollection <BlogPostEntry>?entries;

            try
            {
                entries = await _client.GetEntries(builder);
            }
            catch (ContentfulException e)
            {
                _logger.LogError(e, "Failed to fetch from Contentful");
                return(PagedPostCollection.Empty(postsPerPage));
            }

            var list = new List <BlogPost>();

            foreach (var entry in entries.Items)
            {
                list.Add(await entry.ToBlogPostAsync());
            }

            return(new PagedPostCollection
            {
                Posts = list.AsReadOnly(),
                CurrentPage = page,
                TotalPosts = entries.Total,
                PostsPerPage = postsPerPage
            });
        }
        public async Task <IActionResult> Index()
        {
            string resumeId = config.GetValue <string>("ResumeId");
            var    builder  = new QueryBuilder <Resume>().FieldEquals(a => a.Sys.Id, resumeId).Include(3);
            var    resume   = (await client.GetEntries(builder)).FirstOrDefault();

            return(View(resume));
        }
        public async Task <IActionResult> Index()
        {
            _logger.LogInformation("HomeController - Index() - start.");
            var qb = QueryBuilder <Product> .New.ContentTypeIs("product");

            var products = await _client.GetEntries <Product>(qb);

            return(View(products));
        }
Beispiel #5
0
        public async Task <IActionResult> Index()
        {
            var q = QueryBuilder <Posts> .New.ContentTypeIs("post");

            var allPosts = await _client.GetEntries <Posts>(q);

            ViewData["Title"] = "All Posts";
            return(View(allPosts));
        }
Beispiel #6
0
        public async Task <List <GroupAdvisor> > GetAdvisorsByGroup(string slug)
        {
            var builder = new QueryBuilder <ContentfulGroupAdvisor>().ContentTypeIs("groupAdvisors").Include(1);

            var entries = await _client.GetEntries(builder);

            if (entries == null)
            {
                return(new List <GroupAdvisor>());
            }

            var result = entries.Select(item => _contentfulFactory.ToModel(item)).ToList();

            return(result.Where(item => item.Groups.Contains(slug)).ToList());
        }
        public async Task <IActionResult> GetAssociatedCampaign([FromRoute] int id)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            //Get this working


            var dbentry = await _context.Person.FindAsync(id);

            var userid  = dbentry.FirstName + " " + dbentry.LastName;
            var builder = QueryBuilder <dynamic> .New.ContentTypeIs("campaign").FieldEquals("fields.owner", userid);

            var entriesForUser = await _client.GetEntries(builder);

            // entries would be an IEnumerable of Product
            // var entriesForUser  = await _client.GetEntry<dynamic>(userid);
            //_client.
            if (entriesForUser == null)
            {
                return(NotFound());
            }

            return(Ok(entriesForUser));
        }
Beispiel #8
0
        public async Task <IEnumerable <Blog> > GetBlogs()
        {
            var query = QueryBuilder <Blog> .New
                        .ContentTypeIs("blog")
                        .Include(10);

            return(await _client.GetEntries <Blog>(query));
        }
Beispiel #9
0
        public async Task <IViewComponentResult> InvokeAsync()
        {
            //I dont fully understand the next two lines. I kinda understand what they are asking for but not fully!
            var qb = QueryBuilder <MetaData> .New.FieldEquals("sys.id", "3A1FviHKNy6IQqSAq4UocQ");

            var home = (await _client.GetEntries <MetaData>(qb)).FirstOrDefault();

            return(View(home));
        }
        /// <summary>
        /// Get Entries of specified type using ContentType attribute of a type T
        /// </summary>
        /// <param name="client"></param>
        /// <param name="queryBuilder"></param>
        /// <param name="cancellationToken"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static Task <ContentfulCollection <Entry <T> > > GetEntriesByTypeAsync <T>(this IContentfulClient client, QueryBuilder <T> queryBuilder = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            var contentTypeDefinition = typeof(T).GetTypeInfo().GetCustomAttributes <ContentTypeAttribute>().Single();

            queryBuilder = queryBuilder ?? new QueryBuilder <T>();
            queryBuilder.ContentTypeIs(contentTypeDefinition.ContentTypeId);

            return(client.GetEntries <Entry <T> >(queryBuilder.Build(), cancellationToken));
        }
Beispiel #11
0
        public async Task <IActionResult> Index()
        {
            WhoIAm AAI = new WhoIAm();
            var    qb  = QueryBuilder <Author> .New.FieldEquals("sys.id", "56WvqVr1oIOGqScqoY6EYK");

            var iqb = QueryBuilder <Pages> .New.FieldEquals("sys.id", "5jnJqcTTW8SQQoa6wS0u8y");

            var pqb = QueryBuilder <Portfolio> .New.FieldEquals("sys.id", "3UsrI0nJzWu8Meiw2AIgE2");

            AAI.Author    = (await _client.GetEntries(qb)).FirstOrDefault();
            AAI.Pages     = (await _client.GetEntries(iqb)).FirstOrDefault();
            AAI.Portfolio = (await _client.GetEntries(pqb)).FirstOrDefault();

            ViewData["Title"] = "About Me";
            return(View("Index", AAI));
        }
Beispiel #12
0
        public async Task <IActionResult> Index()
        {
            if (appsettingsEmpty)
            {
                return(View("NoAppSettings"));
            }

            var products = await _client.GetEntries <Product>();

            return(View(products));
        }
Beispiel #13
0
        public async Task OnGet()
        {
            var qb = QueryBuilder <object> .New.Limit(5);

            Entries = await _client.GetEntries(qb);

            Assets = await _client.GetAssets();

            var imageQuery = QueryBuilder <Asset> .New.MimeTypeIs(MimeTypeRestriction.Image);

            ImageAssets = await _client.GetAssets(imageQuery);
        }
Beispiel #14
0
        public async Task <IActionResult> Index()
        {
            var model = new IndexModel();

            var qb = QueryBuilder <object> .New.Limit(5);

            model.Entries = await _client.GetEntries(qb);

            model.Assets = await _client.GetAssets();

            var imageQuery = QueryBuilder <Asset> .New.MimeTypeIs(MimeTypeRestriction.Image);

            model.ImageAssets = await _client.GetAssets(imageQuery);

            return(View(model));
        }
Beispiel #15
0
        public async Task <IActionResult> Index()
        {
            if (appsettingsEmpty)
            {
                return(View("NoAppSettings"));
            }

            var space = await _client.GetSpace();

            var entries = await _client.GetEntries <dynamic>();

            var assets = await _client.GetAssets();

            var contentfulExampleModel = new ContentfulExampleModel()
            {
                Space   = space,
                Entries = entries.ToList(),
                Assets  = assets.ToList()
            };

            return(View(contentfulExampleModel));
        }
Beispiel #16
0
        private async Task <ContentfulCollection <Page> > Fetch(QueryBuilder <Page> builder)
        {
            var result = await _contentfulClient.GetEntries(builder);

            return(result);
        }
        public async Task <ActionResult <IEnumerable <Course> > > Get()
        {
            var courses = await _client.GetEntries <Course>();

            return(courses);
        }
        /// <inheritdoc />
        public IEnumerable <IDocument> Execute(IReadOnlyList <IDocument> inputs, IExecutionContext context)
        {
            Space space = null;

            try
            {
                space = _client.GetSpace().Result;
            }
            catch (AggregateException ae)
            {
                ae.Handle((ex) => {
                    if (ex is ContentfulException)
                    {
                        Trace.TraceError($"Error when fetching space from Contentful: {ex.Message}");
                        Trace.TraceError($"Details: {(ex as ContentfulException).ErrorDetails.Errors}");
                        Trace.TraceError($"ContentfulRequestId:{(ex as ContentfulException).RequestId}");
                    }

                    return(false);
                });
            }

            var queryBuilder = CreateQueryBuilder();
            ContentfulCollection <JObject> entries = null;

            try
            {
                entries = _client.GetEntries(queryBuilder).Result;
            }
            catch (AggregateException ae)
            {
                ae.Handle((ex) => {
                    if (ex is ContentfulException)
                    {
                        Trace.TraceError($"Error when fetching entries from Contentful: {ex.Message}");
                        Trace.TraceError($"Details: {(ex as ContentfulException).ErrorDetails.Errors}");
                        Trace.TraceError($"ContentfulRequestId:{(ex as ContentfulException).RequestId}");
                    }

                    return(false);
                });
            }

            if (_recursive && entries.Total > entries.Items.Count())
            {
                entries = FetchEntriesRecursively(entries);
            }

            var includedAssets  = entries.IncludedAssets;
            var includedEntries = entries.IncludedEntries;

            var locales = space.Locales.Where(l => l.Default);

            if (_locale == "*")
            {
                locales = space.Locales;
            }
            else if (!string.IsNullOrEmpty(_locale))
            {
                locales = space.Locales.Where(l => l.Code == _locale);
            }

            if (!locales.Any())
            {
                //Warn or throw here?
                throw new ArgumentException($"Locale {_locale} not found for space. Note that locale codes are case-sensitive.");
            }

            foreach (var entry in entries)
            {
                foreach (var locale in locales)
                {
                    var localeCode = locale.Code;

                    var items = (entry as IEnumerable <KeyValuePair <string, JToken> >).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

                    var content = "No content";

                    content = items.ContainsKey(_contentField) ? GetNextValidJTokenValue(items[_contentField], locale).Value <string>() : "No content";

                    if (string.IsNullOrEmpty(_contentField))
                    {
                        content = "";
                    }

                    var metaData = items
                                   .Where(c => !c.Key.StartsWith("$") && c.Key != "sys")
                                   .Select(c => new KeyValuePair <string, object>(c.Key, GetNextValidJTokenValue(c.Value, locale))).ToList();
                    metaData.Add(new KeyValuePair <string, object>(ContentfulKeys.EntryId, $"{entry["sys"]["id"]}"));
                    metaData.Add(new KeyValuePair <string, object>(ContentfulKeys.EntryLocale, localeCode));
                    metaData.Add(new KeyValuePair <string, object>(ContentfulKeys.IncludedAssets, includedAssets));
                    metaData.Add(new KeyValuePair <string, object>(ContentfulKeys.IncludedEntries, includedEntries));
                    var doc = context.GetDocument(context.GetContentStream(content), metaData);

                    yield return(doc);
                }
            }

            JToken GetNextValidJTokenValue(JToken token, Locale locale)
            {
                var localizedField = token.Children <JProperty>().FirstOrDefault(c => c.Name == locale.Code);

                if (localizedField == null && locale.FallbackCode != null)
                {
                    return(GetNextValidJTokenValue(token, locales.FirstOrDefault(c => c.Code == locale.FallbackCode)));
                }

                return(localizedField?.Value);
            }
        }