<?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>Nathan Bridgewater &#187; T4</title>
	<atom:link href="http://www.integratedwebsystems.com/tag/t4/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.integratedwebsystems.com</link>
	<description>My Little .NET Sandbox</description>
	<lastBuildDate>Fri, 10 Sep 2010 16:13:08 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>SubSonic3 Works on Mono!</title>
		<link>http://www.integratedwebsystems.com/2010/08/subsonic3-works-on-mono/</link>
		<comments>http://www.integratedwebsystems.com/2010/08/subsonic3-works-on-mono/#comments</comments>
		<pubDate>Mon, 09 Aug 2010 05:00:00 +0000</pubDate>
		<dc:creator>Nathan</dc:creator>
				<category><![CDATA[ADO.Net]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Mono]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[POCO]]></category>
		<category><![CDATA[SubSonic]]></category>
		<category><![CDATA[T4]]></category>

		<guid isPermaLink="false">http://www.integratedwebsystems.com/?p=773</guid>
		<description><![CDATA[So a couple weeks ago I decided to test a few changes made to SubSonic3 that fixed a LINQ evaluation bug related to medium trust. Using a simple console app on linux/mono, I tested basic data access to a SQLite database using repository mode, and to my surprise it worked! I&#8217;ve always been a big [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.subsonicproject.com"><img style="border-right-width: 0px; width: 280px; margin-bottom: 1em; float: right; border-top-width: 0px; border-bottom-width: 0px; height: 41px; margin-left: 1em; border-left-width: 0px" alt="SubSonic  Project" src="http://www.subsonicproject.com/content/images/SubSonicSMall.png" /></a>So a couple weeks ago I decided to test a few changes made to <a href="http://www.subsonicproject.com">SubSonic3</a> that fixed a LINQ evaluation bug related to medium trust. Using a simple console app on linux/mono, I tested basic data access to a SQLite database using repository mode, and to my surprise it worked! </p>
<p><a href="http://www.mono-project.com"><img style="border-right-width: 0px; margin: 0px 10px 10px 0px; width: 100px; display: inline; float: left; border-top-width: 0px; border-bottom-width: 0px; height: 120px; border-left-width: 0px" title="Mono-gorilla-aqua.100px" border="0" alt="Mono-gorilla-aqua.100px" src="http://www.integratedwebsystems.com/wp-content/uploads/2010/08/Monogorillaaqua.100px1.png" width="100" height="120" /></a></p>
<p>I&#8217;ve always been a big fan of SubSonic since its 2.0 version, which I used for a mid-sized e-commerce site. With a totally rewritten core, 3.0 uses LINQ (language integrated query) for all of its data access providing a great alternative to Dblinq for the Mono platform.</p>
<p>&#160;</p>
<p>&#160;</p>
</p>
<p> <span id="more-773"></span>
</p>
<p>SubSonic3 supports <a href="http://www.subsonicproject.com/docs/Using_ActiveRecord">ActiveRecord</a>, <a href="http://subsonicproject.com/docs/Using_SimpleRepository">Repository</a>, and <a href="http://www.subsonicproject.com/docs/Using_AdvancedTemplates">Custom Linq</a> modes, which give you the flexibility to build code-first or database-first.&#160; SubSonic3 is not an ORM (object relational mapping) like <a href="http://www.nhibernate.com/">NHibernate</a>, but it can behave like one when you use Repository Mode using POCO (plain old CLR object) representations of your tables. SubSonic handles the mapping and database query generation itself based on the database provider configured. Its intention is to allow you to build code-first and let the persistence of the object be non-critical to your application. It can even migrate your class definition changes (table schema) to the database automatically during runtime; however, it still has the flexibility to let you design your database with keys, indexes, and constraints yourself without using the automatic migration. The <a href="http://www.subsonicproject.com">SubSonic website</a> has a <a href="http://subsonicproject.com/docs/Simple_Repo_5_Minute_Demo">great demo</a> showing this capability.</p>
<h3>Database Independence</h3>
<p>To make SubSonc3 truly database agnostic, you have to use Repository mode. Active Record and Custom Linq modes DO support multiple database engines, but they all require custom class generation which is hard-wired to those engines. So when you change database types like from MySql to MSSQL or vice-versa, you have to regenerate your classes.</p>
<p>With Repository mode, you simply change your connection string in the app.config. It will use the 2.0 Data Provider model provided by the database engine client and the definition of your POCO classes to determine the SQL syntax and schema to use.&#160; SubSonic is pre-wired with MSSql, SQLite, MySql, and a generic ANSI Sql syntax support. There&#8217;s been lots of talk about implementing Oracle and PostgreSql, which may already work in ActiveRecord or LinqTemplates, but are not yet in the Core assembly for use with Repository.</p>
<h3>Decoupled &#8211; Mocking for Unit Tests and Framework Independence</h3>
<p>Another big advantage of Repository is the ability to decouple your data framework from your application completely. Since the POCO objects are not directly tied to SubSonic, they can be re-used with other frameworks like <a href="http://www.nhibernate.com">NHibernate</a> or the latest <a href="http://blogs.msdn.com/b/adonet/archive/2010/07/14/ctp4codefirstwalkthrough.aspx">Entity Framework 4</a> without touching a single line of application code. It also opens the door to mocking and testability. Dependency Injection frameworks like <a href="http://unity.codeplex.com/">Unity</a> or <a href="http://structuremap.github.com/structuremap/index.html">StructureMap</a> work perfect for this.</p>
<h3>So how about a sample?</h3>
<p>This is a silly little test application that is neither pretty nor elegant, but it proves that this code will run on Mono 2.6.3 and 2.7 (trunk) with a SQLite database. It also uses Unity for dependency injection much like you would in Asp.NET MVC. Within the project, you&#8217;ll find an AppService interface used to provide the definition for simple &#8216;business&#8217; functionality. This is meant to be generic for the sample; but in a real application, I would breakdown the services by functional purpose. They all can share the same LinqRepository data interface, which provides basic rules for LINQ-based CRUD. SubSonic3 hooks right into that and is nearly transparent to the application with the exception of a few attributes on the domain objects. There are some placeholder Mock classes there and sample mappings in the code just for show.</p>
<p><a href="/resources/p773/SubSonicDemo.zip">Download the sample project</a></p>
<p>You can also get the latest version from <a href="http://github.com/nathanb/iws-snippets">IWS Snippets project</a> subversion.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.integratedwebsystems.com/2010/08/subsonic3-works-on-mono/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Simple Linq to Sql Enhancements with T4 Templating</title>
		<link>http://www.integratedwebsystems.com/2009/10/simple-linq-to-sql-enhancements-with-t4-templating/</link>
		<comments>http://www.integratedwebsystems.com/2009/10/simple-linq-to-sql-enhancements-with-t4-templating/#comments</comments>
		<pubDate>Fri, 23 Oct 2009 16:15:15 +0000</pubDate>
		<dc:creator>Nathan</dc:creator>
				<category><![CDATA[T4]]></category>
		<category><![CDATA[Linq to Sql Classes]]></category>
		<category><![CDATA[Sql Server]]></category>
		<category><![CDATA[visual studio]]></category>

		<guid isPermaLink="false">http://www.integratedwebsystems.com/?p=373</guid>
		<description><![CDATA[I sometimes underestimate the power of the tools that come with visual studio. Usually this is because I&#8217;m ignorant of the fact they even exist until I see them used or read about them somewhere else. T4 text generation is no exception.  This is a very useful tool that&#8217;s built right into Visual Studio 2008 [...]]]></description>
			<content:encoded><![CDATA[<p>I sometimes underestimate the power of the tools that come with visual studio. Usually this is because I&#8217;m ignorant of the fact they even exist until I see them used or read about them somewhere else. <a href="http://www.olegsych.com/2007/12/text-template-transformation-toolkit/" target="_blank">T4 text generation</a> is no exception.  This is a very useful tool that&#8217;s built right into Visual Studio 2008 which I discovered while peeking at the new <a href="http://www.subsonicproject.com" target="_blank">SubSonic 3</a> code when it came out. (Thanks <a href="http://blog.wekeroad.com/" target="_blank">Conery</a>). <img src='http://www.integratedwebsystems.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>After spending a day drilling into T4 and learning how it works, I have to say that it was definitely time not wasted. I&#8217;ve since used it for tons of miscellaneous code generation projects including mostly data layer extensions. And with the help of the data provider specific templates in the SubSonic project, much of the schema extraction code has been provided for us through open source.</p>
<p>I&#8217;m a big fan of SubSonic, and I like to push it in all the shops I work with that aren&#8217;t already anchored down to another data framework. However, sometimes we still have to fall back to vanilla data layers like Linq to Sql (L2S), Entity Framework (EF), or straight up ADO.Net depending on the shop and its personalities. Having experience using SubSonic opens your eyes to some useful ways you can improve L2S and the others.</p>
<p><span id="more-373"></span>Like, for example, updating data&#8230; Have you been in a situation (like a web form postback or a web service call) where you&#8217;re instantiating a new entity instance whose data already exists in your database and you need to simply update it?  In L2S, this isn&#8217;t very straight forward. If you don&#8217;t want to mess with detaching and reattaching data entities, you can simple load an instance from the data context and update its fields with the new data; then commit the change back to the data context.</p>
<p>Well that&#8217;s great and all, but who&#8217;s going to type all the load functions? Not me, I hate typing. <img src='http://www.integratedwebsystems.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />   So T4 comes to the rescue.  Here you&#8217;ll see a simple script that looks at a database and generates LoadFromExisting() functions for each table into a partial class that extends the original L2S class. Then anytime the schema changes, you simply run the T4 template and it re-executes your generation code.</p>
<h3>Using the Generated Code</h3>
<p>Here’s an example helper save function using Linq to Sql.  It simply checks for an existing record. If it exists, it updates its fields with the ones you passed in making it dirty to the data context, or it instructs the data context to insert it as a new one.</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public void SaveSection(Section section)
{
    var data = this.GetSectionByID(section.ID);

    if (data == null)
    {
        data = section;
        _DB.Sections.InsertOnSubmit(data);
    }
    else
        data.LoadFromExisting(section);

    _DB.SubmitChanges();
}</pre>
<p>Here is the corresponding LoadFromExisting() definition. You can see it’s very simple. All I really want to do here is update the values and flag the fields on the instance we pulled from the data context as dirty. The main thing to note here is that the class definition is partial.  It matches the namespace and name of the class generated in our DBML data context file.</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public partial class Section
{

    public Section LoadFromExisting(Model.Section data)
    {
        this.ID = data.ID;
        this.DefaultContentID = data.DefaultContentID;
        this.Description = data.Description;
        return this;
    }

}</pre>
<h3>Now for Actually Generating Code with T4</h3>
<p>To briefly explain T4, it’s basically a .net virtual machine hosted by visual studio. The code files appear a lot like classic ASP and MVC where you have rendered sections and functional sections. In T4, the token used to start and end a code section is: &lt;# #&gt;.  Like asp, you can include other files to re-use code files. Those files in this example have the ttinclude extension. Normal T4 scripts must end with the “.tt” extension.</p>
<p>Since we’re using what has already been setup for us by the SubSonic templates, we’re re-using their shared files: <em>Settings.ttinclude</em> and<em> SqlServer.ttinclude</em>. The <em>settings.ttinclude </em>file has all your basic shared settings like the global directives, includes, references, and supporting object model for the database structures. The <em>SqlServer.ttinclude </em>file contains the Sql Server specific schema extraction functions.</p>
<p><a href="http://www.integratedwebsystems.com/wp-content/uploads/2009/10/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="image" src="http://www.integratedwebsystems.com/wp-content/uploads/2009/10/image_thumb.png" border="0" alt="image" width="185" height="103" align="right" /></a> Add both these files to your project, and then add a new text file with extension “.tt” to your project.  Copy the content from template.tt into your new tt file. The template content simply includes the shared files for you. Notice every time you save this file, it re-runs itself; so be very aware when you’re saving to avoid running the code accidentally.</p>
<p>Here’s the full script for the partial extension:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">&lt;#@ template language="C#v3.5" debug="True" hostspecific="True" #&gt;
&lt;#@ include file="SQLServer.ttinclude" #&gt;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Linq.Expressions;
using System.Collections;
using System.ComponentModel;
using System.Data.Common;

namespace &lt;#=Namespace #&gt;
{
&lt;#

    var tables = LoadTables();

    foreach(Table tbl in tables)
    {
        if(!ExcludeTables.Contains(tbl.Name) &amp;&amp; !tbl.Name.StartsWith("aspnet"))
        {
#&gt;

    /// &lt;summary&gt;
    /// A class which represents the &lt;#=tbl.Name #&gt; table in the &lt;#=DatabaseName#&gt; Database.
    /// &lt;/summary&gt;
    public partial class &lt;#=tbl.ClassName#&gt;
    {

            public &lt;#=tbl.ClassName #&gt; LoadFromExisting(Model.&lt;#=tbl.ClassName #&gt; data)
            {
&lt;#
            foreach(Column col in tbl.Columns)
            {

                if (tbl.ClassName == col.CleanName)
                {
                    col.CleanName += "X";
                }
#&gt;
                this.&lt;#=col.CleanName #&gt; = data.&lt;#=col.CleanName #&gt;;
&lt;#
            }
#&gt;
                return this;
            }

        }
&lt;#
   }
  }
#&gt;
}</pre>
<p>So as  you can see, it’s very straight forward.  Here, we’re loading up all the tables, spinning through each one and then writing a function that spins its columns to generate assignment expressions.  (this.&lt;#=col.CleanName #&gt; = data.&lt;#=col.CleanName #&gt;; )  You’ll notice a few variable names being used like “Namespace” or ExcludeTables, etc.  With T4, you have to pretend that anything defined in a global scope is really just a member of this virtual class we created as our script. Those names were actually defined earlier in the Settings.ttinclude.  That is also where we’re setting our connection string name for the connection info. It uses the app.config in current project so you don’t have to save it statically in the file, which is another perk of these SubSonic templates.</p>
<p>For partial classes to work, you have to match the namespace and class name in your partial file. This is extremely useful, because I can generate code all day long with this file and then create yet another partial extension for the the more functional fine detail extensions.</p>
<h3>Enum Generator</h3>
<p>Here’s a nice little enum generator I wrote the other day. We typically use lookup tables in a lot of our projects whose names and values match what we have in our tables. This script uses a global list of table names in the <em>Settings.ttinclude </em>file and selects their data to generate enum code with values. The table structure is: (ID int, Name varchar(50), Description varchar(100)). You’ll need to create the table and fill it with your enumeration data first. Then run this script.</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">&lt;#@ template language="C#v3.5" debug="True" hostspecific="True" #&gt;
&lt;#@ include file="SQLServer.ttinclude" #&gt;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Linq.Expressions;
using System.Collections;
using System.ComponentModel;
using System.Data.Common;

namespace &lt;#=EnumNamespace #&gt;
{
&lt;#
            var list = GetEnums();
            foreach (KeyValuePair&lt;string, List&lt;EnumValue&gt;&gt; pair in list)
            {

            #&gt;

        /// &lt;summary&gt;
        /// An enumeration that represents the table &lt;#= pair.Key #&gt; in database: &lt;#= DatabaseName #&gt;
        /// &lt;/summary&gt;
        public enum &lt;#=pair.Key#&gt;
        {
&lt;#            int counter = 0;
            foreach(var value in pair.Value)
            {
                counter++;
                if (!string.IsNullOrEmpty(value.Description)) {#&gt;
            /// &lt;summary&gt;
            /// &lt;#= value.Description #&gt;
            /// &lt;/summary&gt;
&lt;# } #&gt;            &lt;#= value.Name #&gt; = &lt;#= value.Value #&gt;&lt;#if (counter &lt; pair.Value.Count) {#&gt;,&lt;#}#&gt;

&lt;#            }#&gt;
        }

&lt;#            }#&gt;
}</pre>
<p>In my case, I dropped these enumerations into a custom namespace since the names were shared with the entities representing the tables.  If you wanted to, you could easily drop these into a class as well.</p>
<h3>Download</h3>
<p><a href="/t4.zip" target="_blank">Here’s the zip file containing the four scripts</a>.</p>
<p><em>Disclaimer/Licensing: All code provided here was derived using some of the code in SubSonic templates; hence, this code is open source under the same license. New BSD, which I&#8217;ve included in the downloadable archive. </em></p>
<p>Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.integratedwebsystems.com/2009/10/simple-linq-to-sql-enhancements-with-t4-templating/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
