Inheritance with JavaScript

This post is in continuation in my last post.  In my last post, I discussed various ways to create custom object in JavaScript. I’ll advise you to go through that if you didn’t get a chance to have a look then you can go through it. Please find the link below

Various ways to Create custom objects in JavaScript

In this post, We will discuss, how we can use other features of Object Oriented concepts in JavaScript. Today I’ll discuss one of the main concepts of Object Orient Programming that is Inheritance.

So how can we use Inheritance with JavaScript ?

Various ways and plugins are available that provides similar ways to use Inheritance that we have used in other object oriented language. But the prototype based Inheritance is used most.

JavaScript is a object based language that is based upon Prototype based programming. It is free from Class and completely rely on objects only .

Did you hear earlier  that What is Prototype based language or what is Prototype based programming?

I would say this is just another way to provide object oriented feature by a language. As per wiki

Prototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based languages) is performed via a process of cloning existing objects that serve as prototypes. This model can also be known as classless, prototype-oriented or instance-based programming. Delegation is the language feature that supports prototype-based programming”.

So let’s start learning. To create a Class in JavaScript, we are required to create a function  that we also used to call a Constructor. I’ll use the word constructor in my further discussion. So Let’s create a Constructor called person

         function Person() {
             this.ToString = function () { alert('I am a Person'); }
             this.DisplayResidence = function () { alert('I stay near my office'); }
         }

As in my last post, I mentioned that Person is a nested function. As you can see that here we have following two functions in the Person constructor.

  1. ToString
  2. DisplayResidence

So let’s create a new object and display it

function DisplayObject()
{
var objPerson = new Person(); // Line- 1 Creates the instance of Person
objPerson.ToString();  // Line- 2
objPerson.DisplayResidence(); // Line- 3
}

Here both display as expected . Line 2 – I am a Person and Line 3 – I stay near my office

Now let’s say we want to create a constructor Employee as

         function Employee() {
             this.ToString = function () { alert('I am an employee'); }
             this.DisplayRole = function () { alert('My role is development and implementation'); }
         }

As you can see it has two methods ToString and DisplayRole. Now how can Employee inherit the properties/methods of Person. It can be done by writing as

Employee.prototype = new Person();

Now the employee has the properties of person as well. Now it has three methods

  • ToString()
  • DisplayResidence()
  • DisplayRole()

Let’s examine it by the method

         function DisplayObject() {
                var objPerson = new Person(); // Line- 1: Calles constrouctor Person to create an instance and assign it to objPerson
                objPerson.ToString(); // Line- 2: Calles ToString method of Person
                objPerson.DisplayResidence(); // Line- 3: Calles ToString method of Person

                var objEmployee = new Employee();  // Line- 4: Calles constrouctor Employee to create an instance and assign it to objEmployee
                objEmployee.ToString(); // Line- 5: Calles ToString method of Person
                objEmployee.DisplayResidence(); // Line- 6:  Calles ToString method of Person
                objEmployee.DisplayRole(); // Line- 7:  Calles ToString method of Person

                alert(objPerson instanceof Person);  // Line- 8:  Checks the type of objPerson
                alert(objEmployee instanceof Person);  // Line- 9:  Checks the type of objEmployee
         }

Let’s discuss it by Line numbers

Line 2 and Line 3- same as discussed above

Line 5- What it will display ? It displays I am an employee because ToString is available at both current and parent. But because the objEmployee holds the instance of derived class so the overridden method is called.

Line 6- Here DisplayResidence is not defined in Employee so it calls the base class(Person) method and displayed.

Line 7-  DisplayRole is added in Employee object only and it shows ‘My role is development and implementation‘.

Line 8 – To check more on the type I added the last two lines. As objPerson is instance of Person only so it shows true.

Line 9 – As Employee inherits Person so it also shows true but if you delete the below line ….

<br />Employee.prototype = new Person();<br />

then it’ll show false as it does not inherit person any more.

Now you must have got enough Idea about prototype based inheritance in JavaScript.

There is one more way to add a method to and existing constructor as Person has two methods and  that we defined as nested class. You can write that in the following way as well

         function Person() {
         }
         Person.prototype.ToString = function () { alert('I am a Person'); }
         Person.prototype.DisplayResidence = function () {alert('I stay near my office');}

Now the question arises,  how Inheritance works in JavaScript.

Whenever we create an instance using the new Operator, It creates all the properties/methods and also has internally a variable called __proto__ (double underscore at both side) this is the variable which is responsible for the inheritance feature. So let’s say I created a instance of Employee as

var objEmployee = new Employee();

It’ll be having two methods/properties as defined and on __proto__ as

  1. ToString
  2. DisplayRole
  3. __proto__

Just because I have written also as

Employee.prototype = new Person();

The __proto__ variable gets assigned to the person instance. This __proto__ used to determine the prototype chain and return the property values. This allows us to access the base class methods and public properties.

As I talked about prototype chain, means as soon as I assign

Employee.prototype = new Person();

a proto variable gets available to us that can be be further used for inheritance. So lets create another constructor as

         function TeamLead() {
             this.ToString = function () { alert('I am a Manager.'); }
             this.DisplayRole = function () { alert('I rarely code but do lot of code reviews'); }
             this.DisplayMeetings = function () { alert('I have 3 meetings scheduled daily'); }
         }

Now as soon as I’ll create an instance using new operator then instance will be have the properties

  1. ToString
  2. DisplayRole
  3. DisplayMeetings
  4. __proto__

Now if we write the code for inheritance as

TeamLead.prototype = new Employee();

It can access all the properties in the hierarchies. We can check the type of instances as

 function DisplayObject() {
             var objTeamLead = new TeamLead();
             alert(objTeamLead instanceof Person);  // returns true because TeamLead inherits base class Person
             alert(objTeamLead instanceof Employee);  // returns true because TeamLead inherits  base class Employee
             alert(objTeamLead instanceof TeamLead); // returns true as expected
             }

You can see the results and they are expected

Let’s see the prototype chain as discussed earlier

         function DisplayObject() {
             var objTeamLead = new TeamLead();

             // Also here I'll show, How the prototype chain works
             alert(objTeamLead.__proto__ == TeamLead.prototype); // returns true because it represents the same prototype
             alert(objTeamLead.__proto__.__proto__ == Employee.prototype);  // returns true because second level __proto__ belongs to Employee.prototype
             alert(objTeamLead.__proto__.__proto__.__proto__ == Person.prototype);  // returns true because third level __proto__ belongs to Employee.prototype
         }

As you can see that actually __proto__ variable is actually the key for the inheritance.

Now you all must have got enough Idea about Prototype based programming and how we can use inheritance with JavaScript.

Do share your feedback.

Happy Coding,
Brij

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

Learning checked and unchecked context

Today, I am going to discuss about one of the rarely used but very useful keywords of C# that are called checked and unchecked context. I learnt this few days back.  These keywords can be used at certain scenarios and can save you from hazardous situations. This would be more useful when you are playing with lots of data and doing lots of operations over it.

So let’s start with a quiz. Just predict the result of the following code snippet

   int value = 5000000;
   int multiplier = 2500;
   int result = value * multiplier;
   Console.WriteLine(result);

What would be the result?
12500000000?   No

It would be -384901888. But how?

Because if you check the max value of int. It is 2147483647. Now you can see that the result of multiplication is higher than this max value. So you can think that the value displayed is min value of int. Which is certainly not desirable.

And even you would not get any overflow exception. So be cautious, while selecting the data types of variable whether it is a normal or temporary variable.

By default, Arithmetic overflow and underflow exception is turned off. You can turn it in on assembly level. For this, you can go to

Project->Properties->build tab-> advanced button. So you’ll get the following screen.

Here you can check the checkbox for arithmetic overflow/underflow and now if you run the code, you will get the OverflowException.

But this got enabled at assembly level and if you want to to have at some code snippet level then first uncheck the above marked checkbox and second you need to use the checked and unchecked keyword to have this feature.

So checked and unchecked keywords are provided for these scenarios. If you want to get exception if some values overflows or underflows.

  
   int value = 5000000;
   int multiplier = 2500;
   int result = 0;
   checked
   {
   	result = value * multiplier;
   }

So if you run the above you’ll get the overflow exception again. What actually checked does, whenever a value is assigned to primitive variable, it the checks with the variable’s max value if the value is greater/lower than the max/min value, it throws overflow/underflow exception.

The above code  that is in checked block, can also be written as

int result = checked((int)(value * multiplier));

One need to be cautious while writing checked/unchecked keyword. This code would not throw any exception.

unchecked keyword also can be used if you don’t want to have a check for overflow/underflow. the code can be written as

            int value = 5000000;
            int multiplier = 2500;
            int result = 0;
            unchecked
            {
                result = value * multiplier;
            }
            Console.WriteLine(result);

If you have enabled overflow exception check at assembly level but don’t want it at certain situations then you can use unchecked keyword.

There are few key points, one need to remember-

  • In any case, you cannot rely on user input whether you have some validation or not. So it’s always recommended that you have this check and code for handling the overflow exception. Even if you are getting from some third party services etc, then also I would recommend this check.
  • You cannot rely on the following code, generally it does not throw overflow/underflow exception.
        static void Main(string[] args)
        {
        	checked
            {
            	addition();
            }
            Console.ReadKey();
        }
    
        private static void addition()
        {
        	int value = 5000000;
        	int multiplier = 2500;
        	int result = 0;
        	result = value * multiplier;
        	Console.WriteLine(result);
        }
    

    I mean, one should write code statements in checked block. If you are calling any method from the checked/unchecked block, you cannot sure that it work as desired.

  • These checked/unchecked context works on CLR primitive types only.
  • System.Decimal is c# primitive type but not CLR. So checked/unchecked context has no effect on this.

I hope you all have enjoyed this feature if didn’t learn it earlier.

Who already aware of this feature, please share some more points that can be added here.

Cheers,
Brij

Various ways to Create custom objects in JavaScript

Hi All,

Many developers still put their data at client side in multiple variables and some times it becomes very tough to manage them. If we store the data in object format then it becomes very easy to manage and control it. We can have similar model as we use at server side, it provides consistency of the data model in our application.

So today we’ll see various ways to store the data in Object format at Client side.

A Simple way:

We can create a normal object and can encapsulate related data in a single object. To create  a simple object, you just need to assign a variable with new Object() and create the properties according to our requirement and assign the values as

 var person = new Object();
 person.FirstName = "Brij";
 person.LastName = "Mishra";
 person.Age = 27;

This is a simple object with few properties like FirstName, LastName and Age. You can read the object as

function displayObject() {
      alert(person.FirstName + " " + person.LastName);
      alert("Age: " + person.Age);
}

Here as you can see it is an object which contains the details of an person but here we didn’t define any class (as we do in C#) then we create an object assign some values in that. But we just created a object and created properties on the fly. Now obviously, while reading the object, you  might not get any intellisense on some editor and we need to remember the name of the properties. And if we wrongly typed the property name then we’ll get an error at run time.

Because JavaScript is loosely coupled language. There is no way if we create similar object and check whether they are similar type of object. Also it is impossible to identify  the object that you are using is actually of what type.

But there are more standard ways to Create a Type. We’ll discuss in coming section. First, we are going to discuss

Closure
Closure is function that encapsulate a class. Actually closure is not a normal function but it contains other functions and you can say it is a nested function. Inner functions actually constitutes its properties and methods. It provides an elegant way to create multiple instances of a type like person. It provides exactly similar behavior like class and object. Let’s create a closure

        function Person(fisrtName, lastName, age) {
            var _firstName = fisrtName;
            var _lastName = lastName;
            var _age = age;

            this.set_FirstName = function (fisrtName) {
                _firstName = fisrtName;
            }
            this.get_FirstName = function () {
                return _firstName;
            }
            this.set_LastName = function (lastName) {
                _lastName = lastName;
            }
            this.get_LastName = function () {
                return _lastName;
            }
            this.set_Age = function (age) {
                _age = age;
            }
            this.get_Age = function () {
                return _age;
            }
        }

Now let’s use the person and person instantiate it. As you can see that it is taking three parameters, fisrtName, lastName and age. So you need pass the values while instantiating it. Using it, you can create an instance similar like C# as

function DisplayClosure() {
        function DisplayClosure() {
            var person = new NewPerson("Brij", "Mishra", 27);

            alert(person.get_FirstName() + " " + person.get_LastName());
            alert("Age: " + person.get_Age());

            person.set_FirstName("Rahul");
            person.set_LastName("Khanna");
            person.set_Age("30");

            alert(person.get_FirstName() + " " + person.get_LastName());
            alert("Age: " + person.get_Age());
        }

So you can see, How I created instance. I have created a setter and getter to set and get the properties.

Lets’s discuss another way.

Prototype:

Prototypes provides another way to create custom objects in JavaScript. Every JavaScript object has public prototype property . This actually exposes the public interface of the object. Using this feature, we can add some public properties and methods to a JavaScript object. Let’s see it with example

        Person = function (firstName, lastName, age) {
            this._firstName = firstName;
            this._lastName = lastName;
            this._age = age;

            Person.prototype.set_FirstName = function (firstName) {
                this._firstName = firstName;
            }
            Person.prototype.get_FirstName = function () {
                return this._firstName;
            }
            Person.prototype.set_LastName = function (lastName) {
                this._lastName = lastName;
            }
            Person.prototype.get_LastName = function () {
                return this._lastName;
            }
            Person.prototype.set_Age = function (age) {
                this._age = age;
            }
            Person.prototype.get_Age = function () {
                return this._age;
            }
        }

So you can see that person is assigned to a function which is actually also a nested function but it is uses prototype property of an object. Lets instantiate it and check it.

function DisplayClosure() {
        function DisplayClosure() {
            var person = new NewPerson("Brij", "Mishra", 27);

            alert(person.get_FirstName() + " " + person.get_LastName());
            alert("Age: " + person.get_Age());

            person.set_FirstName("Rahul");
            person.set_LastName("Khanna");
            person.set_Age("30");

            alert(person.get_FirstName() + " " + person.get_LastName());
            alert("Age: " + person.get_Age());
        }

So you can see that this also is used in the similar way as Closure.
So what are the benefits of prototypes over closure. There are many..

  • Prototypes provide better support for Intellisense and debugging.
  • Prototypes also provide better performance in several browsers.
  • Prototypes support reflection and that’s why used a lot in ASP.NET AJAX.
  • Closure does not create an instance, it just specialized members to your object. instanceof does not work with Closure. While Prototype configured once then copied to every instance created using new.

Hope you all like it.

Cheers,
Brij

Recieved Microsoft Most Valuable Award 7th Time in a row

Hello All,

I am very happy to share you all that I have been awarded again as Microsoft Most valuable professional 7th time in a row in Visual Studio Development Technologies.

 

I want to take this opportunity to thanks all my readers, followers, seniors and friends throughout these years. It has never been possible without yourcandid feedback throughout these years.

Initially, I got this award way back in July 2011 in ASP.NET/IIS category which got changed to Visual Studio Development Technologies in 2016. This has been a long and very exciting journey and I have enjoyed each year as part of community and connecting all of you in various ways. I will try to devote more time in various community activities in coming days.

Lately, I have been focusing on ASP.NET Core related technologies and Client side technologies specifically Angular. I also published one Video Course on ASP.NET Core Web API with the association of Packt publishing in June 2016 when ASP.NET core was in nascent stage. You will see some more stuff on ASP.NET Core (MVC, Web API), Web security, Web Performance, Angular etc in coming days. Do let me if you want to see something specific here.

If you also want to know more details about this award you can refer MVP Award Home page and want to get this prestigious award then get the details from here. You can also contact me for any specific details and I will be very happy to guide you.

Thanks again to all of you for your feedback and support.

Cheers,
Brij

Creating Random number in JavaScript

Hello All

Have you ever needed to create random number in JavaScript?

No.

In C#, creating random number is simple and provides multiple options. Random class is used for the same, it’s Next method used to create random number. It also takes min and max value as parameter to create a random number in a range.

In Javascript it is more simple :). Let’s see that

Math.random is used to create a random number. But it returns a decimal numal number between between 0 (including) to 1(excluding). Let’s see that

function displayRandom()
{
    alert(Math.random());
}

It will create different number each time. So if you want to create a random number say upto 10000 then you can get it by simply writing

var randomnumber = Math.random() * 10000;

Pretty simple Right!!

But it will always create a number less than 10000 (till 9999.999..) and if you take the integer part then the max value you will get 9999. But what if want inclusive of 10000?

Then you can leverage the other method Math.ceil which generates the ceiling number as

Math.ceil(6.0001)

Math.ceil(6.203)

Math.ceil(6.0001)

Math.ceil(6.9001)

For all you will get 7. So if you write the original method as

function displayRandom()
{
    alert(Math.ceil(Math.random()));
}

You will get the number between 0 to 10000 both inclusive. You can also use Math.floor or Math.abs to have your own logic for getting random number in a range.

This is small post but I found it bit interesting and useful sometime.

Cheers,
Brij

.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

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