How to share code among different Universal Windows apps

22/04/2014 Leave a comment

By this time, every Windows developer knows about Universal Windows apps, that enable building applications on the converged Windows 8.1 and Windows Phone 8.1 platforms.

A key concept of this new approach is the Shared Project, a particular kind of project that doesn’t have any binary output, but simply allows sharing source between converged apps.

The new Univeral app projects

The new Univeral app projects

Of course, we have the possibility to tailor the design to each device. We can also use conditional if and partial classes in the Shared Project to define platform specific code, that will be compiled within each app. In this way, we have a single common point between Windows 8.1 and Windows Phone 8.1 projects, but we can also write custom code for each app.

But what if we want to share code among different Universal Windows apps, because for example we want to redistribute our libraries? First of all, we can think about using Portable Class Libraries. This type of project has been improved in Visual Studio 2013 Update 2 and now, if we target Windows 8.1 and Windows Phone 8.1, we’ll be able to use all the common APIs. However, PCL produces a single binary that works as is in all the supported projects. Handling divergent APIs requires using higher-level abstractions, such as dependency injection or IoC containers. We can’t simply use conditional if to define platform specific code.

Luckily, there is another solution. Some days ago has been released a Visual Studio 2013 extension called Shared Project Reference Manager that allows to use the same concept of Universal app Shared Project with almost any C#, VB.NET, C++ or WWA/JavaScript projects. Let’s see how to use it.

First of all, create two Class Libraries, one for Windows and one for Windows Phone. They will contain any platform specific code, if necessary.

Libraries for Universal apps

Libraries for Universal apps

Then, we need to add a new Shared Project to the solution. This template has been added to the IDE by the Visual Studio extension mentioned before.

Shared Project

Shared Project

After that, right click on the References node on both the class libraries, select the Add Shared Project Reference command and, in the new window, click on the shared project we just created.

Shared Project Reference Manager

Shared Project Reference Manager

Now we can start creating any file in this new Shared project, as we do in the standard Shared Project created by the Universal app project template: everything we add to it will be automatically available in both the platform specific libraries.

Shared Project Library

Shared Project Library

In this way, we can develop and distribute libraries that allow code reuse, and thanks to the Shared Project all the common portion between Windows 8.1 and Windows Phone 8.1 can be written in a single place, with the ability to use conditional if to define custom behavior. Let’s see a simple example:

// In the project "UniversalLibrary.Shared
public class Utility
{
    public string GetGreetings()
    {
        var greetings = "Hello from {0}!";

#if WINDOWS_APP
        greetings = string.Format(greetings, "Windows");
#endif

#if WINDOWS_PHONE_APP
        greetings = string.Format(greetings, "Windows Phone");
#endif

        return greetings;
    }
}

When compiled, the UniversalLibrary.Windows library will contain the code at line 9, while UniversalLibrary.WindowsPhone will contain the one at line 13. So, starting from a single code file, we have easily realized two class libraries.

Note that, in most cases, the Windows and Windows Phone projects remain empty, as they are needed only to generate the output libraries that can be added to our Universal apps or distributed.

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

07/04/2014 Leave a comment

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; }

    [HttpGet]
    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) =>
    {
        container.RegisterType<BingLocationService>().As<ILocationService>();
    }));

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)
    {
        containerBuilder.RegisterType<BingLocationService>().As<ILocationService>();

        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

The flight of the Drone during Community Days 2014 in Milan

05/03/2014 Leave a comment

Last week, in Milan, took place the biggest Italian Community event, Community Days 2014. Three really interesting days: 11 tracks, 89 sessions, 75 speakers who talked about Web, Windows Phone, Windows 8.1, XAML, SQL Server, C++, gaming, hardware, and everything that can regard the world of developers.

In this scenario, I had the opportunity to take a speech with my friend Marco Dal Pino. We talked about how to interact with external devices using Windows 8.1 and Windows Phone 8. The main part of the session concerned the use of Wi-Fi connections. To make things more practical, we presented the AR.Drone 2.0 by Parrot, a radio controlled flying quadcopter helicopter: we showed how to interact with it from a Windows Store or a Windows Phone app.

Presenting AR.Drone 2.0 at Community Days 2014 Milan

Presenting AR.Drone 2.0 at Community Days 2014 Milan

It was a great (and funny) experience. Instead of using the existing SDK, we decided to start from scratch, with the only help of the Developer Guide. We wanted to understand how difficult it is to manage a complex device like a drone. So, we created a library with all the commands to guide it and we showed its usage during the session, with the following result:


 
I must admit that make the drone take off, fly and then land in front of all the attendees was a great satisfaction! And I think that our expressions at the end of the video are emblematic of how we felt.

Finally, I want to thank Microsoft Italia, that has given us the opportunity to use and test the drone, and Daniele Bochicchio and Andrea Saltarello, the organizers of Community Days, that have choosen our proposal for the session.

Categories: Community, Windows Phone, WinRT

SignalR on ioProgrammo

03/03/2014 Leave a comment

A new article of mine has been published on n°190 of ioProgrammo (March/April 2014). This time I talk about using SignalR to create a real-time communication channel between Windows Store and Windows Phone apps, with the ability to send text messages, location information and execute remote commands.

ioProgrammo March/April 2014

ioProgrammo March/April 2014

Categories: .NET, Windows Phone, WinRT

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>
{
    [RequiresAuthorization(AuthorizationLevel.Anonymous)]
    public IQueryable<Person> Get()
    {
        ...
    }

    [RequiresAuthorization(AuthorizationLevel.User)]
    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:

[RequiresAuthorization(AuthorizationLevel.Anonymous)]
public class PublicContentController : ContentController
{
    [HttpGet]
    [Route("content/{*path}")]
    public new async Task<HttpResponseMessage> Index(string path = null)
    {
        return await base.Index(path);
    }
}

[RequiresAuthorization(AuthorizationLevel.Anonymous)]
public class PublicHelpController : HelpController
{
    [HttpGet]
    [Route("help")]
    public new IHttpActionResult Index()
    {
        return base.Index();
    }

    [HttpGet]
    [Route("help/api/{apiId}")]
    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.

The new Portable Class Library for SQLite

13/02/2014 4 comments

Microsoft Open Technologies has recently released a Portable Class Library for SQLite. Thanks to it, we can use SQLite in the same way in all the supported platforms. Let’s see how to do that.

As prerequisite, we need to install the SQLite Extension SDK that corresponds to our platform. For example, for Windows 8.1, it is the SQLite for Windows Runtime (Windows 8.1) v3.8.2 extension SDK. The other versions are available on the SQLite official download page. Once downloaded, it’s necessary to change the extension from ZIP to VSIX, then double click it to install the SDK. Now we can add the extension to the project using the Add reference command:

SQLite for Windows Runtime

SQLite for Windows Runtime

Because it is a native library, the “Any CPU” architecture is not supported, so we need to choose a specific target platform: Visual studio will reference the appropriate extension SDK version the the project compiles.

Finally, let’s use NuGet to install the Portable Class Library for SQLite:

SQLitePCL on NuGet

SQLitePCL on NuGet

Now everything is ready to start using the library. Suppose for example we want to create a database named Storage.db with a People table:

using (var connection = new SQLiteConnection("Storage.db"))
{
    using (var statement = connection.Prepare(@"CREATE TABLE IF NOT EXISTS People (
                                                ID INTEGER NOT NULL PRIMARY KEY,
                                                FirstName NVARCHAR(50),
                                                LastName NVARCHUAR(50));"))
    {
        statement.Step();
    }
}

First of all, we create an SQLiteConnection object that points to the specified file. If it isn’t rooted, the library assumes that it is located in the ApplicationData.Current.LocalFolder folder (the same assumption applies also for Windows Phone 8).

At this moment, SQLite PCL supports only direct SQL commands (no LINQ provider). At line 3, we use the connection.Prepare method to define the DDL query we want to execute. Then, on line 8, with statement.Step, we send the query to the database engine, that immediately executes it.

The following example shows how to insert data:

using (var statement = connection.Prepare(@"INSERT INTO People (FirstName, LastName)
                                            VALUES(@firstName, @lastName);"))
{
    statement.Bind("@firstName", "Donald");
    statement.Bind("@lastName", "Duck");

    // Inserts data.
    statement.Step();

    // Resets the statement, to that it can be used again (with different parameters).
    statement.Reset();
    statement.ClearBindings();

    statement.Bind("@firstName", "Mickey");
    statement.Bind("@lastName", "Mouse");

    // Inserts data.
    statement.Step();
}

Again, the Prepare method is used to define the SQL command. In this case, it is an INSERT in which we have defined two parameters, @firstName and @lastName. At line 4-5, we bind them to their actual values, using the Bind method. The Step command (line 8) finalizes the operation.

Then, because we want to reuse the same statement to insert another record, we need to call Reset (line 11), that resets the prepared statement back to its initial state, ready to be re-executed, and ClearBindings (line 12), to remove the bindings that have been defined before.

Finally, it’s the moment to retrieve the saved data:

using (var statement = connection.Prepare(@"SELECT * FROM People ORDER BY FirstName;"))
{
    while (statement.Step() == SQLiteResult.ROW)
    {
        var id = (long)statement[0];
        var firstName = (string)statement[1];
        var lastName = (string)statement[2];
    }
}

To read the records returned by the query, we need to iterate through the rows, in a way that resembles the SqlDataReader.Read method.

In order to retrieve the actual values, we need to use the indexer operator on the statement object, specifying the column number. As this method gets a result of Object type, we need to cast it to the real type of the column. If we want to avoid this syntax, and instead prefer to use generics, we can define a simple extension method:

public static class SQLitePCLExtensions
{
    public static T GetValue<T>(this ISQLiteStatement statement, int index)
    {
        return (T)statement[index];
    }
}

And so in the previous loop we can write:

var id = statement.GetValue<long>(0);
var firstName = statement.GetValue<string>(1);
var lastName = statement.GetValue<string>(2);

As we have seen, this library is very straightforward. Its usage mimics the native C++ library (the Prepare, Step and Reset methods, for example), with a great advantage: we can code against one single API, regardless of whether we’re developing Windows Store, Windows Phone or .NET 4.5 projects.

More information about the Portable Class Library for SQLite are available on CodePlex.

Categories: .NET, C#, Windows Phone, WinRT
Follow

Get every new post delivered to your Inbox.