.NET Datetime vs SQL Datetime : Comparison, Issues and Workarounds

Hello All,

Recently, in an application where we were saving the .NET DateTime value in SQL database, we had to compare this DateTime later in the .NET application. We realized that even the same DateTime stamp was not equating once it got fetched from database. I got Once we investigated further we found that the time stamp that we were sending to save in database, was not saving with the complete value and there were some more issues. It looks common requirement where you saving a value in database and later comparing it to add some business logic.  So I am sharing here my findings.

# 1

SQL DateTime type only stores time till milliseconds (3 digits) while in .NET it is stored till ticks. One millisecond is equivalent to 10,000 ticks. It means if you construct the .NET DateTime object from the DateTime of database, then it will never match because it will have all zero after the milliseconds. Lets see an example.
Here I am showing the same .NET DateTime value at application, in database table and again .NET DateTime read from the DB.

.NET DateTime

{6/19/2017 9:24:14 PM}
      Date: {6/19/2017 12:00:00 AM}
      Day: 19
      DayOfWeek: Monday
      DayOfYear: 170
      Hour: 21
      Kind: Local
      Millisecond: 777
      Minute: 24
      Month: 6
      Second: 14
      Ticks: 636335042547778146
      TimeOfDay: {21:24:14.7778146}
      Year: 2017

Let’s see how it is saved in database.

SQL DateTime

In database table it looks like as


When we fetch from database and convert it into it returns the following object
{6/19/2017 9:24:14 PM}
      Date: {6/19/2017 12:00:00 AM}
      Day: 19
      DayOfWeek: Monday
      DayOfYear: 170
      Hour: 21
      Kind: Unspecified
      Millisecond: 777
      Minute: 24
      Month: 6
      Second: 14
      Ticks: 636335042547770000
      TimeOfDay: {21:24:14.7770000}
      Year: 2017

Here we see the TimeOfDay component in both the object then we find that while in first object we have 7778146 while in second 7770000, it means last 4 digits are chopped off and reset to 0.
So is it safe if we compare till milliseconds only (say by using ToString(“MM/dd/yyyy hh:mm:ss.fff”))?
NO
There are some more mystery to it. Let’s see in second point

# 2

Here, I saved a new record in the database and the .net DateTime as
{6/19/2017 11:49:55 PM}
      Date: {6/19/2017 12:00:00 AM}
      Day: 19
      DayOfWeek: Monday
      DayOfYear: 170
      Hour: 23
      Kind: Local
      Millisecond: 731
      Minute: 49
      Month: 6
      Second: 55
      Ticks: 636335129957315136
      TimeOfDay: {23:49:55.7315136}
      Year: 2017

and when we see the record in the table, we see

Oh.. here we see the 730 millisecond while in .NET object it was 731. Let’s fetch the same and check the .net object as

{6/19/2017 11:49:55 PM}
      Date: {6/19/2017 12:00:00 AM}
      Day: 19
      DayOfWeek: Monday
      DayOfYear: 170
      Hour: 23
      Kind: Unspecified
      Millisecond: 730
      Minute: 49
      Month: 6
      Second: 55
      Ticks: 636335129957300000
      TimeOfDay: {23:49:55.7300000}
      Year: 2017

Here again we see 730 millisecond. It means we are losing one millisecond. It also suggests that comparing the two values till milliseconds would also not work. But why this is happening. Let’s dig it more.

Actually SQL DateTime stores till 1/3 millisecond approximately so the last digit of millisecond would always be

**0
**3
**7
**0

and SQL rounds of the milliseconds passed to it so if you pass
001 turns to 000
002 turns to 003
004 turns to 004
005 turns to 007

009 turns to 010

So can we just chop off milliseconds and compare the DateTime?
NO

It may work most of the time. But there are few chances to fail. Say we have a time as 09.00.00.999 then it will turn to 09.00.01.000 so here second got increased by 1. Even minute/hour can be changed if similar situation occur. So here we just have the option to round off the time based on the above logic and then compare.

Do we have any other option?
Yes

DateTime2

To overcome this, there is a new SQL data type datetime2 was introduced in SQL server 2008 which got the ability to save the millisecond till 7th precision. It is like an extension of DateTime which saves the time more accurately. Lets have a look on that

So we see here that the time is saved as 2017-06-19 23:49:55.7353342 while the same was saved in DateTime (type) as 2017-06-19 23:49:55.737 (rounded off). If we now fetch the same and assign the .NET DateTime object we get the exact date time and equality works as expected.

Note – There is one more significant update in datetime2. In DateTime if we want to same a default minimum DateTime then it was 1753 but in DateTime it could be 0001.

Conclusion

In this post, we discussed the behavior of SQL DateTime object, its issues and possible workarounds. Then we saw that the how the issues got resolved in datetime2 which was introduced in SQL server 2008. Obviously, it takes more space in database as it saves the time more granular level. I have rarely seen that DateTime values are stored in datetime2 format, mostly in DateTime at least in legacy application. And many of us don’t know the exact difference or may face the issues that we discussed. If we are working on some legacy application then we may not able to change the SQL data type, in that scenario, putting the round off logic could work.

Hope you have enjoyed the post. Do share your valuable feedback.

Happy Coding,
Brij

Advertisements

Exploring ASP.NET Core View Component

Partial Views and Child Actions are one the most used features of ASP.NET MVC. Partial Views provides us a way to create a reusable component that can be used in multiple Views. There are Actions which can be marked as Child Actions and these cannot be invoked via URL but inside views or partial views. Child Actions are no more available with ASP.NET Core. View Components are new way to implement this feature in ASP.NET Core.

Few Challenges with Partial Views

Partial Views has certain challenges and limitations. Say if we use child action in a view then while execution, an additional life cycle takes place, first ASP.Net MVC life-cycle executes for the loading the main View and once it gets loaded, another for the Child Action. Also, putting certain filter like Authorize over Child Action, used in layout, makes the complete page fail if authorization fails. It also does not support the awesomeness of async programming, test-ability, Separation of Concerns etc.

What is View Component?

View Component is one of the many awesome features introduced in ASP.NET Core. As mentioned earlier, View Components are similar to Partial View and enables us to write reusable component which can be used in multiple views. View Components are robust, leverages asynchrony, Dependency Injection friendly, follows separation of concerns which makes it easily maintainable and testable.

How to Create a View Component

There are few ways to create a View Component. These are

Class name ends with ViewComponent

We can write a plain C# class and name it with suffix ViewComponent as

public class TopBooksViewComponent
{
    public void InvokeAsync()
    {
        // View Component Logic
    }
}

ASP.NET Core recognizes the suffix and render it as view component. As this is a plain C# class, we would not have the basic MVC feature available like MVC Context etc.

Using ViewComponent attribute

It provides another way to create a View Component. We just need to put this attribute on any class as

[ViewComponent]
public class TopBooks
{
    public void InvokeAsync()
    {
        // View Component Logic
    }
}

This is almost similar as previous one. Here again we won’t have the liberty of MVC features until it is inheriting another entity. There is one more usage of this attribute, to provide a custom name to the View Component as

[ViewComponent(Name = "Featured Books")]
public class TopBooksViewComponent
    {
    public void InvokeAsync()
    {
        // View Component Logic
    }
}

Derive from ViewComponent Class

It is a simplest way to create powerful View Component via leveraging standard MVC features like HttpContext, TempData, ModelState etc. Also it allows us to use View similar to normal mvc controller. Here we don’t need any suffix in the class name (which was required in earlier ASP.NET Core versions). It looks as

public class TopBooks : ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync()
    {
        // View Component Logic

        return View();
    }
}

We will use the third option in our example. So let’s start

Note – For this example, I am using Visual Studio 2015 update 3 and ASP.NET Core 1.1.1. Complete code can be downloaded from here.

Here we will be creating a View Component which shows Top n (based on the parameter) books. For this, we will be reading the data from a book repository where we have hard coded data but in real applications, it could be read from Database, web service etc. Let’s have a look on this

public class Book
{
    public int Id { get; set; }

    public string Title { get; set; }

    public string Image { get; set; }

    public string Author { get; set; }

    public float Rating { get; set; }

}
// Repository
public interface IBookRepository
{
    Task<IList<Book>> GetTopBooksAsync(int noofBooks);
}

public class BookRepository : IBookRepository
{
    static IList<Book> allBooks;

    public BookRepository()
    {
        allBooks = new List<Book>()
        {
            new Book() { Id=1001, Title="Lifehacker: The Guide to Working Smarter, Faster, and Better", Image="LTGWSFB.jpg", Author="Adam Pash; Gina Trapani", Rating=4.4F },
            new Book() { Id=1002, Title="Mindhacker: 60 Tips, Tricks, and Games to Take Your Mind to the Next Level", Image="M6TTGTYMNL.jpg", Author="Ron Hale-Evans; Marty Hale-Evans", Rating=4.6F },
            new Book() { Id=1003, Title="Information Technology for Management: Improving Strategic and Operational Performance", Image="ITMISOP.jpg", Author="Efraim Turban; Linda Volonino", Rating=5F },
            new Book() { Id=1004, Title="Visualize This: The FlowingData Guide to Design, Visualization, and Statistics", Image="VTTFDGDVS.jpg", Author="Nathan Yau", Rating=4.6F },
            new Book() { Id=1005, Title="Creating Personal Presence", Image="CPP.jpg", Author="Dianna Booher", Rating=4.4F }
        };
    }
    public Task<IList<Book>> GetTopBooksAsync(int noofBooks)
    {
        return Task.Run(() =>
            {
                IList<Book> orderedBooks = allBooks.OrderByDescending(b => b.Rating).ToList().Take(noofBooks).ToList();
                return orderedBooks;
            });
    }
}


We have created a book class with basic properties. Then we created an interface for repository and implemented the same in BookRepository which implements the GetTopBooks method. As mentioned earlier the data is hard-coded here. So we have created our Repository, we need to add it in our application. ASP.Net Core is DI (Dependency Injection) friendly and provides a basic DI container. To add this repository, we need to write the below code in ConfiguerServices method at startup.cs

services.AddTransient<IBookRepository, BookRepository>();

It injects a new instance of service every time it is used in the application. There are few other options based on the scope and life time of instance. To learn more about dependency injection ASP.NET MVC core refer my previous post.

Till now we have written code for supplying data to our component. Now it’s time to write the View Component.

Step 1:

First, we will create a Class which derives from ViewComponent. I have created a class name TopBooks and here we need to implement InvokeAsync method which can take multiple parameters based on the need which is passed while invoking the view component. My View Component class looks like

public class TopBooks : ViewComponent
{
    IBookRepository bookRepostiroty;
    public TopBooks(IBookRepository repository)
    {
        this.bookRepostiroty = repository;
    }
    public async Task<IViewComponentResult> InvokeAsync(int noOfBooks)
    {
        var items = await bookRepostiroty.GetTopBooksAsync(noOfBooks);

        items.ToList().ForEach(b => b.Image = @"/images/" + b.Image);

        return View(items);
    }
}

In the InvokeAsync method, we are passing a parameter noOfBooks and based on that we are fetching the books from bookRepository. The items return by the repository contains the book image name which is getting converted in the complete URL so that it can be directly used on UI. Then we are passing these items in the view. We didn’t provide a view name, it finds a view with name Default.cshtml but we can also provide any other name as well. For that we need to pass the view name in string format, similar to normal controller returning named view. We can see that here the return type of this method is IViewComponentResult which is specific for View Component.

This class looks like mini controller as it returns the view. It has only one method InvokeAsync which can be called from the specific View Component, not from the browser. It also provides another method InvokeAsync which can be used instead for async handling.

We used here our BookRepository that we created and it got injected via constructor. Now we will move to step 2.

Step 2:

We need to create the UI for View Component. It is normal razor view and we will create a new view with name as Default.cshtml. We cannot put this view anywhere but one of the following locations

  • ~/Views/Shared/Components/[ViewComponentName]/Default.cshtml
  • ~/Views/[ControllerName]/Components/[ViewComponentName]/Default.cshtml

If we want to use the View Component across multiple controllers, then first location should be used. On the other hand, if we want to restrict its usage to the same controller then second option should be chosen.

Also as we choose the name of the view component as default.cshtml but we can use any other name. When we have any other name like Foo.cshtml then we need to pass the name of View from our mini controller as

 return View("Foo", items);

It is similar like Views in the normal controller where if the action name and view name is same then we do not need to pass the view name else need to provide.
Let’s see our View (Default.cshtml)

@model IEnumerable<ViewComponentBlog.Models.Book>
<table class="table table-condensed table-hover">   
<tr> 
<th> </th>
<th> Title</th>
<th> Author</th>
<th> Rating</th>
    </tr>
    @foreach (var b in Model)
    { 
<tr>  
<td> <img src=@b.Image /></td>
<td> @b.Title</td>
<td> @b.Author </td>
<td> @b.Rating</td>
        </tr>
    }
</table>

It is like normal view where we have the list of books as in the model and we iterated that to display on the screen.

Step 3:

Now the final step is to use the View Component in any view. It is very simple, we can invoke it at any place.

@await Component.InvokeAsync("TopBooks", 3)

Here the first parameter is the name of the view component and then the parameters that we used while implementation of InvokeAsync method. We used only one parameter number of books so here we are passing the same. Other important thing as we are using asynchronous method, we need to use await keyword as in the example else it won’t be rendered on the screen.

Now we are done and now let’s run the application

So we can see that our view component is displayed as expected.

View Component can also be used in MVC Controller as well. For that we need to use ViewComponetResult class as

public IActionResult IndexVC()
{
    return ViewComponent("TopBooks", 3);
}

How to use ViewComponent as TagHelper 

View Component also can be used tag helpers in ASP.NET Core 1.1. Tag Helpers are also a new feature introduced with ASP.NET Core which provides us to render a server side code in the razor mark up in a HTML friendly way and allows us to write robust, reliable and maintainable. I wrote a post on it long back on it, you can have a look here. As newer version of ASP.NET Core got released, there may be slight changes in it. To use it as TagHelper we need to first include TagHelper library in project.json (Microsoft.AspNetCore.Mvc.TagHelpers) then add it in the Views as

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, ViewComponentBlog

Here ViewComponentBlog is the project name. Now it can be used on the view as

<vc:top-books no-of-books="2" >
</vc:top-books>

It looks simpler and cleaner. To use any View Component, the tag should start with vc and the view component and parameter name are converted on lower kebab case (means all in lower case and if there is case change then a hyphen is inserted like TopBooks changed to top-books), it would not work if the naming is not properly used. So now you have the beauty of TagHelper with ViewCompoenent.

Conclusion

In this post, we have seen that View Component is powerful feature of ASP.NET Core which can be used to write complex reusable controls for the application. It is loaded with separation of concern, async and testability features and similar to normal controller and view.  We created a sample view component in step by step approach and used that in a view and used the power of DI for injecting Repository in our control.  Also, we saw that in ASP.NET Core 1.1, it can be written as TagHelper which makes sure, we are not forced tow write C# code in the view J. Complete code is attached with the post.

Leveraging Dependency Injection in ASP.NET Core

Millions of software has been built in last couple of decades which helped in coming up a set of patterns for resolving different problems and we have a ready reference as GoF design patterns from quite long now. In last decade, Inversion of Control and one of its implementation Dependency Injection (DI) became one of most used pattern across platforms for building great soft wares. Agile methodology for building software which focuses on small releases and more adaptive to the changes, made it very important tool. In this post, we will discuss Dependency Injection and different.

What is Dependency Injection?

Dependency Injection is a design pattern which is an implementation of Inversion of Control (IoC) that provides us a way to resolve dependencies. Objects works in collaboration model and the whole communication becomes pretty complex as system grows.  Inversion of Control says that the objects should not itself create the object/component on which they are dependent to their work, instead these are passed from external sources.

ASP.NET Core and DI

Due to DI’s long list of advantages it has become the norm in software development. But implementation in earlier versions of ASP.NET was not straight forward. Although there are different extensions and libraries made our life easy but ASP.Net as a framework was not open for the same. Due to these kind of new challenges, Microsoft has overhauled the complete framework and made the changes from ground up. The new framework is modularized and using the DI at its core. ASP.Net Core itself provides basic IoC container that we will discuss and later we will how we can use other.

Default container in ASP.NET Core

As mentioned earlier that ASP.NET Core uses DI for instantiating all its components and services. This container is configured in startup.cs class which is the entry point to an ASP.NET Core application. In Startup.cs we have method ConfigureServices which is where we configure all the services that can be later used in the entire application’s life cycle. Let’s see what all are the options provided by ASP.NET core.

aspnetdicore

ASP.NET Core provides above three options to register the services. Let’s discuss each.

AddTransient

Services registered using this method get instantiated each time it is accessed. If we have a service which is used multiple places in same request, a new instance would be created each time.

This method should be used for lightweight, stateless and rarely used services. Let see an example.

Here I have created a service named as TestService which has a method named as GetUniqueId. In this method, I am returning the hash code of the for the instance to check the uniqueness of the instance as

    public class TestService : ITestService
    {
        public int GetUniqueId()
        {
            return this.GetHashCode();
        }    
    }

This service is injected at two places in the sample MVC application

  1. In my home controller as
        public class HomeController : Controller
        {
            private ITestService testService;
    
            public HomeController(ITestService _testService)
            {
                this.testService = _testService;
            }
            public IActionResult Index()
            {
                ViewBag.ServiceInstanceId = testService.GetUniqueId();
                return View();
            }
        }
    
  2. And in my view (Yes we can inject services in the View as well) as
    cshtmlinject

Here service is injected in it at line 1 and called the GetUniqueId method at line 6. While at Line 4, unique Id for the instance is displayed that got injected in home controller. Now it’s time to test the application and register the service as

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddTransient<ITestService, TestService>();
        }

When we run the application
addtransient
Here we can see that in the same request we are getting two instances as expected.

AddScoped

In case of AddScoped, only one instance is created for each request, regardless the number of times it is used in the request. So if you have a service which maintains some state in each request or used frequently then it could be a better choice.

In the same example, we will change the registration of service as

services.AddScoped<ITestService, TestService>();

And run the application
addscoped1
Here we see that only one instance created for the same request. Let’s see multiple requests
addscoped2
As expected here, two different instances gets created for different request while it is unique per request.

AddSingleton

As the name suggests, it created only once instance which get created in the first request itself. In every subsequent request, same instance is used. So, if there is requirement of a singleton behavior, maintaining state across requests then this option is best. Creating our own singleton behavior is not recommended.

It provides two important flavors.

  1. First where we let the framework to create the instance as
    services.AddSingleton<ITestService, TestService>();
    
  2. Second where we create the instance and register the same instance as
    ITestService testService = new TestService();
    services.AddSingleton(testService);
    

    So if we have some custom heavy object that can be used across request or do some changes in the instance before registering then second option is good.

Now let’s run the application
addsingelton
Here we get the same instance across multiple requests.

Third party DI containers

For basic usages of DI, we can use the default DI container but for the advance usage, we can use any third part DI container with the ASP.NET like Autofac, Unity, Ninject etc or some custom one. For that we need to have an adapter which provides implementation of IServiceProvider or we can write our own. We have already the required implementation for Autofac which can be easily integrated. let’s see that.

Using Autofac with ASP.NET

It’s very simple to leverage to use the power of Autofac. We need to include the following package in our project.

Autofac.Extensions.DependencyInjection

Once that is added, we need to make few changes in ConfigureServices Method. By default, it returns void but to use other provider, it should return IServiceProvider. We will create the instance of ContainerBuilder then register our services. Then get the container and return the service provider from the context.

        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            var builder = new ContainerBuilder();
            builder.RegisterType<TestService>().As<ITestService>().InstancePerLifetimeScope();
            builder.Populate(services);
            var container = builder.Build();
            return container.Resolve<IServiceProvider>();
        }

Here we can see that we provided the life time of the instance while registering the service similar to AddScoped. We can also see that we used default container to add mvc, it means we can mix and match with containers.

Final words

Dependency Injection is very helpful for writing loosely coupled and testable software. Its usage with earlier versions of ASP.NET was bit tricky but with the new version ASP.NET, It has become the first-class citizen of ASP.NET Stack. We have seen that it provides a basic DI container and discussed with an example with details. Also, we discussed that how we can configure other third party containers like Ninject, Autofac, unity etc. We have configured Autofac in our example and saw we can use multiple container in same application.

Wish you all a very Happy New Year : 2017

Print

As the year 2016 is coming to an end, I want to take this opportunity to Wish all my blog readers a very Happy New Year. Wish that the New Year brings joy, happiness, good health and you achieve all the things that you wished.

2016 has been a fantastic year for me. My MVP award renewed again in this year 6th time. My first video course got published by Packt on Building Web API using ASP.NET Core framework. ASP.NET Core is the latest version of ASP.NET which got complete bottom up change. I would encourage you to have a look on it here. The first wish of any MVP after getting the award, is to attend the MVP summit. This year, it got fulfilled and I attended my First MVP Summit after almost six years. I also visited Delhi during a conference and got a chance to meet so many friends again. .

In last couple of months, I could not provide enough time to my blog and other community activities due to personal reasons and lot of travel. I hope it would get normalized very soon and I will be able to give more time here and connect to all of you via various ways.

Thank you all again for your continuous support and feedback. Again Wish you all a very Happy New Year.

Cheers,
Brij

Few ways of Handling Exceptions in ASP.NET MVC

Exception handling is one of the major areas of an application development and when it is a web application, it requires additional care so that errors gets handled gracefully without breaking the complete system and relevant information is shown to the users with proper error message. Also making sure that no internal details gets propagated till user when application crashes or error occur because it could be a major security threat. All the exception details and other additional information should be logged so that it can be later used for proper investigation. In this post we will talk about the few options available to handle the exception in ASP.NET MVC and best practices to use them.

In ASP.NET MVC, the request first hits the route handler which identifies the controller and action to be serving the request. We put the whole logic in our controller itself. There are various type of filters in ASP.NET MVC that are also part of the request processing and some time we extend them to put some custom logic based on specific requirement. There is an Exception filter for handling exceptions as well and this Filter is key in handling exceptions in MVC. First let’s see available filters and their order of execution in request processing flow

orderoffilters

So we can see here that there are four filters in total and exception filter executes at end. It means if we use exception filter then it will be caught there whether the exception occurs in Action or even in Authorization/Action/Result filters.

Note – Filters are added as an attribute so it also inherits from ‘System.Attribute’.

Broadly we can say that exceptions may occur in controller or in some cases while processing the routes and filters. But as most of our core logic resides in action so the chances in are most. Before focusing on filters, let’s first discuss one basic way to handle to exception that is part of C#.

Using Try/Catch block

This is C# feature and one of the basic ways to handle exceptions so we can wrap all our code in our Action as below.

try
{
    // Add your code here
}
catch
{
    // Exception Handling code
} 

But there are many issues with this approach and the primary issue is the limitation to single Action. To handle that, we need to put try catch block in each Action of the application which is repeating the same exception handling code which defies the code re-usability logic. It does not mean that we should never use it but there are some scenarios where we require to perform some another activity in case of exception without letting the user know or more specifically if you are calling to some third part services etc. then it might be a good Idea to use this approach.

Global Error Handling

Global error handling is one of the simplest way to handle exceptions at application level. It leverages the Exception Filter to handle exception and applies at application level itself. This is out of the box feature and can be easily set up by following step.

  1. Set customErrors errors as On in web.config as
    <customErrors mode="On"></customErrors>
  2. Have a common error view (in Shared folder with name error.cshtml) which will be shown in case of error aserrorviewHere we see that we get a model of type HandleErrorInfo class which provides the details about that error occurred, controller and action name etc.
  3. Make sure we registere HandleErrorAttribute in Application_Start (Global.asax)method
    RegisterGlobalFilters(GlobalFilters.Filters);
    
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
         filters.Add(new HandleErrorAttribute());
    }
    

    Now if any error occurs then error view will be shown.

Customizing global error handling

We have seen that how easily we can configure the error handling at application level. But what if we want to handle it bit differently. Say we want to save the details in database and/or want to send the email notification when error occurs. We have two options here

  1. Override OnException method :

    We can override OnException method as in our controller as

    protected override void OnException(ExceptionContext filterContext)
    {
        Exception ex = filterContext.Exception;
        // Log Exception ex in database
    
        // Notify  admin team
    
        filterContext.ExceptionHandled = true;
    
        // Setting the View in case of error
        filterContext.Result = new ViewResult()
        {
            ViewName = "CustomErrorView"
        };
    }
    

    Here we can log our exception, send the mail etc. and set our own view that will be shown (like here I used CustomErrorView) in case of error. But this code won’t be reusable and need to write in each controller wherever we need.

  2. To handle it in better way, we need to extend HandleErrorAttribute as
    public class MyCustomHandleErrorAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
                       Exception ex = filterContext.Exception;
                	     // Log Exception ex in database
    
                	     // Notify  admin team
    
                	     filterContext.ExceptionHandled = true;
    
    
            filterContext.ExceptionHandled = true;
    
            filterContext.Result = new ViewResult()
            {
                ViewName = "DVZ"
            };
        }
    }
    

    And instead of registering the default HandleErrorAttribute we need to register the custom one as

    filters.Add(new MyCustomHandleErrorAttribute());
    

    Now this custom error attribute will be used in the whole application.

Handling exception at more Granular level

Till now, we have seen that how can we apply filter at global level. MVC allows us to handle exceptions at more granular level similar at controller and action level as
granularexceptions

For Controller either we can use the default HandleErrorAttribute or we can use the extended attribute similar to MyCustomHandleErrorAttribute and put it at controller as

[MyCustomHandleError]
public class EventController : Controller
{
// Controller code
  	…
}

For Action

public class EventController : Controller
{
	[MyCustomHandleError]
public ActionResult About()
{
	// Action code
}
…
}

Note – Here I have put ‘MyCustomHandleError’ as an attribute. We can use default ‘HandleError’ attribute instead of custom one.

Another variation

There may be some scenarios where we may need to show specific view or details based on the type of exception occurs in Controller/Action. In other words, say if in Controller/Action, if a specific exception occurs, then showing user one view and any other exception occurs then show a different view. Let’s see an example

[HandleError(ExceptionType = typeof(DivideByZeroException), View = "DVZ")]
[MyCustomHandleError]
public ActionResult Create()
{
	// Action code
}

Here if DivideByZeroException occurs then view DVZ will be loaded else default one would be loaded. We can add as many type of exception based on requirement. Also similarly we can apply at Controller level as well.

ExceptionHandled property usage

In OnException method, you must have seen the following line many times.

filterContext.ExceptionHandled = true;

As the name suggests that when we set it true (default: false), then the exception does not propagate further and it is handled in the same method. Say we have put the Exception Filter at action, added a Global exception filer and we did not set the ExceptionHandled filter or set it false then once the exception is caught by action level exception filter that will be thrown further to next level and caught at global filter. Normally when we handle exception we make it false because we have already handled the exception. But there could be few scenarios where we do something with exception details and throw it further so accordingly we need to set this property.

Exception handling outside the scope of MVC

Exceptions are bound to happen and it can always find the way to reach user. We need to block every route. As we know handled the exceptions using MVC framework features but if something happens outside of the MVC scope. As we know that MVC framework is built on top of the ASP.NET platform then we can use the Application_Error method that is available since beginning to handle Application level error. It can be depicted pictorially as
aspnetnmvc

Here we can see that once the control reaches ASP.NET platform, this method can help us so we should handle the exception here as well and we can put all the logging and notification code here as

protected void Application_Error()
{
    Exception ex = Server.GetLastError();
    // Log Exception ex in database

    // Notify  admin team

    // Clear the error
    Server.ClearError();

    // Redirect to a landing page
    Response.Redirect("home/index");
}

Note: Application_Error should not be used in replacement MVC global exception filer, because as soon as you get out of MVC scope, you won’t get its execution context which is very important to provide the relevant details about the exception.

Conclusion

We have discussed various possible ways of handling exceptions. We find that all the exception handling moves around the handle error attribute with many variations. Another two that we discussed: using try catch block and using Application_Error. Best solution for any application would be a combination of these approaches like extend HandleErrorAttribute based on the requirement and use it accordingly. Application Error should be used as if an exception somehow find its way to get out from MVC scope, then it will be caught here. Try Catch block should be really avoided as it just not makes the code ugly but we can miss lots of relevant information that may be helpful in fixing the issue so unless specific case, do not use it.

Popup boxes in JavaScript : Do you use all ?

How many times have you used alert popup in your JavaScript code?

Most of the web developer’s answer would just less than infinite. This is the most used keyword and become rescue tool when we stay late at office to resolve a silly JavaScript issue. Alert prompts user a popup with some information. Earlier it was also used heavily for showing validation error messages.

But do you know what all are other popup options available with JavaScript?

These are in total three as below

popupboxes

Let’s discuss one by one

Alert

It is the simplest one and most widely used to show some message to user in one way. Once the message on browser, it shows OK button which is required to be pressed before moving further as

alert

Syntax

Syntax is pretty simple

   alert("Your meesage to user");

Confirm

This is another important  message box which instead of just showing a message to user, it also accepts the user’s response. It is used to take a Boolean response (true/false) from the user. When displays it show two buttons Ok and Cancel. Ok return true and Cancel returns false. Lets see it

confirm

Syntax
    if(confirm("Do you want to proceed"))
    {
        // Proceed further
    }
    else
    {
        // Stop 
    }

Prompt

This is another popup message box which is used least. But this can be very helpful in certain scenarios. This allows to take some input from the user. When it is shown to user, it provides an input box in popup where user can enter some text with OK and Cancel button. If OK is pressed then the entered value is passed to the backend else it returns null. It also allows us provide a default value in text box.
prompt

Syntax
    var enteredSocialMedia = prompt("Which social media site you use most", "Twitter")
    if (enteredSocialMedia == null)
    {
        alert("No worries!! You can save your preference any time");
    }
    else
    {
        alert("We have saved your preference");
    }

I have used Internet Explorer for this example and if you have used alert or any of them with earlier version of IE like IE 6/7, its looks much better now. It looks different on different browser because its the browser which shows its own popup. Although in most of the cases, we don’t use these popup due to its limitation and look n feel but can help in many scenarios and suitable for small applications.

Cheers,
Brij

Singleton vs Static class : Key Differences and Usages

The debate about Singleton vs Static is quite old and it is still continuing and there are lots of confusion around this as well. In this post, I am trying to explain these two concepts, key differences and its usages.In this post I will not focus on the basics of Static and Singleton and how to write that. If you are new to these keywords, I will advise you to learn about these first to get more benefited.

So first we are going to understand the characteristics of each . Lets start with static class

Static Class :

  1. Static classes cannot be instantiated so it restricts us in many ways like it cannot implement Interfaces, inherit any class etc.
  2. Any other scenarios where this keyword is required, it cannot be used like indexer etc. Also it cannot be used as method parameter, local variable etc for the same reason.
  3. Static classes can have only static members – constructor, fields, methods, properties, events.
  4. One cannot control when static constructors are called. It’s always earlier than first access of the class. So no parameters can be passed as well.

Internally when compiler compiles static class, it marks it as a abstract and sealed. So that no instance can be created and cannot be extended as well. Now let’s talk about Singleton

Singleton Class :

  1. As name suggests it allows to have only one instance of a class.
  2. The constructor of this class are marked as private so that accidentally one cannot create multiple instances and provides a static function/property which first create one instance and returns the same each time.
  3. As singleton is a normal class, it allows us to leverage all that features of object oriented programming concepts.

Memory Management :

There is much confusion around memory management of static class and Singleton class. In simple words, any class whether it is itself static or any member if marked as static then it would not be collected by Garbage Collector.

Static variables/classes are not stored in normal Heap and there is a separate space in memory to store static resources which holds the static classes and variables.This space is beyond the scope of GC and memory get release only when corresponding process/AppDomain unloads.

Because singleton holds a static reference which cannot be collected by GC so the instance cannot be collected and both (Static and Singleton) gets destroyed with the AppDomain/Process.

Some Key common characteristics :

  • As both of the static and singleton instances are have just one copy in memory throughout the whole application, both used for holding global state in an application.
  • Both are initialized lazily, it means for static classes it is initialized only when accessed first time and for Singleton, it gets created only when it is accessed first time.

The Differences

  1. Very first difference is that Static is a language feature and Singleton is a architectural pattern so both belongs to difference arena altogether.
  2. Now a days everybody is behind using Dependency Injection and Static does not fit there because it is interface driven.
  3. Unit Testing is another topic where you can find some way to create a mock for singleton instances but testing static is a nightmare.
  4. Being singleton is a just another class, it enable you to use Object oriented concepts.

Singleton approach is much more flexible as we can see that from the differences itself. We can use interface with it and implement it in a class and use in our application. If some requirement changes and later we require to change the logic then we can just remove the older implementation and replace with new one without hiccups as long as the interface is same.. Also testing is another key benefit.

Static classes is mainly recommended for having grouping of a bunch of utility methods that can be called independently but again testing could be a problem and benefits of OOP is gone. So most of the time static should be avoided.

Having said that using global variable (like static class or singleton) makes a strong coupling between the global data and all the places where it is used.

Cheers,
Brij