why is my System.ServiceModel.OperationContext null from silverlight client and the SOAP Message Header – note to me

When you are starting out with Silverlight and WCF/SOAP to implement WS-Security using SOAP headers into request messages or for that matter if you are accessing SOAP services from silverlight, you may run into this silly issue that’s why I am making note of it here.

Silverlight documentation clearly says that

SOAP headers are supported via the OutgoingMessageHeaders and IncomingMessageHeaders properties inside an operation method call.

OutgoingMessageHeaders is the outgoing message headers for the active OperationContext.

Use the OperationContext from within a service operation to access the current operation execution environment.

The OperationContext has the following properties and methods.

  • The Current property returns the OperationContext object that represents the current execution context.

Documentation is not very clear so this is when you may run into this issue because OperationContext is null if you directly access OperationContext.Current from silverlight client.

Let’s look at OperationContext .Current setter to find out who sets it, as shown below in reflector snapshot. Now you know  OperationContextScope sets the Context so you have to first create OperationContextScope using your ContextChannel before accessing the current Operation Execution Environment.

using (OperationContextScope contextScope = new OperationContextScope(client.InnerChannel))
reflector snapshot

Thread Scheduling Priority in .NET and no idle priority thread

I have seen numerous .net application where a background thread is created for background tasks but at the same time thread scheduling priority is never set. By default, managed thread runs with normal relative priority so now if you have a thread doing some maintenance work,  that thread has no reason to run with Normal relative priority or sometime even the thread sending occasional updates to UI will run with normal relative priority

However, managed thread doesn’t allow you to set the thread priority to true THREAD_PRIORITY_IDLE class.

If you have done Win32 development then you are used to calling ::CreateThread() with Suspended flag and ::SetThreadPriority() to start thread with some priority. The default behavior of ::CreateThread is to create a thread with Normal Priority(relative to process priority class) same as managed Thread.Start(), but you will have to pass CREATE_SUSPENDED flag first.

If you insert a breakpoint in kernel32!CreateThread, you will see that Thread.Start() will call into this Win32 API because this is the only way you can create a thread in Windows OS, even if you use CRT _beginthreadex. One important difference is you don’t have an option to specify thread CreationFlags in managed code.

visit msdn documentation http://msdn.microsoft.com/en-us/library/74169f59.aspx for more information on Managed and Unmanaged Threading.

Managed Thread doesn’t support THREAD_PRIORITY_IDLE but rather maps it to THREAD_PRIORITY_LOWEST and also it doesn’t support THREAD_PRIORITY_TIME_CRITICAL.

PAL documentation says that SetThreadPriority should set THREAD_PRIORITY_IDLE to the least-priority value the host operating system allows, as the common language runtime sets threads to THREAD_PRIORITY_IDLE then busy-waits with a Sleep(0) loop until the garbage collection thread has run, with the garbage collection thread at a priority greater than idle.

Another important aspect to managed runtime is when you write your own host, you can use fiber to map one os thread to multiple managed threads with your own scheduling algorithm since fiber is implemented in usermode. Jeffrey Richter’s book “Programming Applications for Microsoft Windows” has very good description on Fiber. Windows OS supports fiber mainly for portability since other operating systems don’t have the same threading model.

But, if you do need to map managed thread priority to supported thread priority in windows , you can use System.Diagnositcs.ProcessThread. System.Diagnostics.ThreadPriorityLevel maps one to one with thread priority class in Win32 API(windows server 2003/XP).

Windows Vista/7 and windows server 2008 introduced THREAD_MODE_BACKGROUND_BEGIN and THREAD_MODE_BACKGROUND_END see the msdn documentation http://msdn.microsoft.com/en-us/library/ms686277(VS.85).aspx

If you really want to have your application to do task in background with minimal impact to system resources, you should consider setting thread priority to THREAD_MODE_BACKGROUND_BEGIN on Windows 7/2008 through interop.

One important point is, most of the managed application don’t really need a thread with idle priority, you can meet your application’s performance objectives by manipulating the thread scheduling priority less or higher than default Normal relative priority as defined in  System.Threading.ThreadPriority Enumeration

Tess Blog – First look at debugging .NET 4.0 dumps in Visual Studio 2010

First look at debugging .NET 4.0 dumps in Visual Studio 2010

Tess talks about debugging a memory dump generated in .NET 4.0 using VS2010.

And Wow, VS 2010 supports post mortem debugging for managed application and as Tess mentioned you no longer need to learn WinDbg/SOS for some of the common debugging scenarios.  VS2010 also has source server support and along with intutive debugging environment, VS2010 is a big step forward to integrate mixed mode debugging in it.

When Application or Process Isolation is not really the solution


There is an Application Server which apparently dies with OutOfMemory Exception. It has been determined that App Server is not scalable at all because it needs one thread per user so that means 1000 user sessions will consume 1000 threads, holding on to 1GB of virtual memory with 30% cpu spent in Interrupt so yeah you hear the story right.

I came across this issue and the adopted solution which I think is worth mentioning.

The next thing I heard App Server has been split into 2 Application Server and the 2nd process contains user’s session consuming all the threading resources. One of the idea behind this architecture was to give each process 2GB of virtual address space. And on top of that, both the app servers need to be up and running in order to serve a request. And on top of that, no client is consuming services from the 2nd app server. Another point to note is, application server in question is a very simple application server with no algorithmic complexities, but rather act as a middle man processing the request with some caching and data manipulation.

Really ?? We all know that process isolation provides stability and reliability with fault tolerant architecture but at the same time they don’t depend on each other.

With the above architecture they didn’t only introduce latency because of inter process communication but the real issue which is one thread per user with user mode default stack size consuming 1 MB of virtual memory never got resolved.

If you are implementing process isolation because of the above reason, just don’t do it. This is the time to rethink and redesign your application server to make sure that your application server is scalable to support 1000 users without consuming 1000+ threads

Silverlight App not working as expected in FireFox, IE shows error message “Unhandled Error in Silverlight 2 Application – Element is already the child of another element”

Problem Description

This exception is thrown in a Silverlight 2 App while trying to show and hide System.Windows.Controls.TabItem in System.Windows.Controls.TabControl

Steps to Recreate

browse to http://debuggingblog.com/sl/project1/default.html and click on button “Show Angelina”  3 times

Debugging Silverlight app using WinDbg

We will be analyzing a memory dump of IE on System.InvalidOperationException

1. We have the following two InvalidOperationException exception objects on managed heap

0:007> !dumpheap -type System.InvalidOperationException
Address       MT     Size
1013c79c 0f1ff824       72
1015addc 0f1ff824       72
total 2 objects
MT    Count    TotalSize Class Name
0f1ff824        2          144 System.InvalidOperationException
Total 2 objects

2. Lets get the stack trace when this exception occured

0:007> !pe 1013c79c
Exception object: 1013c79c
Exception type:   System.InvalidOperationException
Message:          Element is already the child of another element.
InnerException:   <none>
StackTrace (generated):
SP       IP       Function
021FF640 0F40F06A !MS.Internal.XcpImports.CheckHResult(UInt32)+0×32
021FF64C 0E3A4CE9 !MS.Internal.XcpImports.SetValue(MS.Internal.INativeCoreTypeWrapper, System.Windows.DependencyProperty, System.Windows.DependencyObject)+0xa9
021FF680 0E3A4118 !MS.Internal.XcpImports.SetValue(MS.Internal.INativeCoreTypeWrapper, System.Windows.DependencyProperty, System.Object)+0×100
021FF71C 0E3A3FBC !System.Windows.DependencyObject.SetObjectValueToCore(System.Windows.DependencyProperty, System.Object)+0x1c4
021FF760 0E3A1CBB !System.Windows.DependencyObject.SetValueInternal(System.Windows.DependencyProperty, System.Object, Boolean, Boolean, Boolean)+0×503
021FF834 0E3A17A1 !System.Windows.DependencyObject.SetValueInternal(System.Windows.DependencyProperty, System.Object)+0×21
021FF848 0E3A1763 !System.Windows.DependencyObject.SetValue(System.Windows.DependencyProperty, System.Object)+0x1b
021FF85C 0E3D68D7 !System.Windows.Controls.ContentControl.set_Content(System.Object)+0×37
021FF870 0E3212CF !SilverlightApplication1.Page.ShowContent()+0×57

021FF880 0E3208BE !SilverlightApplication1.Page.ShowHideAngelina_Click(System.Object, System.Windows.RoutedEventArgs)+0×76
021FF898 0E4099B5 !System.Windows.Controls.Primitives.ButtonBase.OnClick()+0x5d
021FF8B0 0E40993F !System.Windows.Controls.Button.OnClick()+0×47
021FF8C0 0E40986D !System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(System.Windows.Input.MouseButtonEventArgs)+0×85
021FF8D0 0E4097D1 !System.Windows.Controls.Control.OnMouseLeftButtonUp(System.Windows.Controls.Control, System.EventArgs)+0×41
021FF8E0 0E36C887 !MS.Internal.JoltHelper.FireEvent(IntPtr, IntPtr, Int32, System.String)+0x1b7

3. This exception occured while trying to Set the Content of a Control, so lets find out what is this content and who holds this UIElement, lets get the IL of method SilverlightApplication1.Page.ShowContent()

0:007> !dumpil 0f224060
ilAddr = 0f4607f8
IL_0000: ldarg.0
IL_0001: newobj System.Windows.Controls.TabItem::.ctor  // A new TabItem object is created
IL_0006: stfld SilverlightApplication1.Page::item
IL_000b: ldarg.0
IL_000c: ldfld SilverlightApplication1.Page::item
IL_0011: ldstr “Angelina Jolie”
IL_0016: callvirt System.Windows.Controls.TabItem::set_Header
IL_001b: ldarg.0
IL_001c: ldfld SilverlightApplication1.Page::item//Get the reference to a  TabItem object created earlier
IL_0021: ldarg.0
IL_0022: ldfld SilverlightApplication1.Page::content
IL_0027: callvirt System.Windows.Controls.ContentControl::set_Content //Set_Content is called  with SilverlightApplication1.Page object’s data member content
IL_002c: ldarg.0
IL_002d: ldfld SilverlightApplication1.Page::TabList
IL_0032: callvirt System.Windows.Controls.ItemsControl::get_Items
IL_0037: ldarg.0
IL_0038: ldfld SilverlightApplication1.Page::item

We have 2 interesting objects TabItem and SilverlightApplication1.Page::content here

4. First get the address of SilverlightApplication1.Page::content object which is being set in TabItem because that’s what resulting in exception

0:007> !do 1003b3c0
Name:        SilverlightApplication1.Page
MT    Field   Offset                 Type VT     Attr    Value Name
0f42e730  400000d       58 …Windows.UIElement  0 instance 1011c0e8 content

0:007> !dumpheap -mt 0e396648
Address       MT     Size
1003ed3c 0e396648      140
101276a0 0e396648      140
1013c050 0e396648      140
total 3 objects
MT    Count    TotalSize Class Name
0e396648        3          420 System.Windows.Controls.TabItem
Total 3 objects

We have 3 TabItem objects on heap and the address of the content object(UIElement) is 1011c0e8

5. The next step to find out is which TabItem object has this UIElement and why is this TabItem object still around.

0:007> !dumpheap -mt 0e396648
Address       MT     Size
1003ed3c 0e396648      140
101276a0 0e396648      140
1013c050 0e396648      140
total 3 objects

0:007> !do 101276a0
Name:        System.Windows.Controls.TabItem
MethodTable: 0e396648
EEClass:     0e3bb768
Size:        140(0x8c) bytes
File:        System.Windows.Controls, Version=, Culture=neutral
MT    Field   Offset                 Type VT     Attr    Value Name

0ec444e8  40002b4       34        System.Object  0 instance 1011c0e8 _treeContent

0:007> !gcroot 101276a0
Note: Roots found on stacks may be false positives. Run “!help gcroot” for
more info.
Scan Thread 7 OSTHread 1710
Scan Thread 27 OSTHread 1200
Scan Thread 28 OSTHread 1278
Scan Thread 31 OSTHread 1488

6. TabItem object with address = 0e396648 has the reference to content object 1011c0e8 and this object is not rooted so that means this object is ready to be garbage collected.

There is already a TabItem object on managed heap holding reference to the same content object which is being assigned to new TabItem object on SilverlightApplication1.Page.ShowHideAngelina_Click(), that’s why we get System.InvaildOperationException with the error message “Element is already the child of another element”

7. You can get the address of Method Description for each of the methods in SilverlightApplication1.Page

0:007> !dumpmt -md 0f224094
MethodDesc Table
Entry       MethodDesc      JIT Name
0e320848   0f224038 JIT SilverlightApplication1.Page.ShowHideAngelina_Click(System.Object,
0e321300   0f224058      JIT SilverlightApplication1.Page.HideContent()
0e321278   0f224060      JIT SilverlightApplication1.Page.ShowContent()

Let’s look at the implementation of ShowHideAngelina_Click

0:007> !dumpil 0f224038
ilAddr = 0f46071c
IL_0012: ldstr “Show”
IL_0017: callvirt System.String::Contains
IL_001c: brfalse.s IL_003f
IL_001e: ldloc.0
IL_0039: call SilverlightApplication1.Page::ShowContent
IL_003e: ret
IL_003f: ldloc.0
IL_004a: ldarg.0
IL_004b: call SilverlightApplication1.Page::HideContent
IL_0050: ret

This method checks the Text of the button and calls ‘ShowContent’ if the text =“Show” otherwise calls ‘HideContent’, so let’s look at HideContent implementation

0:007> !dumpil 0f224058
ilAddr = 0f4607d6
IL_0000: ldarg.0
IL_0001: ldfld SilverlightApplication1.Page::item
IL_0006: brfalse.s IL_001f
IL_0008: ldarg.0
IL_0009: ldfld SilverlightApplication1.Page::TabList
IL_000e: callvirt System.Windows.Controls.ItemsControl::get_Items
IL_0013: ldarg.0
IL_0014: ldfld SilverlightApplication1.Page::item
IL_0019: callvirt class [System.Windows]System.Windows.PresentationF◆䷒¥⽫Ż�::Remove
IL_001e: pop
IL_001f: ret

HideContent calls TabList.get_Items and remove the TabItem from System.Windows.Control.TabControl


HideContent() method removes the TabItem from TabControl.Items so unless TabItem is Garbage Collected  removed TabItem will still hold the reference to Content UIElement. You can quickly fix this issue by assiging Content = null, when that item is removed as shown below in HideContent

//OLD Buggy Implementation

private void HideContent()
if (item != null)

//new implementation to make sure Content is set to null

private void HideContent()
item.Content = null; //assign TabItem Content = NULL
if (item != null)

Unhandled Error in Silverlight 2 Application – Invalid or malformed application: Check manifest

This error is very silly and obviously there is something wrong with the Manifest file as shown below

Webpage error details

Message: Unhandled Error in Silverlight 2 Application
Code: 2103
Category: InitializeError
Message: Invalid or malformed application: Check manifest

Code: 0

But if this helps anyone, i would like to point out that When you create a silverlight application using visual studio, it copies XAP package in ‘ClientBin” folder. You can either unzip the .XAP file to look at AppManifest.xaml or if you have access to source code then you can direcly open “AppManifest.xaml” file from bin/<> folder.

Make sure these entries are correct

EntryPointType=”SilverlightApplication1.App//this should be same as your “Namespace.Application” class
<AssemblyPart x:Name=”SilverlightApplication1″ Source=”SilverlightApplication1.dll(make sure that, this is the output dll you have in your project configuration)/>

By default,    app.xaml will have the application class=”App”, i have changed it to “MyControl” as shown below so if you are using visual studio and you have renamed your project or App class make sure to make the corresponding changes in Project Configuration (assembly name, startup project)

public class MyControl: Application
public App()
this.RootVisual = new Page();

Dissecting Silverlight Control/XAP package and How to create a barebone silverlight application – Silverlight wins hands down over ADOBE AIR/Flash in some areas

When you use visual studio to create a silverlight application, you will notice that it creates the application xaml, page xaml and their corresponding code behinds. When you build the application, xap package will be created inside ‘ClientBin” folder along with a test page.

I will show you how to create a silverlight xap package without visual studio with a very simple control to help you understand how silverlight control essentially works. In my previous post I mentioned how a browser based on http response loads Silverlight Plug-in(NPCTRL.DLL) with MIME type=”application/x-silverlight-2″ specified in object tag.

Let’s first look at Silverlight Application Project which gets created by default using Silverlight Application project template in visual studio. It creates the following files in a silverlight application project


AppManifest.xml contains the XAML object elements Deployment and Depolyment Parts which is used to build application package’s manifest file. When AppManifest xaml file is generated for XAP package, it also includes the followings

<            EntryPointAssembly=”MySilverlightControl”
<AssemblyPart x:Name=”XName” Source=”MySilverlightControl.dll” />

EntryPointAssembly/Type and the Assembly Part are mandatory in a Silverlight Application because that’s how coreservices determines the entry point in an assembly.

App.xaml.cs implements the followings

public partial class App : Application


public App()
this.Startup += this.Application_Startup;
this.Exit += this.Application_Exit;
this.UnhandledException += this.Application_UnhandledException;


private void Application_Startup(object sender, StartupEventArgs e)
this.RootVisual = new Page();

private void Application_Exit(object sender, EventArgs e)
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs         private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)

Application class is essentially adding the event listener to AGCORE.DLL through Managed Runtime and sets the root as Page object in a visual tree. Below is the implementation of InitializeComponent

public void InitializeComponent()
    if (!this._contentLoaded)
       this._contentLoaded = true;
        Application.LoadComponent(this, newUri("/MyControl;component/App.xaml", UriKind.Relative));

InitializeComponent implementation will fool you into believing that you will need xaml file. But you don’t even need to call InitializeComponent unless of course you are using designer generated code, behind the scene designed generates the source code for xaml file

So far, we have seen that silverlight project has an App class which derives from System.Windows.Application and apart from setting the event listeners for error handling and etc, it just sets the visual root to a Page object which is nothing but System.Windows.Control.UserControl deriving from System.Windows.Controls.Control ..and Control in turn from UIElement.

When you build the project, it will create a xap pacakge which is nothing but just a ZIP file. XAP package includes assemblies and the application manifest XAML file and that’s what get hosted in a web page

Let’s put these pieces together

1. We need a web server which can support MIME Type=application/x-silverlight-2 to serve silverlight content

2. web page hosts silverlight control by including a XAP package in object tag

3. XAP package is a zip archive format which includes application manifest(xaml file) and a managed assembly

4. managed assembly should have System.Windows.Application object

5. Application object needs a visual root tree which could be any control/UIElement

6. and of course managed assembly will need silverlight runtime

Steps to create a barebone Silverlight Control with no visual studio or xaml

1. Open your notepad and type the followings to create your barebone silverlight control deriving from System.Windows.Application and save it as MySilverlightControl.cs

public class MySilverlightControl : System.Windows.Application

public MySilverlightControl()

//create a textblock control and assign a width,height with text =”hello silverlight”
System.Windows.Controls.TextBlock txtBlock = new System.Windows.Controls.TextBlock();
txtBlock.Text = “Hello Silverlight”;
txtBlock.Width = 800;
txtBlock.Height = 600;

//make sure it is centered
txtBlock.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
txtBlock.VerticalAlignment = System.Windows.VerticalAlignment.Center;

//margin (left,top,..)
txtBlock.Margin = new System.Windows.Thickness(400, 300, 0, 0);
txtBlock.FontSize = 24;
//set the application visual root to txtblock control
this.RootVisual = txtBlock;

2. Launch command prompt to compile this file to create a MySilverlightControl.dll

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\csc /target:library MySilverlightControl.csc.exe /reference:”C:\Program Files\Microsoft Silverlight\2.0.40115.0\System.Windows.dll”

3. Type the followings in a notepad to create application manifest xaml file

<Deployment xmlns=”http://schemas.microsoft.com/client/2007/deployment”
<AssemblyPart x:Name=”XName” Source=”MySilverlightControl.dll” />

Rememeber these attributes are mandatory in a silverlight application assembly but not in a class library. I have copied Runtime Version from http://msdn.microsoft.com/en-us/library/cc265156(VS.95).aspx

The above URL describes the MIME type and their corresponding silverlight runtime version. EntryPointAssembly and the other attributes are self explanatory and that’s what will be used by coreservices.

4. Zip those 2 files AppManifest.xaml and MySilverlightControl.dll with .xap extension

5. Create the following html file and copy it under the same folder as .xap file

<title>Barebones – Silverlight Control Testing</title>
<div id=”silverlightControlHost”>
<object data=”data:application/x-silverlight-2,” type=”application/x-silverlight-2″ width=”100%” height=”100%”>
<param name=”source” value=”MySilverlightControl.xap”/>

Below is the snapshot
browser snapshot

This is it and your silverlight control is ready to be hosted.

Obviously, you don’t need to manually create it, but this is an attempt to explain how silverlight works and what are the components involved in a silverlight control. You can dynamically generate a code or even use Reflection.Emit to generate MSIL and above all host your content on any webserver with mime type=”application/x-silverlight-2″ for silverlight 2 runtime.

This makes Silverlight very powerful and at the same time very simple to implement and silverlight coreclr has great debugging tool in WinDbg/CoreCLR!SOS.

Kudos to Microsoft Silverlight team.

silverlight is very appealing when it comes to out of browser experience and the development platform. Of course there are some limitations in silverlight app because it runs in security sandbox model so that means no access to filesystem but the development platform along with deployment makes a great case for consideration if you are thinking about using Adobe Flash/AIR

Dissecting Silverlight and CoreCLR Runtime on Windows OS using WinDbg – Silverlight Plugin and Silverlight .NET runtime explained

Let’s deep dive into silverlight run time and find out how the request is processed
We need fiddler ,  WinDbg  and a browser in Windows OS. We have a simple html page hosted in IIS with a Silverlight control in it as shown below
<html><head>   <title>SilverlightApplication1</title></head>
<body> <div id=”silverlightControlHost”>
<object data=”data:application/x-silverlight-2,” type=”application/x-silverlight-2″>
<param name=”source” value=”ClientBin/SilverlightApplication1.xap”/>
</object>  </div></body></html>

Attach browser to WinDbg, if you are using IE8 then make sure that you are attaching the child process (tabbed browser), use process explorer to identify the child process.
Execute command “.cmdtree <pathname>sld.txt” as shown below; you can download sld.txt from here as shown below

command tree snapshot

Silverlight runtime by default gets installed under <system drive> \Program Files\Microsoft Silverlight\<version #>
As shown below

silverlight runtime installation folder

We will be interested more in native dll which makes up of Silverlight runtime. .NET library is part of Silverlight CoreCLR.
In order to get the order of the loaded modules of Silverlight runtime, we can execute command “sxe ld” or you can double click on “Break On Loaded Modules” from command tree and browse to html page containing Silverlight xap file.

You need to ignore most of the dlls but the one loaded from “C:\Program Files\Microsoft Silverlight\2.0.40115.0” (Silverlight runtime path on my machine). The order of loaded modules is
Npctrl.dll, agcore.dll, coreclr.dll, .net dlls
You can use any disassembler  or ndepends to look at the exported functions or download one from http://www.smidgeonsoft.prohosting.com/pebrowse-pro-file-viewer.html to look at these native dlls

Below is the snapshot for NPCTRL.DLL
NPCTRL.DLL snapshot

NPCTRL.dll is a COM dll which gets loaded in browser when http request is made with silverlight control in it(object tag). Shown below in the fiddler

Browser determines this based on http response since the MIME type in html file is
type=”application/x-silverlight-2″. NPCTRL.dll gets loaded as Silverlight Plug-in.

This occurs before XAP package gets downloaded,

fiddler snapshot

As shown below, you can now clear breakpoints on loaded modules and set breakpoint for each of dll one by one because debugger remembers the last ld settings.

command treesnapshot

You may want to change the symbols path to Silverlight runtime so that you can set breakpoints on all exported methods (see the above snapshot).

NPCTRL.DLL imports followings from AGCORE.DLL

command treesnapshot

NPCTRP.DLL first loads AGCORE.DLL. NPCTRL.dll implements CXcpBrowserHost/CommonBrowserHost and it makes a call to agcore!ObtainCoreServices to set the frameworkcallbacks. NPCTRL.DLL also implements CWindowsServices::CreateCLRRuntimeHost. NPCTRL.dll calls NPCTRL!GetCLRRuntTimeHost to load CORECLR.dll . CORECLR.dll is our Silverlight .NET runtime engine, basically stripped down version of MSCORWKS.dll

coreclr dll

Once CLRRuntime is created, coreclr will create a domain and load the .net assembly as a private copy using normal assembly binding. CORECLR will use PEImage layout to map the view of file same as .net runtime. Below is the call stack when application domain for coreclr is set up

0220f4d4 04a9b399 System.Activator.CreateInstance(System.String, System.String)
0220f4e8 04a9b349 System.AppDomain.CreateInstance(System.String, System.String)
0220f504 04a9b298 System.AppDomain.CreateInstanceAndUnwrap(System.String, System.String)
0220f51c 04a9b1d8 System.AppDomain.CreateDomainManager(System.String, System.String)
0220f560 04a94d6a System.AppDomain.SetDomainManager(System.Security.Policy.Evidence, System.Security.Policy.Evidence, IntPtr, Boolean)
0220f5b0 04a98dfd System.AppDomain.Setup(System.Object)

Once app domain is set up, ManagedRuntimeHost will be created as shown below from the reflector

Managed Runtime Host snapshot

This is when coreclr will also set up System.Windows.Threading.DispatcherSynchronizationContext for Single Threaded Apartment (UI). At this point, it will also create a callback handler in AGCORE.DLL. AGCORE.DLL is the Unmanaged version of Silverlight. AGCORE.DLL implements event listener, Setting the visual root and the callback handler is used for communication between CORECLR and AGCORE.

The main interface for communication between CORECLR and AGCORE is MS.Internal.XcpImports(implemented in System.Windows.DLL) XcpImports is the interop layer importing the exports section in AGCORE.dll


Once XcpImports.SetFrameworkCallbacksNative is called to set the callback handler, MS.Internal.FrameworkCallbacks will create System.Windows.DependencyObject.

After dependency object is created, Application object will be created as shown below

0220f2e4 0108008d SilverlightApplication1.App..ctor()
0220f850 026b2e90 System.Reflection.ConstructorInfo.Invoke(System.Object[])
0220f860 026b2a98 MS.Internal.TypeProxy.CreateInstance(UInt32)

.net library will be responsible for creating the visual tree and passing the buffer into agcore.dll native code and so on.

when does XAP package get downloaded?

Once NPCTRL.DLL and AGCORE.DLL are loaded, NPCTRL!CommonBrowserHost implements (shown below) npctrl!CommonBrowserHost::OnGotSourceDownloadResponse and this will make a call into agcore!CCoreServices::StartDeploymentTree which in turn calls agcore!CCoreServices::CLR_Startup and finally this will be routed to  npctrl!CWindowsServices::CreateCLRRuntimeHost to load CORECLR.DLL, see below for the callstack

kernel32!LoadLibraryW - Will load CORECLR.DLL

Silverlight with better production debugging support – SOS.dll in coreclr has better extension command support than sos in CLR 2.0

sos.dll installed with Silverlight Runtime has more extension commands compare to mscorwks version of SOS. Although you can load coreclr version of sos with command “.loadby sos coreclr” to make sure that you have the sos loaded from the same location as your coreclr.dll, but you should also get the sos.dll when you are debugging a silverlight app dump from a customer machine because silverlight has more than one runtime version.

Below are the cool/new extension commands in silverlight version of sos to make our life easier, please note that some of these extension commands and dml were supported in .NET framework 1.1 SOS version but not in 2.0

1. DML support, you can turn it on by executing command “.prefer_dml 1″ or you can add “/D” with individual command. DML will definitely save you lot of typing as shown below

This allows you to click on object link to dump the object equivalent to( “!DumpObj /d <address>”)

2. These are the new commands in silverlight version of sos. SOS help documentation has done a great job in explaining the details on each of the command, you can execute “!help <commandname>” to get details.

GCWhere and FindRoots are very handy.

GCWhere command not only outputs the Generation number of an object but also the GC Segment and the address

FindRoots with -gen option allows you to break into your application on the next collection of specified generation number in -gen option to find out the cross generation reference to the object.

New commands in Diagnostic Utilities
ListNearObj (lno)
AnalyzeOOM (ao)
!FinalizeQueue [-allReady] [-short]
New commands to Examine the GC history   (you will need stress log file, congfigured in registry. You can get more details by executing command “!help DumpLog” )