How to implement logging Framework in Asp.net Core Blazor ?


Tracing logging is one of the critical part of any application to fix the issue or bugs quickly without spending more time to debug application.

There are so many logging framework for blazor, but i will show one of the most popular framework i.e log4Net. Currently i am using in one of my personal demo project.

These are the following steps to implement in Blazor application.

Step 1. Install this 2 packages in project from Nuget Package like this

Step 2. Go to the startup.cs file and inject this package like this

Step3: Create the log4net.xml in parent folder and write the code like this

 <log4net>
	<appender name="Console" type="log4net.Appender.ConsoleAppender">
		<layout type="log4net.Layout.PatternLayout">
			<!-- Pattern to output the caller's file name and line number -->
			<conversionPattern value="%5level [%thread] (%file:%line) - %message%newline" />
		</layout>
	</appender>

	<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
		<file value="logFiles\CarInspectionLog.log" />
		<appendToFile value="true" />
		<maximumFileSize value="100KB" />
		<maxSizeRollBackups value="2" />

		<layout type="log4net.Layout.PatternLayout">
			<conversionPattern value="%level %thread %logger - %message%newline" />
		</layout>
	</appender>

	<root>
		<level value="DEBUG" />
		<appender-ref ref="Console" />
		<appender-ref ref="RollingFile" />
	</root>
</log4net>

 

Step 4: Now use the Log method by using ILogger interface like this

Step 5: Run the application, to see the log message

Advertisement

Implementing Swagger in Asp.net Web API Core 3.1 in clean way


What is the Swagger ?

This is one of the best tool for testing web api method. It will also give very good user friendly definition of web api method.

Advantages:
1. We can easily test web api method
2. We will get user friendly documented message about web api method
3. We can easily debug the web api method using this tool.

How to implement in Asp.net Web API Core 3.1 in Clean way ?

Step 1: Firstly create the web api 3.1 project like this

Creating Web Api Core 3.0 layer using Dapper and .net standard 2.0

Step 2: Go to Web API layer and install the swagger related nuget package

Swagger
Swagger

Note: if you are using asp.net core 3.0 or 3.1 then install the swagger version v5.0

Step 3: Create SwaggerExtension.cs file in the Extensions folder of We API Layer and write the Extension Method for IServiceCollection and IApplicationBuilder like this

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;

namespace Dapper_Demo.Extensions
{
    public static class SwaggerExtension
    {
        public static void AddSwagger(this IServiceCollection services)
        {
            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "EmpManagement API", Version = "v1" });
            });
        }

        public static void AddCustomSwagger(this IApplicationBuilder app)
        {
            //Adding Swagger and SwaggerUI
            app.UseSwagger();

            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "EmpManagement ASP.NET Core API v1");
            });
        }
    }
}

Step 4: Go to the Startup file of application and add the swagger in middleware and service configure like this

Swagger_Middleware
Swagger_Middleware

Step 5: Run the application and type this URL

If you want to download the source code for this demo. You can download from below demo.

https://github.com/Chandradev819/Dapper_Demo_With_Asp.netCore

How to test Web API Method using PostMan tool? (Part 3)


In previous post,i.e. How to do CRUD operations in asp.net WEB API we have already written the CRUD operation methods using WEB API, but on browser we cannot test all methods, we have to take help of some external tool like fiddler or postman tool for testing all the methods.

what is the postman tool ?
Postman is a Google Chrome app for interacting with HTTP APIs. It presents you with a friendly GUI for constructing requests and reading responses.
Using Postman we can easily test the rest enable service like web api.

How to Install the postman tool ?

>> Search the postman in google then install it
OR
download from given the path https://chrome.google.com/webstore/category/extensions?hl=en

How to test the WEB API Get method using postman ?

Step 1: Lunch the postman tool

Step 2: Give the URL of get method as given below image then click on Send button. You will get the result as given below.
If get method execute successfully, you will get status 200 OK.

How to test the WEB API POST method using postman ?

Step 1: Lunch the postman tool

Step 2: Give the URL of POST method as given below image then click on Send button. You will get the result as given below.
If get method execute successfully, you will get status 201 Created.

How to test the WEB API PUT method using postman ?

Step 1: Lunch the postman tool

Step 2: Give the URL of PUT method as given below image then click on Send button. You will get the result as given below.

How to test the WEB API Delete method using postman ?

Step 1: Lunch the postman tool

Step 2: Give the URL of DELETE method as given below image then click on Send button. You will get the result as given below.
If DELETE method execute successfully then you will get status 200 OK.

How to decompile the .net dll code?


So many time we will get the scenario to read the code of .net dll for better understanding the framework. But by default there are no option to read the code in visual studio.

There are so many commercial tool are available for doing this task.But that all are not the free tool. Recently I found one of more stable open source tool to read the .net dll code i.e. ILSpy.

You can download this tool from this url http://ilspy.net/

Steps to use this dll

Step 1: Just download the binary file from the given above URL

Step 2: Extract the folder and click on ILSpy.exe

Step 3:

Now add your dll and click on class as given below image

Code Coverage Tool (Part 3)


This is the last part of code coverage tool, in this post we will see the open source code coverage tool,i.e. OpenCoverage which is light weight and totally free to use. Which will give almost all functionalities as similar to third party code coverage tool (Ncoder and DotCover)

NCover Code Coverage Tool
DotCover Coverage Tool

How to use OpenCover tool?

Step 1: Create some demo unit test case in visual studio. I have written some dummy unit test case as given below

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestCase_Sample
{
    [TestClass]
    public class UnitTestCaseDemo
    {
        [TestMethod]
        public void AdditionOfTwoNum()
        {
            var a = 0;
            var b = 0;
            if (a!=0 && b!=0)
            {
                var result = a + b;
                Assert.AreEqual(30, result);
            }
            else
            {
                var result = a + b;
                Assert.AreEqual(0, result);
            }
        }

        [TestMethod]
        public void SubstractionOfTwoNum()
        {
            var a = 20;
            var b = 10;
            var result = a - b;
            Assert.AreEqual(10, result);
        }

        [TestMethod]
        public void MultiplicationOfTwoNum()
        {
            var a = 20;
            var b = 10;
            var result = a * b;
            Assert.AreEqual(200, result);
        }

        [TestMethod]
        public void DivisionOfTwo_Num()
        {
            var a = 20;
            var b = 10;
            var result = a / b;
            Assert.AreEqual(2, result);
        }

        [TestMethod]
        public void Addition_Of_ThreeNum()
        {
            var a = 10;
            var b = 20;
            var c = 30;
            var result = a + b + c;
            Assert.AreEqual(60, result);
        }

        [TestMethod]
        [ExpectedException(typeof(DivideByZeroException))]
        public void Test()
        {
            int i = 10, j = 0;
            int x;
            x = i / j;
        }
       
    }
}

Step 2: Download the OpenCover UI from Microsoft store, from the given below URL

https://marketplace.visualstudio.com/items?itemName=jamdagni86.OpenCoverUI

In Visual Studio Tab will show like this

Step 3: Right click on solution explorer and click on Manage NuGet Packages and Install the OpenCover and ReportGenerator in your application as given below

Step 4: Go to Visual studio Tool ->> Options ->> OpenCoverUI Options then select the OpenCover.Console.exe from your application.

Step 5: Go to OpenCover tool of Visual Studio and Select OpenCover Test Explorer and select the test cases to be run like given below Image

Now we will get output like given below

In the above result it is showing that how much code has been covered in which test case.

If you have to fix the problem then just double click on given method, you will see the code like this given below image

This indicate that below code branch has not been executed. So we have to write the other unit test case to cover above code.

How to get the report as third party control as similar to Ncover and DotCover

For getting the report in user friendly manner we have to take help of Report Generator Tool.
For that we have to create the .bat file, which will generate the report in given folder.

Firstly create the notepad file keep this syntax as given below

"C:\Source\Test \packages\OpenCover.4.6.519\tools\OpenCover.Console.exe" -register:user -target:"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\mstest.exe" -targetargs:"/noisolation /testcontainer:\"C:\Source\Test \Test\bin\Debug\Test.dll\" /resultsfile:C:\Reports\MSTest\.trx" -mergebyhash -output:C:\Reports\MSTest\projectCoverageReport.xml


"C:\Source\Test \packages\ReportGenerator.2.5.2\tools\ReportGenerator.exe" -reports:"C:\Reports\MSTest\projectCoverageReport.xml" -targetdir:"C:\Reports\CodeCoverage"

Now save the file as .bat extension and run the bat file.

Note: Before running the bat file, please create the Reports\CodeCoverage and MSTest directory in C folder.

Now go to the CodeCoverage folder and see the report after clicking on Index.html file like as given below

In the above tools compare we show that OpenCover contains almost all the major features which contains all the paid version tools and it is very light weight and flexible to use in any project.

Comparison between all the Tools