Simple Expression Evaluator project now on CodePlex

August 28, 2008

I have uploaded a new project, Simple Expression Evaluator, to Codeplex. I haven’t had time to create any documentation imageyet, but as usual the project contains unit tests and a sample application to play with. Simple Expression Evaluator abstracts the the parser+compiler from the object model, allowing any kind of parser to be used to construct expressions. Simple Expression Evaluator works by converting an Abstract Syntax Tree into an Expression Tree and evaluating the expression tree. A discussion of dynamic expression evaluation and links to resources can be found here. It is very simple to add new language elements, operators or functions, and comes with an array of options for plugging in custom variable evaluators or function evaluators by either implementing an interface or by associating events with delegates. 

Simple Expression Evaluator’s default parser and expression language use the Irony.net Compiler toolkit. The expression language itself is a modified, stripped down version of Script.NET (S#) and supports things like array indexers and aggregate functions such as Sum, Avg, etc that can be used on collections. Here is a screen shot of the sample app:

.NET Utility Libraries Galore

July 15, 2008

Yesterday Karl Seguin announced a new .NET Extension Library. One of the really interesting pieces of the library is a streamlined approach to a simple dictionary imagecache, which is similar to the one described in another interesting looking utility library called ShadeTree. Recently, Ayende Rahein reviewed another .NET utility library called Umbrella, which looks like a pretty wide and deep set of utilities. As I am about to create a new solution to consolidate the utility functionality we use across our various projects, it got me thinking it might be time to pick an established (or growing) library from the community and try to contribute any missing pieces we need for our own projects.

I figured that the three utility libraries mentioned above probably weren’t the only ones – it’s something anyone that works on more than one project is likely to at least think about creating, and something that is easy to contribute to open source, because utility libraries like these are generic by their nature. Here is what I found on Codeplex (none of these are dead – they all have relatively recent check-ins, and decent download traffic):

http://www.codeplex.com/Utilities
http://www.codeplex.com/publicdomain
http://www.codeplex.com/nice <- primarily graphics and math
http://www.codeplex.com/DotnetCommons
http://www.codeplex.com/dotNetTipsUtility
http://www.codeplex.com/toolbox
http://www.codeplex.com/nucleo

And the two already mentioned:

http://www.codeplex.com/umbrella
http://www.codeplex.com/nxl

And the Shade Tree project:

http://storyteller.tigris.org/source/browse/storyteller/trunk/src/ShadeTree.Core/?rev=177#dirlist

 

[Update/Correction] Apparently Rhino Commons is far more than a collection of utilities. To be honest, I haven’t looked too closely at it yet, and had a misconception about what it was. Time to repair my ignorance, I suppose.
http://ayende.com/wiki/Rhino+Commons.ashx
If you’re interested in learning a bit about Rhino Commons, and you don’t mind learning about it in the context of ASP.NET MVC, or alternatively you just want to visit a site called “frickinsweet.com”, check out this series of posts by Ryan Lanciaux: (I’m linking to part one – there are currently 5 parts)
http://frickinsweet.com/ryanlanciaux.com/post/RhinoCommons2c-NHibernate-and-ASPNET-MVC.aspx

Here’s a “utility” library with some light similarity (but much smaller scope) to Rhino Commons (in that it contains Repository and Unit Of Work implementations for NHibernate), and there is some WCF bag-o-trick stuff here as well:
http://davybrion.com/blog/stuff/

 

And for good measure, here is a round up of the extension method collections I’ve seen lately:

http://weblogs.asp.net/okloeten/archive/2008/06/19/6296904.aspx
http://weblogs.asp.net/okloeten/archive/2008/08/01/6463327.aspx
http://www.iridescence.no/Posts/A-Set-of-Useful-Extension-Methods-for-DateTime.aspx
http://james.newtonking.com/archive/2008/03/27/formatwith-string-format-extension-method.aspx
http://www.hanselman.com/blog/ASmarterOrPureEvilToStringWithExtensionMethods.aspx
http://elegantcode.com/2007/12/05/firing-events-with-extension-methods/

Here is a new library of extension methods for .NET 3.5, and a blog post describing the project

http://codeplex.com/dotNetExt

Update: Vijay Santhanam mentioned a website in the comments, http://www.extensionmethod.net/, that is pretty much exactly what I had in mind when I wrote the below paragraphs. It would be cool if it could be used beyond extension methods, for other sorts of utility classes & tools (maybe it can), but still, very cool website.

 

Wow…That’s a Lot

I’m not likely to have time to evaluate them all in order to choose one, but it got me thinking about utility libraries in general and if it makes sense to “choose one” at all. Utility Libraries (that is, all purpose, non-specialized ones, like the giant Swiss army knife above) are kind of personal. They aren’t like other libraries, where you have something you need done, and they do it well. They are all the million odd places you put a dab of oil onto the framework you’re using because it sticks or creaks, and one thing is certain, no matter how complete your utility library, you’ll need that one more helper class here and extension method there, and at a moments notice, and you’ll need somewhere to put them. Maybe a utility library is less like a giant Swiss army knife and more like a fisherman’s hat or a tackle box, everyone has one, they contain a lot of the same things, but every team has their own, highly personal selection that makes sense to their particular style and scope of work. image

Another problem with finding “the” utilit
y library to use is that, while I’m sure there is heavy overlap among the various options, while perusing each I’m certain to  find a few utilities done very well in one library, and others done very well in another, and yet I don’t want to reference half a dozen utility dll’s in my project.  For instance, the caching mechanism in the new .NET Extension Library looks awfully handy, but the Umbrella project contains a number of great things I think I would use on a daily basis as well. As I look through the others, I’m quite certain I’ll continue to have that experience.

That makes me more likely to cut and paste code out of the various offerings into my own utility library more likely than with any other kind of open source project I can think of, in the same way perhaps as a fisherman prepares his tackle box.

Well, I don’t have a good solution to this, but I wonder if the utility library concept doesn’t really work as an open source project you choose and use as your main utility provider, unless perhaps everyone can agree on one, and the barrier to getting contributions accepted is very low. Another approach might be a Wiki approach (Karl Seguin’s own Code Wiki comes to mind, or a version of it anyway) where anyone can contribute source code and tests for their utilities very easily, and people can comment on or discuss them, download them or cut and paste them. The whole thing could probably be available as a solution, but it would also be easy to pull out pieces via copy and paste or maybe single file download that match your type of projects and your style of working, and it would be A-OK to have lots of utilities even for edge cases and niche’s, because the thing wouldn’t need to be monolithic. And it would be searchable, tag-able, browse-able, etc.

Anyway, that isn’t likely to happen any time soon, even if it’s feasible, which it might not be. In the mean time, I imagine it is cut and paste for me :)

[Update: http://www.extensionmethod.net/ looks like it might be the kind of thing I'm talking about]

Linxter Offers Durable Messaging for Remote Clients

July 10, 2008

A discussion on the nServiceBus discussion list has been taking place recently regarding how to have durable messaging on remote nodes, such as smart clients, where the deployment and maintenance requirements of MSMQ aren’t tenable. The main concept being tossed around was a local database to hold un-sent messages at the remote endpoint that could be attached to any transport, making any non-durable transport durable. Ayende went off to build a prototype (but hasn’t reported back, so I’m not sure if it is still in progress, although there were strange noises coming out of his blog recently that suggest he might still be working on it) and it was mentioned that Evan Hoff was building such a thing using Berkeley DB.

One advantage of both of those options is that durability could be bolted on to any transport, such as HTTP or one of the non-durable WCF bindings, without much fuss. However there is at least one commercial service that I’ve talked about before, Linxter, that provides an internet-oriented message transport (or Internet Service Bus, ISB) with lots of cool features. What I didn’t realize, until today, was that the Linxter client API does exactly what was discussed at the NSB forum – provides a local cache for messages via an embedded DB (SQLite in this case), essentially enabling an x-copy deployable, durable, asynchronous messaging endpoint.

Of course, it doesn’t have the flexibility to attach “durability” to any conceivable transport – because Linxter is it’s own transport – but in most cases I don’t think that should be a big issue. The only question now, is, how much will it cost? Apparently pricing will be announced with Beta 3, which is scheduled for July 31st. Version 1.0 is scheduled for August 15th.

Here is the e-mail I received from Lixter’s Jason Milgram explaining the local queue:

Yes, the Linxter API queues messages locally (does this in Beta2), and does not take them off the queue until they are delivered. In Beta 3, we will offer additional reliability and efficiency for file transfers by enabling chunking. For example, let’s say you are transferring a 100MB file, and after transmitting 70MBs you lose your connection,…when the connection is re-established, it picks up from where it left off. We felt that these queuing and chunking features were pretty important especially with wireless connectivity becoming the norm.
The ISB is a distributed system, with failover built into the SDK (API)  as well as on the ISB. If the API cannot connect to a service on a particular set of clustered servers, it will failover to another set of servers. We can also dynamically reprovision server and service assignments for programs.

And here is the updated roadmap [emphasis mine]:

Release dates:

  • July 31st        Beta 3
  • Aug. 15th        Version 1.0

Beta 3 Overview:

  • Linxter SDK for both .NET and Java
  • Reorganization of methods for on demand and scheduled sending
  • Enhancements to Web Manager user interface
  • Web Manager support for both IE and Firefox
  • Standardization of API local datastore to SQLite
  • Availability of Quick Starts – feature based sample apps

On our website we have added the following:

Evaluating Expressions at Runtime in .NET (C#)

July 8, 2008

Evaluating dynamic, ad hoc or user provided expressions at runtime, usually in the context of an application’s current state, has been a valuable tool in the programmers tool-belt since the days when Cro-Magnon man was beating the brains out of Saber-toothed tigers to feed his hungry, hairy family.

In an interpreted language, like JavaScript, this is no problem, there is almost always some kind of Eval(string) command that will allow you to pass in and execute some arbitrary piece of code, such as an expression, as capriciously as you like.

With compiled languages, though, by the time your program actually executes, the compiler has completed its work and gone home to have a glass of Wild Turkey and watch football. If you want to evaluate some arbitrary expression (like this one that you might use in a reporting tool)

if (Amount < 0) then 'Red' else 'Black'

You either need to call the compiler back into the office or roll up your sleeves and do the job yourself. Some people would call this a DSL, or Domain Specific Language, at this point, although personally I feel like calling a simple expression language a DSL, especially if it doesn’t have any elements that relate to your specific domain but just operate on the objects you have in memory, whatever they are, is a bit of a stretch. But that’s an abstract distinction, DSL or not, the options are the same.

Compile Code on the Fly

In .NET you can use the System.CodeDom.Compiler classes to compile some arbitrary piece of source code into an in-memory class inside an in-memory assembly, and then execute the code. This is the approach you would take if you were going to use Boo (or some expression language based on Boo), but really there is a lot of baggage that comes with that approach that I think makes it inappropriate for most scenarios where you want to evaluate ad hoc expressions. Namely, if you are dealing with a large number of potential expressions that aren’t mostly known at the start of your application, you will be creating lots of dynamic assemblies, which isn’t blazing fast (although executing the expressions will be), and keeping them around in memory. If you allow end users or developers to modify expressions at runtime, the old assembly holding the previous version of the expression can’t be unloaded from memory, and you generally have a mess. However, there is a huge design-time upside to this approach, which is that you don’t have to define an expression language yourself, you can re-use the expression syntax of the language you are using, and you don’t have to think much about parsing or compiling anything. But the runtime story in many scenario often makes the approach untenable.

Reflection Emit – the lightweight, high performance approach

If you’re very clever, there is a middle way in .NET, which is to use black magic and Reflection.Emit to generate methods straight to IL (basically a custom parser/compiler just for expressions), which bypasses most of the ugliness of the previous approach. Expressions are still compiled and use early binding (not reflection) to evaluate your expressions. I think in many, many scenarios this is a great option. Plus, you don’t need to collect all the frogs tongues and newts eyes to whip up this voodoo yourself, some kind, intelligent soul has done this for us.

The Old-Fashioned Way

If you want complete control of your expression language, though, perhaps to make it more end user friendly than C#, or you need late bound semantics when evaluating your expressions, or you just like to take things apart and get dirty, there’s always the old fashioned way. The old fashioned way is a three part approach, both a bit tedious, but not particularly difficult, especially with modern tools.

1. Define the syntax and grammar of your expression language

2. Parse your expression into an Abstract Syntax Tree (AST) based on your grammar

3. Compile your expression into an object model (or, alternatively, directly interpret from the AST)

Step one involves taking a string like “(10 – 2) + x ^ y” and splitting it up into something a computer can make use of. AST’s are all the rage now-a-days along with DSL’s, so won’t go into too much detail here, ask Google all about them. The point is, the string needs to be parsed. This task itself can be accomplished in one of three ways:

A. Hand roll parsing logic, possibly using Regular Expressions. Yuck. Error prone and tedious.

B. Use a modern parser-generator, like ANTLR, to define the grammar of your expression language in a clean, easily understood manner and let the tool code generate the classes required to parse expression strings according to your grammar. This is a straightforward, robust approach that offers the most flexibility. However, it also requires a few steps to create a grammar, generate a parser, test, modify, repeat. It isn’t without some tedium.

C. Use a parser that doesn’t use code generation, but allows your grammar to be directly defined in your target language and fed directly to a parser for parsing your strings. The only example of this I am aware of is a very cool tool on CodePlex called Irony. There may be others like it, but this is the only one I’m aware of personally, and it is quite nice.

(D. Of course, you could use an existing expression evaluator library – there are several – one of them is certain to suit your needs – I list the ones I’ve found below)

Once your expressions are parsed into a nice Abstract Syntax Tree, you need to do something with that tree. You can interpret the tree directly, or you can “compile” the AST into an object model that can be used to quickly evaluate the expression in many different contexts, with many different values for variables, etc. This is it’s own exercise in tedium, but once done can be relatively easily enhanced and modified as your expression language evolves.

[UPDATE:] A CodeProject article just popped up with another Parser Generator for .NET that looks pretty cool. This is a stand alone tool that takes your grammar and generates a parser <GASP!> No…really? Um…like all other parser generators in the world? Yes, BUT, it generates the parser completely, i.e. it does NOT generate some source code that derives from or must be consumed by the parent library (like most other parser generators). This means that the parser this tool generates is entirely standalone, it adds no dependencies to your project, and if you feel like it you could tweak it or study it or do whatever you like, it’s all there. I haven’t evaluated this one yet, but I definitely will in the near future. Here is a blurb from the intro to the CodeProject article:

“TinyGP stands for “Tiny Parser Generator”. This particular generator is an LL(1) recursive descent parser generator. This means that instead of generating a state machine out of a grammar like most compiler compilers, instead it will generate source code directly; basically generating a method for each non-terminal in the grammar. Terminals are expressed using .Net’s powerful regular expressions. To help the programmer create .Net regular expressions a Regex tool is embedded in TinyPG. Grammars can be written using the extended BNF notation. TinyGP will generate a scanner, parser and parsetree file in c# code from this which can be compiled directly into your own projects.”

[UPDATE 2] Using the recipe above, and Irony.net, I have posted a reference implementation an object-model based expression evaluator on Codeplex and called it Simple Expression Evaluator. Check it out. I used Irony.net as the default compiler, but structured the project so that by implementing a simple interface you could easily plug in any parser you like.

And that’s it, then you’re done. For those too busy or not geeky enough to want to build your own expression evaluating machines, I’ll list the libraries I have identified that looked good enough (to me) to use in a professional project.

Resources

1. Flee – Fast Lightweight Expression Evaluator – uses IL generation to produce a high performance expression evaluator based on C#.

2. LazyParser.NET – a late bound expression evaluator that does the whole bit manually. Uses reflection to resolve context variables, so it is slower than flee, but has the advantage of being late bound and so a little more flexible in certain circumstances.

3. The Spring.NET framework has a pretty intense expression evaluator library as well

4. Script.NET – A fully featured, interpreted scripting language based on C# and using Irony.NET. It can do a lot more than evaluate expressions, but it can evaluate expressions, too.

5. CodeProject article on using the ANTLR + Grammar approach to rolling your own expression evaluator. Article has a pretty professional library included in the code download.

6. Irony.NET compiler construction kit on Code Plex – a code gen-less parser tool. Create your grammars directly in C#.

7. A blog post on how Irony works

8. CodeProject article on getting started with Irony.NET

9. CodeProject article on writing a DSL using Irony.NET

10. Several approaches to evaluating expressions, ignoring the parsing aspect. Basically, various ways you could transform your AST into an object model.

11. TinyParser Generator is a utility that will generate the source code for a complete compiler from your grammar, without any intermediate libraries needed to be referenced by your code.

12. Simple Expression Evaluator – Irony.NET based Expression Evaluator


More Extension Methods…

July 1, 2008

Here’s another selection of nice extension methods.

Create Bullet Graphs with Google Charts in 7 Easy Steps

June 5, 2008

I haven’t paid much attention to Google Charts so far, but I have enjoyed Stephen Few’s “Bullet Graphs.” A bullet graph is an extremely condensed sort of bar chart that shows the current value of a KPI, and various ranges such as unacceptable, acceptable and target, and an optional indicator line that can mean several things. Anyway, here is an example of a bullet chart (from wikipedia):

 

Bullet graph labeled.png

 

This blog post referenced below was referenced in Stephen Few’s blog this morning and describes the several easy steps required to create a bullet graph using the Google API. Being able to easily throw these things up, ad hoc, in any web page is pretty phenomenal, if you ask me. The image below is actually a Google Graph:

 

Here is the link to the guide:

DEALER DIAGNOSTICS » Blog Archive » Create Bullet Graphs with Google Charts in 7 Easy Steps

SimpleStateMachine CodePlex Project

May 30, 2008

I have posted a CodePlex project here that implements a simple, customizable State Machine & miniature runtime. The point of this project was to replace Windows Workflow Foundation in one of our applications as the state machine engine. Windows Workflow foundation is a powerful, robust technology but turns out to be unsupportable overkill if all you are really after is defining and coordinating state transitions in your application. Plus, it can be rather difficult to unit test, even more difficult to version and extend once an application is deployed, and requires all sorts of baggage in the form of database infrastructure and GAC requirements, etc.

Anyway, this library does nothing else besides let you define a set of events, states, and transitions between states when triggered by events, and optionally allows for user defined actions to fire during the initialization or finalization of any or all states.

As for representing the actual state machines there are a few options: A visual designer such as WF provides. The WF designer itself is awful for representing state machines, even simple ones, as it was designed to suit sequential workflows as well and the two kinds of diagrams have different needs. It might be possible to create a visual designer that did the job well, but it would be a big task. Another option is to configure state machines in code using an object model or fluent interface. This would have worked, but it ends up looking pretty ugly after a while and you can’t change your state machines without deploying updated assemblies.

The approach I settled on was to use a DSL, using Boo and Rhino DSL, as described by Ayende Rahien in his (unfinished) book on the subject. The State Machine language itself was inspired by Martin Fowler, who appears also to be writing a book about DSL’s.

An example state machine definition looks like the sample below. It isn’t as snazzy and colorful as the visual designer version you get with WF, but in practice it is much more practical.

workflow "Telephone Call"

trigger @CallDialed
trigger @HungUp
trigger @CallConnected
trigger @LeftMessage
trigger @PlacedOnHold
trigger @TakenOffHold
trigger @PhoneHurledAgainstWall

state @OffHook:
	when @CallDialed             >> @Ringing

state @Ringing:
	when @HungUp                 >> @OffHook
	when @CallConnected          >> @Connected

state @Connected:
	when @LeftMessage            >> @OffHook
	when @HungUp                 >> @OffHook
	when @PlacedOnHold           >> @OnHold

state @OnHold:
	when @TakenOffHold           >> @Connected
	when @HungUp                 >> @OffHook
	when @PhoneHurledAgainstWall >> @PhoneDestroyed

state @PhoneDestroyed

ASP.NET without ASP.NET – SharpTemplate.NET pre-release on CodePlex

May 26, 2008

This looks like a fantastic, flexible, simple to use template engine for .NET. I can’t imagine not finding a use for this in the near future. I haven’t dug any deeper, but LazyParser.NET may have significant promise as well.

 

ASP.NET without ASP.NET – SharpTemplate.NET pre-release on CodePlex

Microsoft VM Offline Servicing Tool

May 9, 2008

As working with VM’s becomes more important in more scenarios, tools like this could make a big difference.

Microsoft opens Offline Virtual Machine Servicing Tool beta

SSMS Tools Pack

May 8, 2008

Here is are some extensions to SQL Server Management studio that look like they might be pretty useful. For some reason the “Run one script on multiple databases” feature catches my eye…

Get the software here: SSMS Tools Pack

 

From the website:

 

SSMS Tools PACK is an Add-In (Add-On) for Microsoft SQL Server Management Studio and Microsoft SQL Server Management Studio Express.
It contains a few upgrades to the IDE that I thought were missing from the Management Studio: