Tuesday, May 27, 2014

Language Features in Up Coming C# 6.0 (Build 2014)

I am so excited to write this post in which I am going to explain the upcoming language features of  C# 6.0 which was announced in Microsoft Build 2014 Conference last month. To give you a surprise, to try these language features, you don’t have to wait until C# 6 is officially released. Once you download the Roslyn Preview and install it in your machine, you are ready to write C# 6.0 code.

If you haven’t heard about the C# 6.0 new language features already, I am sure you must be feeling excited to see those. So let’s dive in.

1. Using static

This feature allows specifying a type in a using clause, making all the accessible static members of the type available without qualification in subsequent code:
using System.Console; 

class Program
{
    static void Main(string[] args)
    {
        WriteLine("Hello C# 6.0");
    }
}
While this making our code shorter, it increases the risk of ambiguity. So you should be using this carefully.

2. Initializers for auto-properties

You can now add an initializer to an auto-property, just as you can to a field.
public class Employee
{
   public string FirstName { get; set; } = "Jaliya";
   public string LastName { get; set; } = "Udagedara";
}
The initializer directly initializes the backing field; it doesn’t work through the setter of the auto-property. So it now makes sense to have auto-properties without setters.
public class Employee
{
    public string FirstName { get; } = "Jaliya";
    public string LastName { get; } = "Udagedara";
}
But now there is another problem. Getter-only auto-properties would seem kind of useless if they couldn’t somehow acquire values passed in to constructors of the object. For this reason, now comes the concept of Primary Constructors.

3. Primary Constructor

Primary constructors allow constructor parameters to be declared directly on the class or struct, without an explicit constructor declaration in the body of the type declaration. These parameters are in scope as simple names for initialization throughout the whole class declaration.
3.1. Parameters on classes and structs
Here’s an example of a class with a primary constructor.
public class Employee(string firstName, string lastName)
{
    public string FirstName { get; set; } = firstName;
    public string LastName { get; } = lastName;
}
To achieve the same without primary constructors, we would have to write the code in the following way.
public class Employee
{
    private string firstName;
    public string FirstName
    {
        get
        {
            return firstName;
        }
    }

    private string lastName;
    public string LastName
    {
        get
        {
            return lastName;
        }
    }
 
    public Employee(string firstName, string lastName)
    {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}
Now you can see with the introduction of primary constructors, we don’t have declare primary variables and write all those lines of code.
3.2. Field Parameters
By default, a Primary Constructor parameters are only around at initialization time. Function members such as properties and methods cannot refer to it, because by the time they are called, the object has been constructed and the parameter is gone.

For an example, consider the following code.
public class Employee(string firstName, string lastName, DateTime birthday)
{
    public string FirstName { get; } = firstName;
    public string LastName { get; } = lastName;
    public int Age
    {
        get
        {
            return (DateTime.Now.Year - birthday.Year);
        } 
    }
}
Here I am getting the error, “Parameters of a primary constructor can only be accessed in instance variable initializers and arguments to the base constructor.”. And for that you can declare private variable and initialize it with the parameter.
public class Employee(string firstName, string lastName, DateTime birthday)
{
   public string FirstName { get; } = firstName;
   public string LastName { get; } = lastName;
 
   private DateTime _birthday = birthday;
   public int Age
   {
       get
       {
           return (DateTime.Now.Year - _birthday.Year);
       }
   }
}
Unfortunately the private field wouldn’t be able to use the same name as the parameter, and needs some other name.

And for that C# 6 introduces, Field Parameters.
public class Employee(string firstName, string lastName, private DateTime birthday)
{
    public string FirstName { get; } = firstName;
    public string LastName { get; } = lastName;
    public int Age
    {
        get
        {
            return (DateTime.Now.Year - birthday.Year);
        }
    }
}

4. Declaration Expressions

I would say, this is one of my favorite feature in the up coming C# 6.0. Consider the following example.
int i;
if (Int32.TryParse("10", out i))
{
    Console.WriteLine(i);
}
Only for the out parameter, we had to declare a variable in a separate line. But not any more.
if (Int32.TryParse("10", out int i))
{
    Console.WriteLine(i);
}
And also, we don’t have to specifically say it’s an int. We can use var and compiler will understand and will be treated var as an int here.
if (Int32.TryParse("10", out var i))
{
    Console.WriteLine(i);
}

5. Indexed members and element initializers

Let’s take the following Dictionary collection initializer written using C# 5.0.
Dictionary<string, string> myDictionary = new Dictionary<string, string>()
{
  {"a", "Apple"},
  {"o", "Orange"},
};
Let’s say I want to access an item in the dictionary, this is how I would do it.
Console.WriteLine(myDictionary["a"]);
C# 6.0 has this new syntax to initialize objects allowing you to set values to keys through any indexer that the new object has.
Dictionary<string, string> myDictionary = new Dictionary<string, string>()
{
   ["a"] = "Apple",
   ["o"] = "Orange",
};
Not only that, there is this new syntax for “indexed members”, which let you pretend that a literal string key is a sort of member.
Dictionary<string, string> myDictionary = new Dictionary<string, string>()
{
    $a = "Apple",
    $o = "Orange",
};
You can access the elements using the same syntax.
Console.WriteLine(myDictionary.$a);

6. Await in catch and finally blocks

In C# 5.0 the await keyword cannot be used in catch and finally blocks. In C# 6.0, you can.
Resource res = null;

try
{
    res = await Resource.OpenAsync(…);       // You could do this.
}
catch (ResourceException e)
{
    await Resource.LogAsync(res, e);         // Now you can do this …
}
finally
{
    if (res != null) await res.CloseAsync(); // … and this.
}

7. Binary literals and digit separators

Binary literals will be allowed in C# 6.0.
var bits = 0b00101110;
For long literals (and these new binary ones can easily get long!) being able to specify digits in groups also seems useful. C# will allow an underscore ‘_’ in literals to separate such groups:
var bits = 0b0010_1110;
var hex = 0x00_2E;
var dec = 1_234_567_890;
You can put as many as you want, wherever you want, except at the front.

8. Exception filters

VB has them. F# has them. Now C# has them too. This is what they look like:
try
{ … }
catch (MyException e) if (myfilter(e))
{
}
If the parenthesized expression evaluates to true, the catch block is run, otherwise the exception keeps going. Exception filters are preferable to catching and re throwing because they leave the stack unharmed. If the exception later causes the stack to be dumped, you can see where it originally came from, rather than just the last place it was re thrown.

So that's it. Hope you all find this these new language features interesting. If you are, please leave your feedback to Microsoft.

Happy Coding.

Regards,
Jaliya

Monday, May 26, 2014

Introduction to .NET Native

In Microsoft Build 2014 Conference, Microsoft has announced the first release of .NET Native. So what is this “.NET Native”?. In this post we are going to find out what.

In simple .NET Native is Microsoft's newest compiler or rather a pre compilation technology for building and deploying Windows Store apps. Typically, apps that target the .NET Framework are compiled to intermediate language (IL). At run time, the IL gets translated in to native code using the just-in-time (JIT) compiler or Native Image Generator (Ngen.exe). In contrast, .NET Native compiles Windows Store apps directly to native code.

In deep, .NET Native do more than just compiling Windows Store App to native code. It transforms the way that .NET Framework apps are built and executed. In particular:
  • During precompilation, required portions of the .NET Framework are statically linked into your app. This allows the app to run with app-local libraries of the .NET Framework, and the compiler to perform global analysis to deliver performance wins. As a result, apps launch consistently faster even after .NET Framework updates.
  • The .NET Native runtime is optimized for static precompilation and thus is able to offer superior performance. At the same time, it retains the core reflection features that developers find so productive.
  • .NET Native uses the same back end as the C++ compiler, which is optimized for static precompilation scenarios.
.NET Native is able to bring the performance benefits of C++ to managed code developers because it uses the same or similar tools as C++ under the hood.

So at a glance what’s the benefit of using .NET Native. In simple .NET Native offers you the performance of C++ with the productivity of C#. Windows Store apps which are compiled with .NET Native start up to 60% faster with .NET Native and have a much smaller memory footprint.

Download the .NET Native Developer Preview 2 and try it out on your Windows Store apps. Make sure you have Visual Studio 2013 Update 2 installed as the .NET Native Developer Preview 2 installs on Visual Studio 2013 Update 2.

Read more about .NET Native,

Happy Coding.

Regards,
Jaliya

Sunday, May 25, 2014

Session : Universal Apps for Windows Devices at H One, Sri Lanka

Last Friday delivered a session titled “Universal Apps for Windows Devices” for Windows Store and Windows Phone developers at H One Pvt Ltd, Sri Lanka.

The session was very interesting. The session started introducing the latest technologies which are now being used to develop apps for Windows 8.1 and Windows Phone 8.1. Then went back to explaining the concepts of “Build for Both” describing the features such as “Add as Link”, “using #if – endif directives”, “Use of partial classes and abstraction classes” and “Portable Class Libraries” etc. After demoing those features then moved into the introduction of Visual Studio 2013 Update 2.

There, I have demoed the features like new Universal Apps template, context switcher in the editor etc. Then moved to the end of the session demoing creating a new blank Universal App, explaining the new project structure writing some code.



Happy Coding.

Regards,
Jaliya

Monday, May 19, 2014

Visual C# Technical Guru - April 2014

March, 2014 was not a good month for me in TechNet Guru Awards. Managed to become Visual C# Technical Guru couple of months before and in March this year, couldn’t have that pleasure.  In the month of April, 2014, Managed to become third in Visual C# Technical Guru Awards.

The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Post in WikiNinjas Official Blog,
image
Visual C# Technical Guru - April 2014.
Got some encouraging comments from the judges and looking forward to make my next wikis very informative.

Happy Coding.

Regards,
Jaliya

Friday, May 16, 2014

Check Whether a Particular Folder Exists in Your OneDrive Using Live SDK

This is a quick post on how you can check whether a particular folder exists in your OneDrive using Live SDK. My requirement here was, for one of my Windows Phone 8 applications, I needed to check whether a particular folder exists in my OneDrive. Following is a very simple method for that.
private static async Task<string> CheckIfFolderExistsAsync(LiveConnectClient client, string folderName)
{
    LiveOperationResult operationResult = await client.GetAsync("me/skydrive/files?filter=folders,albums");
    dynamic result = operationResult.Result;
 
    foreach (var item in result.data)
    {
        if (item.name == folderName)
        {
            return item.id;
        }
    }
    return string.Empty;
}

If a folder exists under given name, it will return the id of the folder and if not, an empty string will be returned.

Happy Coding.

Regards,
Jaliya

Wednesday, May 7, 2014

Entity Framework Code First - Defining Foreign Keys using Data Annotations and Fluent API

When using Entity Framework Code First approach, there are actually three ways to define foreign keys. In this post let’s explorer these different ways with some examples (Please note here I am not going to cover the basics of EF, assuming you have some knowledge in Entity Framework.) . Before starting off with the code, first let’s have a quick look at the mentioned three different ways.

First way is pretty much straight forward. That is when you add a navigation property, EF it self will create a foreign key relationship. The second one is using Data Annotations. The last would be using Fluent API.

Now let's see all these in action. Please consider the following two entity classes.
public class Department
{
    public int DepartmentId { get; set; }
    public string DepartmentName { get; set; }
}
 
public class Employee
{
    public int EmployeeId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Department Department { get; set; }
}
Here I have two classes which are “Department” and “Employee”. In “Employee” class, I have a navigation property named “Department” which is of type “Department”. So here what I says is Employee is belonging to a Department.

I have the following “MyContext” class which inherits from DbContext.
public class MyContext : DbContext
{
    public DbSet<Department> Departments { get; set; }
    public DbSet<Employee> Employees { get; set; } 

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}
There in my overrided OnModelCreating method, I am saying that I don’t want to pluralize the table names when tables are created in EF. (You can basically ignore that particular line of code, as it has nothing to with the topic today).

Now in my Main method, I am writing the following code to add some data to “Department” table, so the tables will get generated.
static void Main(string[] args)
{
    using (MyContext context = new MyContext())
    {
        context.Departments.Add(new Department() { DepartmentName = "Microsoft Visual Studio" });
        context.SaveChanges();
    }
}
Once I run the code and check the database created, I can see the following.
Picture1
Through Navigation Property
In the “Employee” table, you can see there is a foreign key created named “Department_DepartmentId”. So that is the first way.

Now let’s have a look at defining the foreign key using Data Annotations.

For that, I am going to modify the “Employee” class as follows.
public class Employee
{
    public int EmployeeId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int DepartmentId { get; set; }
 
    [ForeignKey("DepartmentId")]
    public Department Department { get; set; }
}
Here I have defined a property of type int named “DepartmentId”. And I have annotated my “Department” property saying that Foreign key is newly added “DepartmentId”. I am deleting the previous database and running the program back again. Now I can see the following database structure.
Picture2
Through Data Annotations
Now let’s have a look the third and final way which is defining the foreign key using Fluent API.

In “MyContext” class I am modifying the OnModelCreating() method as follows and I am removing my Data Annotations in the "Department" class.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
 
    modelBuilder.Entity<Employee>()
        .HasRequired(e => e.Department)
        .WithMany()
        .HasForeignKey(e => e.DepartmentId); 
}
Again I am deleting the previous database and running the program back again. When I examine the created the database now, It’s as same as the previous method.
Picture2
Through Fluent API
So hope you find this post helpful. I am uploading the sample to my OneDrive. Do check it out and appreciate your feedback.


Happy Coding.

Regards,
Jaliya