Pick the Right Meal Using C#, ASP.NET and Nutritionix
Time to read: 7 minutes
Proper nutrition is a topic that is near and dear to my heart. I struggled at one point in my life with making the right food choices and over time the weight piled on. After learning a lot about nutrition, I feel like I have a good handle on making choices in the grocery store. This isn’t always easy though and it is really difficult when traveling.
As an evangelist I travel a lot, so often I come home to an empty fridge. Sometimes I know that I will be leaving in a few days for another trip so I don’t want to do a full fridge restock. A couple quick and easy meals is all I’m after. There be dragons! Convenience food is some of the worst stuff on the planet for you but there are healthier options even in this realm of on-the-go eating. With a couple of quick photos of barcodes and an MMS message, you can get the nutrition decision you need without having to read labels and compare calories, protein, carb and fat totals.
Try it yourself! Grab some food items and snap some clear, up close pictures of their barcodes and send them to:
United States: (267) 433-2613
Canada: (450) 954-1629
Recipe (get it?!)
- Twilio account – sign up for a free account here
- Twilio .NET helper library
- MMS enabled Twilio number
- Zxing.NET barcode scanner NuGet package
- Nutritionix API account
- Nutritionix NuGet package
How It Works
Our user will have a few ways to work with our barcode to nutrition info service. The first option is sending in a single barcode. In this case, we will return nutrition information for the single product. Another option is to send in multiple barcodes with an optional keyword to indicate how to process the information. If no keyword is specified we will total up the nutrition information for all of the products send in. This will help the user tell the nutrition details for a meal composed of these items. If the user sends in the ‘compare’ keyword, we will send back a “winner” based on the calories, protein, carbs and fat totals for the given items. This will help the user choose a particular item based on their nutrition goals.
There is a chance that some barcodes will not be recognizable. There is also a chance that some products will not be available in the Nutritionix database. I chose the Zxing.NET barcode reader because it was free, easy to work with and worked on most barcodes I sent to it. I chose Nutritionix because they have a well-populated database of items with the ability to query via barcode. There are many other nutrition databases available which have more items in them. Feel free to explore the options out there.
The full project is available if you want to follow along: Github
Setting Up the Project
Start by creating a new ASP.NET Web Application project from the Empty template with MVC references:
Add a new controller to the project called BarcodeNutrition. Delete the default Index() method since we won’t need it in our application.
Now we need to install some NuGet packages for the libraries we will be using. First we’ll install the Twilio.Mvc package (commands shown for Package Manager Console):
Next, we’ll install the ZXing.NET package:
Finally, install the Nutritionix package:
Add the following using statements to the top of BarcodeNutritionController.cs:
We also need to add an action method to handle incoming messages from Twilio. This will be the entry point to our service:
All the pieces are in place for us to begin writing our barcode to nutrition info service. There are a lot of moving parts in this hack so you’re probably going to want to be able to test things as you build them. When Twilio receives an incoming message at your phone number it will need to make an HTTP request to our Inbound action method. If you want to test locally you will need to expose your localhost to the outside world. I recommend using ngrok for this. You can use this tutorial to help get you set up with ngrok on your Windows machine. Once you have that up and running, configure the Messaging URL for your Twilio number in the numbers portal to point at your local server’s /BarcodeNutrition/Inbound endpoint:
With this set up you will be able to send barcodes to your Twilio number during the development process so I’d encourage you to set breakpoints and write tests as you follow along.
Reading Barcodes From the Incoming Images
We first check to make sure the user sent in at least one image. If they didn’t we need to let them know to try again with some barcodes:
This will generate TwiML to be returned to Twilio. TwiML is XML that tells Twilio how to handle incoming messages and calls. In this case we are returning TwiML that tells Twilio to send an SMS message back to the user with the text specified. Here is the TwiML generated by the code above:
Read this document to learn more about TwiML.
With that out of the way we can get down to the business of decoding the barcode images. Add this code to the Inbound method:
This code relies on a DecodeBarcodes method that we will add now:
For each barcode image that is sent in there will be a corresponding media URL. We use this URL to populate a Bitmap object which is required by the ZXing.NET barcode reader. If the barcode is able to be decoded we add the result string to an array of EAN codes. If any of the barcodes are unreadable we return null from the method. A failed barcode reading means we can’t perform a total or a comparison so we want to give the user a chance to try again.
At this point we have a list of EAN codes that can be used to query the Nutritionix database for nutritional info.
Before moving on, try these barcodes to make sure the reader is working properly:
Mmm, Hot Pockets and Cheerios…that’s a meal fit for a king if I’ve ever seen one.
Fetching Nutrition Info From Nutritionix
The Nutritionix API is queryable using the barcode numbers available on our food and drink items. The NutritionixClient object in the NuGet package we added earlier makes it really easy to work with this information. Add the following class level variables to the top of the BarcodeNutritionController making sure to replace the placeholders with your credentials:
Next we’ll set up a list for food items we successfully query and another for barcodes that are not found in the Nutritionix database:
Now we’ll add the method that will populate these lists by querying the Nutritionix API:
Note the try/catch block in the middle of the method. This will handle scenarios where the barcode format is not recognized since NutritionixClient will throw an HttpException for the resulting 404 error in this case.
Now we can call the nutrition lookup from our action method passing in the two lists as reference parameters:
If we had to skip any barcodes because they weren’t in the Nutritionix database, we’ll let the user know to try again without these barcodes:
At this point we have all of the food items populated and can process the results based on what the user requested. In the case where we only have one barcode, we’ll return nutrition details for just that item:
If the user wanted the server to total up the nutrition info either by specifying the ‘total’ keyword or by not specifying a keyword we’ll use the following method:
The last option for processing the results is the ‘compare’ function:
This method tries to help the user pick the best choice depending on some common nutrition goals – low calorie, high protein, low carb and low fat. It’s not a perfect way to pick the right food but it’ll do when you’re stuck at a gas station trying to decide between cheese puffs and a granola bar.
Now we just need to add a method to decide which calculation to use:
We’ll call this from our Inbound method and return the resulting response string as TwiML to Twilio. The user will get a text message with their requested nutrition information. Armed with this info, hopefully they will make the right choice in the grocery aisle.
Now that the app is completely built, give it a try by sending a couple of barcodes to your new Twilio MMS enabled phone number. Make sure to try out the “compare” feature!
Next Steps
I hope you find this tool as helpful as I did when I wrote it. It definitely served me well this week as I came back from Xamarin Evolve only to have to head off to Connect.js in a few days. With a quick couple of picture messages I was able to grab a few healthy meals for the week!
You don’t have to stop with what I built here though. Here’s some next steps:
- Render a nutrition label and return it via MMS
- Send the nutrition data to MyFitnessPal, Fitbit, etc.
- Make better choices and live a healthier life!
I hope you’re excited to build lots of cool things with MMS using C#. I’m stoked to see what you create so please share them with me on Twitter @brentschooley or through email at brent@twilio.com.
Related Posts
Related Resources
Twilio Docs
From APIs to SDKs to sample apps
API reference documentation, SDKs, helper libraries, quickstarts, and tutorials for your language and platform.
Resource Center
The latest ebooks, industry reports, and webinars
Learn from customer engagement experts to improve your own communication.
Ahoy
Twilio's developer community hub
Best practices, code samples, and inspiration to build communications and digital engagement experiences.