Trying to figure out in which process a particular DLL is currently loaded, I have found two solutions (perhaps there are more).

Solution 1: tasklist.exe

Solution 2: listdlls.exe (from sysinternals)

It might be that listdlls is more reliable than tasklist. I have ran into cases when tasklist failed to list processes that had a specific dll loaded, while listdlls was showing them.

, , Hits for this post: 31295 .

DocProject with Sandcastle are a great choice for creating MSDN-style documentation. You can author conceptual documentation using MAML (Microsoft Assistance Markup Language) and reference documentation from managed assemblies and XML comments. Here is the documentation for DocProject. Writing conceptual documentation I ran into some problems that were not straight forward to solve. Hopefully these tips will help you if you have the same problems.

Overloaded Methods
The codeEntityReference tag allows you to link to API reference documentation (namespaces, types, methods, properties, fields). You have to prefix the fully qualified name of the entity with N: for namespaces, T: for types, P: for properties, F: for fields and M: for methods. What if you have overloaded methods and you want to link to the page that displays all of them, not one particular method? The O: prefix Visual Studio is expecting (for XML comments) does not work. Sandcastle Help File Builder (SHFB) expects Overload: instead.

Methods with arguments
If you want to link to API reference documentation for a method that take some parameters you must specify those parameter’s type in parenthesis.

However, if the method takes more than one parameter, you must separate the argument types with a comma and use no whitespaces between them. If you have whitespaces the API reference will not be resolved.

Constructors are special methods so you must use a special notation for them: instead of using their name use the #ctor tag.

Of course, if the constructor has some arguments you must specify them in parenthesis:

When it comes to generics you must use the special notation with ` (grave accent). The grave accent (`) indicates the level and the number after it is the number of the generic types. Here are the rules (as indicated in the ECMA specification ):

  • Arguments that define generic type parameters have an appended grave accent character followed by the number of type parameters (ex. T`1)
  • For nested types, the number is based upon the of new type parameters on the nested type(ex. T`1.Nested`2)
  • Arguments that refer to generic type parameters on types are encoded using a single grave accent character (`) followed by the zero-based index of the type parameter.
  • Arguments that use generic parameters on methods use double grave accent characters (``) followed by the zero-based index of the type-parameter instead of the single grave accent used for parameters on types.

For instance, let’s say your class looks like this:

If you want to link to the generic bar type you must do it like this:

What if you had a generic method too?

Then you must refer to the function as follows:

API Reference Documentation
When you author documentation you probably want to put together conceptual documentation and API reference documentation. The later you build from external sources, i.e. assemblies and XML files with the XML-comments you wrote in the source code. Question is where and how do you insert this API reference? The answer was not very easy to find; luckily a colleague of mine was able to help me with the answer.

First of all, there is only one place in the hierarchy of your topics hierarchy where you can insert it. So no matter from how many sources you build this, it all goes into one place. To set the place you must edit the topics.xml file (under Help\Settings). This file looks like this (of course, this is a dummy sample):

There is a special tag you can insert as a child of a topic. It’s called stoc and looks like this:

This will tell the builder to insert under topic1 all the API reference documentation.

, , , , Hits for this post: 28346 .

It is possible to register both 32-bit and 64-bit versions of the same COM server on 64-bit machine. This leads to several questions such as how are they registered and which one of the two is used. I will try to answer them below. But first, let’s start with an example.

Let’s say we have the a simple COM local server called COM3264Server.exe. There is just one interface called ICoCOM3264Server. Here is the IDL file:

The implementation of the method SayHello() is straight forward; it just displays a message box with a text that varies between the two architectures, x64 and x86.

When you register the COM server, the 32-bit and 64-bit versions are registered in different parts of the registry. On 64-bit machine, the registry has two views (or modes):

  • a native view, for 64-bit application; (e.g. registry path for CLSIDs is HKEY_CLASSES_ROOT\CLSID\)
  • a WOW64 view, which enables redirections for 32-bit applications, a process transparent to the user (e.g. registry path for CLSIDs is HKEY_CLASSES_ROOT\Wow6432Node\CLSID\)

Here is the Registry registration of the (native) 64-bit COM server (notice the registry key in the status bar of the editor, and the path to the server executable).

On, the other hand, the 32-bit COM server is registered under the Wow6432 node.

So if both versions are registered in Windows Registry, which one is picked? Well, both the server and the client can specify which architecture to use:

  • the COM server can do this via the PreferredServerBitness Registry value
  • the client can do this using one of the flags CLSCTX_ACTIVATE_32_BIT_SERVER and CLSCTX_ACTIVATE_64_BIT_SERVER, which overrides the server preference

If neither the client nor the server specifies a preference, then:

  • If the computer that hosts the server is running Windows Server 2003 with Service Pack 1 (SP1) or a later system, then COM will try to match the server architecture to the client architecture. In other words, for a 32-bit client, COM will activate a 32-bit server if available; otherwise it will activate a 64-bit version of the server. For a 64-bit client, COM will activate a 64-bit server if available; otherwise it will activate a 32-bit server.
  • If the computer that hosts the server is running Windows XP or Windows Server 2003 without SP1 or later installed, then COM will prefer a 64-bit version of the server if available; otherwise it will activate a 32-bit version of the server.

Server Preference
The server can specify its preferred architecture in the PreferredServerBitness value under AppId (available only on 64-bit Windows). This integer value can be:

  • 1: Match the server architecture to the client architecture. For example, if the client is 32-bit, use a 32-bit version of the server, if it is available. If not, the client’s activation request will fail.
  • 2: Use a 32-bit version of the server. If one does not exist, the client’s activation request will fail.
  • 3: Use a 64-bit version of the server. If one does not exist, the client’s activation request will fail.

Here is the value set in Registry to specify the 64-bit architecture.

When you run the client, it launches the 64-bit version and in my example the following window pops-up:

If I change the value to indicate the 32-bit architecture, the other COM server is launched and the displayed message is:

Client Preference
The client code I used so far looked like this:

However, the 64-bit version of Windows added new flags to the CLSCTX enumeration.

  • CLSCTX_ACTIVATE_32_BIT_SERVER: used to activate or connect to a 32-bit version of the server; fail if one is not registered.
  • CLSCTX_ACTIVATE_64_BIT_SERVER: used to activate or connect to a 64 bit version of the server; fail if one is not registered.

As I mentioned earlier, if the client uses one of these flags, it overrides the server preference (specified via the PreferredServerBitness Registry value).

In the following example, the client requests the 64-bit COM server:

And if you run it, no matter what the server specified, the 64-bit COM server is launched.

To read more about the subject see the MSDN links above.

, , , Hits for this post: 70100 .

COM Apartments

If you work with COM, apartments is one of the concepts you must comprehend, because it’s an important topic. Before explaining what apartments are let’s think about classes and objects regardless of COM. When you build a class, you know (or you should) whether objects of that class will be used from a single thread, or from multiple threads. In the later case, if those threads might access shared data at the same time, you must synchronize the access to that data (using critical sections, mutexes, or others). So when you create your class you either make it thread-safe or not. If it’s not thread safe, objects of that class can only be accessed from one thread at a time, if it’s thread-safe, then objects of that class can be accessed from different threads at the same time.

Now, the same rule applies in the COM world. Your coclasses can either be thread-safe or not. If the are thread-safe, you can access one object from different threads at a time, otherwise not. Here enter the apartments. So what is an apartment? An apartment is an environment in which COM objects can live. It’s not a thread, nor a process, but it handles access from COM clients to COM objects. There are several types of apartments: single-threaded apartments (STA), multi-threaded apartments (MTA) and neutral-threaded apartments (NTA).

Single-Threaded Apartments
An STA allows only one thread at a time to access a COM object. This is achieved using a hidden window with a message pump. Calls from clients living in different threads are queued with the message pump. Only when the current call from a thread ends, the next call can proceed.

Assume you had a COM object called CoUserGroups that implements an interface IUserGroups that provides two methods: one called Add that adds a new user group, and one called Delete that deletes a user group. Since both methods work on the same list of user groups, adding and deleting is not possible at the same time without synchronizing access. But since such synchronization was not implemented, the COM object specifies that it can leave only in an STA, and let the apartment do the synchronization of calls from clients living in different threads.

Multi-Threaded Apartments
An MTA allows any number of threads to access a COM objects. However, the COM objects must be thread-safe, otherwise your application will behave unexpectedly and even crash.

Going back to the previous example, if CoUserGroups was implemented in a thread-safe manner, then it would be possible for clients living in different threads to access it. In this case there would be no need for an apartment level synchronization. The COM coclass specifies that it can live in an MTA and when simultaneous calls from different threads are received they are directed immediately to the COM object. This situation is shown in the next image.

Neutral-Threaded Apartments
NTAs, like MTAs, allow multiple threads to enter one apartment, but once a thread entered the apartment it acquires an apartment wide lock that will block the other threads, until the current thread exists the apartment. Calls into NTA (from STA or MTA in the same process) do not generate context switches; the thread leaves the apartment in which it executes and enters the NTA without any context switch, which increases performance. This model was introduced with COM+ (in Windows 2000) and is meant for components with no user interface.

A process can contain several apartments:

  • zero or one MTA
  • zero or one NTA
  • zero, one or several STAs; the first STA created for a process is called the main STA

As a COM client, you specify the apartment you want to join with a call to CoInitializeEx(). This methods must be called from each thread.

The second parameters is a set of flags specifying the initialization options for the thread. To join the unique MTA, use COINIT_MULTITHREADED. To join a new or existing STA, use COINIT_APARTMENTTHREADED. Function CoInitialize() calls CoInitializeEx() specifying COINIT_APARTMENTTHREADED for the flags.

How to specify the threading model allowed for a coclass?
A coclass can specify the type of apartment it can join. If you’re using ATL you can specify that when you create the coclass. The next image shows the available options:

What they mean:

  • Single: object wants to join the main STA (the first STA created into the process)
  • Apartment: object wants to join one of the STAs in the process
  • Both: object wants to join either an STA or the MTA
  • Free: object wants to join the MTA
  • Neutral: object wants to join the NTA

ATL adds the appropriate value to the registry script it creates for your coclass. COM depends entirely on the registry, and the threading model is also specified in the registry. Here is an example:

When that is merged into the Windows Registry, it looks like this:

The possible values in registry are:

  • no value specified: equivalent of ATL ‘Single’
  • Apartment: equivalent of ATL ‘Apartment’
  • Free: equivalent of ATL ‘Free’
  • Both: equivalent of ATL ‘Both’
  • Neutral: equivalent of ATL ‘Neutral’

If you want to read more about COM apartments I suggests articles like this one.

, , , , , , Hits for this post: 54798 .

.NET allows you to expose components as COM and consume them from unmanaged code. There are many references on how to this (and you can only start with MSDN), and I will not talk about that part. What I want to explain here is something different. Suppose you have this interface:

Method GetUsers() returns an array on string representing the user names. But what if you also wanted the user passwords or addresses? Since this is exposed as COM, you cannot return an array of User. But you can return multiple arrays of string. So, how would you deal with out string[]? This is what I want to show you in this tutorial.

This is a .NET interface exposed to COM. It has two methods, GetUsers() that returns an array of string representing user names, and GetUsers2() that returns an array of strings as an output parameters and a bool as return type, indicating whether any user was found.

And this is the implementation:

Note: If you are trying this example make sure you set the ComVisible attribute to true, either for each type or per assembly (in AssemblyInfo.cs)

Second, you have to check the “Register for COM interop” setting in the Build page of the project properties.

The first thing to do in C++ is importing the .TLB file that was generated by regasm.exe.

If we look in the .TLB file, we can see how the IAccounts interface looks like:

The following C++ functions, GetUsers1() retrieves the users users list using method GetUsers() from IAccounts. It puts the users in a CStringArray (notice that this container does not have an assignment operator, so the only way to return such an array is with a reference in the parameters list).

UnpackBstrArray() is a function (see below) that extracts the elements of a SAFEARRAY and adds them to a CStringArray.

Function GetUsers2() uses the second method, GetUsers2() from IAccounts. This needs the address of a pointer to a SAFEARRAY (i.e. SAFEARRAY**) that will hold the values returned by the COM method. This time we have to create an empty SAFEARRAY and then pass its address to the COM method. The rest is similar to the previous case.

The helper method UnpackBstrArray() used previous looks like this:

Attached you can find a demo project (C# and C++) with the complete example show in this tutorial.

output SAFEARRAY** example (1518)

, , , , , Hits for this post: 66823 .

Project Tuva

Project Tuva is an enhanced video player created by Microsoft Research to freely host the lectures give my Richard Feynman at the Cornell University in the ’60s. Bill Gates saw the lectures two decades ago, was impressed with them and wanted to make them freely available. Now, it finally happened. You can watch them at Microsoft Research.

The seven lectures given by professor Feynman are:

  • Law of Gravity
  • The Relation of Mathematics and Physics
  • The Great Conservation Principles
  • Symmetry in Physical Law
  • The Distinction of Past and Future
  • Probability and Uncertainty – The Quantum Mechanical View of Nature
  • Seeking New Laws

These are great lectures given by one of the greatest physicists of the 20th century. They really worth watching.

, , , Hits for this post: 20091 .

Arrays in F#

Yesterday I wrote about list in F#. Today I’ll write about arrays, which unlike lists are a mutable flat storage and cannot be resized. That means you have to create a new array if you want to remove or add elements. Advantages include constant look-up time and the fact that they can store a large amount of data.

You can create a literal array in a similar way with the lists, placing the elements between [| |]:

The empty literal array is [||].

To create an array you can either use Array.create or Array.init. They both create and initialize an array, but the second makes a lambda expression, which allows advance initialization possibilities. The following creates an array with 10 elements initialized to 1:

Here is the output:

The same can be achieved using Array.init:

But we can use Array.init to initialize the elements from 1 to N for instance:

The arrays are mutable data structures. Elements are accessed with .[] or .(). The following code shows how to set the elements of an array:

You can iterate over the elements of an array with Array.iter and Array.iteri, the second also providing access to the index of the elements.

Retrieving the length of the array can either be done with Array.length arr or with arr.Length.

Like the lists, arrays provide mapping that creates a new array by applying a function on all the elements of an array (with or two arrays (with Array.map2).

A copy of an array can be done with Array.copy.

Appending elements to an array is also possible with Array.append, but the result is a new array, created by concatenating two arrays.

The last operation of arrays I’m going to mention here is the folding, which allows applying a function to all the elements of an array, threading an accumulator argument in the process. The following example shows how to compute the sum of the elements of an array.

Hits for this post: 41848 .

Lists in F#

In this post I will talk about the lists in F#, one of the fundamental concepts of the language. What should be said from the very beginning is that list are imutable single linked list. That means whenever you change a list, a new list is created.

You can declare a list in the following ways:

To print the content of the list you can do this:

You can concatenate two lists with operator @:

and you can append elements to the beginning of the list with operator ::

You can also use the List (defined in Microsoft.FSharp.Code) functionality to print a list by iterating over its elements:

The same can be achieved using the pipe operator:

You can also iterate and get the index of the list elements, with List.iteri:

List have a special representation, a head followed by a tail, that is in turn another list (including empty list []). Let’s consider the list [1;2;3]. It has the head 1, and the tail [2;3]. The tail, in turn, has the head 2 and the tail [3]. This tail has the head 3 and the tail [], which is the empty list.
You can see the head and tail of a list with List.hd and

The ouput for list1 [1;2;3] is:

Enough with basic things. Let’s try working with lists.

1. Minimum and maximum from a list

We can compute the maximum (or minimum) of a list using the following algorithm:

  • if the list is empty, indicate error
  • if the list has only one element, that is the maximum (or minimum)
  • if the list has at least to elements, compute the maximum between that element and the maximum from the rest of the list

That sounds like a recursive operation, which can be simply put in F# like this:

We can use that like this:

and the output would be:

2. Reversing a list

How would we reverse a list? We should take the last element and append to it the one before the last. To the new list we append the one before the one before the end, etc. That again sounds recursive.

And here is the output:

3. Inserting in a list

So how could we insert an element in a list, before or after a specified element? We can use the following algorithm:

  • if the list is empty, the new list has one element (the one to insert)
  • else, if the head is the element we are looking for, create a list, with the new element either before the head, or between the head and the tail
  • else, if the head is not the element we are looking for, append the head to a list created by inserting the new element in the tail.

You got that right, recursion again.

And the output is:

4. Removing elements from a list

As a last exercise, let’s consider the removing of elements from a list. The following steps can be used to remove elements:

  • if the list is empty, return an empty list
  • if the list is not empty and the head meets the removing criteria, return a list obtained by reiterating the algorithm on the tail of the list
  • if the list is not empty and the head does not meet the removing criteria, return a list obtained by appending the head to a list optained by reiterating the algorithm on the tail of the list

The great thing about this implementation is that we can pass a lambda expression as a predicate, and use it to specify the criteria for removing elements. We can remove like that, for instance, the odd elements, or the even elements, or the negative elements. Here is some sample code:

The output for this sample is:

I hope this will help you to get a grip on how you can work on lists in F#.

Hits for this post: 35195 .