JavascriptServices: ASP.NET Core meets node.js

JavascriptServices In the past, I talked about how to integrate Angular 2 and ASP.NET Core just by using gulp tasks and configuring ASP.NET Core. In one of those post, I used the Microsoft.AspNet.SpaServices NuGet package to create a fallback route. This package is part of a set of tools named JavascriptServices which provides infrastructure that helps you to create awesome React/Angular 2/Knockout/etc sites, as well as, integrate with existing node.js code into your ASP.NET Core apps.

Introducing JavascriptServices

JavascriptServices is a set of tools that currently includes three components/NuGets: Microsoft.AspNetCore.NodeServices, Microsoft.AspNetCore.SpaServices and Microsoft.AspNetCore.AngularServices. In the past, there was also a ReactServices package, but this package is no more needed as you can use the SpaServices package instead. Now, let’s see them in more detail.

NodeServices

First, NodeServices, which is the base package. This package provides a way to run JavaScript in the server from a .NET application. To do this, it takes advantage of the Node.js environment.

In order to consume NodeServices, you need to add the using Microsoft.AspNetCore.NodeServices; statement and enable it inside the ConfigureServices method of your Startup class.

public void ConfigureServices(IServiceCollection services)
{
    // ... all your existing configuration is here ...

    // Enable Node Services
    services.AddNodeServices();
}

Now, you can use this service from any action by adding the nodeServices parameter to it and calling the nodeServices’ InvokeAsync method. Just pass the name of the node.js script file as first parameter and then the JavaScript function’s parameters if you need to.

public async Task<IActionResult> MyAction([FromServices] INodeServices nodeServices)
{
    var result = await nodeServices.InvokeAsync<int>("./addNumbers", 1, 2);
    return Content("1 + 2 = " + result);
}

In this example, the addNumbers.js script should be placed at the root of your ASP.NET Core app and look something like the following. Note that function should have a callback parameter in the first position which expect and error and the result. As a result of this, you might want to wrap your existing code in a new script that calls it.

module.exports = function (callback, first, second) {
    var result = first + second;
    callback(/* error */ null, result);
};

For more details on the API, you can check the repository, which also includes some extra use cases and samples.

SpaServices

The second package is SpaServices, which is built on top of NodeServices. This package includes a lot of tools that are generally useful when building Single Page Applications (SPAs). I already mentioned the routing helpers (the MapSpaFallbackRoute extension method).

One of the most interesting tools included in the SpaServices package is the Webpack middleware. This middleware enables you to hook your webpack configuration in ASP.NET Core in a similar way as you can do with express in node.js.

Another interesting feature included in SpaServices, is the support for hot module replacement. By using this feature, you can reduce the amount of time reloading the page after changes which is very useful for big SPAs.

Lastly, you can create universal (a.k.a. isomorphic) applications thanks for the support for server-side rendering. This is especially interesting for improving SEO (Search engine optimization) and client-side performance.

As this package is a bit more complex than the previous one, I will try to create a new post in the near future to show how to configure Angular 2 and/or React using it. In the meantime, you can read the documentation and the samples at the repository.

AngularServices

The last package is AngularServices, which provides some extra tools for Angular including some validation helpers and a “cache priming” feature.

The yeoman generator

Finally, there is a yeoman generator called generator-aspnetcore-spa which includes templates using these packages configured with Angular 2, React, React + Redux and Knockout.

JavascriptServices: generator-aspnetcore-spa

Wrapping up

To wrap up, these are a great set of tools if you plan to create SPA sites using the latest frameworks. Moreover, this is just the beginning for these tools as they are in heavy development.

Creating a simple API with ASP.NET Core

I posted about ASP.NET Core in the past. In this opportunity, I would like to share a simpler introduction to it using the nodejs’ approach. This approach consists in showing how to create a simple Web API (first with the http module and then using the express framework).

ASP.NET Core

ASP.NET Core is the new web framework in the .NET world, which is open-source (at GitHub) and cross-platform. It was created with focus on modern web development which are generally deployed in clouds environments and serves as backends for mobile apps or IoT apps as well as web apps. Additionally, as part of the redesign of ASP.NET, ASP.NET Core apps can run on .NET Core or on the full .NET Framework and ships entirely as NuGet packages (in a similar way as, for example, node.js apps).

In order to start working with ASP.NET Core, you should install .NET Core first. To do this, visit the oficial site and follow the instructions based on your preferred platform. Furthermore, you will need an editor for which I suggest Visual Studio Code (which is also cross-platform) along with the C# extension.

Creating the base app

Now that you have your environment ready, the first thing that you usually do in node.js is to create the package.json file. To do this, you would run the npm start command to create that file. In a similar way, for a new .NET Core app you will execute dotnet new. By executing this command, you will get the base structure for the app, which consist in two files: project.json and Program.cs. The first one contains the program metadata, including frameworks versions as well as dependencies. The other one is the program code itself.

Similar to node’s npm install, you should now restore the dependencies by executing dotnet restore. This will generate a new file, project.lock.json, which contains all the required information for running the app. At this point, you can see your first “Hello World!” output by running the dotnet run command. Note that this command checks the project source every time to determine if a re-build is necessary. Because of this, this command is intended for active development scenarios. In other scenarios you can execute dotnet build and then run the generated .dll file.

Adding the ASP.NET Core magic

After having the running .NET Core app, you will need to add the Microsoft.AspNetCore.Server.Kestrel dependency in order to run a simple web server similar to what the nodejs’s http module can do. In order to do this, open the project.json file and update the dependencies section as shown below.

{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true
  },
  "dependencies": {
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0"
  },
  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.0.0"
        }
      },
      "imports": "dnxcore50"
    }
  }
}

Again, you will need to execute dotnet restore to restore the new dependency and update the project.lock.json file accordingly. After doing that, open the Project.cs file to add the following using statements at the top.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;

Update the content of the Main function with the following. This will create the web host, configure it to use Kestrel and return to every request the “Hello World!” message.

public static void Main(string[] args)
{
   var host = new WebHostBuilder()
       .UseKestrel()
       .Configure(app => app.Run(context => context.Response.WriteAsync("Hello World!")))
       .Build();

   host.Run();
}

Same as you did before, execute the updated code with dotnet run. Then, open a browser and navigate to localhost:5000. As result, you should be able to see the new “Hello World!” message in your browser.

Adding the MVC framework

At this point in any node.js introduction you would include express, which facilites you creating routes as well as getting the request information. For ASP.NET Core we will include Microsoft.AspNetCore.Mvc as dependency.

{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true
  },
  "dependencies": {
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.0"
  },
  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.0.0"
        }
      },
      "imports": "dnxcore50"
    }
  }
}

Now, create new file named Startup.cs and add the following content, replacing the aspnetcoreapp namespace with the one use have in the Program.cs file. This configure the MVC services that take advantage of the build-in dependency injection feature. Additionally, configure the application itself to use the MVC framework, adding support for Controllers.

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

namespace aspnetcoreapp
{
  public class Startup
  {
    public void ConfigureServices(IServiceCollection services)
    {
      services.AddMvc();
    }

    public void Configure(IApplicationBuilder app)
    {
      app.UseMvc();
    }
  }
}

After creating this file, you will need to update the Program.cs again, using the following code which configures the Startup class that you just created instead of a custom configuration.

public static void Main(string[] args)
{
  var host = new WebHostBuilder()
    .UseKestrel()
    .UseStartup<Startup>()
    .Build();

  host.Run();
}

Creating the first Controller

Create a new folder named Controllers and then create a new file named ValuesController.cs in it. Add the following content to the new file to have a simple API that returns a list of values as json.

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;

namespace aspnetcoreapp.Controllers
{
  [Route("api/[controller]")]
  public class ValuesController : Controller
  {
    [HttpGet]
    public IEnumerable<string> Get()
    {
      return new string[] { "value1", "value2" };
    }
  }
}

Once this is ready, you just need to execute dotnet run again and navigate to localhost:5000 in your browser to see the list values.

Manifoldjs, a tool to create hosted apps

Modern web technologies are evolving not only to create faster and complex websites but also to create apps. There are plenty of examples for this. First of all, node.js, which is the one of the best examples, moving JavaScript to the server side. Then, you have electron, which is the technology behind Visual Studio Code, atom, the slack client and kitematic. Furthermore, you can think of frameworks that enables to create mobile apps using web technologies like apache cordova, ionic and React Native. However, you can go a step further creating a website and apps all in one using Manifoldjs.

Manifoldjs creates hosted web apps and some polyfill apps for Android, iOS, Windows 8.1, Windows Phone 8.1, Windows 10, FirefoxOS, Chrome, and the web, all based on the W3C Manifest for Web Apps. In addition to these platforms, the new version of manifoldjs supports creating your own platforms.

manifoldjs

So, what is a “Hosted Web App”? It’s a store app (i.e. apps that can be downloaded from Google Play or Windows Store), whose content is hosted on a web server. In other words, it’s a website converted into an installable app. You can find more information about hosted web apps in this post.

A W3C Manifest for web apps is a standardized JSON-based manifest that provides developers a centralized place to put metadata associated with a web application. With this manifest, you can forget about using all the platform-specific meta tags that set the different size icons for each platform and other settings. In order to support this manifest on your site, you just need to add a single <link> tag:

<link rel="manifest" href="manifest.json">

An example of a manifest.json could be something like:

{
    "name": "manifold.js",
    "short_name": "mjs",
    "icons": [{
        "src": "images/tiny.png",
        "sizes": "70x70",
        "type": "image/png"
    }],
    "start_url": "/",
    "scope":"http://www.manifoldjs.com/*"
    "display": "standalone",
    "orientation": "landscape"
}

If you want to generate a manifest.json for your site, there are several sites that can help you, for example, you can use the manifoldjs generator site or this one.

Of course, like most cool new features on the block, not every browser supports it yet. However, you can use the ManUp.js polyfill, for example, which will create the required meta tags on your site based on the manifest.json file. You can find more information about W3C Manifest and ManUp.js in this post.

Manifoldjs provides three ways to create your apps:

  • A node-based command-line interface (CLI) which you can install with npm and is easy to use.
  • A node.js module interface, which you can use to create your own tool just by adding the module as a common npm dependency in your node.js app.
  • A website that generates the apps for you: http://www.manifoldjs.com/generator

I will try to explain each scenario in more detail in future posts, but for now, the website is the easiest option.

To sum up, with your site, a W3C Manifest JSON file and manifoldjs, you can easily leverage your site in a cool way, creating Store apps for today’s most important platforms.

Introduction to Docker – Global Azure Bootcamp 2016

Today as part of the Global Azure Bootcamp 2016 in Buenos Aires, Argentina; I give an introduction to Docker and what are the possibilities to use it from within Microsoft Azure.

Global Azure Bootcamp 2016 logo

The Global Azure Bootcamp is an incredible community event that take place the same day in multiple locations around the world since 2013. Last year I take the challenge to organize the local event and it was an incredible experience. This year, Matías Quaranta y Guillermo Bellmann organize the local event and it was even better. You can find more information about the local event here.

If you want to know more about the WordPress/Nginx scenario I showed, you can review my blog posts:

  1. Creating a docker Virtual Machine on Azure manually
  2. WordPress Docker container with Compose
  3. Nginx for serving multiple sites in docker
  4. Using Let’s Encrypt with nginx on docker
  5. Automating the Let’s Encrypt certificate renewal

Regarding the demos, the docker command to run dotnet inside a container but modifying the host machine was the following. This command is really useful is you want to test the latest version taken from the build server of dotnet.

docker run -it --rm -v "$PWD":/tmp/app/ -w /tmp/app/ microsoft/dotnet-preview dotnet new

I also, showed kitematic as an easy to use interface for docker.

Docker demo showing kitematic

Finally, you can find the slides I used for my presentation.