Here is a common pattern of code:

// set some temporary state for the following block
try
{
    // do some stuff
}
finally
{
    // un-set the temporary state set above
}

A perfect example is showing the wait cursor during an operation in a Windows Forms application:

this.UseWaitCursor = true;
try
{
    // do some stuff
}
finally
{
    this.UseWaitCursor = false;
}

Every time I write one of these, I think there must be a better way to do this, something more akin to the old CAutoPtr template class in C++/ATL. The CAutoPtr class worked because C++ (regular C++, not the managed version) has deterministic calling of destructors. This is to say, that when an object is freed, its destructor is called immediately. This is in contrast with managed code which is garbage collected.

In managed code (C#, VB.NET, etc.) when the last reference to an object is release, via setting the reference to null or when the reference variable goes out of scope, the object’s memory is not actually released right away, and the destructor is not called either. Instead, the object sits on the heap in the same state it was when that last reference was released until the .NET runtime decides it is running out of memory and needs to garbage collect. In today’s systems with 4 GB of RAM or more, this often does not happen until the application’s process ends.

To compensate for this and allow developers to explicitly force an object’s destructor to be called immediately, the creators of the .NET Framework provided the IDisposable interface. This article is not about IDisposable so I won’t go in to a long explanation about it. Instead, you should know these basic facts about IDisposable:

  • IDisposable is an interface that should (must?) be implemented by any class which manages critical, particularly unmanaged, resources.
  • IDisposable has one method, Dispose(), which should clean up any critical resources.
  • Unlike most interfaces, both C# and Visual Basic.NET have built-in knowledge and support of the IDisposable interface via the using statement (Using in Visual Basic.NET). When an object that implements IDisposable is wrapped in a using statement, its Dispose() method is called immediately when the using statement goes out of scope. Example:
        string text;
        // The StreamReader class implements IDisposable
        using (StreamReader reader =
                    new StreamReader("c:\\tmp\\foo.txt"))
        {
            text = reader.ReadToEnd();
        }
        // At this point, the using statement goes out of
        // scope, which causes the StreamReader's Dispose
        // method to be called, which closes the file's
        // handle.

Based on this, I knew any CAutoPtr like class would need to use the IDisposable interface in order to take advantage of the using statement, but I never took the time to actually figure out the details. That is, until now. As I have become more proficient at LINQ and lambda expressions, it became clear that the combination of IDisposable and lambda expressions was the answer. Interestingly, my AutoCleanup class itself does not leverage lambda expressions itself anywhere, rather it is the ability to use anonymous functions when constructing the AutoCleanup class that makes this so useful.
Here is the complete AutoCleanup class:

using System;

namespace ITDevWorks.Utility
{
    /// <summary>
    /// Guarantees automatic execution of delegate functions
    /// when an instance of this class is constructed and/or
    /// when it is disposed.
    /// </summary>
    /// <remarks>
    /// The <b>AutoCleanup</b> class is used in cases where
    /// you would normally use a try/finally to ensure that
    /// your cleanup code is executed, regardless of
    /// whether an exception was thrown or not.  With the
    /// <b>AutoCleanup</b> class, instead of all of the
    /// try/catch lines which can make code less readable,
    /// you can leverage the <see langword="using"/>
    /// statement, instantiating an instance of this class,
    /// and pass either just the cleanup code or both the
    /// constructor code and cleanup code to execute.
    /// </remarks>
    public class AutoCleanup : IDisposable
    {
        public delegate void ExecuteAction();

        private bool disposed = false;
        private ExecuteAction executeOnDispose;

        /// <summary>
        /// Constructs an <see cref="AutoCleanup"/> object,
        /// immediately executing a delegate function, and
        /// the guaranteeing the execution of a second
        /// deletate function when disposed.
        /// </summary>
        /// <param name="executeOnConstruct">
        /// The delegate function to execute during
        /// construction.
        /// </param>
        /// <param name="executeOnDispose">
        /// The delegate function to execute when disposed.
        /// </param>
        public AutoCleanup(ExecuteAction executeOnConstruct,
                           ExecuteAction executeOnDispose)
        {
            if (null != executeOnConstruct)
            {
                executeOnConstruct();
            }
            this.executeOnDispose = executeOnDispose;
        }

        /// <summary>
        /// Constructs an <see cref="AutoCleanup"/> object,
        /// guaranteeing the execution of a provided delegate
        /// function when disposed.
        /// </summary>
        /// <param name="executeOnDispose">
        /// The delegate function to execute when disposed.
        /// </param>
        public AutoCleanup(ExecuteAction executeOnDispose)
        {
            this.executeOnDispose = executeOnDispose;
        }

        #region IDisposable Members
        /// <summary>
        /// Disposes the <see cref="AutoCleanup"/> object,
        /// executing the delegate function provided in the
        /// constructor.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        //
        // Internal implementation of the Dispose() method.
        // See the MSDN documentation on the IDisposable
        // interface for a detailed explanation of this
        // pattern.
        //
        private void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                //
                // When disposing is true, release all
                // managed resources.
                //
                if (disposing)
                {
                    if (null != this.executeOnDispose)
                    {
                        this.executeOnDispose();
                    }
                }
                disposed = true;
            }
        }
        #endregion
    }
}

To use this class, you construct a new instance of it inside of a using statement, and pass in two parameter-less, anonymous functions. Note that when an anonymous function has not parameters you must provide the open and close parenthesis with nothing between them where the parameter list would normally go.

private void Form1_Shown(object sender, EventArgs e)
{
    using (new AutoCleanup(() => this.UseWaitCursor = true,
                           () => this.UseWaitCursor = false))
    {
        // do form initialization
    }
}

Furthermore, I was able to use AutoCleanup as a base to create specialized derivations of for common use cases. Below is an example that implements the UseWaitCursor logic.

using System;
using System.Windows.Forms;

namespace ITDevWorks.Utility
{
    /// <summary>
    /// Automatically enables the wait cursor for a Windows
    /// Forms control and disables it when the class is
    /// disposed.
    /// </summary>
    public class AutoWaitCursor : AutoCleanup
    {
        public AutoWaitCursor(Control control)
            : base(() => { control.UseWaitCursor = true;
                           Application.DoEvents(); },
                   () => { control.UseWaitCursor = false; })
        {
            // Do Nothing
        }
    }
}

Like the XML comment shows above, to use this class all you need to do is:

private void Form1_Shown(object sender, EventArgs e)
{
    using (new AutoWaitCursor(this))
    {
        // do form initialization
    }
}

This is far simpler and easier to read than the whole try/finally clumsiness.

{ 0 comments }

I don’t know if any of you have experienced this, but it has been causing me grief for some time, but I finally solved it.

The Background
I have a web page that is part of the admin area of a client’s website.  The page has a GridView with a list of the website’s members.  The GridView is contained inside of an UpdatePanel control. 

The Problem
When you click the “Edit” button for a row, and your browser is some version of Internet Explorer (this does not happen with Firefox), your Page_Load() method is called twice. The first time IsPostBack == false, and none of your ViewState variables are available, so as far as your code is concerned, it looks like a first time page load and any “!IsPostBack” logic you have is executed.  The second call to Page_Load() is the normal one where .IsPostBack is true and your event handlers are called.

Since the ViewState variables are not present, you cannot set any sort of flag indicating the page has already been loaded.  Setting Trace=”true” on the @Page directive in the .aspx file yields nothing because the page is loaded twice so the first one is overwritten by the second.  I even tried setting an onunload handler in the client script to raise a server event (via Page.ClientScript.GetCallbackEventReference), but for some reason the onunload handler was never called, regardless of whether I set it on the window, document or body element.

The Solution
After trying all sorts of ways to reliably identify when a Page_Load() call was bogus, I finally came across this thread in the ASP.NET forums.  Basically, the solution is very simple and easy – you check the Page.Request.RequestType property.  If the RequestType is “GET”, it is the real first time page load.  If it is “POST”, then it is a postback.  So, I created the following property:

protected bool IsFalseFirstPageLoad
{
    get { return (!this.IsPostBack &&
            0 == String.Compare(this.Request.RequestType, "POST", true)); }
}

Then, at the top of my Page_Load() method, I have the following code:

if (this.IsFalseFirstPageLoad)
{
    return;
}

As simple as that. Problem solved.

{ 1 comment }

When I was at Microsoft I worked on two different teams that were part of the larger Developer Division – Visual Studio Tools for Office (VSTO) and Visual Studio Team System (VSTS).  While neither of these was the core VS team, we were close enough to get occasional wisdom from them.  One such piece of wisdom dealt with cases when Visual Studio slows down dramatically, especially when debugging.  The solution was simple, just exit VS altogether, navigate to the folder where your .sln file is located and delete the .suo file there.  I don’t recall exactly why this works, but apparently the information in this aut0-generated file can get into a state where it causes VS to work way too hard to resolve otherwise simple problems.  Note that when you re-open the project in Visual Studio, all of your breakpoints, open files and similar session state information will be lost, but hopefully your slowness problems will be resolved.

If this does not solve your Visual Studio performance woes, here are a couple of other links which may be useful:

  • Microsoft KB 920805:  Describes a slow response time in Visual Basic 2005 projects and a link to a hotfix to install.
  • Visual Studio 2008 PAINFULLY SLOW!!: A thread on social.msdn.microsoft.com about performance issues in VS.  The primary answer in this thread has to do with changing an option in Internet Explorer which causes VS to check on the internet for certificate revocations by third-party control/library providers.

Hope this helps someone.

{ 0 comments }

Which Authorize.net API to use?

by davep on December 3, 2009

I recently answered a question on the Authorize.net forum. The questioner wanted to know which API to use for a single, one-time transaction. Below is my answer. You may find it helpful in determining which Authorize.net API to use for your purposes.

  • Use AIM to make a single payment in real-time while the customer is using your application/website and has their credit card in-hand, and (if your application is a website) your site has an SSL certificate installed such that all senstive credit card information is entered via a from over an https:// connection.
  • Use SIM if the above is true but you do not have an SSL certificate installed (and do not plan to install one).
  • Use CIM if you want to support storing the customer’s credit card (or bank account, if you support it) information so the customer does not have to re-enter it if they return to your site *or* you have a recurring billing situation where either the amount or frequency of billing fluctuates.In either case, you will need the SSL certificate / https:// connection for when the customer enters their payment information.

The other common factor which causes people to choose AIM over SIM is they want to maintain the branding of their site when the customer pays. When you use SIM, the customer is sent to a form hosted by Authorize.net to enter their payment information. You can customize the header and footer somewhat, and change the background color and a couple other things, but you cannot do anything like add links back to your site or add your normal menus, etc.

This is just a quick summary of the key differences between and uses for the different Authorize.net APIs. I plan to write an Authorize.net 101 post one of these days, which provides a high-level overview of their primary payment gateway APIs.  In the meantime, if you need more information, you should refer to Authorize.net’s own documentation, or check out their developer community forums.

{ 5 comments }

Coding and Development Standards: 15 Do’s and Don’ts for My Subcontractors

November 25, 2009

I am an independent software development consultant. By independent, I mean I generally work directly with my clients, rather than going through a contract agency or other firm. When I have more work than I can take on myself, I sometimes hire subcontractors to help out. To help get new subs up to speed on projects [...]

Read the full article →

CIM User Interface – Somebody has to announce it

November 10, 2009

[Update: 2009-11-10 @ 2:30 PM PST: It seems that as soon as I put this out Michelle C. from Authorize.net officially announced this feature on the Developer Community Forums. It also notes that this is phase one of a two-phase rollout, so there is more functionality to come.] Those folks over at Authorize.net are so [...]

Read the full article →

InitializableDictionary: Why is this not in System.Collections.Generic?

October 27, 2009

I am a total neat freak when it comes to code (my desk, though, is another matter). Whenever I find myself writing the same or very similar code within an application, I immediately want to factor out to a common, shared method. When something is repeated many times (say, 10-15 or more), my desire is [...]

Read the full article →

Authorize.net Terminology Overload: Test vs. Live

October 22, 2009

Authorize.net is one of the service providers that allows you to process payments by taking credit card and/or electronic check payments on your website. Integrating with Authorize.net requires testing, first. So, when you create an account with Authorize.net, it is placed in Test Mode, and you must manually put the account in Live Mode before you can actually [...]

Read the full article →

Did you know?: Authorize.net per-transaction charge on validating CIM PaymentProfile

October 13, 2009

Update 2009-10-18:  Authorize.net has posted an announcement on their forums regarding support of Visa Mandates surrouding validation charges.  In short, if you submit a transaction for $0.01 (or something similar) but do not “fully reverse” the charge, you could be subject to a “Misuse of Authorization” fee.  Instead, Visa will allow you to submit a [...]

Read the full article →