phone booth
January 22nd, 2008phone booth, originally uploaded by Mike & Corinne.
We were walking down Magnolia last night and came across this decaying phone booth. I wish I had taken it from a different angle than the two that I did, but it came out all right.
All post processing was done in Camera Raw + a little dodge+burning to bring out some highlights.
A Use for Extension Methods
December 4th, 2007Extension Methods (added to c# 3.0) have quite a few bad uses but a few positive uses have been found. One potentially use that I haven’t heard mentioned before is adding methods to Enums. As always, I’m sure there are dozens of ways to abuse this, and there may be better ways to do this but for some cases I think this might have some value. For example:
public enum ErrorStatus {
Open = 1, InProgress = 2, Closed = 3, WillNotFix = 4
}
public static class ErrorStatusExtensions {
public static string Color(this ErrorStatus status) {
if (status == ErrorStatus.Open) {
return "red";
}
else {
return "green";
}
}
}
Surely I’m not going to start adding dozens of methods to my enums and even more surely an not going to start storing data in opaque extension methods, but for a case like this, I think this just might work.
Is this a good idea?
August 7th, 2007I just created a folder named “RottingDeprecatedLegacyCode”…
C# 3.0 Expression Trees and Reflection.Emit
July 27th, 2007C# 3.0 brings many enhancements to the C# language such as implicitly typed local variables, extension methods, lambda expressions, query expressions and expression trees (see the spec for details). Expression trees are one aspect of the language which have yet to receive the attention that they deserve. This is both surprising and expected. Surprising because expression trees may be one of the most powerful new features of C#. Expected because they are the hardest to understand.
Here is an example. Sometimes you need to be able to access properties on objects that you do not know the name of at compile time. A common way of doing this is to have one class that generates delegates which are good for getting a given property from a given target type. Like so
public delegate object Getter(object target);
public interface IAccessorGenerator{
Getter GetGetter(Type targetType, string propertyName);
}
Once we have this interface defined, we can use it like this:
IAccessorGenerator generator = IoC.Resolve();
Getter getPersonName = generator.GetGetter(typeof(Person), "Name");
Person me = new Person("Mike Thomas");
string myName = getPersonName(me);
Obviously, this is a poor use since the property name is know at compile time, but it will suffice.
Using C# 2.0 our IAccessorGenerator can be implemented in a couple ways. First, we could use normal reflection:
public class ReflectingAccessorGenerator : IAccessorGenerator {
public Getter GetGetter(Type targetType, string propertyName) {
MethodInfo getMethod = targetType.GetProperty(propertyName).GetGetMethod();
return delegate(object target) {
return getMethod.Invoke(target, new object[] { });
};
}
}
This method is clean, easy to understand and very slow.
Another way to implement this method is using the powerful Reflection.Emit. Reflection.Emit allows IL code to be generated and executed at runtime.
public class EmitAccessorGenerator : IAccessorGenerator{
private static string GetRandomMethodName() {
return Guid.NewGuid().ToString();
}
public Getter GetGetter(Type targetType, string propertyName)
{
//Get the "get" method on the target type
MethodInfo targetGetMethod = targetType.GetProperty(propertyName).GetGetMethod();
DynamicMethod getMethod = new DynamicMethod(
GetRandomMethodName(),
typeof(object),
new Type[] { typeof(object) },
targetType.Module);
ILGenerator getIL = getMethod.GetILGenerator();
getIL.Emit(OpCodes.Ldarg_0);
if (targetType.IsValueType)
{
LocalBuilder lb = getIL.DeclareLocal(targetType);
getIL.Emit(OpCodes.Unbox_Any, targetType);
getIL.Emit(OpCodes.Stloc_0);
getIL.Emit(OpCodes.Ldloca_S, lb);
}
else
{
getIL.Emit(OpCodes.Castclass, targetType);
}
if (targetGetMethod.IsVirtual)
{
getIL.Emit(OpCodes.Callvirt, targetGetMethod);
}
else
{
getIL.Emit(OpCodes.Call, targetGetMethod);
}
if (targetGetMethod.ReturnType.IsValueType)
{
getIL.Emit(OpCodes.Box, targetGetMethod.ReturnType);
}
getIL.Emit(OpCodes.Ret);
return (Getter)getMethod.CreateDelegate(typeof(Getter));
}
}
This method is much faster, but can is harder to understand and debug.
C# 3.0 allows for another option. We can build and compile the Getter function at runtime using an expression tree. This gives us syntax that is almost as clear as the syntax from the ReflectingAccessorGenerator that runs just as fast as the EmitAccessorGenerator:
public class ExpressionAccessorGenerator : IAcessorGenerator {
public delegate object Getter(object target);
public Getter GetGetter(Type type, string property) {
PropertyInfo info = type.GetProperty(property);
ParameterExpression target = Expression.Parameter(typeof(object), "target");
Expression getter =
Expression.Lambda(
Expression.Convert(
Expression.MakeMemberAccess(
Expression.Convert(target, type),
info
),
typeof(object)
),
target
);
return (Getter)getter.Compile();
}
}
This method is not as simple as the reflecting method, but it is still quite clear and vastly easier to debug than Reflection.Emit.
This is a fairly simple and contrived example, but I think that it is enough to hint at the power that lies in Expression Trees. Some have compared the power of Expression Trees to that of Lisp. Someone else shows how to create extremely fast switch statement (I think this is an amazing example). I am excited to see what new and powerful things that developers find to use this for!
Intercepting nHibernate events in ActiveRecord (or how to automatically set Update and Create dates)
July 25th, 2007I am currently working on a large .NET web application that I am just now porting to use nHibernate and ActiveRecord. I used MyGeneration to create entity classes based on the existing database schema and am using a pattern similar to Oren’s Repository<T> pattern. One implication of this is that all of my entity classes do not derive from ActiveRecordBase<T>. Instead, they all merely derive from my own EntityBase class. When I started my project, the EntityBase class was empty – existing only as a “just in case” class.
Eventually, I ran across a problem. Many but not all of my entities had CreateDate, CreateUser, RevisionDate, and RevisionUser properties. Others just had a CreateDate and CreateUser but no RevisionDate or RevisionUser. The most elementary way to handle something like this would be to do something like:
Person person = new Person();
person.CreateDate = DateTime.Now;
person.CreateUser = UserIdentity.Name;
Repository<person>.Save(person);
The problem with this approach is that you would have to maunally update the CreateDate and RevisionDate whenever you created or saved an entity. Not good. Option two is to set the CreateDate and CreateUser in the constructor of all entities but that doesn’t solve the problem of the RevisionDate and RevisionUser. In addition you are repeating that code in every entity class.
At this point, I stepped back and asked myself what the best way to do this would be, regardless of the framework:
- Whenever an object is INSERTed into the database and it has a CreateDate and CreateUser they should be set.
- Whenever an object has been changed and is being UPDATEd to the database and it has a RevisionDate and Revision user they should be set.
Having that in mind, I created two interfaces:
interface IHasCreateStamp {
DateTime CreateDate{get; set;}
DateTime CreateUser{get; set;}
}
interface IHasRevisionStamp{/*omited*/}
Having applied these interfaces to the appropriate classes I now had to find where I could intercept the nHibernate Save and FlushDirty events. It took me more time that I would like to find this, but in the end the solution (while not ideal) is quite simple. ActiveRecords sets a nHibernate IInterceptor that forwards all nHibernate events to the appropriate ActiveRecord entity classes as long as they inherit from ActiveRecordHooksBase. I had to modify my EntityBase class to inherit from ActiveRecordHooksBase and in my EntityBase class am able to override the OnFlushDirty method:
protected override bool OnFlushDirty(object id, IDictionary previousState, IDictionary currentState, IType[] types) {
if(this is IHasRevisionStamp) {
DateTime now = DateTime.Now;
string userPcid = SecurityHelper.GetCurrentIdentity().PeopleCodeId;
currentState["RevisionDate"] = now;
currentState["RevisionOpid"] = userPcid;
return true;
}
return false;
}
In the OnFlushDirty you are able to modify the currentState and any changes you make will be propagated to the database. You also have to make sure to return “true” if you make any modifications.
Once that and the BeforeSave methods were overridden all CreateDates and RevisionDates are set automatically. One great benefit too, is that a RevisionDate will only be updated if the entity has changed.
About This Blog
July 24th, 2007This is going to be a note pad and journal of sorts. I will try to keep track of ideas I have and discoveries I make about programming. I am primarily a .NET developer so much of what I write about will be related to .NET and C#.


