How to see the value returned by a method in Visual Studio Debugger?

In Visual Studio’s Debugger, it has always been a pain to not be able to see the value returned by a method if no variable was assigned to it.
Indeed, the debugger would not give a way to see the value returned by the following method:

static string Concat(string p1, string p2)
{
    return p1 + p2;
}

The only way to see the value before it is returned by the method would be to modify (!) the source code and assign a variable to the result before returning it. This is less than ideal as it means we have to stop the debugging session, modify code and restart debugging. It has unfortunately been a trick many developers have had to use throughout the years.
If we take the example here above, we would change the method to something like the following to be able to see its return value at debug time:

static string Concat(string p1, string p2)
{
    string value = p1 + p2;
    return value;
}

 

The good news is that starting from Visual Studio 2013 we do not have to do such trick anymore; we can directly examine the return value of a method even if there is no variable holding the value. We can do that at 2 moments in time:

  1. Just before the method returns: When we step over to the end of the method (the curly brace at the end of the method definition).
  2. Just after the method returns: When we step out of the method (back to the line of code calling the method). Note that the return value will be lost after the next Debugger Step Over.

There are 2 places where we can see the method return value:

  • In the Debugger Immediate window, using the $ReturnValue keyword. To open the Immediate window while debugging, choose Debug -> Windows -> Immediate (or press keyboard shortcut: Ctrl + Alt + I).
  • In the Debugger Autos window. To open the Autos window while debugging, choose Debug -> Windows -> Autos (or press keyboard shortcut: Ctrl + Alt + V, A).

 

Example when Stepping Over to the method end.

The return value will only be visible when we step over to the end of the method (on the curly braces ending the method definition).

In the picture hereunder, $ReturnValue does not return any value as we have not yet reached the end of the method.
Method Return Value Before Method End

In the picture hereunder, we are at the end of the method (on its ending curly brace). At this stage the debugger knows the value returned by the method and $ReturnValue is populated by the debugger. We can enter $ReturnValue in the debugger Immediate window and see that it holds the value returned by the method. The return value is also visible in the debugger Autos window at the entry with the word “returned” in it. The entry is only a placeholder to show the object instance returned by the method (in this case a string) and does not correspond to any actual variable name.
Mothod Return Value At Method End

 

Example when Stepping Out of the method.

In the picture hereunder we have just stepped out of the method which we want to know its returned value. We can see that the return value is made available by the debugger in both the Immediate and the Autos window.
Return Value When Step Out Of Method

Once we step over to the next line of code in the debugger (F10 shortcut), the entry in the Autos window for the return value is lost and in the Immediate window, $ReturnValue does not evaluate to anything anymore.
No Return Value After Step Out Of Method

Reference: http://msdn.microsoft.com/en-us/library/dn323257.aspx

Visual Studio compile error: Cryptographic failure while signing assembly Access is denied

One of the development environment for developing BizTalk Server 2006 solutions I worked on had Windows XP and Visual Studio 2005 running on it. The environment was quite complicated with scripts and Domain Controller Policies executing each time you would log on the machine. Moreover, I think that the C:\Documents and Settings directory was mapped to some network resource as the directory would become inaccessible when network problems occurred.

Anyhow, one day while compiling a BizTalk solution in Visual Studio, I had the following error:

Cryptographic failure while signing assembly ‘MyAssemblyName’ Access is denied.

The cause was that I had lost access rights in the following directory: C:\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys.  I don’t know why I had lost access rights but it was probably due to one of those unusual scripts/policies loaded at startup… and I never had such error on any other environments. After giving myself full access rights on that folder, the BizTalk solution would compile without error.

In the following screenshot I gave full access right to “Everyone” for simplicity sake as more than one user needed the access rights.

crypto_RSA_Folder_ACL

 

Conclusion:

The underlying reason for the compilation error is that because BizTalk libraries are deployed to the GAC, they must be signed with a strong name key file. As the signing process uses the C:\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys folder, the assembly could not be signed without being able to access the folder and the compilation would faild. Once I fixed the access rights, the assembly could be signed and Visual Studio could compile the BizTalk solution successfully.

This means that this error can happen any time the folder is needed such as in the following scenarios:

  • Compiling a Visual Studio project which assembly is signed.
  • Compiling a project or solution containing strongly signed assemblies through msbuild and/or TFS.
  • Generating a strong name key file with Visual Studio or with the utility sn.exe
There are probably other scenarios this folder is used for but it will obviously always be related to cryptography.

 

Debug a process on a remote machine not having Visual Studio installed

This article will explain how to do remote debugging with Visual Studio.

I had to debug a BizTalk application that is running on a remote integration server on which Visual Studio is not installed. Actually, the remote server was a Virtual Machine but that does not change anything.
I took the following steps to be able to debug the remote BizTalk process from my development machine on which Visual Studio is installed:

  1. Copy the Remote Debugger folder from the development machine (having Visual Studio installed) to the remote machine. If you don’t find it, its location can be found from Visual Studio’s start menu. For VS 2005, VS 2008, VS 2010 it respectively is:
    1. <Program Files>\Microsoft Visual Studio 8\Common7\IDE\Remote Debugger\
    2. <Program Files>\Microsoft Visual Studio 9.0\Common7\IDE\Remote Debugger\
    3. <Program Files>\Microsoft Visual Studio 10.0\Common7\IDE\Remote Debugger\

    The <Program Files> token is Visual Studio installation folder which is by default C:\Program Files (x86)\ on 64 bit machines and C:\Program Files\ on 32 bit machines. Note that on 64 bit machines, VS 2005 has the 64 bit remote debugger in C:\Program Files\ and the 32 bit debugger in C:\Program Files (x86)\. VS2010 has all the debugger versions under C:\Program Files (x86)\.

  2. Start Visual Studio Remote Debugging Monitor on the remote machine. The process is called msvsmon.exe. I executed it with the “Run as” option using the domain user name that I use on my development machine to avoid credential issues and to give unrestricted access to the debugger process.
    msvsmon.exe run as
  3. After the remote debugging monitor process is started, copy the Server Name in the clipboard or in notepad. The Server Name is found by clicking Tools -> Options. The remote debugging monitor server name has the following format: DomainName\UserName@MachineName.
    msvsmon.exe Visual Studio Remote Debugging Monitor
  4. Copy the necessary libraries and symbol files (.dll and .pdb) in a directory on the remote machine. For the sake of this example let’s put them in C:\Code\Debug
  5. Configure Visual Studio on the local development machine so that it can instructs the remote debugging monitor on where to find the symbol files (.pdb). To do that, open Visual Studio and go to Tools -> Options -> Debugging -> Symbols and set the path where msvsmon.exe can find the pdb files on the remote machine. It is C:\Code\Debug in our example.
    Visual Studio Options Debugging Symbols Location
  6. Attach the remote process to debug by Visual Studio’s debugger. When the project is loaded in Visual Studio and breakpoints are set, go to Debug -> Attach to Process. In the Qualifier field, put the Server Name published by the remote debugging monitor that we took note of in step 3. Click refresh so that the processes of the remote server are displayed.
    Visual Studio Debugger Attach To Remote Process
  7. Select the process that you want to debug and click Attach. In our case we want to debug a BizTalk application so the BizTalk process (BTSNTSvc.exe) was chosen. Confirm “Attach” on the security warning dialog.
    Visual Studio Debugger Attach To Remote Process Warning

That’s it, it is now possible to debug on the remote server! For BizTalk scenarios this can prove very powerful to debug orchestrations when the Orchestration debugger is not enough or when we want to debug a .Net library that is loaded as part of some BizTalk processing (pipelines, orchestrations, maps …).

How to Handle Unhandled Exception

When an unhandled exception occurs in the .Net Framework run-time 1.0 & 1.1, the Windows Process will terminate only if the exception occurred on the main application thread. Would an unhandled exception occur in a thread other than the main application thread, it will be caught by the runtime and therefore NOT cause the application to terminate. This means that unhandled exceptions in child threads disappear silently without anyone being able to know about it, implying that bugs are silently swallowed by the runtime without anyone being notified about it. The dangerous scenario is that a user might believe that a unit of work has executed successfully while it is actually not the case. This is in my opinion something not desirable and has been addressed in later version of the .Net Framework.

Indeed, from the .Net Framework 2.0 onwards, unhandled exceptions occurring on ANY thread (thus including any child threads being background threads or not) shuts down the application running the particular thread.

When the runtime terminates an application because of an unhandled exception, it writes an entry in the Windows Event Log which looks like the following:

EventType clr20r3, P1 processname, P2 1.0.0.0, P3 485f85f0, P4 system, P5 2.0.0.0, P6 471ebf0d, P7 3832, P8 bf, P9 system.componentmodel.win32, P10 NIL.

“processname” being the name of the .Net executable.

1. How to resolve unhandled exceptions? The System.AppDomain.UnhandledException event.

If an unhandled exception occurs in a windows application (multi-threaded or not), a windows service named winservice.exe for example, the runtime will terminate the service and write an Event Log entry such as:
“EventType clr20r3, P1 winservice.exe, P2 1.0.0.0, P3 485f85f0, P4 system, P5 2.0.0.0, P6 471ebf0d, P7 3832, P8 bf, P9 system.componentmodel.win32, P10 NIL.”

While it is good to be notified that a service crashed, the information supplied is rather cryptic and has very little added value. It would be nicer to have a way to log unhandled exceptions with a more meaningful message so that it is possible to get enough information to be able to fix the source code and re-deploy the application.

Conveniently, the .Net Framework provides the System.AppDomain.UnhandledException event. This event fires whenever an application domain unloads because of an unhandled exception. Note that registering for the event does not cause unhandled exceptions to be “handled”. It simply notifies you that an exception has gone unhandled, so that it is possible to take some action such as logging the exception message and stack trace and eventually do some clean up before the application dies. The Exception is still unhandled and so still causes the application to shut down.

The discussion in this article is not a solution on how to handle exceptions. Exception handling is a strategy on how to handle exceptions and is a different discussion. This article explains how to act with unhandled exceptions so that details about the exception can be logged so that a proper solution can be found to resolve the issue/bug.

Ideally, all exceptions should be handled in the source code with try-catch-finally blocks so that unhandled exceptions do not occur. Nevertheless, there are always unforeseen cases and developer mistakes which, in my opinion, justify caring for unhandled exceptions across the board.

Here is an example on how to register for the event with an event handler that log exception details in the Windows Event Log:

// This event provides notification of uncaught exceptions. Write this in the entry point of your program, like in the OnStart() method of a Windows Service.
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler);
static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args)
{
Exception ex = (Exception)args.ExceptionObject;
EventLog.WriteEntry(“WinService.exe”, “Unhandled Exception caught: ” + ex.Message + ex.StackTrace, EventLogEntryType.Error);
}

2. Note for Windows Form Applications – Application.ThreadException event.

2.1 Application.ThreadException event

For Windows Form Applications, there is another event that is raised when an unhandled exception occurs, the System.Windows.Forms.Application.ThreadException. Nevertheless, this event fires only when unhandled exceptions happen in Window Forms threads (UI threads). This means when an exception is thrown from code that was ultimately called as a result of a Windows Message. Windows Messages are emitted by keyboard hits, mouse clicks or “paint” messages,… in short, nearly all code in a typical Windows Forms application.

While this works perfectly, it lulls one into a false sense of security that all exceptions will be caught by the central exception handler:

  • Exceptions thrown on worker threads are a good example of exceptions not caught by Application.ThreadException.
  • Exceptions thrown by the code inside the Main method of the Windows Forms application, including the main form’s constructor, executes before the Windows message loop begins and so is another example of exceptions that do not raise the Application.ThreadException event.

In this case, we said the Application.ThreadException event handler to be a “central exception handler” because it is still possible for the application to keep running when this event is raised, depending on what kind of logic is implemented in the handler.

As a reminder, Worker Threads are threads:

  • Created manually: Thread.Start()
  • Created by the ThreadPool: ThreadPool.QueueUserWorkItem()
  • Created by any kind of asynchronous call which internally uses a thread pool thread to execute: Delegate.BeginInvoke(), BeginXXX()

One must attach a handler to the Application.ThreadException event before instantiating the main form of the application by calling Application.Run(). Also, because this is a static event, you must detach the event handler(s) when the application is disposed or memory leaks will result.

The Application.ThreadException as a default event handler which behaves in the following way:

  • If an unhandled exception occurs in the main application thread, the default exception handler catches it and terminates the application.
  • If an exception occurs in a thread other than the main application thread, the thread exits, but the application continues to run.

2.2 Application.SetUnhandledExceptionMode

It is possible to instruct the application whether it should catch all unhandled exceptions thrown by Windows Forms components and terminate the application, or whether it should raise an event so that an event handler can be implemented; the event handler could halt execution and expose the unhandled exception to the user. This is setting is done by using the application configuration file or the Application.SetUnhandledExceptionMode() method.
It is possible to instruct the application whether it should catch all unhandled exceptions thrown by Windows Forms components and terminate the application, or whether it should raise an event so that an event handler can be implemented; the event handler could halt execution and expose the unhandled exception to the user. This is setting is done by using the application configuration file or the Application.SetUnhandledExceptionMode() method.

  • UnhandledExceptionMode.ThrowException never route exceptions to the Application.ThreadException event handler and so the default event handler will terminate the application when an unhandled exception occurs as explained earlier.
  • UnhandledExceptionMode.CatchException always route exceptions to the Application.ThreadException event handler.

Again, as a reminder, the Application.ThreadException event handler is only for unhandled exception occurring on UI threads and so the SetUnhandledExceptionMode() method affects only the way unhandled exceptions coming from UI threads are treated, it does not affect how non UI threads unhandled exceptions are treated. System.AppDomain.UnhandledException event handlers will always be called when non UI threads unhandled exceptions occur.

2.3 Sample

Hereunder is a code sample on how to register to the Application.ThreadException event in a Windows Form Application. As said earlier the event handler will only be called for unhandled exceptions occurring on the UI thread. Thus, the code sample also has an event handler for unhandled exception on non-UI threads by registering to the System.AppDomain.UnhandledException event:

static class Program
{
///

/// The main entry point for the application.
///

[STAThread]
static void Main()
{
// Add the event handler for handling UI thread exceptions to the event.
Application.ThreadException += new ThreadExceptionEventHandler(Form1_UIThreadException);

// Set the unhandled exception mode to force all Windows Forms errors on UI threads
// to go through our handler regardless of application settings.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

// Add the event handler for handling non-UI thread exceptions to the event.
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

// Default generated code by Visual Studio for WinForms
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}

You can find a zip file here containing a complete Visual Studio 2008 solution demonstrating both type of unhandled exception event handler and their effect.

3. Note for ASP.NET applications – Application_Error in Global.asax.

Would an unhandled exception occurs in an ASP.NET application on a worker thread, the runtime will terminate the worker process (w3wpp.exe) and write an Event Log entry such as:
“EventType clr20r3, P1 w3wp.exe, P2 6.0.3790.1830, P3 42435be1, P4 app_web_7437ep-9, P5 0.0.0.0, P6 433b1670, P7 9, P8 a, P9 system.exception, P10 NIL.”

In ASP.Net, there is an Application_Error method in the Global.asax file that can be implemented so that an action can be taken when an unhandled exception occurs (logging the exception details, for example). Again, treating an unhandled exception in such a way is not handling an exception (that should be done in the try-catch-finally block in the code), the web application will still crash and display an error message on the browser but it lets the programmer have a way to log information about the exception and eventually do some other clean-up tasks.

Nevertheless, similarly to Windows Forms Application, the Application_Error will be called only for unhandled exception that occurred on the main thread. Unhandled exceptions occurring on worker threads will not be caught by the Application_Error event handler in the global.asax file. If we want to be notified of unhandled exception occurring on worker threads, we need to register an event handler to the System.AppDomain.UnhandledException event, as we did for Windows Services and Forms Applications. The event handler should at least log the exception and eventually do some clean tasks.

Microsoft has a KB on how to implement an event handler for the System.AppDomain.UnhandledException event within an HTTPModule.

You can find here a zip file with a Visual Studio 2008 solution using the HTTPModule defined in the KB. I registered the HTTP module in the web.config the following way:



.Net assembly is said to have a strong name when it is signed.

There are 2 ways to retrieve the Public Key Token from a strongly named assembly:

  • The lazy way is to add the assembly in the GAC and go to C:\WINDOWS\assembly, one of the column showed in Windows Explorer is the Public Key Token. Only strongly named assemblies can be stored in the GAC.
  • Run the command line “sn -T UnhandledExceptionModule.dll” which prints the Public Key token of a strongly named assembly.

Contrary to the instructions given in the KB, I did not GAC either NGEN the HTTP module; I just referenced the HTTPModule project from the web project so that the HTTP module library is automatically copied to the web application bin folder. All assemblies in the bin folder are automatically found by the run-time so that is not necessary to GAC all third party libraries.

SQL Server and .Net Data Type mapping

Today I would like to post a table listing the corresponding .Net Type to use with each SQL Data Type. This comes in handy when writing ADO.NET code.

The following link lists Microsoft SQL Server data types and their equivalent data type in .Net.
To be more exact it lists:

  • Every SQL Server data types
  • Their equivalent in the Common Language Runtime (CLR) for SQL Server in the System.Data.SqlTypes namespace
  • Their native CLR equivalents in the Microsoft .NET Framework

SQL Server Data Types and Their .NET Framework Equivalents

I have also copy-pasted the SQL Server and .Net Data Type mapping table hereunder for my own convenience:

SQL Server data type CLR data type (SQL Server) CLR data type (.NET Framework)
varbinary SqlBytes, SqlBinary Byte[]
binary SqlBytes, SqlBinary Byte[]
varbinary(1), binary(1) SqlBytes, SqlBinary byte, Byte[]
image None None
varchar None None
char None None
nvarchar(1), nchar(1) SqlChars, SqlString Char, String, Char[]
nvarchar SqlChars, SqlString SQLChars is a better match for data transfer and access, and SQLString is a better match for performing String operations. String, Char[]
nchar SqlChars, SqlString String, Char[]
text None None
ntext None None
uniqueidentifier SqlGuid Guid
rowversion None Byte[]
bit SqlBoolean Boolean
tinyint SqlByte Byte
smallint SqlInt16 Int16 (short in C#)
int SqlInt32 Int32 (int in C#)
bigint SqlInt64 Int64 (long in C#)
smallmoney SqlMoney Decimal (decimal in C#)
money SqlMoney Decimal (decimal in C#)
numeric SqlDecimal Decimal (decimal in C#)
decimal SqlDecimal Decimal (decimal in C#)
real SqlSingle Single (float in C#)
float SqlDouble Double (double in C#)
smalldatetime SqlDateTime DateTime
datetime SqlDateTime DateTime
sql_variant None Object
User-defined type(UDT) None Same class that is bound to the user-defined type in the same assembly or a dependent assembly.
table None None
cursor None None
timestamp None None
xml SqlXml None

Regarding CLR Data Types, Data Types are basically divided in 3 categories:

Furthermore, 3 types of CLR Data Type structures exist to hold numeric values:

See Data Types (C# Reference) for a complete reference and correspondance between CLR types and C# types.