Monday 22 August 2016

Receiving expiration messages for commands in IoT Hub

When you are dealing with devices in an IoT scenario, you want to ensure that you get a feedback to the commands you issued. Generally, the nature of the feedback itself depends on the type of IoT scenario you are trying to build. For example - if the device is tied to a building which sends out temperature readings of the rooms, it may not be necessary that the device receive a "ChangeTemperature" command immediately. It could very well be acceptable if it take up the command after a minute. However, imagine a scenario where you are trying to remotely control a moving object e.g. drone, toy car, ship, cattle, you may want to ensure that commands are received by the remote object quickly or you get to re-issue another command after the previous command has expired.

IoT Hub's service SDK provides a very useful API to receive feedback to every command that you issued.

1. Enable acknowledgement of the command when you issue it. If you are only looking for negative acknowledgements (expiration, rejection etc.) then set the acknowledgement enum to "NegativeOnly".


2. Start a feedback receiver and verify the status of the commands.



Now, when message expires before it is received by the device, you get a feedback with status "Expired" and you can re-issue the command if you like :).



Thursday 11 August 2016

Creating GIF images programatically

Do you have a requirement to create GIF files dynamically? I had a similar requirement where I needed to create GIF files which will show a set of data point over a fixed time duration.

It turns out that the StackOverflow and GitHub are a great place :). There are plenty of libraries available that could help me achieve this. In the end, I picked BumpKit. I mixed its capabilities with a wonderful extension class mentioned in a StackOverflow post.

Code:

static void Main(string[] args)
        {
            string content = @"{
""items"":
[
    {
        ""Value"": ""120""
    },
    {
        ""Value"": ""125""
    },
    {
        ""Value"": ""130""
    },
    {
        ""Value"": ""135""
    },
    {
        ""
Value"": ""140""
    }
]
            }";
            JObject obj = JObject.Parse(content);
            Console.WriteLine(obj);
            var img = Image.FromFile(@"Untitled.png");
            int delay = 0;
            using (GifWriter writer = new GifWriter("output.gif", 1000, -1))
            {
                foreach (var jItem in obj["items"])
                {
                    delay += 1000;
                    string imagePath = null;
                    var backgroundImage = img.ScaleToFit(new Size(100, 100), false, ScalingMode.Overflow);
                    using (var gfx = Graphics.FromImage(backgroundImage))
                    {
                        gfx.DrawString(jItem["
Value"].ToString(),
                            new Font(FontFamily.Families.First(f => f.Name.Contains("Times")), 15),
                            Brushes.White, 15, 25, 10,
                            new[] { Color.Black},
                            new[] { (float) 1 });
                        gfx.DrawImage(backgroundImage, 0, 0);
                    }
                    writer.WriteFrame(backgroundImage, delay);
                }
            }
            Console.ReadLine();
        }
    }

Untitled.png is a blank image with white background that I created using MSPaint.

Output:


You can let your imagination decide how you want to use this to create interesting gifs programmatically.

Tuesday 9 August 2016

Simple OTP verification - Azure Multi Factor Authentication Provider

Have you ever run into a situation where you need to apply an additional layer of security on certain areas of your application (web and mobile both)? If you look at most of the applications that are available today, they tend to use "Multi Factor Authentication" for similar objective, but during authentication process. One way of implementing MFA is to SMS a one time use password/phrase to user's registered mobile phone number and have user enter that value. Quite familiar, isn't it?

Imagine if you had a similar requirement where you have already authenticated the user but you want the user to go through another verification process before letting them perform some action - this is really not a user authentication process but additional security for whatever he/she is going to do next (e.g. Change Password?, Remove Account? etc.). One Time Password is common utility for such scenario as well.

Let us have a look at Multi Factor Authentication Provider Service available in Microsoft Azure and how to use that to achieve the specific scenario.

You can create a stand alone "MFA Provider" in Azure.


You can choose to associate the MFA provider to an Azure Active Directory if you like. In my scenario, I did not associate it with an AAD. Please do note that this setting can not be modified later, so do give this a thought.



You are now all set to integrate the OTP feature in your application.

Click the "Manage" link.


It opens up another portal where you can configure multiple properties of the MFA server (including the audio message that user would hear when they get a phone call if we use phone call verification). Amount of modification to the out of the box functionality is totally up to you to decide. I would not delve into that in this post.


Click on SDK link. It would open up a page which gives away the standard SDKs that you can use for interacting with the MFA provider you created. Each download has a specific certificate associated with it - therefore if you want to reuse it for other MFA providers, ensure that you have the right certificate.


I downloaded the ASP.NET 2.0 C# version. It is a website. You can open it in visual studio.

The version I downloaded gave me compilation errors as it was not able to identify the highlighted file part of solution.




There can be n reasons of why it was not working - I just took the short route of copying the file content into "example.aspx.cs" file and excluding the highlighted file. Since the source code uses a hard coded path "C:\\cert_key.p12" for locating the certificate file, I (being lazy) copied the file to C:\ and ran the application. You can change the path as per your liking.

Once you run the solution, it opens a test page that lets you test out different capabilities of MFA provider. In this case I am interested in verifying the OTP functionality.


If you are not in USA, it would not work out of the box as country code "1" is hard coded in the SDK code :). You can modify the country code in the class "PfAuthParams".


When testing the app, enter your phone number without country code. If you want to debug, put a break point at "pf_authenticate_internal" function.


"get_response_status" function returns the value of OTP sent to the end user. Your application can store that and compare that against the user entered value for OTP. Easy, right!!


Of course, there are better ways to do this. This is just one simple way to achieve this. Good thing is that you do not have procure a MFA server and you pay for the number of authentication (or number of users) your application goes through.

Wednesday 3 August 2016

protobuf vs json

It can be a demanding ask for you to decide between two great options. Case in point - ProtoBuf or JSON.

From my experience, the decision boils down to following:

1. Is the messaging contract between two parties strict?

winner: protobuf.

protobuf expects folks to work with an Interface Definition Language (IDL) and produce a .proto file. Once the file is ready, both parties need to generate their platform specific proxies from the .proto file and generated code should not be modified.

json is a little liberal format and does not force a schema by itself. There are tools available to force a json schema but json serialization process does not force schema validation itself. It is always an added step and is performed by referencing another 3rd party (and may be not free) library.

2. What is the expectations around speed of serialization/deserialization?

winner: protobuf

3. What is the expectation around size of serialized data?

winner: protobuf

4. What is the expectation around readability of serialized data?

winner: json

5. What is the application?

winner: json (web applications, web apis, dynamic data type requirements.)
winner: protobuf (low latency scenarios, high throughput etc.)


reference: http://maxondev.com/serialization-performance-comparison-c-net-formats-frameworks-xmldatacontractserializer-xmlserializer-binaryformatter-json-newtonsoft-servicestack-text/

http://ganges.usc.edu/pgroupW/images/a/a9/Serializarion_Framework.pdf

File upload from device in IoT Hub ("Message":"ErrorCode:InvalidStorageEndpointProperty;BadRequest")

I was recently trying out the newly introduced feature of "File Upload" in IoT Hub and ran into an interesting issue. I followed every step mentioned in the Azure documentation for the code creation and configured the file upload on IoT Hub using the prescribed link

The code kept failing with following error:

Exception: Exception caught: 'System.ArgumentException' in mscorlib.dll ("{"Message":"ErrorCode:InvalidStorageEndpointProperty;BadRequest",
 "ExceptionMessage":"Tracking ID:98cf5df7f44c4d0f9a463b1cec691e14-G:4-TimeStamp:08/03/2016 05:59:50"}").
 Exception caught: 'System.ArgumentException' in mscorlib.dll
 ("{"Message":"ErrorCode:InvalidStorageEndpointProperty;BadRequest",
 "ExceptionMessage":"Tracking ID:98cf5df7f44c4d0f9a463b1cec691e14-G:4-TimeStamp:08/03/2016 05:59:50"}")

As it turns out there is a bug in the current Azure Portal UI that does not set the storage account details and container name in the "File Upload" options. It shows the UI as following:


You can verify that by getting the details of the resource through PowerShell.

PS C:\windows\system32> Login-AzureRmAccount
PS C:\windows\system32> $res = Get-AzureRmResource -ResourceId /subscriptions/XYZ/resou
rceGroups/StreamAnalytics-Default-East-US/providers/Microsoft.Devices/IotHubs/123iothub
PS C:\windows\system32> $res

Name              : 123iothub
ResourceId        : /subscriptions/XYZ/resourceGroups/StreamAnalytics-Default-East-US/
                    providers/Microsoft.Devices/IotHubs/123iothub
ResourceName      : 123iothub
ResourceType      : Microsoft.Devices/IotHubs
ResourceGroupName : StreamAnalytics-Default-East-US
Location          : eastus
SubscriptionId    :
XYZ
Tags              : {}
Properties        : @{state=Active; provisioningState=Succeeded; hostName=123iothub.azure-devices.net;
                    eventHubEndpoints=; storageEndpoints=; messagingEndpoints=; enableFileUploadNotifications=True;
                    cloudToDevice=; operationsMonitoringProperties=; features=DeviceManagement; generationNumber=0}
ETag              : AAAAAABLpj8=
Sku               : @{name=F1; tier=Free; capacity=1}

PS C:\windows\system32> $res.Properties

state                          : Active
provisioningState              : Succeeded
hostName                       : 123iothub.azure-devices.net
eventHubEndpoints              : @{events=; operationsMonitoringEvents=}
storageEndpoints               : @{$default=}
messagingEndpoints             : @{fileNotifications=}
enableFileUploadNotifications  : True
cloudToDevice                  : @{maxDeliveryCount=10; defaultTtlAsIso8601=PT1H; feedback=}
operationsMonitoringProperties : @{events=}
features                       : DeviceManagement
generationNumber               : 0

PS C:\windows\system32> $res.Properties.storageEndpoints
$default
--------
@{sasTtlAsIso8601=PT2H; connectionString=; containerName=}

So, till the UI gets fixed, the work around is to either to update through PowerShell or use a wonderful site called https://resources.azure.com



Once you have updated the details, the UI starts to show the assigned storage account as well. Of course, the file upload functionality starts to work as well.