TOP

Microsoft Azure: Secure Site with SSL certificate (revisited)

Back in January 2011 I wrote the first instructions on how to secure your site with SSL certificate on Windows Azure. Since then, both Azure and IIS have been updated, so I’m revising these instructions here.

Learn how you can create the CSR (Certificate Signing Request) for Windows Azure, using Internet Information Services on Windows Server. The CSR is used to generate the proper SSL by any certificate provider. You will know learn how to go through the process of securing your Windows Azure hosts and enable users to access your services over HTTPS.

Create a new Windows Server

As it is now possible to create virtual machines on Windows Azure, you could easily create a new VM on Azure if you don’t have any on-premisses Windows Server.

create-vm

After the machine is provisioned, you can connect using Remote Desktop Client. You will find the public TCP port on the Endpoints page of the virtual machine. Connect to your Windows Server, either on Windows Azure, another provider or on any on-premiss server.

Install Internet Information Management

Choose the Add roles and features option on the Server Manager. Go through the wizard and select the Web Server (IIS) option on the Serve Roles step. Accept the dialog that adds required feature, the IIS Management Console.

configure-server

Certificate Signing Request

First open IIS Manager and navigate to the root element for the web server. Open the Server Certificates by double-clicking on the icon, as seen in the screenshot.

Server-Certificates

On the right you will see the Actions options. Click the Create Certificate Request to start the wizard.

Certificates-Actions

Fill out the fields in the wizard, in the Common name you will out your domain name.

Request-Certificate-1

Next step is choosing the bit length (strength) on the certificate. Choose a minimum of 2048, in this example I have chosen 4096 which is more secure, but require more computation and can be slower on high traffic sites.

Request-Certificate-2

Choose where to store the signed certificate request on your local computer.

Request-Certificate-3

Open the file in a text editor and copy everything. You need this in your application for SSL certificate.

Request-Certificate-4

Copy and paste the signed request to your selected SSL provider. There are many providers available, and there are different processes for verification and different levels of verifications. Make sure you research which type of certificate and verification that fits your requirement.

Installing and exporting SSL certificate

After you have supplied the request to your SSL provider, and have completed the other verification steps, you will receive one or multiple .crt files, often packed in a .zip.

You normally don’t need the extra certificates, such as the CA (Certificate Authority) certificates that are included. These certificates are normally already installed on your server.

Copy the www_domain_com.crt or similar named file to your Windows Server.

Next step is to install the SSL certificate on your local web site in IIS. We will install the certificate and later export it for use on Windows Azure.

Go back to IIS Manager and the Server Certificates window. Below the link we used earlier there is another one named Complete Certificate Request. Click this and complete the wizard. Note that IIS normally looks for files with the .cer extension, so you might have to choose the *.* option in the Open dialog, if your certificate is in the .crt format.

Complete-Certificate-1

It’s OK to install the certificate in the Personal certificate store, you might get permission error if you try another.

Located the installed certificate in the Server Certificates view inside IIS. Right-click on the certificate and choose Export.

Export-Context

Pick a selection to store the .pfx, and enter a password. Make sure it’s a decent quality password, if you ever loose the .PFX you don’t want anyone being able to easily brute force the password. If you loose the PFX and the password, others will have access to the private key of your certificate and can use it to do malicious actions in various manners.

Export-Certificate

 

Important: Keep your PFX file safe and keep it’s password safe. It contains the private keys and shouldn’t be distributed widely.

 

Configure Certificate for Azure Web Role

Next step is to configure web roles in your cloud project within Visual Studio, to use the new certificate. First thing to do on your development machine, is to copy the .pfx file, double-click to open it, choose the store location to be Local Machine, fill out the password you entered earlier. As you already have an exported private key, within the .pfx file, you don’t need to check the Make this key as exportable.

Certificate-Import-Wizard

 

Now you can open your Visual Studio solution with the cloud project. Expand the Roles folder and double-click your Web Role. find the Certificates tab, click Add Certificate. Fill out a identifier name, can be anything, choose the Store Location to be LocalMachine and the Store Name to be My. In the Thumbprint column, click the “…” button to open certificate selection dialog.

Add-Certificate

If you can’t find the certificate in the dialog, experiment with the various stores to see if you can find it. If you are unable to find it, you can manually install it using the Certificate Management Console add-in.

Navigate over to the Endpoints tab and add a new endpoint with HTTPS as the protocol, and select the certificate to be active for that endpoint.

Add-Endpoint

Now you can launch your web project from Visual Studio and the local Azure-emulator will open two instances, one for HTTP and one for HTTPS. Don’t be afraid of the certificate warnings, these are normal. Your certificate are only valid for the production URL that you specified while ordering the certificate. Meaning that you will get a warning if you re-use the certificate for localhost, “dev.domain.com” and other sites. There exists wild-card certificates, which can be *.domain.com and can be used for many purposes. If you are building a big cloud solution, where you want to have custom domains for Azure Storage, etc. then you should apply for a wildcard certificate. Beware though, it comes with a premium price.

Certificate-Warning

Simply choose to skip/ignore/accept the certificate for your localhost debugging and developing needs.

Adding Certificate to Windows Azure hosts

The last and final step before you deploy your updated web role, is to ensure that Azure have a copy of the certificate.

Login to the Azure Management Portal, find your Azure instance, navigate to the Certificates option. Choose the Upload a certificate link and find your .pfx file.

No-Certificate

 

Upload-Certificate

After the process is complete, you can deploy the updated version of your cloud project. Your site should now be fully functional with the ability to run over HTTPS for secure communication.

Conclusions

Securing your services with HTTPS is important to ensure the privacy and safety of your customers and users. Never allow anyone to authenticate their credentials with your site unless it’s with HTTPS. When you don’t use HTTPS, all the information the user enters on your web site can be sniffed and logged by third parties at various steps in the network from the client computer to your hosted server. In many cases, this data travels across multiple country borders.

Installing and configuring HTTPS certificates is sometimes hard, but I hope this walk-through makes you aware of the importance to use it and how quickly and easy you can get up and running with a valid SSL certificate.

If there is any questions, please leave a comment.

TOP

Chromeless Chrome App

Here follows a working example on how to build a chromless Chrome App, which replicates the minimize, restore, maximize and close buttons with custom styling. This makes it possible for you to easily build your Chrome App with a totally custom chrome/window.

Introduction

When you start developing Chrome Apps, you’ll quickly discover that the frame/chrome is not native on Windows 8. The frame is completely white, and it doesn’t indicate in any way if a window is active or in the background, other than inactive X (close) button, which changes from red to gray when the window goes into the background.

Here is how the frame looks like, and on a white background, you can’t really see the frame, it blends into the background.

Chrome_window

The next screenshot shows the normal native Windows 8.1 frame/chrome.

Windows_8_1_window

Source Code

The source is very simple and is built using AngularJS. The example app icon is provided by Pixel-Fabric.

Here is a screenshot from the structure and source of the index.html file.

chromeless_source

Here is how the final results looks like.

Chrome_chromeless_window

The code is fairly simple and if you are already looking into Chrome App development, you should feel right at home.

Downloadchromeless.zip.

The source code license is Public Domain (CC0), do whatever you want with it. The icon is obviously free to use, but is copyright by Pixel-Fabric.

TOP

Packaged Web Apps

firefox-marketplace_logo-only_RGBI have developed rich web based applications since 1999. The first web apps ran solely on Internet Explorer, as it was the most advanced browser with features such as DHTML, iframe and later years the XML Http Request object.

Third party proprietary runtimes has outplayed it’s role. While Flash has been a great productivity tool and given us real multimedia features in the browser, HTML 5 has matured enough to take over that space. Silverlight by Microsoft had a short life, but is still the primary runtime for apps on Windows Phone.

For the last few years, there has been interesting developments in the way you develop and distribute web applications. Both Google Chrome and FireFox has added support for desktop integration for web applications. This means you can install web based apps almost like native apps, with their own icons and sometimes access to local resources. It will be interesting to see what will happen with development and distribution of web apps on the next version (or update) to Windows and Internet Explorer. While you can develop and distribute native apps for Windows 8 in JavaScript, you still have to go through the app store.

Enter Packaged Apps

The basic concept of packaged apps, is that they are regular web apps but additionally includes an application manifest file that defines features such as app name and app icons. These are often in JSON or XML format. W3C has a Packaged Web Apps specification in recommendation state as of november 2012.

As you install one of these apps, they can launch in their own separate window outside of the browser. Depending on the browser, apps can be installed directly from a web site, or through a marketplace/app store.

Chrome Web Store
FireFox Marketplace

While there are others, these are the two biggest browsers and their accompanied stores. One other example I would like to show, is Pokki, which I personally use.

While FireFox Marketplace can be installed and launched from the desktop, it appears their main strategy is a marketplace of HTML 5 apps and games that will be compatible with the coming mobile devices running FireFox OS. There is even an FireFox OS simulator you can install on FireFox.

The feature sets are different. Google Chrome used to allow you to create desktop shortcuts, but that feature has been removed (or hidden from me) when Chrome (development branch) was updated with the new app launcher. In my example screenshot, I have an shortcut to SkyDrive that was created before the new launcher arrived.

First screenshot shows the Firefox Marketplace opened on a regular FireFox instance. On the desktop, I have three web apps that has been installed on my computer. The top most window, is the Pulse app running in a separate window.

FireFox

In this second screenshot, you can see the old SkyDrive desktop icon that launches the Microsoft SkyDrive web app in a separate window. The top most window, is the new app launcher in Google Chrome. You can right-click on the apps to set options on how to launch the various apps. As you can see on the left, I have launched the Kindle Reader web app in another separate window.

Chrome

As you can see, the web is starting to get fully integrated with the desktop. Improvements to JavaScript engines and support for hardware accelerated animations and graphics, is slowly but steadily moving the web technologies towards a true replacement of native apps.

Why consider packaged web apps?

Building apps and software in the future will for the majority of all the worlds applications, be based on web technologies: HTML, JavaScript and CSS. There is no way around this fact and the development is happening fast. It’s very hard to follow the trends and we are in an period of trial and errors. Both FireFox, Chrome and others, are experimenting with how to successfully move the web closer to the desktop.

If you are afraid of change and want a stable foundation to build your apps and games on, you should consider something other than web technologies as of today. If you embrace this change and innovation, you can reap the benefits of learning these technologies early. Being early adopter always comes at a cost, but HTML 5 and packaged web apps is already starting to gain traction.

Why would you continue to develop apps and games on runtimes and languages that are proprietary and limited in their reach? With packaged web apps, you can write once and run everywhere. And that includes every single mobile platform, every single desktop platform, every single browser. Just a side note regarding those platforms that currently don’t fully support building apps in HTML 5, you can use the long used trick of hosting your app inside a browser frame and deploy your app using normal procedures. I have done this for my Image Cards for Kids app that I built for Windows Phone. Libraries such as PhoneGap can help you access native APIs from JavaScript on the various device platforms.

I’m working on multiple packaged web apps that will be released this and next year. Please feel free to contact me for any questions and help.

Additional information

Here follows some more links to learn more about packaged web apps and how you can get started developing these on your own.

Google Chrome – What Are Packaged Apps?

FireFox Marketplace – Developer Hub

TOP

Secure documents in the Cloud

Here is a good way you can secure your documents in the cloud using Windows 7 and Windows 8. I’d like to note there is one alternative (among many) which I also use, which is TrueCrypt. The method described here relies on SkyDrive, VHD and BitLocker. Some if the tips does apply to the use of TrueCrypt.

Get Cloud Storage

Recently all the major cloud storage system have released a rich client for the Windows and Mac desktop OSes where you can sync a local folder, with your cloud storage. There are many smaller and bigger competitors in this space, the big players are Google, Microsoft and DropBox.

I’m using all of these three alternatives, with SkyDrive being my primary platform. Make sure you download the software for your cloud storage provider and setup the sync between cloud and your computer.

Create the Virtual Hard Disk

Next step is to launch the Computer Management console on your Windows computer. On Windows 8, open the File Explorer then choose the “Manage” button on the ribbon bar. This should open the Computer Management.

Navigate into Storage/Disk Management. Right Click on the Disk Management and choose the Create VHD option.

In the Location field, locate your synced cloud storage folder and type the name of your VHD file. For example “Documents.vhd”. I choose the option VHD and not the VHDX, to ensure the file is compatible with Windows 7. Pick whatever file size you want the virtual hard disk to be.

I choose the disk type to be dynamically expanding. It’s important to note that SkyDrive sync is intelligent and it won’t sync the whole huge file every time there is a change, it intelligently figures out the changes and only syncs those parts of the file.

After the disk has been created, you should run the Initialize Disk option. After Initialize, you have to right click on the partition and choose “New Simple Volume”. Assign the disk to a drive volume and perform a format from the wizard.

Turn on Encryption

The next step is important to ensure your file are stored encrypted and securely in the cloud. Here is one important step: You have to choose what encryption technology to use.

Microsoft have a table sheet that shows the differences between BitLocker and EFS.

For my own needs, I’ve chosen BitLocker. On Windows 8, all you have to do is open the mounted drive, in my example here, the X: drive and choose the Manage tab from the ribbon bar on the top.

Choose the Turn on BitLocker option and complete the wizard that appears. Make sure you enter a strong (long) password. A very long sentence that you remember, is a lot better than some small amount of random characters.

One of the new options on Windows 8, is to store the recovery key for BitLocker with your Microsoft account. This will somewhat defeat the purpose of storing your virtual hard disk encrypted on SkyDrive, as you are giving away the key to unlock the drive. Print out the recovery key and store it on external USB drive.

Mount and Eject

To mount the virtual hard disk on any of your computers, just right click on the vhd file and choose Mount.

When you do this operation, you might see the following error message appear:

“Sorry, there was a problem mounting the file.”

You might at this point have discovered that the mounting actually worked just fine, the drive appears on your File Explorer, but there is one final step you need to complete. You need to unlock you drive.

Right-click on the drive from the File Explorer and choose the Unlock Drive… option. Enter your password and then you should have fully unlocked your secure and encrypted cloud storage drive.

Backups

As long as your VHD is stored in the cloud, you should ensure that it is encrypted with BitLocker. Additionally you should make sure that the password used for BitLocker is NOT the same as your Microsoft account.

If someone steals or guesses your Microsoft account password, they still won’t be able to look into your documents and files.

Make sure you take backup of your VHD files once in a while to a local hard disk. My suggestion here, is to copy the .vhd off the SkyDrive folder, then mounting that to a separate drive and finally run the operation to remote BitLocker from that copy of the VHD file. That way, you will have a backup of the VHD which is not encrypted in case of emergency.

TOP

Get Social With Facebook

At the Norwegian Developer Conference 2012 (NDC) in Oslo, I did a talk on how you can get social with Facebook. By that, I mean that you, as a developer, should get into the Facebook Developer Platform.

You can view a recording of the whole talk and my slides are also available below here.

And my slides, which are a bit off due to custom fonts.

Source Code

I have built a basic solution with some projects that does a basic Facebook integration for user authentication. In the example provided here, I’m doing synchronous loading of the Facebook API. This is preferable if you are building a web application which relies on the Facebook API for authentication. If you are loading asynchronously, which is preferable for a regular website, it will only take a longer time for the users to be automatically logged into to your app.

Source code is based on my open source project, InTheBoks. The previous beta version currently in production, was built on Silverlight and not open source.  The new version is built on HTML 5 and will be licensed under the MIT license.

The sample has an improved implementation of logon status check and visual updates of the current authentication state. Feel free this use it as a better starting point to building Facebook apps.

Browse the source on GitHub

Download ZIP with source code

TOP

Technology Predictions for 2012

It’s that time of year again, where you start contemplating on the year that has gone by and the new year that is about to start. As a tradition on my blog, I will make my technology predictions for the next year. As it happens, I forgot to do predictions for last year, but I want to review my predictions for 2010 and see how they was realized, or if my predictions was a total miss.

Previous predictions: 2008, 2009, 2010.

Since last time I did these predictions, I have moved away from Oslo, the capital of Norway, to a small place called Vennesla. Vennesla is just outside of Kristiansand, in the southern parts of Norway. Here I work for a consulting company called Deepmind, where I work as a senior solutions architect.

 

“A lot of movie and game predictions for The Tens evolve around misery of all forms: World Wars, famine, terror, death and global disasters from natural disasters, the creation of intelligent machines and whatnot. I predict that very little of the movies and games mentioned above will come true”

Already in the introduction, I was very wrong. There are wars all over the world, and I live in a country that is part of the crimes against humanity. We sent fighter planes and bombed Libya. We have lots of military forces in Afghanistan. While these efforts will come to an end, the people of these areas will never receive an apology from our governments. They will be left to their own, after we have helped destroy their countries. I hope for better times for these people, but when they lack even the most basic human needs, it is going to take a long while before they can reap any benefits from technological developments.

We still have famine in some parts of the world. It’s incredible and unbelievable that this is still happening. It’s something we could have gotten rid of easily, with minimal efforts. Yet, it’s not going to happen. Politicians and world leaders are responsible for holding the poorest down in the mud and keeping them there. There won’t be any real peace in the world, unless people are free from their leaders, including “democratic” countries in the west.

When disasters happens somewhere today, it is on the local news within hours. While the news media reports on more global disasters than ever before, it doesn’t mean that more bad things are happening. We get fed up with the media from time to time, they are a huge source for negative input and can be exhausting for any adult individual, let alone how our kids are bombarded with negative news from around the world. Is there not a great marked for positive and good news?

 

“My main major prediction for The Tens is that it will represents a dramatic shift towards subscription based models for everything.”

With the launch of Spotify in the USA and Amazon in talks with book publishers on e-book subscriptions, I can safely say that this is the future. Still, many publishers, authors and artists have started to air their negative feelings around these services and withdrawn their products. It would had been very interesting to see how much artists such as Lacuna Coil have earned or lost from going away from Spotify in the last year. Will our kids even know about great bands such as AC/DC and Metallica, when their albums are unavailable on popular services such as Spotify? Do they really think that parents will go out and buy CDs for their kids, when they already pay a monthly subscription to millions of other songs?

 

“Television sets will include support for streaming videos over the Internet.”

Most new flat-screen TVs comes packaged with features, streaming over the network and Internet is just basic functionality today. YouTube is a must for any TV or TV-connected device, such as AppleTV and Blu-ray players.

 

Since this was for 2010, the iPad had not yet been announced…

 

“Apple will release an incredible, amazing, awesome tablet computing device. Google will continue to develop Google Wave and their OS will be largely ignored by the market”

Other predictions I made has more or less come true. Not exactly rocket science to predict what I did, so for next year I will make a quick list of my most important predictions.

My Top List of 2012 Technology Predictions

  1. Quad-HD TVs will start to be available for consumers.
  2. NASA will find further proof of water (and previous life) on Mars, with the event of Curiosity rover landing in August 2012.
  3. Large Hadron Collider will make the Higgs boson particle no longer a hypothetical particle.
  4. Microsoft releases Windows 8 and Windows Phone 8.
  5. The biggest websites will all be HTML 5 based.
  6. Apps (and games) built on HTML 5 will see exponential growth.
  7. Millions more will play Massive Online Multiplayer Games.
  8. Commercialization of space will take a giant leap forward.
  9. Prototypes of robots that will “eat” our garbage to improve recycling of important metal and other materials.
  10. New and improved humanoid robots will mimic human behavior – still years away from commercial use.
  11. Global disasters due to weather changes.
  12. Iran will be attacked.
  13. Next generation of (Xbox) Kinect is announced.
  14. I hope the first free-state is founded (Seasteading, Free State Initiative), but I doubt it.
  15. More electric cars will see the day, resulting in loss of income to big oil and big government.
  16. New buildings will become more and more self contained, producing it’s own power and potentially reusing/recycle some materials, such as water.
  17. Many big and important online services will be hacked and have their customer details leaked.
That’s it for my 2012 list! There are plenty more in my head, but that’s what I wanted to put down on the list. Feel free to leave a comment with your own predictions and good luck in the next year!

(Photo by Marc Dalio)

TOP

Moving to Kristiansand

After 4 great years in Oslo, having worked at two great companies: Capgemini and Steria – it is time to move back to southern Norway. Earlier this year, I became the father of a beautiful little girl. Unfortunately there are no relatives living in or around Oslo, family lives in Vennesla.

Therefor I’m looking for new job opportunities in and around Kristiansand. Make sure you check out my résumé, which has all my contact details.

(Photo by Germán Póo-Caamaño)

TOP

Preparing for Windows 8

This post is written without any special knowledge about the upcoming release of Windows 8. I’m relying on the already publicly known details that Windows 8 will support tablet devices to the full and enable developers to utilize their web skills building rich applications.

A very good friend of mine, Ingo Rammer, did a talk at NDC 2011 on HTML 5. One of the best tip I got from his talk, was to start using Adobe AIR as the shell for your HTML 5 applications. As you might not be aware of, Adobe AIR includes the WebKit browser engine which more or less supports some of the HTML 5 features.

That means you can build a rich desktop application in HTML 5 which have access to local resources, such as the file system. Another neat feature is the cross-platform support between Windows and Mac. Unfortunately Adobe has quit their support for Linux.

Get the Adobe AIR SDK

First thing first, get the Adobe AIR SDK. After downloading and unpacking, you should add the path to the bin folder to your paths environment variable. this makes it quicker to build your application.

Building your first application

Create a new folder for your application on your computer, preferably you should use a source control, such as Mercurial. This makes it easier to recover from human errors.

To start off, I suggest using the HTML 5 boilerplate. I suggest going through the custom build and remove all the backwards compatibility features, as you are only going to be building for the WebKit browser.

In this folder, you can add your stylesheets, graphics, html, javascript and other resources you will be using in your application.

I suggest creating a file named Launch.bat which can be used during development and testing to launch your application.

Content of Launch.bat: adl.exe “MyIncredibleApp-app.xml”

Then you need to create your MyIncredibleApp-app.xml file, which is the manifest definition for your application. All this really needs, is the default HTML page it should render when starting up. Here is an example from one of my own applications:

<?xml version="1.0" encoding="UTF-8"?>
<application xmlns="http://ns.adobe.com/air/application/2.7">
    <id>FlickrDownloadr</id>
    <versionNumber>0.1</versionNumber>
    <filename>Flickr Downloadr</filename>
    <initialWindow>
        <content>Flickr Downloadr.html</content>
        <visible>true</visible>
        <width>800</width>
        <height>600</height>
    </initialWindow>
  <copyright>Copyright (c) 2006-2011 Sondre Bjellås.</copyright>
  <icon>
    <image16x16>icons/Flickr-Downloadr-16x16.png</image16x16>
    <image32x32>icons/Flickr-Downloadr-32x32.png</image32x32>
    <image48x48>icons/Flickr-Downloadr-48x48.png</image48x48>
    <image128x128>icons/Flickr-Downloadr-128x128.png</image128x128>
  </icon>
</application>

The next very important step, is to copy the Adobe AIR JavaScript files into your folder. Depending on your installation path, you should find the AIRAliases.js and AIRIntrospector.js files located here: AdobeAIRSDK\frameworks\libs\air. Copy these two files into your project and make sure you reference the AIRAliases.js in your web page. The AIRIntrospector you won’t be needing unless you are doing advanced debugging.

<script src=”AIRAliases.js”></script>

Make a wrapper around the JavaScript API

Going forward, with advances in browsers such as Internet Explorer, Chrome, FireFox and Opera – you might see that some actually already today – will support access to local resources. That means you can build web applications that doesn’t required Adobe AIR as a delivery mechanism.

For this reason, I suggest writing your own wrapper around the JavaScript API included with Adobe AIR. That means you won’t be directly dependent on Adobe AIR and it will make the transition to support other platforms and browser much smoother.

Here is an example on how to show a folder dialog using the Adobe AIR JavaScript SDK:

    var file = new air.File();
    file.addEventListener(air.Event.SELECT, dirSelected);
    file.browseForDirectory("Select a directory where you want to save photos.");

Launching your rich desktop web application

Next step is to complete your HTML page, I would suggest downloading libraries such as jQuery UI to add animations and other great features. While this post does not explain how to go from a development environment to releasing your app, I suggest referring to the Adobe AIR SDK documentation for additional features.

This is a starting point on how to get started and possibly preparing for a possible future of building great Windows 8 web applications.

Here is a screenshot of one of my own web based rich desktop applications:

TOP

Configurable Service Routes

configurationOne of the things I don’t like about the default way of working with (URL) routes in ASP.NET MVC, is code in the Global.asax. While this is fine for simple MVC-routing, you don’t want to hard-code all your WCF endpoints inside that class, instead you want to configure using the web.config.

The first part of this code example is based upon code from one of my colleagues (thanks Roy Tore), it’s basically a custom configuration element for your web.config, which allows you to define a list of services and the route it should be registered on.

Second element of this sample, is how the types are defined in the serviceType proprety in the web.config, which does not require a specific type, but support the use of interfaces. There is additional code in the example, which extends the WebServiceHostFactory with support for dependency injection using Autofac.

Walkthrough

Here is a walkthrough on how you can do this from scratch.

  1. Create a new ASP.NET MVC 3 Web Application.
  2. Install the Autofac.MVC3 NuGet package.
  3. Add a reference to System.ServiceModel.dll, System.ServiceModel.Activation and System.ServiceModel.Web.dll
  4. Download the Routing.zip and unpack this into your web project.
  5. Modify the global.asax.cs, inside the Application_Start handler, add the following code in the beginning of the method:
    DependencyResolver.SetResolver(new AutofacDependencyResolver(CreateContainer()));

    And on the bottom of the method, after the ASP.NET MVC routes (RegisterRoutes):

    RouteTableManager.MapRoutes(DependencyResolver.Current.GetService<DynamicWebServiceHostFactory>());

  6. Modify the same file, but this time inside the RegisterRoutes method. We need to make sure the regular ASP.NET MVC routing will ignore our special services URI. See the full example below, and here is the modified default route:

    routes.MapRoute(
        "", 
        "{controller}/{action}/{id}",
       new { controller = "Home", action = "Index", id = UrlParameter.Optional },
       new { controller = "^(?!services).*" } // Important for WCF services to work.
        );
     
  7. Create a new method called CreateContainer inside global.asax.cs, which creates your inversion of control container. Preferbly this should be placed somewhere else in a separate class. The first 3 registrations is to enable Autofac-support for your regular ASP.NET MVC controllers. After the changes, your global.asax.cs should look similar to this:
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
     
        routes.MapRoute(
            "", // Route name
            "{controller}/{action}/{id}",
         new { controller = "Home", action = "Index", id = UrlParameter.Optional },
         new { controller = "^(?!services).*" }
            );
    }



    protected void Application_Start() { // Set the MVC IOC resolver to our Autofac resolver. DependencyResolver.SetResolver(
    new AutofacDependencyResolver(CreateContainer())); AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); // Map all the routes configured in web.config. RouteTableManager.MapRoutes(
    DependencyResolver.Current.GetService<DynamicWebServiceHostFactory>()); } private IContainer CreateContainer() { var builder = new ContainerBuilder(); builder.RegisterControllers(typeof(MvcApplication).Assembly); builder.RegisterModule(new AutofacWebTypesModule()); builder.RegisterModelBinderProvider(); builder.RegisterType<DynamicWebServiceHostFactory>(); // Register all the WCF (REST) services. builder.RegisterType<ItemService>().As<IItemService>(); var container = builder.Build(); return container; }

  8. Create your WCF (REST) Services (and modify the CreateContainer).
  9. Modify your web.config with the example below and you are done!

Add the following to your web.config, right after the configuration elemenet:

  <configSections>
    <section name="routingExtention" type="
ConfigurableServiceRoutes.Routing.RouteTableSection, ConfigurableServiceRoutes, 
Version=1.0.0.0, Culture=neutral" />
  </configSections>

  <routingExtention>
    <routes>
      <add route="services/items" serviceType="
ConfigurableServiceRoutes.Services.IItemService, ConfigurableServiceRoutes, 
Version=1.0.0.0, Culture=neutral" />
    </routes>
  </routingExtention>

If you need more services, just keep adding into the routes collection with more add elements.

Next part of the config change, is to enable the ASP.NET Compatability. This is important for the sample to work.

  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
  </system.serviceModel>

That’s it!

Benefits

There are multiple benefits from this sample.

  • Service Routing are configured, not compiled in code.
  • Services does no longer require an empty constructor.
  • Services supports dependency injection.
  • WCF Services works fine together with ASP.NET MVC.

And that’s basically it, I hope you enjoy this for your own projects.

Source Code

You can download a fully working sample here: ConfigurableServiceRoutes.zip

When you run the sample, you will get a 404 on the root as it’s based on an empty ASP.NET MVC 3 Web App. If you access the URL with /services/items, you should see the WCF REST Service initialize correctly.

Notes of caution

There is one place in the code, inside the DynamicWebServiceHostFactory where I override the CreateServiceHost method. The logic that replaces the base here, I don’t know what the original code was and there might be special instances where your service instance won’t work properly. It works on my machine!

TOP

Database Provider Factories: EF + SQL Compact

Now that Entity Framework 4.1 has been released and SQL Compact Edition 4.0 was released a while back, you can start using those technologies in your projects. I was working on a MVC 3 project when I discovered a NuGet package for SQL Compact Edition.

You have three option to install SQL Server Compact 4.0, using the Web Platform Installer, direct download, or you can add it as a NuGet package. I would suggest using the NuGet option, as that includes the required files with your source code. Make sure you get the documentation as well.

SqlServerCompact package: http://nuget.org/List/Packages/SqlServerCompact

With this package, you can start building code that queries and stores data in a file-based database. Yet, you still need one more package to make it work properly together with Entity Framework 4.1. Luckily, there is another NuGet package for this, EntityFramework.SqlServerCompact.

The SqlServerCompact package will try to modify your web.config/app.config with the following keys:

<configuration>
  <system.data>
    <DbProviderFactories>
      <remove invariant="System.Data.SqlServerCe.4.0" />
      <add name="Microsoft SQL Server Compact Data Provider 4.0" 
  invariant="System.Data.SqlServerCe.4.0" 
  description=".NET Framework Data Provider for Microsoft SQL Server Compact" 
  type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, 
  Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
    </DbProviderFactories>
  </system.data>
</configuration>

Also included in the package is the binaries for SQL Server Compact 4.0, located at the same level as your Visual Studio solution file, you should find this folder and within it all the assemblies needed to run: packages\SqlServerCompact.4.0.8482.1. Inside the lib folder is the System.Data.SqlServerCe.dll, which is the .NET assembly you need to work against SQL Server Compact.

The other package includes the assembly System.Data.SqlServerCe.Entity.dll, which contains code that generates proper queries against the SQL Server Compact. Additionally, it will add a source code file to your project inside the App_Start folder, that contains this code:

using System.Data.Entity;
using System.Data.Entity.Infrastructure;

[assembly: WebActivator.PreApplicationStartMethod(
typeof(InTheBoks.Test.Integration.App_Start.EntityFramework_SqlServerCompact), 
"Start")]

namespace InTheBoks.Test.Integration.App_Start {
    public static class EntityFramework_SqlServerCompact {
        public static void Start() {
            Database.DefaultConnectionFactory = 
              new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
        }
    }
}
 

What happens here is that the default connection factory of the Entity Framework is changed to the provider specified in the web.config/app.config. While I was working on the previous builds of SQL Server Compact 4 and Entity Framework 4.1 CTPs, I did not have the provider changed in the web.config. The new key in the config made me wonder for what reasons it removed and added the provider again. So I investigated with an integration test project to see what really happens.

The default connection factory is SqlConnectionFactory. That means that we need to change the connection factory in the start up of our application, which is done with the code inside the Start method displayed above, which changes it to SqlCeConnectionFactory.

To investigate what the default configuration is, I had to access a list of factories using the API: DbProviderFactories.GetFactoryClasses(). This will give you a data table with rows for all the factories. I did this to figure out why the NuGet package made the changes to my web.config/app.config and to see if there was any difference to my already installed factory and the one added in the config. Conclusion was, there is no difference. The reason why the package adds the provider, is probably because the factory is not registered on the computer if you don’t install using the manual or Web Platform Installer – so it have to add it manually in the config. My suggestion is to keep the configuration key in place, this ensures that your application will work without the need to install SQL Server Compact.

Reference Table for DbProviderFactory Classes.

Name Description Invariant
Odbc Data Provider .Net Framework Data Provider for Odbc System.Data.Odbc
Type System.Data.Odbc.OdbcFactory, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
OleDb Data Provider .Net Framework Data Provider for OleDb System.Data.OleDb
Type System.Data.OleDb.OleDbFactory, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
OracleClient Data Provider .Net Framework Data Provider for Oracle System.Data.OracleClient
Type System.Data.OracleClient.OracleClientFactory, System.Data.OracleClient, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
SqlClient Data Provider .Net Framework Data Provider for SqlServer System.Data.SqlClient
Type System.Data.SqlClient.SqlClientFactory, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Microsoft SQL Server Compact Data Provider .NET Framework Data Provider for Microsoft SQL Server Compact System.Data.SqlServerCe.3.5
Type System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=3.5.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91
SQLite Data Provider .Net Framework Data Provider for SQLite System.Data.SQLite
Type System.Data.SQLite.SQLiteFactory, System.Data.SQLite, Version=1.0.66.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139
Microsoft SQL Server Compact Data Provider 4.0 .NET Framework Data Provider for Microsoft SQL Server Compact System.Data.SqlServerCe.4.0
Type System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91

(Foto by Tim Morgan)