Pages

Tuesday, May 27, 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

{

staticvoid 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.

publicclass Employee

{

publicstring FirstName { get; set; } = "Jaliya";

publicstring 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.

publicclass Employee

{

publicstring FirstName { get; } = "Jaliya";

publicstring 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.

publicclass Employee(string firstName, string lastName)

{

publicstring FirstName { get; set; } = firstName;

publicstring LastName { get; } = lastName;

}

To achieve the same without primary constructors, we would have to write the code in the following way.

publicclass Employee

{

privatestring firstName;

publicstring FirstName

{

get

{

return firstName;

}

}

privatestring lastName;

publicstring 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.

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.

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.

Monday, May 26, 2014

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.

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.

Monday, May 19, 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.

Friday, May 16, 2014

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.

Wednesday, May 7, 2014

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.

publicclass Department

{

publicint DepartmentId { get; set; }

publicstring DepartmentName { get; set; }

}

publicclass Employee

{

publicint EmployeeId { get; set; }

publicstring FirstName { get; set; }

publicstring 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.

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.

Once I run the code and check the database created, I can see the following.

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.

publicclass Employee

{

publicint EmployeeId { get; set; }

publicstring FirstName { get; set; }

publicstring LastName { get; set; }

publicint 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.

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.

protectedoverridevoid 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.

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.