tsJensen

A quest for software excellence...

Custom Recursive Model Validation in .NET Using Data Annotations

Need to write your own model validator outside the scope of an application framework such as ASP.NET MVC? A short while ago, I needed to do just that. I was writing a WCF service with a relatively complex data model which required a much greater level of validation than the DataMember attribute’s IsRequired property could provide.

Here’s the solution I found. But first a bit of background.

Validation in ASP.NET MVC 
I’ve been using Data Annotations attributes for view model validation for years in the context of ASP.NET MVC for model validations, client and server side. I always took the server side validation for granted and looked at the client side with greater interest. When getting started with ASP.NET MVC, I used Steve Sanderson’s xVal library. Then I switched to ASP.NET MVC 3’s client side validation.

For client side validation, I’m really starting to like jQuery’s unobtrusive validation and the ASP.NET MVC’s HtmlHelper class and its GetUnobtrusiveValidationAttributes method. And for the server side, view model binding and the ModelState.IsValid property works fine.

Validation Without an App Framework 
But this post is not about client side validation or server side validation in ASP.NET MVC. I had to do the validation against the model in the WCF service which, as far as I know, does not have a nice model validation facility other than its own data model serialization which just throws a nasty exception should the data being passed over the wire not provide required data.

So why not use the same approach used by our friends in the ASP.NET MVC world. A little Google investigation turned up something that looked like exactly what I wanted. I found an answer posted to StackOverflow by Mike Reust which included a link to his DataAnnotationsValidatorRecursive library. (Gotta love StackOverflow.)

After some experimentation, I had made some tweaks to Mike’s code and came up with something that worked the way I wanted it to. Here’s a partial example of a data model and how the ValidateObject with it’s optional MinOccursOnEnumerable can be used to require one or more items to be included in a required complex enumerable type that will get recursively.

[DataMember(IsRequired = true), 
	Required(ErrorMessage = "Employer cannot be null."), 
	ValidateObject]
public Employer Employer { get; set; }


[DataMember(IsRequired = true), 
	Required(ErrorMessage = "Children cannot be null."), 
	ValidateObject(MinOccursOnEnumerable = 1)]
public Child[] Children { get; set; }

Using the recursive validation library is easy. Here’s an example:

//perform validation using DataAnnotations for custom validation messages
List<ValidationResult> results = new List<ValidationResult>();
bool isValid = DataAnnotationsValidator.TryValidateObjectRecursive<MyModelData>(model, results);

//now examine isValid and the results

And here’s the code for the validation extensions and ValidateObject attribute.

using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System;

namespace MyValidator
{
	public static class DataAnnotationsValidator
	{
		public static bool TryValidateObject(object obj, ICollection<ValidationResult> results)
		{
			return Validator.TryValidateObject(obj, new ValidationContext(obj, null, null), results, true);
		}

		public static bool TryValidateObjectRecursive<T>(T obj, List<ValidationResult> results)
		{
			bool result = TryValidateObject(obj, results);

			var properties = obj.GetType().GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(ValidateObjectAttribute)));

			foreach (var property in properties)
			{
				var valAttrib = property.GetCustomAttributes(typeof(ValidateObjectAttribute), true).FirstOrDefault() as ValidateObjectAttribute;
				var value = obj.GetPropertyValue(property.Name);

				if (value == null || valAttrib == null) continue;

				var asEnumerable = value as IEnumerable;
				if (asEnumerable != null)
				{
					List<object> items = new List<object>();
					foreach (var enumObj in asEnumerable) items.Add(enumObj);
					foreach (var enumObj in items)
					{
						result = TryValidateObjectRecursive(enumObj, results) && result;
					}
					if (items.Count < valAttrib.MinOccursOnEnumerable)
					{
						string errorMessage = valAttrib.ErrorMessage ?? "MinOccursOnEnumerable validation failed.";
						results.Add(new ValidationResult(errorMessage));
						result = false;
					}
				}
				else
				{
					result = TryValidateObjectRecursive(value, results) && result;
				}
			}

			return result;
		}
	}

	public static class ObjectExtensions
	{
		public static object GetPropertyValue(this object o, string propertyName)
		{
			object objValue = string.Empty;

			var propertyInfo = o.GetType().GetProperty(propertyName);
			if (propertyInfo != null)
			{
				objValue = propertyInfo.GetValue(o, null);
			}
			return objValue;
		}
	}
}

You need to use the ValidateObject attribute on any complex type you want validated deeply. I found out the hard way that if you try to validate all reference objects, you get nasty results on DateTime properties.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyValidator
{
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, Inherited = false, AllowMultiple = false)]
	public class ValidateObjectAttribute : Attribute
	{
		int _minOccurs = 0;
		//marker for object properties that need to be recursively validated

		public ValidateObjectAttribute() { }

		public int MinOccursOnEnumerable { get { return _minOccurs; } set { _minOccurs = value; } }

		public string ErrorMessage { get; set; }
	}
}

Of course you can take off on this or Mike’s original code and create your own validation library for a WCF service, a business logic layer, or whatever you need. Good luck and please update me on your validation adventures.

C# Basics: On the Importance of the Using Statement and IDisposable

The world of .NET programming is full of objects that implement the IDisposable interface. File, Font, DataContext, Stream, DbConnection, and many more—all implement the IDisposable interface. And for good reason. They touch the outside world and the outside world is messy, full of resource allocations that can only be used one at a time and must be explicitly returned to their owner to be used by another caller.

So in this 8th installment of C# Basics, let’s take a look at how best to use the IDisposable interface by simply using the using statement. The using statement is really just syntactic sugar but it helps you produce much more readable and reliable code.

using (var myobj = new MyDisposable())
{
  myobj.DoSomething();
}

You can even stack them like this:

using (var myobj = new MyDisposable())
using (var otherobj = new MyOtherDisposable())
{
  var x = myobj.DoSomething();
  otherobj.DoAnotherThing(x);
}

Of course, you could write your own resource cleanup explicitly, but it can start to look a bit messy and as lazy as we often are, the cleanup often gets forgotten.

var myobj = new MyDisposable();
var otherobj = new MyOtherDisposable();
try
{
  var x = myobj.DoSomething();
  otherobj.DoAnotherThing(x);
}
finally
{
  if (otherobj != null) otherobj.Dispose();
  if (myobj != null) myobj.Dispose();
}

Use the using statement where you can. It's not a one size fits all syntax sugar, but it is sweet where it fits.

C# 5.0 Exciting New Asynchrony Features Coming

I’m gradually catching up with presentations from last month’s BUILD conference on Channel 9. Today I ran into a blog post by Samuel Jack in the UK on the topic of what’s new in C# 5.0. I recommend you read his blog, but more strongly recommend you watch Anders Hejlberg’s presentation on Channel 9 about C# 5.0 and VB 11.0.

Among my favorite goodies are the async and await keywords. For anyone who has put off learning how to write asynchronous application behavior because it is just too hard to understand, you are in luck. Wait a few more months, perhaps a year, and you can learn just a few easy concepts about how to use async and await keywords in your code and you will be an asynchronous coding wizard.

Exciting times!

C# Basics: const vs readonly vs static

In this 7th installment of C# Basics, I’m going to cover the differences between the modifiers const, readonly, and static, specifically in reference to class members where the developer wishes to use the fields or properties in client code that cannot change the value of that member.

To illustrate and discuss the differences between each modifier, I’ve put together a contrived set of classes with the least amount of code I can think to add in order to review and to examine the differences in the IL (intermediate language) taken from Ildasm.exe. (Visit this nice page to learn how to use Ildasm.exe from with Visual Studio.)

using System;

namespace ReadOnlyConstant
{
  public class MyConstOnly
  {
    // assigned at declaration and used at compile time only
    public const int Age = 20;
  }

  public class MyReadOnly
  {
    // can only be assigned in declaration or constructor
    public readonly int Age = 0;
    public MyReadOnly()
    {
      Age = 20;
    }
  }

  public static class MyStaticOnly
  {
    // can be assigned within class but "readonly" for client
    private static int _age = 20;
    public static int Age { get { return _age; } }
  }
}

The goal in each class above is to create a public field or member that can be read by client code but cannot be changed by client code. Looking through the IL produced by compiling this code can also be instructive even if you do not fully understand each and every IL instruction. Take a look here at these classes under the compiled covers and notice that the MyConstOnly class does not have a getter method to retrieve Age nor is it's value set in the .ctor but only noted by the compiler in the .field definition for use by the compiler later should client code use it. Then read through to the client code and see its IL code as well.

// =============== CLASS MEMBERS DECLARATION ===================

.class public auto ansi beforefieldinit ReadOnlyConstant.MyConstOnly
       extends [mscorlib]System.Object
{
  .field public static literal int32 Age = int32(0x00000014)
  .method public hidebysig specialname rtspecialname 
          instance void  .ctor() cil managed
  {
    // Code size       7 (0x7)
    .maxstack  8
    IL_0000:  ldarg.0
    IL_0001:  call       instance void [mscorlib]System.Object::.ctor()
    IL_0006:  ret
  } // end of method MyConstOnly::.ctor

} // end of class ReadOnlyConstant.MyConstOnly

.class public auto ansi beforefieldinit ReadOnlyConstant.MyReadOnly
       extends [mscorlib]System.Object
{
  .field public initonly int32 Age
  .method public hidebysig specialname rtspecialname 
          instance void  .ctor() cil managed
  {
    // Code size       25 (0x19)
    .maxstack  8
    IL_0000:  ldarg.0
    IL_0001:  ldc.i4.0
    IL_0002:  stfld      int32 ReadOnlyConstant.MyReadOnly::Age
    IL_0007:  ldarg.0
    IL_0008:  call       instance void [mscorlib]System.Object::.ctor()
    IL_000d:  nop
    IL_000e:  nop
    IL_000f:  ldarg.0
    IL_0010:  ldc.i4.s   20
    IL_0012:  stfld      int32 ReadOnlyConstant.MyReadOnly::Age
    IL_0017:  nop
    IL_0018:  ret
  } // end of method MyReadOnly::.ctor

} // end of class ReadOnlyConstant.MyReadOnly

.class public abstract auto ansi sealed beforefieldinit ReadOnlyConstant.MyStaticOnly
       extends [mscorlib]System.Object
{
  .field private static int32 _age
  .method public hidebysig specialname static 
          int32  get_Age() cil managed
  {
    // Code size       11 (0xb)
    .maxstack  1
    .locals init ([0] int32 CS$1$0000)
    IL_0000:  nop
    IL_0001:  ldsfld     int32 ReadOnlyConstant.MyStaticOnly::_age
    IL_0006:  stloc.0
    IL_0007:  br.s       IL_0009

    IL_0009:  ldloc.0
    IL_000a:  ret
  } // end of method MyStaticOnly::get_Age

  .method private hidebysig specialname rtspecialname static 
          void  .cctor() cil managed
  {
    // Code size       8 (0x8)
    .maxstack  8
    IL_0000:  ldc.i4.s   20
    IL_0002:  stsfld     int32 ReadOnlyConstant.MyStaticOnly::_age
    IL_0007:  ret
  } // end of method MyStaticOnly::.cctor

  .property int32 Age()
  {
    .get int32 ReadOnlyConstant.MyStaticOnly::get_Age()
  } // end of property MyStaticOnly::Age
} // end of class ReadOnlyConstant.MyStaticOnly

// =============================================================

You can read the MSDN full explanations of each modifier but here’s the basics:

const
Can only be assigned a value in declaration and can only be a value type or string. Use the const modifier when you KNOW the value won’t change. If you think it might change at a later date and your assembly is distributed as a compiled library, consider one of the other modifiers to assure that you don’t have a value you didn’t expect in your client code. (See use code sample below.)

readonly
Can assign a value at declaration or in the class constructor. It is important to note that if you use a reference type with modifiable members, your client code can still modify those members even if it cannot assign a value to the readonly reference. Note in the IL above that the initialization of the declared value occurs in the .ctor before the assignment in the .ctor, so if you are wondering which would be better, now you have some insight into that question.

static
Can assign the value of the private member anywhere within the class code. Note the initialization of the value in the static .ctor of the class. You could also assign the value in some other method later but with the public property implementing only a get, the client code cannot assign a value.

And here is the client code and it’s IL just below it. The most important point to note in the IL is that the client code is compiled with the const’s literal value, NOT a get to the class. This is why you must watch for the use of a const that could change with a new library. Make sure you compile your client code against that new library when you get it or you could be very sorry when the library is using one const compiled value and you’re using another.

namespace TestConsole
{
  class Program
  {
    static void Main(string[] args)
    {
      // compiler will replace with constant value
      // If the referenced assembly is changed to 40 and this is
      // not compiled again against that new assembly, the value
      // for mcoAge will still be 20. (See IL below.)
      int mcoAge = MyConstOnly.Age;

      MyReadOnly mro = new MyReadOnly();
      int mroAge = mro.Age;

      int msoAge = MyStaticOnly.Age;

      Console.WriteLine("{0} {1} {2}", mcoAge, mroAge, msoAge);
    }
  }
}

// output: 20 20 20

// and here is the IL with some of my own comments

// =============== CLASS MEMBERS DECLARATION ===================

.class private auto ansi beforefieldinit TestConsole.Program
       extends [mscorlib]System.Object
{
  .method private hidebysig static void  Main(string[] args) cil managed
  {
    .entrypoint
    // Code size       53 (0x35)
    .maxstack  4
    .locals init ([0] int32 mcoAge,
             [1] class [ReadOnlyConstant]ReadOnlyConstant.MyReadOnly mro,
             [2] int32 mroAge,
             [3] int32 msoAge)
    IL_0000:  nop
    IL_0001:  ldc.i4.s   20   //NOTE: literal value assigned - no mention of MyConstOnly class
    IL_0003:  stloc.0
    IL_0004:  newobj     instance void [ReadOnlyConstant]ReadOnlyConstant.MyReadOnly::.ctor()
    IL_0009:  stloc.1
    IL_000a:  ldloc.1
    IL_000b:  ldfld      int32 [ReadOnlyConstant]ReadOnlyConstant.MyReadOnly::Age
    IL_0010:  stloc.2
    IL_0011:  call       int32 [ReadOnlyConstant]ReadOnlyConstant.MyStaticOnly::get_Age()
    IL_0016:  stloc.3
    IL_0017:  ldstr      "{0} {1} {2}"
    IL_001c:  ldloc.0
    IL_001d:  box        [mscorlib]System.Int32
    IL_0022:  ldloc.2
    IL_0023:  box        [mscorlib]System.Int32
    IL_0028:  ldloc.3
    IL_0029:  box        [mscorlib]System.Int32
    IL_002e:  call       void [mscorlib]System.Console::WriteLine(string,
                                                                  object,
                                                                  object,
                                                                  object)
    IL_0033:  nop
    IL_0034:  ret
  } // end of method Program::Main

  .method public hidebysig specialname rtspecialname 
          instance void  .ctor() cil managed
  {
    // Code size       7 (0x7)
    .maxstack  8
    IL_0000:  ldarg.0
    IL_0001:  call       instance void [mscorlib]System.Object::.ctor()
    IL_0006:  ret
  } // end of method Program::.ctor

} // end of class TestConsole.Program

// =============================================================

C# Thread Safe Class Essentials

In this post I'm recording my own code sample for future reference. It is not meant to be perfectly usable or even a representation of best practices but a practical reminder note of the most common thread safe code I end up writing. The code is a thread safe singleton class that demonstrates the use of the lock keyword, the Interlocked class, ReadWriterLockSlim class, and one of the new concurrent collections available in .NET 4.0.

In the code below, I've only shown the ConcurrentDictionary being used. There is a gold mine of power in the other concurrent types to be explored in other posts.

using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Threading;

namespace SafeThreads
{
  public sealed class DataCache
  {
    // Thread Safe Singleton Pattern
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++
    
    //volatile to insure assignment before read access
    private static volatile DataCache _instance;
    
    //the sync root object - clever name
    private static object _threadBolt = new object();

    private DataCache() { } //cannot create outside this

    public static DataCache Instance
    {
      get
      {
        if (null == _instance)
        {
          lock (_threadBolt)
          {
            if (null == _instance)
            {
              _instance = new DataCache();
            }
          }
        }
        return _instance;
      }
    }
    

    // Thread Safe with lock
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++

    private long _callCount = 0;
    private long _updateCount = 0;

    public long UpdateCountWithLock(long callCount)
    {
      lock (_threadBolt)
      {
        _callCount += callCount;
        _updateCount++;
        return _updateCount;
      }
    }

    // Thread Safe Interlocked class
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++

    public long UpdateCountWithInterlocked(long callCount)
    {
      Interlocked.Add(ref _callCount, callCount);
      Interlocked.Increment(ref _updateCount);
      return _updateCount;
    }

    private Tuple<int, string> _currentItem = 
      new Tuple<int, string>(0, string.Empty);

    public Tuple<int, string> CurrentItemInterlocked
    {
      get { return _currentItem; }
      set
      {
        Interlocked.Exchange<Tuple<int, string>>(ref _currentItem, value);
      }
    }


    // Thread Safe ReaderWriterLockSlim
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++

    private ReaderWriterLockSlim _slimLock = new ReaderWriterLockSlim();
    private Dictionary<string, int> _keys = new Dictionary<string, int>();
    private List<string> _values = new List<string>();

    public int Count
    {
      get
      {
        _slimLock.EnterReadLock();
        try
        {
          return _values.Count;
        }
        finally
        {
          _slimLock.ExitReadLock();
        }
      }
    }

    public string this[int index]
    {
      get
      {
        _slimLock.EnterReadLock();
        try
        {
          if (_values.Count > index && index > -1)
            return _values[index];
          else
            return null;
        }
        finally
        {
          _slimLock.ExitReadLock();
        }
      }
    }

    public string this[string key]
    {
      get
      {
        _slimLock.EnterReadLock();
        try
        {
          if (_keys.ContainsKey(key))
          {
            return _values[_keys[key]];
          }
          else
            return null;
        }
        finally
        {
          _slimLock.ExitReadLock();
        }
      }

      set
      {
        _slimLock.EnterWriteLock();
        try
        {
          if (_keys.ContainsKey(key))
          {
            _values[_keys[key]] = value;
          }
          else
          {
            _values.Add(value);
            _keys.Add(value, _values.Count - 1);
          }
        }
        finally
        {
          _slimLock.ExitWriteLock();
        }
      }
    }

    //demonstrate upgrade from read to write lock
    public AddUpdateResult AddOrUpdate(string key, string value)
    {
      AddUpdateResult result = AddUpdateResult.Unchanged;
      _slimLock.EnterUpgradeableReadLock();
      try
      {
        if (_keys.ContainsKey(key))
        {
          if (value == _values[_keys[key]])
            return result;
          else
            result = AddUpdateResult.Updated;
        }
        else
          result = AddUpdateResult.Added;

        //upgrade to write lock
        _slimLock.EnterWriteLock();
        try
        {
          if (result == AddUpdateResult.Updated)
          {
            _values[_keys[key]] = value;
          }
          else
          {
            _values.Add(value);
            _keys.Add(value, _values.Count - 1);
          }
        }
        finally
        {
          _slimLock.ExitWriteLock();
        }
        return result;
      }
      finally
      {
        _slimLock.ExitUpgradeableReadLock();
      }
    }

    public enum AddUpdateResult
    {
      Added,
      Updated,
      Unchanged
    };


    // Thread Safe Collections
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++

    private ConcurrentDictionary<string, string> _concurrentCache = 
      new ConcurrentDictionary<string, string>();

    public ConcurrentDictionary<string, string> ConcurrentCache
    {
      get { return _concurrentCache; }
    }
  }
}

DomainAspects: Aspect Oriented Library Update - Configuration by Code and Convention

A year ago I posted a library that I enjoy using in one form or another called DomainAspects, an aspect oriented infrastructure or template for domain driven design in .NET applications. The library allows you to isolate cross cutting concerns such as exception logging and authorization from domain or business specific concerns. I promised to write more about the library but I got distracted with work and other topics.

In this post, I will introduce a new version of the library in which I mark the domain classes internal in order to isolate the implementation of the domain interface from the outside world making it impossible to create an instance of the domain implemenation directly. This change helps to enforce the use of the DomainAspects proxy wrapper to create and dispose of the domain object.

internal class ClassroomDomain : IClassroomDomain
{
  public List<string> GetStudents()
  {
    return new List<string>();
  }
}

I also wanted to explore the idea of getting away from XML configuration in part because Castle Project shuns it while supporting it for backward compatibility and in part because managing runtime configuration files can be problematic and convention is generally easier to support. Here's the aspect oriented service components being registered in the DomainFactory's static constructor:

container = new WindsorContainer(); //no more XML

container.Register(
  Component.For<IPrincipalProvider>()
  .ImplementedBy<PrincipalProvider>()
  .Named("PrincipalProvider")
  .LifeStyle.Transient,
  
  Component.For<IOperationAuthorizer>()
  .ImplementedBy<OperationAuthorizer>()
  .Named("OperationAuthorizer")
  .LifeStyle.Transient,
  
  Component.For<IOperationAuditor>()
  .ImplementedBy<OperationAuditor>()
  .Named("OperationAuditor")
  .LifeStyle.Transient,
  
  Component.For<OperationInterceptor>()
  .Named("OperationInterceptor")
  .LifeStyle.Transient);

Now, the DomainFactory's Create method uses the convention that the implementation has the same name without the "I" prefix on the interface name.

/// <summary>
/// Use this factory method to create a transient (one time use) instance.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T Create<T>() where T : class
{
  var svc = container.GetService<T>();
  if (null == svc)
  {
    //resolution of type by convention MyClass implements IMyClass
    Type interfaceType = typeof(T);
    var implementedByName = interfaceType.AssemblyQualifiedName
      .Replace("." + interfaceType.Name + ",",
					"." + interfaceType.Name.Substring(1) + ",");
    Type implementedByType = Type.GetType(implementedByName);
    if (null == implementedByType) 
      throw new TypeAccessException(string.Format("Type {0} could not be found.", implementedByName));

    container.Register(Component.For(interfaceType)
      .ImplementedBy(implementedByType)
      .Named(implementedByType.Name)
      .Interceptors(InterceptorReference.ForKey("OperationInterceptor")).Anywhere
      .LifeStyle.Transient);
  }
  if (!isConfigured) throw initializationException;
  return container.Resolve<T>();
}

Now I remove the app.config from my projects and run my tests XML-config-free. There is a lot more fun stuff to explore in this library, so check back soon for more info on DomainAspects.

You can download the new code here: DomainAspects_v1_1.zip (30.25 KB).

C# Basics: Extension Methods and QDD vs TDD

In this sixth installment of C# Basics, I want to share a brief snippet of an extension method I’ve found useful that will introduce you to QDD as well. Quick and Dirty Design (QDD) is my name for having multiple tiny console application projects lying around in which I test little code snippets before putting them into something more serious. This is only necessary in projects in which TDD has not been used and no testing framework or tests are available for whatever reason.

But back to extension methods. From MSDN we learn:

“Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.”

As the MSDN article points out, the most common extension methods you may run into are the LINQ standard query operations. But don’t let that stop you from providing yourself with some very nice little extension methods like this one:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace IOTest
{
  class Program
  {
    static void Main(string[] args)
    {
      string phone1 = @"8015551212";
      string phone2 = @"(8a0d1d)d d5d5d5d-d1d2d1d2";

      if (phone1.StripNonNumeric() == phone2.StripNonNumeric())
        Console.WriteLine("true");
      else
        Console.WriteLine("false");

      Console.ReadLine();
    }
  }

  static class Ext
  {
    private static Regex nonNum = new Regex(@"[^0-9]");

    public static string StripNonNumeric(this string item)
    {
      return nonNum.Replace(item, string.Empty);
    }
  }
}

C# Basics: Symmetric Encryption with Rijndael

I often need to encrypt a string and then decrypt it. Sometimes its to move some value from one server to another without the benefit of SSL. So for the fifth installment of C# Basics, I’ll share the a generic version of a little encryption utility I’ve used many times and in many places.

Most Important: If you decide to use this code, be sure to change the key and vector text to something only you know. You might even want to use a hardware security module.

I like AES (formerly known as Rijndael, pronounced “rain-doll”) but you can pick your own algorithm. The code below will work with most of the .NET symmetric encryption algorithms.

using System;
using System.Security.Cryptography;
using System.Text;

namespace MyCrypt
{
  public static class Tokenizer
  {
    //create your own unique key and vector strings
    //maybe even lock them up and require a cert to get them out
    private const string keyText = @"The quick brown fox jumps";
    private const string vectorText = @"over the lazy dog.";
    private static byte[] key = null;
    private static byte[] vector = null;

    static Tokenizer()
    {
      key = GetMD5Hash(keyText);
      vector = GetMD5Hash(vectorText);
    }

    public static string Encrypt(string val)
    {
      if (string.IsNullOrWhiteSpace(val)) return null;
      RijndaelManaged rjm = new RijndaelManaged();
      rjm.KeySize = 128;
      rjm.BlockSize = 128;
      rjm.Key = key;
      rjm.IV = vector;
      byte[] input = Encoding.UTF8.GetBytes(val);
      byte[] output = rjm.CreateEncryptor()
        .TransformFinalBlock(input, 0, input.Length);
      string data = Convert.ToBase64String(output);
      return data;
    }

    public static string Decrypt(string val)
    {
      if (string.IsNullOrWhiteSpace(val)) return null;
      try
      {
        RijndaelManaged rjm = new RijndaelManaged();
        rjm.KeySize = 128;
        rjm.BlockSize = 128;
        rjm.Key = key;
        rjm.IV = vector;
        byte[] input = Convert.FromBase64String(val);
        byte[] output = rjm.CreateDecryptor()
          .TransformFinalBlock(input, 0, input.Length);
        string data = Encoding.UTF8.GetString(output);
        return data;
      }
      catch
      {
        return null;
      }
    }

    static byte[] GetMD5Hash(string data)
    {
      MD5 md5 = MD5CryptoServiceProvider.Create();
      return md5.ComputeHash(Encoding.UTF8.GetBytes(data));
    }
  }
}