Windows Workflow 4: Dynamically Load Workflows

I’m starting a new project where I plan to use Windows Workflow Foundation to load custom jobs from external XML files like plug-ins. In order for this to work, I’ll have a sub-directory that my application watches. If files are found, they will be loaded and executed.

The reason I want to do this is because Windows Workflow Foundation 4 makes it easy to keep the workflows as human-readable XML files that can be edited by technical-but-not-developer users. This allows for easy, efficient customization of workflows. The processes we have now require developer interaction for any customization or modification since everything is compiled into DLLs making our development team an unnecessary bottleneck for warranty and enhancement.

Over the next days and weeks, I’ll be publishing a number of posts that demonstrate small nuggets of WF4 functionality. I’ve been impressed with what I’ve been able to accomplish in just a few days of fooling around, so this I’m very excited about this endeavor!

I’m keeping it short and simple with this post: loading and running an XML (XAML) workflow from a file at runtime. This very powerful functionality can be accomplished in a single line of code:

WorkflowInvoker.Invoke(ActivityXamlServices.Load("HelloWorld.xml"));

One of my main goals is encapsulating all of my functionality in human-readable XML, so I also wanted to provide the contents of my HelloWorld.xml file. This workflow is unimpressive and simply writes “Hello, world!” to the console, but here it is, nonetheless:

<Activity xmlns="http://schemas.microsoft.com/netfx/2009/xaml/activities" 
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <WriteLine Text="Hello, world!" />
</Activity>

Redirect Console Output in C#

Those of you that know me know that I love a good console application. I use them all the time for samples and prototypes. Sometimes it’s nice to capture the output from a console application to share with others.

It’s remarkably simple to accomplish this with the .NET Framework. There is a static method Console.SetOut that accepts a TextWriter. Redirecting output from your console application is as simple as creating a TextWriter and calling that method.

Here’s a quick example (taken directly from MSDN):

Console.WriteLine("Hello World");
FileStream fs = new FileStream("Test.txt", FileMode.Create);
// First, save the standard output.
TextWriter tmp = Console.Out;
StreamWriter sw = new StreamWriter(fs);
Console.SetOut(sw);
Console.WriteLine("Hello file");
Console.SetOut(tmp);
Console.WriteLine("Hello World");
sw.Close();

XSL Transformations in C#

In Visual Studio 2005 (yea–this happened a few years ago), Microsoft redesigned the architecture of their XSL transformations. It wasn’t difficult to execute a simple transformation before, but it’s downright ridiculous now.

Here’s a complete example of executing a simple XSL transformation:

using System.Xml.Xsl;

namespace Xml.XslTransformation
{
    class Program
    {
        static void Main(string[] args)
        {
            var prog = new Program();
            prog.Run();
        }

        public void Run()
        {
            var xslt = new XslCompiledTransform();
            xslt.Load("mapping.xslt");
            xslt.Transform("sample.xml", "output.xml");
        }
    }
}

EmitDefaultValue and the DataContractSerializer

Often times when serializing an object to XML, you may want to include empty elements with their default values. This is the default behavior of the .NET Framework’s DataContractSerializer, but it can be toggled by using the EmitDefaultValue property in the DataMember attribute on a class’s properties. EmitDefaultValue has a default value of true, meaning it will include empty elements with their default value. Setting this property to false causes empty elements to be excluded.

Here’s a complete example:

namespace Serialization.EmitDefaultValue
{
    [DataContract]
    public class Human
    {
        [DataMember]
        public string Name { get; set; }
    }

    [DataContract]
    public class HumanNoDefault
    {
        [DataMember(EmitDefaultValue = false)]
        public string Name { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var prog = new Program();
            prog.Run();
        }

        public void Run()
        {
            SerializeToConsole<Human>();
            SerializeToConsole<HumanNoDefault>();

            Console.ReadLine();
        }

        public void SerializeToConsole<T>() where T : new()
        {
            using (var ms = new MemoryStream())
            {
                var h = new T();
                var serializer = new DataContractSerializer(typeof(T));
                serializer.WriteObject(ms, h);
                ms.Seek(0, SeekOrigin.Begin);
                var sr = new StreamReader(ms);
                Console.WriteLine("{0}:{1}{2}{1}", typeof(T).Name, Environment.NewLine, sr.ReadToEnd());
            }
        }
    }
}

And the output (note that the Name element is excluded in the second XML):

Human:
<Human xmlns="http://schemas.datacontract.org/2004/07/Serialization.EmitDefaultValue" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><Name i:nil="true"/></Human>

HumanNoDefault:
<HumanNoDefault xmlns="http://schemas.datacontract.org/2004/07/Serialization.EmitDefaultValue" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"/>

Verify Function Arguments Using Constraints in Rhino Mocks

Verifying arguments passed into a mocked or stubbed method can help you write more specific, robust unit tests. This is easily accomplished with Rhino Mocks by using Constraints.

As an example, let’s write a test for the function MyClass.MyMethod in the code below:

public interface IMyDependency
{
    void DependencyMethod(MyResult myResult);
}

public class MyResult
{
    public int Code;
}

public class MyClass
{
    public IMyDependency MyDependency { get; set; }

    public MyClass(IMyDependency myDependency)
    {
        MyDependency = myDependency;
    }

    public void MyMethod(string input)
    {
        switch (input)
        {
            case "A":
                MyDependency.DependencyMethod(
                    new MyResult { Code = 1 });
                break;
            case "B":
                MyDependency.DependencyMethod(
                    new MyResult { Code = 2 });
                break;
            default:
                break;
        }
    }
}

The first thing we need to do is create a mock IMyDependency and verify that its DependencyMethod is called, so let’s do that:

[TestMethod]
public void MyMethodTest()
{
    // Arrange
    var mockMyDependency = MockRepository.GenerateMock();
    var target = new MyClass(mockMyDependency);

    mockMyDependency.Expect(
        x => x.DependencyMethod(Arg<MyResult>.Is.Anything));

    const string input = "A";

    // Act
    target.MyMethod(input);

    // Assert
    mockMyDependency.VerifyAllExpectations();
}

This test passes, but how do we know the argument with the correct value was used? We can modify our mock object’s Expect call to use argument constraints to do this!

mockMyDependency.Expect(
    x => x.DependencyMethod(Arg<MyResult>.Matches(arg => arg.Code.Equals(1))));

Now my test only passes when the mock is called with an argument that matches the specified criteria. This is obviously a very basic example, but the fact that you can pass a delegate or derive a custom class from Rhino Mocks’s AbstractConstraint class makes this a very powerful feature.

C# Interop Tutorial

Creating a .net library for use with a VB6 application can be a tricky thing, but it’s really not that difficult when you follow the correct steps. This article will walk you through the tasks necessary to create an interop class in c# and invoke its methods from a VB6 application.

Create your interface

Just make an interface. Note the ComVisible attribute on the class and the DispId attribute on the methods.

namespace Sample.Vb6Interop
{
    [ComVisible(true)]
    public interface IMyInterop
    {
        [DispId(1)]
        string HelloWorld();
    }
}

Implement the interface in a class

Now implement your interface. Once again, I need to use the ComVisible attribute on the class.

namespace Sample.Vb6Interop
{
    [ComVisible(true)]
    public class MyInterop : IMyInterop
    {
        public string HelloWorld()
        {
            return "Hello, world!";
        }
    }
}

Register the assembly

You’ll use RegAsm to register your DLL. The key to this step is to use the /tlb option to create and register a COM type library. I also use the /codebase option since I’m not installing my DLL in the GAC.

regasm /tlb /codebase Sample.Vb6Interop.dll

Instantiate and use

Now the hard part’s done. In your VB6 project, you can instantiate and use your new class. I use late-binding in my project, but you could also add a reference to your project and use early-binding. (Early-binding is necessary for event handling.)

Private Sub Command1_Click()
    
    Dim objMyInterop As Object
    
    Set objMyInterop = CreateObject("Sample.Vb6Interop.MyInterop")
    
    Call MsgBox(objMyInterop.HelloWorld)
    
End Sub

This will give you a working example, but it only scratches the surface. Things get more complicated quickly when you start talking about events and callbacks.

Convert a Class Library to a Test Project in Visual Studio

Occasionally, you may run into a Visual Studio Class Library project that contains unit tests. This can be a frustrating scenario because creating a unit test using Visual Studio’s right-click context menus will not allow you to add a test to the project.

This can be remedied quite easily, though, by adding the correct project type guid to the Class Library’s project file. Here are the steps to do this from within Visual Studio:

  1. Right-click the project in Solution Explorer and choose Edit Project File
  2. Add a new child in the <PropertyGroup> node:
    <ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
  3. Save your changes and close the file
  4. Right-click the project in Solution Explorer and choose Reload Project

After following those steps, your project will show in the list of output projects in the Create Unit Tests dialog box.

For a list of known project type Guids, check out this site: http://www.mztools.com/articles/2008/mz2008017.aspx

The Magic of Doing One Thing at a Time

Full post here: http://blogs.hbr.org/schwartz/2012/03/the-magic-of-doing-one-thing-a.html

In the past, the focus has always been on doing more at the same time. Multitasking equals increased productivity, right? This article states the opposite, and I agree. I know from personal experience that trying to do 3, 4, 5, or more things at the same results in thrashing that absolutely destroys my productivity. So much time is spent switching between tasks that nothing is ultimately accomplished.

One of the methods that you can use to help keep focused is called The Pomodoro Technique. The idea here is simple: get yourself a 25 minute timer, pick a task, and work on that task uninterrupted for 25 minutes. After each interval, you get a short break to collect yourself and rest, and then you start again. After 4 intervals, take a longer break. Keep a list of your tasks on a blank piece of paper. When interruptions that need your attention occur, add them to your list but do not let them distract you. Getting behind on email? Make it a task! This is a great way to improve your time management. As a bonus, you get a documented log of all that you’ve accomplished in a day!

However you do it, try to focus on a single task at-hand, and I bet your productivity will skyrocket!

Ordered Tests with Rhino Mocks AAA Syntax

Before the AAA syntax was introduced, you would create ordered unit tests by wrapping Expect calls in a using block like so:

var mocks = new MockRepository();
using (mocks.Ordered())
{
    // ...
}

However, AAA syntax does not require you to instantiate a MockRepository, so how can we do ordered tests? This can be accomplished by accessing the implied MockRepository via the GetMockRepository method.

var myMock = MockRepository.GenerateMock<IMyInterface>();
using (myMock.GetMockRepository().Ordered())
{
    // ...
}

Here’s a complete example.

[TestMethod]
public void RunTest()
{
    // Arrange
    var target = new Program();
    var mockModel = MockRepository.GeneratePartialMock<MyModel>();
    target.Model = mockModel;

    using (mockModel.GetMockRepository().Ordered())
    {
        mockModel.Expect(x => x.Populate());
        mockModel.Expect(x => x.Save());
    }

    // Act
    target.Run();

    // Assert
    mockModel.VerifyAllExpectations();
}
// This fails
public void Run()
{
    Model.Save();
    Model.Populate();
}

// This passes
public void Run()
{
    Model.Populate();
    Model.Save();
}

The Almighty Console Application

When I was learning C++ in college, I couldn’t wait to start developing applications that were more than just a console app. It was the twenty-first century, and “real” applications had forms with stuff you could click with a mouse. Nobody wants an app that you can only interact with by typing. And no graphics? No thanks.

It’s funny how time can change you.

I still believe that, generally, people don’t want a console application. And if I’m writing an application intended to be used by others, I’m probably going to go with Windows Forms, ASP.net, or WPF. I do a significant amount of development that isn’t aimed at end users, though, and that’s where I’ve learned to appreciate the value of the console application.

Your first try will likely be your worst

The first time you try something new, it’s likely to be your worst attempt. So, if you’re experimenting with a new technology or implementing logic that you aren’t familiar with, why would you try in production code? Further, once you’ve got it implemented and functional in your production code, there’s a chance that some unnecessary figuring-it-out code will sneak into the product.

This is where the oft overlooked console application comes into play. For my money, the console app is the fastest way to an isolated, bare-bones sandbox for learning and optimizing a solution. A valid argument can be made that a Windows Forms application is just as fast(er), but you can waste time manipulating controls on a form that really don’t provide any value at the end of the day. Hard-code your input or prompt the user and use Console.ReadLine()–it’s as fast as declaring a variable, and your project doesn’t get any of the extra “fluff” that comes with forms and designers. (It’s also great for blogging since you don’t have to explain what each control is or provide screenshots!)

A personal library

You know how you did that one cool thing for some project a few years ago? Can you send me that code?

A great side-effect of doing your learning and experimenting outside of the application it’s ultimately targeted for is that you build a personal snippet and reference library. If you browse through my Visual Studio projects folder, you’ll see a LOT of folders: EncryptionConsole, ZipConsole, FtpConsole, TfsSdkConsole, SerializationConsole, etc. It’s easy to find a functional, self-contained code sample that you can share with others. Or, if you need to expand on a previous topic with a more advanced technique, you’ve got a foundation already built.