<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Finite Epiphany &#187; .net</title>
	<atom:link href="http://finite.mikeandcorinne.com/category/net/feed/" rel="self" type="application/rss+xml" />
	<link>http://finite.mikeandcorinne.com</link>
	<description>Mike&#039;s thoughts on programming and tech</description>
	<lastBuildDate>Fri, 05 Mar 2010 23:28:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>An indexed foreach for .aspx Web Forms</title>
		<link>http://finite.mikeandcorinne.com/2008/03/an-indexed-foreach-for-aspx-web-forms/</link>
		<comments>http://finite.mikeandcorinne.com/2008/03/an-indexed-foreach-for-aspx-web-forms/#comments</comments>
		<pubDate>Tue, 11 Mar 2008 17:21:37 +0000</pubDate>
		<dc:creator>Mike Thomas</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[webforms]]></category>

		<guid isPermaLink="false">http://www.mikeandcorinne.com/finite/2008/03/11/an-indexed-foreach-for-aspx-web-forms/</guid>
		<description><![CDATA[ Nick blogged about why ASP.Net Repeaters Suck the other week and talked about using foreach loops in your .aspx.  I love this and have been doing it for a while &#8211; the strong typing and consice syntax is great.  However, sometimes I need format data based on odd and even rows&#8230;  &#60;table&#62; &#60;tr class='Row'&#62;&#60;td&#62;&#60;/td&#62;&#60;/tr&#62;   [...]]]></description>
			<content:encoded><![CDATA[<p> Nick blogged about why<span style="text-decoration: underline"> </span><a href="http://www.nickandgrace.com/code/archive/2008/03/03/asp.net-repeaters-suck.aspx#feedback">ASP.Net Repeaters Suck</a> the other week and talked about using foreach loops in your .aspx.  I love this and have been doing it for a while &#8211; the strong typing and consice syntax is great.  However, sometimes I need format data based on odd and even rows&#8230;</p>
<pre> &lt;table&gt;</pre>
<pre>   &lt;tr class='Row'&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;</pre>
<pre>   &lt;tr class='AltRow'&gt;...&lt;/tr&gt;</pre>
<pre>&lt;/table&gt;</pre>
<p>To accomplish this I created a helper function in the page code behind:</p>
<pre>protected void Foreach&lt;T&gt;(IEnumerable&lt;T&gt; enumerable, Proc&lt;T, int&gt; action){</pre>
<pre> int i = 0;</pre>
<pre> foreach(T t in enumerable){</pre>
<pre>    action(t, i);</pre>
<pre>  i++</pre>
<pre>}</pre>
<pre>}</pre>
<p>Then in the .aspx</p>
<pre>&lt;%Foreach(People, (person, i) =&gt; { %&gt;</pre>
<pre>  &lt;tr class='&lt;%=i%2==0 ?  "Row" : "AltRow"%&gt;'&gt;&lt;td&gt;&lt;%=person.FullName%&gt;&lt;/td&gt;&lt;/tr&gt;</pre>
<pre>&lt;%});%&gt;</pre>
<pre></pre>
<p>Just what I needed!</p>
]]></content:encoded>
			<wfw:commentRss>http://finite.mikeandcorinne.com/2008/03/an-indexed-foreach-for-aspx-web-forms/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>C# 3.0 Expression Trees and Reflection.Emit</title>
		<link>http://finite.mikeandcorinne.com/2007/07/c-30-expression-trees-and-reflectionemit/</link>
		<comments>http://finite.mikeandcorinne.com/2007/07/c-30-expression-trees-and-reflectionemit/#comments</comments>
		<pubDate>Sat, 28 Jul 2007 04:18:44 +0000</pubDate>
		<dc:creator>Mike Thomas</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C# 3.0]]></category>

		<guid isPermaLink="false">http://www.mikeandcorinne.com/code/?p=6</guid>
		<description><![CDATA[C# 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 [...]]]></description>
			<content:encoded><![CDATA[<p>C# 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 <a href="http://msdn2.microsoft.com/en-us/library/ms364047(vs.80).aspx">spec</a> 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.</p>
<p>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</p>
<pre lang="csharp">   public delegate object Getter(object target);

   public interface IAccessorGenerator{
	Getter GetGetter(Type targetType, string propertyName);
   }</pre>
<p>Once we have this interface defined, we can use it like this:</p>
<pre lang="csharp">   IAccessorGenerator generator = IoC.Resolve<iaccessorgenerator>();
   Getter getPersonName = generator.GetGetter(typeof(Person), "Name");
   Person me = new Person("Mike Thomas");
   string myName = getPersonName(me);
</iaccessorgenerator></pre>
<p>Obviously, this is a poor use since the property name is know at compile time, but it will suffice.</p>
<p>Using C# 2.0 our IAccessorGenerator can be implemented in a couple ways.  First, we could use normal reflection:</p>
<pre lang="csharp">   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[] { });
            };
        }
    }</pre>
<p>This method is clean, easy to understand and very slow.</p>
<p>Another way to implement this method is using the powerful Reflection.Emit.  Reflection.Emit allows IL code to be generated and executed at runtime.</p>
<pre lang="csharp">    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));
        }
    }</pre>
<p>This method is much faster, but can is harder to understand and debug.</p>
<p>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:</p>
<pre lang="csharp">    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> getter =
                Expression.Lambda<getter>(
                    Expression.Convert(
                        Expression.MakeMemberAccess(
                            Expression.Convert(target, type),
                            info
                        ),
                        typeof(object)
                    ),
                    target
                );

            return (Getter)getter.Compile();
        }
    }
</getter></getter></pre>
<p>This method is not as simple as the reflecting method, but it is still quite clear and vastly easier to debug than Reflection.Emit.</p>
<p>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.  <a href="http://www.interact-sw.co.uk/iangblog/2005/09/30/expressiontrees">Some have compared the power of Expression Trees to that of Lisp</a>.  <a href="http://blogs.msdn.com/jomo_fisher/archive/2007/03/28/fast-switching-with-linq.aspx">Someone else shows how to create extremely fast switch statement</a> (I think this is an amazing example).  I am excited to see what new and powerful things that developers find to use this for!</p>
]]></content:encoded>
			<wfw:commentRss>http://finite.mikeandcorinne.com/2007/07/c-30-expression-trees-and-reflectionemit/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Intercepting nHibernate events in ActiveRecord (or how to automatically set Update and Create dates)</title>
		<link>http://finite.mikeandcorinne.com/2007/07/intercepting-nhibernate-events-in-activerecord-or-how-to-automatically-set-update-and-create-dates/</link>
		<comments>http://finite.mikeandcorinne.com/2007/07/intercepting-nhibernate-events-in-activerecord-or-how-to-automatically-set-update-and-create-dates/#comments</comments>
		<pubDate>Thu, 26 Jul 2007 05:29:19 +0000</pubDate>
		<dc:creator>Mike Thomas</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[activerecord]]></category>
		<category><![CDATA[nhibernate]]></category>

		<guid isPermaLink="false">http://www.mikeandcorinne.com/code/?p=4</guid>
		<description><![CDATA[I 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&#8217;s Repository&#60;T&#62; pattern. One implication of this is that all of my entity classes [...]]]></description>
			<content:encoded><![CDATA[<p>I am currently working on a large .NET web application that I am just now porting to use <a href="http://www.hibernate.org/343.html">nHibernate </a>and <a href="http://castleproject.org/activerecord/">ActiveRecord.</a>  I used <a href="http://sourceforge.net/projects/mygeneration">MyGeneration </a>to create entity classes based on the existing database schema and am using a pattern similar to <a href="http://www.ayende.com/Blog/Default.aspx">Oren&#8217;s</a> <a href="http://www.ayende.com/Blog/archive/2007/06/08/Rhino-Commons-RepositoryltTgt-and-Unit-Of-Work.aspx">Repository&lt;T&gt; </a>pattern.  One implication of this is that all of my entity classes do not derive from ActiveRecordBase&lt;T&gt;.  Instead, they all merely derive from my own EntityBase class.  When I started my project, the EntityBase class was empty &#8211; existing only as a &#8220;just in case&#8221; class.</p>
<p>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:</p>
<pre lang="csharp">
Person person = new Person();
person.CreateDate = DateTime.Now;
person.CreateUser = UserIdentity.Name;
Repository&lt;person&gt;.Save(person);
</pre>
<p>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&#8217;t solve the problem of the RevisionDate and RevisionUser.  In addition you are repeating that code in every entity class.</p>
<p>At this point, I stepped back and asked myself what the <strong>best</strong> way to do this would be, regardless of the framework:</p>
<ul>
<li>Whenever an object is INSERTed into the database and it has a CreateDate and CreateUser they should be set.</li>
<li>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.</li>
</ul>
<p>Having that in mind, I created two interfaces:</p>
<pre lang="csharp">
interface IHasCreateStamp {
     DateTime CreateDate{get; set;}
     DateTime CreateUser{get; set;}
}

interface IHasRevisionStamp{/*omited*/}
</pre>
<p>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:</p>
<pre lang="csharp">
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;
}
</pre>
<p>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 &#8220;true&#8221; if you make any modifications.</p>
<p>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.</p>
]]></content:encoded>
			<wfw:commentRss>http://finite.mikeandcorinne.com/2007/07/intercepting-nhibernate-events-in-activerecord-or-how-to-automatically-set-update-and-create-dates/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
