Archive for the ‘Azure’ Category

Custom Vision Companion on ioProgrammo

20/10/2017 Leave a comment

I have written a new article for the n°219 of ioProgrammo (November 2017). I talk about Custom Vision Service and show how to build a Universal Windows Platform app that uses these APIs to get predictions from images and photos taken in the real world.

ioProgrammo n°219 (November 2017)

ioProgrammo n°219 (November 2017)

The app described in the article, Custom Vision Companion, is open source and is available on GitHub.


Xamarin.Forms and Azure Mobile apps on ioProgrammo

08/09/2016 1 comment

I have written a new article for the n°206 of ioProgrammo (September 2016). This time I talk about Xamarin.Forms and how to use it together with Azure Mobile apps in order to create an app that is strictly integrated with Facebook.

ioProgrammo September 2016

ioProgrammo September 2016

Categories: .NET, Azure, C#, General, Xamarin

Accessing service information in custom APIs of Mobile Services .NET Backend

07/04/2014 Comments off

When working with Mobile Services .NET Backend, we could have the need to access service information, like settings, log, push client, etc.

The TableController class provides a Services property that exposes all the service information, so if we inherit from this object, we have immediately use it. However, if we want to define a custom API, we need to inherit from the standard ApiController class, that doesn’t contain any reference to the Mobile Service.

If we look deeper, we’ll see that TableController inherits from ApiController and defines the following property:

public ApiServices Services { get; set; }

It provides an object that allows to access all the service information and that it is automatically set via Autofac property injection. So, we can add the same property in our custom APIs classes that directly inherit from ApiController. For example:

public class ImagesController : ApiController
    public ApiServices Services { get; set; }

    public string Get()
        // Writes a message in the Service Log.
        Services.Log.Info("Method Images/Get called");

        return "Data";

Of course, we can also create a base class with this property and make custom APIs inherit from it, so that they can directly use it.

Categories: Azure, C#, Mobile Services

Using Dependency Injection in Mobile Services .NET Backend

24/03/2014 1 comment

The .NET Backend of Mobile Services makes use of Dependency Injection through the Autofac library. So, we can configure it by adding our dependencies, just like we would do in any other .NET application.

Suppose we have the following interface and one possible implementation:

public interface ILocationService
    Task<string> ReverseGeocodeAsync(double latitude, double longitude);

public class BingLocationService : ILocationService
    public Task<string> ReverseGeocodeAsync(double latitude, double longitude)
        // ...
        return Task.FromResult("<value>");

We want to pass it to our controllers using Inversion of Control. So, let’s open the WebApiConfig.cs file in the App_Start folder. First of all, we need to add the using Autofac; statement at the top of the file, because we need some extension methods that are defined within this namespace.

Then, locate the following line in the Register method:

// Use this class to set WebAPI configuration options
HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options));

The ConfigBuilder constructor has an overload accepting an Action that receives the Inversion of Control container as argument. So, we can use it do add our dependency:

HttpConfiguration config = 
    ServiceConfig.Initialize(new ConfigBuilder(options, (container) =>

Now the dependcy is registered in the container, and so we can use it as usual:

public class LocationController : ApiController
    private ILocationService locationService;

    public LocationController(ILocationService locationService)
        this.locationService = locationService;

    public async Task<string> GetAddress(double latitude, double longitude)
        var address = await locationService.ReverseGeocodeAsync(latitude, longitude);
        return address;

If we prefer a more structured solution, instead of defining all the configurations within the Register method, we can also create a class that inherits from ConfigBuilder and overrides its ConfigureServiceDependencies method:

public class MyCustomConfigBuilder : ConfigBuilder
    public MyCustomConfigBuilder(ConfigOptions options) 
        : base(options)
    { }

    protected override void ConfigureServiceDependencies(HttpConfiguration config, 
        ContainerBuilder containerBuilder)

        base.ConfigureServiceDependencies(config, containerBuilder);

The last thing to do is to tell the application that we want to use our custom ConfigBuilder:

// Use this class to set WebAPI configuration options
HttpConfiguration config = ServiceConfig.Initialize(new MyCustomConfigBuilder(options));

The Autofac site contains a lot of documentation and example on how to use it, so we can refer to it for more information.

Categories: Azure, C#, Mobile Services

Authorization and public Help pages for Mobile Services written in .NET

28/02/2014 1 comment

Last week one of the most awaited feature for Azure Mobile Services has been released: the full support for writing backend logic using .NET and the ASP.NET Web API framework. We can now use Web API and Visual Studio to write, test and deploy our services. On Scott Guthrie’s blog you can read the official announcement, along with a step-by-step guide about how to use this new feature.

An interesting feature of this new support is that, because we’re working with a Web API, we can navigate to the /help page of the service to obtain the documentation of all the available methods (table functions, APIs, jobs). For each resource there are exanples of request and response messages, with a button that allows to directly invoke the function, so that it is easy to test the service.

This tool is very useful if we need to provide the documentation of our API to third parties, because all the pages are automatically generated for us.

However, it seems that the Help system only works when we execute the service within Visual Studio. In fact, after we have deployed the Mobile Service to Azure, if we try to access the /help page, we’ll obtain an HTTP erorr 403 – Forbidden. This is because, by default, all remote requests to mobile service resources are restricted to clients that present the application key.

In general, this behavior can be changed with the RequiresAuthorization attribute on contollers (or their methods). For example, we can use this attribute on a TableController like the following:

public class PeopleController : TableController<Person>
    public IQueryable<Person> Get()

    public async Task<IHttpActionResult> Post(Person item)

In this case, the Get method, that reads from the table, has anonymous access, while the Post operation, that performs an insert, requires an authenticated user. In other words, this attribute is used to specify the table methods permissions, like we do in the portal when we use Node.js for the backend.

The problem with Help is that it is provided by a class called HelpController that is part of the Azure Mobile Services SDK: so, like all the other controllers, once deployed it requires the application key, and this behavior cannot be changed because we don’t have direct access to the class (and so we can’t add a Custom Attribute to it). On the other hand, if we want to make the documentation of our service public, it must be accessed anonymously with a normal browser. Note that we have the same problem with ContentController, that is responsible for providing static content like CSS, Javascript, and so on.

The solution is to create a class that inherits from HelpController and another from ContentController, each of them with the anonymous authorization level:

public class PublicContentController : ContentController
    public new async Task<HttpResponseMessage> Index(string path = null)
        return await base.Index(path);

public class PublicHelpController : HelpController
    public new IHttpActionResult Index()
        return base.Index();

    public new IHttpActionResult Api(string apiId)
        return base.Api(apiId);

As attribute routing takes precedence, we’re overwriting the default routes for /content and /help request, using controllers that allow anonymous access. We can now publish the Mobile Service to Azure and verify that the Help page can be correctly reached with a normal browser.

Note that the Help page of the deployed service has a different layout than the local one, but the information shown are the same (page layouts are embedded in the library). More important, even if the Help page is now public, other controllers mantain their own access rules, and so, for example, if we want to test a method of a TableController that has an Authorization level of Application (the default), in the Test Client Dialog we need to specify the Application Key of the Mobile Service using the X-ZUMO-APPLICATION header:

Azure Mobile Service Test Client Dialog

Azure Mobile Service Test Client Dialog

It is possible to refer to the official documentation for more information about this topic.

Using the new system properties of Azure Mobile Services Tables from a client application

26/11/2013 2 comments

Some days ago an update to Azure Mobile Services has been released. As we can read on Carlos Figueira’s blog:

The main change is that they now have ids of type string (instead of integers, which is what we’ve had so far) […]. Tables have also by default three new system columns, which track the date each item in the table was created or updated, and its version. With the table version the service also supports conditional GET and PATCH requests, which can be used to implement optimistic concurrency. […]

Each new table created in a mobile service will have three new columns:

  • __createdAt (date) – set when the item is inserted into the table
  • __updatedAt (date) – set anytime there is an update in the item
  • __version (timestamp) – a unique value which is updated any time there is a change to the item

In this article we’ll focus on using the new table columns (also called system properties) from a client application.

First of all, we need to download the Azure Mobile Services SDK release 1.1.0 from NuGet. Then, as usual let’s create a MobileServiceClient in our app, pointing to the online service:

public static MobileServiceClient mobileServiceClient = new MobileServiceClient(
    applicationKey: "");

As said before, each new table has three system columns, that are automatically handled by the Mobile Service (they are read-only for the client). Since they may not be necessary in many scenarios, by default they aren’t returned to the client, unless explicity requested. To obtain these values, each request to the service must have an additional query string parameter, called __systemproperties.

The client SDK manages this for us. We just need to add the appropriate properties to the class that maps the table record, using some new custom attributes:

public class Photo
    public string Id { get; set; }

    public string Description { get; set; }

    public string Uri { get; set; }

    public DateTime CreatedAt { get; set; }

    public DateTime UpdatedAt { get; set; }

    public string Version { get; set; }

The CreatedAt, UpdatedAt and Version attributes are defined in the Microsoft.WindowsAzure.MobileServices namespace. Their are used to specify that the corresponding properties must be set using the relative values from the service.

Now we can make a request like this:

var table = App.mobileServiceClient.GetTable<Photo>();
var photos = await (from p in table
              select p).ToListAsync();

Since the Photo class contains the three system columns, the Client SDK automatically sets the new SystemProperties property of the table object at line 1 using the flags of the MobileServiceSystemProperties enumeration that correspond to the required values. In this way, it will be able to add the correct query string when making the request to the Mobile Service:

The objects returned from the server will contain the values for __createdAt, _updatedAt and __version system columns, that will be assigned to the Photo instances. If we don’t need all the information, we can simply remove the attributes from the unwanted properties (or delete them at all), and the __systemproperties query string parameter will be updated accordingly.

When using untyped tables, we can obtain system columns as well by explicitly setting the SystemProperties property of the table:

table.SystemProperties = MobileServiceSystemProperties.CreatedAt 
    | MobileServiceSystemProperties.Version;

Note that this property can be used also with typed tables, for example if we have specified all the system columns in the class declaration, but in some scenarios we need only some values. So, at any time we can override the default behavior.

Introducing WACEL: how to use Cloud Tables

12/11/2013 1 comment

WACEL, Windows Azure Cache Extension Library, is the newcomer among Azure tools. As we can read on the CodePlex project site:

WACEL provides implementation of high-level data structures that can be shared among your services and application. You can use WACEL data structures just as if you were using local data structures such as arrays, tables, circular buffers and OLAP cubes, and these data structures are backed by Windows Azure Cache, Windows Azure Table Storage, or both.

Integrating WACEL in our application is straightforward. The library is available on NuGet:

Installing WACEL from NuGet

Installing WACEL from NuGet

At this moment, WACEL depends on the libraries System.Spatial 5.2.0 and Microsoft.Emd.Data 5.2.0, that aren’t compatible with Windows Store and Phone apps. So, for now we can install it only on .NET applications.

Using a Console Application as example, let’s see how to use WACEL Cloud Table, one of the feature that I like much. A Cloud Table provides an abstraction layer over Windows Azure Table Storage: it allows to access tables using POCO entities, without using specialized types such as TableEntity, TableOperation and TableQuery.

So, first of all, let’s create the following POCO classes:

public class Student
    public string ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime BirthDate { get; set; }
    public List<Exam> Exams { get; set; }

    public Student()
        Exams = new List<Exam>();

public class Exam
    public string Subject { get; set; }
    public DateTime Date { get; set; }
    public int Vote { get; set; }

In order to save a Student class and related exams on a Table Storage using WACEL Cloud Tables, we need the following code:

CloudTableStorage<Student> students =
    new CloudTableStorage<Student>("ID", "UseDevelopmentStorage=true", "students");

var student1ID = Guid.NewGuid().ToString();
var student1 = new Student
    ID = student1ID,
    FirstName = "Marco",
    LastName = "Minerva",
    BirthDate = new DateTime(1981, 4, 2),
    Exams = new List<Exam>()
        new Exam
            Subject = "Operating Systems",
            Date = new DateTime(2002,7,4),
            Vote = 28
        new Exam
            Subject = "Compure Architecture",
            Date = new DateTime(2005, 5,13),
            Vote = 30

var student2ID = Guid.NewGuid().ToString();
var student2 = new Student
    ID = student2ID,
    FirstName = "Mario",
    LastName = "Rossi",
    BirthDate = new DateTime(1976, 12, 10),


// Retrieves the inserted students.
var existingStudent = students.Read(student1ID.ToString());

The CloudTableStorage constructor requires the following parameters:

  • The name of the field in the POCO entity that holds the primary key of the item;
  • The connection string of the Storage Account. In this example, we use the connection string that refers to the Storage Emulator, but of course we can use any existing Azure Storage Account;
  • The name of the table in which to store data. It will be automatically created if it doesn’t exist.

Then, we create two instances of the Student class and, finally, we call the Insert method, that actually adds the complete entities to the Table Storage.

The last instruction shows how to use the Read method to retrieve an element using its primary key. If the specified key doesn’t exist, an ArgumentOutOfRangeException error is raised.

There is another way to get entities, through the List method, that allows to use query predicates. For example, if we want to retrieve all the students whose last name starts with M, we can write:

var lastNameWithM = students.List(s => s.LastName.StartsWith("M"));

The predicate can be any valid lambda expression. So, to get the students who have taken at least a 30 on an exam, we just need the following code:

var bestStudents = students.List(s => s.Exams.Any(e => e.Vote == 30));

Of course, the library provides also methods to update and delete entities:

// Deletes the student with the given ID.

// Retrieves a student and updates it.
var existingStudent = students.Read(student2ID);
existingStudent.FirstName = "Riccardo";
existingStudent.Exams.Add(new Exam
    Subject = "Languages",
    Date = new DateTime(2006, 10, 29),
    Vote = 26


In conclusion, as we have seen in this post, Cloud Tables provide the following features:

  • use of POCO types instead of TableEntity
  • Direct CRUD operations without TableOperation
  • Query using predicates instead of TableQuery

For more information and examples, we can refer to the WACEL CodePlex project site.

Categories: .NET, Azure, C#