Using Azure Blob Storage

Blob storage has the concept of containers (which can be thought of as directories) and those containers can contain BLOB’s. Containers cannot contain containers and hence differ from a file system in structure.

Containers can be private or allow anonymous read access to BLOBs only or allow anonymous read access for containers and BLOBs.

In the Azure Portal, if you haven’t already got one set up, create a storage account then create a Blob service. Next create a container, mine’s named test. Next, upload a file, I’ve uploaded Hello World.txt which as you imagine simply has the line Hello World within it.

When you create a Blob service you’re assigned an endpoint name, along the lines of https://<storage account>.blob.core.winodws.net/

When we add containers, these get the URL https://<storage account>.blob.core.windows.net/<container name> and files get the URL https://<storage account>.blob.core.windows.net/<container name>/<file name>

A comprehensive document on using .NET to interact with the Blob storage can be found at Get started with Azure Blob storage using .NET.

Reading a Blob

Here’s some code to read our uploaded Hello World.txt file

Firstly we need to use NuGet to add package WindowsAzure.Storage and Microsoft.WindowsAzure.ConfigurationManager.

using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage;

private static void ReadBlob()
{
   var storageAccount = CloudStorageAccount.Parse(
      CloudConfigurationManager.GetSetting(
         "StorageConnectionString"));

   var blobClient = storageAccount.CreateCloudBlobClient();
   var container = blobClient.GetContainerReference("test");
   var blob = container.GetBlockBlobReference("Hello World.txt");
   var contents = blob.DownloadText();

   Console.WriteLine(contents);
}

In the example our file is a text file, but we can also access the blob as a stream using DownloadToStream (plus there’s a whole bunch of other methods for accessing the blobs).

Writing a Blob

We can write blobs pretty easily also

public static void WriteBlob()
{
   var storageAccount = CloudStorageAccount.Parse(
      CloudConfigurationManager.GetSetting(
         "StorageConnectionString"));

   var blobClient = storageAccount.CreateCloudBlobClient();

   var container = blobClient.GetContainerReference("test");

   var blob = container.GetBlockBlobReference("new.txt");
   blob.UploadFromFile("new.txt");
}

In this example, as you’ll see, we still do the standard, connect to cloud via the blob client, get a reference to the container we want to interact with, but next we get a blob to a file (in this case new.txt didn’t exist) and then upload or write from a stream to blob storage. If “new.txt” does exist in the blob storage it’ll simply be overwritten.

Deleting a Blob

We’ve looked at Creation/Update of blobs and Retrieval or them so let’s complete CRUD operations on blobs with delete

public static void DeleteBlob()
{
   var storageAccount = CloudStorageAccount.Parse(
      CloudConfigurationManager.GetSetting(
         "StorageConnectionString"));

   var blobClient = storageAccount.CreateCloudBlobClient();

   var container = blobClient.GetContainerReference("test");

   var blob = container.GetBlockBlobReference("new.txt");
   blob.DeleteIfExists();
}

References

Along with the standard CRUD type operations we can carry out actions on containers, list blobs etc.

See Get started with Azure Blob storage using .NET for more information.

The Blob Service REST API lists the REST API’s if you’d prefer to bypass the Microsoft libraries for accessing the Blobs (or need to implement in a different language).

Azure Storage

Blobs, Files, Tables and Queues – with Azure Cosmos DB in preview (at the time of writing), these are the currently supported Storage account options in Azure. Ofcourse, along side the storage account options are SQL databases which I’ll cover in a post another time.

Usually when you create an application within Azure’s portal, you’ll also have an App Service plan created (with your deployment location setup) and a Storage Account will be setup automatically for you.

Note: You can view your storage account details via the Azure portal or using the Windows application, Storage Explorer, which also allows access to local storage accounts for development/testing.

Blobs

The Blob container is used internally by Azure applications to store information regarding webjobs (and probably more, although I’ve not yet experience of all options), but for us developers and our applications (or just for used a plain old storage) we can use it to store any types of file/binary data. The difference between the Blob storage and file is more down to the way things are stored.

Within Blob storage we create containers (such as Azure creates for our applications/connections) and we can make a container private, blob anonymous read (for blob read access, i.e. publicly access individual blobs) and container anonymous read (for container and blob reads, which allows us to publicly view containers and the blobs within).

Files

Unsurprisingly, given that Blob storage acts a little like a file system, Azure also includes a File storage mechanism which one can look at like a file share (which uses SMB 3.0 protocol at the time of writing). Again this is used internally by Azure applications for log file storage. There’s little more to say except that file storage allows us to create directories and files or subdirectories as one would expect. We can also set quota on our shares to ensure the total size of files on the share doesn’t exceed a threshold (in GB’s, currently there’s a limit of 5120 GB).

Tables

Table storage allows us to work with entity storage. This is more of a No SQL (or key/value storage) offering than the SQL databases options within Azure. We’re definitely not talking relational databases here, but instead we have a fast mechanism for storing application data. Again, Azure already uses table storage within our storage account for internal data.

Check out this post Working with 154 million records on Azure Table Storage – the story of “Have I been pwned?” on performance within Table storage, Troy Hunt’s storing far more than I currently have within Table Storage.

Table storage stores entities whereby each entity stores key/value pairs representing the property name and the property value (as one would expect). Along with the entity’s properties we also need to define three system properties, ParitionKey (a string which identifies the partition an entity belongs to), a RowKey (a string unique identifier for the entity within the partition) and a Timestamp (a DateTime which indicates when a the entity was last modified).

Note: An entity, according to Get started with Azure Table storage using .NET can be upto 1MB in size and can have a maximum of 252 properties.

In C# terms we can simply derive our entity object from the Microsoft.WindowsAzure.Storage.Table.TableEntity which will supply the required properties. For example

using Microsoft.WindowsAzure.Storage.Table;

public class PersonEntity : TableEntity
{
   public PersonEntity()
   {
      // We need to expose a default ctor
   }

   public PersonEntity(string firstName, string lastName)
   {
      PartitionKey = lastName;
      RowKey = firstName;
   }

   public int Age { get; set; }
}

In the above we’ve declared the last name as the ParitionKey and the RowKey as the first name, obviously a better strategy will be required in production systems, see Designing a Scalable Partitioning Strategy for Azure Table Storage and Azure Storage Table Design Guide: Designing Scalable and Performant Tables for more information on partition strategy keys.

For more information on developing C#/.NET code for Table Storage, check out Get started with Azure Table storage using .NET.

Queues

Not as fully featured as MSMQ, but Queues offer a message queue service. This feature allows us to communicate between two separate applications and/or Azure functions to put together a composite application.

Let’s go to Azure functions and create a C# QueueTrigger function, the default code will simply log the queue’s message and looks like this

using System;

public static void Run(string myQueueItem, TraceWriter log)
{
    log.Info($"C# Queue trigger function processed: {myQueueItem}");
}

You’ll need to set the Queue name to the name of the queue you’ll be sending messages on, so let’s call ours test-queue.

Now Run the function.

From Storage explorer or from another instance of the Azure portal (as we want to watch the Azure function running) create a Queue named test-queue and that’s basically it.

Now Add a message to the queue and watch your Azure function log. It should display your message. After a message has been received it’s automatically removed from the queue.

Cosmos DB

At the time of writing Azure Cosmos DB is in preview. So anything I mention here should be by changed by the time it’s out of preview.

I won’t go through ever capability of Cosmos DB, you can check out the Welcome to Azure Cosmos DB link for that, but some of the key capabilities that interest me the most include distributed data across regions, uses “standard” API’s including MongoDB and Table API and well as tunable consistency.

Recording HTTP interactions with Scotch

Scotch is an HTTP recorder and playback library. What this means is that, whether we’re writing unit tests which require an HTTP connection or content, or if we need to test and application offline, we can first record a session, running code against our HttpClient and record the results of any calls, then take our application offline and replay those interactions.

Let’s get started…

Add the NuGet package scotch. If you’re using C# this will also deploy some F# assemblies, don’t panic, as it’s .NET it’s runnable from C# and luckily the API uses C# design style and hence looks like any other C#/.NET framework library.

This example, shows how we might have code which connects to the scotch GitHub page and using ScotchMoe.Recording, we record any interactios to the httpClient and save these to the data.json file – this example shows using the HttpClients.NewHttpClientWithHandler if we need to go through a proxy server, otherwise we just use HttpClients.NewHttpClient

var proxy = new WebProxy(proxy, port)
{
   Credentials = CredentialCache.DefaultCredentials
};
var httpHandler = new HttpClientHandler
{
   Proxy = proxy
};

var httpClient = HttpClients.NewHttpClientWithHandler(
   httpHandler, 
   @"c:\Development\interactions\data.json", 
   ScotchMode.Recording);

var result = await httpClient.GetAsync(
   new Uri("https://github.com/mleech/scotch"));

Now, assuming we’ve saved a recording we can switch the code to ScotchMode.Replaying (this example demonstrates non-proxy code and hence uses HttpClients.NewHttpClient

var httpClient = HttpClients.NewHttpClient(
   @"c:\Development\interactions\data.json", 
   ScotchMode.Replaying);

var result = await httpClient.GetAsync(
   new Uri("https://github.com/mleech/scotch"));

Adventures in UWP – Prism (more Unity than Prism)

Prism is a well used framework in WPF and it’s also available in UWP. So let’s try it out. We’re going to start by looking at switching the default generated (blank) UWP application into one which uses Prism or more specifically Unity and Prism’s navigation functionality.

  • Create a Blank UWP application
  • From Nuget install the package Prism.Unity (I’m using v6.3.0)
  • Edit App.xaml.cs and change the base class from Application to PrismUnityApplication (yes we’ll use Unity for this test), don’t forget to add using Prism.Unity.Windows;
  • Remove all generated code from App.xaml.cs except for the constructor
  • Open App.xaml and change it from using Application to PrismApplication, for example
    <windows:PrismUnityApplication
        x:Class="MathsTest.App"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:MathsTest"
        xmlns:windows="using:Prism.Unity.Windows"
        RequestedTheme="Light">
    
    </windows:PrismUnityApplication>
    
  • Add the following bare bones method (yes it’s not handling possible startup states etc. as I wanted to reduce this code to the minimum)
    protected override Task OnLaunchApplicationAsync(LaunchActivatedEventArgs args)
    {
       NavigationService.Navigate("Main", null);
       return Task.FromResult(true);
    }
    
  • By default the UWP project will have created a MainPage.xaml but Prism’s navigation code expects this to be in a Views folder, so create a Views folder in your solution and move MainPage.xaml into this Views folder.

    If you see an exception along the lines of “The page name does not have an associated type in namespace, Parameter name: pageToken” then you’ve probably not got a view with the correct name within the Views folder. Don’t forget to update the XAML and the xaml.cs files to include Views in the name space, i.e. TestApp.Views.MainPage

At this point we have UWP running from Prism.

Internal error 500, code 0x80070021 in IIS

Whilst setting up a new build server I came across the following error internal error 500, code 0x80070021 from IIS (I was setting up CruiseControl.net, but I assume this isn’t specific to that application).

It seems this is down to the handlers being locked in IIS, running the following fixed this issue

%windir%\system32\inetsrv\appcmd.exe unlock config -section:system.webServer/handlers

Beware those async void exceptions in unit tests

This is a cautionary tale…

I’ve been moving my builds to a new server box and in doing so started to notice some problems. These problems didn’t exist on the previous build box and this might be down to the updates versions of the tools, such as nant etc. I was using on the new box.

Anyway the crux of the problem was I was getting exceptions when the tests were run, nothing told me what assembly or what test, I just ended up with

NullReference exceptions and a stack trace stating this

System.Runtime.CompilerServices.AsyncMethodBuilderCore.b__0(System.Object)

Straight away it looks like async/await issues.

To cut a long story short.

I removed all the Test assemblies, then one by one place them back into the build, running the “test” target in nant each time until I found the assembly with the problems. Running the tests this way also seemed to report more specifics about the area of the exception.

As we know, we need to be particularly careful handling exceptions that occur within an async void method (mine exist because they’re event handlers which are raised upon property changes in a view model).

Interestingly when I ran the Resharper Test Runner all my tests passed, but switching to running in the tests in Debug showed up all the exceptions (ofcourse assuming that you have the relevant “Exceptions” enabled within Visual Studio). The downside of this approach, ofcourse, is that I also see all the exceptions that are intentionally tested for, i.e. ensuring my code exceptions when it should. But it was worth it to solve these problems.

Luckily none of these exceptions would have been a problem in normal running of my application, they were generally down to missing mocking code or the likes, but it did go to show I could be smug in believing my tests caught every issue.

net share is my friend

I recently had to set-up some shares on a server box using File Explorer and the share menu option, but after a reboot they all disappeared.

Note: I’m not concerned by this behaviour, of losing the shares, as it’s probably down to some security policy but every now and then it’s so much easier having the shares available to work from when I need to deploy apps etc.

Anyway, using net share in a batch file saves the day.

Just run

net share

to view the current shares on your machine.

Now to create a share, simply use

net share DEPLOYMENT=d:\mydeployment /GRANT:EVERYONE, READ

In this case I’m actually creating a READ only share with access granted to everyone. The string to the left of the = operator is the sharename (i.e. what you’ll see or use to access the share) obviously the right hand side is the location on the machine the share points to.

Obviously EVERYONE might by less than great in terms of security, so instead you can GRANT individual user’s access. The permission can be READ | CHANGE | FULL, see the output of net share /?

The syntax of this command is:

NET SHARE
sharename
          sharename=drive:path [/GRANT:user,[READ | CHANGE | FULL]]
                               [/USERS:number | /UNLIMITED]
                               [/REMARK:"text"]
                               [/CACHE:Manual | Documents| Programs | BranchCache | None]
          sharename [/USERS:number | /UNLIMITED]
                    [/REMARK:"text"]
                    [/CACHE:Manual | Documents | Programs | BranchCache | None]
          {sharename | devicename | drive:path} /DELETE
          sharename \\computername /DELETE

Trying out Refit (a REST client library)

REST is cool in that it’s lightweight and simple to use but lacks a lot of the tooling etc. that SOAP/XML has.

In .NET we have libraries such as ServiceStack (and others) to enable generation of REST services to be fairly painless, there are also a few client frameworks out there, but for this post I’m looking at Refit which (as the documentation states) is automatically type-safe and available in .NET standard 1.4 which also includes Xamarin, UWP and desktop. So pretty universal in it’s availability.

Show me the code!

Enough chat, let’s get into the code. I’m going to use ServiceStack to generate a simply REST service, the default one is the “Hello” service, which in code looks like this

[Route("/hello/{Name}")]
public class Hello : IReturn<HelloResponse>
{
   public string Name { get; set; }
}

public class HelloResponse
{
   public string Result { get; set; }
}

and this will be called using http://127.0.0.1:8088/hello/World which in turn returns (in JSON format)

{"Result":"Hello, World!"}

All pretty simple.

One thing we will do, is switch ServiceStack to use JSON be default, so in the MyService generated code we’ll add an AddHeader attribute, so it will look like this

public class MyServices : Service
{
   [AddHeader(ContentType = MimeTypes.Json)]
   public object Any(Hello request)
   {
      return new HelloResponse { Result = "Hello, {0}!".Fmt(request.Name) };
   }
}

Creating our client

Fire up Visual Studio and create a console application (I’ve targeted .NET 4.6), then add Refit via NuGet.

As we already have the HelloResponse class from our ServiceStack sample application, we can just copy that into our Refit application, or visit https://quicktype.io/ and paste {“Result”:”Hello, World!”} into the JSON edit box on the left of the site and it’ll create the class for us. So using either method we need to add the JsonProperty so it now looks like this in our Refit app.

public class HelloResponse
{
   [JsonProperty("Result")]
   public string Result { get; set; }
}

Next up we need create an interface that calls our REST service. We know, having written/generated the code for the service that there’s a Hello class that defines the route and response, but we won’t be copying this, instead Refit likes to use methods returning a Task (which makes sense being a web service call) so create (in your Refit app.) the following

public interface IHelloService
{
   [Get("/hello/{name}")]
   Task<HelloResponse> SayHello(string name);
}

Note we create an interface and that the route is within the Get attribute points to our Hello endpoint. Next we created a method to be called to contact our endpoint at the aforementioned route. This is the main area where we actually have to do any coding for this example to work.

Let’s now create the client code

var svc = RestService.For<IHelloService>("http://127.0.0.1:8088");
var response = svc.SayHello("World");

and that’s it – obviously you’ll need to await or Result etc. to get the actually HelloResponse object, but that’s all there is to this (admittedly very simple example).

As you can see the RestService.For method creates an instance of an IHelloService for us acting as a transparent proxy through to the service.

References

The automatic type-safe REST library for Xamarin and .NET
Exploring refit, an automatic type-safe REST library for .NET Standard

Writing your first Azure Function

With serverless all the rage at the moment and AWS Lambda’s and Azure Functions offering us easy routes into serverless in the cloud, I thought it about time I actually looked at what I need to do to create a simple Azure function.

Creating a function using the portal

  • Log into https://portal.azure.com/
  • From the Dashboard select New
  • Select Function App
  • Supply an App name, set your subscription, location etc. then press Create (I pinned mine the dashboard also using the Pin to dashboard checkbox)
  • After a while (it’s not instant) you’ll be met with options for your Function Apps, Functions, Proxies and Slots.
  • Click in the + of functions
  • Select HttpTrigger – C# or whatever your preferred language is, other triggers can be investigated later but this basically creates a simple REST like function, perfect for quick testing
  • Give your function a name and for now leave the Authorization level alone

I used the default name etc and got the following code generated for me by Azure’s wizard.

Note: Whilst there is some information out there on renaming Azure functions, the current portal doesn’t seem to support this, so best to get your name right first time or be prepared to copy and paste code for now into a new function.

using System.Net;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    // parse query parameter
    string name = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
        .Value;

    // Get request body
    dynamic data = await req.Content.ReadAsAsync<object>();

    // Set name to query string or body data
    name = name ?? data?.name;

    return name == null
        ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
        : req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
}

This is basically the Hello World of Azure functions. If you run it from the portal you’ll see the output “Hello Azure” as well as logs output. The request box allows you to edit the “name” field which is sent to the function.

By default the authorization level is Function, which basically means that a key is required to run this function. If you click the </> Get function URL link, Azure will supply the fully URL, minus the request payload and this will include the text code=abc123 where abc123 represents a much longer key.

Note: you can find your keys also via the Manage option below the Functions list on the left of the portal. Click the “Click to show” on Function Keys default.

We can remove the requirement for the key and make the function accessible to anonymous users by selecting the Integrate option under the Function name on the left list of the portal and changing Authorization level to Anonymous.

Beware that you’ll be allowing anyone to call your function with the Anonymous option which ultimately ends with your account paying for usage.

Now, once you have the URL for you function just append &name=World to it and navigate to the function via your browser (remove the code= text and don’t bother with the & for anonymous access).

Creating and deploying from Visual Studio 2017

If you have the Azure tools installed then you can create Azure functions directly in Visual Studio (I’m using 2017 for this example).

  • File | New Project
  • Select Cloud | Azure Functions (or search for it via the search box)
  • Name your project, mine’s HelloWorldFunctions
  • At this point I build the project to bring in the NuGet packages required – you can obviously do this later
  • Add a new item to the project, select Azure Function, mine’s named Echo.cs
  • Select HttpTrigger to create a REST like function
  • Leave Access rights to Function unless you want Anonymous access

When completed, we again get the default Hello Azure/World sample code. We’re not going to bother changing this at this time, but instead will look to deploy to Azure. But first, let’s test this function in Visual Studio (offline). Simply click the run button and a console window will open with a web server running mimicking Azure, mine creates makes the function available via

http://localhost:7071/api/Echo

If we run this from a web browser and add the ?name=, like this

http://localhost:7071/api/Echo?name=Mark

we’ll get “Hello Mark” returned.

Okay, so it’s working fine, let’s deploy/publish it.

  • Right mouse click on the project
  • Select Publish…
  • Either create new or select existing (if you already have an app), you may need to enter your account details at this point
  • In my case I created the application via the Portal first so I selected existing and then select my application from the options available
  • Press OK
  • Eventually the Publish button will enable, then press this

This will actually publish/deploy the DLL with your Azure function(s) to the Azure application. When you view the function in the Azure Portal you won’t see any source code as you’ve actually just deployed the compiled DLL instead.

In the portal, add your Request body, i.e.

{
   "name" : "Azure"
}

and run from the Portal – this is basically a replica (at the functional level) of the portal’s created default function.

Let’s look at the code

I’m going to show the code created via the Visual Studio template here

public static class Echo
{
   [FunctionName("Echo")]
   public static async Task<HttpResponseMessage> Run(
      [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
      HttpRequestMessage req, TraceWriter log)
   {
      log.Info("C# HTTP trigger function processed a request.");

      // parse query parameter
      string name = req.GetQueryNameValuePairs()
         .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
         .Value;

      // Get request body
      dynamic data = await req.Content.ReadAsAsync<object>();

      // Set name to query string or body data
      name = name ?? data?.name;

      return name == null ? 
        req.CreateResponse(HttpStatusCode.BadRequest, 
           "Please pass a name on the query string or in the request body")
       : req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
   }
}

If you’ve used any C# or Java HTTP like functions, this will all seem pretty familiar.

Our function is passed two parameters, the first being the HTTP request message and the second is the logging object. Obviously the logger is pretty self explanatory.

The HttpRequestMessage contains all those sorts of things we’d expect for an HTTP request, i.e. query name parameters, headers, content etc. and like many similar types of functions we return an HTTP response along with a result code.

Adventures in UWP – Getting Started

For a while now I’ve wanted to do something in UWP (Universal Windows Platform).

UWP always gives me the “uncanny valley” sort of feeling; it looks like WPF and looks like a standard Windows .NET application, but it also has that feeling on the unknown about it. To illustrate what I mean, UWP application compile to an EXE, but anyone used to Windows programming will probably double click on the EXE and find that Windows responds with a message box stating “This application can only run in the context of an app container”.

We’ll cover this soon enough, but let’s start our adventure with the classic Hello World type example and look at the basic parts of a UWP application and using Visual Studio 2017 to run the application etc.

Versions etc.

First off, I’m using Windows 10.0.15063.0 and Visual Studio 2017, version 15.2 (26430.16). I state this upfront because I’ve found books/posts talking about previous versions telling us to expect this file and this dialog when creating a new project, so what you see may differ from what I describe here, depending upon your versions.

Creating our project

In Visual Studio, carry out the following

  1. File | New Project
  2. Visual C# | Windows Universal
  3. Select Blank App (Universal Windows)
  4. Name it HelloWorld
  5. You’ll be prompted to choose a target version and minimum version, leave these as defaulted for now

Navigating the project

Properties

Within the Properties section is the usual AssemblyInfo.cs, but also the Default.rd.xml. This is used to contain runtime directives (hence .rd.). This allows us to specify elements within our program that are available for reflection.

Reference

Unlike non-UWP applications, the References have only two items (excluding the Analyzers). Microsoft.NETCore.UniversalWindowsPlatform and Universal Windows.

Assets

By default the Assets folder contains seven png images. Including store logo and splash screen. These are templates (if you like) for your own images. Every one of the images is a square with a cross in it – so you’ll know pretty quickly if you’ve not supplied an image/logo/splash screen for some area.

App.xaml

Like WPF, we have an App.xaml (and ofcourse the App.xaml.cs code behind). The code behind has a fair bit more code within it, unlike WPF. Default code is there for us to handle state loading during the application launch, a point to save state when the application is suspended etc. Also, unlike WPF, the MainWindow (in this case MainPage) is navigated to via the OnLaunched code as opposed to being declared in the App.xaml file like WPF.

HelloWorld_TemporaryKey.pfx

A temporary key is created for us. As UWP is aimed at being downloaded and installed from the Windows Store (or side loaded) this requires the application to be signed, hence we’re given the starting point for this.

MainPage.xaml

MainPage.xaml and it’s code behind contain minimal XAML and code (like a standard WPF control). UWP tends to class these controls as Pages (reminds me of Silverlight).

Package.appxmanifest

Finally we come to the application manifest. This allows us to set up things like the application’s display name, the rotations supported (for tablet/phone type devices). We can assign our assets to specific scenarios, such as for tiles, app. icons and so on. We’ll also need to declare what capabilities the application needs access to. Sort of standard mobile phone development requirements, i.e. this application will require Bluetooth etc.

Note: It’s best to reduce the capabilities to the bare minimum required as some user’s may prefer to lock down the access an application has.

What happens if we run the application now?

So if we want to run the application, you’ll notice that (at least on my install of Visual Studio) there the run button on the toolbar with Local Machine shown (mine’s also defaulted to x86 instruction set). From the drop down we also have Simulator, Remote Machine, Device as well as a bunch of Mobile Emulators of different screen sizes.

The emulators obviously allow us to view our application on a mobile phone or tablet like sized device.

Remote Machine allows us to run the application remotely, so for example on a Windows tablet, but without needing to install it directly etc.

The simulator is a virtual device or maybe better thought of as a remote desktop. The odd thing is that you’re really remote desktop-ing into your own machine, so changes to the simulator affect your machine.

So, let’s choose Local Machine, then we’re doing the equivalent of running a “standard” windows application. You’ll notice a square with a cross in it displayed, this is the SplashScreen.scale-200.png supplied by the project template within our Assets folder. Change this and then re-run to confirm.

Once running our application is, as expected, a blank application, but before we move onto actually writing some code/designing the UI, when we ran the application Visual Studio actually installed the application for us in the Start Menu, under Recently Added you should see HelloWorld (if you followed my naming for the application). If you attempt the run the EXE within the build folder, you’ll get the message box stating “This application can only run in the context of an app container”, however from the Start Menu, the application will be correctly run from a container.

Finally for this section, when you run the application via Visual Studio you’ll see four icons on your main page, these include tools to view the visual tree of a selected item at runtime and enable selected option, display layout adorners and a track focused element tool.

These, by default, are hidden outside of the debugger, but we can also hide within the debugger experience by selecting Tools | Options | Debugging | General, then locate Enable UI Debugging Tools for XAML and deselect this option.

The splash screen

As mentioned previously, we define the splash screen image (or edit the existing) within the Assets, as this is assigned via the manifest. UWP automatically displays the splash screen for us over the application Window and within App.xaml.cs, the OnLaunched method, when Window.Current.Activate() is called, the splash screen will be removed (obviously it will not immediately happen as the Windows message will need to be sent through, but it’s at this point the UWP application then “properly” starts your application. Hence within OnLaunched, is the place to restore state or setup anything prior to the splash screen being removed.

Note: Like Windows Services, your application is expected to start within a certain amount of time or it’s perceived as failing to start. I’ve read this time is approximately 15 seconds. So you’ll need to be a little more creative if loading your application takes longer than this, i.e. run code on a non-blocking thread or simply lazy load state etc.