Friday, September 30, 2016

Why is it Important to Understand JavaScript Hoisting

Before moving on with the post, just consider the following very simple JavaScript code.
x = 5;
var x;
console.log(x);
If you think the above code will give an error, then I am sorry, you might not know what JavaScript Hoisting is. Above will print "5" to the console without any errors. The reason is Hoisting in JavaScript.

Basically JavaScript Hoisting is moving declarations to the top while the JavaScript Interpretation. Even though you have written you code like above, following is what actually gets executed.
var x;
x = 5;
console.log(x);
Notice that declaration of x is being moved to the top.

Now let's take a look at what's Hoisting’s effect on functions. Consider the following code. Here I have two functions, one is a function declaration and the other is a function expression.
foo();
bar();
 
function foo() {
    console.log("foo");
};
 
var bar = function() {
    console.log("bar");
};
Here if you run this, "foo" will be printed on the console, and then when the call to bar() is getting executed, it will throw TypeError: bar is not a function. What’s happening here is again Hoisting. What is getting executed is the following code.
var bar;
 
function foo() {
    console.log("foo");
};
 
foo();
bar();
 
bar = function() {
    console.log("bar");
};
Here is also the declarations has moved to the top.

Now I hope you figured why it is so important to understand this little but very critical concept.

Happy Coding.

Regards,
Jaliya

Tuesday, September 27, 2016

Use of First(), FirstOrDefault() and Single(), SingleOrDefault()

In this post let’s see the difference between Enumerable.First() and Enumerable.Single() and of course with there null handling counter parts which are Enumerable.FirstOrDefault() and Enumerable.SingleOrDefault().

Let’s go by a very simple example. Consider the following Employee POCO class and a List<Employee>. For the sake of argument, let’s say Id is a primary key and cannot be duplicated.
public class Employee
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
List<Employee> employees = new List<Employee>()
{
   new Employee()
   {
       Id = 1,
       FirstName = "Jaliya",
       LastName = "Udagedara"
   },
   new Employee()
   {
       Id = 2,
       FirstName = "John",
       LastName = "Smith"
   }
};
Now imagine, I want to get the Employee who is having a particular Id. In this case, I can use either First() or Single().
employee = employees.First(e => e.Id == 1);
employee = employees.Single(e => e.Id == 1);
Technically there is nothing wrong using either of them, but practically or in the best practice perspective, it’s ideal to use Single() instead of First(). Because when we say First(), it means that out of set of matching rows, I am interested in the First() item. But in our case, we know that there can only be one Employee having a particular IdFirstOrDefault() and SingleOrDefault() are just null handling counter parts of First() and Single(). Basically what it will do is, it will return null if no matching record is found, where as First() and Single() will throw System.InvalidOperationException: Sequence contains no matching element when no matching record is found.

Now consider the following example where I want to get the Employee whose FirstName starts with a particular letter/word (well, it's not a ideal scenario, but again for the sake of argument).
employee = employees.First(e => e.FirstName.StartsWith("J"));
employee = employees.Single(e => e.FirstName.StartsWith("J"));
Here using First()/FirstOrDefault() is the ideal approach as there can be many employees whose FirstName starts with a particular letter/word. But use of Single()/SingleOrDefault() in such scenario will throw System.InvalidOperationException: Sequence contains more than one matching element as there can be many rows which matches that criteria.

So what to get from this? Always use Single()/SingleOrDefault() if you know that there can be only one record which matches the given criteria as that will improve the code readability. Use First()/FirstOrDefault() if you know that there can be many records which matches the criteria and you are only interested in the first record.

Hope this helps.

Happy Coding.

Regards,
Jaliya

Thursday, September 22, 2016

List<T> Vs. IEnumerable<T> Vs. IQueryable<T> in Data Retrieval

(Couple of years back I wrote this post about IEnumerable<T> Vs. IQueryable<T> and I suggest you reading that as well as I will not be explaining what I written there over in this post.)

In this post let’s see a very important difference between List<T> and IEnumerable<T> and IQueryable<T> in Data Retrieval.

Basically I am sure you already know List<T> is a class and IEnumerable<T> and IQueryable<T> are interfaces. List<T> implements IEnumerable<T> along with some other interfaces, but it doesn’t implement IQueryable<T>. IQueryable<T> implements IEnumerable<T>.

Let’s consider the following code sample. Please note that here I am using EF and SQL Server Data Source(AdventureWorks sample database).
using (AdventureWorks2014 context = new AdventureWorks2014())
{
    List<Employee> lMales = context.Employees.Where(c => c.Gender == "M").ToList();
}
When you run this, a SELECT query (with a WHERE condition of course) will get executed on the underlined database.

Now if take the IEnumerable<T> and IQueryable<T> version, it’s as follows.
using (AdventureWorks2014 context = new AdventureWorks2014())
{
    IEnumerable<Employee> eMales = context.Employees.Where(c => c.Gender == "M").AsEnumerable();
    IQueryable<Employee> qMales = context.Employees.Where(c => c.Gender == "M");
}
Here when you run this, still no query will get executed against the database and that’s because IEnumerable<T> and IQueryable<T> has deferred execution. You need to either iterate through or do a ToList().

Let’s consider the following scenario. Let’s add another Where on eMales which is of type IEnumerable<T> and take it into a List<T> and see how the underlined query looks like.
List<Employee> maleSingles = eMales.Where(c => c.MaritalStatus == "S").ToList();
SELECT 
    [Extent1].[BusinessEntityID] AS [BusinessEntityID], 
    [Extent1].[NationalIDNumber] AS [NationalIDNumber], 
    [Extent1].[LoginID] AS [LoginID], 
    [Extent1].[OrganizationLevel] AS [OrganizationLevel], 
    [Extent1].[JobTitle] AS [JobTitle], 
    [Extent1].[BirthDate] AS [BirthDate], 
    [Extent1].[MaritalStatus] AS [MaritalStatus], 
    [Extent1].[Gender] AS [Gender], 
    [Extent1].[HireDate] AS [HireDate], 
    [Extent1].[SalariedFlag] AS [SalariedFlag], 
    [Extent1].[VacationHours] AS [VacationHours], 
    [Extent1].[SickLeaveHours] AS [SickLeaveHours], 
    [Extent1].[CurrentFlag] AS [CurrentFlag], 
    [Extent1].[rowguid] AS [rowguid], 
    [Extent1].[ModifiedDate] AS [ModifiedDate]
FROM [HumanResources].[Employee] AS [Extent1]
WHERE N'M' = [Extent1].[Gender]
You can see that on there WHERE condition has only Gender related condition but nothing on MaritalStatus. So here what’s happening is, it will first select the males into the memory and then select singles from there. Not so efficient.

Now let’s add the Where on qMales which is of type IQueryable<T> and take it into a List<T> and see how the query looks like.
List<Employee> maleSingles = qMales.Where(c => c.MaritalStatus == "S").ToList();
SELECT 
    [Extent1].[BusinessEntityID] AS [BusinessEntityID], 
    [Extent1].[NationalIDNumber] AS [NationalIDNumber], 
    [Extent1].[LoginID] AS [LoginID], 
    [Extent1].[OrganizationLevel] AS [OrganizationLevel], 
    [Extent1].[JobTitle] AS [JobTitle], 
    [Extent1].[BirthDate] AS [BirthDate], 
    [Extent1].[MaritalStatus] AS [MaritalStatus], 
    [Extent1].[Gender] AS [Gender], 
    [Extent1].[HireDate] AS [HireDate], 
    [Extent1].[SalariedFlag] AS [SalariedFlag], 
    [Extent1].[VacationHours] AS [VacationHours], 
    [Extent1].[SickLeaveHours] AS [SickLeaveHours], 
    [Extent1].[CurrentFlag] AS [CurrentFlag], 
    [Extent1].[rowguid] AS [rowguid], 
    [Extent1].[ModifiedDate] AS [ModifiedDate]
FROM [HumanResources].[Employee] AS [Extent1]
WHERE (N'M' = [Extent1].[Gender]) AND (N'S' = [Extent1].[MaritalStatus])
And here you can see that the WHERE condition contains both Gender and MaritalStatus.

And if we go further more on IQueryable<T> for something like below,
List<Employee> maleSingleAccountants = qMales
    .Where(c => c.MaritalStatus == "S")
    .Select(e => new
    {
        NationalIDNumber = e.NationalIDNumber,
        JobTitle = e.JobTitle,
    })
    .Where(e => e.JobTitle == "Accountant").ToList();
And following is the underlined query.
SELECT 
    1 AS [C1], 
    [Extent1].[NationalIDNumber] AS [NationalIDNumber], 
    [Extent1].[JobTitle] AS [JobTitle]
FROM [HumanResources].[Employee] AS [Extent1]
WHERE (N'M' = [Extent1].[Gender]) AND (N'S' = [Extent1].[MaritalStatus]) AND (N'Accountant' = [Extent1].[JobTitle])
If we did this on eMales which is of type IEnumerable<T>, it will be selecting the all males with their all properties (like last IEnumerable<T> example) from the database, and do the rest in memory. But here IQueryable<T> is smart enough to combine all the Wheres and only Select what is projected.

Isn’t that great. I am sure with right use of these, you can make your code more efficient.

So hope this helps.

Happy Coding.

Regards,
Jaliya

Wednesday, September 14, 2016

Wrote a post on Wiki Life at Official Blog of TechNet Wiki

Wrote a post in Wiki Ninjas - Official Blog of TechNet Wiki. The title of the post is TNWiki Article Spotlight - ASP.NET Core 1.0 RC2 and Angular 2 using WEB API.
image
TNWiki Article Spotlight - ASP.NET Core 1.0 RC2 and Angular 2 using WEB API
Read the rest on,
TNWiki Article Spotlight - ASP.NET Core 1.0 RC2 and Angular 2 using WEB API

Happy Coding.

Regards,
Jaliya

Tuesday, September 6, 2016

C# Conditional Attribute and #if Directive

In this post let’s see the use of Conditional attribute and how it differs from #if directive.

It’s always best to go by an example. Consider the following.

Example 1
using System;
using System.Diagnostics;
 
namespace ConditionalAttributeDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            SayHello1();
        }
 
        static void SayHello1()
        {
            Console.WriteLine("Hello World 1");
        }
    }
}
It’s more than simple. If we run this “Hello World 1” will be printed on console. Now imagine that I want the method to be run only when a given condition satisfies. I know you can think of variety of ways to achieve that. But here the condition is based on a compilation symbol (DEBUG etc.).

Now let’s modify the code adding a compilation symbol named SOMETHING.

Example 2
#define SOMETHING
 
using System;
using System.Diagnostics;
 
namespace ConditionalAttributeDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            SayHello1();
        }
 
        [Conditional("SOMETHING")]
        static void SayHello1()
        {
            Console.WriteLine("Hello World 1");
        }
    }
}
Now if we run this application, again "Hello World 1" will be printed on the console. And if we commented out the first line "#define SOMETHING", SayHello1() method will not get called thus the application will not print anything. It’s basically because the condition fails.

Now as you might aware, I can do the same using #if directive. Let’s modify the code to use #if.

Example 3
#define SOMETHING
 
using System;
 
namespace ConditionalAttributeDemo
{
    class Program
    {
        static void Main(string[] args)
        {
#if SOMETHING
            SayHello1();
#endif
        }
 
        static void SayHello1()
        {
            Console.WriteLine("Hello World 1");
        }
    }
}
This will print “Hello World 1” and if we commented out the SOMETHING symbol, SayHello1() method will not get called. It’s basically Just as in Example 2. So now you must be wondering what’s the difference between Conditional attribute and #if directive. Let’s move on.

The first difference is, when you use #if, the code which is wrapped between #if and #endif, will only get compiled if the condition next to #if is true. Basically you can write almost anything within the #if and #endif and as long the condition is false, it will not throw any compilation errors (even if there are any).

The second and most important difference is, how IL is emitted in both these scenarios. When you use #if, the IL for code within the #if and #endif, will only get emitted if the given condition is true. Where as when you use Conditional attribute, IL will be emitted based on the method calls. Confused?, let’s go by the example. Let me modify the code to use both Conditional attribute and #if, and then let’s compare the IL which gets generated.

Example 4
#define SOMETHING
 
using System;
using System.Diagnostics;
 
namespace ConditionalAttributeDemo
{
    class Program
    {
        static void Main(string[] args)
        {
#if SOMETHING
            SayHello1();
#endif
            SayHello2();
        }
 
        static void SayHello1()
        {
            Console.WriteLine("Hello World 1");
        }
 
        [Conditional("SOMETHING")]

        static void SayHello2()
        {
            Console.WriteLine("Hello World 2");
        }
    }
}
Now after compiling the code, let’s see what the generated IL is (here I am using ildasm.exe).

image
ildasm.exe
Here let’s see what we have for Main() method.

image
IL for Main()
You can see that IL is generated for two method calls SayHello1() and SayHello2(). Now let’s commented out the compilation symbol SOMETHING, compile the code and examine the emitted IL back again.

image
IL for Main()
Now there is nothing on SayHello1() and SayHello2() method calls in Main() method. Still no difference. Let’s come to this later in the post again.

Now let’s modify the code further as below.

Example 5
//#define SOMETHING
 
using System;
using System.Diagnostics;
 
namespace ConditionalAttributeDemo
{
    class Program
    {
        static void Main(string[] args)
        {
#if SOMETHING
            SayHello1();
#endif
            SayHello2();
        }
 
        static void SayHello1()
        {
            Console.WriteLine("Hello World 1");
            SayHello3();
        }
 
        static void SayHello2()
        {
            Console.WriteLine("Hello World 2");
            SayHello3();
        }
 
        [Conditional("SOMETHING")]
        static void SayHello3()
        {
            Console.WriteLine("Hello World 3");
        }
    }
}
Take a note that, I have the first line commented out (otherwise, there won’t be any difference). Now let’s compile and examine the IL on Main() method back again.

image
IL for Main()
And now, you should be able to see a clear difference. There is nothing on SayHello1() method call, but you can see the IL code for SayHello2() method call.

The reason is, now the call to our conditional method (SayHello3()) is done through intermediate method (SayHello2()). And you can see, even if I use the same approach in #if scenario, but still no IL was generated for that.

And now the reason for IL code to be same on Example 4 is, in that case we were directly calling a conditional method (SayHello2()) from the Main() method. And since the condition is false, compiler knows it can’t call the SayHello2(). Because of that no IL code is generated for conditional (SayHello2()) method call.

Hope this post gives you a clear understanding on Compilation attribute and it’s difference between #if directive.

Happy Coding.

Regards,
Jaliya