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 2010

    Hosting an ADO.NET Data Service inside an NUnit Integration Test Fixture

    This post is geared towards ADO.NET Data Services but the techniques used here could really be used to perform integration testing for any WCF service. 

    First off, yes, I realize that you can test the vast majority of your service functionality outside of an actual service -- after all, there’s no reason for us to test the networking code somebody at Microsoft wrote.  But lets assume that, for some reason, you wanted to perform a full-blown integration test for your ADO.NET Data Service.  How can we do it?  A few notes to get started:

    1) The service needs to start before any tests execute.  We can accomplish this by using the TestFixtureSetup attribute in NUnit.

    2) The service needs to run in its own thread.  This is because it will service requests that originate from tests in the same test fixture.  NUnit executes all methods within the fixture synchronously.  If the service started and blocked while waiting for requests then that would be a very bad thing – as the test run would never complete and no tests would be executed.

    3) The service needs to handle requests for the lifetime of the test fixture and no longer.  We can make this happen by using an AutoResetEvent instance.  This will cause the thread that’s hosting the service to block until it receives a signal.  We can initiate this signal from a method that is adorned with the TestFixtureTeardown attribute.  NUnit executes all methods with this attribute after it executes all methods adorned with the "Test attribute. This will allow the service to close and dispose of itself.

    private static readonly Uri serviceUri = new Uri("http://localhost:1642/MyService.svc");
    
    private static AutoResetEvent serviceResetEvent = new AutoResetEvent(false);
    
    [TestFixtureSetUp]
    public void FixtureSetup()
    {
        Action runService = () =>
        {
            using (var host = new WebServiceHost(typeof(MyService), serviceUri))
            {
                host.Open();
                serviceResetEvent.WaitOne();
                host.Close();
            }
        };
    
        var thread = new Thread(new ThreadStart(runService));
        thread.Start();
    }

    The key thing to notice here is that the AutoResetEvent instance starts with its initial state == false.  This will cause calls to the “WaitOne” method to block until a signal is sent using the “Set” method – which is exactly what we need to do in the test fixture tear down operation:

    [TestFixtureTearDown]
    public void FixtureTearDown()
    {
        serviceResetEvent.Set();
    }

    We can now create integration tests that actually call the Data Service.  A simple example might be:

    [Test]
    [Category("Integration")]
    public void DataServiceIntegrationTestExample()
    {
        DataServiceContext context = new DataServiceContext(serviceUri);
    
        DataServiceQuery query =
            context.CreateQuery< MyType >("MyMethod")
            .AddQueryOption("someParameter", "'someValue'");
    
        var results = context.Execute< MyType >(query.RequestUri);
    
        Assert.IsTrue(results.Count< MyType >() == 1);
    }

    This will create a WCF service request which will get served by the service instance created in the test fixture setup method.


    Categories: WCF | C# | Testing
    Posted by Beau on Tuesday, March 24, 2009 11:58 PM
    Permalink | Comments (2) | Post RSSRSS comment feed

    Calling TryParse Dynamically

    Most of the common types have a “TryParse” method available.  Here’s a method you can use to dynamically call the corresponding TryParse method for a specific Type:

    public static T ConvertValue<T>(string stringValue)
    {
        if (typeof(T) == typeof(string))
            return (T)Convert.ChangeType(stringValue, typeof(T));
    
        var type = typeof(T);
    
        bool nullableType = type.IsGenericType 
            && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>));
    
        if (nullableType)
        {
            if (stringValue == null)
                return default(T);
    
            type = new NullableConverter(type).UnderlyingType;
        }
    
        Type[] argTypes = { typeof(string), type.MakeByRefType() };
    
        var tryParse = type.GetMethod("TryParse", argTypes);
    
        if (tryParse == null)
        {
            string exceptionMessage = string.Format("A method named 'TryParse' does not exist for the '{0}' Type.", type.FullName);
            throw new InvalidOperationException(exceptionMessage);
        }
    
        object[] args = { stringValue, null };
    
        bool successfulParse = (bool)tryParse.Invoke(null, args);
    
        if (!successfulParse)
            throw new InvalidCastException();
    
        return (T)args[1];
    }



    I’m currently using this in a code generation scenario where I have a string value and “T” is known at generation time.  Enjoy.


    Categories: C# | Reflection | Code Generation
    Posted by Beau on Tuesday, March 24, 2009 7:35 PM
    Permalink | Comments (3) | Post RSSRSS comment feed

    ASP.NET Development Server stopped serving pages

    I’m running Vista Ultimate and, for some odd reason, the ASP.NET Development Server stopped serving pages after I installed IIS7 (at least that’s the last time I remembered it working).  Another oddity is that it would serve pages when I changed the localhost domain to 127.0.0.1.

    I poked around a little and found a fix for the problem.  You simply need to add an entry to the “hosts” file at the following path:

    C:\Windows\System32\drivers\etc

    The magic line you need is:

    127.0.0.1        localhost


    Posted by Beau on Monday, March 23, 2009 9:47 PM
    Permalink | Comments (0) | Post RSSRSS comment feed

    Testing Work Flow Dependencies with Rhino Mocks 3.5

    We’re currently working on a custom Work Flow system (no, not Windows Work Flow) that utilizes MSMQ.  To make each work flow node highly testable what I decided to do was create an abstraction of the items I needed from the System.Messaging.MessageQueue class.  This abstraction is an interface named IMessageQueue.  The next thing was to create a “QueueServer” class that obtains an instance of IMessageQueue via a simple Inversion of Control container named QueueResolver.

    QueueServer Start method:

    public void Start()
    {
        Queue = QueueResolver.Current.CreateInstance(Path, Transactional);
    
        if (Transactional)
        {
            Queue.PeekCompleted += PeekCompleted;
            Queue.BeginPeek();
        }
        else
        {
            Queue.ReceiveCompleted += ReceiveCompleted;
            Queue.BeginReceive();
        }
    }


    The default implementation of the QueueResolver class is quite simple (yes, i know we could use any of the common IOC containers to achieve this – but I like this approach for some specific situations since it is more lightweight and I don’t have to worry about maintaining a .config file, etc):

    public class QueueResolver
    {
        static QueueResolver()
        {
            Current = new QueueResolver();
        }
    
        public static void Initialize(QueueResolver resolver)
        {
            Validate.NotNull("resolver", resolver);
    
            Current = resolver;
        }
    
        public static QueueResolver Current
        {
            get;
            private set;
        }
    
        protected QueueResolver()
        {
        }
    
        public virtual IQueueClient< T > CreateClient< T >(string name, string path, bool transactional)
            where T : class, IFlowObject< long >
        {
            return new QueueClient< T >(name, path, transactional);
        }
    
        public virtual IQueueServer< T > CreateServer< T >(string name, string path, bool transactional)
            where T : class, IFlowObject< long >
        {
            return new QueueServer< T >(name, path, transactional);
        }
    
        public virtual IMessageQueue CreateInstance(string path, bool transactional)
        {
            Validate.NotNullOrEmpty("path", ref path);
    
            MessageQueue queue;
    
            if (MessageQueue.Exists(path))
            {
                queue = new MessageQueue(path);
            }
            else
            {
                queue = MessageQueue.Create(path, transactional);
            }
    
            queue.Formatter = new BinaryMessageFormatter();
    
            return new MessageQueueProxy(queue);
        }
    }


    This ends up being a very simple way for me to break the dependency on an actual MSMQ instance and allows me to inject test doubles of IMessageQueue with some simple code like:

    const string Name = "Test Queue";
    const string Path = @".\Private$\TestQueue";
    const bool Transactional = true;
    
    var resolver = MockRepository.GenerateStub< QueueResolver >();
    var queue = MockRepository.GenerateMock< IMessageQueue >();
    resolver.Stub(r => r.CreateInstance(Path, Transactional)).Return(queue);
    
    QueueResolver.Initialize(resolver);

    The advantage to all this, of course, is that I can now use Rhino Mocks to test the inner functionality of the QueueServer by utilizing this Dependency Injection technique:

    bool eventRaised = false;
    
    var customer = MockRepository.GenerateStub< ICustomer >();
    var server = new QueueServer< ICustomer >(Name, Path, Transactional);
    
    server.ItemReceived += delegate(object sender, QueueEventArgs< ICustomer > e)
    {
        eventRaised = true;
        Assert.AreSame(e.Item, customer);
    };
    
    server.Start();
    
    var message = new Message();
    message.Body = customer;
    queue.Raise(q => q.PeekCompleted += null, queue, new EventArgs< message >(message));
    
    Assert.IsTrue(eventRaised);

    We also have a QueueClient class that obtains an instance of IMessageQueue in the same manner.  With these two classes we will be able to easily model our work flow and completely unit test the interaction between the queues.  Also we will be able to easily unit test the entire lifespan of a “flow object” and write robust unit tests to track it throughout the work flow.


    Categories: C# | Design Patterns | Testing
    Posted by Beau on Sunday, March 15, 2009 10:35 AM
    Permalink | Comments (0) | Post RSSRSS comment feed

    Hacking into the Windows Workflow Rules Engine

    On my current gig we have been toying with the idea of creating a rules engine to a control a simple work flow that centers on Microsoft Message Queue.  The main idea is to build a very simple UI that allows a Business user to enter an expression based off of a Type in our system, such as ICustomer.   We would give the user some sort of “Poor Man’s Intellisense” to help them with the syntax but, other than that, they would be on their own – just keep pressing keys until you have a valid expression (we would wrap the expression evaluation call in a try/catch).

    My first thought was to use the LINQ Dynamic Query API to allow a user to enter a statement as a string and then simply call some code that looks something like this:

    var lambda = DynamicExpression.ParseLambda(typeof(ICustomer), typeof(bool), txtExpression.Text.Trim());
    var result = (bool)lambda.Compile().DynamicInvoke(instance);

    The statement, in this case, would evaluate to a Boolean value (the conditional part of the Rule evalulation).  That looked very promising and definitely would have fit the bill for the vast majority of our needs. I wanted something more though – namely the ability to use extension methods as part of the expression and to also be able to execute method invocation statements.  I was not having any luck in modifying the LINQ Dynamic Query code to consistently do what I needed to for these items.  That led me to look elsewhere.

    I had previously heard about using the WF Rules Engine outside of WF itself at the Twin Cities Code Camp a few months ago.  It’s a pretty simple concept really and I remember thinking at the time that it looked very promising.  In an effort to pay this problem its due diligence I investigated WF in more detail.  Turns out it’s pretty easy to interact with the Rule object model directly:
    var thisType = typeof(IShipment);
    
    var currentInstance = new Shipment();
    
    var ruleSet = new RuleSet("Test");            
    var ruleValidation = new RuleValidation(thisType, null);
    
    Rule rule = new Rule("Rule 1");
    rule.ReevaluationBehavior = RuleReevaluationBehavior.Never;
    rule.Condition = Parser.ParseCondition("ShipmentDate > DateTime.Now.AddDays(-30)", ruleValidation);
    rule.ThenActions.AddRange(Parser.ParseStatementList("Queue.Send(\"StagingQueue\", this)", ruleValidation).ToArray());
    
    ruleSet.Rules.Add(rule);
    
    RuleExecution exec = new RuleExecution(new RuleValidation(currentInstance.GetType(), null), currentInstance);
    ruleSet.Execute(exec);

    The crux of my problem is obviously how to parse an arbitrarily complex expression into an an instance of RuleExpressionCondition.  If you look at the above code you will notice some references to a static class named “Parse”.  This, unfortunately, is a class that I had to create.  I noticed that WF uses the System.Workflow.Activities.Rules.Design.RuleSetDialog Windows Form to maintain a RuleSet.  I cracked this Type open in Reflector in an effort to see how they were taking the strings entered on the UI and converting them to expressions.  As I expected, the functionality for doing this is all internal.  Bummer.  Well, for now, I decided to use a little Full Trust reflection to create a wrapper around some Reflection calls:

    using System;
    using System.Collections.Generic;
    using System.Reflection;
    using System.Workflow.Activities.Rules;
    
    namespace WFRulesSample
    {
        public static class Parser
        {
            private const string TypeName = "System.Workflow.Activities.Rules.Parser, System.Workflow.Activities, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
    
            public static RuleExpressionCondition ParseCondition(string expression, RuleValidation ruleValidation)
            {
                return ExecuteMethod("ParseCondition", new object[] { ruleValidation }, new object[] { expression }) as RuleExpressionCondition;
            }
    
            public static List< RuleAction > ParseStatementList(string expression, RuleValidation ruleValidation)
            {
                return ExecuteMethod("ParseStatementList", new object[] { ruleValidation }, new object[] { expression }) as List< RuleAction >;
            }
    
            private static object ExecuteMethod(string name, object[] ctorParameters, object[] methodParameters)
            {
                var type = Type.GetType(TypeName);
                var ctor = type.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(RuleValidation) }, null);
                var instance = ctor.Invoke(ctorParameters);
                var method = instance.GetType().GetMethod(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                return method.Invoke(instance, methodParameters);
            }
        }
    }

    It’s doubtful that the above code will ever see the light of day for this project.  I just found it interesting.

    Caveat – yes, the above code is probably not great in terms of performance.  There are numerous ways you could speed it up with the use of some DynamicMethod calls.  Good luck and happy hacking.


    Categories: Reflection | C#
    Posted by Beau on Saturday, March 14, 2009 1:03 AM
    Permalink | Comments (3) | Post RSSRSS comment feed