Quote for the Week

"Learn to enjoy every moment of your life"

Saturday, December 11, 2021

What’s New in .NET 6.0?

 Microsoft was released .NET 6.0 on November 8, 2021. Visual studio 2022 version 17.0 required for develop .Net 6.0 console application. Visual Studio 2022 support .NET 6.0.


.NET 6.0 is a long-term support release; it will be supported for three years. Microsoft recommends developers start to migrate their applications to this new version, the upgrade process is fairly simple from both .NET Core 3.1 and .NET 5.


In addition to this unification, the .NET 6 ecosystem offers:

  • Simplified development: Getting started is easy. New language features in C# 10 reduce the amount of code you need to write. And investments in the web stack and minimal APIs make it easy to quickly write smaller, faster microservices.
  • Better performance: .NET 6 is the fastest full stack web framework, which lowers compute costs if you're running in the cloud.
  • Ultimate productivity: .NET 6 and Visual Studio 2022 provide hot reload, new git tooling, intelligent code editing, robust diagnostics and testing tools, and better team collaboration.

Feature #1: Console template


Traditionally, a console application would have a namespace, class name and a Main method. The Main method would execute when the console application is started.

With an ASP.NET Core application, the Main method is where web application instance would be built, configured and ran.

// Program.cs
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
 
namespace RoundTheCode.DotNet6
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }
 
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

However, with .NET 6, you can do away with the console application's namespace, class name and Main method. As a result, the file just has the contents on the Main method included.

// Program.cs
using RoundTheCode.DotNet6;
 
Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder.UseStartup<Startup>();
    }).Build().Run()

Feature #2: Merger of Program and the Startup class 


In ASP.NET Core 5, there would be two classes to configure the application.

We looked at the Program class above which builds and runs the application. In addition, there is a Startup class, which is where we make our configuration changes, such as adding a database connection, or using dependency injection. Those two classes have now been merged into the Program.cs file.

And, with the elimination of namespace, class and Main method, it means we simply have one Program.cs file that creates the WebApplicationBuilder instance, and configures the settings for the application.


// Program.cs
using RoundTheCode.DotNet6;
 
var builder = WebApplication.CreateBuilder(args);
 
builder.Services.AddControllers();
 
builder.Services.AddSingleton<ITeamService, TeamService>();
 
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new() { Title = "RoundTheCode.DotNet6", Version = "v1" });
});
 
var app = builder.Build();
 
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseSwagger();
    app.UseSwaggerUI(c => {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "RoundTheCode.DotNet6 v1");
        c.RoutePrefix = string.Empty;
    });
}
else
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
app.UseHttpsRedirection();
 
app.UseRouting();
 
app.UseAuthorization();
 
app.MapControllers();
 
app.Run();


Feature #3: Minimal APIs


ASP.NET Core 6 introduces Minimal APIs.

With ASP.NET Core 5, it was possible to use the mapping methods inside the UseEndpoints method. However, the only parameter that was able to be passed through that was the HttpContext instance.

As a result, the MVC route would have been a better solution as dependencies can be passed in as parameters.

But with ASP.NET Core 6, there are new mapping methods as part of the WebApplication instance. And, they allow you to pass in dependencies as methods.

For example, a WebApplication instance is created when the application calls builder.Build().


var app = builder.Build();

Within the WebApplication instance, there are methods that represent each of the CRUD verbs.

MapGet
MapPost
MapPut
MapDelete

With that, we can go ahead and set up a new API endpoint by passing in the route, any parameters that we need, and then returning a response.


app.MapGet("team/{id}", (ITeamService teamService, int id) => teamService.Read(id));

If we were to run our API at this point, it would run fine. However, if we have Swagger configured for our Web API, it will not appear in the Swagger documentation.

We need to call the AddEndpointsApiExplorer endpoint when building up our web application for it to appear in Swagger.

// Program.cs
var builder = WebApplication.CreateBuilder(args);
 
// Add services to the container.
 
builder.Services.AddControllers();
 
builder.Services.AddEndpointsApiExplorer(); // Need to add this in for it to appear in Swagger.
 
builder.Services.AddSingleton<ITeamService, TeamService>();
 
...
 
var app = builder.Build();

// Configure the HTTP request pipeline.
if (builder.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "RoundTheCode.DotNet6 v1"));
}
 
app.MapGet("team/{id}", (ITeamService teamService, int id) => teamService.Read(id));
...
 
app.Run();

By running our application now, our endpoint will now appear in our Swagger documentation.

Feature #4: DateOnly and TimeOnly structs

A feature that is long overdue in .NET 6 is the ability to set an object that is just a date, or just a time.

Traditionally, the DateTime struct would need to be used. That would mean that the time would exist, even if we were just using the date. And vice-versa with the time.

With the DateOnly struct, we can add a new instance by specifying the year, month and day. And it has similar methods to the DateTime struct.

Here is an example of how to add seven days to a DateOnly struct.

var dayNow = new DateOnly(2021, 08, 30);
var dayWeekTime = dayNow.AddDays(7);
 
return dayWeekTime.ToShortDateString();

It's a similar story with TimeOnly struct. Creating a new TimeOnly struct allows for us to pass in parameters, such as hours, minutes and seconds.

From there, we can do things, like adding a certain number of hours. If the number of hours goes beyond 24, it will revert back to 0.

Here is an example of adding 8 hours to 18:00 in a TimeOnly struct. The output would be 02:00.

var timeNow = new TimeOnly(18, 0, 0);
var timeNowEightHours = timeNow.AddHours(8);
 
return timeNowEightHours.ToString();

Conclusion

In this article, we explained the basics of .NET 6.0 and what’s new features in .NET 6.0.

Friday, November 13, 2020

What's new in .NET 5 ?

 Microsoft announced the new .NET 5 (future of .NET) at the Build 2019 conference. .NET 5 will be the single unified platform for building applications that runs on all platforms(Windows, Linux) and devices (IoT, Mobile).


Microsoft named this new release .NET 5.0 instead of .NET Core 4.0 for two reasons:

 -  Skipped version numbers 4.x to avoid confusion with .NET Framework 4.x.

 -  Dropped "Core" from the name to emphasize that this is the main implementation of .NET going forward. .NET 5.0 supports more types of apps and more platforms than .NET Core or .NET Framework.

ASP.NET Core 5.0 is based on .NET 5.0 but retains the name "Core" to avoid confusing it with ASP.NET MVC 5. Likewise, Entity Framework Core 5.0 retains the name "Core" to avoid confusing it with Entity Framework 5 and 6.


C# updates

Developers writing .NET 5 apps will have access to the latest C# version and features. .NET 5 is paired with C# 9, which brings many new features to the language. Here are a few highlights:

 - Records: Immutable reference types that behave like value types, and introduce the new with keyword into the language.


 - Relational pattern matching: Extends pattern matching capabilities to relational operators for comparative evaluations and expressions, including logical patterns - new keywords and, or, and not.


 - Top-level statements: As a means for accelerating adoption and learning of C#, the Main method can be omitted and application as simple as the following is valid:

                    System.Console.Write("Hello world!");

 - Function pointers: Language constructs that expose the following intermediate language (IL) opcodes: ldftn and calli.


ASP.NET Web Forms

ASP.NET Web Forms will not be coming to .NET 5 and Microsoft is currently recommending a move to Blazor which was an experimental project that's recently been promoted to official. The other alternatives are Angular, React, and Vue SPA frameworks if you are good at JavaScript.


If you are currently using ASP.NET MVC as a full stack web app, you can continue to use the same stack by using ASP.NET Core MVC or the new Razor Pages introduced in .NET Core 2.0, which may look similar to ASP.NET web forms for quickly building web form applications without views and controllers. However, if you are developing modern web applications for enterprises, its better to consider single page applications such as Blazor, Angular, or React instead of a traditional web app for providing rich client-side functionality.


WCF (Windows Communication Foundation)

The announcement that WCF is going to miss the .NET 5 train surprised many, including me. There has been a lot of discussion on GitHub of bringing back WCF into .NET Core, but Microsoft decided not to do so because their initial estimation for porting WCF into .NET Core was three years. (Source: DotNetRocks Podcast)


Microsoft is recommending the use of gRPC as an alternative which is a modern, open-source, high-performance RPC framework that can run in any environment. However, unlike WCF, gRPC cannot be hosted in IIS as of today, because of HTTP/2 implementation of Http.Sys does not support HTTP response trailing headers which gRPC relies on.


What’s Been Replaced

 EF Core - Entity Framework Core is replacing EF 6 in the .NET Core Framework.

ASP.NET Core - ASP.NET is replaced by ASP.NET Core. Check the migration guide for porting ASP.NET applications into ASP.NET Core.

ASP.NET Core MVC - ASP.NET Core MVC unified ASP.NET MVC and Web API. Check the migration guide for porting asp.net mvc app into ASP.NET MVC.

MSIX - Microsoft's new packaging tool which replaces the old MSI package installer for desktop applications.

JsonDocument - The new Json Document library from the System.Text.Json.JsonDocument API will replace json.net. It is 2-3 times faster than the old json.net.


Summary

At the end of this article, you have a high-level idea of how .NET 5 will impact your existing .NET projects and which opportunities the new platform is going to offer you. Maybe these highlighted five things may seem like little stuff, but they should allow you to find your way around this turning point in the .NET evolution.

Tuesday, October 30, 2018

What's New in .Net Core?

Microsoft .NET Core Version 2.1, a cross-platform implementation of the company’s .Net development platform, has been released, featuring improvements to build time performance and tools deployment. Version 2.0 will reach end-of-life status on September 1, 2018, and patches will no longer be provided for it.

And Microsoft expects to ship .Net Core 3 in 2019, with the first beta expected later in 2018.

Features of .NET Core


Yes, as it is the new generation .NET framework, it contains all features of .NET framework + its own new features, let’s go through them

  • Cross platform support : .NET Core is supporting development of apps that can be deployed beyond windows platform, we can deploy our apps on Linux or on MacOS.
  • Containers and Dockers support : Containers and dockers are very famous in these days, they can be easily adaptable by cloud technologies, Don’t worry .NET Core has full support of these components.
  • Performance Improvement.
  • MVC and web API merged : Before .NET Core, Developer needs to use MVC and Web API separately to create REST services using JSON, but .NET Core does job more simpler and merged them in a single module.
  • Seamless support to Microservices.
  • Command line development possible on Windows, MacOS, Linux.
  • It support adjacent .NET versions per applications.
Now let’s discuss the road ahead for .NET Core 2.1:-

Build-Time Performance: For the developers into .NET Application Development this will be bring good news as build-time performance has been improved in .NET Core 2.1 especially for incremental build. These improvements valid for both .NET build on the command line and to builds in Visual Studio. Microsoft has also made improvements in the CLI tools and in the MSBuild in order to make the tools deliver much faster experience to the developers.

.NET Core Global Tools: In .NET Core 2.1, it will include a new deployment and extensibility mechanism for tools. This new experience is similar to Node global tools. Microsoft has used the same syntax and experience. .NET Core tools are .NET Core console apps which are packaged and acquired as NuGet packages. These tools are framework dependent application by default and include all of the NuGet dependencies. This implies that a given global tool will run on any OS or chip architecture by default. Microsoft expects a whole new ecosystem of tools to establish itself for .NET. Some of these tools will be specific to .NET Core development and many of them will be general in nature.

HttpClient Performance: Outgoing network requests are important part of application performance for microservices and other types of application. .NET Core 2.1 has a new HttpClient handler which is rewritten for high performance. Microsoft is also including a IHtt[ClientFactory fearture that provides circuit breaker and other services for HttpClient calls. This new feature has been built on top of the new HttpClient handler.

Windows Compatibility Pack: When you port existing code from the .NET framework to .NET Core, you can use the new Windows compatibility pack. It provides access to an additional 20,000 APIs more than what is available in .NET Core. This includes System.Drawing, EventLog, Performance Counters, Windows Services an EventLog.

Summary

We have discussed some of the new features which are being added into .Net Core 2.1 by Microsoft. Till now the feedback and experience of the developers has been great. These improvements will make the .NET Core development even more easier and make the applications run more faster while using less memory.

Tuesday, May 15, 2018

ORM(Object Relational Mapping) in .NET

An Object Relation Mapping(ORM) library helps developers to create data access applications by programming against a conceptual model instead of programming against a relational database model.  ORMs bring lot of advantages and few of the prominent ones are -  RDBMS independent data access layer development, rapid application development, huge reduction in code, auto generation of boilerplate methods for CRUD operations and abstract access to data.

I have collected some of ORMs which can used for developing .Net Applications -


LLBLGen Pro Runtime Framework



The LLBLGen Pro Runtime Framework is an optional ORM that works in conjunction with the LLBLGen entity modeling tool. We say it’s optional because LLBLGen can also work with other ORMs such as Entity Framework.


Like Entity Framework, the LLBLGen Pro Runtime Framework is full OOP style ORM. But it differs in several ways, the first being an emphasis on performance. Though EF Core is significantly faster than classic Entity Framework, both are still considerably slower than other ORMs. Frans Bouma, author of LLBLGen Pro, hosts a performance shootout comparing materialization speed of various .NET data access / ORM implementations.


The LLBLGen Pro Runtime Framework also differs from EF/EF Core in that it is not context-bound. Each entity tracks its own changes, allowing you to manipulate an object graph in memory without holding a context open. (Which will make your DBA happy because not holding an open context also means you aren’t holding an open connection, which would otherwise interfere with database connection pooling.)



Like most ORMs for .NET Core, there are some limitations with the Core version of LLBLGen Pro Runtime Framework. However, this is mostly limited to missing features in .NET Core itself such as TransactionScope not being supported by SqlClient or fewer objects being binary serializable.

Microsoft Entity Framework



Entity Framework is one of the most advanced and feature rich ORM library from Microsoft.  Using the Entity Framework, developers can write data access code using the popular LINQ queries to retrieve and manipulate data as strongly typed objects. The Entity Framework’s ORM supports change tracking, identity resolution, lazy loading and query translation so that developers can focus on building their application specific business logic rather than wring thousands of lines of code for fundamental data access.

The Entity Framework is built on top of  ADO.NET provider model and it integrates very well with Visual Studio. It supports Domain model and Code First model and have providers for various databases like Sql Server, SQL Azure, Oracle, MySql and DB2.

NHibernate



NHibernate is the .NET sibling of popular Java ORM framework Hibernate. If you are looking for an ORM library outside of Microsoft provided libraries, NHibernate is the most probable candidate you would end up choosing. NHibernate  is a mature, open source ORM framework which is actively developed, fully featured, highly performant and successfully used in thousands of projects.


This framework is being developed for over a decade by community members and used in thousands of commercial and open source applications. NHibernate uses XML description of entities and relationships, automatically generates SQL for retrieving and manipulating data. Optionally you can describe mappings metadata with attributes in source code.

Microsoft LINQ to SQL



LINQ to SQL is another Microsoft ORM library which was released before Entity Framework. Before shipping Entity Framework, Microsoft heavily promoted Linq To Sql and it is used in many .NET applications. The LINQ to SQL provider allows LINQ to query SQL Server databases to retrieve and manipulate data as strongly typed objects. Basically it’s a semi-ORM which is meant for Sql Server and if you are looking for building generic data access code that works on any database, then Linq to Sql is not the choice for you.

ORMapster


ORMapster for Visual Studio 2013 is a simple ORM data mapper and code generator extension that does one thing: iI reads your data source and creates a data access layer with LINQ self-tracking entities. That's it. The resulting data entities can then be used in your projects, including WCF, ASP.NET MVC, Web Forms, Windows Forms and so on.


ORMapster integrates directly with Visual Studio, and versions are available for Visual Studio 2010 through 2013. To work with the LINQ entities created by ORMapster, you'll also need the ORMapster Framework NuGet package.


There's a handy Getting Started guide on the ORMapster Web site that walks you through building a data model based on the beloved Northwind sample database. Also, although there's pretty much no documentation explaining it, you might check out the ORMapster Web UI NuGet package, which appears to be a DataSourceControl optimized for data binding with ORMapster-generated entities.



There are few other less known libraries available and used in few projects – AutoMapper, EntitySpaces.NET, LightSpeed etc. For a comprehensive list of .NET ORM libraries.

Which one is the best?


Hmm... this is a tough question to answer as it highly depends on the projects to say which ORM is best for a .NET project. There are various factors we need to consider before nailing down on the ORM – availability of developer pool with a specific ORM knowledge, size, performance & scalability requirements of the target application, level of support required and  time to market factors.


In the list of available ORM libraries Microsoft Entity Framework & NHibernate stands out in the crowd. If you organization is a fan or open source community and looking for a well oiled and proven library then you should consider NHibernate.


On the other side, Microsoft is heavily investing in developing Entity Framework and in the past couple of years 5 iterations has been released.  It’s one of the most actively developed and well optimized ORM library that plays well any of the .NET technologies. The future for Entity Framework looks very promising as the big boss Microsoft is driving it. There is a good developer community available in the market with Entity Framework skills.


So, according to points above and based on your requirements choose between Entity Framework or NHibernate.

Tuesday, June 27, 2017

ELMAH Exception Logging Integration in MVC

In this article, Let us see what is ELMAH..

WHAT IS ELMAH?

ELMAH stands for Error Logging Modules And Handlers that provide functionality to logging run time ASP.NET errors.

  •  Enables logging of all unhandled exceptions.
  •  logs all errors in many storages, like - SQL Server, MySQL, Random Access Memory (RAM), SQL Lite, and Oracle.
  • It has functionality to download all errors in CSV file.
  • RSS feed for the last 15 errors
  • Get all error data in JSON or XML format
  • Get all errors to our mailbox
  • Send error log notification to your application
  • Customize the error log by customizing some code.

Implementing into MVC Application

1. Install ELMAH using Nuget package manager into your application.



2.  Configure your web.config with  ELMAH attributes like below:


<?xml version="1.0" encoding="utf-8"?>  
    <!--  
For more information on how to configure your ASP.NET application, please visit  
http://go.microsoft.com/fwlink/?LinkId=301880  
-->  
    <configuration>  
        <configSections>  
            <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->  
            <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />  
            <sectionGroup name="elmah">  
                <section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah" />  
                <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah" />  
                <section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah" />  
                <section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah" />  
            </sectionGroup>  
        </configSections>  
        <connectionStrings>  
            <add name="DefaultConnection" connectionString="Data Source=.;Initial Catalog=ExceptionLog;Integrated Security=True" providerName="System.Data.SqlClient" />  
        </connectionStrings>  
        <appSettings>  
            <add key="webpages:Version" value="3.0.0.0" />  
            <add key="webpages:Enabled" value="false" />  
            <add key="ClientValidationEnabled" value="true" />  
            <add key="UnobtrusiveJavaScriptEnabled" value="true" />  
            <add key="elmah.mvc.disableHandler" value="false" />  
            <add key="elmah.mvc.disableHandleErrorFilter" value="false" />  
            <add key="elmah.mvc.requiresAuthentication" value="false" />  
            <add key="elmah.mvc.IgnoreDefaultRoute" value="false" />  
            <add key="elmah.mvc.allowedRoles" value="*" />  
            <add key="elmah.mvc.allowedUsers" value="*" />  
            <add key="elmah.mvc.route" value="elmah" />  
            <add key="elmah.mvc.UserAuthCaseSensitive" value="true" />  
        </appSettings>  
        <system.web>  
            <authentication mode="None" />  
            <compilation debug="true" targetFramework="4.5.1" />  
            <httpRuntime targetFramework="4.5.1" />  
  
            <!--add this-->  
            <httpHandlers>  
                <add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />  
            </httpHandlers>  
  
            <!--add this-->  
            <httpModules>  
                <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />  
                <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />  
                <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />  
            </httpModules>  
        </system.web>  
        <system.webServer>  
            <!--add this-->  
            <handlers>  
                <add name="Elmah" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />  
            </handlers>  
            <!--add this-->  
            <modules>  
                <remove name="FormsAuthentication" />  
                <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" />  
                <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler" />  
                <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler" />  
            </modules>  
            <validation validateIntegratedModeConfiguration="false" />  
  
        </system.webServer>  
        <runtime>  
            <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">  
                <dependentAssembly>  
                    <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />  
                    <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />  
                </dependentAssembly>  
                <dependentAssembly>  
                    <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />  
                    <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />  
                </dependentAssembly>  
                <dependentAssembly>  
                    <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" />  
                    <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />  
                </dependentAssembly>  
                <dependentAssembly>  
                    <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" />  
                    <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />  
                </dependentAssembly>  
                <dependentAssembly>  
                    <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />  
                    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />  
                </dependentAssembly>  
                <dependentAssembly>  
                    <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />  
                    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />  
                </dependentAssembly>  
                <dependentAssembly>  
                    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />  
                    <bindingRedirect oldVersion="0.0.0.0-5.2.2.0" newVersion="5.2.2.0" />  
                </dependentAssembly>  
                <dependentAssembly>  
                    <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />  
                    <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />  
                </dependentAssembly>  
                <dependentAssembly>  
                    <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />  
                    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />  
                </dependentAssembly>  
                <dependentAssembly>  
                    <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />  
                    <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />  
                </dependentAssembly>  
            </assemblyBinding>  
        </runtime>  
        <entityFramework>  
            <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">  
                <parameters>  
                    <parameter value="mssqllocaldb" />  
                </parameters>  
            </defaultConnectionFactory>  
            <providers>  
                <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />  
            </providers>  
        </entityFramework>  
        <elmah>  
  
            <!--add this-->  
            <!--. If allowRemoteAccess value is set to 0, then the error log web page can only be viewed locally. If this attribute is set to 1 then the error log web page is enabled for both remote and local visitors.-->  
            <security allowRemoteAccess="0" />  
            <errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="DefaultConnection" />  
            <!--add this-->  
        </elmah>  
  
    </configuration>  


3. Now, Let us create a table to log the errors :

CREATE TABLE[dbo].[ELMAH_Error]  
(  
  
    [ErrorId][uniqueidentifier] NOT NULL,  
  
    [Application][nvarchar](60) NOT NULL,  
  
    [Host][nvarchar](50) NOT NULL,  
  
    [Type][nvarchar](100) NOT NULL,  
  
    [Source][nvarchar](60) NOT NULL,  
  
    [Message][nvarchar](500) NOT NULL,  
  
    [User][nvarchar](50) NOT NULL,  
  
    [StatusCode][int] NOT NULL,  
  
    [TimeUtc][datetime] NOT NULL,  
  
    [Sequence][int] IDENTITY(1, 1) NOT NULL,  
  
    [AllXml][ntext] NOT NULL  
  
)  


Create below Stored Procedures :

Create PROCEDURE[dbo].[ELMAH_GetErrorsXml]  
  
(  
    @Application NVARCHAR(60),  
    @PageIndex INT = 0,  
    @PageSize INT = 15,  
    @TotalCount INT OUTPUT  
  
)  
  
AS  
  
SET NOCOUNT ON  
  
DECLARE @FirstTimeUTC DATETIME  
DECLARE @FirstSequence INT  
DECLARE @StartRow INT  
DECLARE @StartRowIndex INT  
SELECT  
  
@TotalCount = COUNT(1)  
  
FROM  
  
    [ELMAH_Error]  
  
WHERE  
  
    [Application] = @Application  
SET @StartRowIndex = @PageIndex * @PageSize + 1  
IF @StartRowIndex <= @TotalCount  
  
BEGIN  
  
SET ROWCOUNT @StartRowIndex  
  
SELECT  
  
@FirstTimeUTC = [TimeUtc],  
  
    @FirstSequence = [Sequence]  
  
FROM  
  
    [ELMAH_Error]  
  
WHERE  
  
    [Application] = @Application  
  
ORDER BY  
  
    [TimeUtc] DESC,  
    [Sequence] DESC  
  
END  
  
ELSE  
  
BEGIN  
  
SET @PageSize = 0  
  
END  
  
SET ROWCOUNT @PageSize  
  
SELECT  
  
errorId = [ErrorId],  
  
    application = [Application],  
    host = [Host],  
    type = [Type],  
    source = [Source],  
    message = [Message],  
    [user] = [User],  
    statusCode = [StatusCode],  
    time = CONVERT(VARCHAR(50), [TimeUtc], 126) + 'Z'  
  
FROM  
  
    [ELMAH_Error] error  
  
WHERE  
  
    [Application] = @Application  
  
AND  
  
    [TimeUtc] <= @FirstTimeUTC  
  
AND  
  
    [Sequence] <= @FirstSequence  
  
ORDER BY  
  
    [TimeUtc] DESC,  
  
    [Sequence] DESC  
  
FOR  
  
XML AUTO  

Create PROCEDURE[dbo].[ELMAH_GetErrorXml]  
  
(  
  
    @Application NVARCHAR(60),  
    @ErrorId UNIQUEIDENTIFIER  
  
)  
  
AS  
  
SET NOCOUNT ON  
SELECT  
  
    [AllXml]  
FROM  
  
    [ELMAH_Error]  
WHERE  
  
    [ErrorId] = @ErrorId  
AND  
    [Application] = @Application  

Create PROCEDURE[dbo].[ELMAH_LogError]  
  
(  
  
    @ErrorId UNIQUEIDENTIFIER,    
    @Application NVARCHAR(60),    
    @Host NVARCHAR(30),    
    @Type NVARCHAR(100),  
    @Source NVARCHAR(60),    
    @Message NVARCHAR(500),  
    @User NVARCHAR(50),   
    @AllXml NTEXT,    
    @StatusCode INT,   
    @TimeUtc DATETIME  
  
)  
  
AS  
  
SET NOCOUNT ON  
  
INSERT  
  
INTO  
  
    [ELMAH_Error]
(  
  
    [ErrorId],   
    [Application],   
    [Host],  
    [Type],  
    [Source],  
    [Message],    
    [User],    
    [AllXml],    
    [StatusCode],    
    [TimeUtc]  
  
)  
  
VALUES  
  
    (  
  
    @ErrorId,  
    @Application,    
    @Host,    
    @Type,    
    @Source,   
    @Message,    
    @User,   
    @AllXml,   
    @StatusCode,   
    @TimeUtc  
  
)  


That's it, Now your application is ready to track run time errors or exception by your site.

www.<sitename>.com/elmah.axd