C#

  • Bundling & Minification in ASP.NET Core MVC Application

    Bundling is the process of concatnating a set of files into one single file and Minification is removing all the whitespaces and comments in the code, removing extra statements to make the file smaller in size. By doing bundling and minification in our application will reduced the request payloads as well as the number of requests to the server for downloading the assets such as CSS and JS files.

    .NET Framework had an in-built bundling and minification feature for sometime and since the advent of .NET Core they moved to use Grunt and Gulp for doing the same in both the RC versions. These tools primarily used JavaScript for operations such as file manipulation, automation, bundling and minification. Using these tools, we can also schedule tasks to run during a build or a publish event and is very useful in setting up a workflow for these opertions. The only downfall of these were we need to have some knowledge of programming in JavaScript and if you are not a fan of JavaScript then you will have some difficulties playing with it.

    So Mads Kristensen created an extension which automates these processes and the functionality can be achieved with no code. So when Microsoft released .NET Core 1.0 they integrated this into the ASP.NET Core Web project template and is now available for you out of the box, if you are using Visual Studio 2015 for your developement. Basically it supports

    • Bundling your assets into a single file
    • Minification of your assets
    • Create triggers for doing re-bundling automatically
    • Globbing patterns
    • MSBuild support

    Also the same is available as a NuGet package so that non Visual Studio users will also be able to use that in their projects. In this post, I am going to show how to do this a ASP.NET Core MVC project using Visual Studio Code and .NET CLI tools.

    Adding Reference & Configuring BundlerMinifier

    The first is to add the BundlerMinifier package in your json file as shown below

    tools": {
        "BundlerMinifier.Core": "2.0.238",
        "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
        "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
      },
    

    Now we need to add a configuration file in which we will specifiy the files that needs to be bundled and minified. The default name for the config file is bundleconfig.json, the advantage being that the tool will take it automatically by the bundle command. If we specify a different filename, then we need to set it explicitly while executing the command for bundling.

    As you can see from the above snippet, we can specify multiple files that needed to be bundled into a single file as input and when the bundling operation is completed the unified file will be named using the value set in the outputFileName property. To minify the files, just set the value as true for the enabled property in the minify element.


  • Converting a .NET Core RC2 Web Application to RTM

    After two years in the works, Microsoft has released .NET Core to the public in the last week of June. Prior to that they had released two RC version of the framework and many of the developers like us embraced it and started working with it. To make those projects work in .NET Core 1.0 we need to  make some changes in the project so that it continues to work properly in the RTM version too.

    About .NET Core 1.0

    .NET Core 1.0 is available for Windows, Linux and MacOS and can be used to create web apps, microservices, libraries and console applications. Along with the release, they have also introduced a new site called dot.net which is a central location for all the information about .NET framework including .NET Core.

    The easiest way to install .NET Core 1.0 in your machine is by installing the Visual Studio 2015 with Update 3. If you are not using Visual Studio, then you can go ahead and download the following which meets your requirements

    .NET Core SDK - For developing apps with .NET Core and CLI tools

    .NET Core - For running apps with .NET Core Runtime

    Please refer here for more details for downloads

    Upgrading to RTM

    Unlike upgrading from RC1 to RC2, the process for RC2 to 1.0 is pretty straight forward and I was able to complete the whole process within 15 minutes for a simple .NET Core MVC application. 

    Step 1 : Replace all the references with 1.0.0-rc2-final to 1.0.0 in the project.json file

    "Microsoft.AspNetCore.Diagnostics": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Mvc": "1.0.0-rc2-final",
    

    to

    "Microsoft.AspNetCore.Diagnostics": "1.0.0",		    
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.0",	
    

  • Logging into Console in ASP.NET Core MVC Application

    One of the important upgrades happened in .NET Core is the complete rewrite of the diagnostic logging pipeline which emits different events for logging errors. .NET Core now supports logging framework out of the box and also supports extensibility to make use of third party logging frameworks such as Log4Net, NLog etc. Logging can be implemented in quick time with a minimal amount of code in your application.

    Microsoft uses Microsoft.Extensions.Logging namespace for implement logging functionality and acts a wrapper for third party logging frameworks. This eradicates the need of writing our own logging framework to provide abstraction for third party frameworks such NLog, Log4Net etc. Also it has got inbuilt providers for supporting logging into Console, Event log, Trace Logging etc.

    Console logging in ASP.NET Core MVC application.

    As I said earlier logging has got inbuilt support provided by the ILogger class in .NET Core. For that, first we need to add a reference to the Microsoft.Extensions.Logging package in project.json file. Add the following entries under dependencies section in the json file for implementing providers for console and debug logging. 

    "Microsoft.Extensions.Logging": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging.Console": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging.Debug": "1.0.0-rc2-final",

  • Custom Error Pages in ASP.NET Core MVC Application Using StatusCodePages Middleware

    While developing a web application, one of the best practice every developer should follow is to set up a custom error page for the site. Showing that dreaded yellow page to the user during the occurance of an exception is highly unprofessional and is prone to security risks. In one of the earlier post in the blog, I have explained the use of StatusCodePages middleware and various approaches for implementing it in a ASP.NET Core web application.

    In this post, I am going to implement custom error handling in an ASP.NET Core MVC application using the StatusCodePages Middleware. I will use the UseStatusCodePagesWithReExecute method provided by the middleware for showing the error the page in the case of an error. So let's add the following line in the Configure method in the Startup.cs file as shown below

    app.UseStatusCodePagesWithReExecute("/Error");

    This method is telling the web server to execute the action method name Index in the ErrorController. Since we are using the ReExecute method the redirection will happen in the server itself thereby avoiding a round trip between the server and the client.

    Now, we need to create the controller and the action method in it. Create a file in the Controller folder, save it as ErrorController.cs and add the following lines in it


  • Creating and Running Unit Tests for a .NET Core Application

    Unit testing has become a major part in the daily life of a developer these days and most of them are expected to write unit tests when they add a new functionality in the software that is under development. There are lot of third party tools like NUnit, xUnit as well as MS Test framework for writing unit tests for applications developed in .NET. In this post, I am going to detail the steps needed for adding unit test in .NET Core app using Microsoft Test Framework.

    Creating Project

    Let's create a simple .NET Core console application project and then a unit test project for running the tests. For that I have created two folders, src and test for each project and added these in the projects key in global.json file in the root directory. 

    {
    "projects":["src", "test"]
    }

    After that, I created the console application using the dotnet new command and the contents of the Program.cs file and project.json is given below.

    Program.cs

    Created a new class and added a new method which returns the sum of the values in the two variables passed into it.


  • Hosting ASP.NET Core Web App in Docker and Accessing it from outside

    In one of the earlier posts here, I have explained the steps needed to deploy a console application created in your local machine into a docker container. Today, I am going to go through the various steps needed for deploying a .NET Core web app into a Docker container using a dockerfile.

    Please refer the links given towards the bottom of the post to know more about Docker for Windows and .NET Core Apps.

    Creating the Project.

    In this post, I am going to use Yeoman for scaffolding a ASP.NET Core web app from the command prompt. You can read more about Yeoman and how to set it up in machine by referring the links given below.

    Getting Started With Yeoman
    Scaffolding Using Yeoman

    The command used for scaffolding a ASP.NET Core web app is

    yo aspnet

    When this command is executed, Yeoman will list the available options as shown in the image below.



  • Using StatusCodePages middleware in ASP.NET Core Application

    In ASP.NET Web and MVC applications, we have a customErrors.Mode property in the web.config file to specify custom error pages for exceptions happening in the application.

    In an ASP.NET Core web application we can make use of the UseStatusPages middleware to return a custom error page or a error message to the output stream. The middleware can be used to return a custom error message or page when there is an invlid response code between 400 and 600. Normally, the 4xx error is used for client errors where as 5xx is used for server errors.

    To explain the various options available in the middleware, I am going to use a ASP.NET Core web application created using Visual Studio Code and .NET CLI tools to run the application. You can also do the same using Visual Studio IDE too.

    Let's create a empty MVC project and run the application using the dotnet run command. It will self host the application and exposes port# 5000 for accessing the site. Open the site in the default browser by typing in http://localhost:5000/ and if you try to access a page which doesn't exists in the project, the browser will show an empty page or a page with a message saying that Page not found. Given below is the screenshot of the page I got in Chrome. If you open up the developer tools by pressing F12, you can see that the response from the server has 404 as status code.


  • Pushing images to Docker Repository

    Today, in this post I am going to explain the steps needed for publishing an image in your local Docker daemon to the Docker hub.

    Docker hub is central registry of images maintained by Docker. We can use the images to build containers by downloading them into the local machine. For example, in of the previous post, I showed you how to build and deploy .NET core apps in Docker. This was done by downloading the .NET Core image from the Docker repository to my local machine and created the console application using the downloaded image and deployed it to a container.

    You can access the public repository of Microsoft for Docker images @ https://hub.docker.com/u/microsoft/

    The main difference between a registry and repository in Docker terms is that, Registry can be hosted by a third party like Docker hub, Google Container Registry where as a docker repository is collection of different images with same name but with different tags.

    So let's see how can we push our image in the Docker repository.

    Step 1 : Create an account in Docker Hub.

    It's necessary that you should have an account with Docker for maintaining your repositories. So if you haven't created one yet, goto http://hub.docker.com and create if before proceeding to the next steps.

    Step 2 : Create an Image locally.

    Please refer my earlier post here to how to create a console application using .NET Core in Docker. I am going to reuse the image created in that post for pushing it into the public repository.


  • Publishing .NET Core Application in Docker Using DockerFile

    In one of the earlier posts in the blog, I have showed you how to create and run a console application created in .NET Core from a docker container. Please refer the post here to know the details about it. In this post I am going to show you can publish an app created in the host machine to Docker container using a dockerfile.

    A dockerfile is used by Docker to build automatically by reading the instructions inside it. The complete help file is available in Docker documentation site and you refer that for detailed information on the commands that can be used in the file.

    You can go through my earlier posts on how to setup Docker for Windows Beta in your machine and how to troubleshoot issues you face while trying to get started with Docker in your Windows machine.

    Also I will be using .NET Core for creating the console application and will be using the CLI commands and a normal editor for writing the source code for this example on a Windows 10 machine.

    Creating Project

    Let's create a new HelloWorld project in .NET Core using the following command.

    dotnet new

    The above command will create a boilerplate console application which will have a C# file named Program.cs and a project.json file which will have dependencies specified.


  • Json.NET - Finding an element in a JArray Object

    Recently I hit a roadblock in parsing and finding an element in a JArray object in one of the projects which I was working at my workplace. I was working with JSON string like the one given below.

    "[{'Name':'Amal', 'Country':'India'},{'Name':'Luke', 'Country':'England'},{'Name':'Tom', 'Country':'Australia'}, {'Name':'Ram', 'Country':'India'}]"

    It was an array of items which has got two keys named Name and Country and I want to return the object if the search criteria is matched. I can use the combination of a foreach loop and condition check to retrieve the item, but I didn't want to use that because I felt that it's not the proper way to do it. Also, I didn't wanted to create a new class to bind these elements because I just needed to find whether this string has value for a particular key and return the object if found. So I did some research on this topic and finally resolved it using the SelectToken method available in JSON.NET.

    First you need to add the JSON.NET package to your project via NuGet. Then import the Newtonsoft.Json.Linq namespace to your class using the below statement.

    using Newtonsoft.Json.Linq;

    Next up is to parse the json string to an array using the JArray.Parse() method.

    var jArrObject = JArray.Parse(<JSON string>);

    Now we will make use of the JSONPath queries to search for the item 

    var srchItem = jArrObject.SelectToken("$.[?(@.<key name>=='<value>')]");

    If you search result is going to have more than one values then you need to make use of the SelectTokens() method.

    var items = jArrObject.SelectTokens("$.[?(@.<key name>=='<value>')]");

    In JSONPath syntax,

    $ -> root element

    .  -> child operator

    [] -> subscript operator

    ?() -> used to apply a filter

    So in our case the expression is equivalent to saying that For all($) elements in the string return the item if the current element(@) is matching the specified filter(<key name>=='<value>').

    You can refer the documentation here to know more about the JSONPath syntax.


  • Publish a Web App Into Docker Container From Visual Studio

    As most of you may know already that Docker has released a beta version of their Windows avataar some time ago. Unlike the stable version, this one is using native components like Powershell and Hyper-V to leverage it's capabilities in the local machine. You can read more about the beta program and the installation procedure in the links given below.

    Docker for Windows Beta announced
    Installing Docker For Windows Beta
    Native Docker comes to Windows and Mac

    Installing Visual Studio Tools For Docker

    The Visual Studio team also released some tooling for creating containers directly from VS as well as for debugging application hosted in Docker. These are called Visual Studio Tools for Docker and is available for download from the following link.

    Download Visual Studio 2015 Tools for Docker

    The installer is around 30 Megs in size and the installation process is pretty straightforward. You just need to double click on the downloaded installer to start the installation. The first screen will be as shown below, and to start the installation you will need to agree the license terms by clicking on the checkbox.


  • Create and Run a Sample C# Program Using .NET Core RC2 Image in Docker

    You all may be knowing that Microsoft is in the process of rebuilding the .NET framework from the scratch to embrace the rapid advancements happening in the technology world. Last week they released the RC2 version on .NET Core which is vastly imporved from the last release with more APIs and performance improvements. You can read more details about the changes in one of the posts I have blogged earlier here.

    In this post I am going to show you how to make use of the Docker container images for .NET Core to create and execute a C# program in Docker. Meaning I am not going to install the framework in my machine, rather host the runtime in a docker container and use it for compiling and running the program.

    So one of the pre-requisite for this procedure to work is to have Docker installed in your machine. I am going to use a Windows 10 machine for this example and I have the latest Docker for Windows Beta installed in it. Please read my earlier posts on how to install Docker for Windows Beta in your machine and to troubleshoot the issues which may come up during the installation.

    1. Installing Docker For Windows Beta
    2. Docker : Troubleshooting Installation Issues

    Downloading the Image and Running the Container

    The first step is to download the RC2 version of the image from the Docker Repository. You can use the following command in the powershell window for that. It will download the image and runs the container when the download is completed.

    docker run -it microsoft/dotnet:latest

    It will pull the latest version, that is RC2 in our case from the repository and once it completes the download you will get a bash shell prompt, from where you can execute the CLI commands. You can refer the Microsoft repoository in Docker to know about more options such as downloading a specific version etc.


  • .NET Core RC2 Released with Some Major Changes

    Early this week Microsoft has released the .NET Core RC2 which includes some significant changes to the core framework and is a major update from RC1 which was released in November. RC2 includes a new set of APIs and tools along with performance and reliablity improvements.

    RC2 contains updates to the following components

    .Net Core RC2

    ASP.NET Core RC2

    .NET Core RC2 SDK Preview 1

    You can read more about the RC2 release of .NET Core here.

    One of the major change is with the Dotnet Execution Environment(DNX), which is now termed as .NET Core SDK in RC2. DNX was released with RC1 which included a runtime and a toolset to build ASP.NET Core 1.0 applications. It consisted mainly of three parts.

    DNVM - install script for obtaining DNX

    DNX - DotNet Execution runtime for executing the code

    DNU - DotNet developer utility, for managing dependencies, building and deploying applications. 

    In RC2, all these three are now part of a single toolset called .NET CLI(Command Line Interface) and features provided by these tools are now available out of the box.

    DNVM & CLI

    DNVM or DotNet Version Manager was used to install DNX on your machine. It was used by users to download specific versions from the specified feed as well as to make a runtime active etc.

    .NET CLI doesn't have an equivalent command for this, instead it comes in two types of packaging

    1. Native installers for each platform
    2. Install Scripts

    With Native installers, CLI is distributed as installers such as DEB packages for Ubunutu, MSI bundles for Windows etc. These will install the CLI and setup the environment so that the users will be able to get started with CLI immediately after the install. One disadvantage of this approcah is that the user will require administrative privileges for installation.

    Install scripts doesn't need eleveted privileges, but the user will need to manually install the pre-requisites before installing the CLI.

    You can refer the here for more on the .NET CLI installation process.

    Command List

    In DNX, we were using dnx or dnu before the commands, but in CLI, we will have only one prefix called dotnet. So to run our program from the command line, we are going to use dotnet run instead of dnx run command. Given below is the list of common commands used in DNX and it's corresponding ones in CLI

    DNX CommandsCLI Commands
    dnx rundotnet runTo run the compiled file
    dnu builddotnet buildBuild the source code into IL
    dnu packdotnet packTo build your source as a NuGet Package
    dnu restoredotnet restoreTo restore the dependencies/packages defined in your project.json
    dnu publishdotnet publishPublishes your application for deployment

    Some of the commands omitted from CLI are

    1. dnx [command] , for eg dnx web
    2. dnu install
    3. dnu wrap
    4. dnu commands

    Development Workflow

    The simplest form of workflow for developing apps using .NET core is to create a new project, restore the dependencies and then build and run the app using the following commands

    dotnet new

    dotnet resore

    dotnet run

    Please read the post Announcing .NET Core RC2 and .NET Core SDK Preview 1 from .NET blog to know more about the changes and features in .NET Core RC2


  • Using HtmlAgility Pack to Extract Contents in a Web Page

    Recently I was working on a hobby project and in that I wanted to extract all the <image> tags from a web page. There are lot of solutions available for parsing the HTML page by using regex or by using various string manipulation methods. But I was looking for a neat solution and stumbled upon the HtmlAgility Pack. It's a .NET library that allows us to parse HTML files and outputs a sturcture similar to the DOM.

    It's been available for sometime now and is hosted at Codeplex and is available as a NuGet package. To install it in your solution, you can either use the NuGet package manager UI or the console. To install it from the console, run the following command

    Install-Package Htmlagilitypack

    Once the installation is completed, it will be added under the dependencies in project.json as well in References.

     


  • Json.NET - Converting Collections

    Json.NET supports serialization and deserialization of array, generic list, dictionaries and custom collections too.

    Serialization

    To serialize collection, you needs to call the SerializeObject method and pass the collection object to it as the parameter and Json.NET converts it to json string automatically without needing any other configuration.

    In the example given below, we have created a class User with two properties, Name and Age. And in the main method we are intializing a list of users and to serialize the list, we are passing it to the SerializeObject method in JsonConvert class.

    string jsonText = JsonConvert.SerializeObject(usrs, Formatting.Indented);

    Deserialization


  • Json.NET - Converting JSON to XML and Vice Versa

    Json.Net supports the conversion from XML to JSON and JSON and XML vice versa.

    JSON to XML Conversion.

    We are going to use 

    DeserializeXNode(string json, string nodeName)

    method defined in JsonConvert class to convert JSON to XML It will return an XNode object containing the XML. You will need to import System.Xml and System.Xml.Linq namespaces for this sample to work correctly


  • Json.NET - Using JsonSerializer Class

    In the previous post, I have detailed the serialization and deserialization functionalities using the Serialize and Deserialize methods in JsonConvert class. These methods are built on top of JsonSerializer class which is doing all the heavy lifiting during the conversion process under the hood. 

    In this I will show you how to use JsonSerializer class for doing the conversion. One advantage of using this class is that we have more control over the conversion process. It exposes different properties through which we can control how Json.Net will serialize/deserialize the json

    So let's add one more property EffectiveDate which is a DateTime field to our class from the previous post 

    In this example, I am using JsonSerializer class instead of JsonConvert class for doing the serialization. Unlike the latter one, using this allows me to write JSON directly to the stream using StringWriter and JsonTextWriter. Like the JsonConvert class, JsonSerializer also has a number of properties for customizing the serialization process and it allows the developer to have more control over it.  

    Also in this example, I have used a converter for serializing the date, JavaScriptDateTimeConverter. If I serialized it without usng the converter the output would be like the one given below

    {"ColorId":1,"ColorName":"Green","EffectiveDate":"2016-04-01T00:00:00"}

    The date format will be in ISO date format But if you want to have the JavaScript Date object in your json, you can use the JavaScriptDateTimeConverter for that.


  • Json.NET - Handling Errors

    Json.NET supports two type of error handling, using the Error event and using OnErrorAttribute

    The methods allows you to catch errors and allows it to handle it by you and continues the serialization process or it bubbles up the chain as an unhandled one

    The Error event is defined in the JsonSerializer and this event fires whenever there is an error during serialization of deserialization process. You can use the JsonSerializerSettings instance to set the Error event.

    In this example, I have created a delegate for the error event, which will add the error to a collection. Here, I have intentionally entered a string for the DateTime field so that an exception will occur during the conversion process. When the exception occurs, it's catched by our delegate, adds it to the collection and set the Handled property to true so that it's not bubbled up.

    You can see that eventhough the exception has occured, it doesn't stop the conversion process with the rest of the items.

    OnError Attribute

    You can use this attribute on the class like any other attribute so far in this series. To use this one, just decorate the method you want to handle the error with the attribute [OnError] as shown below

    [OnError]
    internal void OnError(StreamingContext context, ErrorContext errorContext)
        {
            errorContext.Handled = true;
        }
    


  • Json.NET - Logging And Debugging

    Logging feature can be implemented in Json.Net by making use of the ITraceWriter interface. MemoryTraceWriter and DiagnosticsTraceWriter are the two implementations of ITraceWrite available in Json.Net. The former implementation keeps the messages in memory and is not persisted in any storage medium and is useful for doing basic debugging. The later one writes messages to the tracelisteners that our application is using. Advantage of using TraceListeners is that the information is persisted and is available for reference even after the application is closed.

    In this example, I am going to implement the MemoryTraceWrite for logging information as well as error messages

    First I have created an instance of the ITraceWriter and set it to the TraceWriter property in JsonSerializerSettings instance. 

    Also you implement your own trace writers by creating new logger classes by inheriting the ITraceWriter interface. By doing this way, you will be able to integrate it with your own logging framework,


  • Json.NET - Conditional Serialization

    In the last post, I have showb you how to use DataMember and JsonIgnore attributes for skipping properties from getting outputed to json. But in some case we need to omit it based on conditions and these apporaches is not to going to help you

    In Json.NET we can do this by adding a method whose name will start with ShouldSerializeMethod and append the name of the property to it.

    In the following example I have a class with two properties, Username and Password and I didn't want the password to be sent across. So I created a method ShouldSerializePassword(ShouldSerialize + name of the property that needs to be omitted).

    So by manipulating the return value of the method, we can conditionally skip members from the resulting json.