Memory dumps of a developer

Articles and tutorials on .NET Core, ASP.NET MVC, Kendo UI, Windows 10, Windows Mobile, Orchard

  • Serving Static Files Using nginx in Docker

    nginx is an open source web server lighting up the hosting world with rapid growth and is catching up with the sector leader Apache very fast. It's very fast, light weight web server which can also act as a load balancer or a caching server. One of the main feature of nginx is it's capability to handle a large number of concurrent connections and is the main reason why the popular sites such as wordpress.com, Hulu etc is using it. In nginx, scaling is implemented using an asynchronous architecture instead of threads to handle simultaneous requests. This helps nginx to serve lot of requests concurrently without consuming lot of system resources.

    In this post, I am going to take you through the various steps needed to set up nginx in a Docker container to serve static files.

    Step 1 : Pulling Docker Image

    The image for ngnix for Docker is available in the Docker Hub and can use the below command to pull down the latest image into your local Docker client.

    docker pull nginx

    It will pull the latest image from the hub if it's not found in your local docker client and once the download is completed we can verify the same by executing the docker images command. I had downloaded the image some time back and you can see that in the below screenshot as the last item in the list. 


  • Installing .NET Core in Ubuntu 15.10 in Azure

    One of the benefits of being a Microsoft MVP is the credit you receive for using various services/resources like in Windows Azure which is now around 9.1K INR for each month. That credit is more than enough if you want to play with various options in Azure. So I went ahead and created a Linux VM in Azure using Ubuntu 15.10 distro, then subsequently installed Ubuntu Desktop, xrdp and xfce for connecting remotely into the VM using RDP from Windows machines. I am planning to write a post on the installation process and steps needed for configuring it and will share it as soon as it's available in the blog.

    Many of you people may be knowing that Microsoft has released .NET Core 1.0 to the public last month. It's the new .NET framework completly built from scratch, modular and truely open source. In this post, I am going to show you the steps needed for installing .NET Core SDK in a Linux machine. .NET Core SDK consists of .NET Core CLR runtime and CLI tools which are needed for developing the applications in .NET core.

    Step 1: Check Ubuntu version 

    Make sure that the installed version of Ubuntu is 15.10. The following steps were tried and tested in Ubuntu 15.10 and may not work in other versions. You can check the version from terminal by using the following command.

    lsb_release -a

    Step 2: Set up feed and update packages

    Add the feed for downloading .NET Core SDK to dotnetdev.list by executing the following command.

    sudo sh -c 'echo "deb [arch=amd64] https://apt-mo.trafficmanager.net/repos/dotnet-release/ trusty main" > /etc/apt/sources.list.d/dotnetdev.list'

    Add the following key to the list so that packages authenticated with this key will always be considered as a trusted one.

    sudo apt-key adv --keyserver apt-mo.trafficmanager.net --recv-keys 417A0893

    Execute the apt-get update command to fetch the latest version and dependencies

    sudo apt-get update


  • 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",	
    

  • Adding Google Verification File in Orchard CMS

    Whenever you want to serve a static file from your Orchard website, you will get a 404 error(page note found) error by default. This is happening for Orchard because in the web.config file the default configuration is set to return a page not found error for all the static files in the root. This will become an annoying issue whenever you try to verify the identity of the website by uploading a verification file in the root folder as I found out when I wanted to verify the identity of my site from Google Search Console.

    This is issue can be resolved in two ways,

    1. Configure a route in ASP.NET MVC to serve the static page.

    2. Modify the web.config file in the route to return the correct page instead of 404

    I will explain the steps needed to overcome this issue using the second approach. In this step, you needs to make couple of changes in the web.config file in the root directory of your Orchard site. The modifications is to be done in the sections <httpHandlers> and in <handlers> inside <system.webServer>. It is recommended to make these changes in both the places so that it works both on IIS6 and IIS7.

    By default the <httpHandlers> and <handlers> sections will have the following entries in it

    <httphandlers>
        <add path="*" verb="*" type="System.Web.StaticFileHandler"></add> 
    </httphandlers>

    <system.webServer>
    <handlers accessPolicy="Script">
    <add name="NotFound" path="*" verb="*" type="System.Web.HttpNotFoundHandler" preCondition="integratedMode" requireAccess="Script"/>
    </handlers>
    </system.webServer>

    I have omitted some entries from the config file in the following snippet as it's not relevant for the topic which is being discussed in this post. Basically these two entries are telling the web server to return a page not found error whenever we request for a static file. So we will add the following entries into the config file for ignoring this rule.

    <httphandlers>
    <add path="file.html" verb="*" type="System.Web.StaticFileHandler" />
    <add path="*" verb="*" type="System.Web.StaticFileHandler"/>
    </httphandlers>

    <system.webServer>
    <handlers accessPolicy="Script, Read">

    <add name="VerificationFile" path="file.html" verb="*" modules="StaticFileModule" preCondition="integratedMode"
    resourceType="file" requireAccess="Read" />

    <add name="NotFound" path="*" verb="*" type="System.Web.HttpNotFoundHandler" preCondition="integratedMode" requireAccess="Script"/>
    </handlers>
    </system.webServer>

    Please make a note of the following points to make our solution work

    1. If you add the entries before the existing ones which says to serve the 404, then our entries doesn't have any effect. So you should always over statement above the existing one.
    2. Give Read permission in accessPolicy for handlers in <system.webServer> section. 
    3. Make sure that the name provided is unique across the handler entries in the config file.


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