Inside and Out…

An attempt to understand technology better…

Enumerating AppDomains – I

Posted by Gaurav Khanna on June 9, 2007

Surprisingly, enumerating AppDomains is not that straightforward. The System.AppDomain type does not expose functionality to enumerate them at all. The way to enumerate them will be to use the V1 Hosting interface, ICorRuntimeHost and then invoke the EnumDomains and NextDomain methods against it to get the list. If you are using CLR 2.0, you needn’t worry as CLR 2.0 does implement the V1 interfaces as well.

 

Below is the snippet that exemplifies the concept (note: AppDomains will only be enumerated in the current process – I will discuss AppDomain enumeration in remote processes later). You can download the source code (VS Solution) from http://www.wintoolzone.com/ListDotNET.aspx?Listtype=5

 

// EnumAppDomains.cpp : Defines the entry point for the console application.
// 
#include "stdafx.h"
#include <windows.h>
#include "mscoree.h"
#import "C:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727\\mscorlib.tlb" raw_interfaces_only
using namespace mscorlib; 
#define EXITONERROR(hr, mesg) \
if (FAILED(hr)) \
{ \
printf("%s\n", mesg); \
ExitProcess(1); \
} 
#define SUCCESSFUL(hr) (SUCCEEDED(hr) && hr != S_FALSE) 
int _tmain(int argc, _TCHAR* argv[])
{
ICorRuntimeHost * pV1HostPtr = NULL;
HRESULT hr = CorBindToRuntimeEx(NULL,
NULL, 0, 
CLSID_CorRuntimeHost,
IID_ICorRuntimeHost,
(LPVOID *)&pV1HostPtr);
EXITONERROR(hr, "Unable to get ICorRuntimeHost*"); 
// Start the runtime
hr = pV1HostPtr->Start();
EXITONERROR(hr, "Unable to start the runtime"); 
// Enumerate the AppDomains
HDOMAINENUM adEnum;
hr = pV1HostPtr->EnumDomains(&adEnum);
EXITONERROR(hr, "Unable to enumerate AppDomains");
// Loop thru the domains
IUnknown * pDomainUnk = NULL;
hr = pV1HostPtr->NextDomain(adEnum, &pDomainUnk);
while(SUCCESSFUL(hr))
{
// Got the IUnknown* to the AppDomain - convert it to AppDomain pointer
_AppDomain * pCurDomain = NULL;
hr = pDomainUnk->QueryInterface(__uuidof(_AppDomain), (VOID**)&pCurDomain);
if (SUCCESSFUL(hr))
{
// Display the name of the AppDomain
BSTR str;
if (SUCCESSFUL(pCurDomain->get_FriendlyName(&str)))
{
wprintf(L"AppDomain: %s\n",str);
}
else
{
printf("AppDomain: unable to get the name!\n");
}
} 
// Loop onto the next Domain
hr = pV1HostPtr->NextDomain(adEnum, &pDomainUnk);
} 
// Stop the runtime
if (pV1HostPtr)
{
pV1HostPtr->Stop();
}
return 0;
} 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: