Tuesday, February 16, 2016

Reading version information from project.json

As of now, many of you are aware about the information stored in project.json file in ASP.NET Core 1.0. My this blog post will tell, how to retrieve the version number from project.json file.

Below is the screenshot of my json file:

And below is the code to get the version number:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
            // Reading project.json file
            var projConfig = new ConfigurationBuilder().AddJsonFile("project.json").Build();

            //app version number
            var appVersion = projConfig["version"];

            // SQL Server version number
            var sqlServerVersion = projConfig["dependencies:EntityFramework.MicrosoftSqlServer"]; 
Hope this post was helpful.
Mothertouch Round Walker (Blue)

Thursday, February 11, 2016

Application State in ASP.NET Core 1.0

Mee Mee Steam Engine
Introduction to Application State
Application state provides a way to store in-memory data, which are smaller in size. It includes both global and user-specific data. Such data can be used across application and can be used by all users. Prior to ASP.NET Core 1.0 also there were Application and Session state options available to store such sort of data.

Ways of managing Application State?
Now question is, which state storage provider is to be used and when? It is influenced by variety of factors:
  • Size of data
  • Format of data
  • Duration to persist data
  • Sensitivity of data, etc.
Based on your answers, Application State can be managed in variety of ways like:
  • HTTPContext
  • Cookies
  • Session
  • Querystring and Post
  • Cache
  • Other options (EF, Azure Table Storage, etc.)
As part of ASP.NET Core 1.0 release, there is change in HTTPContext object. Hence I’ll emphasis on that.

Items collection of HTTPContext is used to store data which is required only for that particular request. It means contents are discarded and renewed after every HTTP request. HTTPContext.Items is a simple dictionary collection of type IDictionary<object, object>. HTTPContext.Items is very useful in sharing data between various middleware components. In another words, one middleware component can add data to HTTPContext.Items collection and other middleware component in the same HTTP request pipeline can read it. Ways to get an instance of HTTPContext can be found here.
Why HTTPContext re-introduced?
Main reasons for re-introducing HTTPContext are:
  • ASP.NET Core 1.0 no more uses System.Web assembly. It was done in order to reduce the application footprint by introducing new libraries based on functionality.
  • Huge size of object graph for HttpContext. Earlier this size was approximate 30K, which has now come down to approximate 2K.
Application State Considerations
  • Data is stored in-memory. Hence it is fast as compared to database stored on the server.
  • Application State stores data as Object type, so value has to be converted to appropriate type while reading.
  • Application State data can be access simultaneously by many threads. So, data updates should be done in thread-safe manner.
  • Application State cannot be preserved in Web Farm and Garden scenarios.

Wednesday, February 10, 2016

Consuming Services in ASP.NET Core MVC View

Exclusive Amazon Deals
In continuation to my previous post on injecting services in controller, this time I'm writing on how to inject services directly in MVC View. In order to achieve this, a new keyword @inject is used.
Here I'm not writing entire code again as it can be referred from my previous article.

Let's register the service in ConfigureServices method as:

public void ConfigureServices(IServiceCollection services)

Next is to inject service inside a View as:
@inject IGUIDService guidService

Now service is injected and available for use. Let's quickly use it:

@using CustomTagHelper.Services;
@inject IGUIDService guidService


Run your application and you will be able to see the required output as:

Hope you enjoyed learning :)

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: 


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.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.