Moving to ASP.NET MVC Core 1

Introduction

The new version of ASP.NET MVC, Core 1, brought a number of changes. Some were additions, but others were removals.The structure is similar and will be mostly familiar to anyone who has worked with ASP.NET MVC, but a few stuff is very different. Let’s visit all of them, in a lightweight way – more posts coming soon.

Unified API

MVC and Web API have been merged together, which is a good thing. The new API is based on OWIN. There is a single Controller base class and an IActionResult serves as the base class for the responses, if we so want it – we can also return POCO objects.

Application Events

Application_Start and Application_End events are now gone, as is IRegisteredObject interface and HostingEnvironment.RegisterObject. If you want to be notified (and possibly cancel) hosting event, get a handle to the IApplicationLifetime instance using the built-in service provider and hook to the ApplicationStarted, ApplicationStopping or ApplicationStopped properties.

Dependency Injection

The dependency resolution APIs of both MVC and Web API has been dropped in favor of the new .NET Core mechanism, which is usually configured in the Startup class. You can plug your own IoC/DI framework as well. I wrote a post on this, which you can find here. There are now several new services that you can use to query information from the executing context, experienced users will perhaps find it complex. I’d say this is matter for a full post soon.

Routing

Attribute routing comes out of the box, no need to explicitly configure it. There is no global routing table (RouteTable.Routes), so we need to configure it in the Startup class, in the UseMvc method:

app.UseMvc(routes =>

{

    routes.MapRoute(

        name: "default",

        template: "{controller=Home}/{action=Index}/{id?}");

});

Route handlers (IRouteHandler) are not directly usable. Remember, route handlers are called when the route is matched. Instead, we need to use an IRoute:

public class MyRouter: IRouter

{

    private readonly IRouteHandler _handler;

 

    public MyRouter(IRouteHandler handler)

    {

        this._handler = handler;

    }

 

    public VirtualPathData GetVirtualPath(VirtualPathContext context)

    {

        return null;

    }

 

    public Task RouteAsync(RouteContext context)

    {

        context.Handler = this._handler.GetRequestHandler(context.HttpContext, context.RouteData);

 

        return Task.FromResult(0);

    }

}

Routes are added in Startup as well:

app.UseMvc(routes =>

{

    var routeBuilder = routes.MapRoute(

        name: "default",

        defaults: new {},

        template: "{controller=Home}/{action=Index}/{id?}");

 

    routeBuilder.DefaultHandler = new MyRouter();

});

There is already an handler so in this example we are overriding it. You better know what you’re doing if you are going to do something like this!

Route constraints (IRouteConstraint) are still available, just configured in a different way. These allow us to define if a route’s parameter should be matched:

services.Configure<RouteOptions>(options => options.ConstraintMap.Add("my", typeof(MyRouteConstraint)));

And then on the route template attribute we use the constraint:

[Route("home/action/{id:myconstraint}")]

Now there are also conventions (IApplicationModelConvention) that we can use:

public class MyConvention : IApplicationModelConvention

{

    public void Apply(ApplicationModel application)

    {

        //...

    }

}

Registration is done in the AddMvc method too:

services.AddMvc(options => options.Conventions.Insert(0, new MyConvention()));

Configuration

The Web.config file is gone, now configuration is done in a totally different way, preferably through JSON. You can either make the IConfigurationRoot instance available through the services collection:

public IConfigurationRoot Configuration { get; set; }

 

public void ConfigureServices(IServiceCollection services)

{

    //build configuration and store it in Configuration

 

    services.AddSingleton(this.Configuration);

 

    //...

}

or you can build a strongly typed wrapper class for the configuration. For example, for this JSON file:

{

    "ConnectionString": "Data Source=.;Integrated Security=SSPI; Initial Catalog=MyDb",

    "Timeout": 300

}

we could have this code:

class MySettings

{

    public string ConnectionString { get; set; }

    public int Timeout { get; set; }

}

 

public class Startup

{

    public IConfigurationRoot Configuration { get; set; }

    

    public void ConfigureServices(IServiceCollection services)

    {

        services.AddOptions();

        services.Configure<AppSettings>(this.Configuration);

 

        //...

    }

}

 

public MyController : Controller

{

    public MyController(IOptions<AppSettings> appSettings)

    {

        //...

    }

}

Public Folder

Now the public folder is not the same as the project folder: by default, there’s a wwwroot folder below the project folder which is where all the “physical” assets will be copied to at runtime.

Virtual Path Providers

Again, virtual path providers are gone, but there is a similar mechanism. You need to get a hold of the IHostingEnvironment instance and use or change its ContentRootFileProvider or WebRootFileProvider properties. There’s a new file provider interface, IFileProvider, that you can leverage to provide your own behavior:

public class MyFileProvider : IFileProvider

{

    public IDirectoryContents GetDirectoryContents(string subpath)

    {

        //...

    }

 

    public IFileInfo GetFileInfo(string subpath)

    {

        //...

    }

 

    public IChangeToken Watch(string filter)

    {

        //...

    }

}

If you do not wish to or cannot implement one of the IDirectoryContents, IFileInfo or IChangeToken, just return null.

The difference between ContentRootFileProvider and WebRootFileProvider is that the first is used for files inside IHostingEnvironment.ContentRootPath and the latter for those inside IHostingEnvironment.WebRootPath.

OWIN

MVC Core is now based on the OWIN standard, which means you can add your own middleware to the pipeline. This replaces both HTTP Modules and HTTP Handlers. OWIN middleware sits on the pipeline, like this:

public class MyMiddleware

{

    private readonly RequestDelegate _next;

 

    public MyMiddleware(RequestDelegate next)

    {

        this._next = next;

    }

 

    public async Task Invoke(HttpContext context)

    {

        await context.Response.WriteAsync("Hello from a middleware class!");

        await this._next.Invoke(context);

    }

}

We register middleware components in the IApplicationBuilder instance:

app.UseMiddleware<MyMiddleware>();

A middleware class is just a simple POCO class that follows two conventions:

  • The constructor receives a RequestDelegate instance
  • It has an Invoke method taking an HttpContext and returning a Task

The constructor can also take any service that is registered in the service provider. Pay attention, the order by which we add add our middleware has importance. Make sure you add yours soon enough to encapsulate whatever logic you wish to wrap.

Logging and Tracing

Logging and tracing is now only supported as part of the new unified logging framework. You can also write your own middleware that wraps the MVC processing and add your own logging logic. You gain access to the ILoggerFactory or ILogger/ILogger<T> instances through the service provider or using Dependency Injection:

public class MyController : Controller

{

    public MyController(ILogger<MyController> logger)

    {

    }

}

Custom Errors

The custom errors setting is also gone. In order to have similar behavior, enable developer exception page in the Startup class.

Controllers and Views

Controllers stay the same with one addition: we can have POCO controllers, that is, controllers that do not inherit from a base class (other than Object, that is). In order to make proper use of them, for example, if we want to access the context, we need to inject some properties into the controller class – the HttpContext.Current property is no more:

public class HomeController// : Controller

{

    //automatically injected

    [ActionBindingContext]

    public ActionBindingContext BindingContext { get; set; }

 

    //automatically injected

    [ViewDataDictionary]

    public ViewDataDictionary ViewData { get; set; }

 

    //automatically injected

    [ActionContext]

    public ActionContext ActionContext { get; set; }

 

    //constructor-set

    public IUrlHelper Url { get; private set; }

 

    public dynamic ViewBag

    {

        get { return new DynamicViewData(() => this.ViewData); }

    }

 

    public HomeController(IServiceProvider serviceProvider)

    {

        this.Url = serviceProvider.GetService(typeof(IUrlHelper)) as IUrlHelper;

    }

}

The serviceProvider instance will come from the ASP.NET MVC Core dependency injection mechanism.

In views, we now only have the Razor engine. We can now inject components into views:

@inject IMyClass MyClass

 

@MyClass.MyMethod()

and also define functions in the markup:

@functions {

    string MyMethod() {

        return "Something";

    }

}

Another new thing is the _ViewImports.cshtml file. Here we can specify stuff that will apply to all views. The following directives are supported:

  • addTagHelper
  • removeTagHelper
  • tagHelperPrefix
  • using
  • model
  • inherits
  • inject

Layouts files stay the same.

On the other hand, mobile views no longer exist. Of course, you can add logic to find if the current browser is mobile and then serve an appropriate view. Again, the Browser and IsMobileDevice properties are now gone (with the browser capabilities database), so you will have to do your own sniffing.

You can still add view engines (currently, only Razor is supported), you do that when you register MVC services (no more ViewEngines.Engines property):

services

    .AddMvc()

    .AddViewOptions(x =>

        {

            x.ViewEngines.Add(new MyViewEngine());

        });

Model validation providers used to be extensible through the IClientValidatable interface. Now, we have IClientModelValidatorProvider, and we need to add our providers to a collection also when we register MVC services:

services

    .AddMvc()

    .AddViewOptions(x =>

        {

            x.ClientModelValidatorProviders.Add(new MyClientModelValidationProvider());

        });

A client model validation provider needs to implement IClientModelValidatorProvider:

public class MyClientModelValidationProvider : IClientModelValidatorProvider

{

    public void CreateValidators(ClientValidatorProviderContext context)

    {

        //...

    }

}

Finally, views now cannot be precompiled. In the early days of ASP.NET MVC Core, it was possible to precompile them, but not anymore.

Filters

There is no longer a static property for holding the global filers (GlobalFilters.Filters), instead, they can be added to the services collection, normally through the AddMvc overload that takes a lambda:

services.AddMvc(mvc =>

{

    mvc.Filters.Add(typeof(MyActionFilter));

});

Of course, it is still possible to scope filters at the class or method level, using either an attribute inheriting from a *FilterAttribute class (like ActionFilterAttribute) or using TypeFilterAttribute, for dependency injection.

View Components and Tag Helpers

These are new in Core 1. I wrote about View Components here and on Tag Helpers here, so I’m not delving into it again. Two very welcome additions indeed!

Bundling

In the old days, you would normally use the Microsoft ASP.NET Web Optimization package to bundle and minify your JavaScript and CSS files. Now, by default, Gulp is used for that purpose. You can also use BundleMinifier.Core from Mads Kristensen, this needs to be added as a tool and configured through a bundleconfig.json file. BundleMinifier is installed by default starting with Visual Studio 2015 Tooling Preview 1.

Maintaining State

In pre-Core days, one could store state in the Application, which would be available to all requests. Unfortunately, this led to several problems, and the application storage was dropped. Of course, it is still possible to use static members and classes.

Likewise, the Cache storage was also dropped, this time in favor of a more flexible and extensible mechanism. You’ll need the Microsoft.Extensions.Caching.Abstractions Nuget package for the base contracts plus a specific implementation (see Memory or Redis, for example):

public void ConfigureServices(IServiceCollection services)

{

    services.AddDistributedMemoryCache();

 

    //...

}

 

public class MyController : Controller

{

    public MyController(IDistributedCache cache)

    {

        //...

    }

}

Sessions are still around, but they need to be explicitly configured. You need to add a reference to the Microsoft.AspNetCore.Session package, and then register the services and middleware (a distributed memory cache is also required):

public void ConfigureServices(IServiceCollection services)

{

    services.AddDistributedMemoryCache();

    services.AddSession();

}

 

public void Configure(IApplicationBuilder app)

{

    app.UseSession();

    app.UseMvc();

}

 

After this, the ISession instance can be accessed through the HttpContext instance exposed, for example, by the Controller class.

There is no longer support for automatically storing the session in a SQL Server database or the ASP.NET State Service, but it is possible to use Redis, a very popular distributed cache technology.

Publishing

Publish profiles are still around, but now you have other options, such as deploy to Docker. There’s also the dotnet publish command, which places all deployable artifacts in a folder, ready to be copied to the server.

Conclusion

You can see that even though this is still MVC, a lot has changed. In my next post, I will talk a bit about some of the new interfaces that were introduced. In the meantime, hope this gets you up and running! Do let me know if I skipped something or you wish to know more about this. Your feedback is always greatly appreciated!

ASP.NET MVC Core: The Good Parts

MVC 6 should be out any day, so we need to be prepared.

The good thing is, it’s all very similar to MVC 5; the even better thing is, it got better! A couple of ways it is so cool, in my mind, are:

  • Most of the stuff is very similar to what we had: controllers, views, mostly work the same way;
  • MVC and Web API have been merged together, so it’s not really any different add an API controller that returns JSON or an MVC controller that returns an HTML view;
  • All of its code is available in GitHub, and you can even contribute to it;
  • It is now cross-platform, meaning, you will be able to deploy your web app to Linux (even as a Docker container) and Mac (if you use .NET Core);
  • It is very modular: you only add to your project the Nuget packages you really need;
  • It now uses service providers to resolve all of its features; you do not need to know the static location of properties, like, ControllerBuilder.Current, GlobalFilters.Filters, etc; the boilerplate configuration in the Startup class is pretty easy to follow and change;
  • The default template has Bower, NPM and Gulp support out of the box;
  • No need to explicitly add attribute routing, it is built-in by default;
  • We have a better separation of contents and code, in the form of the wwwroot folder to which servable contents are moved;
  • Logging is injected, as are most of the services we need, or we can easily add our own without the need to add any IoC library; even filters can come from IoC;
  • It is now possible to have our Razor pages inherit from a custom class, have custom functions defined in Razor (by the way, do not use it!) and inject components into it;
  • View components and tag helpers are a really cool addition;
  • The new OWIN-based pipeline that is now ASP.NET is much more extensible and easy to understand than System.Web-based ASP.NET used to be;
  • This one is a corollary from the latter: Web.config is gone; let’s face it, it was a big beast, so it’s better to just drop it.

On the other hand, we will need to learn a lot of new stuff, namely, a whole lot of new interfaces and base classes to use. Also, it may sometimes be a bit tricky to find out which Nuget package contains that specific API we’re after. And because there is no more System.Web, all of the infrastructure management is very different. Finally, not all the libraries we’re used to will be immediately available for .NET Core, but that’s really not a problem with ASP.NET Core itself.

All in all, I think it is a good thing! I’ll be talking more on ASP.NET Core, so stay tuned!

Payloads as dynamic Objects in ASP.NET MVC

Even though the dynamic type seems to be everywhere these days, ASP.NET MVC still doesn’t support having dynamic parameters in controller action methods out of the box; which is to say, this doesn’t work as expected:

[HttpPost]

public ActionResult Post(dynamic payload)

{

    //payload will be an object without any properties

 

    return this.View();

}

However, because MVC is so extensible, it is very easy to achieve it. For that, we need to build a custom model binder and apply it to our action method parameter. We’ll assume that the content will come as JSON from the HTTP POST payload. Note that this does not happen with Web API, but still happens with MVC Core!

There are a couple of ways by which we can bind a model binder to a parameter:

First, let’s focus on the actual model binder, the core for any of the above solutions; we need to implement the IModelBinder interface, which isn’t really that hard to do:

public sealed class DynamicModelBinder : IModelBinder

{

    private const string ContentType = "application/json";

 

    public DynamicModelBinder(bool useModelName = false)

    {

        this.UseModelName = useModelName;

    }

 

    public bool UseModelName { get; private set; }

 

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)

    {

        dynamic data = null;

 

        if ((controllerContext.HttpContext.Request.AcceptTypes.Any(x => x.StartsWith(ContentType, StringComparison.OrdinalIgnoreCase) == true) &&

            (controllerContext.HttpContext.Request.ContentType.StartsWith(ContentType, StringComparison.OrdinalIgnoreCase) == true)))

        {

            controllerContext.HttpContext.Request.InputStream.Position = 0;

 

            using (var reader = new StreamReader(controllerContext.HttpContext.Request.InputStream))

            {

                var payload = reader.ReadToEnd();

 

                if (string.IsNullOrWhiteSpace(payload) == false)

                {

                    data = JsonConvert.DeserializeObject(payload);

 

                    if (this.UseModelName == true)

                    {

                        data = data[bindingContext.ModelName];

                    }

                }

            }

        }

 

        return data;

    }

}

Nothing fancy here; it will check to see if both the Accept and the Content-Type HTTP headers are present and set to application/json, the official MIME type for JSON, before parsing the posted content. If any content is present, JSON.NET will parse it into it’s own object. The UseModelName property is used to bind to a specific property of the payload, for example, say you are binding to a parameter called firstName, and you want it populated with the contents of the firstName field in the payload. In our case, we don’t need it, we want the whole thing, so it is set to false.

Now, the way I recommend for applying this model binder is through a custom attribute:

[Serializable]

[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]

public sealed class DynamicModelBinderAttribute : CustomModelBinderAttribute

{

    public DynamicModelBinderAttribute(bool useModelName = false)

    {

        this.UseModelName = useModelName;

    }

 

    public bool UseModelName { get; private set; }

 

    public override IModelBinder GetBinder()

    {

        return new DynamicModelBinder(this.UseModelName);

    }

}

It goes like this:

[HttpPost]

public ActionResult Post([DynamicModelBinder] dynamic payload)

{

    //payload will be populated with the contents of the HTTP POST payload

 

    return this.View();

}

Or, if you want to do it for several dynamic parameters, just set a global model binder provider for type Object; this is safe, because we would never have a parameter of type Object:

public sealed class DynamicModelBinderProvider : IModelBinderProvider

{

    public static readonly IModelBinderProvider Instance = new DynamicModelBinderProvider();

 

    public IModelBinder GetBinder(Type modelType)

    {

        if (modelType == typeof (object))

        {

            return new DynamicModelBinder();

        }

 

        return null;

    }

}

And we register is as this:

ModelBinderProviders.BinderProviders.Insert(0, DynamicModelBinderProvider.Instance);

And that’s it. This is one of what I consider to be ASP.NET MVC flaws, and they will deserve another post, soon. Web API already solves this problem, but it is still there in the future version of MVC Core, and can be solved in the same way.

Encrypted JavaScript in ASP.NET MVC Core

To complete the Data URI saga, here is another technique that you may find interesting: this time, it’s about encrypting JavaScript contents, so as to make them more difficult to tamper with.

Data URIs can be used for serving any content that would normally come from an external resource, such as a JavaScript/CSS file or an image. What we will do here is, using ASP.NET MVC Core’s Tag Helpers, we get hold of the JavaScript that is defined inside a SCRIPT tag and we turn into a Data URI. Pretty simple, yet the result is also pretty cool!

Show me the code, I hear you say:

[HtmlTargetElement("script")]

[HtmlTargetElement("script", Attributes = "asp-encrypt")]

[HtmlTargetElement("script", Attributes = "asp-src-include")]

[HtmlTargetElement("script", Attributes = "asp-src-exclude")]

[HtmlTargetElement("script", Attributes = "asp-fallback-src")]

[HtmlTargetElement("script", Attributes = "asp-fallback-src-include")]

[HtmlTargetElement("script", Attributes = "asp-fallback-src-exclude")]

[HtmlTargetElement("script", Attributes = "asp-fallback-test")]

[HtmlTargetElement("script", Attributes = "asp-append-version")]

public class InlineScriptTagHelper : ScriptTagHelper

{

    public InlineScriptTagHelper(ILogger<ScriptTagHelper> logger, IHostingEnvironment hostingEnvironment,

        IMemoryCache cache, IHtmlEncoder htmlEncoder, IJavaScriptStringEncoder javaScriptEncoder,

        IUrlHelper urlHelper) : base(logger, hostingEnvironment, cache, htmlEncoder, javaScriptEncoder, urlHelper)

    {

    }

 

    [HtmlAttributeName("asp-encrypt")]

    public bool Encrypt { get; set; }

 

    public override void Process(TagHelperContext context, TagHelperOutput output)

    {

        if ((this.Encrypt == true) && (string.IsNullOrWhiteSpace(this.Src) == true))

        {

            var content = output.GetChildContentAsync().GetAwaiter().GetResult().GetContent();

            var encryptedContent = Convert.ToBase64String(Encoding.ASCII.GetBytes(content));

            var script = $"data:text/javascript;base64,{encryptedContent}";

 

            output.Attributes.Add("src", script);

            output.Content.Clear();

        }

 

        base.Process(context, output);

    }

}

You can see that this tag helper inherits from ScriptTagHelper, which is the OOTB class that handles SCRIPT tags. Because of this inheritance, we need to add all the HtmlTargetElementAttributes, so that all the rules get applied properly. For this one, we need to add an extra rule, which forces the SCRIPT tag to have an asp-encrypt attribute.

So, say you have this in your Razor view:

<script asp-encrypt="true">
   1:  

   2:     window.alert('hello, world, from an encrypted script!');

   3:  

</script>

What you’ll end up with in the rendered page is this:

<script src="data:text/javascript;base64,DQoNCiAgICB3aW5kb3cuYWxlcnQoJ2hlbGxvLCB3b3JsZCwgZnJvbSBhbiBlbmNyeXB0ZWQgc2NyaXB0IScpOw0KDQo="></script>

Cool, wouldn’t you say? Of course, no JavaScript that runs on the client can ever be 100% secure, and you should always keep that in mind. But for some purposes, it does pretty well! Winking smile

Inline Images in ASP.NET MVC Core

I have blogged extensively about Data URIs in the past. It allows us to render external contents inside of the page’s HTML, avoiding additional HTTP requests, but enlarging the HTML to serve. Sometimes, it does make sense, especially because the whole page can be made cacheable.

MVC does not offer any mechanism for serving images as inline Data URIs, and that is the reason for this post! Winking smile

For this example, I added an extension method to the IHtmlHelper class, InlineImage:

public static class HtmlHelperExtensions

{

    private static string GetFileContentType(string path)

    {

        if (path.EndsWith(".JPG", StringComparison.OrdinalIgnoreCase) == true)

        {

            return "image/jpeg";

        }

        else if (path.EndsWith(".GIF", StringComparison.OrdinalIgnoreCase) == true)

        {

            return "image/gif";

        }

        else if (path.EndsWith(".PNG", StringComparison.OrdinalIgnoreCase) == true)

        {

            return "image/png";

        }

 

        throw new ArgumentException("Unknown file type");

    }

 

    public static HtmlString InlineImage(this IHtmlHelper html, string path, object attributes = null)

    {

        var contentType = GetFileContentType(path);

        var env = html.ViewContext.HttpContext.ApplicationServices.GetService(typeof (IHostingEnvironment)) as IHostingEnvironment;

 

        using (var stream = env.WebRootFileProvider.GetFileInfo(path).CreateReadStream())

        {

            var array = new byte[stream.Length];

            stream.Read(array, 0, array.Length);

 

            var base64 = Convert.ToBase64String(array);

 

            var props = (attributes != null) ? attributes.GetType().GetProperties().ToDictionary(x => x.Name, x => x.GetValue(attributes)) : null;

 

            var attrs = (props == null)

                ? string.Empty

                : string.Join(" ", props.Select(x => string.Format("{0}=\"{1}\"", x.Key, x.Value)));

 

            var img = $"<img src=\"data:{contentType};base64,{base64}\" {attrs}/>";

 

            return new HtmlString(img);

        }

    }

}

You can see that I only support three image formats: JPEG, GIF and PNG. These are the safe formats that can be rendered by all browsers. The format is inferred from the file name’s extension.

The InlineImage method takes a local file name that will be considered from the site’s root, and an optional collection of attributes. If present, these attributes are added to the generated IMG tag as-is.

To use this extension, all we need is to add this code in a Razor view:

@Html.InlineImage("image.jpg", new { width = "200", height = "200" });

And the output should look like this (trimmed):

<img src="data:image/jpeg;base64,SGVsbG8sIFdvcmxkIQ%3D%3D...=" width="200" height="200" />

This code works as is in ASP.NET MVC Core, but can be easily changed to work in MVC 5 or prior: just use Server.MapPath to get the physical address of the file to load.

MVC Controller Resolver Cache

I recently faced a curious problem: I was using a third party IoC container in an MVC 5 (ASP.NET 4.*) app. In it, I had registered a service with a lifetime of transient, meaning, each resolution would return a different instance.

As you may know, in an MVC controller, there are two ways by which we can resolve a service using the MVC infrastructure:

 

I was using Controller.Resolver to resolve a service, but, after the first resolution, I would alwas get the same instance! It turns out that, by default, Controller.Resolver does not resolve to the same as DependencyResolver.Current, but instead uses an internal implementation that caches resolved services(DependencyResolver.CurrentCache, an internal property)! This means that it is virtually unusable with any lifetime other than singleton!

There are at least three workarounds:

 

If you were to ask me, I’d go for option #3.

ASP.NET 5 Node Services

At the MVP Global Summit, Steven Sanderson (@stevensanderson) presented a Microsoft project he was working on: Node Services. In a nutshell, this is an integration of ASP.NET 5 and Node.js, it makes it possible to call a Node.js function from ASP.NET. One of its possible usages is to use Node.js to compile AngularJS directives or ReactJS JSX files, and for that reason, there are two modules built on top of Node Services just for that purpose (code available at GitHub and NuGet, here and here).

Disclaimer: this is still in early stage, and is likely to change!

So, after you install the NuGet package using the now familiar syntax:

image

You need to register the Node Services it in Startup.cs’s ConfigureServices method:

var app = services.Single(x => x.ServiceType == typeof (IApplicationEnvironment)).ImplementationInstance as IApplicationEnvironment;

 

services.AddSingleton<INodeServices>(new Func<IServiceProvider, INodeServices>(sp => Configuration.CreateNodeServices(NodeHostingModel.Http, app.ApplicationBasePath)));

Now, there are two ways by which ASP.NET can communicate with the Node.js host:

  • HTTP (NodeHostingModel.Http): a local service is started which waits for JSON requests and routes them to Node.js;
  • Interprocess communication (NodeHostingModel.InputOutputStream): a direct stream with the Node.js hosting process; much faster than the HTTP version, but also less reliable.

Creating a Node.js module is easy; let’s add a .JS file to the project:

module.exports = function (cb, a, b)

{

    a = parseInt(a);

    b = parseInt(b);

 

    return cb(null, (a + b).toString());

};

For simplicity’s sake, we are doing a very simple operation: just adding two numbers, but in a real-life scenario you can require any other Node.js modules and do any arbitrarily complex operations. You need to be aware of a couple of things:

  • The first parameter to the exported function must be a callback function; this will be used for returning the result;
  • Each parameter must either be a string or a JSON object;
  • The result – second parameter to the callback function – also needs to be a string or JSON.

And how do you call this? You just need a reference to the registered instance of INodeService, and on it you call a module asynchronously, passing it some parameters:

var node = this.Resolver.GetService(typeof(INodeServices)) as INodeServices;

var result = await node.Invoke<string>("sum.js", "1", "2");    //"3"

You can also specify the module and function name explicitly, if you export it from the .JS file (not in this example):

var result = await node.InvokeExport<string>("sum.js", "sum", "1", "2");

Happy Noding! Winking smile

ASP.NET 5 View Components

One of my favorite features in ASP.NET 5 / MVC 6 is View Components. Like I said of Tag Helpers, I think they are what MVC was missing in terms of reusable components.

View Components are similar to partial views, except that they don’t have a visual design surface; all of its contents must be produced by .NET code. Only “tangible” content can be returned, no redirects, or any other contents that require HTTP status codes.

A View Component needs to either inherit from ViewComponent (no API documentation yet) or be a POCO class decorated with the ViewComponentAttribute. If it inherits from ViewComponent, it gets a lot of useful infrastructure methods, otherwise, it is possible to inject some context, such as a ViewContext reference.

A View Component looks like this:

public class SumViewComponent : ViewComponent

{

    public IViewComponentResult Invoke(int a, int b)

    {

        return this.Content($"<span class=\"result\">{a + b}</span>");

    }

}

As you can see, a View Component can take parameters, any number, for that matter, and, by convention, its entry point must be called Invoke, return an instance of IViewComponentResult, and here is where its parameters are declared.

A View Component is rendered like this:

@Component.Invoke("Sum", 1, 2);    <!-- <span class="result">3</span> –>

As you can see, the argument to Invoke must be the View Component’s class name, without the ViewComponent suffix. We can override this and set our own name, by applying the ViewComponentAttribute:

[ViewComponent(Name = "Sum")]

public class ArithmeticOperation

{

    public IViewComponentResult Invoke(int a, int b)

    {

        return new ContentViewComponentResult($"<span class=\"result\">{a + b}</span>");

    }

}

Notice that this uses a POCO class that does not inherit from ViewComponent. However, the Razor syntax will be exactly the same, because of the Name passed in the ViewComponentAttribute attribute. It basically only needs to be public, concrete and non-generic.

It is also possible to use an asynchronous version:

[ViewComponent(Name = "Sum")]

public class ArithmeticOperation

{

    public async Task<IViewComponentResult> InvokeAsync(int a, int b)

    {

        return new ContentViewComponentResult($"<span class=\"result\">{a + b}</span>");

    }

}

In this case, the Razor syntax must be instead:

@await Component.InvokeAsync("Sum", 1, 2);    <!-- <span class="result">3</span> –>

Because the ViewComponent class exposes some properties that give access to the execution context, namely, ViewContext, it is also possible to have it in the POCO version, by decorating a ViewContext property with ViewContextAttribute:

[ViewContext]

public ViewComponentContext ViewContext { get; set; }

The ViewComponentContext class gives direct access to the arguments, the ViewData and ViewBag collections, the FormContext and a couple of other useful context properties, so it is generally good to have it near by. It is even possible to access the view’s model:

var v = this.ViewContext.View as RazorView;

dynamic page = v.RazorPage;

var model = page.Model;

View Components can benefit of dependency injection. Just add the types that you wish to inject to the constructor, works with both the POCO and the ViewComponent version:

public class SumViewComponent : ViewComponent

{

    public SumViewComponent(ILoggerFactory loggerFactory)

    {

        //do something with loggerFactory

    }

}

One last remark: view components are automatically loaded from the executing assembly, but it is possible to load them from other assemblies, we just need to get an handle to the web application’s IViewComponentDescriptorCollectionProvider. From it, we can get to the ViewComponents collection and add our own:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)

{

    var vcdcp = app.ApplicationServices.GetService<IViewComponentDescriptorCollectionProvider>();

    var list = vcdcp.ViewComponents.Items as IList<ViewComponentDescriptor>;

 

    var viewComponentType = typeof(MyViewComponent);

 

    var attr = viewComponentType.GetTypeInfo().GetCustomAttributes<ViewComponentAttribute>(true).SingleOrDefault();

    var fullName = attr?.Name ?? viewComponentType.DisplayName(true);

 

    list.Add(new ViewComponentDescriptor

    {

        FullName = fullName,

        ShortName = viewComponentType.DisplayName(false),

        Type = viewComponentType

    });

 

    //rest goes here

}

This makes it very easy to register View Components that are declared in different assemblies.

Have fun! Winking smile

Using ASP.NET 5 Tag Helpers and the Bing Translator API

Update: In the latest version of ASP.NET 5, the GetChildContextAsync, that was previously available in the TagHelperContext class, is now in TagHelperOutput.

Introduction

If you’ve been following my posts you probably know that I have been a critic of MVC because of its poor support of reuse. Until now, the two main mechanisms for reuse – partial views and helper extensions – had some problems:

  • Partial views cannot be reused across projects/assemblies;
  • Helper methods cannot be easily extended.

Fortunately, ASP.NET 5 offers (good) solutions for these problems, in the form of Tag Helpers and View Components! This time, I’ll focus on tag helpers.

Tag Helpers

A tag helper behaves somewhat like a server-side control in ASP.NET Web Forms, without the event lifecycle. It sits on a view and can take parameters from it, resulting on the generation of HTML (of course, can have other side effects as well).

Tag helper can either be declared as new tags, ones that do not exist in HTML, such as <animation>, <drop-panel>, etc, or can intercept any tag, matching some conditions:

  • Having some pre-defined tag;
  • Being declared inside a specific tag;
  • Having some attributes defined;
  • Having a well-known structure, like, self-closing or without ending tag.

A number of these conditions can be specified, for example:

  • All IMG tags;
  • All A tags having an attribute of action-name;
  • All SPAN tags having both translate and from-language attributes;
  • All COMPONENT tags declared inside a COMPONENTS tag.

ASP.NET 5 includes a number of them:

  • AnchorTagHelper: generates links to action methods in controllers;
  • CacheTagHelper: caches its content for a number of seconds;
  • EnvironmentTagHelper: renders its content conditionally, depending on the current execution environment;
  • FormTagHelper: posts to an action method of a controller;
  • ImageTagHelper: adds a suffix to an image URL, to control caching of the file;
  • InputTagHelper
  • LabelTagHelper
  • LinkTagHelper
  • OptionTagHelper
  • ScriptTagHelper
  • SelectTagHelper
  • TextAreaTagHelper
  • ValidationMessageTagHelper: outputs model validation messages;
  • ValidationSummaryTagHelper: outputs a validation summary.

In order to use tag helpers, we need to add a reference to the Microsoft.AspNet.Mvc.TagHelpers Nuget package in Project.json (at the time this post was written, the last version was 6.0.0-beta8):

"dependencies": {

    ...

    "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta8"

}

Enough talk, let’s see an example of the TagHelper class with some HtmlTargetElement attributes (no API documentation available yet):

[HtmlTargetElement("p", Attributes = "translate, to-language")]

[HtmlTargetElement("span", Attributes = "translate, to-language")]

public sealed class TranslateTagHelper : TagHelper

{

}

This tag helper will intercept the following tag declarations, inside a view:

<p translate="true" to-language="pt">This is some text meant for translation</p>

<span translate="true" to-language="pt">Same here</span>

Tag helpers need to be declared in a view before they can be used. They can come from any assembly:

@addTagHelper "*, MyNamespace"

Properties declared on the markup will be automatically mapped to properties on the TagHelper class. Special names, such as those having , will require an HtmlAttributeName attribute:

[HtmlAttributeName("to-language")]

public string ToLanguage { get; set; }

If, on the other hand, we do not want such a mapping, all we have to do is apply an HtmlAttributeNotBound attribute:

[HtmlAttributeNotBound]

public string SomeParameter { get; set; }

The TagHelper class defines two overridable methods:

  • Process: where the logic is declared, executes synchronously;
  • ProcessAsync: same as above, but executes asynchronously.

We only need to override one. In it, we have access to the passed attributes, the content declared inside the tag and its execution context:

public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)

{

    var content = await context.GetChildContentAsync();

    var text = content.GetContent();


    //do something with content


    content.TagName = "DIV";

    content = output.Content.Clear();

    content = output.Content.Append("HTML content");

}

You can see that I am redefining the output tag, in this case, to DIV, and, also, I am clearing all content and replacing it with my own.

Now, let’s see a full example!

Content Translation

Microsoft makes available for developers the Bing Translator API. It allows, at no cost (for a reasonable number of requests) to perform translations of text through a REST interface (several API bindings exist that encapsulate it). Let’s implement a tag helper that will automatically translate any text contained inside of it.

In order to use this API, you first need to register at the Microsoft Azure Marketplace. Then, we need to create a Marketplace application. After we do that, we need to generate an authorization key. There are several tools that can do this, in my case, I use Postmap, a Google Chrome extension that allows the crafting and execution of REST requests.

The request for generating an authorization key goes like this:

POST https://datamarket.accesscontrol.windows.net/v2/OAuth2-13

grant_type: client_credentials

client_id: <client id>

client_secret: <client secret>

scope: http://api.microsofttranslator.com

The parameters <client id> and <client secret> are obtained from our registered applications’ page and grant_type, client_id, client_secret and scope are request headers. The response should look like this:

{
“token_type”: “
http://schemas.xmlsoap.org/ws/2009/11/swt-token-profile-1.0″,
“access_token”: “<access token>“,
“expires_in”: “600”,
“scope”: “
http://api.microsofttranslator.com”

}

Here, what interests us is the <access token> value. This is what we’ll use to authorize a translation request. The value for expires_in is also important, because it contains the amount of time the access token is valid.

A translation request should look like this:

GET http://api.microsofttranslator.com/V2/Ajax.svc/Translate?to=<target language>&text=<text to translate>&from=<source language>

Authorization: Bearer <access token>

The <target language> and <text> parameters are mandatory, but the <source language> one isn’t; if it isn’t supplied, Bing Translator will do its best to infer the language of the <text>. Authorization should be sent as a request header.

Let’s define an interface for representing translation services:

public interface ITranslationService

{

    Task<string> TranslateAsync(string text, string to, string @from = null);

}

Based on what I said, a Bing Translator implementation could look like this:

public sealed class BingTranslationService : ITranslationService

{

    public const string Url = "http://api.microsofttranslator.com/V2/Ajax.svc/Translate?text={0}&to={1}&from={2}";


    public string AuthKey { get; set; }


    public async Task<string> TranslateAsync(string text, string to, string @from = null)

    {

        using (var client = new HttpClient())

        {

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", this.AuthKey);


            var result = await client.GetStringAsync(new Uri(string.Format(Url, WebUtility.UrlEncode(text), to, from)));


            return result;

        }

    }

}

Let’s register this service in ConfigureServices:

services.AddSingleton<ITranslationService>((sp) => new BingTranslationService { AuthKey = "<access token>" });

Of course, do replace <access token> by a proper one, otherwise your calls will always fail.

Caching

In order to make our solution more scalable, we will cache the translated results, this way, we avoid unnecessary – and costly – network calls. ASP.NET 5 offers two caching contracts, IMemoryCache and IDistributedCache. For the sake of simplicity, let’s focus on IMemoryCache, On the ConfigureServices method of the Startup class let’s add the caching services:

services.AddCaching();

And now let’s see it all together.

Putting it All Together

The final tag helper looks like this:

[HtmlTargetElement("p", Attributes = "translate, to-language")]

[HtmlTargetElement("span", Attributes = "translate, to-language")]

public sealed class TranslateTagHelper : TagHelper

{

    private readonly ITranslationService svc;

    private readonly IMemoryCache cache;


    public TranslateTagHelper(ITranslationService svc, IMemoryCache cache)

    {

        if (svc == null)

        {

            throw new ArgumentNullException(nameof(svc));

        }


        this.svc = svc;

        this.cache = cache;

    }


    [HtmlAttributeName("from-language")]

    public string FromLanguage { get; set; }


    [HtmlAttributeName("to-language")]

    public string ToLanguage { get; set; }


    public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)

    {

        if (string.IsNullOrWhiteSpace(this.ToLanguage) == true)

        {

            throw new InvalidOperationException("Missing target language.");

        }


        var content = await context.GetChildContentAsync();

        var text = content.GetContent();


        if (string.IsNullOrWhiteSpace(text) == true)

        {

            return;

        }


        var cacheKey = $"{this.FromLanguage}:{text.ToLowerInvariant().Trim()}:{this.ToLanguage}";

        var response = string.Empty;


        this.cache?.TryGetValue(cacheKey, out response);


        if (string.IsNullOrWhiteSpace(response) == true)

        {

            response = await svc.TranslateAsync(text, this.ToLanguage, this.FromLanguage);

            response = response.Trim('"');


            cache?.Set(cacheKey, response);

        }


        content = output.Content.Clear();

        content = output.Content.Append(response);

    }

}

It tries to obtain the translated context from the cache – if it is registered – otherwise, it will issue a translation request. If it succeeds, it stores the translation in the cache. The cache key is a combination of the text (in lowercase), the source and destination languages. The only strictly required service is an implementation of our ITranslationService, the cache is optional. In order use the tag in a view, all we need is:

@addTagHelper "*, MyNamespace"


<p translate="yes" to-language="pt">This is some translatable content</p>

Conclusion

I hope I managed to convince you of the power of tag helpers. They are a powerful mechanism and a welcome addition to ASP.NET MVC. Looking forward to hearing what you can do with them!

The Evolution of .NET Dependency Resolution

Introduction

Dependency Resolution (RS), Dependency Injection (DI) and Inversion of Control (IoC) are hot topics nowadays. Basically all frameworks are aware of it, or offer some mechanisms to help implement it. It all started a long time ago, however, and things are slightly confusing at the moment – but will get better!

In this post, I won’t go through all of the details of all dependency resolution libraries in existence, instead I will only focus on Microsoft libraries. Also, I will only talk about generic dependency resolution, leaving out more specialized usages, such as WCF, WF and SharePoint, which also use similar concepts.

Origins

It all started with the venerable IServiceProvider interface. It basically provided a single method, GetService, that gave answer to “get me an implementation for this type”. That was it, the single parameter was a Type, and the response, a single object. There were no public implementations of it, but Windows Forms designers – auto generated code – used it a lot to request services from the design surfaces (aka, Visual Studio designer). You were free to implement it in any way, the only recommendation was to return null in case no service could be found, instead of throwing an exception.

ASP.NET MVC

ASP.NET MVC started as a built-in template option in Visual Studio but then migrated to NuGet deployment, which is how Microsoft now delivers its fast-moving libraries. MVC 4 introduced its own dependency injection container and API. It was built around IDependencyResolver interface, which did not implement IServiceProvider. although it offered a GetService method that had exactly the same signature – and requirements – as IServiceProvider’s. It also added another method, GetServices, for retrieving all implementations of a given service, again identified by its Type.

This time we had a registration point, which was DependencyResolver.Current. You could set it to your custom implementation, or use the default, which didn’t really return anything.

ASP.NET Web API

Web API came out a bit later than MVC, and, while sharing its philosophy, and also being delivered through NuGet, offered its own APIs, namely, for dependency injection. There was also a IDependencyResolver interface, again, not inheriting from IServiceProvider, but with a slightly more complex inheritance: now we had also IDependencyScope, which was where the GetService and GetServices methods were declared, as well as IDisposable, supposedly so that we could have dependency resolution scopes. The well-known registration point was GlobalConfiguration.Configuration.DependencyResolver.

ASP.NET SignalR

SignalR was something of an outsider in the ASP.NET stack. Like MVC and Web API, it was offered (and still is, for that matter) as a separate NuGet package. No wonder that it also offered its own dependency resolution API, in the form of IDependencyResolver. Again, not related to IServiceProvider, and as such offered a couple of other methods: besides the classic GetService (same signature and contract), we also had GetServices, and even a registration method (RegisterType with a couple of overloads). It was also IDisposable, perhaps to control registration scopes. The registration point was available as GlobalHost.DependencyResolver and there was a default implementation, appropriately named DefaultDependencyResolver.

Entity Framework 6

Leaving ASP.NET land for a moment, Entity Framework 6 also introduced its own (of course…) API for dependency resolution. The IDbDependencyResolver also offered the now classic GetService and GetServices methods, but this time, these also took an optional key parameter. GetService should not throw if a matching service was not found, and GetServices should return an empty enumeration likewise. The registration was done through DbConfiguration.DependencyResolver, no public default implementation. EF 6 expected a number of services to be supplied through dependency resolution, otherwise, it would use its own built-in defaults.

Entity Framework 7

Although still in pre-release, EF 7 shuffles things a bit. For once, the DbContext constructor can now take an instance of IServiceProvider. More details coming soon, I guess, but apparently it seems to be going back to the roots.

Unity

Unity is part of Microsoft’s Enterprise Library and long time readers of my blog should know that it’s what I normally use for inversion of control (IoC), dependency injection (DI) and aspect-oriented programming (AOP). Being an IoC container, it includes its own API, IUnityContainer, which also offered service resolution methods, besides lots of other stuff; this time, the names are Resolve and ResolveAll, with several overloads and generic as well as non-generic versions. Resolve can take an optional key, but a major difference is that the default implementation (UnityContainer) will throw an exception if a service is not found.

Common Service Locator

Because there are lots of dependency resolution libraries out there, offering conceptually similar services but with different APIs, Microsoft sponsored an open-source library for defining a common interface for dependency resolution to which interested parties could comply, or, better, write an adapter for. The code is available in Codeplex and NuGet and several library authors provided adapters for the Common Service Locator, such as Unity, Castle Windsor, Spring.NET, StructureMap, Autofac, MEF, LinFu, Ninject, etc. See a list of NuGet packages matching Common Service Locator here. The Common Service Locator API only prescribes two families of methods in its IServiceLocator API: GetInstance and GetAllInstances. Interestingly, IServiceLocator inherits from IServiceProvider, and it also features an optional key for GetInstance, like EF6 and Unity, as this is the more general case – multiple registrations for the same type under different keys, the default key is null.

ASP.NET 5

ASP.NET 5 is just around the corner, and Microsoft seems to me to be moving in the right direction. MVC, Web API and SignalR are merged together, so the dependency resolution mechanisms should be the same. The IServicesCollection (sorry, no public API documentation) interface allows for the registration and the resolution of services through the conventional Startup.ConfigureServices method and is made available in the HttpContext and IApplicationBuilder implementations as the ApplicationServices and RequestServices properties, of type IServiceProvider. Not that you typically need it, but the default implementation of IServicesCollection is ServicesCollection, and one key difference is that you do not have a global entrypoint to it, you can only access it through the current HttpContext reference, in most cases.

Conclusion

That’s it. Looking forward for your feedback on this.