Monday, February 8, 2016

Consuming Services in ASP.NET Core MVC Controller


Exclusive Amazon Deals
Another interesting feature of ASP.NET Core is service consumption using Dependency Injection. I already provided the overview of Dependency Injection in my earlier articles. Moving further, in this article we will see how one can inject and consume services to controller using dependency injection.

In ASP.NET, you can access services at any stage of your HTTP pipeline through dependency injection. By default, it provides Constructor injection, but it can easily be replaced by any other container of your choice. Before moving ahead, one point is very important to understand and that is lifetime of services.

ASP.NET Core allows you to configure four different lifetimes for your services.
  • Transient - Created on every request
  • Scoped - Created once per request
  • Singleton - Created first time when they are requested
  • Instance - Created in ConfigureServices method and behaves like a Singleton

To understand the service consumption in easier way, we will create a sample application going step-by-step. My example service will provide GUID to respective controller. So, let's start quickly. 
Create a new project - Create a new project using ASP.NET Web Application template as shown below:
















Add Service Interface - Create an interface named IGUIDService under Services folder as shown below:

public interface IGUIDService
    {
        string GenerateGUID();
    }

Add Service Implementation - Create a class named GUIDServiceunder Services folder and provide the implementation of IGUIDService interface as shown below:

public class GUIDService : IGUIDService
    {
        public string GenerateGUID()
        {
            return ("Generated GUID is: " + Guid.NewGuid()).ToString();
        }
    }


Add a Controller - Next task is to add a Controller namedGUIDController by right clicking on Controllers folder as shown below:














Add a View - Before adding a View, create a folder named under Views folder. Now add a View by right clicking on GUID folder as shown:

















Update the code inside View as shown below: 

@ViewData["GeneratedGUID"]

Use Service in Controller - Now instantiate the service and set the data for View as shown below:

public class GUIDController : Controller
    {
        private IGUIDService _guidService;

        public GUIDController(IGUIDService guidService)
        {
            _guidService = guidService;
        }
        public IActionResult Index()
        {
            ViewData["GeneratedGUID"] = _guidService.GenerateGUID();
            return View();
        }
    }

Register Service - Last step is to register the service in the ConfigureServices method of Startup class as shown below:


public void ConfigureServices(IServiceCollection services)
        {
           ...
           services.AddMvc();
           services.AddInstance<IGUIDService>(new GUIDService());
        }


Everything is set. Now run your application and you would be able to see GUID on browser as:

Friday, February 5, 2016

Tag Helpers in ASP.NET Core 1.0

Exclusive Amazon Deals
This article is for those who would like to use Tag Helpers over old Razor/HTML helpers. Tag Helpers, another new feature of ASP.NET Core. Let’s quickly have a look at it.

What are Tag Helpers?
As per ASP.NET documentation:
                    "Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files".

Tag Helpers are somewhat similar to HTML Helpers/Razor Helpers introduced in previous version of ASP.NET MVC but those helpers were not that easy to understand for web designers because of inline C# method calls. As web designers are more inclined towards HTML, a simpler and comfortable approach was required. Fortunately, ASP.NET Core 1.0 provided that. Now one need not to use HTML Helpers to build cshtml forms. Means when you had to write this:




Now you can write this:




As you can see above format is very easy to understand as it is purely a HTML syntax.

How Tag Helpers work?

When you create a new ASP.NET web application in Visual Studio, it adds Microsoft.AspNet.Tooling.Razor to the project.json file. This is the package that adds Tag Helper tooling and enables intelliSense in Visual Studio. In order to make our Razor views aware of Tag Helpers, a special file named _ViewImports.cshtml is used. This file is stored in Views folder. By default this file will be there. By any chance if file is not there, then create it and add following line in it:




Pre-defined Tag Helpers

ASP.NET Core 1.0 includes a list of pre-defined Tag Helpers:

Anchor - generates hyperlink
Input - generates input elements
Select – generates dropdownlist
Cache – manages partial page caching
Form – generates form element
Script – processes script tag
Link – processes link element
Label – outputs label element
Option – targets individual options in a list                   
TextArea – processes textarea tag
Environment – controls rendering of content
ValidationMessage – generates validation error
ValidationSummary – provides validation summary message
I’ll try to brief about all above Tag Helpers in coming posts. Now what if existing tags doesn't fulfill our need? In that case, we have to go ahead and invent something else. Should we proceed to create Tag Helper based on our requirement? 
Creating Custom Tag Helpers
As part of this article, we will create a new Tag Helper for appreciating someone. Our tag will be <appreciate>. For example:
<appreciate person-name-for-appreciation="shweta"></appreciate>
 
The server will use appreciate Tag Helper to convert that markup into following:
<label>Great Work, Shweta</label>
In order to create this new Tag Helper, we have to create a new class named AppreciateTagHelper and inherit TagHelper in that. Make sure to add the reference of Microsoft.AspNet.Razor.TagHelpers in this new class. Sample code is as:










Note - it is not mandatory to suffix TagHelper in class name. It is just a good practice.
To make this Tag Helper available to all Razor views, we have to add addTagHelper directive to _ViewImports.cshtml file as:
@addTagHelper "*,CustomTagHelper"
 
Above statement signifies that all the custom Tag Helpers (denoted by wild card character) will be available from assembly named CustomTagHelper. If interested, instead of * you can go with fully qualified names also.
Next step is to update our views. Let’s go ahead and append below line in view:
<appreciate person-name-for-appreciation="shweta"></appreciate>
Good thing is, you will get intelliSense for your custom Tag Helper also J
Run your application and you will find that appreciate Tag Helper is replaced with your label markup with output as:
 






Hope you enjoyed learning this new feature.

Tuesday, February 2, 2016

Handling 404 Error for Unknown File Extensions in ASP.NET Core 1.0

Exclusive Amazon Deals
In my previous article, I already briefed about Static Files in ASP.NET Core. Now let’s move bit further and know about how ASP.NET treats content files which are of unknown type for any browser. You might be aware that ASP.NET Core middleware serves only those content files which falls under known content types. As of now, it defines close to 400 known file content types. Now question is, how browser will respond to unknown content type files? Let’s understand it better with an example.

I’m having an image file named SampleData with extension as .shweta. Here shweta is my custom extension and browser has no information about it. Browser has no idea about how to render this type of file. Please note, this is a static resource placed on wwwroot and has to be served to client. Now quickly open SampleData.shweta in browser and see what happens?
 
 
 
 
 

Uhh! This is HTTP 404 Not Found L
But is this message correct? If you will go back and cross check your solution explorer, that file is present as:




























Now question is why such discrepancy? Straight forward answer would be – ASP.NET middleware is not able to serve this unknown file type.

Serving unknown content type
In order to serve file of unknown type, we have to tell browser that which type of file is this. Fortunately, ASP.NET provides us with two useful properties named ServeUnknownFileTypes and DefaultContentType which will do this task for us.







Now if the user glances to a file whose content type is unknown, the browser will treat it as an image and render it accordingly as shown below:











Next interesting question is, what if there are multiple types of files having an unknown to ASP.NET? No worries, ASP.NET Core has solution for that alsoJ. 

Serving multiple unknown content types
It provides a class named FileExtensionContentTypeProvider. Hence any custom content type has to be first added in a collection of this class with proper mapping of extension an MIME type. Below is the sample code for achieving this:







More information about FileExtensionContentTypeProvider class is given here at github and more information about application/x-msdownload is given here.
Hope you enjoyed learning unknown content types in ASP.NET Core.

Friday, January 29, 2016

Consuming Static Resources in ASP.NET Core 1.0

Exclusive Amazon Deals
As discussed in my previous article, static files are those files which are served directly to clients. It includes HTML, CSS, image and JavaScript files. In ASP.NET Core 1.0, default location of static files is wwwroot of project and location of this wwwroot is defined in project.json. So, all the static files which you want to serve to clients must be placed at wwwroot location.  

My article focuses on how to access and expose such static resources to client. Now let’s proceed step-by-step to create awareness on how to use static files.

Step 1 - Create an empty ASP.NET 5 project
Open Visual Studio 2015, select an empty project template for creating new ASP.NET application as:

 Step 2 – Introduce Static File
Create a HTML file under wwwroot folder. Below is my sample HTML file named SampleHTML:

 
 
 
 
 
 


Step 3 - Configure Middleware
Middleware are small components that can be combined as part of application in order to handle HTTP request response pipeline. So in order to serve static files. Midddleware has to be configured by adding static files to the pipeline. And this can be achieved by using extension method named UseStaticFiles in Startup class. But before that, add the required dependency in project.json file as highlighted below:


 

 


Next is to update Configure method in Startup class as:



 

Step 4 - Build and run
Build your code. Now type address as http://<your app name>/SampleHTML.html, your page will be rendered as:


 

 

Hope you enjoyed playing with static files. Benefit of using static files in such a way is that you need not to put extra effort to save your sensitive static file because if your file is not available at wwwroot, it won’t be rendered to client. Enjoy learning !!!

Thursday, January 28, 2016

Fixing ‘DNX design time process error in VS 2015’

Exclusive Amazon Deals

Today I thought to create my first demo using Visual Studio 2015 for ASP.NET Core 1.0. So, I opened VS2015 and chose Web Application template under ASP.NET 5 Templates. Visual Studio started creating a project for me. Although my project was created but at the same time some DNX error was thrown as shown below:

 
 
 
 
 
 
 
 
 
 
I tried various options including restarting machine, re-installing Visual Studio, etc.
But Alas ! Nothing worked. But on surfing for few hours, I found a solution which worked for me.
You can run any of the below commands:
dnvm update-self OR dnvm upgrade
 
Open Visual Studio 2015 and do dnvm update using command line as:


 

 
Once this command was executed, I didn’t get that error again. Hope reading this blog will save your few minutes of troubleshooting. Enjoy learning.

Wednesday, January 27, 2016

Features of ASP.NET Core 1.0

Exclusive Amazon Deals
ASP.NET Core 1.0 is a new open-source framework for building modern Web applications. As compared to previous versions of ASP.NET there are many major changes happened. I’ll try to capture most of the changes in this blog post.

ASP.NET Core 1.0 was initially named as ASP.NET 5. I’m dedicating this blog post to showcase the major features of ASP.NET Core 1.0.

Single aligned web stack
ASP.NET Core 1.0 is a single aligned web stack on top of ASP.NET for Web API and Web UI as shown in below figure (image taken from mva):
 












Above figure clearly depicts that there is very less sharing between these three stacks. If you will see from ASP.NET template view, you will notice that all the three options are dimmed out as shown below:


Much leaner framework with reduced surface area
ASP.NET Core 1.0 is no longer based on System.Web.dll. As per dzone, typical HTTPContext object graph takes 30K in memory while new implementation takes around 2K.It means now you can take only those NuGet packages which are really required. It strictly follows pay-for-what-you-use model.

project.json file
A new JSON file named project.json is introduced which takes care of dependencies and versions. Below is the sample project.json file:


















A very good thing is VS2015 provides the IntelliSense support for all the available NuGet packages and versions.











global.json file
This file is used to configure solution as a whole. By default, in includes below data:








Options for storing configuration settings
Unlike earlier ASP.NET verisons, Web.config is not the only place for storing the configuration settings. ASP.NET Core 1.0 allows you to read configuration values from range of sources like XML, JSON, environment variables. All the configuration sources can be set in a class file named Startup as shown below:























In cloud environment value of environment variables will automatically be used rather than local configuration values.

Client Side Dependency Management
Dependencies folder contains two subfolders corresponds to two package managers named Bower and npn. These folder tells which client side dependencies are managed by which tool.



















Server Side Dependency Management
In ASP.NET Core 1.0, server side references are placed in References folder with corresponding target frameworks



















More Options for Hosting
Cross platform support by .Net Core 1.0 opened up the new hosting options. Now user need not to rely only on IIS for web application hosting. This initiative was taken because IIS is not available on other platforms like Mac and Linux. On such platforms, ASP.NET applications can be self-hosted or kestrel web server can be used.

Inbuilt Dependency Injection Support
ASP.NET Core 1.0 includes a simple built-in inversion of control (IoC) container that supports constructor injection by default, but this can be replaced with any other container. Services are made available through dependency injection and can be setup in ConfigureServices method of StartUp class. I’ll emphasis more on this in my next blog.

Static files at wwwroot
Static files are those files which are served directly to clients. It includes HTML, image and JavaScript files. In ASP.NET Core 1.0, default location of static files is wwwroot of project and location of this wwwroot is defined in project.json. In other words, static files which are not located to wwwroot will not be accessible. Introducing this feature enhances the security capability of application and one need not to impose any exceptional guidelines to block access to delicate files.












Target Frameworks
In order to support cross platform development, applications built using ASP.NET Core 1.0 can target full .Net and .Net Core framework. It means you can run your application either on Windows or on Mac or Linux.














ASP.NET Core 1.0 features at a glance[reference – scott’s weblogs]:
  • Build and run cross-platform ASP.NET apps on Windows, Mac and Linux  
  • Built on .NET Core, which supports true side-by-side app versioning   
  • New tooling that simplifies modern Web development 
  • Single aligned web stack for Web UI and Web APIs   
  • Cloud-ready environment-based configuration  
  • Integrated support for creating and using NuGet packages  
  • Built-in support for dependency injection        
  • Ability to host on IIS or self-host in your own process    
                Basically this new ASP.NET(MVC + Web API + Web Pages = ASP.NET Core 1.0) is much more tuned for modern web development.