Subscribe: Rupreet's Weblog
Preview: Rupreet's Weblog

Rupreet's Weblog

Looking deep inside under the hood

Copyright: Rupreet Singh Gujral

Move to new blog...

Tue, 10 Dec 2013 07:47:39 GMT

Originally posted on:

I'm moving my blog to my own domain and will be blogging on it going forward. Please visit/subscribe my new blog - Thanks!

WinDBG: How to load specific version of mscordacwks.dll for debugging crash dumps

Mon, 12 Mar 2012 10:28:48 GMT

Originally posted on: anyone of you has debugged managed crash dumps, I am sure you must have come across a situation when debugger keeps telling you it’s not able to load mscordacwks.dll. It usually happens when the dump was taken from a machine that had a specific version on .NET framework with patches installed and the machine where the crash dump is being analyzed has different .NET framework version number. When I talk about different version no, I mean the minor version. E.g. Crash dump was taken from machine v2.0.50727.5448 but the debugger is running on machine v2.0.50727.4016, the debugger would complain as version doesn’t match. Something like this – OR Failed to load data access DLL, 0x80004005 Verify that 1) you have a recent build of the debugger (6.2.14 or newer)             2) the file mscordacwks.dll that matches your version of mscorwks.dll is                 in the version directory             3) or, if you are debugging a dump file, verify that the file                 mscordacwks___.dll is on your symbol path.             4) you are debugging on the same architecture as the dump file.                 For example, an IA64 dump file must be debugged on an IA64                 machine. Resolution To solve this, we need this specific version of the assembly to continue debugging. The minor version of the framework changes whenever Microsoft releases some patches, hot fixes or service packs. Depending on what patch or hot fix is applied on that machine, the version of the assembly will differ. One of the easy ways to resolve is to copy the mscordacwks.dll from the machine the dump was taken and copy in the “discoverable” folder (path which is part of .sympath). But there are times when that machine is not available or don’t have access to it or simply you are not able to get your hands on the specific assembly. This site( details out each and every hotfix/patch with specific framework version number associated to it so that when we need a specific version, we can download the patch and extract the required assemblies. Once the update/hotfix is downloaded, we extract the required assemblies using the below commands – c:\ >expand.exe -f:* C:\Windows6.0-KB983589-x64.msu C:\temp c:\ >expand.exe -f:* C:\temp\ C:\temp\cab In the cab folder, the required assembly would be present. The other way to extract the files is to use Winzip or some compression tool which lets you extract files from *.cab. Just rename the assembly in mscordacwks___.dll format and place it in the discoverable path of the debugger (path which is part of .sympath). [...]

Avoid Assembly.LoadFrom; instead use Assembly.Load

Mon, 15 Feb 2010 19:19:20 GMT

Originally posted on: the context… We have a web application which communicates with WCF based service façade for any business functionality. This service façade then loads assembly (based on configuration) at the runtime for making the system pluggable. By default the implementation is in the service assembly itself. Below is the sample code for loading the assembly and creating an instance of the desired class.   Assembly asm = Assembly.LoadFrom(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, assemblyName)); if (asm != null) {      Type type = asm.GetType(typeName));      if (type != null)      {          return Activator.CreateInstance(type);       } }   Testing this code from a console application works like a charm but when the service façade is integrated with the web application, we get the below error: [A] cannot be cast to [B]. Type A originates from in the context 'Default' at location 'C:\Windows\Microsoft.NET\Framework\v4.0.21006\Temporary ASP.NET Files\root\10e649fb\634e3b21\assembly\dl3\9f96095e\325f141a_f8aaca01\. Type B originates from in the context 'LoadNeither' at location 'D:\\ \bin\.   Debugging the issue… In the initial debugging, everything seemed correct and on inspecting the “type” of the object, it seems correct but the cast failed. When nothing helped, I revered back to the debugging basics – read the error message clearly. The error message said - Type A originates from in the context 'Default' at location 'C:\Windows\Microsoft.NET\Framework\v4.0.21006\Temporary ASP.NET Files\root\10e649fb\634e3b21\assembly\dl3\9f96095e\325f141a_f8aaca01\abc.dll Type B originates from in the context 'LoadNeither' at location 'D:\work\Projects\\bin\ abc.dll. Now – from the message we can see the abc.dll (name changed) is getting loaded twice in the application domain and from two different locations. To verify this, I debugged the application again and saw the output window which shows the assembly getting loaded again from a different location. Below is the content of the output window:   'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.DynamicData\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.DynamicData.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.   'WebDev.WebServer40.EXE' (Managed (v4.0.21006)): Loaded   'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.CSharp\v4.0_4.0.0.0__b03f5f7f11d50a3a\Microsoft.CSharp.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.   'WebDev.WebServer40.EXE' (Managed (v4.0.21006)): Loaded   'D:\work\Projects\\bin\ abc.DLL', Symbols loaded.   'WebDev.WebServer40.EXE' (Managed (v4.0.21006)): Loaded   'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.WorkflowServices\v4.0_4.0.0.0__31bf3856ad364e35\System.WorkflowServices.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.   We have same assembly, loaded twice in the app domain from two different locations. When the managed environment tries to type cast the objects, it throws this error. Conclusion: To answer as to why the assembly loaded twice in the application domain – it is because the first assembly was loaded by the web application while calling the service façade and it was loaded from the web application temporary location. The assembly was loaded again by the code mentioned above is because we are using “LoadFrom” where we specify the path of the assembly from it needs to be loaded from and this by-passes the assembly probing mechanism. While loading this assembly, CLR thinks this assembly is a different assembly from the previously loaded assembly because the context of both the assemblies i[...]

Tip: How to view assembly directory structure

Sat, 24 Jun 2006 13:05:00 GMT

Originally posted on:

Assembly folder in windows directory is a special folder which shows files in a different manner. To view this folder in a normal view – with all files and directory structure in it, just a tweak in registry needs to be done.


Add “DisableCacheViewer” DWord key and set its value to 1 at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion


How to determine whether a file is a .NET Assembly or not?

Wed, 02 Nov 2005 05:39:00 GMT

Originally posted on:            There are some scenarios where need to check programmatically if the given file is a .NET assembly or not. How do we do that? One way is to use reflection and try to load that file (assembly). If the assembly gets loaded, and doesn’t throw any exception, then yes, it’s a valid .NET assembly. If it’s not a valid file, then it’ll throw a “BadImageFormatException”. The idea of checking weather a file is assembly or not by loading it and checking if exception is thrown or not; doesn’t seem to be too clean way at least to me. So I was trying some other way with which I can get to know if the file is an assembly or not. Here is the solution I got;               .NET assemblies are regular Win32 PE files. Operating System doesn’t differentiate between .NET assemblies and Win32 executable binaries; for it, they are same normal PE files. So how does system get to know if this file is a managed assembly and if yes, how to load CLR? How OS loads CLR is a separate discussion, I’ll just talk about how to check this header for validating the file if it’s a managed assembly or not. Well if we go through the ECMA Specifications Partition II – Metadata which is shipped along with .NET SDK, we see that we have a separate CLI Header in the PE Format. It is the 15th data directory in the PE Optional Headers. So, in simple terms, if we have value in this data directory, then it means that this is a valid .NET assembly, otherwise it is not.   Here is the code sample that does the same:   private void GetHeaders() {     uint peHeader;     uint peHeaderSignature;     ushort machine;     ushort sections;     uint timestamp;     uint pSymbolTable;     uint noOfSymbol;     ushort optionalHeaderSize;     ushort characteristics;     ushort dataDictionaryStart;     uint[] dataDictionaryRVA = new uint[16] ;     uint[] dataDictionarySize = new uint[16];         Stream fs = new FileStream(@"D:\Test.exe", FileMode.Open, FileAccess.Read);           BinaryReader reader = new BinaryReader(fs);             //PE Header starts @ 0x3C (60). Its a 4 byte header.           fs.Position = 0x3C;                          peHeader = reader.ReadUInt32();             //Moving to PE Header start location...           fs.Position = peHeader;           peHeaderSignature = reader.ReadUInt32();                     //We can also show all these value, but we will be                  //limiting to the CLI header test.                     machine = reader.ReadUInt16();           sections = reader.ReadUInt16();           timestamp = reader.ReadUInt32();           pSymbolTable = reader.ReadUInt32();           noOfSymbol = reader.ReadUInt32();     &nb[...]

ILDASM locks the file if there is some error while disassembling the assembly

Wed, 09 Nov 2005 04:48:00 GMT

Originally posted on:

I have been using ILDASM a lot for past few days when I encountered this bug. This problem is with ILDASM shipped with .NET 1.1 SDK.


The problem:

            If you open an assembly built with .NET 2.0 and try to disassemble it, it throws error “error : Failed to open meta data” which is valid because we trying to disassemble an assembly built on 2.0 with ILDASM for 1.1. But on clicking OK button, without closing ILDASM, try to delete or rename the assembly you are trying to disassemble. You cannot do it as IDLASM doesn’t release the lock over the file its trying to disassemble which it failed to do so.



            Workaround for this is simple, just close ILDASM or open another assembly in ILDASM and it’ll release the lock over this file. Then you are free to delete or rename your assembly.


Bug for the same has been logged to MSDN Product Feedback.


Getting window caption and class name

Mon, 17 Oct 2005 14:58:00 GMT

Originally posted on: I was working on a utility very similar spy++, but could do more than what we have in spy++ - like besides getting me the window (not Windows :P) class name and its height/width etc, it could also give me the caption of the window. I read couple of articles and all suggested to use global hooks. Using hooks because we are doing all this stuff using mouse – a very similar UI experience like that of spy++ - you click on the bull’s eye icon and drag the mouse to the destination window, it’ll give you all the details. If we read MSDN about hooks, the very first thing they say is that they are pretty expensive. Of course, it will be expensive; we are adding another function to be processed before the message reaches its destination. When I started working on it, I simply had some P/Invoke definitions and handled Mouse Down and Mouse Up events and it worked! Just simple .NET event handling and some P/Invokes, you are done! In my Mouse Down event, I set my cursor icon to Bull’s eye and other UI effectsJ. In Mouse Up, we get the cursor position, get the window handle by using WindowFromPoint(Point p) API defined in user32.dll. Once you get the window handle, you can get all kind of window details like the window class name, window height, width etc using APIs defined in user32.dll. Then I tried to get the caption of the window – and that also was simple 2 line code. I used SendMessage API again defined in user32.dll and passed WM_GETTEXT (value of WM_GETTEXT is defined in winuser.h file) in the message parameter of this API. Here are the signatures of the same   [DllImport("user32.dll")] static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, [Out] StringBuilder lParam);   In first parameter, pass the handle of the window whose caption you are looking for, second parameter is your message ID – in this case, its WM_GETTEXT, third parameter is the length of the string it should read, and fourth parameter which is an out parameter, is the buffer where the caption text will be copied and we can read it from here.   If you want to have a look at this utility, email me and I’ll send it across.   So without using any hooks, we got window caption and class name – simple isn’t it? [...]

Test your CF based applications on emulators which require Active Sync Connection!

Mon, 11 Jul 2005 08:55:00 GMT

Originally posted on:

Don't have a Pocket PC? Still want to write applications which require an Active Sync Connection with Pocket PC; Here is the way.....

Below is what i did to test my RAPI based application which required an Active Sync Connection!

1. Active Sync 3.7.1 on my PC
2. VS 2005 Device Emulators on my PC. (I think there must be separate installation for need to install VS2005 for this need to check for it)

Here is the procedure:
1. Navigate to your "Program Files\Microsoft Device Emulator\1.0" folder. Start the "Device Emulator Manager" by clicking "dvcemumanager.exe" file.
2. Select one emulator e.g. "Pocket PC 2003 SE Emulator" and select Connect from the Actions Menu. Pocket PC 2003 SE Emulator will start.
3. Keep the emulator selected and Select "Cradle" from the Action Menu. The PPC emulator will go into "cradle" mode. You can see the icon beside the emulator name in the Device Emulator Manager change.
4. Start Active Sync if it is not running.
5. Devices will start communicating with each other and you can sync up your data.
6. Start writing your applications :)



Mon, 17 Oct 2005 14:57:00 GMT

Originally posted on:

The views expressed on this weblog are mine and do not necessarily reflect the views of my employer.
All postings are provided "AS IS" with no warranties, and confer no rights.

Using SOS debugger from within your VS.NET IDE

Wed, 15 Jun 2005 09:42:00 GMT

Originally posted on:

You can use SOS from within your VS.NET IDE. First you need to unable “unmanaged code” debugging option in Visual Studio. Go to Project Properties -> Configuration Properties -> Debugging -> “Enable Unmanaged Debugging”. Set this option to “True”. Then you set a breakpoint in your code. When this breakpoint is hit, open the “immediate window” and load SOS debugger extension through the “.load sos” command. You can also use “!help” command to get the list of all commands. (image)

IrdaClient.DiscoverDevices throws InvalidProgramException - Bug in Compact Framework

Wed, 22 Jun 2005 08:53:00 GMT

Originally posted on:

Last evening, I was trying to write an application which could detect IR Devices from my machine and give its details. I was using VS2005 Beta 2 Winforms. I added System.Net.IrDA.dll from “C:\Program Files\Microsoft Visual Studio 8\SmartDevices\SDK\CompactFramework\2.0\WindowsCE\System.Net.IrDA.dll” path. The program is simple, just create an instance of IrDAClient and look for devices using IrDA.DiscoverDevices(int max) which gives an array of IrDADeviceInfo. But to my surprise, when I launch the application, it was throwing exception "IrdaClient.DiscoverDevices throws InvalidProgramException".

Reading more about InvalidProgramException exception online, MSDN says "The exception that is thrown when a program contains invalid Microsoft intermediate language (MSIL) or metadata. Generally this indicates a bug in the compiler that generated the program". I was still doubtful if it was really a bug or am I doing something wrong. After working on the code and looking over internet, nothing resolved this issue. Then I thought will log this issue to MSDN Product Feedback Center. While logging the issue, I found it’s already logged and Microsoft Product Team has already confirmed that this is a reproducible at there end and validated it as a bug. Here are the bug details.


My previous Blog site!

Wed, 15 Jun 2005 09:40:00 GMT

Originally posted on:

Moved to this new blog site, my previous blog site link is here.


VS2005 Another Desinger Issue - Winforms not opening

Wed, 21 Dec 2005 03:56:00 GMT

Originally posted on: week, i got the resolution for one the Designer Issue we were facing and this week we bumped into another. Here is the Designer error message we get when we open up winform. One or more errors encountered while loading the designer. The errors are listed below. Some errors can be fixed by rebuilding your project, while others may require code changes. Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. Hide     at System.Reflection.Module.GetTypesInternal(StackCrawlMark& stackMark)at System.Reflection.Assembly.GetTypes()at Microsoft.VisualStudio.Shell.Design.AssemblyObsoleteEventArgs..ctor(Assembly assembly)at Microsoft.VisualStudio.Design.VSDynamicTypeService.ReloadAssemblyIfChanged(String codeBase)at Microsoft.VisualStudio.Design.VSDynamicTypeService.CreateDynamicAssembly(String codeBase)at Microsoft.VisualStudio.Design.VSTypeResolutionService.AssemblyEntry.get_Assembly()at Microsoft.VisualStudio.Design.VSTypeResolutionService.AssemblyEntry.Search(String fullName, String typeName, Boolean ignoreTypeCase, Assembly& assembly, String description)at Microsoft.VisualStudio.Design.VSTypeResolutionService.SearchProjectEntries(AssemblyName assemblyName, String typeName, Boolean ignoreTypeCase, Assembly& assembly)at Microsoft.VisualStudio.Design.VSTypeResolutionService.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase, ReferenceType refType)at Microsoft.VisualStudio.Design.Serialization.CodeDom.AggregateTypeResolutionService.GetType(String name, Boolean throwOnError, Boolean ignoreCase)at Microsoft.VisualStudio.Design.Serialization.CodeDom.AggregateTypeResolutionService.GetType(String name, Boolean throwOnError)at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.GetType(ITypeResolutionService trs, String name, Dictionary`2 names)at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.FillStatementTable(IDesignerSerializationManager manager, IDictionary table, Dictionary`2 names, CodeStatementCollection statements, String className)at System.ComponentModel.Design.Serialization.TypeCodeDomSerializer.Deserialize(IDesignerSerializationManager manager, CodeTypeDeclaration declaration)at System.ComponentModel.Design.Serialization.CodeDomDesignerLoader.PerformLoad(IDesignerSerializationManager manager)at Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.PerformLoad(IDesignerSerializationManager serializationManager)at Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.DeferredLoadHandler.Microsoft.VisualStudio.TextManager.Interop.IVsTextBufferDataEvents.OnLoadCompleted(Int32 fReload)   Cause: I don’t have any concrete reason for this, but I am assuming that VS2005 has some kind of assembly cache which it maintains and while designing the form, somehow it gets corrupted, hence we get this error.   Workaround: Follow the steps and it should work fine then!   1. When you open your form and you get this error. Close all the forms. 2. Close VS.NET (make sure none of the forms are open at this time) 3. Delete "bin" and "obj" folder physically. 4. Open VS.NET 5. Rebuild your application 6. Try opening your forms now. It should work! [...]

VS2005 Designer Issue - WinForms not opening after migrating

Wed, 14 Dec 2005 13:06:00 GMT

Originally posted on: in my project we migrated from VS2003 to VS2005.  The application I am working on is a smart client application so it has lot many Win Forms. After migration, when the solution was opened up in VS2005, we faced this strange problem. None of the Forms were opening in the designer mode. It was throwing exception (shown below)   One or more errors encountered while loading the designer. The errors are listed below. Some errors can be fixed by rebuilding your project, while others may require code changes. Object reference not set to an instance of an object. Hide     at System.Resources.Tools.StronglyTypedResourceBuilder.DefineResourceFetchingProperty(String propertyName, String resourceName, ResourceData data, CodeTypeDeclaration srClass, Boolean internalClass, Boolean useStatic)at System.Resources.Tools.StronglyTypedResourceBuilder.InternalCreate(Dictionary`2 resourceList, String baseName, String generatedCodeNamespace, String resourcesNamespace, CodeDomProvider codeProvider, Boolean internalClass, String[]& unmatchable)at System.Resources.Tools.StronglyTypedResourceBuilder.Create(IDictionary resourceList, String baseName, String generatedCodeNamespace, String resourcesNamespace, CodeDomProvider codeProvider, Boolean internalClass, String[]& unmatchable)at System.Resources.Tools.StronglyTypedResourceBuilder.Create(IDictionary resourceList, String baseName, String generatedCodeNamespace, CodeDomProvider codeProvider, Boolean internalClass, String[]& unmatchable)at Microsoft.VisualStudio.Design.Serialization.ResXGlobalObject.BuildType()at Microsoft.VisualStudio.Design.Serialization.ResXGlobalObject.GetObjectType()at Microsoft.VisualStudio.Shell.Design.GlobalType.get_ObjectType()at Microsoft.VisualStudio.Design.Serialization.ResXGlobalObject.get_Children()at Microsoft.VisualStudio.Design.Serialization.ResXGlobalObjectProvider.CreateGlobalObjectsForItem(ProjectItem item, GlobalObjectCollection oldObjects, GlobalObjectCollection newObjects, ITypeResolutionService typeResolver)at Microsoft.VisualStudio.Design.Serialization.ResXGlobalObjectProvider.CreateGlobalObjectsForItem(ProjectItem item, GlobalObjectCollection oldObjects, GlobalObjectCollection newObjects, ITypeResolutionService typeResolver)at Microsoft.VisualStudio.Design.Serialization.ResXGlobalObjectProvider.CreateGlobalObjects(Project project)at Microsoft.VisualStudio.Design.Serialization.ResXGlobalObjectProvider.GetGlobalObjectsCore(Project project, Type baseType)at Microsoft.VisualStudio.Shell.Design.GlobalObjectProvider.GetGlobalObjects(Project project, Type baseType)at Microsoft.VisualStudio.Shell.Design.GlobalObjectService.GetGlobalObjects(Type baseType)at Microsoft.VisualStudio.Shell.Design.GlobalObjectService.GetGlobalObjects()at Microsoft.VisualStudio.Design.Serialization.CodeDom.AggregateTypeResolutionService.GetTypeFromGlobalObjects(String name, Boolean throwOnError, Boolean ignoreCase)at Microsoft.VisualStudio.Design.Serialization.CodeDom.AggregateTypeResolutionService.GetType(String name, Boolean throwOnError, Boolean ignoreCase)at Microsoft.VisualStudio.Design.Serialization.CodeDom.AggregateTypeResolutionService.GetType(String name, Boolean throwOnError)at System.Resources.ResXDataNode.ResolveType(String typeName, ITypeResolutionService typeResolver)at System.Resources.ResXDataNode.GenerateObjectFromDataNodeInfo(DataNodeInfo dataNodeInfo, ITypeResolutionService typeResolver)at System.Resources.ResXDataNode.GetValue(ITypeResolutionService typeResolver)at System.Resources.ResXResourceReader.ParseDataNode(XmlTextReader reader, Boolean isMetaData)at System.Resources.Res[...]