Every now and then I generate SQL scripts for setting up test databases or for deployment purposes. Typically I use the "Publish to provider" command that is available in Visual Studio. That often serves med well, but it has one feature that I don't like about it: if I choose to script only Stored Procedures, it will generate a script that will also drop and create all tables that these procedures talk to (which I find a bit on the dangerous side). Furthermore, it will not do this in a certain order (such as drop all tables, drop all procedures, create tables, create procedures), but mix the handling of different object types through the file. This makes it rather hard to clean the file by hand. This is a sample of what they look like:

/****** Object:  ForeignKey [FK_SomeKey]    Script Date: 03/25/2010 17:25:14 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_SomeKey]') AND parent_object_id = OBJECT_ID(N'[dbo].[SomeTable]'))
ALTER TABLE [dbo].[SomeTable] DROP CONSTRAINT [FK_SomeKey]
GO
/****** Object:  ForeignKey [FK_SomeOtherKey]    Script Date: 03/25/2010 17:25:14 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_SomeOtherKey]') AND parent_object_id = OBJECT_ID(N'[dbo].[SomeOtherTable]'))
ALTER TABLE [dbo].[SomeOtherTable] DROP CONSTRAINT [FK_SomeOtherKey]
GO
/****** Object:  StoredProcedure [dbo].[SomeProcedure]    Script Date: 03/25/2010 17:25:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SomeProcedure]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SomeProcedure]
GO
/****** Object:  View [dbo].[SomeView]    Script Date: 03/25/2010 17:25:15 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[SomeView]'))
DROP VIEW [dbo].[SomeView]
GO
/****** Object:  StoredProcedure [dbo].[SomeOtherProcedure]    Script Date: 03/25/2010 17:25:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SomeOtherProcedure]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SomeOtherProcedure]
GO
/****** Object:  UserDefinedFunction [dbo].[SomeFunction]    Script Date: 03/25/2010 17:25:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SomeFunction]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[SomeFunction]
GO

So, say we want to clean the script so that only stuff that is related to stored procedures remain. If the file is big, that is a lot of editing to do. Luckily, the Visual Studio editor supports regular expressions, and this is one of those occasions where regular expressions are extremely useful. Unfortunately, the regex syntax is somewhat special in Visual Studio, but it is still usable. The following expression will locate all script blocks that are not related to stored procedures:

/\*+ Object\::b:b~(StoredProcedure)(.*\n)#GO\n

So, by using that regex and replacing all matches with an empty string, only blocks related to stored procedures will remain.


I am working for a great consultancy company called Diversify, located in Sweden. We are hiring skilled .NET developers. If you are interested, don't hesitate to get in touch with me.

The other day I published a blog post showing an example of how extension methods can be used to hide infrastructure code. Today's post runs along the same lines, but instead aims to encapsulate a little code snippet that is repeated whenever you deal with events. Let's take it from the start to the end (but I'll still keep it rather brief).

An event declaration will typically look something like this:

public event EventHandler<EventArgs> SomeEvent;

Then, in the type that raises the event, you will have a method called On[EventName], that carries out the task of actually raising the event:

protected void OnSomeEvent(EventArgs e)
{
    EventHandler<EventArgs> temp = SomeEvent;
    if (temp != null)
    {
        temp(this, e);
    }
}

An event is null if it has no event handler attached to it. What you see here is the recommended pattern for raising events. The step of assigning the event to the temp variable is taken in order to avoid a race condition where the event may have an event listener when performing the null check, but then the event handler is detached from the event after the null check (by another thread), but before the event is invoked. That would lead to a NullReferenceException, and we don't want that here.

Events inherit from MulticastDelegate, which is an immutable type, so by simply assigning the event to a variable, we have shielded our code from any subsequent changes to the invocation list of the event; since any such modification will cause SomeEvent to refer to a completely new MulticastDelegate instance; our local copy is still referring to the old one. (There is a quirk here that I will bring up in the end)

Bottom line is; the code pattern above is a candidate for being repeated for each and every event in your code. And we don't like repetition, do we? This can easily be taken care of by a simple extension method:

public static class EventHandlerExtensions
{
    public static void SafeInvoke<T>(this EventHandler<T> evt, object sender, T e) where T : EventArgs
    {
        if (evt != null)
        {
            evt(sender, e);
        }
    }
}

This means that the OnSomeEvent method above can be reduced to this one-liner:

protected void OnSomeEvent(EventArgs e)
{
    SomeEvent.SafeInvoke(this, e);
}

Two notes

You may wonder thy I did not have to assign the event to a temporary variable in the extension method as I needed to do in the first version of OnSomeEvent. Give it a thought and see if you can figure it out. Here is the answer: when passing the event as an argument to the extension method, the argument becomes our local variable that will continue to refer to the old instance of the event in case of any modifications.

And lastly, the quirk. While the presented code pattern does protect the code from throwing a NullReferenceException, we may experience another scenario, which is sort of the opposite. Say we have an event handler attached, the null check is performed, and then the event handler is detached before the event is raised. The method raising the event will still have the now detached event handler in its invocation list for the event, so it will indeed get invoked. This means that there is a possibility (small, but real) that an event handler is invoked after it has been attached.

kick it on DotNetKicks.com


I am working for a great consultancy company called Diversify, located in Sweden. We are hiring skilled .NET developers. If you are interested, don't hesitate to get in touch with me.

Extension methods have been around for a while in C# by now, and sometimes you see questions regarding the real use of this approach. That can be debated, and this text is not aiming to cover the subject in whole, but instead show on one case where you may find them usable.

Recently I was working on a piece of code that needed a lot of synchronization to control access to a shared resource (that code will be covered in a coming blog post). I used the ReaderWriterLockSlim for this, which sometimes produced code blocks like the following (this code sample has, as usual, been created just for demo purposes):

private static int GetFromQueueWithoutExtensions()
{
    int result = -1;
    _lock.EnterUpgradeableReadLock();
    try
    {
        if (_sharedResource.Count > 0)
        {
            _lock.EnterWriteLock();
            try
            {
                result = _sharedResource.Dequeue();
            }
            finally
            {
                _lock.ExitWriteLock();
            }
        }
    }
    finally
    {
        _lock.ExitUpgradeableReadLock();
    }

    return result;
}

_sharedResource is a static Queue<int> instance, declared elsewhere in the class. The above method contains 12 lines of code (disregarding blank lines, and lines consisting of only a curly brace). In these 12 lines of code, only 4 are directly related to the task of the function, the remaining 8 lines being what we could call infrastructure; various control mechanisms to make sure that appropriate locks are acquired and released. This can make the code harder to read, since you will need to filter out the (minority of) lines that carry out the actual functionality of the method.

If we investigate the code structure a bit closer, we can see that the pattern around running code while holding a certain lock looks like this (pseudo code):

acquire the lock
try
{
   execute the task while holding the lock
}
finally
{
   release the lock
}

This is a repeating pattern, so now I see two reasons to refactor the original code sample shown above; try to move infrastructure out of the method, and stick to the DRY (Don't Repeat Yourself) principle.

I will start by trying to encapsulate the "run code under lock" pattern into a separate method:

private static void RunWithUpgradeableReadLock(ReaderWriterLockSlim readerWriterLock, Action action)
{
    readerWriterLock.EnterUpgradeableReadLock();
    try
    {
        action();
    }
    finally
    {
        readerWriterLock.ExitUpgradeableReadLock();
    }
}

The above code needs to be repeated for each lock method (so methods encapsulating EnterReadLock and EnterWriteLock need to be added). Now, the calling code can be shortened down quite considerably:

private static int GetFromQueueWithEncapsulation()
{
    int result = -1;

    RunWithUpgradeableReadLock(_lock, () =>
    {
        if (_sharedResource.Count > 0)
        {
            RunWithWriteLock(_lock, () =>
            {
                result = _sharedResource.Dequeue();
            });
        }
    });

    return result;
}

Now, by making a couple of small modifications to the encapsulating method, we can make it into an extension method. First we need to move it into a class that is declared as public static. Second we need to add the keyword this in front of the ReaderWriterLockSlim parameter:

public static class ReaderWriterLockSlimExtensions
{
    public static void RunWithUpgradeableReadLock(this ReaderWriterLockSlim readerWriterLock, Action action)
    {
        readerWriterLock.EnterUpgradeableReadLock();
        try
        {
            action();
        }
        finally
        {
            readerWriterLock.ExitUpgradeableReadLock();
        }

    }
}

By doing this you add one feature above all (in my opinion): discoverability. The method RunWithUpgradeableReadLock method will show up in IntelliSense when using a ReaderWriterLockSlim:

extensionmethods.intellisense

In order to have your code call the extension method rather than the encapsulated method shown earlier, you write code that invokes the method on the lock object rather than passing the lock object as an argument:

private static int GetFromQueueWithExtensions()
{
    int result = -1;

    _lock.RunWithUpgradeableReadLock(() =>
    {
        if (_sharedResource.Count > 0)
        {
            _lock.RunWithWriteLock(() =>
            {
                result = _sharedResource.Dequeue();
            });
        }
    });

    return result;
}

This code block contains two extra lines of code (plus scoping curly braces) for the locking mechanisms. In my opinion this is making the code much more to the point, making it easier to read and understand what it does.

kick it on DotNetKicks.com


I am working for a great consultancy company called Diversify, located in Sweden. We are hiring skilled .NET developers. If you are interested, don't hesitate to get in touch with me.