DCSIMG
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

Windows Media Foundation: Controlling Camera Properties

Published at May 19 2012, 11:05 PM by pavely

I have blogged about Media Foundation before; it’s the “next generation” of DirectShow, introduced in Windows Vista, enhanced in Windows 7 and further enhanced in Windows 8 (more on that in a future post). One of the tasks I encountered recently was to do a video capture from a camera. This is not too difficult to do (once you understand how Media Foundation works) and there’s even two sample in the SDK. But how do you control various camera properties, such as focus, zoom, white balance, etc.?

It turns out Media Foundation does not define any specific interfaces for these tasks. Curiously enough, it implements interfaces defined by its predecessor, DirectShow, on its media source (represented by the IMFMediaSource interface), when that media source is a video camera.

This means that all you need to do is use the usual COM QueryInterface on the media source to get to the relevant functionality, represented by (at least) two DirectShow-defined interfaces, IAMCameraControl and IAMVideoProcAmp. Here’s an example that sets some properties of a camera passed in as a media source:

  1. HRESULT CMFVideoCaptureDlg::SetupCamera(IMFMediaSource* pCameraSource) {
  2.     CComQIPtr<IAMCameraControl> spCameraControl(pCameraSource);
  3.     HRESULT hr = S_OK;
  4.     if(spCameraControl) {
  5.         long min, max, step, def, control;
  6.         hr = spCameraControl->GetRange(CameraControl_Exposure, &min, &max, &step, &def, &control);
  7.         if(SUCCEEDED(hr))
  8.             hr = spCameraControl->Set(CameraControl_Exposure, 1, CameraControl_Flags_Manual);
  9.     }
  10.     CComQIPtr<IAMVideoProcAmp> spVideo(pCameraSource);
  11.     if(spVideo)
  12.         hr = spVideo->Set(VideoProcAmp_WhiteBalance, 0, VideoProcAmp_Flags_Auto);
  13.     return hr;
  14. }

The code uses ATL’s CComQIPtr<> smart pointer class to do the QueryInterface more compactly.

Note that any such modifications may fail, because some properties are not supported by the individual camera or the camera driver. If you know your camera supports some functionality for sure, your best bet is to update the driver. Sometimes a generic camera driver is not enough and the vendor-specific driver is required.

Windows 8: TopMost vs. TopMost

Published at May 16 2012, 09:54 AM by pavely

In Windows, a Window can be made topmost, by setting an extended style with the value WS_EX_TOPMOST (8), typically provided to CreateWindowEx. A topmost window is always on top of non-topmost windows. Among all topmost windows, the normal z-order rules apply. That is, until Windows 8.

A Metro application is built with a topmost window – that makes perfect sense. What about desktop apps? Here’s an empty desktop snapped with a metro app (the desktop itself can be seen as a kind of metro app):

image

Now let’s open Task Manager and make it topmost (Options / Always On Top). Slide it across the dividing snap bar and Task Manager is happy to be on top of the metro app:

image

Curiously, clicking on the metro app window does not make Task Manager any less topmost. Now let’s open Process Explorer and make it topmost as well (Options / Always On Top). Slide it over the metro app window, and this is the result:

image

It seems its topmost attribute is less powerful than Task Manager’s or the metro window! That’s certainly a surprise. It turns out Task Manager is “special” – I couldn’t find any other window that can stay on top of a metro app window – or on top of Task Manager for that matter.

Maybe Task Manager has a new “secret” style bit that makes it “super topmost”. Let’s open Spy++ and select Spy / Find Window from the menu:

image

Dragging the “Finder Tool” over Task Manager’s main window and clicking ok, shows this in the Styles tab:

image

The extended style is 0x108, which is WS_EX_TOPMOST | WS_EX_WINDOWEDGE – the latter being a minor appearance adjustment, irrelevant for our purposes. It looks like a regular WS_EX_TOPMOST. Let’s try the same with the Metro window.

Dragging the Finder Tool over the metro window “doesn’t stick” for some reason. Dragging Process Explorer’s equivalent tool manages to pinpoint the process to which this window belongs (WWAHost.exe, meaning that app was written in HTML/JS), but it doesn’t give out the window handle. So, how can we get the window handle of that metro app?

I decided to try calling the simple WindowFromPoint function, that I’m pretty sure Process Explorer uses as well (I was also sure Spy++ does that, though I can’t understand why it fails to see the window):

  1. POINT pt = { 40, 40 };
  2. HWND h = ::WindowFromPoint(pt);

That worked. I got a handle and typed it into Spy++ handle text box. It turns out this window is a child window, so I navigated to its parent (that window’s name was “Store”) and finally to its parent with is the top level window. These are its properties:

image

The only extended style is WS_EX_TOPMOST. How about Process Explorer’s window?

image

Pretty much the same. So they all have the same extended style bit (WS_EX_TOPMOST), but Task Manager and the Metro window behave as “super topmost” in relation to other topmost windows. Task Manager’s window seems to be the strongest topmost ever. So far, I don’t know how that is configured.

WPF Tip: Attached properties and bindings

Published at May 12 2012, 10:04 PM by pavely

Attached properties are a great way to extend capabilities of existing elements without the need to derive or otherwise tinker with those elements. Suppose we create an attached property that is a collection of objects of some particular kind. When that property changes, those objects are read, and that special functionality is applied. Here’s a hypothetical example of such a scheme:

  1. public static class SomeHelper {
  2.     public static DemoCollection GetData(DependencyObject obj) {
  3.         return (DemoCollection)obj.GetValue(DataProperty);
  4.     }
  5.  
  6.     public static void SetData(DependencyObject obj, DemoCollection value) {
  7.         obj.SetValue(DataProperty, value);
  8.     }
  9.  
  10.     public static readonly DependencyProperty DataProperty =
  11.          DependencyProperty.RegisterAttached("Data", typeof(DemoCollection), typeof(SomeHelper), new UIPropertyMetadata(null, OnDataChanged));
  12.  
  13.     static void OnDataChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) {
  14.         var coll = (DemoCollection)e.NewValue;
  15.         // do something with collection
  16.         foreach(var d in coll) {
  17.             Trace.WriteLine(d.Text);
  18.         }
  19.     }
  20.  
  21. }
  22.  
  23. public class Demo : DependencyObject {
  24.     public string Text {
  25.         get { return (string)GetValue(TextProperty); }
  26.         set { SetValue(TextProperty, value); }
  27.     }
  28.  
  29.     public static readonly DependencyProperty TextProperty =
  30.          DependencyProperty.Register("Text", typeof(string), typeof(Demo), new UIPropertyMetadata(string.Empty));
  31.  
  32. }
  33.  
  34. public class DemoCollection : List<Demo> {
  35. }

To summarize: The SomeHelper class defines the Data property which is of type DemoCollection, which is a List of Demo objects. The reason DemoCollection is defined and the code doesn’t use List<Demo> directly, is because WPF’s XAML does not support generics at this time. For each Demo object within the collection, its property Text is printed using Trace.WriteLine. In a real application, this is where the special code would be.

Let’s use that in a simple scenario:

  1. <Grid>
  2.     <local:SomeHelper.Data>
  3.         <local:DemoCollection>
  4.             <local:Demo Text="Hello" />
  5.         </local:DemoCollection>
  6.     </local:SomeHelper.Data>
  7. </Grid>

The “local” XML prefix points to the namespace and assembly where the above types are defined. In this case, we should see “Hello” traced out to the Visual Studio debugger when running with the debugger. No surprise there.

Now suppose the value of the Text property is derived using data binding like so:

  1. <local:Demo Text="{Binding MyName}" />

This indicates that Text should be bound to the MyName property of the closest DataContext up the visual tree. Let’s set up the DataContext to be the current Window and MyName would be exposed through this window:

  1. public partial class MainWindow : Window {
  2.     public MainWindow() {
  3.         InitializeComponent();
  4.  
  5.         DataContext = this;
  6.     }
  7.  
  8.     public string MyName {
  9.         get { return "Cactus"; }
  10.     }
  11. }

When this is run, the expected output is “Cactus”. Surprisingly, the output is an empty string. The Visual Studio debugger outputs the following in the output window as a data binding error:

  1. System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=MyName; DataItem=null; target element is 'Demo' (HashCode=48380239); target property is 'Text' (type 'String')

It seems the DataContext didn’t “stick”: The message claims that DataItem=null, meaning there is no source for the binding, and so it fails.

If we try something even simpler, such as binding to a named element, such as the window itself with a well known property like this:

  1. <local:Demo Text="{Binding ActualWidth, ElementName=win}" />

(the window is named “win”). Again nothing appears, and the debugger output claims:

  1. System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=ActualWidth; DataItem=null; target element is 'Demo' (HashCode=63379435); target property is 'Text' (type 'String')

Same result. What’s going on? Can’t we use any binding in this case?

The problem is a bit subtle. A DataContext or any element for that matter cannot be found because there is no “WPF" parent” around. The Demo’s instance parent is the DemoCollection object, which knows nothing about WPF and so has no way of knowing who is its “parent” in the visual tree.

Are we doomed? Fortunately, there is a way to fix this. We need to work with an object that is more “WPF aware” than a simple List<>. The next best thing is FreezableCollection<T>. This can hold any object derived from DependencyObject, but Freezable is preferred, and in this case, required; Freezable is an interesting class in itself, but this is beyond the scope of this post and it doesn’t matter in this case. We don’t need the special aspects of Freezable, we just need its awareness of being part of the WPF world.

We need to make two changes. The first, in the collection:

  1. public class DemoCollection : FreezableCollection<Demo> {
  2. }

The other is making sure or Demo class is indeed a Freezable:

  1. public class Demo : Freezable {
  2.     public string Text {
  3.         get { return (string)GetValue(TextProperty); }
  4.         set { SetValue(TextProperty, value); }
  5.     }
  6.  
  7.     public static readonly DependencyProperty TextProperty =
  8.          DependencyProperty.Register("Text", typeof(string), typeof(Demo), new UIPropertyMetadata(string.Empty));
  9.  
  10.  
  11.     protected override Freezable CreateInstanceCore() {
  12.         throw new NotImplementedException();
  13.     }
  14. }

This forces us to implement the abstract CreateInstanceCore from Freezable, but that doesn’t matter in this case, because it will not be created by the Freezable cloning mechanism. In any case, implementing it is typically done by calling the new operator with the default constructor of the current type.

That’s it. Now binding works as expected in all scenarios.

Win32 and Metro–CreateFile(2)

Published at May 03 2012, 01:05 PM by pavely

When a new Windows version comes out, I’m always curious about the new Windows API (Win32) functions that are added to the release.

With Windows 8, things get a little more complicated, as there are desktop apps and there are metro apps. Now, for every Windows API function the documentation states whether this API is valid for desktop apps only or for desktop apps and metro apps.

One classic function is CreateFile. This is one of the oldest functions – exists since the very first Windows NT version. In Windows 8, it’s marked for desktop apps only. This may be understandable, as the Windows Runtime has other ways to use files, such as the StorageFile class. However, Windows 8 has a new function called CreateFile2. This one, in contrast to CreateFile, can be used in desktop and metro apps. Here’s its prototype:

  1. HANDLE WINAPI CreateFile2(
  2.   _In_      LPCWSTR lpFileName,
  3.   _In_      DWORD dwDesiredAccess,
  4.   _In_      DWORD dwShareMode,
  5.   _In_      DWORD dwCreationDisposition,
  6.   _In_opt_  LPCREATEFILE2_EXTENDED_PARAMETERS pCreateExParams
  7. );

Here’s the prototype of CreateFile:

  1. HANDLE WINAPI CreateFile(
  2.   __in      LPCTSTR lpFileName,
  3.   __in      DWORD dwDesiredAccess,
  4.   __in      DWORD dwShareMode,
  5.   __in_opt  LPSECURITY_ATTRIBUTES lpSecurityAttributes,
  6.   __in      DWORD dwCreationDisposition,
  7.   __in      DWORD dwFlagsAndAttributes,
  8.   __in_opt  HANDLE hTemplateFile
  9. );

The first four arguments of CreateFile2 exist in both CreateFile and CreateFile2. The new extended parameters structure of CreateFile2 simply packages the “missing” arguments into an single optional structure:

  1. typedef struct _CREATEFILE2_EXTENDED_PARAMETERS {
  2.   DWORD                 dwSize;
  3.   DWORD                 dwFileAttributes;
  4.   DWORD                 dwFileFlags;
  5.   DWORD                 dwSecurityQosFlags;
  6.   LPSECURITY_ATTRIBUTES lpSecurityAttributes;
  7.   HANDLE                hTemplateFile;
  8. } CREATEFILE2_EXTENDED_PARAMETERS, *PCREATEFILE2_EXTENDED_PARAMETERS, *LPCREATEFILE2_EXTENDED_PARAMETERS;

This structure actually adds nothing to what CreateFile can specify. The dwFlagsAndAttributes of CreateFile is logically split to three groups of flags represented by dwFileAttributes, dwFileFlags and dwSecurityQosFlags in this structure for CreateFile2. Although the split is a good thing, it doesn’t explain why CreateFile is forbidden in metro style apps. Furthermore, the documentation for CreateFile2 states that in metro apps this function can only open files and directories (and not things like pipes, mailslots, consoles, etc.).

So why is CreateFile forbidden in metro apps? Perhaps it does allow opening something that CreateFile2 forbids?

I decided to try calling it from a metro app. Trying to just use CreateFile would not compile, as a set of #ifdef/#endif is placed inside the Windows headers to prevent compiling a forbidden API. This, however, can be circumvented easily. We can just create the correct prototype manually:

  1. extern "C" {
  2.     HANDLE WINAPI CreateFileW(
  3.         __in      LPCTSTR lpFileName,
  4.         __in      DWORD dwDesiredAccess,
  5.         __in      DWORD dwShareMode,
  6.         __in_opt  LPSECURITY_ATTRIBUTES lpSecurityAttributes,
  7.         __in      DWORD dwCreationDisposition,
  8.         __in      DWORD dwFlagsAndAttributes,
  9.         __in_opt  HANDLE hTemplateFile
  10.     );
  11. }

This is just the CreateFile declaration from the docs wrapped in an extern “C” declaration; this is important, otherwise the liker would complain of an unresolved external (trying to look for C++ linkage). Also, note the function is declared as CreateFileW (the Unicode version) and not simply CreateFile, as CreateFile is actually a macro, and would not have been found by the linker.

Let’s add a simple call to this CreateFileW in a blank C++ metro style application in the BlankWindow constructor:

  1. HANDLE h = ::CreateFileW(L"C:\\Users\\Pavel\\Documents\\test.txt", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, 0);
  2. if(h == INVALID_HANDLE_VALUE) {
  3.     auto err = ::GetLastError();
  4. }
  5. else
  6.     ::CloseHandle(h);

This code tries to open a text file. This fails with error code 5 (access denied), as does CreateFile2. Although I set up the manifest with access to the documents library and set up a TXT file association, it refuses to work.

There doesn’t seem to be a noticeable difference between CreateFile and CreateFile2. I don’t understand at this time why CreateFile2 exists, apart from the convenience of that extra optional structure. There’s a room for further investigation, perhaps looking at NtDll.dll to see if these call different system services (unlikely, but worth a check).

WPF 4.5 Cookbook

Published at Apr 26 2012, 07:40 PM by pavely

A few months back, I was approached by Packt publishing, asking me to write a WPF book, in their “cookbook” style, and I accepted. I haven’t written an entire book before, but I have written dozen of courses for Hi-Tech College, John Bryce Training and now for CodeValue, in a range of topics, from Windows Internals and device driver development, to advanced C++, to basic and advanced .NET topics, to WPF, and even some oddities such as the Windows Media Foundation.

Writing a book, however, is different than writing a course, and I was at least curious whether I could produce something useful, given that WPF is not new and has already several decent books out there. So, what’s special about this book? First, it doesn’t target the absolute beginner, although I do cover most of WPF fundamentals in the first two chapters, but is more oriented towards the intermediate WPF developer, and sometimes a bit higher than that (or so I hope). Second, I do expect this “cookbook” style, where recipes to common problems are presented, followed by explanations and expansions, to feel a somewhat different experience, where dependencies among recipes are almost non-existent (and we all know dependencies are bad Smile).

And third, I ‘m reminded by an interview I read a few years back with Dino Esposito, who told the following story about himself: He was to give a session in a conference about COM (Component Object Model). Before that session started, he noticed Don Box (then the ultimate guru of COM) sitting down in the first row to listen. Dino walked up to him and asked why is he here? Surely, there’s nothing new Dino can teach Don Box about COM. Don Box replied, “It’s all about perspective”. Well, this is my perspective on WPF.

According to the publisher, the book must be around 300 pages. This is pretty low for WPF, as WPF is huge, so I had to cut down some topics, to make sure I’m covering the major WPF pillars. Eventually, I expect to be at around 350 pages.

The book includes 11 chapters, 6 of which I’ve already written (without incorporating technical reviewers’ comments):

1. Foundations

2. Resources

3. Layout and Panels

4. Using Standard Controls

5. Application and Windows

6. Data Binding

7. Commands and MVVM

8. Styles, Triggers & Templates

9. Graphics & Animation

10. Custom Elements

11. Threading

The expected publication date (if all goes well) is around August.

The book official page is at http://www.packtpub.com/windows-presentation-foundation-4-5-cookbook/book

Windows Devices UG Meeting Reminder: WinRT & Metro Apps

Published at Apr 17 2012, 06:31 PM by pavely

The Windows Devices user group managed by Elad Shaham and myself is meeting next Tuesday (the 24th) at Microsoft Offices in Ra’anana. We’ll have two sessions dedicated to Windows 8.

Full agenda and registration (free) is available at http://insidewindowsruntime.eventbrite.com/

See you there!

WPF 4.5: Markup Extension for Events

Published at Apr 07 2012, 06:34 PM by pavely

One of the new features coming in WPF 4.5 (already available through the Visual Studio 11 Beta and .NET 4.5 Beta) is the ability to create markup extensions that work on events (as opposed to properties, which have always had this capability).

Markup extensions for properties are crucial, and there are quite a few useful ones, such as {Binding} and {StaticResource}. Would this ability be useful for events?

One such case is when a command is needed to be invoked (ICommand) because of some event, typically found in MVVM scenarios. The problem is that only some events can actually trigger a command (out of the box) such as Click for ButtonBase and Click for MenuItem. What about other events? What about other elements that don’t implement ICommandSource and therefore have no Command property to connect to?

This is where a markup extension for events can come in handy. The solutions so far to this issue usually involved using the Interactivity assembly from the Expression Blend SDK, that provides actions, triggers and behaviors, one of which provides a way to invoke a command (InvokeCommandAction). We can try to do something similar using the new feature, which will not require the Blend SDK at all.

How to use it

Let’s look at the usage first. Consider a simple paining program the draws lines on a Canvas. We want to handle a mouse down, move and up events in the ViewModel (as opposed to the view). This decouples things, and provides command objects that can later be used to manage (e.g.) undo/redo features. Here’s how the Canvas markup should look like:

  1. <Canvas ClipToBounds="True" Background="White"
  2.         MouseLeftButtonDown="{local:EventToCommand StartPaintCommand}"
  3.         MouseMove="{local:EventToCommand AddLineCommand}"
  4.                              MouseLeftButtonUp="{local:EventToCommand EndPaintCommand}">
  5. </Canvas>

The markup extension constructor is interpreted as a property path to bind to (relative to the current DataContext). At first, it seems easier to add a Command property (of type ICommand) to the markup extension (and I did) , but it’s really useful; that’s because it’s not possible to provide a {Binding} expression as the value of that property. To do that we’d have to turn the Command property to a dependency property – but we can’t because MarkupExtension does not derive from DependencyObject Sad smile

The solution I used was to declare a BindingCommandPath property (or via the constructor), that interprets the property path as a binding path (this is the most common scenario). A helper method digs into the property path and gets the actual value:

  1. static object ParsePropertyPath(object target, string path) {
  2.     var props = path.Split('.');
  3.     foreach(var prop in props) {
  4.         target = target.GetType().GetProperty(prop).GetValue(target);
  5.     }
  6.     return target;
  7. }

This little method does not support indexing, but that is not commonly used, and in any case wouldn’t be too hard to add.

Creating a markup extension

Writing a markup extension for events is fundamentally no different than writing it for properties. The first thing is to create a class deriving from MarkupExtension:

  1. public sealed class EventToCommandExtension : MarkupExtension {

The main thing to do is implement the abstract ProvideValue method. This should return something appropriate – in an event case, a delegate object appropriate for the event’s delegate type.

A command can receive a parameter – in this case it would probably want the sender and the RoutedEventArgs-derived type. For this a created a simple generic class:

  1. public sealed class EventCommandArgs<TEventArgs> where TEventArgs : RoutedEventArgs {
  2.     public TEventArgs EventArgs { get; private set; }
  3.     public object Sender { get; private set; }
  4.  
  5.     public EventCommandArgs(object sender, TEventArgs args) {
  6.         Sender = sender;
  7.         EventArgs = args;
  8.     }
  9. }

Now for the main event: overriding ProvideValue. Here we need to return an alternative (our own) handler, that will invoke the required command. First, let’s get the service that provides some context for the markup extension usage:

  1. public override object ProvideValue(IServiceProvider sp) {
  2.     var pvt = sp.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;

Now we can examine the TargetProperty property to get the actual event object. Curiously enough, it’s sometimes an EventInfo (which is expected), but sometimes it’s a MethodInfo. So we need to deal with the difference and eventually connect to our own handler, called DoAction:

  1. if(pvt != null) {
  2.     var evt = pvt.TargetProperty as EventInfo;
  3.     var doAction = GetType().GetMethod("DoAction", BindingFlags.NonPublic | BindingFlags.Instance);
  4.     Type dlgType = null;
  5.     if(evt != null) {
  6.         dlgType = evt.EventHandlerType;
  7.     }
  8.     var mi = pvt.TargetProperty as MethodInfo;
  9.     if(mi != null) {
  10.         dlgType = mi.GetParameters()[1].ParameterType;
  11.     }
  12.     if(dlgType != null) {
  13.         _eventArgsType = dlgType.GetMethod("Invoke").GetParameters()[1].ParameterType;
  14.         return Delegate.CreateDelegate(dlgType, this, doAction);
  15.     }
  16. }

The trick is to create the exact delegate type (it’s RoutedEventHandler or something more specific – we need that specificity to make the command implementor itself simpler and type safe; more on that in a moment. That’s why we create the delegate dynamically with Delegate.CreateDelegate.

In our DoAction method, we need to invoke the connected command correctly:

  1. void DoAction(object sender, RoutedEventArgs e) {
  2.     var dc = (sender as FrameworkElement).DataContext;
  3.     if(BindingCommandPath != null) {
  4.         Command = (ICommand)ParsePropertyPath(dc, BindingCommandPath);
  5.     }
  6.     Type eventArgsType = typeof(EventCommandArgs<>).MakeGenericType(_eventArgsType);
  7.     var cmdParams = Activator.CreateInstance(eventArgsType, sender, e);
  8.     if(Command != null && Command.CanExecute(cmdParams))
  9.         Command.Execute(cmdParams);
  10. }

Again, because we don’t know in advance what kind of EventArgs are actually used by that particular event, we create the EventCommandArgs generic type dynamically, by first creaing the “open” type (with no specific generic parameter) and then calling MakeGenericType to make it a creatable “closed” type. Then we call ICommand.Execute if ICommand.CanExecute returns true.

Implementing the commands

The PaintingViewModel class implements the three commands shown above. Here’s the command to start painting:

  1. bool _isPainting;
  2. ICommand _startPaintCommand;
  3. public ICommand StartPaintCommand {
  4.     get {
  5.         return _startPaintCommand ?? (_startPaintCommand = new RelayCommand<EventCommandArgs<MouseButtonEventArgs>>(args => {
  6.             var element = args.Sender as IInputElement;
  7.             _lastPoint = args.EventArgs.GetPosition(element);
  8.             element.CaptureMouse();
  9.             _isPainting = true;
  10.         }));
  11.     }
  12. }

RelayCommand<> is the typical command used in MVVM scenarios (look at the source code). It’s sometimes called DelegateCommand (available in Prism, but they’re similar).

Here’s the command bound to a mouse move event:

  1. ICommand _addLineCommand;
  2. public ICommand AddLineCommand {
  3.     get {
  4.         return _addLineCommand ?? (_addLineCommand = new RelayCommand<EventCommandArgs<MouseEventArgs>>(args => {
  5.             var element = args.Sender as IInputElement;
  6.             var pt = args.EventArgs.GetPosition(element);
  7.             Model.AddLine(_lastPoint, pt);
  8.             _lastPoint = pt;
  9.         }, args => _isPainting
  10.         ));
  11.     }
  12. }

The Model property is of type Paining that holds a collection of LineInfo objects. Again, look at the source.

Here’s a view at runtime:

image

What’s New in CLR 4.5 Debugging API?

Published at Apr 03 2012, 07:51 PM by pavely

The most used command in the SOS extension DLL is probably !dumpheap. This command is able to show every object on the managed heap. This capability has no match within Visual Studio. The reason is that Visual Studio uses the CLR debugging API, that doesn’t seem to have this capability.

At first glance, the ICorDebugProcess interface has the perfect method: EnumerateObjects. What could be better than that? Unfortunately, the documentation states that this method is not implemented… bummer.

A while back I created a project CLR Explorer. This was supposed to be a tool to look at managed processes. Looking at metadata was easy enough, but runtime information was scarce, as the debug interfaces did not have a way to get managed heap information.

With .NET 4.5. beta released, I looked through the debug interfaces. I wanted to see if anything changed since CLR 4. I discovered there is a new interface supposedly supported on a CorDebugProcess object, ICorDebugProcess5. This new interface (the previous one was ICorDebugProcess3 – clearly the number 4 was to be avoided to not give the false impression that this is available with CLR 4).

This new interface has a method named EnumerateHeap – great! finally… and the method seems to be documented as having an actual implementation.

So, I decided to give it a try…

Attaching to a Process

Warning! C++ (and COM) ahead!

First, let’s get the CLR meta host object:

  1. CComPtr<ICLRMetaHost> spMetaHost;
  2. hr = ::CLRCreateInstance(CLSID_CLRMetaHost, __uuidof(ICLRMetaHost), (void**)&spMetaHost);

This object is the root for starting to work with the CLR (debugging or not). It was introduced in CLR 4.

We need to get the ICorDebug interface. This is how it’s done (hProcess is a handle to the process we want to attach to – obtained using the usual OpenProcess API):

  1. CComPtr<IEnumUnknown> spEnumUnk;
  2. spMetaHost->EnumerateLoadedRuntimes(hProcess, &spEnumUnk);
  3. CComPtr<IUnknown> unk;
  4. spEnumUnk->Next(1, &unk, NULL);
  5. CComQIPtr<ICLRRuntimeInfo> spInfo(unk);
  6. ATLASSERT(spInfo);
  7. CComPtr<ICorDebug> spDebug;
  8. spInfo->GetInterface(CLSID_CLRDebuggingLegacy, __uuidof(ICorDebug), (void**)&spDebug);

(Error handling is mostly non existing to keep the code short)

Now we need to initialize the ICorDebug object and attach to the process to debug:

  1. hr = spDebug->Initialize();
  2. CComObject<CDebugManagedCallback>* pHandler;
  3. pHandler->CreateInstance(&pHandler);
  4. spDebug->SetManagedHandler(pHandler);
  5.  
  6. CComPtr<ICorDebugProcess> spProcess;
  7. hr = spDebug->DebugActiveProcess(pid, FALSE, &spProcess);

The CDebugManagedCallback class is a local C++ COM class that is the handler for debugging events. I will not show this one here (you can check out the CLR Explorer project to see one such class in action). For the purpose of this post, it really is just there so ICorDebug would be happy.

Now for the fun part. Can we get an ICorDebugProcess5? If we can, let’s use it:

  1. CComQIPtr<ICorDebugProcess5> spProcess5(spProcess);
  2. if(spProcess5) {
  3.     COR_HEAPINFO heapInfo;
  4.     hr = spProcess->Stop(0);
  5.     hr = spProcess5->GetGCHeapInformation(&heapInfo);
  6.     cout << "GC Type: " << (heapInfo.gcType == CorDebugWorkstationGC ? "Workstation" : "Server") << endl;
  7.     cout << "Heaps: " << heapInfo.numHeaps << endl;
  8.     if(heapInfo.areGCStructuresValid) {
  9.         CComPtr<ICorDebugHeapEnum> spEnumHeap;
  10.         hr = spProcess5->EnumerateHeap(&spEnumHeap);
  11.         ULONG count;
  12.         hr = spEnumHeap->GetCount(&count);
  13.         if(SUCCEEDED(hr)) {
  14.             // unfortunately... hr = E_NOTIMPL
  15.             cout << "# Objects: " << count << endl;
  16.         }
  17.         COR_HEAPOBJECT obj;
  18.         hr = spEnumHeap->Next(1, &obj, nullptr);    // works!
  19.         CComPtr<ICorDebugType> spType;
  20.         spProcess5->GetTypeForTypeID(obj.type, &spType);
  21.         if(spType) {
  22.             CorElementType type;
  23.             spType->GetType(&type);
  24.             cout << type << endl;
  25.         }
  26.     }
  27. }

The ICorDebugProcess5::GetGCHeapInformation gets some basic info for the heap. Then we can enumerate the objects on the managed heap. The GetCount method on the enumeration interface is not implemented, which makes perfect sense, since this information is unknown to the CLR, would be expensive to keep track of, and adds no real value.

The Next method however, works! Now we can enumerate the heap!

A new version of CLR Explorer is certainly due!

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.

More Posts Next page »