Friday, December 2, 2016

Deconstructors in C# 7

With the release of Visual Studio 2017 RC, you can now explore the upcoming C# 7 features. In this post let’s see how you can use Deconstructors in C# 7.

Please do not get confused in Deconstructors with Destructors as Destructors has nothing to with Deconstructors.

Basically what a Constructor would do is, it will create a new object of given type with given parameters (here I am opting out the default constructor as it has no parameters). So what the Deconstructor would do is, it will deconstruct the object back into it’s original parts. To be specific, you have the control of specifying how would you like the object to be deconstructed.

Let’s go by an example. Here I have a class named Employee, and there is a Constructor which accepts two parameters, First Name & Last Name, and those are being set to Employee’s properties. (Please note that as of today no errors are thrown by the compiler if you have a return type other than void in Deconstructor methods. In other words current Deconstructors lets you return values even though it doesn't make any sense. Microsoft is aware of this and they will get it fixed in the coming releases.)
public class Employee
{
    public string FirstName { get; }
    public string LastName { get; }
 
    public Employee(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = LastName;
    }
}
Above code is pretty simple. And now let’s see how we can add a Deconstructor to Employee.
public class Employee
{
    public string FirstName { get; }
    public string LastName { get; }
 
    public Employee(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = LastName;
    }
 
    public void Deconstruct(out string firstName, out string lastName)
    {
        firstName = FirstName;
        lastName = LastName;
    }
}
It’s simple, isn’t it. The only thing we need to have is, we should have a public void method named Deconstruct and one or more properties that I want the object to be deconstructed into, should be specified as out parameters.

Now let’s see how we can call the Deconstructor.
Employee employee = new Employee("Jaliya", "Udagedara");
var (firstName, lastName) = employee;
 
Console.WriteLine(firstName);
Console.WriteLine(lastName);
Here something to note is Deconstructor is being invoked by C# 7 Tuple syntax. If you are not aware about the Tuples in C# 7, please read this previous post of mine.

And the following will be the output.
image
Output
And the nice thing is, you can have multiple Deconstructors with different parameters (that’s basically method overloading).
public void Deconstruct(out string firstName, out string lastName)
{
    firstName = FirstName;
    lastName = LastName;
}
 
public void Deconstruct(out string firstName)
{
    firstName = FirstName;
}
The respective Deconstructor invocations are as follows.
// first deconstructor invocation
var (firstName, lastName) = employee;
 
// second deconstructor invocation
var (firstName1) = employee; 
If you still couldn’t download Visual Studio 2017 RC, download and try out these new C# 7 features.

Happy Coding.

Regards,
Jaliya

Thursday, December 1, 2016

Response Compression Middleware in ASP.NET Core

Response Compression is if client browser supports response compression, the server sends the content compressed, so the response size is  reduced. There are couple of compression schemes, but almost all the browsers supports gzip and deflate. In this post let’s see how you can use Response Compression Middleware in an ASP.NET Core application to serve the content compressed using gzip.

I am going to use Visual Studio 2017 RC and let’s create an ASP.NET Core Web Application targeting .NET Core and I am selecting the template as Web API as I want to simulate large content being sent to the client.

Once the project is created and all the dependencies are restored, let’s update all our dependencies to ASP.NET Core 1.1. Please note that Visual Studio 2017 RC targets ASP.NET Core 1.0.1 for it’s default ASP.NET Core templates as it’s the LTS (Long Term Support) version as of now.
image
Update Nuget Packages
Once update is completed, let’s modify Get() action in default ValuesController to return some large set of data.
[HttpGet]
public IEnumerable<string> Get()
{
   List<string> someStrings = new List<string>();
   for (int i = 0; i < 100000; i++)
   {
       someStrings.Add($"Value{i}");
   }
 
   return someStrings;
}
Now let’s just run the application, trigget Get() action in ValuesController and explore the request and response information.

First if we examine the request headers, it looks likes follows.
image
Request and Reponse Headers
I am using Chrome and it seems that my current version of Chrome supports set of compression types. But in the response there was no indication the content which got received is compressed.
image
Response Size
Size of the content received is 1.2 MB.

Now let’s add some code to send the content compressed using gzip. Let’s add a new nuget package to the project and that is Microsoft.AspNetCore.ResponseCompression.
image
Install Microsoft.AspNetCore.ResponseCompression
Now let’s modify the ConfigureServices method and Configure method in startup.cs to add and use Response Compression Middleware.
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddResponseCompression(options =>
       {
           options.Providers.Add<GzipCompressionProvider>();
       });
    services.AddMvc();
  
}
 
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();
 
    app.UseResponseCompression();
    app.UseMvc();
}
You will need to add the following using.
using Microsoft.AspNetCore.ResponseCompression;
Now let’s run the application again, trigget Get() action in ValuesController and examine the request and response.
image
Request and Reponse Headers
Request is obviously the same and now you can see that response is being compressed using gzip.
image
Response Size
And this time only 238 KB was transferred. 1.2 MB has been reduced to 238 KB.

Happy Coding.

Regards,
Jaliya

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

Tuesday, November 22, 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

Monday, October 10, 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

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