Building Web Based Temperature/Humidity Monitor App With Raspberry PI 3 and Azure IoT Hub

2. April 2017 07:39

ASP.NET MVC Azure Cloud IoT Projects Raspberry Pi Web Windows 

I was planning to build a web based temperature/humidity monitoring app with Raspberry PI 3 and Windows 10 IoT Core. I have playing around with Raspbian for a while now and this time I wanted to try something different. I have been using Python to write application for Raspberry PI, Windows IoT Core with C# will be something new for me and therefore, this time I choose to go with Windows 10 IoT Core.

Here is the list of things to get started:

  • Raspberry PI 3 with Windows 10 IoT Core
  • Adafruit BME280 Temperature Humidity Pressure sensor\
  • Jumper wires
  • Power Bank
  • Visual Studio 2015/2017
  • IoT Dashboard
  • Azure account

Setting up the PI with Windows 10 IoT Core is a very straight forward process. You can read about it more here. I recommend to connect the device to your Wi-Fi network. This will give you a benefit to move your device around. The problem for the first time users will be that the device will not auto-connect to the Wi-Fi network. To solve this problem, you need to use a wired LAN connection from the network or from the local computer. Once plugged in you will be able to see the device in the IoT dashboard from where you can go to Device Portal and connect to the Wi-Fi network. After the connection is successful, you can then remove the LAN cable. To follow the exact steps, head over to this documentation. This is how your device will get displayed in the IoT dashboard.

Getting things ready in Azure

You can set up things in the cloud from the Azure Portal as well as from the IoT Dashboard itself. From dashboard you can create and provisioned a new IoT Hub and register the device in that Hub. Here is how you can do that. First sign-in to your Azure account by clicking the Sign-In option in the left hand side bar. After the sign-in is successful, you will be prompted with the below screen where you can provision a new IoT Hub and add your current device in the hub.

I am skipping the step for setting the IoT Hub from the Azure Portal as there is a good documentation available at Azure Docs. Pushing data to the IoT Hub with the SDK is easy but you can't make use of the IoT Hub alone to read that data and do your work. Therefore, you also need to set up a Queue to read that data. As of now, you cannot create a Queue from the new Azure Portal instead you have to head towards the old portal at manage.windowsazure.com and create a queue from there. To create a queue, click the New>App Services>Service Bus>Queue>Quick Create. Fill in the details to create a new queue.

Make sure that the region you are selecting here for the queue, it should be the same as your IoT Hub region. If you select a different region than that of your IoT Hub, you will not be able to associate this queue with the hub endpoint.

In the Azure Portal, to associate this queue with the IoT Hub endpoint, click the Endpoints and then click Add to add the queue to the endpoint.

Setting up the circuit

Now as you have the device and the OS ready, you can now build the circuit. The BME280 sensor can be used with both I2C and SPI. For the project, I am using I2C. Below is the Fritzing diagram for your reference. You can download the Fritzing sketch file on Github repo.

Creating Device Application

I am using Visual Studio 2017 Enterprise Edition to build the device application and the web monitor application which I will be hosting in the cloud. For creating the device application, start with selection the Windows Universal project templates and then select Blank App (Universal) template.

There is a project template available for Visual Studio which will let you build applications for Raspberry PI. The problem with that project type is that you will not be able to make use of the libraries or the SDK available for .NET yet. You can still build applications with this project type but you have to make use of REST API and using REST API is not as straight-forward as SDKs.

After the project creation is successful, you need to add below dependencies which will let you connect to IoT Hub and have a device to cloud communication. Below are the NuGet packages you need to install.

This package will enable you to have a device to cloud communication.

Install-Package BuildAzure.IoT.Adafruit.BME280

This package is the wrapper for the BME280 sensor.

Install-Package Microsoft.Azure.Devices.Client

Add the below namespaces in the Main.xaml.cs file.

using Newtonsoft.Json;
using Microsoft.Azure.Devices.Client;
using BuildAzure.IoT.Adafruit.BME280;

Declare the variables.

private DeviceClient _deviceClient;
private BME280Sensor _sensor;
private string iotHubUri = "piiothub.azure-devices.net";
private string deviceKey = "Tj60asOk5ffVAT6a6SvZKMOqo8DYKSwWV7eQ2pLf0/k=";

The iothuburi is the URL for the IoT Hub created in the Azure portal or from the IoT dashboard. You can get the device key from the Device Explorer section in the IoT Hub. You can see how to get the Key from the Device Explorer from the below screen shot. I am using the Primary Key as a devicekey in my code.

In the constructor, initialize the DeviceClient and BME280Sensor objects. I have commented out the InitializeComponent(), but if you want you can keep it as it is.

public MainPage()
{
    //this.InitializeComponent();
    deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey("raspberrypi", deviceKey), TransportType.Mqtt);
    _sensor = new BME280Sensor();
    DeviceToCloudMessage();
}

Now add a function named DeviceToCloudMessage which will connect to the IoT Hub using the device key, read the sensor data, serialize the data in JSON format and send it to the IoT Hub. Add this at the very bottom of the constructor.

private async void DeviceToCloudMessage()
{
    await _sensor.Initialize();
    float temperature = 0.00f;
    float humidity = 0.00f;
    while (true)
    {
        temperature = await _sensor.ReadTemperature();
        humidity = await _sensor.ReadHumidity();
        var sensorData = new
        {
            date = String.Format("{0}, {1}, {2}",
                                 DateTime.Now.ToLocalTime().TimeOfDay.Hours,
                                 DateTime.Now.ToLocalTime().TimeOfDay.Minutes,
                                 DateTime.Now.ToLocalTime().TimeOfDay.Seconds),
            temp = Math.Round(temperature, 2),
            humid = Math.Round(humidity, 2)
        };
        var messageString = JsonConvert.SerializeObject(sensorData);
        var message = new Message(Encoding.ASCII.GetBytes(messageString));
        await deviceClient.SendEventAsync(message);
        //Debug.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString);
        Task.Delay(5000).Wait();
    }
}

The date property in the sensorData type is being set in this specific way because we want to see the graph continuously moving. I can also read Pressure from the sensor but as I am not interested in showing this data, I am skipping it out. If you want you can use it but you also have to change the web app to show this reading. Before I can send this data to the IoT Hub, I am serializing the sensorData object and use ASCII encoding to get the byte[] and pass it to the Message class constructor. The last step is to send the message to the hub by using the DeviceClient class SendEventAsync method. In the last line I am adding a delay of 5 seconds between each reading. You can increase the time and see how the chart renders. I recommend not to go below this time delay as this might give you some false readings from the sensor.

I took this code from the documentation here and tweaked it to have the real data from the sensor connected to the device. Press Ctrl+Shift+B to build the solution. Navigate to Project and then click <project> Properties. Under Debug section, set the Start Options as shown below. Notice that the Platform is set to ARM and Configuration is Active (Debug). When you are done with debugging the code and ready to deploy the code to the device you need to change it to Release.

Unlike Raspbian, where we ssh or RDP into the device and compile or build the code, Windows 10 IoT works in a different way. You need to remote deploy the application from Visual Studio. Also, if you have enabled the remote debugging on the device, you also have to add the port number to the Remote Machine value and set the Authentication Mode to None.

NOTE: When you make changes to device application, you also need to change/increment the version of the application in the Package.appxmanifest file. If you miss this step then the application deployment will fail.

To deploy the app to the device, click the Build menu and select Deploy <Project Name>. If you are deploying the application for the first time, it will take some time to get deployed. After the deployment is successful, you will see the application under the App section. At this moment, the application is stopped. To start the application in the, click the Play button in the list to start the application. The App Type show the type of application or you can say the mode it is running on. When I created the application, I selected the UWP application and therefore, it will always run in the Foreground type. The reason I choose this application type (UWP) is because I can then use the SDK to communicate with the IoT Hub. If you want to create a Background application type then you can download this Visual Studio Extension for 2017 and this for Visual Studio 2015 which will let you build the background application. Keep in mind that you cannot use any SDK library with this project type. All you have now is the power of REST API which is not very easy to use.

Setting the Web App

You can build any kind of app to visualize the data, but because the SDK support for .NET is good I am going to set up a simple MVC application using .NET Framework. As of now, you cannot use Azure SDK with .NET Core application and also it looks like the team does not have any plans to shift their focus for releasing the SDK for .NET Core anytime soon.

Start with installing NuGet packages. First with the package that will let you read the data from the Queue.

Install-Package WindowsAzure.ServiceBus

Because this is a real-time application you also need to install SignalR

Install-Package Microsoft.AspNet.SignalR

After these packages are installed, You need a way to visualize the temperature and humidity received from the queue. To do this you can use any jquery chart plugin or any other library of your choice. I will be using Google Charts in my app, Line Charts to be precise. Installation is straight forward for the charts and you can play around with different options to tweak the look and feel of the chart. I am going to add the chart code in the Index.cshtml file. Below is the complete code for the chart to render.

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
<script>
    var data = [];
    var chart;
    google.charts.load('current', { packages: ['corechart', 'line'] });
    google.charts.setOnLoadCallback(loadChart);
    var hub = $.connection.ioTHub;
    $.connection.hub.start();
    hub.client.iotHubNotification = function (d) {
        console.log(d);
        var pi = JSON.parse(d);
        var time = pi.date.split(',');
        var temp = pi.temp;
        var humid = pi.humid;
        data.addRows([[[parseInt(time[0]), parseInt(time[1]), parseInt(time[2])], temp, humid]]);
        var options = {
            height: 250,
            hAxis: {
                title: 'Time'
            },
            vAxis: {
                title: 'Temperature / Humidity',
                gridlines: { count: 22 }
            }
        };
        chart.draw(data, options);
    };
    function loadChart() {
        data = new google.visualization.DataTable();
        data.addColumn('timeofday', 'Time');
        data.addColumn('number', 'Temperature');
        data.addColumn('number', 'Humidity');
        var options = {
            height: 250,
            hAxis: {
                title: 'Time'
            },
            vAxis: {
                title: 'Temperarture / Humidity',
                gridlines: { count: 22 }
            }
        };
        chart = new google.visualization.LineChart(document.getElementById('chart_div'));
        chart.draw(data, options);
    }
</script>

I make use of the sample code from the examples at Google Charts and used it along with some minor tweaks to suite my needs. loadChart() function is called for the first time when the page is loaded and then I have a SignalR hub which updates the chart with the same option sets that I have in the loadChart() function. I add 3 data columns to display the data in the chart. There are few things that I would like to talk about in the above code. First is the timeofday is displayed on a X-Axis because time is continuous and I want to update the chart with time. Second, the gridlines property of the vAxis let you set how many horizontal rows you want to see in the graph. I have increased it to quite a significant number because I want to see the graph in more detail. You can play around with these settings and see what looks better for you. Third, the response I receive in the hub is in string format and therefore, I have parsed that string to JSON in order to read it and set to the rows. Also note that I have leave the console.log in the above code so that when you run the web app you can see the raw data in the console.

In the HomeController.cs, first I will set the connection string to the queue which I have associated with the IoT Hub endpoint in Azure and set the queue name along with the IHubContext for SignalR communication.

private string connectionString = "Endpoint=sb://iothubqueue-ns.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=88kJcD1mvJnO1jtiiY+AcUtIoinW//V/lF2WicOJ50s=";
private string queueName = "iothubqueue";
private IHubContext _hubContext;

In the constructor, initialize the IHubContext object.

_hubContext = GlobalHost.ConnectionManager.GetHubContext<IoTHub>();

Here is the code for the IoTHub class:

using Microsoft.AspNet.SignalR;
namespace IoTHubTempWebApp.Hubs
{
    public class IoTHub : Hub
    {
        public void IoTHubNotification(string value)
        {
            Clients.All.iotHubNotification(value);
        }
    }
}

And the code for Startup class (Startup.cs)

using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(IoTHubTempWebApp.Startup))]
namespace IoTHubTempWebApp
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}

In the Index ActionResult, I will start a task which will read the messages from the queue and then SignalR will broadcast it to the client side which in turn update the chart with the latest data or temperature/humidity readings.

public ActionResult Index()
{
    Task task = Task.Run(() =>
    {
        QueueClient client = QueueClient.CreateFromConnectionString(connectionString, queueName, ReceiveMode.ReceiveAndDelete);
        client.OnMessage(message =>
        {
            Stream stream = message.GetBody<Stream>();
            StreamReader reader = new StreamReader(stream, Encoding.ASCII);
            string s = reader.ReadToEnd();
            _hubContext.Clients.All.ioTHubNotification(s);
        });
    });
    task.Wait();
    return View();
}

First I create a QueueClient object with the connection string and queue name along with the ReceiveMode. I have set ReceiveMode to ReceiveAndDelete as I want to delete the data from the queue once it has been read. Though you have an option to have the data in the queue for the maximum of 7 days in Azure. The QueueClient has an OnMessage event which process a message in an event-driven message pump, which means that as soon as the something is being added to the queue, this event is fired. I get the message body in the form of Stream, read the message to the end and pass the message to SignalR hub which in turn updates my chart in real-time. Here is the final output I have now.

If you look closely, you will notice that the temperature line is not as smooth as you thought it would be. This is because every time when Raspberry PI read the data from the sensor there is a slight change in the temperature only with a few decimal places. If you don't like this then you can change the gridlines property of the vAxis in the chart. Also you can try changing the time delay on the device to see if that impacts the lines on the chart. try changing both time delay in the device application and the gridlines in the web application to see how the chart renders.

The complete source code is available on Github.

 No Rating

Free E-Book: Understanding Azure - A Guide For Developers

16. October 2016 20:04

Cloud Microsoft Azure 

There is no time better to be a developer. With the cloud, you can compose solutions that were never possible before. You can release new features to millions of users within minutes. You can push the boundaries of current technological limitations in days. Developers can turn ideas from the ground up to successful businesses in only months. Companies need apps that allow them to maximize customer engagement and differentiate against competitors. Teams must have agility with app development for faster time to market. Developers need a flexible platform to scale up and down based on business demands, yet rock-solid resources that can withstand failure.

This guide breaks down the "why" and "how" for scenarios suited to the cloud with a focus on building apps using platform services available in Microsoft Azure. The second half of the guide showcases the breadth and depth of the Azure platform and services designed to help developers make truly competitive and differentiated applications.

The intended audience for this guide includes: 

• Developers wanting to understand why Azure is the best cloud platform for creating applications and how to get started quickly based on the app you want to build today.

• Technical leaders considering Azure to support new or existing application development.

Click to download

 No Rating

Free e-Books From Microsoft And Telerik That You Should Be Reading

14. June 2015 08:15

.NET Framework Cloud Microsoft 

I am involving myself in reading book these days rather than reading blogs. Here are 2 free e-books, one from Microsoft Press with a valuable insights on Cloud, Fundamental of Azure and the other from Telerik, The Developer's Guide To The New .NET. I encourage you to read both the books, but if you are not about cloud then you should read the book from Telerik.

Microsoft Press - Fundamentals of Azure (Download)

From Microsoft Press

The “Microsoft Azure Essentials” series helps you advance your technical skills with Microsoft Azure. “Microsoft Azure Essentials: Fundamentals of Azure” introduces developers and IT professionals to the wide range of capabilities in Azure. The authors—both Microsoft MVPs in Azure—present conceptual and how-to content for seven key areas and describe management tools and business cases.

Telerik - The Developer's Guide To The New .NET (Download)

From Telerik

This ebook is no fluff–just a developer-to-developer breakdown of what’s in store for .NET in 2015. Included are code snippets and step-by-step tutorials on handy new features and techniques.

Download for free, and learn more about:

  • Visual Studio 2015
  • .NET core goes open source
  • Cross platform development with .NET
  • C# 6.0
  • Roslyn
  • Windows 10
 No Rating

Building Real Time Applications With Firebase And AngularJS

17. May 2014 23:25

API Cloud Web 

Building real-time applications with SignalR is easy. But building real-time applications with JavaScript will be a problem if you are not aware of Firebase. I first heard of it when I was learning AngularJS. The official AngularJS site has the example where you can add, edit and delete the detials in real-time. This example uses Firebase as the storage and updates the UI in real time. 

The data is stored in JSON format and accessing it using jQuery makes it very easy. Firebase API is pretty powerful and lets you get started in minutes. To get started with Firebase, you have to first create a new account with Firebase. It's a paid service but for now you can opt for a developer account. As soon as your account is created you will be redirected to your dashboard where you can create a new application or use the one which is there by default from Firebase. Take the note of the URL ending with firebaseIO.com, we will be needing it later on at the time of implementing.

Clicking on Manage App button will take you to the details page of the application. Where you can view/edit/import/export the data in the JSON format, authentication from Facebook, Twitter, Google etc, simulate read/write operation and more. You can see the sample data in JSON format I have been testing in the below screenshot. If you already have a JSON file, you can directly import it from the dashboard using the Import JSON feature.

For this example I am using jQuery and AngularJS. If you wish you can just stick to jQuery. Create a new HTML page and add Firebase JS references in the head section. I am using AngularJS so I am going to add AngularJS reference as well.

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script src="https://cdn.firebase.com/js/client/1.0.11/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/0.7.1/angularfire.min.js"></script>

You get the first three references but the last reference is the AngularFire which is a quick way to work with Firebase applications with AngularJS. This is AngularJS code with firebase dependency.

var feedApp = angular.module('feedDataApp', ['firebase']);

feedApp.controller('feedListController', function ($scope, $firebase) {
    var fbURL = new Firebase("https://scorching-fire-0000.firebaseio.com/Feeds/");
    $scope.feedsList = $firebase(fbURL);

    $scope.save = function () {
        $scope.feedsList.$add({
            Name: $scope.feedsList.Name,
            Url: $scope.feedsList.Url,
            Description: $scope.feedsList.Description
            
        });
        $(":text").val('');
    }
});

I am not getting into the basics of AngularJS, but I will explain few things in the above code. The first line in the above code has the dependency named firebase, in simple AngularJS apps we could have skip the dependecies. Then I have the controller named feeListController, which is accompanied by a very own $scope and new param which is $firebase. Inside the controller I have a variable fbURL which holds my Firebase URL. If you see here, you willl notice that I have appended the URL with Feeds. This is because I want my data to be saved inside the Feeds section in the Firebase storage. The $scope.feedsList will hold the collection of all my entries I have in my storage. I have the save function which will save the details to my storage. Inside the Firebase's $add function, I have passed Name, Url and Description. You can pass as many params as you want. the best thing is that you don't even have to set the storage schema. As soon as you click the save button, a new entry is created in the storage. This is my storage looks like.

If you don't want to save it under the Feeds section then in the above JS file you just have to remove the Feeds from the above URL. The UI for this demo is simple, just listing down the saved JSON data in a readable form using AngularJS.

<div ng-controller="feedListController">
    <table class="table">
        <tr>
            <td>
                Name
            </td>
            <td>
                Url
            </td>
            <td>
                Description
            </td>
        </tr>
        <tr ng-repeat=" feeds in feedsList">
            <td>{{feeds.Name}}</td>
            <td>{{feeds.Url}}</td>
            <td>{{feeds.Description}}</td>
        </tr>
        <tr>
            <td>
                <input type="text" ng-model="feedsList.Name" /><br />
            </td>
            <td>
                <input type="text" ng-model="feedsList.Url" /><br />
            </td>
            <td>
                <input type="text" ng-model="feedsList.Description" /><br />
            </td>
            <td>
                <button type="submit" ng-click="save()">Add Feed</button>
            </td>
        </tr>
    </table>
</div>

Using a simple design I have displayed the details using AngularJS.

The best part is the as soon as I add a new feed details, it will get updated in the UI in real-time. Open the same page on a different browser and add a new entry. You will notice that the data is updated in real-time.

Firebase is not limited for web, it is available for iOS/OS x, Java/Android, Node.js, Ember etc. Building mobile applications using Firebase as a real-time storage will be an amazing thing to do. This is not a very good example for Firebase with AngularJS but this will get you started with Firebase and let you test a part of your application using this awesome real-time storage.

I would recommend you to look at this web application build completely on Firebase and AngularJS. 

References

 No Rating

HTML5 Video - Capture And Upload Image To Azure Storage

2. June 2013 23:46

ASP.NET Cloud HTML5 Web Azure 

I was exploring Github for some image effects/filters and I found some but still keep exploring and found an interesting plugin called face-detection. This plugin uses HTML5 getUserMedia to use your web camera only if your browser supports it. Unfortunately, IE10 still doesn’t support it. This seems cool to me, so I created a sample application to test it. This sample application will let you preview the video using your web camera and allows you to capture the image from your web camera and upload  it to the Azure storage. The javascript code for the HTML5 video I am using is from David Walsh’s post. Not every browser supports getUserMedia, so if the user is not using the browser which supports getUserMedia then you can show an alert message to the user notifying about the browser incompatibility. Here is the function which will check your browser compatibility for getUserMedia.

function hasGetUserMedia() {
 // Note: Opera is unprefixed.
 return !!(navigator.getUserMedia || navigator.webkitGetUserMedia ||
 navigator.mozGetUserMedia || navigator.msGetUserMedia);
}
 
if (hasGetUserMedia()) {
 // Good to go!
} else {
 alert('getUserMedia() is not supported in your browser');
}

To know more and explore more what you can do with getUserMedia visit HTML5Rocks. Moving further, I have a normal HTML page where initially I am placing 3 elements on the page. One is a video tag which will show the stream from the web camera attached to your machine or your laptop camera. Second, is the canvas tag which is used to show the image captured from the web camera and the third one is the normal button which will let me capture the image at my will on its click.

<video autoplay id="video" width="640" height="480"></video>
<input id="snap" type="button" value="Click" />
<canvas id="canvas" width="640" height="480"></canvas>

Notice the autoplay property in the video tag. I have set it because I don’t want the video to be frozen as soon as it started. To make the video work I am using David Walsh’s code as it is without any changes.

window.addEventListener("DOMContentLoaded", function () {
    // Grab elements, create settings, etc.
    var canvas = document.getElementById("canvas"),
        context = canvas.getContext("2d"),
        video = document.getElementById("video"),
        videoObj = { "video": true },
        errBack = function (error) {
            console.log("Video capture error: ", error.code);
        };
 
    if (navigator.getUserMedia) { // Standard
        navigator.getUserMedia(videoObj, function (stream) {
            video.src = stream;
            video.play();
        }, errBack);
    } else if (navigator.webkitGetUserMedia) { // WebKit-prefixed
        navigator.webkitGetUserMedia(videoObj, function (stream) {
            video.src = window.webkitURL.createObjectURL(stream);
            video.play();
        }, errBack);
    }
 
    // Trigger photo take
    document.getElementById("snap").addEventListener("click", function () {
        context.drawImage(video, 0, 0, 640, 480);
    });
}, false);

In the above script, you can see that it first checks if the browser or navigator has the getUserMedia support. if you see there are two conditions one for the standard and other one with the webkit prefix. In the end, the click event on the button which will let me capture the image.

When you view the application in the browser, the browser will prompt you whether you want to allow or deny the application to use the web camera.

You cannot run this just by double-clicking the file due to security reasons. You must access the web page from the server itself, either from within the Visual Studio development server, from IIS or by publishing the file on your production server. It can be annoying for many users to grant the access to the camera every time they access the page. You can save the user consent if you are using https. If you plan to stick with http, you will not be able to do this.

Looking in the address bar again, you will notice that the fav icon of the web application, changed to an animated icon. It is a little red dot which keeps on flashing notifying the user that the camera is in use. If you plan to block the access to the camera permanently or temporarily, you can then click the camera icon which is on the right hand side of the address bar.

When you click the icon you will be prompted with options to continue allow the access to the camera or always block the camera. Also if you notice the camera option, you will see that it is showing me two devices or camera attached to the machine. I build this application on my laptop so I am able to the integrated camera which is the front facing camera of my laptop and the second one is the USB camera I have plugged on my laptop’s USB port. I can choose to use any one of these. If you make any changes to these settings and click on done, you will be asked to reload the page.

This is how my web page looks.

The click button is at the bottom right hand side will let me take a snap of the feed coming from my camera. When I click the Click button, the image is captured and show on the canvas we have added on the page. This is my web page after I took the snap from my web camera.

The second image (at the bottom) is the image on the canvas that is snapped from the camera. Now I want to upload the image to my Azure cloud storage. If you look at the address bar, you’ll notice that I have used normal HTML page. It’s you wish if you want to use a simple HTML page or a web form. Both works good. The problem I am going to face with web forms is if I am going to upload the snapped image to my cloud storage or to my server repository, the page will post-back which is not cool at all. So I am going to accomplish it by making an AJAX call. Add a HTML button to your page and on its click event upload the file to the cloud.

I have the image on my canvas, therefore you just cannot retrieve the image Base64 string just like that. I am going to extract the Base64 string of the image from the canvas and pass it as a parameter. The server method will then convert the Base64 string to stream and upload it to the cloud storage. Here is the jQuery AJAX call.

function UploadToCloud() {
    $("#upload").attr('disabled', 'disabled');
    $("#upload").attr("value", "Uploading...");
    var img = canvas.toDataURL('image/jpeg', 0.9).split(',')[1];
    $.ajax({
        url: "Camera.aspx/Upload",
        type: "POST",
        data: "{ 'image': '" + img + "' }",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function () {
            alert('Image Uploaded!!');
            $("#upload").removeAttr('disabled');
            $("#upload").attr("value", "Upload");
        },
        error: function () {
            alert("There was some error while uploading Image");
            $("#upload").removeAttr('disabled');
            $("#upload").attr("value", "Upload");
        }
    });
}

The line 4 in the above script is the one which will get the Base64 string of the image from the canvas. The string is now in the variable named img which I am passing as a parameter to the Upload web method in my code-behind page. You can use web service or handler or maybe a WCF service to handle the request but I am sticking with page methods. Before you can actually make use of the Azure storage, you have to add reference of the Azure Storage library from NuGet. Fire the below NuGet command to add the Azure Storage reference to your application.

Install-Package WindowsAzure.Storage

After the package/assemblies are referenced in your code, add the below namespaces.

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.Auth;
using System.IO; //For MemoryStream
using System.Web.Services; //For WebMethod attribute

These all the namespace will help me to connect to my local cloud storage emulator or to my live cloud storage. This is my upload method which will upload the file to my live cloud storage.

[WebMethod]
public static string Upload(string image)
{
    string APIKey = "LFuAPbLLyUtFTNIWwR9Tju/v7AApFGDFwSbodLB4xlQ5tBq3Bvq9ToFDrmsZxt3u1/qlAbu0B/RF4eJhpQUchA==";
    string AzureString = "DefaultEndpointsProtocol=https;AccountName=[AccountName];AccountKey=" + APIKey;
 
    byte[] bytes = Convert.FromBase64String(image);
 
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(AzureString);
 
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
 
    CloudBlobContainer container = blobClient.GetContainerReference("img");
 
    string ImageFileName = RandomString(5) + ".jpg";
 
    CloudBlockBlob imgBlockBlob = container.GetBlockBlobReference(ImageFileName);
 
    using (MemoryStream ms = new MemoryStream(bytes))
    {
        imgBlockBlob.UploadFromStream(ms);
    }
 
    return "uploaded";
}

I have decorated this method with WebMethod attribute. This is necessary as I have to call this method from jQuery/javascript. Also the method should be public static. The AzureString  serves as the connection string for the cloud storage. You have to change the [AccountName] in the connection string to the storage account name. In my case it is propics. The method accepts the Base64 string as a parameter.

Storage is something different than that of the container and therefore I have to create a container which actually holds my images which I upload to the cloud storage. I am not explaining the code completely but it is not that complicate. To upload the file to the storage I must have a file name. The image I get from the canvas is just a Base64 string and does not have a name, so I have to give it a name. I have a random function which will generate the random string which I will be using as a file name for my image file.

//stole from http://stackoverflow.com/questions/1122483/c-sharp-random-string-generator
private static string RandomString(int size)
{
    Random _rng = new Random();
    string _chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 
    char[] buffer = new char[size];
 
    for (int i = 0; i < size; i++)
    {
        buffer[i] = _chars[_rng.Next(_chars.Length)];
    }
 
    return new string(buffer);
}

This is a small function which I stole from Stackoverflow to generate random name for my image file. So this is it and when I click the upload button on my page.

Now if I check my cloud storage I have can see the uploaded files.

This is just a simple example to get you started. You can give some cool effects before you can actually upload the files. If you do a quick search you’ll find plenty of links which will let you give some cool effects to your pictures. I came across a brilliant plugin called filtrr. You should try it and come up with something which is awesome or may be something like Instagram. Hope this help some folks out there.

References:

 No Rating

«12»