DCSIMG
July 2009 - 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

July 2009 - Posts

Changing Console Fonts

Published at Jul 23 2009, 08:43 PM by pavely

The other day I created a Console application and changed some colors and sizes. Then I needed to change the font (programmatically). I looked at the System.Console class – nothing. Maybe they just forgot to wrap it up, I thought, and turned to the Win32 API functions for the Console. Guess what? Nothing. Well, almost nothing. There’s a new function (starting with Vista) called SetCurrentConsoleFontEx, but it’s almost useless. It requires a console font index (which is supposed to be from a console font table, which no documented API reveals), and it doesn’t seem to work quite as expected. The font size is given as a COORD structure (in “logical” units, where “logical” is not explained), and even then, only certain sizes actually work, with no indication why).

All this can be done pretty easily through a “shortcut” to the console app (IShellLink), but I needed something more dynamic, to be available at runtime.

This felt really wrong. It seems that some functions are missing. A quick google and some depends.exe reveals that there are actually a few functions that can help in kernel32.dll, namely SetConsoleFont, GetConsoleFontInfo and GetNumberOfConsoleFonts – the catch: undocumented.

With the google help and some investigating I was able to get the prototypes, and they seem to work from XP all the way to Windows 7 in much the same way. At least there’s a way to enumerate those fonts and change to the one you like! I also found another undocumented function, SetConsoleIcon, to change the icon. A bonus!

The prototypes are:

typedef struct _CONSOLE_FONT {

   DWORD index;

   COORD dim;

} CONSOLE_FONT;

 

BOOL WINAPI SetConsoleFont(HANDLE hOutput, DWORD fontIndex);

BOOL WINAPI GetConsoleFontInfo(HANDLE hOutput, BOOL bMaximize, DWORD numFonts, CONSOLE_FONT* info);

DWORD WINAPI GetNumberOfConsoleFonts();

BOOL WINAPI SetConsoleIcon(HICON hIcon);

I’ve created two files ConsoleFont.h/cpp that use those prototypes to make the changes.

I’ve also created a managed wrapper (ConsoleHelper.cs) that can be used from managed code, like so:

static void Main(string[] args) {

   var fonts = ConsoleHelper.ConsoleFonts;

   for(int f = 0; f < fonts.Length; f++)

      Console.WriteLine("{0}: X={1}, Y={2}",

         fonts[f].Index, fonts[f].SizeX, fonts[f].SizeY);

   ConsoleHelper.SetConsoleFont(5);

   ConsoleHelper.SetConsoleIcon(SystemIcons.Information);

}

You may use these at your own risk, as these are undocumented functions, and can be changed in the future by Microsoft, although I believe they will eventually be documented.

There are still things missing. That mysterious console font table – I didn’t find a function that can be used to add entries to it. Perhaps it’s lurking in the registry somewhere. There’s no (exported) AddConsoleFont or something like that.

Happy fonting!

Microsoft HPC Server 2008 and Parallel Techniques

Published at Jul 15 2009, 10:05 PM by pavely

The multi-core mini-revolution signalled the rise of multithreading techniques being discussed more vigorously, as the exploitation of multiple cores is no longer the reach of a few individuals, but is as common as the computer itself.

Another way to get performance scalability is simply to use multiple machines, running some application or parts of it at the same time, hopefully distributing the workload appropriately and communicating if and as required to get the final result. Combining the two techniques (multiple cores and multiple machines) can be even more powerful.

I have been recently introduced to the Microsoft HPC Server 2008 (High Performance Computing), which is a cluster of Windows 2008 64 bit machines, managed by the HPC Server software. This package allows executing jobs (consisting of individual tasks, which are simply executables) that may be configured to run on multiple cores on multiple machines managed by the cluster.

The HPC Server 2008 is the second version of Microsoft’s computing cluster, the first being the Microsoft Compute Cluster Server 2003 (MCCS), built on top of Windows Server 2003 and released in 2006 (followed by a SP1 in 2007).

HPC centres around cluster management, with some client tools to manage a cluster of computers: add nodes (computers), remove, add jobs, and otherwise manage and monitor the cluster. The only requirement is that each and every machine must be a Windows 2008 64 bit server. A client, running any version of Windows, can issue jobs programmatically, or by running the client management tools (supplied with the HPC 2008 Pack).

A typical configuration of HPC Server is as follows:

image

The Head node functions as the “controller” of the cluster, effectively dispatching the jobs to the compute nodes. There is nothing special about the Head node – in fact, the Head node can also be a compute node.

The broker nodes are a special case used when WCF is used to “invoke” a job in a typical WCF way, by calling a service. Internally, the HPC infrastructure translates the call to a job, as HPC is a batch oriented system that simply pushes jobs to the compute nodes.

image

Programming the cluster

The HPC does not deal directly with how to parallelize jobs or tasks. It’s simply a manager and a job dispatcher with decent tools for configuring and monitoring operations. The actual programming is another matter altogether.

What follows is a non-exhaustive list of ways to parallelize stuff on a Windows platform. Some are based on a single machine and some on cluster based techniques.

Libraries and APIs

  • Hard core multithreading – using native Windows threads, either working with the Windows API (CreateThread) or the .NET (roughly equivalent) Thread class. This is definitely the most difficult option, requiring careful planning and doing correct synchronization, considering the available cores, etc. There are plenty of sources of information on how, why and why not to do hard core threading.
  • OpenMP – OpenMP is a standard library to do parallel stuff more easily. It’s implemented as a set of #pragmas that add threading support to a C/C++ applications, without the need to create actual OS threads. Microsoft has implemented the OpenMP 2.0 standard (the current standard being 3.0), and is integrated into Visual Studio 2008. Here’s a simple program that does matrix multiplication in a single threaded manner and then with OpenMP:

#include <omp.h>

 

const int size = 1000;

 

int m1[size][size], m2[size][size];

int m3[size][size];   // result

 

int _tmain(int argc, _TCHAR* argv[]) {

   ::srand(GetTickCount());

 

   for(int i = 0; i < size; i++)

      for(int j = 0; j < size; j++) {

         m1[i][j] = ::rand() % 100;

         m2[i][j] = ::rand() % 100;

      }

   printf("Starting single threaded...\n");

   DWORD start = ::GetTickCount();

 

   for (int i = 0; i < size; i++)

      for (int j = 0; j < size; j++) {

         m3[i][j] = 0;

         for (int k = 0; k < size; k++)

            m3[i][j] += m1[i][k] * m2[k][j];

      }

 

   DWORD stop = ::GetTickCount();

   printf("Elapsed: %d msec\n", stop - start);

   printf("\nStarting with OpenMP parallel for...\n");

   start = ::GetTickCount();

 

#pragma omp parallel for

   for (int i = 0; i < size; i++)

      for (int j = 0; j < size; j++) {

         m3[i][j] = 0;

         for (int k = 0; k < size; k++)

            m3[i][j] += m1[i][k] * m2[k][j];

      }

 

      stop = ::GetTickCount();

      printf("Elapsed: %d msec\n", stop - start);

 

   return 0;

}

The #pragma omp parallel for is the key to parallelizing the outer for loop. OpenMP creates the best number of threads, which is the number of cores in this case. Here’s the  output on my machine (x64 release):

image

We get a nice 84% speed increase, as OpenMP created 2 threads on my dual-core machine. It will create 4 threads on a quad core machine and distribute the work evenly.

  • Task Parallel Library (TPL) a.k.a. Parallel Extensions – in the upcoming .NET 4.0 framework, the high level Task class along with some even-higher level types, such as Parallel will make some things easier in the .NET world. The Parallel.For method, for instance, is the rough equivalent of the above OpenMP #pragma omp parallel for:

Parallel.For(0, 100000, x => DoSomethingWithX(x));

This will automatically parallelize the loop with respect to the number of existing cores, and works great assuming there is no dependency between iterations.

  • MPI – MPI (Message Passing Interface) is a C based library that takes a different approach to parallelism. Instead of focusing on threads, it focuses on processes, so that data does not need to be synchronized (different address space), but to share information a message passing framework is used, which is the heart of MPI. A typical scenario is a master process handing work to worker processes (which may run on different machines), and collects the results when the work is done. The master and workers are actually written with the same code. An MPI based process starts up using a dispatcher tool, mpiexec.exe, which launches all processes with different IDs (called “ranks” in MPI terminology). Each process examines its rank (passed indirectly by a command line argument) and decides what to do (be a master or a worker). This idea scales well on clusters and is supported on HPC Server 2008.
  • MPI.NET – a .NET object oriented wrapper around the MPI library (Codeplex – no release at this time, but available from the university of Indiana). It’s still in a kind of alpha, being supported but not developed by Microsoft, and does not wrap the entire MPI API, but most of it. It may be a reasonable alternative for managed developers to harness the cluster for parallel computing.
  • MPI with OpenMP – there is nothing to stop combining OpenMP multithreading support in a single process with MPI capabilities to stretch across processes and machines. Not usually done, because things may get hairy pretty quickly, but definitely a worth while alternative.
  • Intel tools – Intel has some tools (such as the Intel Parallel Studio recently released) for doing multithreaded stuff (all targeting native developers only), as well as tools to analyze multithreading issues, such as deadlocks and race conditions. They all cost a fair amount of money as opposed to others such as OpenMP and MPI. Intel tools are a topic onto itself which I will not tackle here.

There’s definitely a lot going on in the multi-core, multithreaded, and cluster worlds right now and it won’t be going away any time soon (quite the opposite). Now is a good time to jump on the parallel wagon and see where it takes you (avoiding deadlocks of course…)

Using Embedded Fonts in WPF from a Controls Library

Published at Jul 11 2009, 07:33 PM by pavely

I stumbled upon a thorny issue of using custom fonts (that are not installed on the user’s system) in a WPF application. Using such a custom font is not too difficult when the font is added as a resource to an EXE, but is more difficult to use when it’s in a referenced assembly.

The whole thing is based on the pack URI syntax (which is not too intuitive, but one can get used to it). With an EXE, the font is accessed as a “local” resource. For example, if I add a font, myfont.ttf, I can select it like so:

FontFamily="pack://application:,,,/#myfont"

If the font is embedded in another assembly I’m referencing, then I need to use the extended syntax, like so (assume MyControls is the other assembly):

FontFamily="pack://application:,,,/MyControls;component/.#myfont"

The not-so-obvious thing is how code located in the MyControls library accesses a font (or other resource) located in its own assembly. Should it be treated as a “local” resource (local to the MyControls assembly), or should we look at it through the eyes of the executable that will eventually reference this MyControls library?

It turns out, that the MyControls assembly (DLL) must use the extended (referenced assembly) syntax to access a resource embedded in its own assembly (just as the last example shows).

Maybe this will save someone some time.

I Don’t like “Aero”, but I want thumbnail previews

Published at Jul 06 2009, 10:29 AM by pavely

I don’t like the “Aero” themes in Vista/Windows 7. I tried. I really did. I decided to work for several days with Aero and it was uncomfortable – and it has nothing to do with video card performance. It’s distracting. I simply don’t like it.

I guess I’m entitled to my opinion. But if I don’t use Aero I don’t get thumbnail previews and other goodies. Why is that? I asked around and didn’t get a satisfying answer. The most common was “you must move on to the modern style”. Modern? I think not.

There is no reason (in my humble opinion) to remove thumbnail previews and other features in the “Classic” them. Why can’t I use the Classic theme and have thumbnail previews at the same time?

If anyone has a good answer, I’ll be happy to get it.