Azure functions for single page websites

Some applications are applications that are not used so often, maybe just once a month to update or add a value to a database that a calculation service is using. I’m building a service like that for a customer right now.

While the websites are just used once a month it feels unnecessary to have a website running all the time. Instead for creating a website in Azure App Services I created an Azure function. Azure functions are what is called serverless, which means you don’t have to manage a server at all. You just deploy snippets of code that will be executed when it’s triggered to run, instead of a service that running all the time just waiting for “something to do”.

Many examples about returning HTML from a function that I have read is embedding HTML in the C# code. I don’t like that approach at all, it maybe works if you will create a “Hello World” website. But in my case, I wanted to have a website with a form and validation with JavaScript etc. And when I posting my form I do it to another function that saves the values to the database.

What I did was to add an HTML page in my Visual Studio project and changed Build action from None to Embedded Resource. While it is an HTML page I can edit HTML, CSS and JavaScript will the full power of Visual Studio. The static resources I used for my webpage, like (images, JavaScript- and CSS frameworks), I uploaded to Azure blob storage. While I have them in Azure blob storage I also could add them to a CDN network.

Below is the code that I’m using in the function to read the HTML page and return the result to the browser as an HTML page.

var assembly = Assembly.GetExecutingAssembly();
var resourceName = "MyWebPage.form.html";
 
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
    using (StreamReader reader = new StreamReader(stream))
    {
        string result = reader.ReadToEnd();
 
        var response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new StringContent(result);
        response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/html");
 
        return response;
    }
}

MSDN-förmåner

Du vet väl av att du som har ett MSDN abbonemang har tillgång både till Azure och gratis utbildning? Väldigt många har helt missat att det följer med förmåner som bara försvinner om man inte utnyttjar dem.

Med ditt MSDN.abbonemang följer möjligheten att använda resurser för mellan 50-150 $ månad. Väldigt bra om man vill testa något i befintlig eller kika på nästa version av Microsoft produkter. Framförallt finns också möjligheterna att labba med TFS & Visual Studio!

Det finns ingen risk för ”omedvetna” kostnader och ingen betalkort info krävs för aktivering. För att aktivera Azure-förmånen, logga in på MSDN, https://msdn.microsoft.com/sv-se/subscriptions/manage

MSDN Pluralsight förmån
Med ditt MSDN abbonemang får du också tillgång till ett begränsat utbud (beroende på MSDN abbonemanget) av Pluralsights kurser. Där finns tex kurser om Microsoft Test manager, Fakes, Intellitrace och Scrum med TFS. Klicka bara på länken och logga in med det Microsoft Account (LiveId) som är kopplat till ditt MSDN abbonemang. https://msdn.microsoft.com/sv-se/subscriptions/manage

WordRoom – vägen till cross platform med Xamarin och Azure

Att bygga ett onlinespel innebär många utmaningar, att bygga ett onlinespel cross platform innebär ännu fler utmaningar. Under TechDays kommer jag och Johan Karlsson att berätta om våra erfarenheter efter att vi byggde ordspelet WordRoom där vi använde Xamarin dels för att kunna använda C#, men främst för att kunna dela klientkod mellan alla plattformarna för att spara utvecklingstid och öka förvaltningsbarheten. Som backend använder vi en lösning hostad i Windows Azure, en lösning som är fullt skalbar för att kunna skalas både upp och ner beroende på hur belastningen ser ut.

Under vår session på TechDays kommer vi att fokusera på dessa områden

  • Hur man bygger en cross platform lösning för mobila enheter med hjälp av Xamarin
    Vi kommer att berätta varför vi valde Xamarin och vilken arkitektur vi använder för WordRoom för att kunna dela så mycket kod som möjligt mellan de olika plattformarna, vilken kod man kan dela och vilken kod som måste vara plattformsspecifik.
  • Vad man behöver tänka på för att bygga en skalbar backend med hjälp av Azure
    WordRoom använder flera olika tjänster i Azure. Vi kommer att berätta vilka vi använder och hur vi tänkte när vi byggde en arkitektur anpassad för att kunna utnyttja Azure optimalt.

 

WordRoom finns att ladda mer för Windows 8+, Windows Phone, iOS och Android.

TechDays 2014

Den 19-20 november (17-20 november med pre-conf inkluderat) anordnas utvecklarkonferensen TechDays av Microsoft. Jag och min Sogeti- och IO2GameLabs kollega Johan Karlsson har fått äran att vara med på den. Vi kommer att prata om det vi brinner mest för nämligen cross platform utveckling för mobila enheter.

På pre-conf (den 17 november) kommer vi tillsammans med Peter Bryntesson (Microsoft), Johan Lindfors (Coderox) och Anderas Hammar (Jayway) att hålla en heldag om hur man bygger appar för Windows (Windows Store och Windows Phone) och för iOS och Android med Xamarin. Läs mer här.

Under själva huvudkonferensen kommer jag och Johan att ägna ca en timme till att berätta hur vi har arbetat med vårt spel WordRoom för att göra det cross platform med Xamarin och Microsoft Azure. Läs mer här.

Tycker ni att detta låter intressant tycker jag ni ska komma till TechDays på Kistamässan, självklart kommer det bjudas på massa andra intressanta föreläsningar också. Se hela programmet här.

Azure Mobile Services and Autofac

If you want to use an IoC container in your backend hosted in Azure Mobile Services I recommend to use Autofac. The reason is that Autofac already are wired up in Mobile Services and is used by the runtime to resolve references.

Because Autofac already is wired up you cannot create a container as you use to when not hosting in Mobile Services.

To configure how to resolve your references using Autofac in Mobile Services se the code below. The code should be in the register method in the WebApiConfig class. The class can be found in App_Start folder.

ConfigOptions options = new ConfigOptions();
var configBuilder = new ConfigBuilder(options, builder =>
{
      builder.RegisterType<MyImplementation>().As<IMyInterface>();
});
 
HttpConfiguration config = ServiceConfig.Initialize(configBuilder);
configBuilder.ConfigureOwin(config);

Authentication for REST calls with HTTPClient to Azure MobileServies

In a current project I working with an app that uses a .NET Backend in Azure Mobile Services. Backend is a WebAPI.

On client side I have all the code for networking in portable class library so I can reuse it on other platforms. Right now we are building the app for Windows Phone, but the plan is to build it for both iOS and Android using Xamarin. I am using the HttpClient object to do the REST calls. HttpClient is not in portable class library per default. But if you download “Microsoft HTTP Client Libraries” from NuGet you will get it.

My first problem was about which credentials I should use for the REST call to Azure. You can only see the application key in the portal. Is that the password? And what is the username in that case? The answer is that the application key is the password and username is just an empty string.
Problem number two was how to specify the credentials. My first try was to add the as the code below shows.

var handler = new HttpClientHandler {Credentials = new NetworkCredential("", "appKey") };
 
var client = new HttpClient(handler);

But then I got a 401 (Unauthorized) error back. After some mail conversations with the always helpful Mobile Services team we consider that the problem probably was that the call does not try to authenticate with basic authentication. When I tried the code below instead of the code above it worked.

var client = new HttpClient();
                client.DefaultRequestHeaders.Authorization = 
                    new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes(String.Format("{0}:{1}", "", "appKey"))));

Windows Azure Mobile Services in Portable Class Library

In my current project, a multiplayer game for mobile devices I only using Windows Azure Mobile Services as backend. The game will be available for multiple platforms and I will use Xamarin for iOS and android.

When using Xamarin I can reuse a lot of code if I using PCL (Portal Class Library) that i shipped with Visual Studio. When creating a new PCL-project you can choose which taget platforms the project will build for, in my case Windows Phone, Windows Store, Xamarin iOS and Xamarin Android.

In order to reuse so much code as possible I want to have the communication with my backend in PCL. When using Windows Azure Mobile Services I can have all communication there except for the code for authentication. But then I put an interface i PCL and each platform will have a specific implementation of the interface.

But where to find the Mobile Services assemblies for PCL? I installed Mobile Services via NUGET to my Windows Phone project (Windows Phone is my first platform). But Mobile Services was not just installed to my Windows Phone project, I also got the assemblies for PCL (and other platforms) i my packages folder. It enabled me to add the assemblies manually to the PCL-project.

Solution: Web role deploy problem with Azure SDK 2.2

When I updated my Windows Azure SDK to 2.2 I got a problem when deploying the package of my MVC 4 web site from Visual Studio to a web role in Windows Azure. The message I got was that a exception has occored under recycling and that I should check for unhandled exceptions or configurations errors.

Finnaly I found the solution, setting Copy local to true on the reference to the assembly for WindowsAzure.ServiceRuntime made it work again.

Worker role in Azure with HttpListener, deployment failed

I created a new worker role for a websocket server. But when I would deployed to Azure an error accoured, I did not get any message in Visual Studio but when I opend the Azure portal I found an message that told me that a HttpListenerException occoured. My first thought was that it was a conflict with the port that the worker listened at. But I tried other ports and same result. After som researched I found that the worker was not allowed to register HttpListener.

The solution was to add <Runtime executionContext=”elevated” /> to the ServiceDefinition. When I deployed the worker after adding it the deploy was successful.

<?xml version="1.0" encoding="utf-8"?>
<ServiceDefinition name="DefinitionName" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition" schemaVersion="2012-10.1.8">
  <WorkerRole name="MyWorker" vmsize="ExtraSmall">
    <Runtime executionContext="elevated" />
    <Imports>
      <Import moduleName="Diagnostics" />
      <Import moduleName="RemoteAccess" />
      <Import moduleName="RemoteForwarder" />
    </Imports>
    <Endpoints>
      <InputEndpoint name="endpoint" protocol="http" port="80" localPort="80" />
    </Endpoints>
  </WorkerRole>
</ServiceDefinition>

Enable WebSocket Protocol in IIS

If you want to use WebSockets with IIS8 you need to enabled it. This step by step guide will show you how to enable WebSocket Protocol on Windows 8 and Windows Server 2012.

Enable WebSocket Protocol in Windows 8

  1. Open “Control Panel
  2. Open “Turn Windows features on or off
  3. Expand “Internet Information Services”
  4. Expand “World Wide Web Services”
  5. Expand “Application Development Features
  6. Check WebSocket Protocol and click “OK”

Enable WebSocket Protocol

Enable WebSocket Protocol in Windows 2012 server

  1. Open “Server Manager”
  2. Click on “Manage” in the right corner”
  3. Click “Add Roles and Feature”
  4. Go to “Installation Type in the Wizard”
  5. Select “Role-based or feature installation and click “Next”
  6. Go to “Server Roles”
  7. Expand “Web Server(IIS)”
  8. Expand “Web Server”
  9. Expand “Application Development”
  10. Check WebSocket Protocol and click “Next”
  11. Click on “Install”

Enable WebSocket Protocol Windows Server2012

If you running a web role in Windows Azure you don’t need to activate it, it’s already done!

Office365, SharePoint Online, Azure – Sogeti skingrar molnen

Sogeti kommer att hålla tre seminarium om Microsoftmolnet, fokus kommer att ligga på Office365, SharePoint Online och Windows Azure.
Seminariet beskrivs såhär i inbjudan:

Office365, Azure, SharePoint online, Office Web apps, … känner du igen begreppen men är osäker på vad de egentligen innebär och vad skillnaden är? Känns Molnet som en möjliggörare eller ett hot? Hur hanterar man en molnmiljö? Kan man köra både on-premise och i molnet? När ska man välja vilket?

Jag, Karl-Henrik Nilsson från Sogeti i Borlänge och Fredrik Jansson från Sogeti i Västerås kommer att vara på plats och berätta om möjligheterna med molnet.

Vi syns väl där?

Anmälan, Västerås
Anmälan, Örebro
Anmälan, Borlänge

A project portal, webshop or a blog in Azure in a few minutes

Websites in Windows Azure is not just for hosting your own developed websites you can also choose from a gallery with applications. You can for example usa WordPress, Joomla and Drupal. In a few minutes you will have a running web application in the cloud.

To create a website in Windows Azure, go to the Windows Azure portal and click new then Compute -> Web Site -> From Gallery

Then you get a dialog where you can choose an app to install.

Azure Websites is free to use, but if you need better performance you can upgrade your web site, read more here, http://www.windowsazure.com/sv-se/pricing/details/virtual-machines/

If the app you want to install using MySql you will get 20 Mb for free.

We using Azure Web Site for a project portal for our WordRoom-project. We using Incentive for that, a very good portal including blogs, wikis etc. It’s free to use for up top three users.

 

Authentication with Azure Mobile Services

When developed the multiplayer part of WordRoom we discussed to use different authentication providers. But it was a lot of code to integrate each provider. And we wanted more than one. Instead we developed our own solution.

But just ask yourself, do you want to create an account everywhere with different username and passwords. I don’t. When we discovered Azure Mobile Services it was an obvious choice. Mobile Service gives you authentication with Microsoft-, Google-, Facebook and Twitter account and it’s for free. You only need to connect it to a database server. But we already had a database server in Azure. So i next version of WordRoom, you can authenticate with your Microsoft-, Google-, Facebook- or Twitter account.

With just a few rows of code you can authenticate the user with one of the authentication providers.
That Mobile Service is for five different platforms is a huge strength. You can use it for Windows Store applications, Windows Phone, Android, iOS and HTML5/JavaScript. If you use Xamarin Studio for developing your Android and iOS apps, there is a third part library.

In a Windows Store application you just add the SDK, some rows in App.xaml.cs and one row where you want to authenticate the user.

user = await App.MobileService
                .LoginAsync(MobileServiceAuthenticationProvider.Facebook);

Read more about Mobile Services