I am by no means an expert on Workflow. But after e-mailing back and forth with Jim Bears and Dave McCarter about a possible talk for the July meeting of the San Diego Developers Group, we concluded that not many people understand, use, or appreciate workflow. This could be due to bad experiences they have had in prior versions. Since the 4.0 version has addressed a lot of those shortcomings, we decided that it would be a great topic for discussion at a user group.

As per usual, I was too busy to prepare for the talk more than a day in advance. But I put together some slides, and formed a pretty good idea of the demo I wanted to do before I went in.

The first hour of the talk went pretty well. It was when I got into the unrehearsed part of the demo that things started to go awry. I had packaged up the first demo into a custom activity, and was trying to reuse that in a flowchart activity. Also I was switching from a WorkflowInvoker to running the workflow from a WorkflowApplication. At the same time I was adding persistence. I noted that I was still passing in the custom activity and not the workflow that contained the Flowchart, but I knew that something else was going on. I eventually found it (I was forgetting to call Run on the WorkflowApplication). Once I fixed that however, I forgot to go back and switch to the outer activity. That’s was the reason that nothing else was working.

This morning before I went to work, I fixed that problem, and corrected a couple of typos in the slides. Now that I am back home, I am going to finish the rest of the demo. That was always my plan, because I didn’t think that I would have time to do everything live.

I had already created one event – the completed event. But now that I allow the workflow to persist I want to capture another event – the PeristableIdle event

Here is an example of hooking that up:

app.PersistableIdle = e =>
{
	Console.WriteLine("Persisting...");
	_persistingEvent.Set();
	return PersistableIdleAction.Persist;
};

then I want to change my main from this:

WorkflowApplication app = CreateNewWorkflow();
app.Run();
_completedEvent.WaitOne();

to this:

WorkflowApplication app = CreateNewWorkflow();
app.Run();
_persistingEvent.WaitOne();
app.ResumeBookmark("readPrizeCode", Console.ReadLine());
_completedEvent.WaitOne();

Run it again, and everything works, but now what happens if I close the console application after receiving the prize code?
I need someway of loading the existing workflow, but I don’t have anything that I can load it by. As I mentioned last night there are a couple of ways to do this:
1) by using Promotable properties so that some of your properties are persisted along with the workflow.
2) Just tracking the mapping between your custom property and the instance ID from another table

I chose the second option, and added in the DataAccessLayer to do this already, but to take advantage of this feature I need to add the mapping record when it goes idle and take out the mapping when it completes. The final result looks something like this:

static readonly ManualResetEvent _completedEvent = new ManualResetEvent(false);
static readonly ManualResetEvent _persistingEvent = new ManualResetEvent(false);
static readonly ManualResetEvent _unloadedEvent = new ManualResetEvent(false);

static void Main(string[] args)
{
	string email = null;
	while (string.IsNullOrWhiteSpace(email))
	{
		Console.WriteLine("Enter your e-mail address:");
		email = Console.ReadLine();
	}

	bool done = false;
	while (!done)
	{
		WorkflowApplication app = CreateNewWorkflow(email);

		Guid instanceId;
		using (var session = new EfSession())
		{
			instanceId = session.Workflows.GetWorkflowInstance(email);
		}
		if (instanceId != Guid.Empty)
		{
			app.Load(instanceId);

			string prizeCode = null;
			while (string.IsNullOrWhiteSpace(prizeCode))
			{
				Console.WriteLine("Enter your prize code:");
				prizeCode = Console.ReadLine();
			}

			app.ResumeBookmark("readPrizeCode", prizeCode);
			_completedEvent.WaitOne();
			done = true;
		}
		else
		{
			app.Run();
			_unloadedEvent.WaitOne();
		}
	}
}

public static WorkflowApplication CreateNewWorkflow(string email)
{
	IDictionary<string, object> outputs = null;
	var app = new WorkflowApplication(
		new QuestionForPrize());
	app.Completed += e =>
	{
		outputs = e.Outputs;
		Console.WriteLine("Removing instance {0}...", app.Id);
		using (var session = new EfSession())
		{
			var instances =
				from wi in session.Workflows.All
				where wi.EmailAddress == email && wi.WorkflowInstanceId == app.Id
				select wi;
			var instance = instances.SingleOrDefault();
			if (instance != null)
			{
				session.Workflows.Delete(instance);
				session.Save();
			}
		}
		_completedEvent.Set();
	};
	app.PersistableIdle = e =>
	{
		Console.WriteLine("Persisting instance {0}...", app.Id);
		var wi = new WorkflowInstance
		{
			EmailAddress = email,
			WorkflowInstanceId = app.Id,
		};
		using (var session = new EfSession())
		{
			session.Workflows.Add(wi);
			session.Save();
		}
		_persistingEvent.Set();
		return PersistableIdleAction.Unload;
	};

	app.Unloaded = e =>
	{
		Console.WriteLine("Instance {0} has been unloaded", app.Id);
		_unloadedEvent.Set();
	};

	app.InstanceStore = GetInstanceStore();
	return app;
}

private static InstanceStore GetInstanceStore()
{
	var instanceStore = new SqlWorkflowInstanceStore(
		ConfigurationManager.ConnectionStrings["Workflow"].ConnectionString)
	{
		HostLockRenewalPeriod = TimeSpan.FromSeconds(1)
	};

	InstanceHandle handle = instanceStore.CreateInstanceHandle();
	InstanceView view = instanceStore.Execute(
		handle, new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30));
	handle.Free();
	instanceStore.DefaultInstanceOwner = view.InstanceOwner;
	return instanceStore;
}

Here are the slides and demos for the talk. Thanks everyone for coming!

I love the Reactive Framework, I will get to why in a minute. I even did a talk on it at the Guerrilla.NET class in May. That talk didn’t go so well because they keep changing the freakin’ API! Every single time I upgrade I have to fix things. This last class unfortunately I didn’t even realize that I was upgrading. I made the mistake of creating a project from scratch and using NuGet to pull down the latest version of Reactive. All of the Demo code that I was using broke in subtle ways that I couldn’t quite figure out live, so I had to pull out a project that I had built a week prior. I just now had the time to sift through the changes and make everything work again.

There are still two major ways to subscribe to UI events. The API used to be called FromEvent, now it is FromEventPattern, even though FromEvent still exists for some reason. The important part isn’t whether th API is called FromEvent or FromEventPattern. The distinguishing feature is whether you pass one generic type argument or two. If you just pass one you get access to use the old string method like this:

var mousemoves1 =
	from evt in Observable.FromEventPattern<MouseEventArgs>(rect, "MouseMove")
	select evt.EventArgs.GetPosition(LayoutRoot);

If you pass in two arguments (the first being the delegate type, and the second being the EventArgs type) you get to use the more confusing, but more flexible API. It makes sense after you think about it for a while. That one looks like this:

var mousemoves2 =
	from evt in Observable.FromEventPattern<MouseEventHandler, MouseEventArgs>(
		h => MouseMove += h, h => MouseMove -= h)
	select evt.EventArgs.GetPosition(LayoutRoot);

The reason you can’t simple pass MouseMove is because the add_ and remove_ methods for the event aren’t exposed directly.

Anyway, one of the best features of Reactive is the fact that you can transform a set of UI specific events that can only be handled by the UI to a set of events that can be handled by anyone, a ViewModel for instance.

var textChanged = Observable.FromEventPattern<TextChangedEventHandler, TextChangedEventArgs>(
				h => textBox.TextChanged += h,
				h => textBox.TextChanged -= h);
var stringsChanging = 
	from tc in textChanged
	select ((TextBox)tc.Sender).Text;

// Now that we have transformed these events we can pass 
// them safely into the ViewModel
// which will still know nothing of how they were generated
viewModel.SetupSubscription(stringsChanging);

The idea of transforming an passing around events is one of the main reasons why I still love Reactive even though they break me every month or so…

This week I was called on to do a very strange on-site custom course. They basically couldn’t decide on any one topic so they wanted me to talk a little bit about everything, mainly concentrating on:

  1. Advanced Windows Forms
  2. Windows Communication Foundation
  3. Unit Testing

As I have covered Windows Communication Foundation many times, and I didn’t have quite enough time to do unit testing any justice, the most interesting of the talks (I thought) was Windows Forms. We covered MDI, Notify Icons, and to my surprise had an interesting eventing discussion. Someone had asked about the difference between WPF and Windows Forms. I was trying to describe how they can be very similar but if you program WPF the right way how very different they really were and how complicated WPF was compared to Windows Forms. As part of this description I mentioned that Windows Forms has only the direct event model, but WPF has both bubbling and tunneling in addition to the direct model. Again someone raised their hand and asked if there was no way to simulate the bubbling model that they had in MFC (and WPF) using Windows Forms. He mentioned that they were having problems with coupling between components. I told them that the Client Application Block had something like this built in. He said that they found the CAB a little too heavy, and I agreed. I told him I would think more about it and get back to him tomorrow.

When I got back to the hotel that evening I started thinking about it and realized that there was a way to simulate it using a publish and subscribe type mechanism. This is basically a lightweight version of what the CAB clock does. I named my class the same as theirs as a form of flattery.

When you specify that you want to subscribe to a button click using the following syntax.

EventBroker.Instance.Subscribe(this, typeof(Button), "Click", OnButtonClick);

The EventBroker basically just walks the tree of controls recursively searching for controls of the type button, and then adds itself as a subscriber to that button. If someone else in the hierarchy also subscribes for button clicks the EventBroker knows which subscriber to call first. If the inner subscriber handles the event then the outer subscriber never sees the event, just like bubbling.

Best of all, you only need to drop in this one file, and away you go.
Here is the file in its entirety:

using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;

namespace WindowsFormsApp
{
	// helper method to make the code below more readable
	public static class ControlExtensions
	{
		public static bool IsParentOf(this Control c, Control other)
		{
			Control parent = other;
			while (parent != null)
			{
				if (c == parent)
					return true;
				parent = parent.Parent;
			}
			return false;
		}

	}

	public class EventBroker
	{
		class EventHolder
		{
			public Control Control { get; set; }
			public EventHandler<BubblingEventArgs> EventHandler { get; set; }
		}

		// singleton
		public static readonly EventBroker Instance = new EventBroker();

		readonly Dictionary<Control, List<EventHolder>> subscribers = new Dictionary<Control, List<EventHolder>>();

		public void Subscribe(Control c, Type type, string eventName, EventHandler<BubblingEventArgs> callback)
		{
			SubscribeRecursive(c, c, type, eventName, callback);
		}

		private void SubscribeRecursive(Control subscriber, Control c, Type type, string eventName, EventHandler<BubblingEventArgs> callback)
		{
			if (type.IsInstanceOfType(c))
			{
				// check to see if this eventName exists and subscribe
				Debug.WriteLine(string.Format("{0} is of type {1}", c.Name, type.Name));

				List<EventHolder> list;
				var newHolder = new EventHolder
				{
					Control = subscriber,
					EventHandler = callback,
				};

				// do we already have a subscriber for this object?
				if (subscribers.TryGetValue(c, out list))
				{
					// walk through the list trying to find where to insert this subscriber
					bool inserted = false;
					for (int cnt = 0; cnt < list.Count; cnt++)
					{
						EventHolder holder = list[cnt];

						// uses the extension method above
						if (holder.Control.IsParentOf(subscriber))
						{
							list.Insert(cnt, newHolder);
							inserted = true;
							break;
						}
					}
					// if they weren't inserted add them at the end
					if (!inserted)
					{
						list.Add(newHolder);
					}
				}
				else
				{
					// this is a new object, subscribe to its event
					EventInfo eventInfo = c.GetType().GetEvent(eventName);
					eventInfo.AddEventHandler(c, new EventHandler(OnEvent));

					// then create a new list of subscribers keyed to this object
					list = new List<EventHolder> {newHolder};
					subscribers.Add(c, list);
				}
			}

			// now recursively subscribe
			foreach (Control child in c.Controls)
			{
				SubscribeRecursive(subscriber, child, type, eventName, callback);
			}
		}

		public void OnEvent(object sender, EventArgs e)
		{
			// grab the list of subscribers for this control
			List<EventHolder> list = subscribers[(Control)sender];

			foreach (EventHolder holder in list)
			{
				Debug.WriteLine(string.Format("About to call {0}", holder.Control.Name));

				// call this subscriber
				var handledArgs = new BubblingEventArgs {InnerArgs = e};
				holder.EventHandler(sender, handledArgs);

				// if they handled the event don't propogate further
				if (handledArgs.Handled)
					break;
			}
		}
	}
}

I was working with a client that wanted to be able to layout the screen using some pretty complicated but fixed layouts. All of these needed to be able to be adjusted by the client after they were shown, so they needed to use splitters. To help them to be able to produce these layouts easily I created a control. It allows them to simply set the number of reports and the layout type, and assign the reports to the various panels. To demonstrate what the result looks like and show how to programmatically use the control I created a little test project. Here is a screen shot of the result.

Unfortunately it looks a little bit like an eye chart ;) . However, the cool thing is that all of the splitters shown in the screen capture actually work. In fact if you look I adjusted some on the second row. There is another test that I did where it cycles through all the splitters one at a time. The project is included here.

That’s it. The third time you get asked about a particular topic, its time to stop making it up as you go along, and actually write something down. I was asked (again) today by another one of my clients about Validation within Windows Forms. So I am going to take some time to write up my thoughts

First let me say that there are several parts to validation. There is simple user input or "control" validation, displaying of the results of a failed validation, and then the complex business rule or "form" validation. Lets deal with each in turn

Simple user input validation

As you probably know each control in a form contains a Validating and a Validated event. In order to get those events to fire the CausesValidation property on the control needs to be true, but since that is the default, no problems there. Most people start off by using Validating to implement some simple validation rules like making sure that the input is in the proper form. ASP.NET provides the following forms of validation:

  • RequiredFieldValidator – Make some input has been chosen for the control
  • RangeValidator – Make sure the input is within a specific range
  • RegularExpressionValidator – Make sure the input looks like a regular expression
  • CompareValidator – Make sure that the input in one control "matches" the input in another
  • CustomValidator – Check the input as you see fit

Windows Forms does not provide those controls out of the box. However, there are solutions, as we will see shortly.

There are two basic approaches to validating many controls on a Form. The first is the ASP.NET approach where one or more validators are dragged onto the form for *each* control that needs validation. The second is to use an IExtenderProvider (tooltips and errorProviders are examples of ExtenderProviders). The idea behind a ExtenderProvider is that you drag one component onto the form, and it extends the properties for every control on that form.

Michael Weinhardt wrote an article providing the ASP.NET way. The model was described in a 3 part article as well as the accompanying source code. In the article just look at the first part as 2 and 3 have been obsoleted by newer versions of .NET (2.0).

Billy Hollis wrote an article providing the second way which has since been removed from MSDN. However the WebCast is still around, and the source code can still be downloaded.

The choice between the two models essentially comes down to the percentage of controls needing validation on a given page. If the percentage is large, go with Billy Hollis’ model, if the percentage is small go with Michael Weinhardt’s model. Another reason for going with Weinhardt is if you are building both Forms and ASP.NET applications in order to stay consistent. BTW – I prefer Billy Hollis’s model. His code is in VB.NET, but I ported it to C#.

Displaying errors

Most everyone agrees that the ErrorProvider is the right way to signal errors in Windows Forms. However some people feel that novice users won’t be able to tell what the error actually is. If your application is meant to be used by novices there are two approaches.
a) build a little framework that dynamically creates an error label with each control that is being checked
b) provide a ValidationSummary control ala ASP.NET that contains all of the errors
I prefer the second option here. Note the Weinhardt’s article mentioned above provides a Validation form which pops up a modal dialog containing the error information, which is another way to go. I dislike modal popups, but I recognize that as largely a matter of taste.

Form and complex business rule validation

Examples of this are the CompareValidator that I mentioned earlier. But here is where the Validating event can really shine. Typically you hook this event and the call into some business logic which tests sums of values, or certain strings when an enum has been chosen above, things like that. The same Validation summary can then be used to display the results of such validation.

Happy Validating!

I love Reflector, but sometimes I want to be able to explore through the Framework in more interesting ways. In this post I am going to use the program that I created last time to do some exploring.

How many types are there in the 2.0 version of the framework? Just click Go:
15834 – Wow! [Update: After 3.5 SP1 - 16375]

How many instances of the Async pattern are there in the .NET Framework? There are a bunch of ways to do this one. One way was shown in the picture last time.
Select Method, type ^Begin, press Add, select ParameterType, type AsyncCallback, press And, and click Go
831 [Update: 857]  The Name textbox uses regular expressions so the caret (^) before the word Begin just means that it should only match methods that start with Begin, rather than anywhere in the name (which is the default).

Looking through those it seems that lots of those are the possibly CPU bound delegate BeginInvoke pattern. Let’s filter out the delegates Leaving the expression the way it was last time add:
Select Inherits, type Delegate, check Not (checkbox), press And, and click Go:
233 [Update: 247]
So I guess that means there are about 600 delegates? I will double check that in one second.

First it looks like a lot of the instances of the async pattern that are left inherit from Stream, lets filter those out as well. Again leaving the expression the way it is:
Select Inherits, type Stream, check Not (checkbox), press And, and click Go:
68 [Update: 76] and one of those is Stream itself. Go ahead and have a look – the ones left have a lot of diversity: SqlCommand, LdapConnection, Dns lookup, WebRequest, HttpListener, tons of Socket stuff, MSMQ, .NET Remoting, System.Transactions, and HttpAsyncHandler. All provided for you free of charge in the .NET framework itself.

Now lets go back to those delegates:
Press Clear, select Inherits, type Delegate, and click Go:
595 [Update: 607] – close enough that I believe it :)

Another question that I wanted answered was what are the generic delegates? Leaving the expression the way it is:
Select Type, type `(backtick), and click Go. The backtick is the way that generic types are represented in the IL. Here we see a really small list, but all of them are extremely useful: Action ,Predicate, Comparison, Converter, etc.

UsingReflectForEntities

I played around a little more and found lots of other oddities. For example: I was searching for Trees and I found an RBTree in the System.Data assembly – WTF? I have attached the finished project – happy hunting!

Now that I teach the Essential .NET class for DevelopMentor, I find myself scouring the MSDN reference documentation looking for specific types. After doing this for an hour or so, I got to thinking – there has to be a better way. So I started out with a fairly simple application which used reflection and a simple string.Contains to browse for certain classes in the framework. Because of the naming convention of ending the class name with the name of the class you are inheriting from this worked quite nicely.

The form looked like this:

ReflectForEntities1

However, I soon needed more features like:

  • looking for certain methods
  • being able to delete items from the tree manually, when I found they didn’t apply
  • displaying the count of elements found at any location

So I kept adding functionality.

Then I needed the ability to combine multiple filters at one time, like looking for Asynchronous Programming Model (APM) methods. This is where things got interesting. To do this I created a set of filters. A filter is really just class that stores some information and contains boolean function that acts upon a type to figure out if it should be included in the result set. I created in interface for this purpose which looked like this:

interface IFilter
{
	bool IsTypeAllowed(Type t);
}

The implementation of this interface is pretty easy. Basically checking each the name of each type against a set of regular expressions

public bool IsTypeAllowed(Type t)
{
	if ((Type & TypeSearchType.Namespace) != 0)
	{
		if (t.Namespace == null) return false;
		if (!Regex.Match(t.Namespace).Success)
			return false;
	}
	if ((Type & TypeSearchType.Type) != 0)
	{
		if (!Regex.Match(t.Name).Success)
			return false;
	}
	if ((Type & TypeSearchType.Member) != 0)
	{
		found = false;
		foreach (MemberInfo mi in t.GetMembers())
		{
			if (Regex.Match(mi.Name).Success)
				found = true;
		}
		if (!found) return false;
	}
	return true;
}

This too worked really well until I needed to filter out methods. I needed a way of returning a subset of the methods on the type which met the filter criteria. To accomplish this I had to hackmodify the interface to look like this:

interface IFilter
{
	bool IsTypeAllowed(Type t, out List<MemberInfo> mis);
}

Then I had to modify the behavior to look like this (I added inheritance checking and parameter type checking while I was in there poking around)

public bool IsTypeAllowed(Type t, out List<MemberInfo> mis)
{
	mis = null;
	if (filterNullNamespaces && t.Namespace == null) return false;

	if ((Type & TypeSearchType.Inherits) != 0)
	{
		if (!IsBaseTypeAllowed(t))
			return false;
	}
	if ((Type & TypeSearchType.Namespace) != 0)
	{
		if (!Regex.Match(t.Namespace).Success)
			return false;
	}
	if ((Type & TypeSearchType.Type) != 0)
	{
		if (!Regex.Match(t.Name).Success)
			return false;
	}
	if ((Type & TypeSearchType.Member) != 0)
	{
		if (!IsMemberAllowed(t, out mis))
			return false;
	}
	return true;
}

bool IsBaseTypeAllowed(Type t)
{
	bool foundType = false;
	while (t.BaseType != null)
	{
		t = t.BaseType;
		if (Regex.Match(t.Name).Success)
		{
			foundType = true;
			break;
		}
	}
	return foundType;
}

bool IsMemberAllowed(Type t, out List<MemberInfo> mis)
{
	mis = null;
	bool foundType = false;
	foreach (MemberInfo mi in t.GetMembers())
	{
		bool foundMethod = false;
		if (((mi.MemberType & (MemberTypes.Constructor | MemberTypes.Method)) != 0) &&
			(Type == TypeSearchType.ParameterType))
		{
			MethodBase mb = (MethodBase)mi;
			foreach (ParameterInfo pi in mb.GetParameters())
			{
				if (Regex.Match(pi.ParameterType.Name).Success)
				{
					foundMethod = true;
					break;
				}
			}
		}
		else
		{
			foundMethod = Regex.Match(mi.Name).Success;
		}

		if (foundMethod)
		{
			if (mis == null)
				mis = new List<MemberInfo>();
			mis.Add(mi);
			foundMethod = false;
			foundType = true;
		}
	}
	return foundType;
}

Then on to the boolean logic piece. There are essentially 3 binary operators (that I cared about): NOT, AND, and OR. NOT is a unary operator, whereas both AND and OR are binary. I chose to create three new classes that contain the simple Filter that I had created earlier. The benefit of containing rather than inheriting/overriding is that I was able to encapsulate all of the logic in one and only one place.

The other problem was that regardless of how complicated the final expression was I wanted to be able to perform a NOT on it to produce the sets complement. To do that I had to Add another method on the interface so that all filter types could produce a NOT. The result of all that refactoring looked like this:

	class NotFilter : IFilter
	{
		IFilter subFilter;

		public NotFilter(IFilter subFilter)
		{
			this.subFilter = subFilter;
		}

		public IFilter CreateNot()
		{
			return subFilter;
		}

		public bool IsTypeAllowed(Type t, out List<MemberInfo> mis)
		{
			mis = null;
			List<MemberInfo> subMis;
			bool subAllowed = subFilter.IsTypeAllowed(t, out subMis);
			if (subMis != null)
			{
				mis = new List<MemberInfo>();
				foreach (MemberInfo mi in t.GetMembers())
				{
					if (!subMis.Contains(mi))
						mis.Add(mi);
				}
			}
			return !subAllowed;
		}

		public override string ToString()
		{
			return "!" + subFilter.ToString();
		}
	}

	class AndFilter : IFilter
	{
		IFilter sub1;
		IFilter sub2;
		public AndFilter(IFilter sub1, IFilter sub2)
		{
			this.sub1 = sub1;
			this.sub2 = sub2;
		}

		public IFilter CreateNot()
		{
			return new OrFilter(sub1.CreateNot(), sub2.CreateNot());
		}

		public bool IsTypeAllowed(Type t, out List<MemberInfo> mis)
		{
			mis = null;
			List<MemberInfo> mis1;
			List<MemberInfo> mis2 = null;
			bool allowed =
				sub1.IsTypeAllowed(t, out mis1) &&
				sub2.IsTypeAllowed(t, out mis2);
			if (allowed)
			{
				if (mis1 != null)
					mis = mis1;
				if ((mis == null) && (mis2 != null))
					mis = mis2;

				if ((mis1 != null) && (mis2 != null))
				{
					mis = new List<MemberInfo>();
					foreach (MemberInfo mi in mis2)
					{
						if (mis1.Contains(mi))
							mis.Add(mi);
					}
				}
			}
			return allowed;
		}
		public override string ToString()
		{
			return string.Format("({0}) && ({1})", sub1.ToString(), sub2.ToString());
		}
	}

	class OrFilter : IFilter
	{
		IFilter sub1;
		IFilter sub2;
		public OrFilter(IFilter sub1, IFilter sub2)
		{
			this.sub1 = sub1;
			this.sub2 = sub2;
		}

		public IFilter CreateNot()
		{
			return new AndFilter(sub1.CreateNot(), sub2.CreateNot());
		}

		public bool IsTypeAllowed(Type t, out List<MemberInfo> mis)
		{
			mis = null;
			List<MemberInfo> mis1 = null;
			List<MemberInfo> mis2 = null;
			bool allowed1 = sub1.IsTypeAllowed(t, out mis1);
			bool allowed2 = sub2.IsTypeAllowed(t, out mis2);
			bool allowed = allowed1 || allowed2;
			if (allowed)
			{
				if (mis1 != null)
					mis = mis1;
				if ((mis == null) && (mis2 != null))
					mis = mis2;

				if ((mis1 != null) && (mis2 != null))
				{
					foreach (MemberInfo mi in mis2)
					{
						if (!mis.Contains(mi))
							mis.Add(mi);
					}
				}
			}
			return allowed;
		}
		public override string ToString()
		{
			return string.Format("({0}) || ({1})", sub1.ToString(), sub2.ToString());
		}
	}

I also had to refactor the UI a little bit. The form now looks like this:

ReflectForEntities2

Notice that I got a little bit carried away and placed a Flags button on the UI (initially disabled).

There was one caveat. If you were to give me any random boolean expression, I wouldn’t necessarily be able to express it in the program. Expressed in tree form, my program could only produce expressions that looked like:

ExpressionTree1

However, the program was working great; I had no major flaws in the design (that I could see), and I was able to perform some pretty nifty expressions which I will discuss in another blog entry.