The Castle Project

August 17th, 2007 Comments
Castle Project

In the last couple of years I have noticed a steadily growing interest in the .NET community around the Inversion of Control (IoC) and Dependency Injection (DI) patterns.  This is partly due to the fact that a number of excellent frameworks have emerged and gained popularity that allow us to use these designs in our applications relatively painlessly.  One such framework is the open source Castle Project.  In my opinion Castle is the best implementation of IoC and DI among many others that I have come across including Spring.NET, NInject, and ObjectBuilder.  This is however my opinion; which framework you use largely depends upon your requirements and your preferences.

If you are just getting started with Castle or are curious about why the heck one should use IoC and DI, I strongly suggest you check out the 3-part article series by Simone Busoli.  I just came across these articles and I can’t stress enough how well they are written.

SQL Server Database Comparison and Synchronization

April 18th, 2007 Comments
SQL Server

Since database are usually designed in development environments, migrating changes over to other environments (e.g. QA and production) is not a trivial task.  This is because SQL Server does not have any built-in tools to compare database schemas. 

There are quite a few third-party tools that would make your life easier, most notably, Red Gate’s SQL Compare (reasonably priced around $300).

At times, buying a commercial tool is not really an option, so one must resort to googling for free tools.  There are three such tools that I am aware of:

  1. SQLDBDiff by SQLDBTools
    A very decent tool that comes in both freeware and shareware versions.  Freeware version is not badly crippled; only advanced features such as multi-database comparison, data content comparison, etc. are disabled.

  2. Database Schema Comparison Utility
    This is a Code Project article that comes with C# source code of a schema comparison utility.  The utility itself is pretty bare-bone, but gets the job done.
  3. StarInix Free Database Compare 2.0
    I have not used this tool, but from the advertised feature list, it looks pretty good.  Most notably, in addition to SQL Server, this tool works with Access and MySQL databases.

JScript Eval Method In C#

February 6th, 2007 Comments
JScript

JavaScript and JScript languages provide a convenient Eval method that allows for dynamic evaluation of expressions. This functionality can be duplicated in C# using Microsoft’s JScript CodeDomProvider and Reflection.

Following class automatically compiles an in-memory assembly using JScript CodeDomProvider. The Eval method uses this assembly to dynamically evaluate specified expressions:

using System;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.JScript;

///
/// Implements JScript/JavaScript Eval like
/// functionality in C# to allow dynamic evaluation
/// of expressions.
///
public static class ExpressionEvaluator
{
    #region Private Members

    private static Type _evaluatorType;
    private static object _evaluatorInstance;
    private static readonly string _jscriptEvalClass =
    @"import System;
class JScriptEvaluator
{
public static function Eval(expression : String) : String
{
return eval(expression);
}
}";

    #endregion

    #region Private Methods

    ///
    /// Creates a dynamic in-memory assembly using JScript.NET
    /// to evaluate expressions.
    ///
    private static void Initialize()
    {

        CodeDomProvider compiler = new JScriptCodeProvider();

        CompilerParameters parameters = new CompilerParameters();
        parameters.GenerateInMemory = true;
        parameters.ReferencedAssemblies.Add("system.dll");

        CompilerResults results = compiler.CompileAssemblyFromSource(parameters, _jscriptEvalClass);

        Assembly assembly = results.CompiledAssembly;
        _evaluatorType = assembly.GetType("JScriptEvaluator");
        _evaluatorInstance = Activator.CreateInstance(_evaluatorType);
    }

    #endregion

    #region Public Methods

    ///
    /// Evaluates specified expression using reflection
    /// on the assembly generated in Initialize() method.
    ///
    /// The expression.
    /// A string representing evaluated expression.
    public static string Eval(string expression)
    {
        if (_evaluatorInstance == null)
            Initialize();

        object result = _evaluatorType.InvokeMember(
        "Eval",
       BindingFlags.InvokeMethod,
        null,
       _evaluatorInstance,
        new object[] { expression }
       );

        return (result == null) ? null : result.ToString();

    }

    #endregion
}

Using this class, we can execute statements such as:

        Console.WriteLine(ExpressionEvaluator.Eval("2 + 9"));
        Console.WriteLine(ExpressionEvaluator.Eval("System.DateTime"));
        Console.WriteLine(ExpressionEvaluator.Eval("Environment.OSVersion.VersionString"));

Using IXmlSerializable To Overcome “not expected” Error On Derived Classes

December 10th, 2006 16 comments

This article extends upon Simon Hewitt’s article on CodeProject. It is strongly recommended that you read Simon’s article also in order to fully understand the concepts.

BACKGROUND
XML serialization is an indispensable technique that has built-in support for in the .NET Framework. Using XML serialization, objects can be serialized to XML streams that may be persisted to permanent storage such as files, as well as XML streams can be converted back to objects with exactly the same state as at the time of serialization. With .NET Framework’s built-in support for XML serialization, all this can be achieved with only a few lines of code using the System.Xml.Serialization.XmlSerializer object.

PROBLEM
The problem with XmlSerializer is, however, that it works by generating an on-the-fly assembly behind the scenes at compilation time, that has logic for serialization and deserialization of a given type. For this reason, the exact (concrete) type of the object and it’s public properties must be known to the compiler at the time of compilation. If we try to serialize an object that, for example, has a public member of a given base type, then at run-time we receive a System.InvalidOperationException if the public member was set to a derived type.

WORKAROUND
The workaround to above problem has generally been resorting to custom XML serialization, which can get pretty complicated at times.

SOLUTION
An ingenious solutions was discovered by Simon Hewitt using the System.Xml.Serialization.IXmlSerializable interface that allows us to mitigate the by-design issue of XmlSerializer object. While this solution works very well, it requires that a new class be created for each base class that we need serialization support for.

Using C# generics, I took the liberty of extending Simon’s solution, eliminating the need for such new classes, and encapsulating the grunt work into just one class. Once this class has been added to our project (our referenced from another assembly), all we really need to do is decorate any of our public members of base type (that may be substituted with derived types at runtime) with an attribute.

using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace Vocalsoft.Xml.Serialization
{
public class CustomSerializer : IXmlSerializable
{
#region Private Members
///
/// Holds the object that this serializer operates on.
///
private ItemType _parameters;
#endregion

#region Static Methods
///
/// Implicit operators the specified p.
///
/// The p.
///
public static implicit operator
CustomSerializer(ItemType p)
{
return p == null ? null : new CustomSerializer(p);
}

///
/// Implicit operators the specified p.
///
/// The p.
///
public static implicit operator
ItemType(CustomSerializer p)
{
return p.Equals(default(ItemType)) ? default(ItemType) : p.Parameters;
}
#endregion Static

#region Constructors
///
/// Initializes a new instance of the "/> class.
///
public CustomSerializer()
{
}

///
/// Initializes a new instance of the "/> class.
///
/// The parameters.
public CustomSerializer(ItemType parameters)
{
this._parameters = parameters;
}
#endregion Constructors

#region Properties

///
/// Gets parameters.
///
/// The parameters.
public ItemType Parameters
{
get { return _parameters; }
}

#endregion Properties

#region IXmlSerializable Implementation

///
/// Returns schema of the XML document representation of the object that is produced by the method and consumed by the method.
///
///
/// An that describes the XML representation of the object that is produced by the method and consumed by the method.
///
XmlSchema IXmlSerializable.GetSchema()
{
return null;
}

///
/// Generates an object from its XML representation.
///
/// The stream from which the object is deserialized.
void IXmlSerializable.ReadXml(XmlReader reader)
{
// Get type from xml attribute
Type type = Type.GetType(reader.GetAttribute("type"));

// Deserialize
reader.ReadStartElement();
this._parameters = (ItemType)new XmlSerializer(type).Deserialize(reader);
reader.ReadEndElement();
}

///
/// Converts an object into its XML representation.
///
/// The stream to which the object is serialized.
void IXmlSerializable.WriteXml(XmlWriter writer)
{
// Write type as xml attribute
writer.WriteAttributeString("type", _parameters.GetType().ToString());
new XmlSerializer(_parameters.GetType()).Serialize(writer, _parameters);
}

#endregion IXmlSerializable Implementation

}
}

Once the above class has been added to our project, all we need to do is add an attribute directly on the base class property as follows:

[XmlElement(Type = typeof(CustomSerializer))]