All pastes #1810422 Raw Edit

Untitled

public text v1 · immutable
#1810422 ·published 2010-02-25 17:37 UTC
rendered paste body
// Based on: http://www.11011.net/wpf-binding-expressions

using System;
using System.CodeDom.Compiler;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Windows.Data;

using Microsoft.JScript;

namespace WPFPagingWithTabControlProofOfConcept
{
	public sealed class JScriptConverter : IMultiValueConverter, IValueConverter
	{
		private delegate object Evaluator(string code, object value, object[] values);
		private static Evaluator evaluator;

		static JScriptConverter()
		{
			string source = "class Eval { function Evaluate(code : System.String, value : System.Object, values : System.Object[]) : System.Object { return eval(code); } }";

			CompilerParameters cp = new CompilerParameters();

			cp.GenerateInMemory = true;

			foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
			{
				string assemblyLocation;

				try
				{
					assemblyLocation = assembly.Location;
				}
				catch
				{
					// Can fail when in design mode.
					continue;
				}

				if (File.Exists(assemblyLocation))
					cp.ReferencedAssemblies.Add(assemblyLocation);
			}

			JScriptCodeProvider compiler = new JScriptCodeProvider();

			CompilerResults results = compiler.CompileAssemblyFromSource(cp, source);

			Assembly result = results.CompiledAssembly;

			object eval = Activator.CreateInstance(result.GetType("Eval"));

			evaluator = (Evaluator)Delegate.CreateDelegate(typeof(Evaluator), eval, "Evaluate");
		}

		private bool trap = false;

		public bool TrapExceptions
		{
			get { return this.trap; }
			set { this.trap = value; }
		}

		public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
		{
			try
			{
				return evaluator(parameter.ToString(), values[0], values);
			}
			catch
			{
				if (trap)
					return null;
				else
					throw;
			}
		}

		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			return Convert(new object[] { value }, targetType, parameter, culture);
		}

		public object[] ConvertBack(object value, System.Type[] targetTypes, object parameter, CultureInfo culture)
		{
			throw new NotSupportedException();
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			throw new NotSupportedException();
		}
	}
}