By Ugo Lattanzi on Jan. 20th , 2015 in webapi | comments

One of my favorite features of ASP.NET WebAPI is the opportunity to run your code outside Internet Information Service (IIS). I don’t have anything against IIS, in fact my tough matches with this tweet:

But System.Web is really a problem and, in some cases, IIS pipeline is too complicated for a simple REST call.

we fix one bug and open seven new one (unnamed Microsoft employee on System.Web)

Another important thing I like is cloud computing and Microsoft Aure in this case. In fact, if you want to run your APIs outside IIS and you have to scale on Microsoft Azure, maybe this article could be helpful.

Azure offers different ways to host your APIs and scale them. The most common solutions are WebSites or Cloud Services.

Unfortunately we can’t use Azure WebSites because everything there runs on IIS (more info here) so, we have to use the Cloud Services but the question here is Web Role or Worker Role?

The main difference among Web Role and Worker Role is that the first one runs on IIS, the domain is configured on the webserver and the port 80 is opened by default; the second one is a process (.exe file to be clear) that runs on a “closed” environment.

To remain consistent with what is written above, we have to use the Worker Role instead of the Web Role so, let’s start to create it following the steps below:

Now that the Azure project and Workrole project are ready, It's important to open the port 80 on the worker role (remember that by default the worker role is a close environment).

Finally we have the environment ready, It’s time to install few WebAPI packages and write some code.

PM> Install-Package Microsoft.AspNet.WebApi.OwinSelfHost

Now add OWIN startup class

and finally configure WebAPI Routing and its OWIN Middleware

using System.Web.Http;
using DemoWorkerRole;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof (Startup))]

namespace DemoWorkerRole
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();

            // Routing
            config.Routes.MapHttpRoute(
                "Default",
                "api/{controller}/{id}",
                new {id = RouteParameter.Optional});

            //Configure WebAPI
            app.UseWebApi(config);
        }
    }
}

and create a demo controller

using System.Web.Http;

namespace DemoWorkerRole.APIs
{
    public class DemoController : ApiController
    {
        public string Get(string id)
        {
            return string.Format("The parameter value is {0}", id);
        }
    }
}

Till now nothing special, the app is ready and we have just to configure the worker role that is the WorkerRole.cs file created by Visual Studio.

What we have to do here, is to read the configuration from Azure (we have to map a custom domain for example) and start the web server.

To do that, first add the domain on the cloud service configuration following the steps below:

finally the worker role:

using System;
using System.Diagnostics;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Owin.Hosting;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace DemoWorkerRole
{
    public class WorkerRole : RoleEntryPoint
    {
        private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
        private readonly ManualResetEvent runCompleteEvent = new ManualResetEvent(false);

        private IDisposable app;

        public override void Run()
        {
            Trace.TraceInformation("WorkerRole is running");

            try
            {
                RunAsync(cancellationTokenSource.Token).Wait();
            }
            finally
            {
                runCompleteEvent.Set();
            }
        }

        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = 12;

            string baseUri = String.Format("{0}://{1}:{2}", RoleEnvironment.GetConfigurationSettingValue("protocol"),
                RoleEnvironment.GetConfigurationSettingValue("domain"),
                RoleEnvironment.GetConfigurationSettingValue("port"));

            Trace.TraceInformation(String.Format("Starting OWIN at {0}", baseUri), "Information");

            try
            {
                app = WebApp.Start<Startup>(new StartOptions(url: baseUri));
            }
            catch (Exception e)
            {
                Trace.TraceError(e.ToString());
                throw;
            }

            bool result = base.OnStart();

            Trace.TraceInformation("WorkerRole has been started");

            return result;
        }

        public override void OnStop()
        {
            Trace.TraceInformation("WorkerRole is stopping");

            cancellationTokenSource.Cancel();
            runCompleteEvent.WaitOne();

            if (app != null)
            {
                app.Dispose();
            }

            base.OnStop();

            Trace.TraceInformation("WorkerRole has stopped");
        }

        private async Task RunAsync(CancellationToken cancellationToken)
        {
            // TODO: Replace the following with your own logic.
            while (!cancellationToken.IsCancellationRequested)
            {
                //Trace.TraceInformation("Working");
                await Task.Delay(1000);
            }
        }
    }
}

we are almost done, the last step is to configure the right execution context into the ServiceDefinistion.csdef

<?xml version="1.0" encoding="utf-8"?>
<ServiceDefinition name="imperugo.demo.azure.webapi" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition" schemaVersion="2014-06.2.4">
    <WorkerRole name="DemoWorkerRole" vmsize="Small">
        <Runtime executionContext="elevated" />
        <Imports>
            <Import moduleName="Diagnostics" />
        </Imports>
        <Endpoints>
            <InputEndpoint name="Http" protocol="http" port="80" localPort="80" />
        </Endpoints>
        <ConfigurationSettings>
            <Setting name="protocol" />
            <Setting name="domain" />
            <Setting name="port" />
        </ConfigurationSettings>
    </WorkerRole>
</ServiceDefinition>

Here the important part is Runtime node. That part is really important because we are using the HttpListener to read the incoming message from the Web and that requires elevated privileges.

Now we are up & running using WebAPi hosted on a Cloud Service without using IIS.

The demo code is available here.

Have fun.

By Ugo Lattanzi on Dec. 2nd , 2014 in events | comments

It’s been a while since my last blog post; Unfortunately I’ve been very busy in the latest months for due to some important deliveries for the company I'm working for.

During the past two days one of my favorite conference, Codemotion, has been in Milan and fortunately I had a talk about NodeJS for .NET Web Developers.

The code used for the demo is available on github here (the most important demo is the Sample 004) and the slides are available on Slideshare and below:

I had a good feeling about the talk, the room was full of people, lot of questions and feedback. It means there is interest about Node from .NET people.

By Ugo Lattanzi on Sept. 2nd , 2014 in open source | comments

One month ago we announced (here more info) the next edition of Web European Conference.

We tried this year to replicate the conference but we got some problems with the venue. This time it seems it's going better; we don't have the venue confirmed yet, but we have good feeling about that.

Anyway, with the conference an important Open Source project was born, we (Simone and I) called it Event Starter Kit (ESK).

The idea is to create something that helps people to organise a conference with a small effort. In our case, the conference is a tech one, but of course, you can use ESK for all kind of conferences.

For this reason we are working on several repositories in the same time:

  • Launch page;
  • Blog;
  • Web site;
  • Mobile app (iOS, Android and Windows Phone);

of course we didn't complete everything yet except for the Launch Page and the blog. We planned to complete the project with the Conference, so spring 2015, but of course part of the project must be completed early (like the website).

For this reason we need help :heart_eyes:

If you wanna collaborate, contact me or send a PR (see the complete documentation about the project here).

Website and APIs are written using NodeJs + Mongo and, for the mobile apps, we are using Xamarin.

Work on ESK is really funny because we are also integrating several external services with our application like:

Why Node and Xamarin?

I would like to do this using ASP.NET vNext but it seems we have to wait a bit before we can use it on a production environment. So Node is the perfect solution because we don't want to impose the choice of server so, if you wanna go on Linux you can, same for Windows (right now we are using Microsoft Azure)

About Xamarin I think it's almost clear, same code with 3 different output (iOS, Android and Windows Phone).

We created a Github organization with all repositories (see it here) and other info about the project are available here.

We are looking for several roles, starting from Front-end developer (compass, bootstrap, angular and so on) till backend (nodejs, mongodb).

What are you waiting for? Join us here

By Ugo Lattanzi on July 9th , 2014 in nodejs | comments

Yesterday I spent some time to understand a problem with a Node Js application on Microsoft Azure. To be quick, my code was a simple web application built on top of Express and the code was something like this:

var express = require("express");
var app = express();

.... configure express

var port = Number(process.env.port || 5000);

app.listen(port, function() {
    logger.info("Listening on " + port);
});

Running locally the code works very well both if you run it on your dev environment or a server. Unfortunately it doesn't work if you try to run it on Microsoft Azure Website. But Why?

Adding some log I identified the problem on the port environment, basically process.env.port returns a string instead of a number (to be precise it was \\.\pipe\e289ed7e-b57b-46bb-8bba-ad8cd1f1529c) f The solution is easy, do not try to convert it to a number but pass it as is to node:

var port = process.env.port || 5000;

app.listen(port, function() {
    logger.info("Listening on " + port);
});

The reason is that Node is not running on its process like on local machine (node app.js to be clear), but it's mapped under IIS using IISNode with a wildcard on an HTTP Handler using named pipe

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.webServer>         
      <handlers>
           <add name="iisnode" path="app.js" verb="*" modules="iisnode"/>
     </handlers>
      <rewrite>
           <rules>
                <rule name="StaticContent">
                     <action type="Rewrite" url="public{REQUEST_URI}"/>
                </rule>
                <rule name="DynamicContent">
                     <conditions>
                          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/>
                     </conditions>
                     <action type="Rewrite" url="app.js"/>
                </rule>
           </rules>
      </rewrite>
    <iisnode 
      debuggingEnabled="false"
      logDirectory="..\..\LogFiles\nodejs" 
      watchedFiles="*.js;iisnode.yml;node_modules\*;views\*.jade;views\*.ejb;routes\*.js;views\*.vash" />
   </system.webServer>
 </configuration>

For confirmation, I wrote to David Ebbo via twitter getting this answer:

Confirmation

Unfortunately (or not), right now there is no way to run Node outside of IIS on Azure Websites but maybe it's not a problem, it works :smirk:

By Ugo Lattanzi on June 30th , 2014 in .net | comments

The idea of this post is born talking with my colleague Antonio about the frameworks a .NET web developer should know (from my point of view of course). That's funny because the list is very long and I asked myself if there is something wrong with my idea of .NET web developer or something else.

From my point of view (and also for my company) there are two kind of web developers, Back End (server side code) and Front End (javascript, css and HTML). Unfortunately, in Italy, these figures matches in only one person and the quality of the product obviously falls.


Back End Developer


ASP.NET MVC

Website: http://www.asp.net/mvc
Source code: http://aspnetwebstack.codeplex.com/

Most of our application runs on top of ASP.NET MVC, so for me it's really important to know it. I think it's a good framework, with a lot of extensibility points, good implementation of the MVC pattern, and we use it in heavy traffic projects without particular problems. Of course there are few things I don't like of it (first of all System.Web), but fortunately the vNext will solve these "problems".


ASP.NET WEBAPI

Website: http://www.asp.net/web-api
Source code: http://aspnetwebstack.codeplex.com/

ASP.NET Web API is probably the best solution if you know ASP.NET MVC and you don't have time to learn something else like NancyFx, NodeJs and so on; The approach is very similar to MVC (Controller + Action). Fortunately it doesn't have the dependency to System.Web but it's a Framework totally separate from MVC and sometime you have to duplicate the same code on MVC and Web API because the same interface/class has a different namespace.


SignalR

Website: http://www.asp.net/signalr
Source code: https://github.com/SignalR/SignalR

I'm not sure if an another Framework for real time applications exists in .NET world, but surely SignalR it is the most famous and used. Build by the same team of ASP.NET MVC / Web API it offers several clients (iOS and Android with Xamarin, Windows 8 and Windows Phone) and finally it supports old browsers (with fallback of course forever-frame, polling and son on).


NancyFX

Website: http://nancyfx.org/
Source code: https://github.com/NancyFx/Nancy

Nancy is a lightweight framework for building HTTP based services on .Net and Mono (yes it runs on linux and OSX). The main difference between Nancy and Web API is the routing approach. It uses lambdas to identify relative paths and arguments. Really helpful if you can't deploy on a Windows Server.


Common Logging

Website: http://netcommon.sourceforge.net/
Source code: https://github.com/net-commons/common-logging

I really like this library. When I need to deploy my code side by side with another application or I have to use a specific logging framework, Common Logging is the perfect solution. It is an abstraction of different logging implementations like Log4net, NLog, Enterprise library or whatever you want (you can write your custom bridge). Like many frameworks in the .NET world, this is a porting of a Java Framework (here more info). Really useful!


Windsor Container

Website: http://www.castleproject.org/
Source code: https://github.com/castleproject/Windsor

Probably the first package I add in a new project. I'm really a Dependency Injection addicted and Castle Windsor fits very well with my needs. It's fast, easy to use, all needed lifecycle and offers lot of extension point (Interceptor, custom lifecycle, factories and so on).


Automapper

Website: http://automapper.org/
Source code: https://github.com/AutoMapper/AutoMapper

In my Italian blog I wrote about the importance to use a DTO for the views and the responses instead of the Domain Model. Automapper is absolutely the best framework to "copy" data from an entity to a DTO. Easy to use, fast and extensible it's the second package I install on a new project. A must.


Service Stack

Website: https://servicestack.net/
Source code: https://github.com/ServiceStack

An extremely interesting set of Frameworks. It contains a Json serializer, ORM, Redis client and Service Clients. This set of Frameworks matches perfectly with those who are obsessed with performance. The tagline of the Framework is "Simplicity at Speed". Here a good presentation about ServiceStack and performances in .NET application


Quartz.NET

Website: http://www.quartz-scheduler.net/
Source code: https://github.com/quartznet/quartznet

Quartz.NET is a job scheduling system for small or large applications. Like Common Logging, this is a porting from a Java project (here more info). It offers several ways to run a job, from Cron pattern to special calendar, or whatever you like. The nice thing is you can have a storage for your jobs (configurable SQL, Mongo, MySql .....) very useful for scalable applications.


Cache Cow

Source code: https://github.com/aliostad/CacheCow

Caching is really important, specially if you application must answer to lot of requests. The best way to keep performance acceptable is to reduce the number of operation, specially if request and response are the same for most of the total requests. Cache Cow is a Framework built by my Twitter friend @aliostad and it offers an easy way to cache HTTP requests (both from client and server) using WEB API. With few line of code, you can have a good caching in your favorite storage (Redis, Azure Caching, Sql Server and so on).


Redis

Website: http://redis.io/
Source code: https://github.com/antirez/redis

Redis is an open source caching Framework that offers an advanced Dictionary (key/value) storage. Recently it's available (as preview) also on Windows Azure (here a good article explains how to use redis with MVC and Azure). The Performance of this Framework are great: it is very fast, and it also available on distributed infrastructures. If you go in a multi-server application, probably it is the best solution.


XUnit

Source code: https://github.com/xunit/xunit

This is the most active testing framework for .NET applications. It's used on lot of the Frameworks mentioned in this post (MS Stack included). It has support for Resharper, CodeRush Test Runner and Xamarin Test Runner.


Autofixture

Source code: https://github.com/AutoFixture/AutoFixture

It's a framework that helps developers to do Test-Driven Development by automating non-relevant Test Fixture Setup. Really I'm not a fan of TDD but Autofixture contains several features like Automock (helpful if you change frequently the constructor dependencies) and AutoMoqData that can help all developers.


Sharp Tests Ex

Source code: http://sharptestex.codeplex.com/

It's a library born to wrap all testing framework using a fluent syntax. Usually I don't change often the testing framework but sometime I need to copy part or my code to an existing application that uses NUnit or MS-Test. In this case the only thing to do is change the Testing attribute in the test class.

Front End Developer


Sass

Website: http://sass-lang.com/
Source code: https://github.com/sass/sass

Sass (Syntactically Awesome Style Sheets) is an extension to CSS. It is CSS as it should have been. Its key features are the ability to use variables, nesting, mixins and loops within your code. This means you can code more quickly and keep your code neat, tidy and easy to maintain. The Sass or SCSS code you write is then compiled in to standard CSS as browsers can't (yet) understand Sass / SCSS.

Also take a look at Compass, it is a great framework for Sass that contains loads of reusable mixins... no more memorising vendor prefixes and obscure pre-spec CSS3 styles!


Bootstrap

Website: http://getbootstrap.com/
Source code: https://github.com/twbs/bootstrap

Created by the guys at Twitter, Bootstrap gives you a massive selection of reusable, robust and attractive styles for your everyday styling needs. It includes a responsive, mobile-first grid system, basic typography styles, styles for common elements such as buttons and form inputs and lots more. Bootstrap is perfect for rapid prototyping but don't use it for everything otherwise we'll end up with all sites looking the same!


Bower

Website: http://bower.io/

Bower is a front-end package management tool, you use it to speed up your dev workflow. It allows you to simply install packages and their dependencies in your project using the command-line. No more Googling for the latest version of jQuery, downloading it, unzipping it, copying it into your project etc... just: $ bower install jquery


Grunt

Website: http://gruntjs.com/
Source code: https://github.com/gruntjs/

Like Bower, Grunt is another dev tool that can be run from the command-line. It is a JavaScript task runner which allows you to automate pretty much anything... minification, unit testing, compiling of Sass, code linting, image compression, launching a node server, creation of documentation, whatever you like. There are many, many Grunt Plugins available which do the most common tasks so it is easy to get started.


Yeoman

Website: http://yeoman.io/
Source code: https://github.com/yeoman/yeoman

Yeoman makes using Grunt and Bower even easier. It allows you to scaffold out a project very quickly using a "Generator". The Generator will create a bare-bones (boilerplate) project architecture, with certain libraries, frameworks, Grunt tasks and Bower dependencies pre-installed. Different Generators are available for different projects. For example if you are starting a new AngularJS app, you would use the Angular Generator and run $ yo angular and it will set up the architecture, along with basic units tests, install AngularJS and Bootstrap (if you want it).


AngularJS

Website: https://angularjs.org/
Source code: https://github.com/angular/angular.js

AngularJS is an open-source MVC JavaScript framework created by Google - it allows you to very quickly extend HTML's capabilities and create powerful, highly testable web applications. Angular includes two-way declarative data-binding which greatly simplifies complex application development as much of the DOM manipulation is handled automatically by the framework. It is (fairly) well documented and there is an active support community on Stack Overflow.


Karma

Website: http://karma-runner.github.io/
Source code: https://github.com/karma-runner/karma/

Karma (formerly Testacular) is a framework agnostic test runner. You write your unit tests alongside your application code and you can automatically test your code as you develop. Karma allows you to test your code in real browsers on real devices or in PhantomJS. It is definitely worth watching the introduction video from creator Vojta Jína.


Jasmine

Website: http://jasmine.github.io/
Source code: https://github.com/pivotal/jasmine

Jasmine is a framework for testing JavaScript code. You can use Jasmine to write your unit tests and then run them using Karma. The syntax of Jasmine is very clear and easy to understand, yet powerful.

If you want to take things further take a look at Jest (by Facebook), it is built on top of Jasmine, and adds some additional levels to Jasmine's feature-set.


Conclusion

It's an hard life for our developers.

Thanks to my friend Daniel Crisp for the support in this post