Playing with C# 6 features

C# 6 has got nothing major coming like LINQ or async/await in past instead it has got several small enhancements which actually helps you clean up your code and get ride of boilerplate code. In this post, I am going to share some of the code snippets I wrote to explore new features in C# 6.

This post is written using VS 2015 CTP6, so the actual specs may vary by the time of final release. If you want to quickly get hands on Visual Studio 2015 CTPs without setting up environment, you can create virtual machine from gallery in Azure

String interpolation:
Methods like string.Format in C# provides great functionality to construct strings using placeholders. However that approach is a bit confusing and error-prone. C# 6 introduces a new way to use variable placeholders directly in string instead of number based placeholders by placing ‘$’ symbol before the string. This makes code a lot more readable.

public static void StringInterpolationEnhancements()
{
  string name = "Adil";
  DateTime date = new DateTime(2015, 03, 13, 10, 15, 0);
  int versionYear = 2015;
            
  // Previously in C# 5
  WriteLine(string.Format("This code was written by {0} on {1} using Visual Studio {2}", name, date, versionYear));

  // In C# 6
  WriteLine(string.Format($"This code was written by {name} on {date} using Visual Studio {versionYear}"));
          
  // In fact you don't need to call string.format 
  WriteLine($"This code was written by {name} on {date} using Visual Studio {versionYear}");

  // This is especially handy when you add more parameters in string format over the time and the order get confusing
  string content = "blog";
  WriteLine(string.Format("This {3} was written by {0} on {1} using Visual Studio {2}", name, date, versionYear, content));

  WriteLine($"This {content} was written by {name} on {date} using Visual Studio {versionYear}");
}

Using static members:
A lot of time you have a class with bunch of static methods and you have to call them via class. e.g.

using static System.Console;
 
//Previously in C# 5
Console.WriteLine("This is how to use static classes");
 
// In C# 6 by adding namespace using static System.Console;
WriteLine("Just call the static method directly"); 

This was one of the feature I liked in Java and its now added in C# as well although Java don’t have many other goodies from C#.

Null propagation:
This one is interesting. Often we have methods with more statements to do null checks then actually intent of method. C# 6 introduces a new null propagation operator (?.) This would automatically check if the left hand side is not null then it uses property of that object.

public void DisplayStudent(Student student)
{
  // Previously in C# 5
  if (student != null)
  {
    WriteLine(student.Name);
  }
}

public void DisplayStudentInCSharp6(Student student)
{
  //In C# 6
  WriteLine(student?.Name);
}

If you want to work with primitive type because C# already has nullable primitives, you can write something like

int? age = student?.Age;

This is especially handy in firing events because you don’t have to do a thread safe null check

event EventHandler OnNetworkChange;
void RaiseNetworkChange()
{
    OnNetworkChange?.Invoke(this, new EventArgs());
}

However I was looking for cases when we have to add null checks before iterating on a collection but I don’t think it works in foreach statement but may be it’s good idea to check language specs or ask this question to language team. Do you know about it, reader?

// can I say something like student?.Courses?.GetEnumberable()
foreach (var course in student.Courses)
{
  WriteLine(course.Id);
}

Expression bodied members:
For method having single return statement or properties with a getter having single return statement, C#6 lets you implement a method with single expression, like we use to do define lamba expressions.

//Instead of 
public override string ToString()
{
  return string.Format("Value : {0}, value};
}

// We can define expression in C# 6
public override string ToString() => $"Value : {value}";

Dictionary Initializers:
C# 3.0 introduces concept of object intializers where you can initialize properties of object like

Student student = new Student { Name = "Adil" };

However if you want to initialize index or dictionary you have to initialize say dictionary first and set value at index in separate statement but not any more

Dictionary<string, int> dictionary = new Dictionary<string, int> {["Year"] = 2015,["Month"] = 03,["Day"] = 15 };

Other enhancements:
There are few other enhancements in the language as well.
– Getter only auto properties
– Constructor assignment for getter only properties
– Auto properties initializers
– Catching exception with filters
– await in catch/finally block
– nameof operator

public class OtherEnhancements
{
    // A getter only property with readyonly backing field
    public int DemoInt { get; }

    // An auto property intialized with default value
    public string DemoString { get; set; } = "Demo";

    public OtherEnhancements()
    {
        // Assignment in constructor for getter only field behaves like readonly field
        this.DemoInt = 100;
    }

    public void DemoMethod()
    {
        try
        {
            // Some code to capable to raise FileNotFoundException
        }
        // catch exception with filter to handle only for particular file 
        catch (System.IO.FileNotFoundException exception) when (exception.FileName == "abc.txt")
        {
            // In previous version of C#, you have to check it inside
            // and then re throw which would result in losing exception data
        }
    }
}

That’s all for this post. The complete sample for above code snippets is available at Github Gist.

Have you tried new features yet? any interesting scenario you would like to share in comments?

Implementing Model-View-ViewModel (MVVM) in Windows Phone

Model-View-ViewModel (MVVM) is a solid presentation model and the best benefit of this design is that it lets you decouple UI and logic which makes you unit test your logic easily. You will find a lot of stuff over the internet about MVVM but I am going to quickly introduce you using a diagram:

Source: Implementing MVVM (Microsoft Patterns & Practices)

The View in case of Windows Phone is the UI page (.xaml) and code behind (.cs/.vb). Model is plain data model. ViewModel contains presentation logic which may encapsulates models, have some logic around it, interact with repositories etc. View and ViewModel are connected via Binding or Commands etc. I will cover those as we code it.

In this post, I am going to share a very naive way of implementing MVVM to develop your apps on Windows Phone but more or less we can implement MVVM same way to develop Windows Store apps. In fact in my upcoming post I would love to write about how we can share code between Windows Phone and Windows Store apps by implementing MVVM + Portable Libraries + Dependency Injection.

Microsoft XAML based solutions supports MVVM as most of basic components required to implement MVVM are baked in as part of framework e.g. DataContext and Binding, INotifyPropertyChanged, Commands etc. I will get back to these terms as we go through code.

So here is something we are going to develop. A simple app with contact page allow user to fill in name, email, select a category, add details to it and submit it. We would add some basic validation here as well.

Contact Form Sketch

So let’s jump to code and start learning MVVM by writing code.

We will start by creating model first. I am gonna add a Category class which we would use to create a collection to populate categories.

Now there are couple of things here that needs explanation. INotifyPropertyChanged and OnPropertyChanged being called in setters. INotifyPropertyChanged is an interface that ships with framework and the class implements it is able to notify their view/clients that a property value has changed. So once we bind our view with ViewModel/Model then we need a mechanism to inform View/UI that a value has been updated. What happens is that when we change value of a property in model it send raises property change event, which is why we are calling “OnPropertyChanged” method, to let view know that a property value has change and therefore please update your UI. And that’s the major purpose of INotifyPropertyChanged interface and we need to implement it in all Models or ViewModels which we intend to bind.

Now let’s create a view model. ViewModels are usually one per view, page in this case. So we are going to create ContactPageViewModel

We have an ObservableCollection<Category> which we would use to populate category list. The ObservableCollection is part of framework and it automatically notifies UI when an item has been added, deleted etc. We also have another property “SelectedCategory” which we would use to populate the selected property by the user. We have Name/Email for user data, Inquiry string for details and IsValid property that we would use for required validation.

Let’s talk about view now. Now here is a part that is kind of easier on Windows Platform such as Windows Store and Windows Phone in contrast to Android and iOS.

So binding a property of control is simple we use special XAML syntax “{Binding PropertyName, Mode = OneWay/TwoWay/OneTime}”. The mode here specify that whether binding would be one way i.e. from Model -> UI or TwoWay i.e. UI -> Model and vice versa. The other important thing to notice is Command. Commands are way to connect view events with ViewModel. In this case, we have registered submit button with SubmitCommand on ViewModel which would eventually call OnSubmit action.

BUT the potential of MVVM can be observed with how validation is handled. What I have done is that submit button will only be enable when IsValid property is true. And who is updating IsValid property? RequiredFieldValidator.
That’s why we have registered TextChanged event in UI which triggers source to update on every key stroke which update the ViewModel property which internally raises PropertyChanged event and that event is being handled by validator which sets IsValid to true all required fields are being populated.

And you just made a simple implementation of MVVM on Windows Phone. Please note that the above code is not production optimized. Also there are different ways to implement MVVM and this is just one way to do it. Also MVVM may not fit to very simple 1-2 pages app however the more complex the app the more likely it is that MVVM is the right fit for your app.

Sample code can be forked or downloaded from Github: https://github.com/adilmughal/DemoMvvm.WP

Why am I excited about Roslyn Project

Microsoft announced Community Technology Preview (CTP) of Roslyn project during BUILD 2011. I am really excited about the Roslyn project (and I will tell you why soon…).

Roslyn? Isn’t it name of a city?

Well you are right and many of Microsoft product code names are now based on city/town names mainly due to copyright issue. If you don’t have idea and you love to dig in languages/compilers, it’s a MUST SEE for you.

The concept is simple that traditionally compilers are kind of black box thing where we provide source files as input and it provide assemblies/DLLs/exe as output. The Roslyn project is all about opening the black box of compiler and allowing us to get internal language object model and things such as syntax tree etc. through Compiler APIs. The objective of the project is to rewrite the VB and C# compilers and language services in managed code. See slide below from Anders’ talk at BUILD 2011.

The Roslyn Project

Interested? Check out http://msdn.com/roslyn for project overview document and to download the available bits. For further introduction, please read Introducing the Microsoft “Roslyn” CTP on Visual Studio blog.

Roslyn APIs

Roslyn APIs exposes four collection of APIs. You can read details of each API in project overview document (from where the image below is taken).

Roslyn APIs Collection

The Services API have dependency over Visual Studio SDK and contains Visual Studio IDE features, such as intellisense, code refactoring and formatting etc.

Before reading on, if you haven’t installed Roslyn binaries, go ahead download them and skim through overview document.

Exciting Part?

If you have been kind of student, who enjoyed compiler construction course(s) during undergrad and really enjoy in going deep into mechanics, then you would definitely love exploring Roslyn APIs. This is because the rewriting of compiler and exposed APIs would allow you to understand the syntactical and semantic model of your code.

Roslyn Core APIs

With this you can not only generate code on fly but also REPL (read-eval-print-loop) operations can be done. Plus you can visualize/parse your existing code and see what syntax tree it has generated. For example, consider the following code snippet using Roslyn API:

SyntaxTree tree = SyntaxTree.ParseCompilationUnit(
@"using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{ Console.WriteLine(""Hello, World!""); }
}
}"
);

Syntax Visualizer

If you traverse/print tree or use Roslyn Syntax Visualizer control, you would get to know the underlying syntax tree structure and its components. Using the above code, the syntax tree has parsed the code and decomposed it into tokens, nodes, and trivia. The debugger visualizer (see image on left) will help you understand the syntax tree generated. This debugger is of great aid if you are developing any IDE extension using Roslyn API.

Please note that syntax visualizer control is available with samples, along with source code, in Samples folder created when you downloaded Roslyn bits. Currently there are some known issues with this control and workaround (code modification) has been explained at Roslyn forum “Known Limitations and Unimplemented Language Features”.

Another fun point is Workspace API which allows you to programmatically do stuff with your solution, projects, assemblies and documents. As a very simple example, consider the following code snippet:

IWorkspace workspace = Workspace.LoadSolution(@"<%PROVIDE PATH OF .SLN FILE");
ISolution solution = workspace.CurrentSolution;

foreach (IProject project in solution.Projects)
{
Debug.WriteLine(project.DisplayName);
foreach (IDocument document in project.Documents)
{
Debug.WriteLine(document.DisplayName);
}
}

And if you are interested to create visual studio extension for developers productivity, Roslyn Service APIs are going to provide you breakthrough. Try exploring Service APIs project using “Roslyn Installed Templates”. Surely, you can VS extensions directly using SDK but with the power of Roslyn, you can get into the code tree and provide intelligent refactoring and productivity aids to developer.

Roslyn Templates 

Do I need Roslyn?

You need to explore Roslyn APIs,

  • if you do a lot of heavy lifting with Reflection in the .NET Framework. At my previous employer, when we used to develop Form Designer for BPM Suite, much percent of our code was based on Reflection due to dynamic nature of the application
  • Already using Visual Studio SDK
  • Interested to understand compiler services
  • Interested to create Visual Studio extensions

But there is much more in Roslyn and I would try to share my experience of whatever I experiment with Roslyn APIs in spare time. If you are working on Roslyn, please do share your experience in comments below.

Debug Class in .NET

One of the alternative yet under utilized way to debug code in .NET is using Debug class found in System.Diagnostics Namespaces. This class really gives bunch of functionalities to developer that are very useful for debugging and I wonder why but I have observed that fewer percentage of developers use it. So I thought to share the usage of Debug class with developers out there as I found it very useful.

I will directly jump to code snippet demonstrating the functionality of Debug class:

using System.Collections.Generic;
using System.Diagnostics;
 
namespace DemoDebugClass
{
    public class Customer
    {
        public int    Id   { get; set; }
        public string Name { get; set; }
        public int    Age  { get; set; }
    }
 
    public static class CustomerExtensions
    {
        public static void PrintCustomersBelowAge25(this IEnumerable customersList)
        {
            foreach (var customer in customersList)
            {
                Debug.WriteLine(string.Format("Customer Name: {0}", customer.Name));
                Debug.WriteLineIf(customer.Age < 25, "Required Customer Found!");
            }
        }
    }  
 
    class Program
    {
        static void Main(string[] args)
        {
            List customersList = new List();
            customersList.Add(new Customer { Id = 1, Age = 30, Name = "Customer A" });
            customersList.Add(new Customer { Id = 2, Age = 15, Name = "Customer B" });
            customersList.Add(new Customer { Id = 3, Age = 20, Name = "Customer C" });
            customersList.PrintCustomersBelowAge25();
        }
    }
}

In the above code snippet, we have a customer class and assume that we are interested in finding customers below age 25 as shown in code snippet above. With the Debug.WriteLine you can print data to Output Window in Visual Studio (View –> Output Window) and even conditional data as well, as depicts in image below.

Output Window

Now this is really interesting because it gives liberty to developers to debug the program and data without using breakpoints as most of us used to do. Further these lines are only executed when the program is executed in Debug mode. Besides, this also allows you to easily share the output log with your colleagues.

So go ahead and give it a try! If you don’t use it for some reason then please share your remarks in comments below. Happy Coding!

Parameters and Arguments

These days I’m reading “C# in Depth, Second Edition” written by a very famous C# MVP Jon Skeet. In his book Jon cleared the difference between Parameters and Arguments which I thought to share, with his permission. A lot of software developers really use these words interchangeably when discussing about programming with each other and sometimes we never realized that.
A parameter is the variable which is part of the method or indexer declaration whereas an argument is an expression used when calling the method or indexer. For example:
private void M1(int number)
{
// some code
}
//somewhere else in the code 
int value = 10;
M1(value);

In the code snippet above number is the parameter whereas as value is the argument. Hope you will now use these words properly, if you were interchanging them previously like me 🙂

The LINQ Way

In this post, I will be sharing some code snippets to continue emphasizing on the use of LINQ. The code is almost the same which I discussed in Emerging .NET Devs UG Meeting in Oct ‘09.

Let’s see a comparison of doing similar task with typical way and the LINQ way, in particular related to LINQ to Object, but first consider interface “ICustomer” on which we are going to play

namespace LinqToObject
{
internal interface ICustomer
{
string CustomerID { get; set; }
string CompanyName { get; set; }
string ContactName { get; set; }
string Country { get; set; }

List<Customer> GetCustomers();
}
}

Now assume there is a class Customer implementing ICustomer and what we want is to retrieve list of all customers in country “Pakistan”.

Typical Way:

public IEnumerable<ICustomer> GetCustomersFromPakistan()
{
List<ICustomer> customerList = new List<ICustomer>();
foreach (Customer c in customer.GetCustomers()) //customer is Customer:ICustomer
{
if (c.Country.StartsWith("Pakistan"))
customerList.Add(customer);
}
return customerList;
}

and it will happily print list of all customers from Pakistan

The LINQ Way:

public IEnumerable<ICustomer> GetCustomersFromPakistan()
{
var result = from c in customer.GetCustomers()
where c.Country.StartsWith("Pakistan")
select c;
return result;
}

Remarks: To be honest, it is a bit clean but nothing very impressive right?

So let’s add a further requirement, now I want all CustomersFromPakistan but ordered by Customer ID. Let’s compare the code again.

Typical Way:

public IEnumerable<ICustomer> GetCustomerFromPakistanList()
{
List<ICustomer> list = new List<ICustomer>();
foreach (ICustomer c in customer.GetCustomers())//customer is Customer:ICustomer
{
if (c.Country.Contains("Pakistan"))
{
list.Add(customer);
}
}
list.Sort(delegate(ICustomer customer1, ICustomer customer2)
{
return customer1.CustomerID.CompareTo(customer2.CustomerID);
});

return list;
}

The LINQ Way:

public IEnumerable<ICustomer> GetCustomersFromPakistan()
{
var result = from c in customer.GetCustomers()
where c.Country.Contains("Pakistan")
orderby c.CustomerID;
select c;
return result;
}

Remarks: What do you say? it’s clean and simple right!!!

Further with the use of Lambda expression, you can filter out lists easily. For instance,

ICustomer customer = new Customer();
var list = customer.GetCustomers()
.Where<ICustomer>(c=> c.Country == "Pakistan");
“Where” is an extension method and will provide you a simple way to filter sequence of values based on predicate defined using lambda expression.

Summary:

As you will come across complex conditions, for loops are really messy and LINQ provides a clean and simple way to perform object manipulation that will also improve productivity of developer. If you are still not using LINQ, I recommend you to get some hands on, you will really enjoy it.

A glimpse on Visual Studio 2010 Beta 2

Great News! Microsoft recently shipped Visual Studio 2010 Beta 2 and is available to download for general public on October 21st.

The very first thing you will notice is the new logo

  VS LOGO MOdified 

Another change you will observe is that Visual Studio now comes with four edition:

  • Visual Studio Express
  • Visual Studio 2010 Professional with MSDN
  • Visual Studio 2010 Premium with MSDN
  • Visual Studio 2010 Ultimate with MSDN

For details about these SKUs, visit Scott Gu post here. Due to MSDN Subscription, I have downloaded Visual Studio 2010 Beta 2. So let’s go ahead and see some of the screen shots of installation.

Setup Screen 1 Setup Screen 2 Setup Screen 3 Setup Screen 4 Setup Screen 5

and it will take some time to complete installation 🙂 So Let’s move ahead. Here is the new splash screen

image

Now there are number of changes in the start up page and it seems to be better organized.

VS 2010 Beta 2 Start Page

And of course the support of targeting different framework versions.

Start New Project

There are numerous new and exciting features that are going to released along with Visual Studio 2010 Beta 2 that we are going to see in several posts ahead.

Event Summary: Oct UG Meeting on LINQ

I participated as speaker along with Munir Usman (MVP) in Emerging .NET DevsOctober UG Meeting on LINQ. I was excited as I was speaking after couple of months 🙂 The event was organized by  Emerging .NET Devs. We tried to make the event as interactive as possible. The style of discussion was comparison between approaches before and after LINQ and how LINQ makes life of programmer easy and increase productivity. 

Adil and MunirDSC01643

Following was the agenda of the discussion:

  • Challenges before LINQ

  • Introduction to LINQ

  • Pre-requisite to LINQ (C# 3.0 Features)

  • LINQ to Objects

  • Refreshment

  • LINQ to SQL

  • LINQ to XML

For more details about the events, please visit Emerging .NET Devs – Oct UG Meeting Summary. Also, those who attended the show, please provide feedback about the event here. Thank you everyone for attending the show.

Real World Scenario: DataGridView Link Click

Finally, I got time to blog another post on Real World Scenario. This time I received an email from a final year student. As mentioned earlier, the purpose of blogging about these issues is to share solution with others facing similar problem.

Scenario: (copied from email)

I’m facing some problems in my project. In one of the form I am using DataGridview to display my data… ! as mention in the attached JPEG. All columns are Databound. (except View Detail Column).
I want, when i click on ‘View’ all the data of particular row will display it new form im detail… ! Is it possible ??

The answer to this query is quite simple. DataGridView exposes an event ‘CellContentClick’ to which you can subscribe and handle the event. Consider the code snippet:

//subscribe the event first
this.dataGridView1.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellContentClick);

//handle the event
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 4) //4 is the index of Column with link (DataGridViewLinkColumn)
    {
        DetailForm detailForm = new DetailForm();
        detailForm.ShowDialog();
    }
}

and that will give you the desired functionality:) Thank you again for contacting me. If you have any issue related to .NET, send me an email and I will try my level best to solve the query for you.

Real World Scenario

Greetings!

From time to time, I receive emails from software developers around the world, specially from Middle East and Asia region, discussing some technical issue. So while I was answering an email today, I thought that it would be great if I create a category “Real World Scenario” on my blog and post the solution there so that many others could benefit.

But first please note some points 🙂

  • Being an MVP doesn’t mean that I know everything 🙂 but I will try my level best to help you in providing solution
  • The solution may not be the best approach to solve a particular problem or there may be a better way to code
  • Also, I may not post the exact question and code asked from person but will create question of similar situation otherwise I need to get permission from that person first

So this is my first post on the series of Real World Scenario.

Scenario: Binding a ComboBox to a Generic List of Custom class A with Display member as another class B exposed as public property in class A

Consider the following code snippet below:

public class B
{
    public string Info { get; set; }
    public int Id { get; set; }
}
public class A
{
    public string Name { get; set; }
    public B Information { get; set; }
}

We created two classes A and B and added some automatic properties in them. Most of the time, we want to bind our ComboBox (let’s say comboBox1) with List and Display member as some primitive data type, something like:

//populate some data
A obj1OfA= new A { Name = "Test1" , Information=new B { Info= "Info Test 1", Id = 1} };
A obj2OfA= new A { Name = "Test2" , Information=new B { Info= "Info Test 2", Id = 2} };
listOfA.Add(obj1OfA);
listOfA.Add(obj2OfA);
//and bind the comboBox1 with A
comboBox1.DataSource = listOfA;
comboBox1.DisplayMember = "Name";

In the code snippet above, we initialized a generic list of class A and then we created two objects of A using object intializer, a feature of C# 3.0, and finally added the objects in list along with binding of list to combobox.

So that will do our job because Name is a public property of type string in class A and it will display in Name easily. The question was that when you want to set Display Member as Information like:

comboBox1.DataSource = listOfA;
comboBox1.DisplayMember = "Information";

it will not display appropriate data in the combo box and that will be something like

WindowsFormsApplication1.B
WindowsFormsApplication1.B

and that is not what we wanted to display. The reason is that it actually calls ToString method and that returns type name in case when display member is Information. So the solution is that you need to override ToString() method in the class B and return the desired data that you want to display. So let’s go ahead and change our class B:

public class B
{
    public string Info { get; set; }
    public int Id { get; set; }
    public override string ToString()
    {
        return Info;
    }
}

and now when we execute our code we will get appropriate output showing the value of Info property in class B bind to our combobox 🙂 That’s all !

Thank you for the email sent by you, The Developers. Interaction with community really gives me an opportunity to learn from you people as well and a chance to serve the community. Thank you once again! Have a fantastic time!