DCSIMG
May 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

May 2012 - Posts

Visual Studio Tip: Show Threads in Source

Published at May 29 2012, 12:20 PM by pavely

Debugging multithreaded applications is always hard, so any help we can get from the debugger is appreciated.

Here’s one tip that can help using Visual Studio 2010 when many threads are running at the same time, some of which run similar code.It’s tedious to lookup each thread’s call stack to see where its next instruction pointer is located. Here’s the Threads window in action:

image

To find the actual source line each thread is at the breakpoint moment, we’ll need to switch to that thread by double clicking it in the Threads window and then we’ll see something like this in the editor:

image

We can keep double clicking threads and get to each one’s source.

The Debug toolbar has a nice alternative, called “Show Threads in Source”:

image

Clicking the marked button causes Visual Studio to show locations of other threads with a special icon:

image

This means there is at least one thread is at the location marked with the “wavy” icon. Hovering that icon displays a tooltip for those threads that are, in fact, at that source line:

image

With this, you can get a quick sense of where threads are running at the moment.

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