Example #1
0
        public async Task <IEnumerable <FoodGroupJson> > GetAsync()
        {
            var client = new CosmosClient();
            var db     = client.ConnectAndGetDatabase(this.configuration);
            var query  = db.GetCollection <FoodGroup>(Collections.GetCollectionName <FoodGroup>()).AsQueryable();
            var list   = (await query.ToListAsync()).OrderBy(fg => fg.Code);

            return(list.Select(fg => FoodGroupJson.FromFoodGroup(fg)));
        }
Example #2
0
        public async Task <IEnumerable <NutrientDetailJson> > GetAsync()
        {
            var client = new CosmosClient();
            var db     = client.ConnectAndGetDatabase(this.configuration);
            var query  = db.GetCollection <NutrientDefinition>(Collections.GetCollectionName <NutrientDefinition>()).Find(_ => true);
            var list   = new List <NutrientDetailJson>();
            await query.ForEachAsync(n => list.Add(NutrientDetailJson.FromNutrientDefinition(n)));

            return(list.OrderBy(n => n.SortOrder));
        }
        public async Task <IActionResult> Get(string id)
        {
            id = id.Trim();
            if (string.IsNullOrWhiteSpace(id))
            {
                return(NotFound());
            }
            var client = new CosmosClient();
            var db     = client.ConnectAndGetDatabase(this.configuration);
            var query  = await db.GetCollection <FoodItem>(Collections.GetCollectionName <FoodItem>()).FindAsync(fi => fi.FoodId == id);

            var item = await query.FirstOrDefaultAsync();

            if (item == null)
            {
                return(NotFound());
            }
            return(Ok(FoodItemDetailJson.FromFoodItem(item)));
        }
Example #4
0
        public static async Task <IActionResult> RunAsync([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
                                                          TraceWriter log,
                                                          ExecutionContext context)
        {
            log.Info("C# HTTP trigger function processed a request.");

            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();

            var client = new CosmosClient();
            var db     = client.ConnectAndGetDatabase(config);
            var query  = db.GetCollection <FoodGroup>(Collections.GetCollectionName <FoodGroup>()).AsQueryable();
            var list   = (await query.ToListAsync()).OrderBy(fg => fg.Code);

            return(new OkObjectResult(list.Select(fg => FoodGroupJson.FromFoodGroup(fg))));
        }
        public async Task <IEnumerable <FoodItemJson> > GetAsync([FromQuery] string groupId = null, [FromQuery] string search = null)
        {
            if (groupId != null)
            {
                groupId = groupId.Trim();
            }
            if (search != null)
            {
                search = search.Trim();
            }
            if (string.IsNullOrWhiteSpace(groupId) && string.IsNullOrWhiteSpace(search))
            {
                return(Enumerable.Empty <FoodItemJson>());
            }
            var client     = new CosmosClient();
            var db         = client.ConnectAndGetDatabase(this.configuration);
            var projection = Builders <FoodItem> .Projection.Include(fi => fi.FoodId).Include(fi => fi.FoodGroupId)
                             .Include(fi => fi.Description).Include(fi => fi.ShortDescription);

            var query = db.GetCollection <FoodItem>(Collections.GetCollectionName <FoodItem>());
            IFindFluent <FoodItem, FoodItem> findFluent;

            if (string.IsNullOrWhiteSpace(groupId))
            {
                findFluent = query.Find(fi => fi.Description.Contains(search));
            }
            else if (string.IsNullOrWhiteSpace(search))
            {
                findFluent = query.Find(fi => fi.FoodGroupId == groupId);
            }
            else
            {
                findFluent = query.Find(fi => fi.FoodGroupId == groupId && fi.Description.Contains(search));
            }
            var projectedQuery = findFluent.Limit(100).Project(projection);
            var list           = new List <FoodItemJson>();
            await projectedQuery.ForEachAsync(fi => list.Add(FoodItemJson.FromFoodItem(fi)));

            return(list.OrderBy(fi => fi.Description));
        }
Example #6
0
        static async Task Run()
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json")
                          .AddEnvironmentVariables();

            var config = builder.Build();
            var client = new CosmosClient();
            var db     = client.ConnectAndGetDatabase(config);

            Console.WriteLine("Grabbing the list of food groups...");
            var groups = await db.GetCollection <FoodGroup>(Collections.GetCollectionName <FoodGroup>()).AsQueryable().ToListAsync();

            Console.WriteLine($"Found {groups.Count} groups. Listing them...");
            foreach (var group in groups)
            {
                Console.WriteLine($"{group.Description}");
            }

            Console.WriteLine("Trying to grab a food item...");

            try
            {
                var foodItem = await db.GetCollection <FoodItem>(Collections.GetCollectionName <FoodItem>()).AsQueryable().FirstOrDefaultAsync();

                foodItem.DeserializeNutrients();
                Console.WriteLine($"Mmmm. Found some {foodItem.Description} in a portion of {foodItem.Weights[0].Amount} {foodItem.Weights[0].Description}");
                Console.WriteLine($"First nutrient is {foodItem.Nutrients[0].Definition.Description} at {foodItem.Nutrients[0].AmountInHundredGrams}");
                Console.WriteLine($"of {foodItem.Nutrients[0].Definition.UnitOfMeasure} per hundred grams.");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"No soup for you! Message: {ex.Message}");
                Console.ReadLine();
                throw;
            }
        }
Example #7
0
        public async Task <IActionResult> Get(string code)
        {
            code = code.Trim();
            if (string.IsNullOrWhiteSpace(code))
            {
                return(NotFound());
            }
            var client = new CosmosClient();
            var db     = client.ConnectAndGetDatabase(this.configuration);
            var query  = await db.GetCollection <FoodGroup>(Collections.GetCollectionName <FoodGroup>()).FindAsync(fg => fg.Code == code);

            var group = await query.FirstOrDefaultAsync();

            if (group == null)
            {
                return(NotFound());
            }
            var foodsQuery = await db.GetCollection <FoodItem>(Collections.GetCollectionName <FoodItem>()).
                             FindAsync(food => food.FoodGroupId == code);

            var list = await foodsQuery.ToListAsync();

            return(Ok(FoodGroupDetailJson.FromFoodGroupAndFoodItemList(group, list)));
        }
Example #8
0
        public async Task <IActionResult> GetTopFoodsAsync(string tag, [FromQuery] string groupId = null)
        {
            if (groupId != null)
            {
                groupId = groupId.Trim();
            }
            tag = tag.Trim();
            if (string.IsNullOrEmpty(tag))
            {
                return(NotFound());
            }
            var client = new CosmosClient();
            var db     = client.ConnectAndGetDatabase(this.configuration);
            var coll   = db.GetCollection <BsonDocument>(Collections.GetCollectionName <FoodItem>());

            var result    = new TopNutrientJson();
            var foodItems = new List <FoodItemNutrientJson>();

            var sort = Builders <BsonDocument> .Sort.Descending($"NutrientDoc.nutrients.{tag}.amount");

            var projection = Builders <BsonDocument> .Projection
                             .Include("_id")
                             .Include("FoodGroupId")
                             .Include("ShortDescription")
                             .Include("Description")
                             .Include($"NutrientDoc.nutrients.{tag}");

            IFindFluent <BsonDocument, BsonDocument> query;

            if (string.IsNullOrEmpty(groupId))
            {
                query = coll.Find(_ => true)
                        .Project(projection)
                        .Sort(sort)
                        .Limit(100);
            }
            else
            {
                query = coll.Find(new BsonDocument {
                    { "FoodGroupId", groupId }
                }).Project(projection)
                        .Sort(sort)
                        .Limit(100);
            }

            var first = true;
            await query.ForEachAsync(fi =>
            {
                var nutrient = fi["NutrientDoc"].AsBsonDocument["nutrients"].AsBsonDocument[tag].AsBsonDocument;
                if (first)
                {
                    result.Id            = nutrient["id"].AsString;
                    result.Description   = nutrient["description"].AsString;
                    result.UnitOfMeasure = nutrient["uom"].AsString;
                    first = false;
                }
                var foodItemNutrient = new FoodItemNutrientJson
                {
                    Id                   = fi["_id"].AsString,
                    FoodGroupId          = fi["FoodGroupId"].AsString,
                    Description          = fi["Description"].AsString,
                    ShortDescription     = fi["ShortDescription"].AsString,
                    AmountInHundredGrams = nutrient["amount"].AsDouble
                };
                foodItems.Add(foodItemNutrient);
            });

            result.FoodItems = foodItems.ToArray();
            return(Ok(result));
        }