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 2012

    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

    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