ASP.NET Core

  • Learn how to split log data into different tables using Serilog in ASP.NET Core

    For most of the application developers, file systems are the primary choice for storing the information generated by the logging providers. One of the main drawbacks of using the files is that it's very difficult for the search for information or to do an analysis of the information written to it over time. Third-party logging providers such as Serilog have facilities to persist the data in database tables instead of the file system. Even then, if you use a single table to write all you errors and other debug information, the size of the table will grow considerably over time which can affect the performance of the whole operation itself.

    So, in this post, I will explore the possibility of using multiple tables for storing the logging information using Serilog. If you are new to Serilog, please refer to my previous articles on the same here using the links given below.

    Code snippets in this post are based on .NET Core 5.0 Preview 5

    Step 1: Create a Web Application in .NET Core

    To get started we will create a new empty web application using the default template available in Visual Studio. Goto File -> New Project -> ASP.NET Core Web Application

    Give a name for the application, leave the rest of the fields with default values and click Create

    Multiple Log Files in Serilog

    In the next window, select Web Application as a project template. Before you click on the Create button, make sure that you have selected the desired version of .NET Core in the dropdown shown at the top. Here, for this one, I selected .NET 5.0

    Multiple Log Files in Serilog

    You can also do this from .NET CLI using the following command

    dotnet new web  --name SerilogMultipleTables
    

    When the command is executed it will scaffold a new application using the MVC structure and then restores the necessary packages needed for the default template.


  • Writing logs to different files using Serilog in ASP.NET Core Web Application

    Application log files play an important role in analyzing the bugs and for troubleshooting issues in an application. It’s worth noting that the log files are also used for writing information about events and other information that occurs when the application is running or serving requests in the case of a web application. Most application developers use a single file to log everything from errors, warnings, debug information, etc. There is no harm in following this approach, but the downside is that it will be harder for you to segregate information from the file easily. We can easily overcome this by maintaining multiple log files depending on the need. In this post, I am going to show how we can achieve this with Serilog

    Serilog is a popular third party diagnostic logging library for .NET applications, I have already written some post about it and it’s usage already. If you are new to Serilog, please refer to those posts using the links given below.

    Code snippets in this post are based on .NET Core 5.0 Preview 5

    Step 1 : Create a Web Application in .NET Core

    Create a new ASP.NET Core MVC application using the below command

    dotnet new mvc  --name MultiLogFileSample
    

    You can also do this from Visual Studio by going into File -> New Project -> ASP .NET Core Web Application

    When the command is executed it will scaffold a new application using the MVC structure and then restores the necessary packages needed for the default template.

    By default, it will create two json files named, appsettings.json and appsettings.development.json. These are the configuration files for the application and are chosen based on the environment where your application is running. These files will have a default configuration as shown below basically sets the default level for logging.

    {
      "Logging":{
        "LogLevel":{
          "Default":Information",
          "Microsoft":Warning",
          "Microsoft.Hosting.Lifetime":Information"
        }
      }
    }
    
    

    By default, it is set as Information, which writes a lot of data to the logs. This setting is very useful while we are developing the application, but we should set it higher severity levels when the application is deployed to higher environments. Since Serilog is not going to reference this section, we can safely remove this from the configuration files


  • Write your logs into database in an ASP.NET Core application using Serilog

    In most scenarios, we normally use a flat-files for writing your logs or exception messages. But what if you write that information into the table in a database instead of a file. To implement this functionality, we can make use of third-party providers such as Serilog to log information in a SQL server database. Even though it's not a recommended approach, one can easily search the logs by executing SQL queries against the table.

    Installing Packages

    Serilog provides the functionality to write logs to different sources such as files, trace logs, database and the providers for these are called Serilog Sinks. To write logs to a table in a SQL Server database, you will need to add the following NuGet packages

    Install-Package Serilog
    Install-Package Serilog.Settings.Configuration
    Install-Package Serilog.Sinks.MSSqlServer
    

    The first package contains the core runtime, the second package can read the key under the "Serilog" section from a valid IConfiguration source and the last one is responsible for making the connection to the database and writing information into the log table.

    Configuring Serilog 

    Modify the appsettings.json file to add a new section called "Serilog". We will set up the connection string to the database, provide the name of the table and instruct Serilog to create the table if not found in the DB

    "Serilog": {
        "MinimumLevel": "Error",
        "WriteTo": [
          {
            "Name": "MSSqlServer",
            "Args": {
              "connectionString": "Server=(localdb)\\MSSQLLocalDB;Database=Employee;Trusted_Connection=True;MultipleActiveResultSets=true",
              "tableName": "Logs",
              "autoCreateSqlTable": true
            }
          }
        ]
      },
    


  • Serializing enums as strings using System.Text.Json library in .NET Core 3.0

    .NET Core 3.0 uses the System.Text.Json API by default for JSON serialization operations. Prior versions of .NET Core relied on JSON.NET, a third party library developed by Newtonsoft and the framework team decided to create a brand new library that can make use of the latest features in the language and the framework.

    The new library has got support for all the new features that got introduced in the latest version of C#. And this was one of the main reasons behind the development of the new library because implementing these changes in JSON.NET meant a significant rewrite.

    While serializing an object into JSON using the new library we can control various options such as casing, indentation, etc, but one notable omission is the support for enums by default. If you try to serialize an enum in .NET Core 3.0 with the default library, it will convert it into an integer value instead of the name of the enum.
    For example, let consider the following model and see if what happens when we serialize it using the System.Text.Json library

    public enum AddressType
    {        
        HomeAddress,
        OfficeAddress,
        CommunicationAddress
        }
    
    public class Employee
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public AddressType CommunicationPreference { get; set; }
    }
    

    and when you serialize it using the serialize method

    List employees = new List{
        new Employee{
            FirstName = "Amal",
            LastName ="Dev",
            CommunicationPreference = AddressType.HomeAddress
        },
        new Employee{
            FirstName = "Dev",
            LastName ="D",
            CommunicationPreference = AddressType.CommunicationAddress
        },
        new Employee{
            FirstName = "Tris",
            LastName ="Tru",
            CommunicationPreference = AddressType.OfficeAddress
        }
    }
    
    JsonSerializer.Serialize(employees);
    

    it will produce an output like the one given below

    [ 
       { 
          "FirstName":"Amal",
          "LastName":"Dev",
          "CommunicationPreference":0
       },
       { 
          "FirstName":"Dev",
          "LastName":"D",
          "CommunicationPreference":2
       },
       { 
          "FirstName":"Tris",
          "LastName":"Tru",
          "CommunicationPreference":1
       }
    ]
    


  • Avoid conversion errors by using Custom Converters in System.Text.Json API(.NET Core 3.0)

    The post is based on .NET Core 3.0
    SDK used : 3.0.100

    One of the most common error encountered while doing JSON serialization and deserialization is the data type conversion errors. Till now, we were using the Json.NET library from Newtonsoft for performing the serialization and deserialization in .NET/ASP.NET/.NET Core, but in the latest iteration of .NET Core which is currently under preview, they have removed the dependency on Json.NET and introduced a new built-in library for doing the same. Along with that, the all new library that is going to be introduced with .NET Core 3.0 provides you to define custom converters that can be implemented to get rid of this kind of errors. If you are not aware of it, I have already written a couple of posts about it which you can refer to using the following links.

     Serializing and Deserializing Json in .NET Core 3.0 using System.Text.Json API

    Step-By-Step Guide to Serialize and Deserialize JSON Using System.Text.Json

    The new API is included with the System namespace and you don't need to add any NuGet package to get started with it. Along with the normally used methods for serializing/deserializing JSON, it also includes methods for supporting asynchronous programming. One of the known limitation in the v1 of the API is the limited support for the data types, given below is the list of currently supported types. For more detail, please refer this link Serializer API Document

    • Array 
    • Boolean
    • Byte
    • Char (as a JSON string of length 1)
    • DateTime 
    • DateTimeOffset 
    • Dictionary<string, TValue> (currently just primitives in Preview 5)
    • Double
    • Enum (as integer for now)
    • Int16
    • Int32
    • Int64
    • IEnumerable 
    • IList 
    • Object (polymorhic mode for serialization only)
    • Nullable < T >
    • SByte
    • Single
    • String
    • UInt16
    • UInt32
    • UInt64


  • Step-By-Step Guide to Serialize and Deserialize JSON Using System.Text.Json

    The post is based on .NET Core 3.0 version.

    Update : In preview 7 few changes were made to the API. For serialization use Serialize method instead of ToString and Deserialize method instead of Parse. Post updated to reflect these changes. SDK version : 3.0.100-preview7-012821

    In the last post, I have already given an overview of the System.Text.Json API that is going to be introduced with the release with .NET Core 3.0. This API will replace the Json.NET library by Newtonsoft which is baked into the framework for doing serialization and deserialization of JSON. You can read more about it using this link.

    Step 1: Refer the namespaces

    Add the following lines in your code. If you are working .NET Core 3 project, then there is no need to add any NuGet packages to your project. For .NET Standard and .NET Framework project, install the System.Text.Json NuGet package. Make sure that Preview is enabled and select install version 4.6.0-preview6.19303.8 or higher

    using System.Text.Json;
    using System.Text.Json.Serialization;

    Step 2: Serializing an object into JSON string

    Serialization is the process of converting an object into a format that can be saved. JSON is one of the most preferred format for encoding object into strings. You will be able to do this conversion by calling the ToString method in the JsonSerializer class available in the System.Text.Json API

    For example, to convert a Dictionary object to a JSON string we can use the following statement

    JsonSerializer.ToString<Dictionary<string,object>>(dictObj)


  • Serializing and Deserializing Json in .NET Core 3.0 using System.Text.Json API

    The post is based on .NET Core 3.0 version

    Last October, the .NET Core team at Microsoft has announced that they are stripping out Json.Net, a popular library used by developers for serializing and deserializing the JSON from the upcoming version of the framework. Along with that, they also announced that they are working on a new namespace System.Text.Json in the framework for doing the same. With the release of the latest preview version of .NET Core 3.0, developers will now be able to make use of this namespace for performing JSON operations.

    The new namespace comes as part of the framework and there is no need to install any NuGet packages for using it. It has got the support for a reader, writer, document object model and a serializer.

    Why a new library now?

    JSON is one of the most widely used formats for data transfer especially from the client-side, be it web, mobile or IoT to the server backends. Most of the developers using the .NET Framework were relying on popular libraries like Json.NET because of the lack of the out of the box support provided by Microsoft.

    One of the major reasons to develop a new library was to increase the performance of the APIs. To integrate the support for Span<T> and UTF-8 processing into the Json.NET library was nearly impossible because it would either break the existing functionality or the performance would have taken a hit

    Even though Json.NET is getting updated very frequently for patches and new features, the tight integration with the ASP.NET Core framework meant these features got into the framework only when an update to the framework is released. So the .NET team has decided to strip the library from the framework and the developers will now be able to add it as a dependency in .NET core 3.0 meaning they will be free to choose whichever version of the Json.NET library they want

    Now the developers has got two options for performing the Json operations, either use System.Text.Json namespace or use Json.NET library which can be added as a NuGet package and using AddNewtonsoftJson extension method.

    Referring the library in your projects

    .NET Core
    To use it in a .NET Core project, you will need to install the latest preview version of .NET Core.

    .NET Standard, .NET Framework
    Install the System.Text.Json package from NuGet, make sure that you select Includes Preview and install version 4.6.0-preview6.19303.8 or higher

    As of now, the support for OpenAPI / Swagger is still under development and most probably won't make be available in time for .NET Core 3.0 release.

    Reference : Try the new System.Text.Json APIs

    Part 2 : Step-By-Step Guide to Serialize and Deserialize JSON Using System.Text.Json


  • Breaking Changes coming your way for ASP.NET Core 3.0

    Microsoft is in the process of releasing a new version for their .NET Core framework and there are some significant changes coming your way in that release. The most important ones are

    1. Removal of some sub-components
    2. Removal of the PackageReference to Microsoft.AspNetCore.App
    3. Reducing duplication between NuGet packages and shared frameworks

    In v3.0, the ASP.NET Core framework will contain only those assemblies which are fully developed, supported and serviceable by Microsoft. They are doing this to reap all the benefits provided by the .NET Core shared frameworks like smaller deployment size, faster bootup time, centralized patching etc

    Removal of some sub-components

    In this version, they are removing some sub-components from the ASP.NET Core shared framework and most notable among them are the following

    Json.NET 

    JSON format has become so popular these days and has become the primary method for transferring data in all modern applications. But .NET doesn't have a built-in library to deal with JSON and relied on third-party libraries like JSON.NET for some time now. In ASP.NET Core, it has a tight integration with Json.NET which restricted the users to chose another library or a different version of Json.NET itself. 

    So with version 3.0 they have decoupled Json.NET from the ASP.NET Core shared framework and is planning to replace it with high-performance JSON APIs. That means you will now need to add Json.NET as a separate package in you ASP.NET Core 3.0 project

    and then update your ConfigureServices method to include a call to AddNewtonsoftJson() as shown below

    public void ConfigureServices(IServiceCollection services)
    {
               services.AddMvc()
                   .AddNewtonsoftJson();
    }
    


  • Spin up Docker Containers in a Kubernetes Cluster hosted in Azure Container Service

    In one of the earlier posts, I have explained in details about the steps that need to be performed for running Docker containers in a Kubernetes cluster hosted in Azure. In that example, I used the default IIS image from Docker Hub for spinning up a new container in the cluster. In this post, I will show you how to containerize an ASP.NET Core MVC application using a private Docker registry and spin-off containers in a cluster hosted in Azure using Azure Container Service

    Pre-Requisites

    1. Azure Subscription
    2. Azure CLI
    3. kubectl 

    You need to install both the CLI tools for Azure and Kubernetes in your local machine for these commands to work and needs an Azure subscription for deploying the cluster in Azure Container Service.

    Step 1: Create a Kubernetes Cluster using Azure Container Service

    The first step is to create the create the cluster in Azure, for that we will use the az acs create command available in Azure CLI. You need to provide a resource group and a name for the cluster. A resource group in Azure is like a virtual container that holds a collection of assets for easy monitoring, access control etc. The --generate-ssh-keys parameter will tell the command to create the public and private key files which can be used for connecting to the cluster.

    az acs create --orchestrator-type kubernetes --resource-group TrainingInstanceRG1 --name TrainingCluster1 --generate-ssh-keys

    Step 2: Get the credentials for the Kubernetes Cluster

    Now we need to download the credentials to our local machine for accessing the cluster. 

    az acs kubernetes get-credentials --name TrainingCluster1 --resource-group TrainingInstanceRG1

    When the command is executed it will download the key files to your local machine and by default, it will reside in a folder under user folder. 


  • Implementing Functional Testing in MVC Application using ASP.NET Core 2.1.0-preview1

    Functional Testing plays an important role in delivering software products with great quality and reliability. Even though the ability to write in-memory functional tests in ASP. NET Core MVC application is present in ASP.NET Core 2.0, it had some pitfalls

    1. Manual copying of the .deps files from application project into the bin folder of the test project
    2. Needed to manually set the content root of the application project so that static files and views can be found
    3. Bootstrapping  the app on the Test Server.

    In ASP.NET Core 2.1, Microsoft has released a new package Microsoft.AspNetCore.Mvc.Testing which solves all the above mentioned problems and helps you to write and execute in-memory functional tests more efficiently. To check how it can be done, let's create two projects - one for the web application and another for our test project.

    Step 1

    Create an ASP.NET Core MVC project without any authentication. The following command will create one in the folder specified by the -o switch

    dotnet new mvc -au none -o SampleWeb/src/WebApp

    Step 2

    Let's add a test project based on Xunit test framework using the below command. As in Step 1, the project will be created in the specified folder

    dotnet new xunit -o SampleWeb/test/WebApp.Tests

    Step 3

    Now we will create a solution file and add these two projects into it. 

    cd SampleWeb

    dotnet new sln

    dotnet sln add src/WebApp/WebApp.csproj

    dotnet sln add .\test\WebApp.Tests\WebApp.Tests.csproj


  • Hosting a ASP.NET Core application in a Docker container using microsoft/aspnetcore image

    You all will be familiar with Docker by now given its popularity among developers and infra people and some of you may have already created containers using Docker images. One of the most widely used workflows among people using .NET Core will create a new web application by using the dotnet new command as shown below.

    The below example uses ASP.NET Core 2.0 framework, in which the dotnet new command will create the project as well as restores the dependencies specified in the csproj file by default. I have already written a post about it and you can refer it for information about it

    Then you will do a build to see if there are any errors and use dotnet run command which will self-host the web application


  • What's changed with new command in .NET Core 2.0

    Microsoft has released a major revision to the .NET Core framework around mid of August bumping the version to 2.0. This release includes not only the upgrade to the core framework but also include ASP.NET Core 2.0 and Entity Framework 2.0. Also along with this .NET Standard 2.0 is also released and it's now supporting around 32K + APIs and is a huge leap from what we had until now. You can read more about it by going to the announcement here.

    One of the changes among these is that the dotnet restore is now an implicit command which means that there is no need to execute the restore command explicitly for commands which needed to do a restore before executing it. 

    For example in .NET Core 1.1 whenever we executed a dotnet new command for creating a project we needed to execute the restore command before doing a build or execution. With .NET Core 2.0 when we execute the new command, the restore is now run automatically as part of the tooling. The following are the list of the commands which have got implicit support for restoration.

    new
    run
    build
    publish
    pack
    test

  • Override Default port and Host Name Used By ASP.NET Core Toolset

    .NET Core is the brand new modular framework from Microsoft for creating a wide variety of applications targeting Windows, Web, Cloud, IoT devices etc. Along with that they have introduced a cross platform toolchain for the command line which will help you to create and execute .NET core apps from the command line. 

    So for creating a normal web app in the .NET Core we will execute the following command.

    > dotnet run -t Web

    Then you will restore the packages by executing the command given below

    > dotnet restore

    After that you will execute the run command to build and host the application locally

    > dotnet run

    When this command is executed, it will first compile the application and upon successful build it will then host it using the built-in web server named Kestrel. Kestrel will use the port number 5000 by default for listening the requests for your app.

    From the screenshot you can see that the app is using port #5000 and is binded to localhost. This will be perfectly ok in a Dev enviroment since the developer will creating the application and is hosting it in the same machine. But this won't work in a production environment, where the requests to our app will be coming to the server from different machines out in the wild. That means, if you try to access the site using the ip address of the machine instead of localhost you will get a 404 error.


  • Compile a ASP.NET Core Web App on the fly using dotnet watch command

    One of the mostly used feature in Visual Studio while developing ASP.NET web applications is the ablity to make changes on the fly in the source code and able to see the changes in the browser without doing a compilation process manually. Actually Visual Studio tracks the changes made in the code and when you save the modifications, VS will automatically compile the changes in the background and restrats the session.

    In the .NET Core world, most of the development is happening with code editors such as Notepad, Visual Studio Code etc. These are vanilla text editors and lacks most of the features found in Visual Studio. So .NET Core team has created a command line tool called dotnet watch to achieve this ability for .NET Core. It's basically a file watcher which restarts the specified application whenever there is change is made in the source code. You can read more about it in the documentation hosted in GitHub.

    To add this functionlity in your code, you need to add the reference in the tools section in the project.json file as shown below.

    "tools": {
        "Microsoft.DotNet.Watcher.Tools": "1.0.0-preview2-final"  
      }

    After adding the entry in the tools, you needs to restore the package using the dotnet restore command to get all the required files for the watch tool.

    Syntax

    dotnet watch <dotnet arguments>

    The watch tool can be used to compile, run application or test and publish whenever there is a change in the source code. So the <dotnet arugments> can be compile, run, publish etc. For the run command the usage is as shown below

    Usage

    dotnet watch run

    Now, if you make any changes in server side code, the application will be automatically compiled and the reflected changes can be seen by just refreshing the browser.  In the following animation, if you look closely in the Terminal Window you can see that the application is stopped and compiled automatically when the source code is saved after making the changes.

    So using this tool, whenever we need to make change in the source code there is no need to stop the running instance and executing the dotnet run command again. Similary it can be used along with any other dotnet command as discussed in the post here in the documentation.


  • Deploying an Optimized Image of your ASP.NET Core MVC Web App in Docker

    In one of the posts I authored in the blog, I have shown you how to deploy an ASP.NET Core Web application in a Docker container, but the approach in the post has got a significant disadvantage. In that approach we always copied the entire contents of the directory which included all the static files, source code files etc, then restores all the packages inside the container and builds the application before it’s hosted in the container. This increases the boot up time of the container as well as the file size of the container.

    In this post, I will show you how to publish a web application into the container rather than copying all the files into container and then build the application inside that. I am going to create an .NET Core MVC web application using the dotnet new command, you can read more about that my post here.

    Step 1 : Create Project

    dotnet new –t web

    Step 2 : Restore Packages

    dotnet restore //restores all the packages referenced in the project.json files

    Step 3 : Publish Project

    dotnet publish –c Release –o publish

    Publishes the output of the project to the publish folder using the Release configuration. Before running the command make sure that node, bower and gulp is installed in your machine otherwise the publish command will fail

    If you look inside the publish folder you will find that it has copied all our static files and resources along with the dlls of our application and the dependencies used in it


  • Scaffolding an ASP.NET Core MVC application using dotnet command

    We all know that the dotnet new command will create a new console project containing a two files Program.cs and project.json out of the box for you

    dotnet new

    dotnet new console app

    Output

    dotnet new console app directory

    It was of great help in getting started with a console application in .NET Core, but this command was missing a more important feature – the ability to create a ASP.NET Core Web project from the command line. So, we developers relied on scaffolding tools such as yeoman to generate Web/MVC/Web API projects targeting .NET Core. So whenever the .NET team made changes to the framework and tools, we faced some incompatibilities. Either we needed to wait till the template is upgraded to support the new changes or needed to manually update the files after the project is created.

    This is now a thing of the past with the latest update to the .NET Core project implementing to facility to scaffold an MVC project targeting the Core  framework.

    Syntax

    dotnet new –t web

    Output

    dotnet new mvc project

    dotnet new mvc project directory

    The process of building and running the web project remains the same by using the following statements

    dotnet restore //restores the referenced packages
    dotnet run //compiles the project if it’s not and then hosts the application in the default port 5000

    dotnet restore mvc core app

    dotnet run web app

    web app in browser


  • Consuming Rest API methods in .NET Core MVC application

    Up until we need to rely on third party libraries for consuming a Web API in .NET Core applications. Even though Microsoft has got the Microsoft.AspNet.WebApi.Client library that can be used for consuming API methods, the support for .NET Core was not there until now. This library had a dependency on Microsoft.Net.Http library which was not supported in .NET Core. So with the release of the 5.2.3 version of Microsoft.AspNet.WebApi.Client they have fixed this issue and now it's available for you to use in .NET Core web applications too.

    Step 1 : Add reference in project.json

    You need to add following entries under dependencies section in the project.json file as given below.

    The Microsoft.AspNet.WebApi.Client is dependent on System.Net.Http and System.Runtime.Serialization.Xml libraries and that's why we need to add the above ones in the json file

    Step 2 : Use HttpClient to consume API

    We will use an object of the HttpClient class in the System.Net.Http namespace which was rebuilt for supporting .NET Core in latest version to invoke a connection to the service and for consuming the method. Then we will the base address and request headers using the BaseAddress and DefaultRequestHeaders methods respectively. To consume the web method, we will use the GetAysnc method which returns a resposne stream object containing the response from the Web API and by using the ReadAsAsync to read the result from the stream

    For other operations such as Post, Put and Delete we can use PostAsAsync, PutAsJsonAsync, DeleteAsync

    For more please refer here: http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client


  • Using Nginx as a Reverse Proxy for ASP.NET Core Web App in Docker

    One of the main features of .NET Core framework is the ability to run the applications on variety of environments such as Linux, MacOS etc. It includes a light weight server known as Kestrel which is used to run web apps targeting the .NET Core framework. But one of the main disadvantage of Kestrel is that it is primarily a development server and is not recommended for production environments. We always used IIS as server for hosting .NET Web app, but in the case of .NET Core since it's cross platform and we can't rely on IIS for platforms other than Windows. In the case of Linux, Nginx is one of the most popular web server out there and is very good at serving static content. But, for the example in this post we are going to make use of the reverse proxy(passing requests to other servers) feature in Nginx to serve our core web app from a docker container running on a Linux distro.

    I had already written a post about the on how to get started with Nginx and I recommend you to go through the post here if you are working with Nginx for the first time. In this post, I am going to host a .NET Core web app in a Docker container using Nginx and Kestrel to serve the site on a Linux machine.

    Before I get started with coding, here's a little advice for all you guys. It is always a recommended thing to follow a proper structure for your source files in your project. In this case, I have created two folders, one for putting all the files related to .NET and one for putting all those related to Nginx as shown in the screenshot below.

    Step 1 : Create .NET Core App

    Create a sample mvc core application under the dotnet folder. I created this one using the boiler plate template provided by yeoman which generated all the folders and files showed in the above image. If you run the application now using the dotnet run command, it will host the application in Kestrel and can be accessed by using the url http://localhost:5000. I have modified the sample page to show the name of the server using the below code.

    Served By : @System.Environment.MachineName 

    Since I'm running it from the local machine, the page will show the name of my local box as the server name as shown in the image below.

    Since we are going to host our application inside the Docker container, let's create a docker file which contains some instructions to Docker to set up the container. It basically tells which base image should be used, copies the files from the current folder to a folder called app inside the container and sets it's as the working directory. Then it executes two dotnet commands to restore the packages first and then executes the build. Once the build is completed it exposes the port #8018 for serving the app from the container. The ENTRYPOINT command is used execute the application when we start the container and in our case it will execute the run command to host the application.


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


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