Wednesday, November 30, 2016

Visual C# Technical Guru - October 2016

Another month as a judge in Microsoft TechNet Guru Awards under Visual C# category. The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Post in WikiNinjas Official Blog,
image
Visual C# Technical Guru - October 2016
Happy Coding.

Regards,
Jaliya

Wednesday, November 23, 2016

Where is project.json in Default .NET Core Application Templates in Visual Studio 2017

As you might already know the Release Candidate of the next version of Visual Studio is released and that is Visual Studio 2017 (It was known as Visual Studio 15 until it was officially named as Visual Studio 2017). If you still couldn’t check it out, download and give it a try.

After downloading and installing, and if you create any .NET Core application (for instance an ASP.NET Core Web Application), you might see that project.json is missing.
image
No project.json
project.json used to be the key file in a .NET Core project, as it was where all the project dependencies, compilation information (targeted .NET Core versions etc.) etc. were maintained.

So now you might be wondering, if we don’t have the project.json, where are all those information defined and maintained. And those are moved back to .csproj file of the project. This change was announced couple of months back (May, 2016 to be specific).

And one important thing, in previous versions of Visual Studio, you need to unload the project first to edit it’s .csproj file. With Visual Studio 2017, you don’t have to do that, just right click on the project and click on Edit {ProjectName}.csproj.
image
Edit {ProjectName}.csproj
And when the file is opened, you can find all the information you are looking for.

Happy Coding.

Regards,
Jaliya

Friday, October 21, 2016

Visual C# Technical Guru - September 2016

Another month as a judge in Microsoft TechNet Guru Awards under Visual C# category. The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Post in WikiNinjas Official Blog,
image
Visual C# Technical Guru - September 2016
Happy Coding.

Regards,
Jaliya

Tuesday, October 11, 2016

Tuples in C# 7

Tuples has been there since the release of .NET 4.0 and it was mostly used for returning more than one value from a method. With C# 7.0, there are couple of new improvements coming around Tuples. Let’s see what those are.

Before C# 7, use of Tuples basically is as follows.
static void Main(string[] args)
{
    List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };
    var values = GetValues(numbers);
    Console.WriteLine($"min:{values.Item1}, max:{values.Item2}, sum:{values.Item3}");
}
 
static Tuple<int, int, int> GetValues(List<int> numbers)
{
    return new Tuple<int, int, int>(numbers.Min(), numbers.Max(), numbers.Sum());
}
So what's not so good with this? First you need to create a new instance of a Tuple before returning. Then you can’t name the single elements, thus you are limited to access the returned elements by Item1, Item2 etc.

With C# 7, following is possible.
static void Main(string[] args)
{
    List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };
    var values = GetValues(numbers);
    Console.WriteLine($"min:{values.min}, max:{values.max}, sum:{values.sum}");
}
 
static (int min, int max, int sum) GetValues(List<int> numbers)
{
    return (numbers.Min(), numbers.Max(), numbers.Sum());
}
Here you can specify the names for the individual elements inside the returning Tuple and no object creation is needed. If you are comfortable with no names, you can still omit the names and access elements by Item1, Item2 etc.
static (int, int, int) GetValues(List<int> numbers)
{
    return (numbers.Min(), numbers.Max(), numbers.Sum());
}
Or you can always me more specific.
static (int min, int max, int sum) GetValues(List<int> numbers)
{
    return (min: numbers.Min(), max: numbers.Max(), sum: numbers.Sum());
}
You can even use some other names when you are declaring the Tuple and doing the deconstruction.
var (_min, _max, _sum) = GetValues(numbers);
(var _min, var _max, var _sum) = GetValues(numbers);
Isn’t that great?

And do keep monitoring what's happening on C# 7,
https://github.com/dotnet/roslyn/issues/2136

Happy Coding.

Regards,
Jaliya

Saturday, October 1, 2016

Visual C# Technical Guru - August 2016

Another month as a judge in Microsoft TechNet Guru Awards under Visual C# category. The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Post in WikiNinjas Official Blog,
image
Visual C# Technical Guru - August 2016
Happy Coding.

Regards,
Jaliya

Thursday, September 29, 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

Wednesday, September 28, 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.

One key difference to keep in mind though. In LINQ to SQL, when running against a IQueryableFirst()/FirstOrDefault() will be issuing a SELECT TOP (1) query,  while Single()/SingleOrDefault() issues a SELECT TOP (2). That is because in Single()/SingleOrDefault(), it needs to see whether there are more than one record which matches the given 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

Friday, September 23, 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