Home » .Net Framework

NullReferenceException not handled by sxe clr

How come sxe clr within windbg does not handle this NullReferenceException?Here is code sxe -c “!clrstack;!pe” clr


using System;

namespace Test
 class Program
 string test;

 static void Main(string[] args)
  new Program().Testing();
 catch {
 Console.WriteLine("Something went wrong");

 int Testing(){
 if (test.Substring(10,20) == "asd")
  return 10;
 return 1;




I able to put a break-point on NullReferenceException ctor and I can see the call-stack then. There is an AV exception but i was hoping a clr exception  And I can also see the exception object in stack by doing !dso. 

What is happening?



Thanks Naveen http://naveensrinivasan.com

5 Answers Found


Answer 2

It still does not answer my question. Like i mentioned there is a NullReference exception on the stack and it is created.

I did also have a bp on the NullReference constructor, how come when i do sxe -c "!clrstack;!pe" clr  it does not break, when the exception is created.

And if i debug it in VS.NET i can catch the exception.


Answer 3

In managed world, there are many exception types, for example: ArgumentNullException and NullReferenceException, from perspective of SEH, all of those exceptions share same error code: 0xe0434352, in WinDbg, we use item ‘CLR exception’ for this error code.


“sxe” command enables first chance exception handling, in another words, WinDbg will break the debuggee immediately after the target process generates an exception, at this time, the debuggee’s exception handling code  doesn’t get chance to execute.


When we use command “sxe clr“ to enable clr  exception, WinDbg will break once an error with code 0xe0434352 occurs. But, your code snippet actually generate an  Access Violation exception which has error code 0xC0000005, that’s why you only see a first chance AV exception,


you may throw a NullReferenceException from your code and use WinDbg to test again:



                thrownew NullReferenceException();







In WinDbg, you will see something like this:

(1ba4.1aec): CLR exception - code e0434352 (first chance)

First chance exceptions are reported before any exception handling.

This exception may be expected and handled.

eax=01831228 ebx=00000000 ecx=00000000 edx=00000000 esi=003805f8 edi=001ff120

eip=005100b2 esp=001ff0cc ebp=001ff0f4 iopl=0         nv up ei pl zr na pe nc

cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00010246


Here, we got a CLR exception, if you set a breakpoint at System.NullReferenceException..ctor() method:

0:000> !name2ee mscorlib.dll System.NullReferenceException

Module:      553f1000

Assembly:    mscorlib.dll

Token:       02000108

MethodTable: 5570470c

EEClass:     55441cb4

Name:        System.NullReferenceException

0:000> !dumpmt -md 5570470c

EEClass:      55441cb4

Module:       553f1000

Name:         System.NullReferenceException

mdToken:      02000108

File:         C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll

BaseSize:        0x54

ComponentSize:   0x0

Slots in VTable: 21

Number of IFaces in IFaceMap: 2


MethodDesc Table

   Entry MethodDesc      JIT Name

55616af8   5546c584   PreJIT System.Exception.ToString()

555ed1a8   55460b0c   PreJIT System.NullReferenceException..ctor()

55c33344   55460b1c   PreJIT System.NullReferenceException..ctor(System.String)

55c33374   55460b28   PreJIT System.NullReferenceException..ctor(System.String, System.Exception)

55c333b0   55460b34   PreJIT System.NullReferenceException..ctor(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)

0:000> !bpmd -md 55460b0c  

MethodDesc = 55460b0c

Setting breakpoint: bp 55C33304 [System.NullReferenceException..ctor()]


And input commang ‘g’ to let the AV exception to be thrown, the breakpoint at System.NullReferenceException..ctor() will be hit:

0:000> g


(1ba4.1aec): Access violation - code c0000005 (first chance)

First chance exceptions are reported before any exception handling.

This exception may be expected and handled.

eax=01831228 ebx=00000000 ecx=00000000 edx=00000000 esi=003805f8 edi=001ff120


0:000> g


Breakpoint 7 hit

eax=55460b0c ebx=00000000 ecx=0183cafc edx=001fe790 esi=003805f8 edi=001fe6e0

eip=55c33304 esp=001fe6b8 ebp=001fe6c4 iopl=0         nv up ei pl nz ac pe nc

cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000216


55c33304 55              push    ebp

0:000> k

ChildEBP RetAddr 

001fe6c4 56dd21db mscorlib_ni!System.NullReferenceException..ctor()

001fe6c4 56df4a2a clr!CallDescrWorker+0x33

001fe740 56df4bcc clr!CallDescrWorkerWithHandler+0x8e

001fe87c 56df4c01 clr!MethodDesc::CallDescr+0x194

001fe898 56ebc74f clr!MethodDesc::CallTargetWorker+0x21

001fe9d8 56ec9269 clr!CallDefaultConstructor+0x154

001fea38 57047842 clr!EEException::CreateThrowable+0x94

001feaf4 56fb2e38 clr!CreateCOMPlusExceptionObject+0x179

001fec5c 56e5cbbf clr!CPFH_RealFirstPassHandler+0x383

001fecb4 56e5ccfe clr!CPFH_FirstPassHandler+0xe6

001fece0 77cb65f9 clr!COMPlusFrameHandler+0x132

001fed04 77cb65cb ntdll!ExecuteHandler2+0x26

001fedb4 77cb6457 ntdll!ExecuteHandler+0x24

001fedb4 005100b2 ntdll!KiUserExceptionDispatcher+0xf

001ff0f4 56dd21db ConsoleApplication2!ConsoleApplication2.Program.Main(System.String[])+0x42 [D:\Workspace\Projects\2010\ConsoleApplication2\ConsoleApplication2\Program.cs @ 19]


001ffcfc 00000000 ntdll!_RtlUserThreadStart+0x1b [d:\w7rtm\minkernel\ntos\rtl\rtlexec.c @ 3111]

0:000> !do 0183cafc

Name:        System.NullReferenceException

MethodTable: 5570470c

EEClass:     55441cb4

Size:        84(0x54) bytes

File:        C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll


      MT    Field   Offset                 Type VT     Attr    Value Name

5570f9ac  400004a        4        System.String  0 instance 00000000 _className

557101f4  400004b        8 ...ection.MethodBase  0 instance 00000000 _exceptionMethod

5570f9ac  400004c        c        System.String  0 instance 00000000 _exceptionMethodString

5570f9ac  400004d       10        System.String  0 instance 00000000 _message

55704004  400004e       14 ...tions.IDictionary  0 instance 00000000 _data

5570fc0c  400004f       18     System.Exception  0 instance 00000000 _innerException

5570f9ac  4000050       1c        System.String  0 instance 00000000 _helpURL

5570f5e8  4000051       20        System.Object  0 instance 00000000 _stackTrace

5570f5e8  4000052       24        System.Object  0 instance 00000000 _watsonBuckets

5570f9ac  4000053       28        System.String  0 instance 00000000 _stackTraceString

5570f9ac  4000054       2c        System.String  0 instance 00000000 _remoteStackTraceString

55712978  4000055       3c         System.Int32  1 instance        0 _remoteStackIndex

5570f5e8  4000056       30        System.Object  0 instance 00000000 _dynamicMethods

55712978  4000057       40         System.Int32  1 instance        0 _HResult

5570f9ac  4000058       34        System.String  0 instance 00000000 _source

5570aa2c  4000059       44        System.IntPtr  1 instance        0 _xptrs

55712978  400005a       48         System.Int32  1 instance        0 _xcode

556ca29c  400005b       4c       System.UIntPtr  1 instance        0 _ipForWatsonBuckets

556c9888  400005c       38 ...ializationManager  0 instance 00000000 _safeSerializationManager

0:000> .exr 001fedcc

ExceptionAddress: 005100b2 (ConsoleApplication2!ConsoleApplication2.Program.Main(System.String[])+0x00000042)

   ExceptionCode: c0000005 (Access violation)

  ExceptionFlags: 00000000

NumberParameters: 2

   Parameter[0]: 00000000

   Parameter[1]: 00000000

Attempt to read from address 00000000




WinDbg is an “unmanaged debugger”, for WinDbg, all CLR exceptions are same because all of them has same error code, but SOS extension can helps to show more information about a specified CLR exception (e.g. use !pe command).


VS Debugger is a “managed debugger” by default, it has different mode against WinDbg, we no need to load SOS in VS Debugger, instead, with the help of managed debugging API, VS Debugger knows all information about a CLR exception, so you received a NullReferenceException instead of an AV exception in VS.


VS Debugger can also act as an “unmanaged debugger”:

1. Launch target application.

2. In VS, select ToolsàAttach to Process,

3. on the pop up dialog, you can see a button has text “Select…”, click this button, on the pop up dialog, select “Debug those code types:” radiobutton, and only tick checkbox of “Native”, click OK, then, select a process and click “Attach” button.

4. To let VS Debugger break when first chance AV exception occurs, select Debug à Exceptions, on the pop up, unwind ‘Win32 Exception’ node, tick the checkbox of ‘Access violation’, click OK.

5. Back to your application, let it execute Testing() method, then, VS Debugger will break with an AV exception.

MSDN Subscriber Support in Forum
If you have any feedback of our support, please contact msdnmg@microsoft.com.
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.

Answer 4

Eric is right. 

To Summarize, not all clr  exceptions are implemented on top of the SEH exception code 0xe0434352 (which is what 'sxe clr' stops on).  There are some 'hardware exceptions' which Windows raises as SEH exceptions with specific codes, and so the CLR doesn't need to create it's own SEH exception for those.  True the CLR will still wrap them in an appropriate Exception object, but not necessarily as soon as they are thrown.  Another example is divide-by-zero.

So basically it's an implementation detail (driven by concerns for performance and interoperability with native code) of how the CLR implements .NET exceptions on top of Windows SEH.  A managed debugger (which operates at the CLR level of abstraction, rather than at the CPU/OS level like WinDbg) will abstract such details from you.  Using WinDbg, some implementation detials like this bleed through.



Answer 5

Thanks Rick.  Especially If I am troubleshooting something in production where there is only windbg, I would like to know list of SEH exception that would not be trapped by sxe clr. Has this been documented? Where can i get this information?






I just read this aricle http://msdn.microsoft.com/en-us/magazine/ee819091.aspx. In Figure 2 (Will These Runtimes Load in the Same Process?) You can read that it is OK to load an assembly compiled against .NET 4 CLR from an application compiled against .NET 2 CLR. But later in the aricle under "Library Developers and Consumers " you can read that it will not work for libraries.

I have a web application (ASP.NET) compiled against .NET 2 CLR that needs to reference an assembly compiled against .NET 4 CLR. Will this work or not? I have tried it several times and it works fine. I don't understand the text in the aricle becase Figure 2 says it's OK but the text under "Library Developers" says it will not be OK. But for me it works. Maybe I have just had luck?


I have a non-CLR, no UDTs Java application that works fine with the SQLServer V1.2 driver and SQLServer 2008 (32 bit). When I switched to the new V3.0 driver (that is the only change), I get this SQLException: "Failed to initialize the Common Language Runtime (CLR) v2.0.50727 with HRESULT 0x8007000e". It only happens on one SQL2008 server. I have other non-CLR applications that work fine with the V3.0 driver on other SQL2008 servers which are installed and configured the same as the failing server.

I can't find any information about any new CLR requirements for the V3.0 driver. Any help on this would be much appreciated.



Hi all,



I have the HWND of an application I'm monitoring / interacting with. If this application creates any child windows while I'm monitoring it, I want to know about it. I have no access to the source code of the application I'm monitoring. Also want to prevent the monitored application ever grabbing windows focus.



C++ and MFC


For anyone who's followed my posts (probably none of you :) I'm currently working on some code that renders windows applications into a texture for use in a directX application. So far I have firefox working almost perfectly, and am now adjusting the code so paint, IE, and chrome work also. However, each has left me with a couple issues, and the two most prominent are as follows:

Whenever an application creates a child window (think the color palette in paint, or an options drop down in firefox) I want to be notified of this, so that I can grab that windows HWND and add it to my rendered image. Is there a windows function that will notify me if an application creates a child window? Or would I have to store a list of child windows the application originally had and then constantly check for changes to the list?

Secondly, is there any way to prevent an application from ever grabbing windows focus? For example, if you inject a mouse event into google chrome on the content window (strangely it doesn't happen on the menu / url windows) it demands to be made the focus window, which obviously wont be acceptable when my fullscreen drectx app is running.


Cheers, cal

After creating a datasource and generating a dataset, my database has changed. 
How can I "refresh" the dataset so it sees these changes.
The only thing I have been able to do is delete the .xsd file from soultion explorer.
But then I have to recreate queries and/or datasource code I have created.

Is there a better way?



i´m experiencing the above mentioned error in a simple message routing scenario with BizTalk Server 2009. The scenario consists of a SOAP receive location and a SOAP send port. The send port has a mapping that only consists of a mass copy functoid that copies the whole message from the source schema to the destination schema. Theres no custom pipeline or mapping functiod involved.

When biztalk is under heavy load, a few times the following error occours randomly:

Error Code:0xc0c01696 (Send Port Map Error)

Suspend Time: 21.04.2010 00:14:57

Error description:

The messaging engine failed while excecuting the outbound map for the message going to the destination URL "..." with the message type "...". Details: "Invalid handle. Paramter name: handle" 

I did not find anything on the internet, not even the error message in association with BTS. Help would be appreciated.


Kind regards,




I have a device app that use SQL Compact and uses sync framework to synchronize to a SQL Server 2008 instance.  In order to speed up the initial synchronization of my device app, I'm creating the database (.sdf) using the sync framework on the server based on the suggestion in this article:


Then I get it via a WCF service down to the device app.  I'm able to download the db and it has data.  When I sync however, the database doesn't seem to think it is syncronized and seems to try to do a full synchronization which won't work because there is too much data.  Do I have to somehow tell the compact db that it is synced already and to just pick up where it left off?  Why isn't that already doing it.

I know you can set the client id, but should i be setting something else?

 ((SqlCeClientSyncProvider)(syncAgent.LocalProvider)).ClientId =      Guid.NewGuid();

Any suggestions are appreciated. 




When interoping with Windows Installers MSIHANDLE (defined as unsigned long, i.e. a 32 bit value), I cannot use SafeHandle derived classes since they become 64-bit on x64.

How do I create a MsiSafeHandle class that captures the value of the method in the following example even in case of asynchronous exceptions

UINT MsiOpenPackage(
  __in   LPCTSTR szPackagePath,
  __out  MSIHANDLE *hProduct





I'm using VSTO 2010 with Microsoft Project 2010 (and Win7). I'm upgrading an existing add-in to work with Project 2010. The add-in is getting the Microsoft Project window handle via GetCurrentProcess().MainWindowHandle and using it as a parent for all WinForms (some modal, some non-modal), and also for CHM help windows. This works great in MSP 2003 and MSP 2007, but with MSP2010, the MainWindowHandle is constantly changing. It will work for a little while, then give me an "Invalid Handle" exception. Why is Process.MainWindowHandle always changing on me (I've checked in debugger, and it periodically changes, with the old handle becoming invalid)? Is there another way to get the main window handle?




Hi All,

I am writing an application to simulate data entry of web pages using a MFC application. This thread might give an idea what i'm trying to do


I have a button in the html page, which when clicked shows up a alert window (javascript window.alert). I want to simulate click of the enter button by getting the HWND to the alert window and sending VK_ENTER to it, so that it goes away. I was able to get the window handle (HWND) to the Internet Explorer window. I iterate through all the child windows of the Internet Explorer window to find the handle to the alert window. But the problem is, i'm not able to get a handle to the alert window. 

I tried to use spy and see what is the parent window of the alert window and in the 'Property Inspector' i can see that the parent of the alert window is 'Windows Internet Explorer'. Further i compared the handle of the 'Windows Internet Explorer' in the 'Property Inspector' with the one i get in my code and it matches. Butttt.... when i do 

HWND childWnd = ::GetWindow(hWnd,GW_CHILD);
childWnd = ::GetWindow(childWnd,GW_HWNDNEXT);									

Where hWnd is the handle to 'Internet Explorer', i do not see the alert window in any of the 'childWnd'. 

Also when i expand the 'Internet Explorer' in the Spy's main window i do not see the alert window although Property Inspector says 'Internet Explorer' in the parent of the alert window. Can someone please explain what is happening here?

Any help is highly appreciated.



Dear all,

    we are developing an xps based printer driver.

    With some applications we are getting a message in the Output widow as "A cryptographic service handle could not be acquired". After that it is unable to call InitializeFilter () it self.

   This problem we are getting only in client-server scenario,
   both the server and client are having administrator privileges only,
   we are using MSVC 2005 editor.

The same behavior I observed with WDK SimplePipelineFilter also.

Any help would be greatly appreciated



Hello! I've just downloaded the latest version of Phoenix RDK (June 2008, 0.64.30627.0) and started playing. My first idea was to load some assembly and see what Phoenix can do. Unfortunately, I've stumbled upon a null-ref right after the start. Here's the code:

private static void Main(string[] args)
    var msilArch = Phx.Targets.Architectures.Msil.Architecture.New();
    var x86Arch = Phx.Targets.Architectures.X86.Architecture.New();
    var msilRuntime = Phx.Targets.Runtimes.Vccrt.Win.Msil.Runtime.New(msilArch);
    var x86Runtime = Phx.Targets.Runtimes.Vccrt.Win32.X86.Runtime.New(x86Arch);

    Phx.Initialize.EndInitialization("PHX|__PHX__", args);


private static void HelloPhoenix()
    var path = @"<some path to an assembly>";
    var module = Phx.PEModuleUnit.Open(path);

    foreach(var unit in module.GetEnumerableContributionUnit())
The crash occurs during the call to GetEnumerableContributionUnit (i.e. even before GetEnumerator gets called). At the same time I get a trace message in the console:

The available PDB has been stripped so it does not contain the required
information for native or IJW images.
Please find the full PDB for this binary and re-run your scenario.

What I've done:
 * Verified that the assembly I'm loading exists.
 * Checked its PDB file - it seems to be fine, but to be safe I've recompiled the DLL+PDB pair by VS 2008.
 * Looked through UVA Summer Workshop Session samples, though I was unable to find an example of loading already existing .NET assembly.

Everything  works fine on localhost.

But after deploying my site on shared hosting an error occured


Server Error in '/' Application.
Object reference not set to an instance of an object.

Source Error:

PricelistBLL logic = new PricelistBLL();

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]
ByteDatabaseTableAdapters.PricelistsTableAdapter.InitConnection() +59
ByteDatabaseTableAdapters.PricelistsTableAdapter.get_Connection() +15
ByteDatabaseTableAdapters.PricelistsTableAdapter.InitAdapter() +262
ByteDatabaseTableAdapters.PricelistsTableAdapter.get_Adapter() +15
ByteDatabaseTableAdapters.PricelistsTableAdapter.GetPriceLists() +13
PricelistBLL.GetLastPricelistURL() +16


I'm creating this program that can record sound from a microphone and save it into wav format using the free and open source library NAudio. The project builds fine but when I run the program and start recording I get a nullrefrenceexception. I know what causes the exception I just don't know the root of the problem can someone please help me the code is below:

static WaveIn^ waveinstream;

static String^ outputfilename;

static WaveFileWriter^ writer;

private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {

SaveFileDialog^ save = gcnew SaveFileDialog();

save->Title = "Location To Save Audio File";

save->Filter = "Wave File | *.wav";

if (save->ShowDialog() == Windows::Forms::DialogResult::OK)


outputfilename = save->FileName;

writer = gcnew WaveFileWriter(outputfilename, waveinstream->WaveFormat);

waveinstream->DataAvailable += gcnew EventHandler<WaveInEventArgs^>(wave_data);


button1->Enabled = false;

button2->Enabled = true;



private: static System::Void wave_data(System::Object^ sender, WaveInEventArgs^ e){

writer->WriteData(e->Buffer, 0, e->BytesRecorded);

int secondsrecorded = (int)(writer->Length / writer->WaveFormat->AverageBytesPerSecond);


P.S exception occurs at line: writer = gcnew WaveFileWriter(outputfilename, waveinstream->WaveFormat);






Hello. I inherit CustomLine from the LineShape.

  Protected Overridable Sub OnBorderColorChanged(ByVal e As System.EventArgs)
    ' I need to set this check, if not I receive the error bellow
    'If IsDisposed Then Return
    If _IsSelected Then
      MyBase.BorderColor = SelectedColor
      MyBase.BorderColor = _BorderColor
    End If
  End Sub

  System.NullReferenceException was unhandled
  Message=La référence d'objet n'est pas définie à une instance d'un objet.
       à Microsoft.VisualBasic.PowerPacks.Shape.set_BorderColor(Color value)
       à MyNamespace.myPanel.CustomLine.OnBorderColorChanged(EventArgs e)
       à MyNamespace.myPanel.CustomLine.OnSelectedChanged(EventArgs e)
       à MyNamespace.myPanel.ArretLineWithPicture`1.OnSelectedChanged(EventArgs e)
       à MyNamespace.myPanel.CustomLine.set_Selected(Boolean value)
       à MyNamespace.myPanel.ArretLineWithPicture`1.OnTacheSelectedChanged()
       à MyNamespace.myPanel.ArretLineWithPicture`1.Tache_SelectedChanged(Object sender, EventArgs e)
       à System.EventHandler.Invoke(Object sender, EventArgs e)
       à MyNamespace.cllGraphiqueHoraire.TacheNonCommerciale.set_Selected(Boolean value) dans D:\Projets\MyNamespace\MyNamespace_NET\ClassLibrary\cllGraphiqueHoraire\Class\TacheNonCommerciale.vb:ligne 92
       à MyNamespace.myPanel.ArretLineWithPicture`1.OnSelectedChanged(EventArgs e)
       à MyNamespace.myPanel.CustomLine.set_Selected(Boolean value)
       à MyNamespace.myPanel.EntreeSortieLine.OnClick(EventArgs e)
       à Microsoft.VisualBasic.PowerPacks.ShapeContainer.OnClick(EventArgs e)
       à System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       à System.Windows.Forms.Control.WndProc(Message& m)
       à System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       à System.Windows.Forms.ContainerControl.WndProc(Message& m)
       à System.Windows.Forms.UserControl.WndProc(Message& m)
       à Microsoft.VisualBasic.PowerPacks.ShapeContainer.WndProc(Message& m)
       à System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       à System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       à System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       à System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       à System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       à System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       à System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       à System.Windows.Forms.Application.Run(ApplicationContext context)
       à Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
       à Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
       à Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
       à MyNamespace.OkapiV3.My.MyApplication.Main(String[] Args) dans 17d14f5c-a337-4978-8281-53493378c1071.vb:ligne 81
       à System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       à System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       à Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       à System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       à System.Threading.ThreadHelper.ThreadStart()

Best regards, Sergiu
I have a PUT that, when run under Pex Exploration, throws a NullReferenceException:

As you can see, the stack trace is rather unhelpful, it doesn't show where the actual error is occurring. Clicking "Go To" just takes me to the PUT, and that PUT isn't throwing any null reference exceptions.

Here's my PUT:

publicvoid CommitCurrentTransactions_CausesSharedItemsToBeFlushedToDisk(
    [PexAssumeUnderTest, PexAssumeNotNull] SharedIndexing target)
    var sharedIds = new[] { Guid.NewGuid() };
    target.SetSharedState(sharedIds, true);

And here's SetSharedState:

publicvoid SetSharedState(IEnumerable<Guid> ids)
     // Simplified to bare minimum to repro the problem.var unshared = WhereNotShared(ids);
     foreach (var id in unshared)

As you can see, it merely Calls into WhereNotShared and evalutes the result.

Here's WhereNotShared. This is where the exception occurs. Commenting out this function fixes the bug.
private IEnumerable<Guid> WhereNotShared(IEnumerable<Guid> ids)
    var commandText = string.Format("SELECT Id FROM {0} WHERE ID = @IdParam;", tableName);
    using (var readCommand = new SqlCeCommand(commandText, connection))
        var idParameter = new SqlCeParameter() { ParameterName = "IdParam" };
        foreach (var id in ids)
            idParameter.Value = id;
            if (readCommand.ExecuteScalar() == null)
                yield return id;

Commenting out the "if (readCommand.ExecuteScalar() ..." line above fixes the bug.

My question is, where is the bug here? Is this a Pex bug? Bug in SQL CE? Help!

Tech, life, family, faith: http://judahgabriel.blogspot.com

System.NullReferenceException: Object reference not set to an instance of an object. at System.Void Microsoft.ExtendedReflection.Interpretation.Interpreter.InstructionInterpreter.AtCallException(System.Object exceptionObject, System.Int32 codeLabel) at System.Void Microsoft.ExtendedReflection.Monitoring._Checks.AtCallObject(System.Object exception, System.Int32 codeLabel) <...>\ProjectTest.cs(65): at System.Void <...>.ProjectTest.AccountingEnabledGetSet(System.Boolean value) at Microsoft.ExtendedReflection.Interpretation.Term Microsoft.ExtendedReflection.__DynamicMethods.invoke:<...>.ProjectTest.AccountingEnabledGetSet(Microsoft.ExtendedReflection.DataAccess.ITermConstructor`1<Microsoft.ExtendedReflection.Interpretation.Term> , Microsoft.ExtendedReflection.DataAccess.ITermDestructor`1<Microsoft.ExtendedReflection.Interpretation.Term> , Microsoft.ExtendedReflection.Interpretation.Term[] ) at System.Void Microsoft.Pex.Engine.PathExecution.PathExecutorBase.InternalRun(Microsoft.ExtendedReflection.DataAccess.ITermDestructor`1<Microsoft.ExtendedReflection.Interpretation.Term> destructor, Microsoft.Pex.Engine.PathExecution.PathSegmentPreparer segmentPreparer, Microsoft.Pex.Engine.PathExecution.PathSegmentReporter segmentReporter, System.Collections.Generic.IEnumerable`1<Microsoft.Pex.Engine.PathExecution.PathSegment> segments) at System.Boolean Microsoft.Pex.Engine.PathExecution.PathExecutorBase.TryRun(Microsoft.Pex.Engine.PathExecution.PexPathExecutionResult& runResult, Microsoft.ExtendedReflection.Interpretation.ISubstitution& finalSubstitution, Microsoft.ExtendedReflection.Interpretation.States.IState& finalState)

It is thrown during Pex 0.91 exploration at the end of the [PexMethod].


While playing around I found out when using TcpChannel in combination with ChannelServices.GetUrlsForObject the method will throw a NullReferenceException. This happens because ChannelServices.GetUrlForObject checks all registered channels if they are a receiver (a server channel). TcpChannel implements both IChannelReceiver and IChannelSender, but instantiates either TcpServerChannel or TcpClientChannel. If the TcpChannel is created as client channel, it is still used as a server channel by the ChannelServices and a call to TcpChannel.GetUrlsForUri will return null, and than cause the exception.

When looking into the reflected code it seems that ChannelServices.GetUrlsForObject expects a NotSupportedException instead of getting a null reference.

This behavior was found in version 2.0.50727.4927. And at a second glance it looks like other channel implementations have the same problem, at least IpcChannel looks very similar in its implementation. 

ChannelServices.RegisterChannel(new TcpChannel());
SomeMbrObject mbrObject = //...
ChannelServices.GetUrlsForObject(mbrObject); // throws a NullReferenceException

Best regards


Seems the [Import] is not working(NullReferenceException), do you know why?

Please note, [Import] is apply to class MyConsum, not class Program.

Here is the code:
using System;

using System.ComponentModel.Composition;

using System.ComponentModel.Composition.Hosting;

using System.Reflection;

namespace ConsoleApplication2


 class Program


  publicstaticvoid Main()


   var prog = new Program();



  publicvoid Run()



   AssemblyCatalog catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());

   var container = new CompositionContainer(catalog);


   //GetExport, works finevar myConfig = container.GetExport<IConfigurationSettings>().Value;

   Console.WriteLine(myConfig.SiteTitle );

   MyConsum my = new MyConsum();

   // System.NullReferenceException 




 publicclass MyConsum



  public IConfigurationSettings MySetting






 //IConfigurationSettingspublicinterface IConfigurationSettings


  string SiteTitle







 publicclass ConfigurationSettings : IConfigurationSettings



  publicstring SiteTitle




    return"My Site Title";








Hi We have recently moved our CS 2002 FP1 servers and split out our Integration to a seperate box and now i am getting 1000s of : 

Type : System.NullReferenceException, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Message : GetUserProfile() userId can not be null for xxxxxxx
Source : SnowValley.Lakeland.Extensions
Help link :
TargetSite : Microsoft.CommerceServer.Runtime.Profiles.Profile GetUserProfile(System.String, System.Data.DbType, System.Object)
Stack Trace :    at SnowValley.Lakeland.Extensions.Integration.IntegrationManagerBase.GetUserProfile(String userObjectColumnName, DbType dbType, Object userObjectValue)
   at SnowValley.Lakeland.Extensions.Integration.IntegrationCustomerManager.UpdateCustomerDetails(CustomerMessage customerMessage)
   at SnowValley.Lakeland.Integration.Website.Erp2Muse.Erp2MuseCustomerTask.Customer(XmlReader message)

Additional Info:

FullName : Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=, Culture=neutral,

After debugging it is apparent that (in bold)

Microsoft.CommerceServer.Runtime.Profiles.Profile GetUserProfile()

Is the null value appearing in the stack

Why is this happening?

Any Ideas?




The previous version completes with no values. The code below will reproduce the bug in v1.0.2563.0





 .Subscribe(new Subject<int[]>());

Edit: Using Observable.Return also causes the same exception:
  .Subscribe(new Subject<int[]>());


<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure