:::: MENU ::::

Monday, December 21, 2015

Dependency Injection (DI) is a technique to develop loosely coupled software systems. Although this article won't go into the details of DI as such, the basic idea is this:
Assume that there is a class Class1 that depends on Class2 and Class3 for its functioning. The normal practice is to instantiate the objects of Class2 and Class3 inside Class1 as shown below:
public class Class1
{
   private Class2 objClass2;
   private Class3 objClass3;

    public Class1()
    {
      objClass2 = new Class2();
      objClass3 = new Class3();
    }
   ....
   ....
}
Although this might work as expected it has a problem of its own - there is tight coupling between Class1 and its dependencies (Class2 and Class3). If you wish to replace Class2 and Class3 with some other implementations you need to change the code of Class1 since these objects are created inside the class.
To get away from this dependency you can do the following:
  • Base Class2 and Class3 on some interface.
  • Supply objects of classes implementing the interface (Class2 and Class3 in this case) from external world.
In other words you inject dependencies of a class from the external world. So, Class1 will look like this:
public class Class1
{
    public Class1(ISomeInterface objClass2, 
                  ISomeOtherInterface objClass3)
    {
      ....
    }
}
Ok. Now that you have some idea about DI, let's see how ASP.NET MVC 6 allows you to work with it.
As far as ASP.NET MVC 6 is concerned, a type to be injected is called a service. The ASP.NET MVC 6 dependency injection framework does two basic tasks for you:
  • It instantiates an object of the said service and supplies it to controllers. The dependencies can be injected through constructor injection or through property injection.
  • It handles the lifetime (when to create an object and when to dispose it) of the injected object.
There are four lifetime modes for a service being injected:
  • Singleton : An object of a service is created and supplied to all the requests to that service. So, basically all requests get the same object to work with.
  • Scoped : An object of a service is created for each and every request. So, each request gets its a new instance of a service to work with.
  • Transient : An object of a service is created every time an object is requested.
  • Instance : In this case you are responsible for creating an object of a service. The DI framework then uses that instance in singleton mode mentioned earlier.
Let's see how each of these modes work.
Begin by creating a new ASP.NET MVC 6 project as outlined here. Then add an interface and a class to the Classes (or some other folder of you choice) folder:
public interface IMyServiceInterface
{
    string UniqueID { get; set; }
}

public class MyService:IMyServiceInterface
{
    public string UniqueID { get; set; }

    public MyService()
    {
        this.UniqueID = Guid.NewGuid().ToString();
    }
}
The MyServiceInterface class defines a single property - UniqueID. The MyService class implements IMyServiceInterface. The UniqueID property is set to a new GUID in the constructor of the MyService class. This way you can observe the value of UniqueID to understand the lifetime modes mentioned above.
Then add HomeController and Index view to the project.

Singleton

The DI services and their lifetime modes are registered in the Startup class. So, open the Startup class and modify the ConfigureServices() method as shown below:
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddSingleton();
}
Notice the line marked in bold letters. It uses the AddSingleton() method of the IServiceCollection to register MyService class as a service type. As the name suggests AddSingleton() method registers MyService with singleton mode.
Next, open the HomeController and write the following code to it:
public class HomeController : Controller
{
    private IMyServiceInterface obj;

    public HomeController(IMyServiceInterface obj)
    {
        this.obj = obj;
    }

    public IActionResult Index()
    {
        ViewBag.Obj = this.obj;
        return View();
    }
}
The HomeController constructor takes a parameter of IMyServiceInterface. Since a type that implements this interface is registered with the DI framework, an object of MyService is created and supplied to the constructor. The object reference is stored in a local obj variable for later use.
The Index() action, simply sets a ViewBag property to this injected object. The Index view outputs the value of UniqueID property as follows:

UniqueID of Obj : @ViewBag.Obj.UniqueID

If you run the application your browser should look something like this:
Now open another browser tab and issue another request to /home/index. You will find that both the tabs output the same UniqueID confirming that a singleton object is being created.

Scoped

To change the lifetime mode to Scoped, open Startup class again and change the call as shown below:
 services.AddScoped();
This time the code uses AddScoped() method. After making this change run the application again. Simulate multiple requests as before. This time you will find that each tab displays different UniqueID. This conforms that each request is being supplied with a new object instance.

Transient

To test the transient mode you need to change the Startup class like this:
services.AddTransient();
This time the code uses AddTransient() method to register MyService. Now, to simulate multiple object creation requests within a single request-response cycle modify HomeController as shown below:
public class HomeController : Controller
{
    private IMyServiceInterface obj1;
    private IMyServiceInterface obj2;

    public HomeController(IMyServiceInterface obj1, 
                   IMyServiceInterface obj2)
    {
        this.obj1 = obj1;
        this.obj2 = obj2;
    }

    public IActionResult Index()
    {
        ViewBag.Obj1 = this.obj1;
        ViewBag.Obj2 = this.obj2;
        return View();
    }
}
This time the HomeController declares two variables of IMyServiceInterface. The constructor accepts two parameters of IMyServiceInterface - obj1 and obj2. This is just to simulate multiple object creation requests. The obj1 and obj2 are stored in ViewBag as before.
The Index view outputs the UniqueID from both the objects like this:

UniqueID of Obj : @ViewBag.Obj1.UniqueID

UniqueID of Obj2 : @ViewBag.Obj2.UniqueID

To test the transient mode, run the application. You will find that the two UniqueID values are different even for a single HTTP request.

Instance

In this case you need to create an instance of MyService and register it with the DI framework. You can do so in ConfigureServices() as shown below:
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    MyService obj = new MyService();
    obj.UniqueID = "013f98e7-bb8b-4d9f-b5a0-04e930db5357";

    services.AddInstance(obj);
}
As you can see, the code creates an object of MyService and assigns its UniqueID property to some GUID. This manually created object instance is then registered with the DI framework using AddInstance() method.
You can run the application as before. You will observe that it works like singleton lifetime mode - the same object instance is supplied to all the requests.

Property Injection Using [FromServices]

The preceding examples used constructor injection to inject MyService instance into the constructor. If you wish you can use an alternative - property injection. To use property injection the controller needs to have public properties of the service type. More importantly they must be decorated with [FromServices] attribute. The following code illustrates how that works:
public class HomeController : Controller
{
    [FromServices]
    public IMyServiceInterface ObjMyService { get; set; }

    ....
    ....
}
The HomeController has a public property ObjMyService. The property is decorated with [FromServices] attribute. The constructor has been removed from the controller. Now the DI framework will instantiate the IMyServiceInterface object according to the lifetime mode configured in ConfigureServices() and assign it to the ObjMyService property. You can then use the ObjMyService wherever you need in the controller.

Tuesday, December 1, 2015

VS 2015 Update 1 is now available for download, including the updated Community edition. The VS 2015 Update 1 Redistribution packages are also available (x86, x64), as well as the Remote Debugging Tools (x86, x64, ARM). For more information, see Brian Harry's blog, the Visual C++ Team blog, and the Visual Studio Team blog.

Compiler and CRT
VS 2015 Update 1 includes a new version of the C/C++ compiler (19.00.23506). There is also a new version of the C/C++ Runtime (14.0.23506).

Note that VS 2015 can target Windows 10, Windows 8.x, Windows 7 Service Pack 1, Windows Vista Service Pack 2, and optionally Windows XP Service Pack 3. The Visual C++ 2015 REDIST does not support Windows 7 RTM, Windows Vista RTM, Windows Vista Service Pack 1, Windows XP RTM, Windows XP Service Pack 1, or Windows XP Service Pack 2 as these platforms are all outside their support lifecycle. See KB2661358.

Windows 10 SDK: VS 2015 Update 1 includes an updated Windows Tools 1.2 with the Windows 10 SDK for Version 1511 (10.0.10586). As before, this is an optional install.

.NET: There is now a 4.6.1 release including a number of Windows Presentation Foundation (WPF) improvements including a D3DImage for Direct3D 11 available on GitHub.

When it comes to writing good code in web development it is easy to get lost in the quantity of resources you find online. There are some basics that everyone knows or should know and there are some more specific ones.
Are you able to tell me right now that you sure you follow these practices ? Probably not. You probably have the intuition that you do and you are certainly writing your code with them in mind but you cannot be sure you always respect them.
As I said, there are a lot of different resources on the web. It is not easy to know all of them. It is not easy to follow all of them. And it is sure not easy to be sure you did it correctly.
This is why we decided to create the Best Practices plugin in Vorlon.js. It is a way for you to automatically get hints and recommandations about how you could improve your code. The current list of practices and scans have been created from our own experience. It is extensible and you can add your own rules to contribute to this plugin and make it more accurate and comprehensive. :)
A great thanks to Guillaume Leborgne and Mehdi Lahlou for their strong work on this!

How to use the best practices plugin

First of all, you need to setup a Vorlon.js environment. You can follow the documentation we provide here :http://vorlonjs.com/documentation/#vorlonjs-server
Once you have an up and running vorlon.js server and your website is connected to it, hit the “play” button on the Best Practice tab. It will run dynamic and static tests on the page you are currently debugging and the resources linked to it (JavaScript files, CSS files, etc.)
The above video shows you the kind of result you get when using this plugin. All the recommendations are organized into 4 categories, Web Standards, Accessibility, Performances, Mobile Web.
Let’s have a look at some of the rules you get in each of these categories.

1. Web Standards

There are a lot of common mistakes we can do in this area. Sometimes, it is not even a mistakes. Take the JavaScript libraries you use for instance: how frequently do you go and check if the version you are referencing is obsolete or not ? Or consider the CSS prefixes problematic: are you sure you always add all the vendor prefixes? That could be a good idea to make sure your site works correctly on the widest range of computers. Do you have code which does browser detection ? You should change it to feature detection. Etc. etc.
This section gives your insights about what you can improve in this area:
  • Avoid browser detection: tells you if you have code calling navigator.userAgent 
  • Avoid browser specific content: is checking whether your website is sending a different content for some browsers
  • Avoid conditionnal comment: Conditional comments are not the best way to adapt your website to target browser, and support is dropped for IE > 9.
  • Incorrect use of css fallback: validates that all the css rules present in the CSS file are really there in the computed styles. This is a dynamic check and the result might be true or false depending on the browser you use.
  • Incorrect use of prefixes: this one is performing a static scan on your CSS files to ensure you are always using all the vendor prefixes
  • Object and embed: the modern web is only about web languages not plugins, activeX and other embeded objects. This validates that your website does not include one
  • Update JavaScript libraries: checks if all the JS files you are using are considered by their creators as not obsolete
  • Use modern doctype: Modern doctype like are better for browser compatibility and enable using HTML5 features.

2. Accessibility

Following web standards does not guarantee you that your web page is easily accessible. Accessibility is something the Vorlon.js team is really concerned about.
A lot of work is done currently for sometimes now about this by great people. One exemple is the aXe product created bydeque. It is an open source tool which gives you a gigantic list of advices about your website. They go deep in the analysis and can for instance tell you that a specific element has insufficient color contrast for someone visually impaired to see properly. This is really awesome work and we worked with the team at deque to integrate this into this plugin.
Note : this integration is not available in the npm version of Vorlon.js yet but you can get it form the dev branch in the github repository.
There are too much rules in there for me to be able to list them all but here are the fixed one:
  • Form elements must have labels: for them to be understandable by automated web readers
  • Images must have alternate text: this one is listing you all the tag which does not contain the alt attribute.
  • Use aria attributes
All the aXe rules are displayed only if they are in a failed state :

3. Performances

You can follow some simple rules to get better performances for your website.
  • Encore static content: tries to determine if you are using gzip or deflate encoding to reduce de network bandwith
  • Minify static files: checks if you used a minification process to reduce the size of your CSS and JavaScript files
  • Try bundling your files: simple algorithm that checks if you created a single file for all your scripts to reduce HTTP requests

4. Mobile Web

When it comes to mobiles, a lot of web devs forget to add the correct elements and information to take it correctly into account.
  • define platform icons: This is really not mandatory but it gives the user a better experience when they are pinning your websites
  • use meta viewport: Use meta viewport tag to choose how your website will get scaled on smaller devices like phones. Define at least
  • use responsive approaches: Even if your website target only certain devices, you may have users with unexpected devices or screen ratio.

Your turn !

The plugin provides for now somes basic rules. We really hope this will be completed by new rules that anyone in the community can create. Do not hesitate to add yours and create a pull request in the Vorlon.js repo.

Monday, November 23, 2015

Today I was working on a blog plug-in for an existing application. The application is an ASP.NET MVC application so the application uses MVC’s routing to handle file access for the most part. One of the requirements for the blogging component is that it has to integrate with Windows Live Writer handling posting and updates to posts. One of the requirements for Live Writer to supported extended post properties when uploading new posts is a Live Writer Manifest file.

Serving the wlwmanifest.xml File from a Subfolder

The issue is that the manifest file has to live at a very specific location in the blog's root folder using an explicit filename.
If your site is running from a Web root, that's not a problem – it's easy to link to static files in the Web root, because MVC is not managing the root folder for routes (other than the default empty ("") route). So if you reference wlwmanifest.xml in the root of an MVC application by default that just works as IIS can serve the file directly as a static file.
Problems arise however if you need to serve a 'virtual file' from a path that MVC is managing with a route. In my case the blog is running in a subfolder that is a MVC managed routed path – /blog. Live writer now expects the wlwmanifest.xml file to exist in the /blog folder, which amounts to a URL like the following:
Sounds simple enough, but it turns out mapping this very specific and explicit file path in an MVC application can be tricky.

MVC works with Extensionless URLs only (by default)

ASP.NET MVC automatically handles routing to extensionless urls via the IIS ExtensionlessRouteHandler which is defined in applicationhost.config:
<system.webServer> <handlers> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="0" /> </handlers> </system.webServer>
Note the path="*." which effectively routes any extensionless URLs to the TransferRequestHandler which is MVC's entrypoint.
This handler routes any extensionless URLs to the MVC Routing engine which then picks up and uses the routing framework to route requests to your controller methods – either via default routes of controller/action or via custom routes defined with [Route()] attributes. This works great for MVC style extensionless routes that are typically used in MVC applications.

Static File Locations in Routed directories

However, things get tricky when you need to access static files in a directory that MVC routes to. For the Live Write scenario particularly I need to route to:
The problem is:
  • There’s no physical blog folder (wlwmanifest.xml resides in the root folder)
  • /blog/ is routed to by MVC
  • /blog/ is a valid and desirable MVC route
  • wlwmanifest.xml can’t be physically placed in this location
And that makes it rather difficult to handle the specific URL Live Writer expects in order to fine the manifest file.
There are a couple of workarounds.

Skip Routing use UrlRewrite

After futzing around with a bunch of different solutions inside of MVC and the routing setup, I instead decided to use the IIS UrlRewrite module to handle this. In retrospect this is the most efficient solution since IIS handles this routing at a very low level.
To make this work make sure you have the IIS Rewrite Module installed – it’s an optional component and has to be installed via the IIS Platform installer.
Then add the following to your web.config file:
<system.webServer>
  <rewrite>
    <rules>
      <rule name="Live Writer Manifest">
        <match url="wlwmanifest.xml"/>
        <action type="Rewrite" url="blog/manifest"/>
      </rule>
    </rules>
  </rewrite>
</system.webServer>
This effectively routes any request to wlwmanifest.xml on any path to a custom MVC Controller Method I have set up for this. Here’s what the controller method looks like:
[AllowAnonymous]        
[Route("blog/manifest")]
public ActionResult LiveWriterManifest()
{            
    return File(Server.MapPath("~/wlwmanifest.xml"), "text/xml");
}
This is an efficient and clean solution that is fixed essentially through configuration settings. You simply redirect the physical file URL into an extensionless URL that ASP.NET can route as usual and that code then simply returns the file as part of the Response. The only downside to this solution is that it explicitly relies on IIS and on an optionally installed component.

Custom Path to TransferRequestHandler

Another, perhaps slightly safer solution is to map your file(s) to the TransferRequestHandler Http handler, that is used to route requests into MVC. I already showed you that the default path for this handler is path="*." but you can add another handler instance into your web.config for the specific wildcard path your want to handle. Perhaps you want to handle all .xml files (path="*.xml") or in my case only a single file (path="wlwmanifest.xml").
Here's what the configuration looks like to make the single wlwmanifest.xml file work:
<system.webServer>
  <handlers>
    <add name="Windows Live Writer Xml File Handler"
      path="wlwmanifest.xml"
      verb="GET" type="System.Web.Handlers.TransferRequestHandler"
      preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="0"  />
  </handlers>
</system.webServer>
Once you do this, you can now route to this file by using an Attribute Route:
[Route("blog/wlwmanifest.xml")]
public ActionResult LiveWriterManifest()
{            
    return File(Server.MapPath("~/wlwmanifest.xml"), "text/xml");
}
or by configuring an explicit route in your route config.

Enable runAllManagedModulesForAllRequests

If you really want to route files with extensions using only MVC you can do that by forcing IIS to pass non-Extensionless Urls into your MVC application. You can do this by enabling the  runAllManagedModulesForAllRequests option on the section in the IIS configuration for your site/virtual:
<system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
</system.webServer> 
While this works to hit the custom route handler, it’s not really something I typically want to enable as it routes every type of document – including static files like images, css, javascript – through the MVC pipeline which adds overhead. Unless you’re already doing this to perform special manipulation of static files, I wouldn’t recommend enabling this option.

Other Attempts

As is often the case, all this looks straight forward in a blog post like this but it took a while to actually track down what was happening and realizing that IIS was short-circuiting the request processing for the .xml file.
Before I realized this though I went down the path of creating a custom Route handler in an attempt to capture the XML file:
public class CustomRoutesHandler : RouteBase
{
    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        var url = httpContext.Request.Url.ToString();

        if (url.ToLower().Contains("wlwmanifest.xml"))
        {
            httpContext.Response.ContentType = "text/xml";
            httpContext.Response.TransmitFile("~/wlwmanifest.xml");
            httpContext.Response.End();
        }        
        return null;
    }

    public override VirtualPathData GetVirtualPath(RequestContext requestContext,
                RouteValueDictionary values)
    {
        return null;
    }
}
To hook up a custom route handler:
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.IgnoreRoute("{resource}.ashx/{*pathInfo}");            
            
    routes.Add(new CustomRoutesHandler());

    routes.MapMvcAttributeRoutes();

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}
The route handler explicitly checks each request coming in and then overrides the behavior to load the static file.
But alas,  this also doesn’t work by default because just like a route that tries to look at an XML file, the file is never actually passed to the MVC app because IIS handles it.
Nevertheless it's good to know t that MVC has the ability to allow you to look at every request it does handle and customize the route or processing along the way which allows for short circuiting of requests which can be useful for special use cases. Irrelevant to my initial problem, but useful and worthwhile to mention in this context :-)

Summary

File based URL access is one of those cases that should be super simple and obvious, but is not. It requires a relatively simple but non-obvious workaround to ensure that you can handle a Url with an extension by either using UrlRewrite or adding an explicit file mapping to the TransferRequestHandler.
Incidentally in ASP.NET 5 (MVC 6) – assumes you’re handling all requests anyway as you are expected to build up the entire request pipeline – including static file handling from scratch. So I suspect in future versions of MVC this sort of thing will be more natural, as long as the host Web server stays out of the way…