DCSIMG
March 2012 - Posts - Pavel's Blog
Sign in | Join | Help

Pavel's Blog

Pavel is a software guy that is interested in almost everything
software related... way too much for too little time

March 2012 - Posts

Asynchronous Programming with C# 5.0 & .NET 4.5 Session

Published at Mar 26 2012, 01:38 PM by pavely

This morning I gave a session on asynchronous programming with C# 5.0 at Microsoft offices in Ra’anana. Thank you all for attending, it was great fun!

As promised, the presentation slides and demos are attached below (the Windows 8 demos can naturally be run on Windows 8 only).

The session was recorded, so if you missed it, or just want to hear the same jokes again, the recording will be available in a few days – check out the MSDN blog for details of availability.

Async Demos

Async Metro Demo

Presentation Slides

INotifyPropertyChanged implementation with C# 5.0

Published at Mar 20 2012, 10:40 PM by pavely

The INotifyPropertyChanged interface has become a very popular interface, typically used in MVVM scenarios (WPF/Silverlight). It looks simple, with a single member, which is an event, and its basic implementation by some data type may be something like this:

  1. class Book : INotifyPropertyChanged {
  2.     public event PropertyChangedEventHandler PropertyChanged;
  3.  
  4.     protected virtual void OnPropertyChanged(string propName) {
  5.         var pc = PropertyChanged;
  6.         if(pc != null)
  7.             pc(this, new PropertyChangedEventArgs(propName));
  8.     }
  9.  
  10.     string _name;
  11.     int _published;
  12.  
  13.     public int Published {
  14.         get { return _published; }
  15.         set {
  16.             if(_published != value) {
  17.                 _published = value;
  18.                 OnPropertyChanged("Published");
  19.             }
  20.         }
  21.     }
  22.  
  23.     public string Name {
  24.         get { return _name; }
  25.         set {
  26.             if(_name != value) {
  27.                 _name = value;
  28.                 OnPropertyChanged("Name");
  29.             }
  30.         }
  31.     }
  32. }

This looks simple enough. Every property setter checks if a change has been requested, and if so, sets the new value and fires the event. A further convenience would be to place OnPropertyChanged in its own abstract base class:

  1. public abstract class ObservableObject : INotifyPropertyChanged {
  2.     public event PropertyChangedEventHandler PropertyChanged;
  3.  
  4.     protected virtual void OnPropertyChanged(string propName) {
  5.         var pc = PropertyChanged;
  6.         if(pc != null)
  7.             pc(this, new PropertyChangedEventArgs(propName));
  8.     }
  9. }
  10.  
  11. class Book : ObservableObject {

Although this is simple, the setter has some issues: first and foremost, type safety; the property name is given as string, which might not exist, with no compile time check. One possibility is to check for its existence at runtime:

  1. protected virtual void OnPropertyChanged(string propName) {
  2.     Debug.Assert(GetType().GetProperty(propName) != null);
  3.  
  4.     var pc = PropertyChanged;
  5.     if(pc != null)
  6.         pc(this, new PropertyChangedEventArgs(propName));
  7. }

This is certainly safer, but still not perfect. The other thing that’s a bit bothering is the length of each setter: there’s an equality check, and then the actual assignment, and then the call to OnPropertyChanged. Can we make it better? Here’s an elegant solution to this, latter, problem:

  1. public abstract class ObservableObject : INotifyPropertyChanged {
  2.     public event PropertyChangedEventHandler PropertyChanged;
  3.  
  4.     protected void SetProperty<T>(ref T field, T value, string propertyName) {
  5.         if(!EqualityComparer<T>.Default.Equals(field, value)) {
  6.             field = value;
  7.             var pc = PropertyChanged;
  8.             if(pc != null)
  9.                 pc(this, new PropertyChangedEventArgs(propertyName));
  10.         }
  11.     }
  12. }
  1. class Book : ObservableObject {
  2.     string _name;
  3.  
  4.     public string Name {
  5.         get { return _name; }
  6.         set { SetProperty(ref _name, value, "Name"); }
  7.     }
  8.  
  9.     int _year;
  10.  
  11.     public int Year {
  12.         get { return _year; }
  13.         set { SetProperty(ref _year, value, "Year"); }
  14.     }
  15. }

The are a few things going on here. The field and value are compared using EqualityComparer<T>. This is used instead of the simpler object.Equals, because EqualityComparer<T> looks for a possible IEquatable<T> implementation, and uses it if found (it actually does a few more checks, but that’s the interesting one). Now the setter needs to call just one method: SetProperty<T>.

The first problem remains, though: The actual name of the property is passed as a literal string. Here’s where C# 5.0 comes in with its support for the caller member attribute, like so:

  1. protected void SetProperty<T>(ref T field, T value, [CallerMemberName] string propertyName = null) {
  2.     if(!EqualityComparer<T>.Default.Equals(field, value)) {
  3.         field = value;
  4.         var pc = PropertyChanged;
  5.         if(pc != null)
  6.             pc(this, new PropertyChangedEventArgs(propertyName));
  7.     }
  8. }

And the Book implementation:

  1. class Book : ObservableObject {
  2.     string _name;
  3.  
  4.     public string Name {
  5.         get { return _name; }
  6.         set { SetProperty(ref _name, value); }
  7.     }
  8.  
  9.     int _year;
  10.  
  11.     public int Year {
  12.         get { return _year; }
  13.         set { SetProperty(ref _year, value); }
  14.     }
  15. }

Look, ma, no property string name!

The property name is passed automatically to the new [CallerMemberName] attribute parameter (a default value must be supplied), so no need to specify it explicitly. Excellent!

What happened to asynchrony with WebClient in .NET 4.5?

Published at Mar 17 2012, 04:01 PM by pavely

In the Visual Studio 2010 Async CTP, a bunch of extension methods have been added to the WebClient class, to facilitate the “awaiting” of C# 5.0, such as DownloadStringTaskAsync, which can be simply used like so:

  1. var wc = new WebClient();
  2. string result = await wc.DownloadStringTaskAsync("http://msdn.microsoft.com");

One of the overloads present in the CTP accepts a CancellationToken, so that the operation could be cancelled by an external CancellationTokenSource. For example:

  1. async Task<string> GetData(string uri, CancellationToken token) {
  2.     var wc = new WebClient();
  3.     string result = await wc.DownloadStringTaskAsync(new Uri(uri), token);
  4.     return result;
  5. }

So, the typical caller can use it like so:

  1. CancellationTokenSource _cts;
  2.  
  3. private async void OnGetData(object sender, RoutedEventArgs e) {
  4.     var wc = new WebClient();
  5.     _cts = new CancellationTokenSource();
  6.     try {
  7.         string result = await wc.DownloadStringTaskAsync(new Uri("http://www.codevalue.net"), _cts.Token);
  8.         _data.Text = result;
  9.     }
  10.     catch(OperationCanceledException ex) {
  11.         _data.Text = "Cancelled";
  12.     }
  13. }

Calling CancellationTokenSource.Cancel causes cancellation, delivered as an OperationCancelledExcpetion exception. The actual Cancel would be typically invoked from some event handler:

  1. private void OnCancel(object sender, RoutedEventArgs e) {
  2.     if(_cts != null)
  3.         _cts.Cancel();
  4. }

In .NET 4.5, I was expecting the WebClient class to have all the extension methods baked into the type as instance methods. The basic DownloadStringTaskAsync method is there, but with no overload that accepts a CancellationToken. Where did that go?

Well, it turns out that WebClient has lost its attraction. There is a new guy in town – HttpClient. It’s a complete replacement for WebClient (and also HttpWebRequest). It’s built with “async” in mind – all its operations are asynchronous, never synchronous. So, the way to allow cancellation while awaiting is to use HttpClient:

  1. _cts = new CancellationTokenSource();
  2. try {
  3.     var result = await client.GetAsync("http://www.codevalue.net", _cts.Token);
  4.     var data = await result.Content.ReadAsStringAsync();
  5.     _data.Text = data;
  6.     _cts.Dispose();
  7.     _cts = null;
  8. }
  9. catch(OperationCanceledException ex) {
  10.     _data.Text = "Cancelled";
  11. }

Note that even getting the actual string is an asynchronous operation (there is a GetStringAsync on HttpClient, but it cannot accept a CancellationToken).

HttpClient is the new HTTP king: it can do anything WebClient and HttpWebRequest can do (plus some more), and all is asynchronous – perfect to use with the new C# 5.0 async feature.

Presentations I’ll be giving this month

Published at Mar 13 2012, 11:03 PM by pavely

This month turned out to be a busy one for me, at least as far as public presentations are concerned. All sessions are free of charge, but you should register – details follow:

Parallel and Asynchronous Programming with .NET 4/4.5 and C# 5.0

This session is to be held on the 20th, at John Bryce offices in Tel Aviv. I will do a quick recap of tasks and the Parallel class, and then move to async programming with and without the new C# 5.0 features. I will be using VS 2010 and the recently released (beta) Visual Studio 11.

Link to registration

Async Programming using C# 5.0 and Tasks in .NET 4.5 and WinRT

This event is held in Microsoft offices in Ra’anana. This talk will focus on the asynchronous features of C# 5.0 and .NET 4.5 (using Visual Studio 11 beta), as well the asynchronous programming model with the new Windows Runtime (WinRT) present in Windows 8.

Link to registration

Introduction to Metro and Windows 8 with C# and XAML

This is part of the Windows Devices User group meetings managed by Elad Shaham and myself. Elad and I will talk about Windows 8, the Windows Runtime, Metro and how to create metro apps with C#, XAML and Visual Studio 11 Beta. Should be interesting!

Link to registration

I hope to see some of you in some of these events!

Static vs. Instance (vs. Extension)

Published at Mar 09 2012, 01:01 AM by pavely

Sometimes I teach a basic .NET & C# course. Among many other things, I discuss arrays. I mention that all .NET arrays derive from System.Array, and so get some functionality for free, such as sorting. Here’s a simple array:

  1. int[] a = new int[10];

Now, the inexperienced student may type “a.”, opening the intellisense list box, and look for a method named Sort – after all, the instructor (me) said arrays support such an operation. The confused student can’t find any such method. Of course the problem is that sorting is implemented as a static method; Intellisense is strict – it does not offer the static method as alternative. The correct call would be:

  1. Array.Sort(a);

This is somewhat bewildering. Why is it not an instance method, if the method accepts the actual array? This confusion is compounded by the fact that types such as ArrayList and List<> offer an instance Sort method and not a static one. Clearly, design decisions are at play.

System.Array is an extreme example, having many static methods that accept the actual array as the first argument: Sort, Resize, Copy, BinarySearch, Clear, Find, to name a few.

I feel that methods like Sort and Clear should be instance methods, as they clearly make modifications to state. Methods such as Resize and Copy can be made static, as they operate on a “higher level” of sorts. Still, it’s all debatable.

Let’s look at other examples.

DateTime

DateTime is another interesting case. It’s a value type and it’s immutable, meaning its internal state cannot change after creation. This is often a desirable trait (I won’t delve into immutability in this post), especially for value types. The most famous immutables in .NET are String and all delegates.

However, it’s easy to forget that immutability of DateTime. I remember a while back I wanted to do something for a range of dates like so (assuming start is less than end when entering the method):

  1. static void DoWork(DateTime start, DateTime end) {
  2.     while(start < end) {
  3.         // do actual work...
  4.         start.AddDays(1);
  5.     }
  6. }

This of course didn’t work as expected. It’s an infinite loop, but it’s easy to miss. AddDays (and other such methods) are instance methods but return a new object (DateTime wants to be immutable). This is the correct code:

  1. static void DoWork(DateTime start, DateTime end) {
  2.     while(start < end) {
  3.         // do actual work...
  4.         start = start.AddDays(1);
  5.     }
  6. }

Maybe AddDays should have been defined as a static method. That would make it more intuitive as to the result. A static method looks more “distant”, as if looking from high above on the actual object:

  1. start = DateTime.AddDays(start, 1);

Wouldn’t it that be better?

The basic problem is consistency. Some types do behave that way. Consider BigInteger. It’s a value type and immutable as well. All operations on BigInteger are static, indicating more clearly that a new result is returned. Here’s an example:

  1. BigInteger n = BigInteger.Pow(2, 128);
  2. BigInteger m = BigInteger.Divide(n, 6);
  3. BigInteger q = BigInteger.Add(m, n);

The Complex value type behaves much the same way.

What about non-immutables?

A few months ago I implemented a mathematical library that included types such as Vector and Matrix, representing those mathematical entities with arbitrary size. Although I like immutability, I decided against it. The problem is that if a simple calculation is attempted, such as multiplying every matrix element by some constant, creating an entire new matrix for this just to maintain immutability may be too expensive, as the matrix may be arbitrarily large. Ideally, I would like the client to decide whether to modify the matrix or create a new one.

The problem I ran into was this: how can I support both self changing operators and non-changing operators (meaning they return new objects) in a consistent way? Here’s a basic Matrix class that I would like to have:

  1. class Matrix {
  2.     double[,] _values;
  3.     
  4.     public int Rows { get; private set; }
  5.     public int Columns { get; private set; }
  6.     
  7.     public double this[int row, int col] {
  8.         get { return _values[row, col]; }
  9.         set { _values[row, col] = value; }
  10.     }
  11.  
  12.     public Matrix(int rows, int cols) {
  13.         Rows = rows; Columns = cols;
  14.         _values = new double[rows, cols];
  15.     }
  16. }

Now suppose I want to allow adding one matrix to another:

  1. public static Matrix operator +(Matrix a, Matrix b) {
  2.     // check for compatible matrix ommited
  3.     var result = new Matrix(a.Rows, a.Columns);
  4.     // do actual calculation
  5.     return result;
  6. }

This clearly returns a new matrix, as is expected from operators. Good thing they are static – this makes it understandable. Sure, I could have added matrix b to a and return a itself. That meant modifying a, which the client would not expect.

How can a client change the actual matrix a? A client could write:

  1. a = a + b;    // or a += b;

This looks easy enough, but a new matrix was created, making a point to that new matrix. The previous matrix is no longer referenced – making it eligible for garbage collection. Clearly, a non-immutable approach is called for.

The solution I chose was to create two Add methods. one static and one instance. This conveys (at least for me) the correct intent:

  1. public static Matrix Add(Matrix a, Matrix b) {
  2.     return a + b;
  3. }
  4.  
  5. public Matrix Add(Matrix b) {
  6.     // add b to this
  7.     return this;    // for convenience
  8. }

Operators are considered “syntactic sugar”, so cannot be the only way to do operations – there should always be an equivalent method.

More matrix operations

The arithmetic operations were solved as described, as well as other common matrix operations, such as Transpose and Inverse. I ended up creating two separate methods, one static and one instance. The instance one changes the contents of this, while the static one returns a new object.

Another thing I needed is the ability to solve a linear equation system. This is a well known problem with well-known solutions and is not interesting for this discussion. The question is, where should I put this capability? Should it be part of the Matrix class, as a matrix is the primary component for this problem?

At first, the answer seems yes, but on second thought this seems awkward. Maybe in the future a better algorithm could be used? Should the Matrix class be changed because of that? Moreover, there are other algorithms involving matrices, should every such algorithm be placed in Matrix?

A possible solution may be to derive a new class from Matrix and implement those algorithms there. But this is counter-productive. Why would anyone use the original Matrix, when the enhanced Matrix offers features that may be required later? Inheritance is not intended for such cases.

The solution I used is to utilize an extension method. That means, a separate static method is written, which can be “imported” by referencing the assembly it’s defined in and making the namespace visible. The compiler would allow using the algorithm as though it’s on the Matrix, but in actuality it’s not. It’s a static method after all. This is somewhere between an instance method and a normal static method:

  1. static class MatrixExtensions {
  2.     public static Vector SolveLinearSystem(this Matrix m, Vector a) {
  3.         Vector result = null;
  4.         // solution omitted for brevity
  5.         return result;
  6.     }
  7. }

  1. Matrix m = ...;
  2. Vector v = ...;
  3. Vector solution = m.SolveLinearSystem(v);

One example of this in .NET is in the Managed Extensibility Framework (MEF). The usual way to get a part instance (MEF terminology for a satisfied object) is by calling the CompositionContainer.GetExportedValue<> instance method. However, sometimes you have an object that was created by other means, but its [Import](s) aren’t satisfied. In this case you call the container’s ComposeParts instance method, but this method is actually an extension method. Someone thought it would be inappropriate for the container to expose that kind of functionality directly, but recognized the need; the result – extension method (implemented by AttributedModelServices class, which is filled with extension methods).

Another example of instance vs. static

One obvious example that comes to mind is AppDomain.Unload. This method is static, but accepts the AppDomain reference as its first argument. It would seem that this should have been an instance method: you have an AppDomain reference, and you instruct it to unload. Why is it static? One reason might be symmetry in respect to the creation of an AppDomain which is done via the static AppDomain.CreateDomain method (no way to create an AppDomain using plain new). This raises another question: why is an AppDomain not created with a simple new, but uses a factory instead? We’ll get back to that in a moment.

The other possible reason is to make the unloading of an AppDomain seem “distant”, perhaps accomplished by an unknown entity. it’s also possible for code calling Unload to unload the calling AppDomain.

Object creation

Let’s get back to the AppDomain case and creation. Why is AppDomain created by a factory method? With AppDomain, the reason is that what you get back is actually a proxy to an AppDomain object (AppDomain derives from MarshalByRefObject). It’s not possible to get that using plain new. new always creates an object in the calling AppDomain (no proxy).

The AppDomain case is rare. More commonly, a factory is used instead of a plain new for two reasons:

1. A constructor overload is required, but there is no good way to distinguish between those constructors. Consider DateTime. It has some reasonable constructors, that take in things like year, month, day, hour, minute, etc. However, it also has some factory methods that take an argument of type long; there’s no way to distinguish that with constructors, so you have DateTime.FromFileTime, DateTime.FromFileTimeUtc, DateTime.FromBinary – all taking long as argument.

2. There is a need to get back a derived type and not the actual type. When we call “new Something”, we get back exactly a Something. Sometimes this is not desirable, and even not possible if that “Something” is abstract, for instance. This is one of the powers of a factory – you can get back a derived type, although most of the time you should not care, because the base type may expose enough functionality. The first example that comes to mind is the WebRequest class. Its constructors are protected. It has a main creation static method, Create. Create receives a URI and returns a derivative of WebRequest (WebRequest is abstract). For example, passing a URI starting with “http://” returns a HttpWebRequest instance. Passing a URI starting with “ftp://” returns a FtpWebRequest; and so on. It’s even possible to register new schemes to get a similar behavior.

Conclusion

Selecting a method to be static or instance is easy – most of the time. but there are cases where it’s not so obvious. And sometimes there is no right or wrong – it may be a matter of taste, or conventions employed by the development team. Extension methods can serve as a compromise, that is still easy to use like an instance method, but is implemented elsewhere as a static method.

Visual Studio 11 Beta–First Impressions

Published at Mar 02 2012, 10:37 AM by pavely

Visual Studio 11 Beta is out (along with Windows 8 Beta), so naturally, I installed it right away (I did create a restore point just in case…). I wanted to get some first impressions of VS 11, and this is the result.

Installation

Installing VS 11 was easier than ever, because there were no choices at all – just install and be done with it. No way to remove unneeded components. I don’t know if this is going to be the final install experience, but this is certainly new. I’m still not sure this is entirely a good thing, because I used to customize the installation by removing (e.g.) SQL Express (I was already using the full edition), the Itanium C++ compilers (nobody uses that anymore) and sometimes removed the “dotFuscator community edition”.

Main Window and Toolbars

Launching VS 11 Beta shows a new start page, similar in concept to the one in VS 2010, perhaps a bit less crowded:

image

The first noticeable thing are the icons. They have all turned into black & white (or dark gray & light gray). This is influenced by the “Metro” style in Windows Phone and Windows 8. This, I think, is taking it way too far. The icons quickly become a mess of dark & light pixels, indistinguishable from one another. The problem gets worse, because the same style is used in the toolbox. Just open a WinForms or WPF application and look at the toolbox. All B&W! Someone forgot what icons are for: convey something that is immediately recognizable, without the need to open some menu item or read some text. Icons in this version become useless. Granted, it seems the designers made great effort to make the icons different from one another, but really, with two colors there’s so much you can do. More informally, VS looks dull. Period. Bring back the colors!

The next thing to note is the default toolbar. Many of the default buttons have been removed, such as Copy and Paste. You can still get them back by clicking the “Add or Remove Buttons” at the toolbar’s end, but really you shouldn’t. I don’t know many developers who use the toolbar to Copy anything – there’s Ctrl+C. In fact, I would argue that developers should almost never use the mouse while writing code.

image

Solution Explorer and Windows

In VS 2010, there is the Productivity Power Tools extension that adds many nice features to the IDE. Many of them have been incorporated into VS 11. For example, the Solution Navigator in from the Power Tools has become the Solution Explorer we know and love:

image

It’s a kind of Solution Explorer + Class View in one. Inside a file there may be classes and inside a class there are members. The new solution explorer makes all this visible in a single window. Great!

Generally, all windows look better, with less stroking around them that have no real value. This saves a few pixels overall, which is a good thing – more space for editing code. The selected tab is more pronounced; it’s now very easy to notice the current one even of many tabs are open.

Conclusion

This was a quick and superficial look at Visual Studio 11 Beta. It looks good, and the non-superficial features (hopefully some to be covered in later posts) are truly exciting, such as working with IntelliTrace, building device drivers, kernel debugging and much more.