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
Statistics:
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
Fields:
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
Statistics:
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=2.0.5.0, Culture=neutral
Fields:
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

Resolution

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)
this.TabList.Items.Remove(item);
}

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

private void HideContent()
{
item.Content = null; //assign TabItem Content = NULL
if (item != null)
this.TabList.Items.Remove(item);
}

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
URI:

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

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

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

-Properties
—AppManifest.xml
—AssemblyInfo.cs
-App.xaml
—App.xaml.cs
-Page.xaml
—Page.xaml.cs

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”
EntryPointType=”MySilverlightControl”
RuntimeVersion=”2.0.31005″>
<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;

InitializeComponent();
}

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
{

//constructor
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”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
EntryPointAssembly=”MySilverlightControl”
EntryPointType=”MySilverlightControl”
RuntimeVersion=”2.0.31005″>
<Deployment.Parts>
<AssemblyPart x:Name=”XName” Source=”MySilverlightControl.dll” />
</Deployment.Parts>
</Deployment>

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

<html>
<head>
<title>Barebones – Silverlight Control Testing</title>
</head>
<body>
<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”/>
</object>
</div>
</body>
</html>

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

AGCORE.DLL
XCpImports

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
npctrl!GetCLRRuntimeHost
npctrl!CWindowsServices::CreateCLRRuntimeHost
agcore!CCLRHost::Initialize
agcore!CRuntimeHost::Initialize
agcore!CCoreServices::CLR_Startup
agcore!CDeployment::Start
agcore!CCoreServices::StartDeploymentTree
npctrl!CXcpBrowserHost::put_Source
npctrl!CommonBrowserHost::OnGotSourceDownloadResponsetype=”application/x-silverlight-2″

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
dmlsnapshot

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
—————————–
VerifyObj
FindRoots
HeapStat
GCWhere
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” )
—————————–
HistInit
HistStats
HistRoot
HistObj
HistObjFind
HistClear

Silverlight Debugging – .loadby sos coreclr Unable to find module ‘coreclr’, Failed to find runtime DLL (mscorwks.dll), 0×80004005 Extension commands need mscorwks.dll

0:000> .loadby sos mscorwks
Unable to find module ‘mscorwks’
0:000> .loadby sos coreclr
Unable to find module ‘coreclr’
0:000> .load C:\Program Files\Microsoft Silverlight\2.0.40115.0\sos.dll
0:000> !clrstack
Failed to find runtime DLL (mscorwks.dll), 0×80004005
Extension commands need mscorwks.dll in order to have something to do.

unable to find mscorwks.dll means there is no clr host but if you do encounter this issue while debugging Silverlight application running in IE or any browser, verify the followings

1. Have you attached WinDbg to the correct browser’s process id?

2. Have you taken the memory dump of the process running silverlight?

If you are using IE8, it runs the tabbed browser as a child process so you will see 2 instances of iexplore.exe running. You can use Process Explorer to identify which process has loaded the coreclr.dll  or agcore.dll(silverlight runtime). See the Snapshot below

Process Explorer snapshot of IE without Silverlight Runtime

IE without Silverlight Runtime

Process Explorer snapshot of IE with Silverlight Runtime

IE with Silverlight Runtime

Caution when using System.IO.FileStream – ask what you need – System.UnauthorizedAccessException: Access to the path is denied

I have come across this issue quite a few times and this issue will be seen more often during deployment in QA/Production machine.

Its not unusual to see the below piece of code
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
XmlReader reader = XmlReader.Create(fs);
XmlSerializer serializer = new XmlSerializer(typeof(T));
Object o = serializer.Deserialize(reader);
}

Many times this will go unnoticed but if you look closely FileStream is using a constructor with FilePath and FileMode alone. System.IO.FileStream implementation of this constructor is

public FileStream(string path, FileMode mode) : this(path, mode, (mode == FileMode.Append) ? FileAccess.Write : FileAccess.ReadWrite, FileShare.Read, 0×1000, FileOptions.None, Path.GetFileName(path), false)
{
}

Default constructor asks for ReadWrite access, so now you see why your application is hosed in production, most of the developers use their system as admin user so of course they have the write access to the requested file. This is not to blame developers who run as admin because I can totally understand the pain.

By default, FileStream needs ReadWrite access that’s why System.UnauthorizedAccessException is thrown because on a production machine, User account under which asp.net worker process runs or a windows service or for that matter any process will not have the write access to a file by default.

Make sure, you ask for what you need. If your application needs only Read access to a file, make sure to specify that in your FileStream constructor. Don’t be GREEDY

using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))

May be I would rather see a Read access by default in System.IO.FileStream implementation rather than ReadWrite.