Exceptions Management (or lack of it)

A good example of what not to do.

Picture 1

DragMove

Did you know there is a new method called DragMove which is part of the Window class and allows you to move the window using a mouse? I certainly did not – till now. This is part of .NET 3.0, specifically part of WPF and . Here is an example from the SDK:

protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
    base.OnMouseLeftButtonDown(e);

    // Begin dragging the window
    this.DragMove();
}
 

Writing High-Perf. Managed Apps?

If you are writing high-perf. managed applications, all the old-world advice from the days of good old COM is still valid. But you do need to think of a few other things such as how the CLR JIT would change things, or the Exception Handling, or Threading and syncing up, or possibly the GC and Allocation Profiles? While this MSDN article is old (now), it still is excellent Food for Thought when it comes to writing high-perf. apps.

Exception Management in Threads

Exception Management is a topic near and dear to me personally, primarily because of the lack of understanding of most developers (that I have come across). There is an interesting change in the .NET 2.0 CLR on how it manages unhandled exceptions in a thread. If you write multi-threaded apps then this is important for you to understand. If you don’t write multi-threaded apps today, but I presume you would soon, then this is a good learning exercises.

In .NET 2.0 the CLR allows unhandled exceptions in threads to proceed naturally – which in many cases probably means that the application will terminate. For certain cases (listed below) where exceptions are used for controlling program flow, the CLR does provide a backstop for unhandled exceptions in threads. Note, the CLR terminated the threads in these cases and does not propagate the exception further.

  • Abort() is called causing a ThreadAbortException.
  • AppDomain (in which the thread is running) is being unloaded, causing a AppDomainUnloadedException.
  • The Host process (or CLR) terminates the thread via an internal exception.

This is a significant change from .NET v1.x where there is no concept of a Unhandled Exception in many situations such as a Thread pool. If an unhandled exception is thrown, the runtime prints that to the console and then returns the thread to the thread pool. Also, if an unhandled exception occurs in the Start() method of a Thread class, the runtime again prints the exception stack trace to the console and then gracefully terminating the thread. Lastly, if an unhandled exception occurs on a Finalizer thread, the trace is written to the console, and the finalizer thread is allowed to resume!

Needless to say, if you have code currently designed for this, it will break in .NET 2.0 and you would need to change your implementation. As a temporary workaround you can choose your app to still use the old style from v1.x by setting the flag in the runtime section, but this should be strictly till such a time you can port the code over to the new version:

<legacyUnhandledExceptionPolicy enabled=”1″/>

If you got MSDN installed for VS 05, you can read more here then.

Execution Context

It is quite interesting to see how many people don’t understand the basics of threading, while it is a difficult topic (especially to debug), and it is not the silver bullet for all the problems, but it sure is quite handy for certain things. With the inevitable shift to multi-core CPU’s and the release of Vista to take better opportunity of these extra power, more applications in the future should be ready to exploit them. Which makes it quite important for the average developer to start playing and understanding this.

If you are new to this, one of the classes I would recommend reading up on is called ExecutionContext class. This class essentially is the equivalent of the COM Apartment (from the good old COM days). This class provides a single container for all information relevant to a logical thread of execution which includes security context, call context, synchronization context, localization context, and transaction context. You cannot change context of the thread (to which a ExecutionContext is attached), you can only copy it to another thread. If you do try and copy it you will get an Exception.

Here is an example from MSDN on how to use this (also testing the new CopyAsHTML Addin):

    1 using System;

    2 using System.Threading;

    3 using System.Security;

    4 using System.Collections;

    5 using System.Security.Permissions;

    6 using System.Runtime.Serialization;

    7 using System.Runtime.Remoting.Messaging;

    8 

    9 namespace Contoso

   10 {

   11     class ExecutionContextSample

   12     {

   13         static void Main()

   14         {

   15             try

   16             {

   17                 Console.WriteLine(“Executing Main in the primary thread.”);

   18                 FileDialogPermission fdp = new FileDialogPermission(

   19                     FileDialogPermissionAccess.OpenSave);

   20                 fdp.Deny();

   21                 // Capture the execution context containing the Deny.

   22                 ExecutionContext eC = ExecutionContext.Capture();

   23 

   24                 // Suppress the flow of the execution context.

   25                 AsyncFlowControl aFC = ExecutionContext.SuppressFlow();

   26                 Thread t1 = new Thread(new ThreadStart(DemandPermission));

   27                 t1.Start();

   28                 t1.Join();

   29                 Console.WriteLine(“Is the flow suppressed? “ +

   30                     ExecutionContext.IsFlowSuppressed());

   31                 Console.WriteLine(“Restore the flow.”);

   32                 aFC.Undo();

   33                 Console.WriteLine(“Is the flow suppressed? “ +

   34                     ExecutionContext.IsFlowSuppressed());

   35                 Thread t2 = new Thread(new ThreadStart(DemandPermission));

   36                 t2.Start();

   37                 t2.Join();

   38                 // Remove the Deny.

   39                 CodeAccessPermission.RevertDeny();

   40                 // Capture the context that does not contain the Deny.

   41                 ExecutionContext eC2 = ExecutionContext.Capture();

   42                 // Show that the Deny is no longer present.

   43                 Thread t3 = new Thread(new ThreadStart(DemandPermission));

   44                 t3.Start();

   45                 t3.Join();

   46 

   47                 // Set the context that contains the Deny.

   48                 // Show the deny is again active.

   49                 Thread t4 = new Thread(new ThreadStart(DemandPermission));

   50                 t4.Start();

   51                 t4.Join();

   52                 // Demonstrate the execution context methods.

   53                 ExecutionContextMethods();

   54                 Console.WriteLine(“Demo is complete, press Enter to exit.”);

   55                 Console.Read();

   56             }

   57             catch (Exception e)

   58             {

   59                 Console.WriteLine(e.Message);

   60             }

   61         }

   62         // Execute the Demand.

   63         static void DemandPermission()

   64         {

   65             try

   66             {

   67                 Console.WriteLine(“In the thread executing a Demand for “ +

   68                     “FileDialogPermission.”);

   69                 new FileDialogPermission(

   70                     FileDialogPermissionAccess.OpenSave).Demand();

   71                 Console.WriteLine(“Successfully demanded “ +

   72                     “FileDialogPermission.”);

   73             }

   74             catch (Exception e)

   75             {

   76                 Console.WriteLine(e.Message);

   77             }

   78         }

   79 

   80         static void ExecutionContextMethods()

   81         {

   82             // Generate a call context for this thread.

   83             ContextBoundType cBT = new ContextBoundType();

   84             cBT.GetServerTime();

   85             ExecutionContext eC1 = ExecutionContext.Capture();

   86             ExecutionContext eC2 = eC1.CreateCopy();

   87             Console.WriteLine(“The hash code for the first execution “ +

   88                 “context is: “ + eC1.GetHashCode());

   89 

   90             // Create a SerializationInfo object to be used for getting the

   91             // object data.

   92             SerializationInfo sI = new SerializationInfo(

   93                 typeof(ExecutionContext),

   94                 new FormatterConverter());

   95 

   96             eC1.GetObjectData(

   97                 sI,

   98                 new StreamingContext(StreamingContextStates.All));

   99 

  100             LogicalCallContext lCC = (LogicalCallContext)sI.GetValue(

  101                 “LogicalCallContext”,

  102                 typeof(LogicalCallContext));

  103 

  104             // The logical call context object should contain the previously

  105             // created call context.

  106             Console.WriteLine(“Is the logical call context information “ +

  107                 “available? “ + lCC.HasInfo);

  108         }

  109     }

  110 

  111 

  112     // One means of communicating between client and server is to use the

  113     // CallContext class. Calling CallContext effectivel puts the data in a thread

  114     // local store. This means that the information is available to that thread

  115     // or that logical thread (across application domains) only.

  116     [Serializable]

  117     public class CallContextString : ILogicalThreadAffinative

  118     {

  119         String _str = “”;

  120 

  121         public CallContextString(String str)

  122         {

  123             _str = str;

  124             Console.WriteLine(“A CallContextString has been created.”);

  125         }

  126 

  127         public override String ToString()

  128         {

  129             return _str;

  130         }

  131     }

  132 

  133     public class ContextBoundType : ContextBoundObject

  134     {

  135         private DateTime starttime;

  136 

  137         public ContextBoundType()

  138         {

  139             Console.WriteLine(“An instance of ContextBoundType has been “ +

  140                 “created.”);

  141             starttime = DateTime.Now;

  142         }

  143         [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.Infrastructure)]

  144         public DateTime GetServerTime()

  145         {

  146             Console.WriteLine(“The time requested by a client.”);

  147             // This call overwrites the client’s

  148             // CallContextString.

  149             CallContext.SetData(

  150                 “ServerThreadData”,

  151                 new CallContextString(“This is the server side replacement “ +

  152                 “string.”));

  153             return DateTime.Now;

  154         }

  155     }

  156 

  157 }

System.Transactions and Timeout

Cross posting from All about Interop; System.Transactions has two timeout values that you can specify in configuration files. The default timeout for System.Transactions transactions is 1 minute.  You can set it in either app config, web config, or machine config.  (You can also set the timeout for a particular transaction programmatically within the application, by using one of the appropriate constructors for TransactionScope or CommittableTransaction).  Setting the default timeout to 30 seconds in config code looks like the following.

<configuration>
 <system.transactions>
  <defaultSettings timeout=”00:00:30″ />
 </system.transactions>
</configuration>

For System.Transactions there is also a maximum transaction timeout. It is designed to be used by the System Administrator to limit transaction timeouts. If this setting is not specified, it defaults to 10 minutes.  It cannot be overridden in code.   If the app.config timeout or the timeout specified in the constructors above exceed the maximum timeout in the machine.config, the timeout is adjusted down to the maximum timeout value. That can be specified only in machine config.  To change that you would specify the maxTimeout property of the machine settings section.  For example, this specifies 30 seconds:

<configuration>
 <system.transactions>
   <machineSettings maxTimeout=”00:00:30″ />
 </system.transactions>
</configuration>

So, for example if your app.config setting specifies a defaultSettings timeout of zero, which implies (with a screwy sort of logic) infinite timeout, or if your application code specifies a zero timeout in one of the constructors, then the actual timeout of the transaction will not be infinite – it will be bound to the setting for machineSettings maxTimeout.

For any high-throughput transactional server, The default maxTimeout setting is probably not right for you.  You’re going to want to set this pretty low.

This is for any transaction managed by DTC – that would include transactions involving SQL Server, Oracle, MQ, DB2, and so on.  If your transactions are timing out after 10 minutes and you want to know why, check these settings.

[Listening to: I Am – Bon Jovi – Have A Nice Day (03:54)]

Secure Startup Volume Encryption in Vista

It has been long overdue and now its finally present. Vista has something called the Secure Startup Volume Encryption which will work on computers with the Trusted Module Platform (TPM) chip. Here, all except the bare minimum of the boot volume is encrypted and at boot time the TPM transparently allows access to the drive. If someone either removed the hard disk and puts it in a different machine or attempts to boot from a different OS, the disk will be unreadable without a password. There is no GUI for this in Beta 1 but the service is there.

Profilers for the CLR

Brad Adams lists out a few options for Profilers available in the CLR – some of these possibly are familiar to you – but its good to see them listed in one place. (got this via Jon Kale who was responding to something else).

Inside regsvc.exe

Ever wondered what is happening inside regsvc.exe? Well so did Tomas Restrepo, and here is what he found out.

System Programming?

If you ever wanted a quick sample of some system programming – something you know is fairly simple to do but did not have the time to do it from scratch – just something quick and dirty, then you should check out this link – which has all the basic stuff Thread Pools, Waitable Handles, Monitors, Secure Remoting channel, etc.

Getting Started With Enterprise Library

If you recall I had recently posted about the release of Enterprise Lib. My colleague, Hisham Baz has a post on how to get started with the Ent. Lib. If you are new to it and want to know more about it, that is a good place to start.

[Listening to: Boy in the Well – R.E.M. – Around the Sun (05:22)]

Tips and Trips for .NET Compact Framework

Dave and John discuss various aspects of the .NET Compact Framework (CF) where in addition to the list belowthey cover things like the fastest way to splat text onto the screen? ExtTextOut using which you can draw text based on the currently selected font, background color, and text color. You can optionally provide dimensions to be used for clipping, opaquing, or both. It can also draw with a transparent background, which labels in the .NET Compact Framework do not support (just try to put a label over a PictureBox and you’ll see).

  • Tips for making programming in the .NET CF environment easier
  • Tricks for making your Pocket PC-based apps run faster
  • Important .NET CF classes
  • .NET CF windowing issues

If you do development on the CF then this is good article to read up on. As they conclude “Writing applications for the .NET Compact Framework is a wonderful experience. The applications are small enough that shareware developers can once again write something on their own and sell it online to make a little bit of money. But the simplicity and small capacity of mobile devices present new challenges to programmers. Without awesome power, you have awesome responsibility. Strive from the get-go to design code that is fast, tight, and highly, highly disposable.

More Information:  http://tinyurl.com/6xvsl

Tracking down managed memory leaks (how to find a GC leak)

At work, recently I attended an excellent presentation given by a colleague where we talked about Debugging in general (across both Managed and Unmanaged code), and what the various categories are, and various tools at ones disposal, etc. I thought this post from Rico on how to find GC leaks was quite timely for that topic.

[Listening to: City of Blinding Lights – U2 – How to Dismantle an Atomic Bomb [Bonus Track] (05:48)]

PInvoke.NET

If you ever thought that PInvoke was a pain in .NET, don’t fret, Adam Nathan has a VS.NET addin that you can get from here after using which you wondered, how the heck did I live without this! He also has a PInvoke.NET wiki for you to use and of course contribute to.

If you rather get to it yourself, then there is an wsdl endpoint exposed and Stripe has written a version that is proxy friendly. If you happen to be a Delphi.NET (strange as that might be) kind of guy or gal, you can get the check out Shenoy’s implementation of this.

After installing the add-in you can right-click in the source code to see the following two menu items:

 

Clicking on the first item opens a dialog allowing you to enter the signature e.g.:

[Listening to: Home Again – Dirty Vegas – One (04:47)]

Assembly signing changes in VS 2005

Bruce has a post (which I verbatim here) highlighting one of the small changes in Whidbey which will make life easier for a whole bunch of us.

In Whidbey, the name of the .snk file is included as a property on the project and is picked up my msbuild when compiling.  To get to it:

  • Right-click on the project in the solution explorer and select Properties.
  • Click on the Signing tab.
  • Provide the path to the .snk file.

How is it done today? As Bruce reminds us (and I verbatim here) signing assemblies in VS2003 and earlier meant adding attributes to the AssemblyInfo file, something similar to the following.

[assembly: AssemblyKeyFile(“..\\..\\ObjectSharp.snk”)]
[assembly: AssemblyDelaySign(false)]

But there are a couple of issues associated with these attributes.  First, the path to the key file is actually embedded in the assembly.  If you use a full path, it is possible that information about your machine (servers and directories, for example) can be easily extracted by using ildasm.  Not overtly dangerous, but not the best situation.

Also, providing a relative path to the key file is annoying.  I’m sure most of you have dealt with the trial and error of finding exactly where the .snk file is relative to the compilation directory.

Finally, because compilation cleanliness is important to all of us, keeping the AssemblyKeyFile attribute in AssemblyInfo generates a warning message.  Not always critical, but annoying.

.NET Service Pack 1 can break HttpWebRequest

If you installed .NET Service Pack 1 you might notice that certain RSS feeds are broken and might return an HTTP Protocol Error. As Dare suggests, this is due to the fact that the HttpWebRequest class has been modified to make it more compliant to the HTTP spec. E.g. on the MS research feeds, this errors because the server returns the Content-Location header as “Content Location” (notice the space as opposed to the hyphen). You can check out the list of fixes in .NET SP1.

Writing Windows-Shell Extensions using .NET

Dino writes an interesting article on how to write shell extensions in managed code. He also provides a brief overview of COM Interop covering both CCW (COM Callable Wrappers) and RCW (Runtime Callable Wrappers), which those of you who have had any experience with COM know has a fair amount of overheard and though is quite seamless to use, it is not to be taken lightly especially if you have custom data types in COM.

The key takeaway to remember for shell extension in addition to the COM Interop basics is the Win32 data types (constants, structs, enums, etc.) that need to be imported. You specify how do you want the type layout – either sequential or offset based – which one you would of course base on the structure of the COM data type.

If you have not played with Interop till now, then I would recommend reading up on the COM Interop tutorials first and trying out some simpler stuff. Also in Longhorn, the shell is running managed code, so there is no interop involved.

Invoking Google's web service on a Smartphone

Incase you did not hear, then which planet are you living on, but Google exposes their offering via a Web Service that you can use to search for … well … stuff. If you have programed on the .NET CF then you know this is quite simple (especially if you program on the “regular” .NET). Incase you have not dabbled in this and are interested in doing something simple then check out this article which steps you thru the simple application. If you are interested in doing some more mobile development then here are a few links for you to check out: