beaucrawford.net

Give me data or give me death

About the author

Author Name is someone.
E-mail me Send mail

Recent comments

Don't show

Authors

Tags

Don't show

    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

    © Copyright 2009

    MSMQ – Sending Messages to Remote Queues

    The situation is simple – you want to send a message to a remote MSMQ. To do so you might write some code that looks something like:

    using (var queue = new MessageQueue(@"FormatName:Direct=TCP:192.168.2.157\Private$\TheQueue"))
    {	
    	var message = new Message(shipment);
    	message.Formatter = new BinaryMessageFormatter();
    	queue.Send(message, MessageQueueTransactionType.Single);	
    }

    This code works fine... most of the time. The problem is that, for remote queues, MSMQ sends messages in a "fire and forget" type of mode by default, i.e. if the message gets there, great! If not, oh damn well. This was not apparent to me at first. In workflow situations where you cannot let things "slip through the cracks" it is critical that you receive acknowledgement of delivery. For example, consider the following pseudo-code:

    using (var transaction = new TransactionScope())
    {
        // Perform numerous database operations here
    
        // Send message to remote queue here
    
        transaction.Complete();
    }

    What if the send operation to the remote queue does not succeed? Well, in a workflow with state tracking, we absolutely must rollback all of the database operations and leave the system in the exact same state that existed before we attempted the send operation. The only way we can do this is to know whether the message arrived in the remote queue. Thankfully MSMQ provides a fairly easy way to accomplish this through the use of an Administrative Queue. The purpose of this queue is to provide a "callback" location for the target queue to send an acknowledgement message. This message is uniquely identified by its Message ID property. The high-level steps for guaranteed delivery are:

    1) Create a message and define an Administrative Queue 
    2) Send the message 
    3) Wait a little 
    4) Check the Administrative Queue for the message's unique ID

    The code to do this is:

    using (var queue = new MessageQueue(@"FormatName:Direct=TCP:192.168.2.157\Private$\TheQueue"))
    {
    	var message = new Message(shipment);
    	message.Formatter = new BinaryMessageFormatter();
    	message.AdministrationQueue = new MessageQueue(@"FormatName:Direct=TCP:192.168.2.148\Private$\AdminQueue");
    	message.AcknowledgeType = AcknowledgeTypes.PositiveArrival;
    	queue.Send(message, MessageQueueTransactionType.Single);
    
    	Thread.Sleep(100);
    
    	bool acknowledged = ReceiveAcknowledgment(message.Id, @".\Private$\AdminQueue");
    
    	if (!acknowledged)
    	{
    	   throw new InvalidOperationException("Acknowledgement was not received");
    	}
    }

    Yes, the above code uses a Thread.Sleep call. I realize that this is somewhat of an anti-pattern but it is called for here as you have no way of gauging network latency.  The best you can really do is supply a sleep time that is relative to your queue architecture, i.e. if your queues are on an Intranet then you can probably get away with 100 ms (or less).  If you’re using queues over the Internet then you will probably need a longer wait time.  This is the price you pay for guaranteed delivery acknowledgement – a small one in my opinion.

    The "ReceiveAcknowledgment" helper method is defined as follows:

    private static bool ReceiveAcknowledgment(string messageId, string queuePath)
    {
        var queue = new MessageQueue(queuePath);
        queue.MessageReadPropertyFilter.CorrelationId = true;
        queue.MessageReadPropertyFilter.Acknowledgment = true;
    
        while (queue.PeekByCorrelationId(messageId) != null)
    	{
    		Message message = queue.ReceiveByCorrelationId(messageId);
    		return true;
    	}
    
        return false;
    }

    Categories: C#
    Posted by Beau on Saturday, June 27, 2009 11:43 AM
    Permalink | Comments (1) | Post RSSRSS comment feed

    CoreDateTime.Now - The Future is Now

    Like most developers, I often find myself dealing with code that references DateTime.Now. For example consider this code that retrieves items relative to the current date/time:

    var command = new SqlCommand();
    command.CommandType = CommandType.StoredProcedure;
    command.CommandText = "GetItems";
    command.Parameters.Add(new SqlParameter("TargetDate", DateTime.Now));

    It would be hard to develop an integration test for this code since it references DateTime.Now. What if I wanted to test the scenario where items with a future date/time value needed to be retrieved, i.e. how will the system behave six months from now? A simple, but very effective, way to deal with this is to add the following class:

    public class CoreDateTime
    {
        static CoreDateTime()
        {
            Executor = () => DateTime.Now;
        }
    
        internal static Func Executor
        {
            get;
            set;
        }
    
        public static DateTime Now
        {
            get
            {
                return Executor();
            }
        }
    }

    The key thing to note here is that the "Executor" property is simply a Func that wraps a call to the normal DateTime.Now. This means that CoreDateTime.Now will behave exactly like DateTime.Now.

    You will also notice that the "Executor" property uses the internal access modifier. This allows testing assemblies to inject a Func of their choosing. You can expose this property to test assemblies using the System.Runtime.CompilerServices.InternalsVisibleTo assembly attribute and then update it with code like:

    CoreDateTime.Executor = () => DateTime.Parse("5/10/2013 10:15 AM");

    You can also have successive calls to CoreDateTime.Now be evaluated against a fixed point in time. This allows you to easily jump to any point of time in the past or future. This code might look like:

    var init = DateTime.Now;
    CoreDateTime.Executor = () => dateTimePicker1.Value.AddSeconds((DateTime.Now - init).TotalSeconds);                

    Happy time travels!


    Categories: C# | Testing
    Posted by Beau on Saturday, June 27, 2009 10:13 AM
    Permalink | Comments (0) | Post RSSRSS comment feed

    ASP.NET Bundle launch giveaway

    Unit Testing ASP.NET? ASP.NET unit testing has never been this easy.

    Typemock is launching a new product for ASP.NET developers – the ASP.NET Bundle - and for the launch will be giving out FREE licenses to bloggers and their readers.

    The ASP.NET Bundle is the ultimate ASP.NET unit testing solution, and offers both Typemock Isolator, a unit test tool and Ivonna, the Isolator add-on for ASP.NET unit testing, for a bargain price.

    Typemock Isolator is a leading .NET unit testing tool (C# and VB.NET) for many ‘hard to test’ technologies such as SharePoint, ASP.NET, MVC, WCF, WPF, Silverlight and more. Note that for unit testing Silverlight there is an open source Isolator add-on called SilverUnit.

    The first 60 bloggers who will blog this text in their blog and tell us about it, will get a Free Isolator ASP.NET Bundle license (Typemock Isolator + Ivonna). If you post this in an ASP.NET dedicated blog, you'll get a license automatically (even if more than 60 submit) during the first week of this announcement.

    Also 8 bloggers will get an additional 2 licenses (each) to give away to their readers / friends.

    Go ahead, click the following link for more information on how to get your free license.

    Posted by Beau on Tuesday, May 19, 2009 8:53 AM
    Permalink | Comments (1) | Post RSSRSS comment feed

    Managing settings between multiple developers

    Managing connection strings, app settings, log4net settings, SMTP settings, etc between developers and environments can be a major pain in the ass.  I’ve used numerous approaches for this in the past but none of them completely satisfied me.  That has, finally, come to an end.

    The approach I have laid out here will allow developers to have their own personal settings and not have to worry about modifying any .config files each time they perform an update from source control.   This approach will also allow you to easily manage your environment specific settings via your Build server.

    Step 1 – Environmental Variable

    Each developer must create an environmental variable that points to the root for their local working directory.

    Step 2 – Project Config Directory

    Create a Config directory under the development directory’s root.  Within this Config directory each developer should have a subdirectory for his/her machine name.  So, for example:

    - Local working directory for project: D:\Projects\SomeProject\

    - Environment variable named MyRoot maps to D:\Projects\SomeProject\

    - Project config path: D:\Projects\SomeProject\Config\

    - Personal config path: D:\Projects\SomeProject\Config\BEAU-PC\

    - The above path for my personal configuration should then be resolvable via: %MyRoot%\Config\BEAU-PC\

    Step 3 – Project .targets File

    This .targets file can contain the properties, targets, etc that are common to all projects.  You will need, at least, the below target which will copy the .config files found in your personal config path to a directory named “Config” in the output assembly’s bin directory:

       
       <Target Name="AfterBuild" Condition="Exists('$(MyRoot)\Config\$(ComputerName)\')">
    	
    	<ItemGroup>
    		<ConfigFiles Include="$(MyRoot)\Config\$(ComputerName)\*.config" />
    	</ItemGroup>
       
    	<Copy SourceFiles="@(ConfigFiles)" DestinationFolder="$(TargetDir)\Config\" />
    		
       </Target>

    Note: the above target must be placed inside the normal MSBuild project structure.

    Step 4 – Modify Projects

    You must now modify all .csproj (or .vbproj) files so that they import the above .targets file.  This is as simple as opening the project file in a text editor and finding the Microsoft.CSharp.targets import and placing your import directly after it (if it’s not after it then it will not fire, as the “AfterBuild” target logic is defined in the Microsoft.CSharp.targets file).


    <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
    <Import Project="$(MyRoot)\SomeProject.targets" />

    Step 5 – Application Configuration

    Within your app.config (or web.config) any machine/environment specific settings can now be stored in separate .config files found in the machine specific directory mentioned above.  You can then use the configSource attribute to reference these settings.  For example:

      <appSettings configSource="Config\AppSettings.config" />
      <connectionStrings configSource="Config\ConnectionStrings.config" />

    You should note that, for web applications, the configSource paths are evaluated relative to the web root and not the bin directory.  This means your configSource paths should look like:

    bin\Config\ConnectionStrings.config

    Hopefully this makes your life easier.


    Categories: General | MSBuild
    Posted by Beau on Saturday, March 28, 2009 8:56 AM
    Permalink | Comments (1) | Post RSSRSS comment feed

    The Poor Man's Inversion of Control Container

    I know most IOC frameworks have all kinds of bells and whistles for Constructor Injection, Setter Injection, Factory method calls, etc.  But I have found that I can solve 99% of my Dependency Injection needs by using what I like to call “Poor Man’s IOC”.  The approach is simple.  I have a single interface named IDependencyResolver that looks like this:

    public interface IDependencyResolver
    {
        T Resolve() where T : class;
    }

    The purpose of this interface is to (obviously) abstract the instantiation of a concrete class.  It assumes that the class has a public default constructor.  With this approach I can have a class that manages a singleton instance of IDependencyResolver for the current application domain.  This class is pretty straightforward and simply wraps a call to a internal static field that is of type IDependencyResolver:

    public static class DependencyResolver
    {
        private static IDependencyResolver currentResolver = new UnityDependencyResolver();
    
    	internal static void Initialize(IDependencyResolver resolver)
    	{
    		Validate.NotNull("resolver", resolver);
    
    		currentResolver = resolver;
    	}
        
    	public static IDependencyResolver CurrentResolver
    	{
    		get { return currentResolver; }
    	}
    
    	public static T Resolve()
    		where T : class
    	{
    		return currentResolver.Resolve();
    	}
    }

    A few interesting points here are:

    1) The currentResolver static field is initialized to an instance of UnityDependencyResolver.  This is simply a class that implements IDependencyResolver and wraps calls to the Unity framework for the inner implementation.  You could obviously use any IOC framework here or provide the mapping between Interface Types and Concrete Types yourself.

    2) The “Initialize” method uses the internal access modifier.  This is by design as I only want it made available to the current assembly or Testing assemblies granted access via the InternalsVisibleTo attribute.

    With this in place all instances are instantiated via a call to DependencyResolver.CurrentResolver.Resolve<T>.  To protect against developers using data layer types in the business layer I typically set them to be internal – which forces you to go through the DependencyResolver.

    A fringe benefit to this simple approach is that it makes injecting test doubles from a unit test extremely easy.  I can actually use Rhino Mocks to create a stub for the IDependencyResolver interface and then set that to be the current resolver:

    // Arrange
    var person = MockRepository.GenerateMock< IPerson >();
    
    // Set expectations about the person instance
    
    var resolver = MockRepository.GenerateStub< IDependencyResolver >();
    resolver.Stub(r => r.Resolve< IPerson >()).Return(person);
    DependencyResolver.Initialize(resolver);
    
    // Act
    
    SomeMethod(person);
    
    // Assert
    
    person.VerifyAllExpectations();

    Done deal.  The next call to DependencyResolver.CurrentResolver.Resolve<IPerson> will return my IPerson mock instance.  Again, I realize that this simple approach does not support everything IOC has to offer – but I feel you can tackle the vast majority of situations with it.  The bonus, of course, is that it’s very simple and easy to maintain.


    Categories: C# | Testing
    Posted by Beau on Wednesday, March 25, 2009 6:15 PM
    Permalink | Comments (1) | Post RSSRSS comment feed