Macro Framework For .Net To Dynamically Populate String Content

As much fun and functionality there is in the ToString() and formatting, sometimes you just want to whole lot of freedom to safely populate a message template with any and all values that might come along.

I found this need when I was building a SOAP API test harness, then again in a Printer test harness when I needed a way to pass arbitrary values into command scripts without wanting to complicate the process with tons of arguments or mudding the scripts with code to parse strings to split arguments out.

This framework is pretty simple but works well and is very flexible when it comes to the source of the actual values.  It is broken out into a set of very small, specifically tasked classes and interfaces, the primary ones of which follow here:

The MacroUtilities, which consists of a single public ExpandMacros method to take a string, and a callback to a MacroEvaluator.  The ExpandMacros method uses a light regular expression Replace call to enumerate all of the “$(?)” patterns in the string, and then calls the MacroEvaluator callback for each one, then repeating the process recursively to expand any macros with those just expanded.  Really this is the actual brains of the process, as the return string from the regular expression is the final expanded result.

The MacroExpander (IMacroExpander) is an instance wrapper of the MacroUtilities methods, which maintains the reference to a single MacroEvaluator callback.  It?s just a nice wrapper.

The MacroEvaluator delegate is used to pass reference to a method call that takes a macro name, everything within the opening “$(” and closing “)”, as a string and returns the expanded result.

The IMacroLibrary interface is used to expose a means for any implementing object to provide access to properties or just about any value by a name.  See the ReflectionMacroLibrary for an included library that uses .Net Reflection to map macro names to public properties automatically.

The last key part of the framework is the MacroManager which links the MacroExpander instance with a macro library.  The MacroManager implements the IMacroExpander and IMacroLibrary interfaces.  It is an instance of this class that ties all the others together and is the one to keep a link to and use by the rest of your application.

IMacroLibrary macroLibrary = someMacroLibrary;
IMacroExpander macroManager = new MacroManager(macroLibrary);
expandedMacroString = macroManager.ExpandMacros(templateMacroString);

The reference to “someMacroLibrary” can be any object that implements the IMacroRepository interface.  There are a number of examples in the attached file that demonstrates different libraries, and I will go more into those later.

Macro libraries can be nested, which is a real strength, so you can have a default set of macro and then expand upon them to include static or dynamic content on the fly.

Download Source

Categories: .Net Framework Tags: ,