<?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; visual studio</title>
	<atom:link href="http://www.integratedwebsystems.com/tag/visual-studio/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.integratedwebsystems.com</link>
	<description>My Little .NET Sandbox</description>
	<lastBuildDate>Thu, 19 Jan 2012 20:37:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<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...]]></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>
		<item>
		<title>Problems Installing Silverlight 3?</title>
		<link>http://www.integratedwebsystems.com/2009/07/installing-silverlight-3-your-silverlight-developer-components-are-out-of-date/</link>
		<comments>http://www.integratedwebsystems.com/2009/07/installing-silverlight-3-your-silverlight-developer-components-are-out-of-date/#comments</comments>
		<pubDate>Sat, 11 Jul 2009 17:37:12 +0000</pubDate>
		<dc:creator>Nathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[installing]]></category>
		<category><![CDATA[silverlight3]]></category>
		<category><![CDATA[visual studio]]></category>

		<guid isPermaLink="false">http://www.integratedwebsystems.com/?p=299</guid>
		<description><![CDATA[So for those of you who have already played around with Silverlight...]]></description>
			<content:encoded><![CDATA[<p>So for those of you who have already played around with Silverlight 2 and saw the newer version Silverlight 3 release this week, you might have some issues installing it. I had the same problem on two different machines while trying to install the new runtimes. The first system was 32bit Windows XP with Silverlight2 Tools and Silverlight2 installed. The second was 64bit Windows 7 RC1 with the same Silverlight components.</p>
<p>  <span id="more-299"></span> <strong>Before you begin</strong>, you should understand that from my observation while doing this, you will need to upgrade all your Silverlight 2 projects to Silverlight 3. Visual Studio simply didn’t open my existing Silverlight 2 projects without upgrading them first. The upgrade itself, however, is painless. Just be aware that when you deploy your next release, your end-users will also need to upgrade their runtime.
</p>
<p>Naturally, I just wanted to start out by installing the <a href="http://www.microsoft.com/silverlight/resources/install.aspx" target="_blank">Silverlight3 runtime</a>.</p>
<p><a href="http://www.integratedwebsystems.com/wp-content/uploads/image11.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" border="0" alt="image" src="http://www.integratedwebsystems.com/wp-content/uploads/image_thumb1.png" width="244" height="115" /></a></p>
<p>When clicking Install Now, I received the first error.&#160; “Your silverlight developer components are out of date.” That seemed odd considering I’m just installing runtime components right? But whatever, so I assume that i need to install the Visual Studio tools for Silverlight 3.&#160; So I continue to do that.</p>
<p><a href="http://www.integratedwebsystems.com/wp-content/uploads/image12.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.integratedwebsystems.com/wp-content/uploads/image_thumb2.png" width="244" height="115" /></a></p>
<p>I downloaded and installed the released tools <a href="http://www.microsoft.com/downloads/details.aspx?familyid=9442b0f2-7465-417a-88f3-5e7b5409e9dd&amp;displaylang=en" target="_blank">Silverlight3_Tools.exe</a>.&#160; And then I re-run the runtime installer, but now there’s a new problem. I get this error.</p>
<p><a href="http://www.integratedwebsystems.com/wp-content/uploads/image13.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.integratedwebsystems.com/wp-content/uploads/image_thumb3.png" width="244" height="115" /></a></p>
<p>Well that seems odd.&#160; So I just assume that my existing runtime need to be removed, so I continue to do that.</p>
<p><strong>**EDIT** </strong>After doing this, I realized that it is better to uninstall both Silverlight and Silverlight Tools for Visual Studio. Otherwise, you’ll need to re-install the tools a second time in order for the debugger to work.</p>
<p><a href="http://www.integratedwebsystems.com/wp-content/uploads/image14.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.integratedwebsystems.com/wp-content/uploads/image_thumb4.png" width="644" height="480" /></a></p>
<p>Finally, I re-run the runtime installer, and it works fine. Follow this by installing Silverlight 3 Tools for Visual Studio.</p>
<p><a href="http://www.integratedwebsystems.com/wp-content/uploads/image15.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.integratedwebsystems.com/wp-content/uploads/image_thumb5.png" width="244" height="115" /></a></p>
<p>So it’s kind of a pain in the ass for some of us; I’m assuming that it’s probably just because I had the older developer tools installed. I tested my wife’s computer which had only Silverlight 2 runtime and it seemed to run fine. Hopefully the rest of them will run as smoothly as hers. Anyways, I hope some of you find this useful.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.integratedwebsystems.com/2009/07/installing-silverlight-3-your-silverlight-developer-components-are-out-of-date/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Regex Groups and Find/Replace Tagged Expressions</title>
		<link>http://www.integratedwebsystems.com/2009/05/regex-groups-for-tagged-expressions/</link>
		<comments>http://www.integratedwebsystems.com/2009/05/regex-groups-for-tagged-expressions/#comments</comments>
		<pubDate>Wed, 13 May 2009 18:25:39 +0000</pubDate>
		<dc:creator>Nathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Group]]></category>
		<category><![CDATA[Regex]]></category>
		<category><![CDATA[regular expression]]></category>
		<category><![CDATA[tagged expression]]></category>
		<category><![CDATA[visual studio]]></category>

		<guid isPermaLink="false">http://www.integratedwebsystems.com/?p=228</guid>
		<description><![CDATA[Every once in awhile I have a need to use regular expressions...]]></description>
			<content:encoded><![CDATA[<p>Every once in awhile I have a need to use regular expressions in code. I love using them in Visual Studio find/replace. And one of my favorite features in the find/replace dialog is tagged expressions. This allows me to make a regular expression match and at the same time extract pieces of it for use in my replace with expression.</p>
<p>So today, I&#8217;m toying around with Regex and find a need to have the same behavior in code. The difference is, tagged expressions in code are referred to as matching groups. Normally you would use braces for your tagged expressions in a find/replace dialog; but in code, you would use parentheses instead.<span id="more-228"></span></p>
<p>(BTW, These are very simplified and by no means an end-all match expression for this scenario).</p>
<p>For today&#8217;s search, I need an expression that would give me a table name from an insert or update t-sql statement. Simple enough right?  With this expression: &#8220;<em>insert into [a-zA-Z0-9_]+|update [a-zA-Z0-9_]+ </em>&#8221; I can validate either of the two statements. But I really want the table name used in this match.  In a tagged expression, I would&#8217;ve used &#8220;<em>insert into {[a-zA-Z0-9_]+}|update {[a-zA-Z0-9_]+}</em> &#8221; so I could use \1 and \2 for my table name in the replace expression. But in code, we&#8217;ll need to use groups. So the regex will look like this, &#8220;<em>insert into ([a-zA-Z0-9_]+)|update ([a-zA-Z0-9_]+)</em> &#8220;.</p>
<p>Fortunately in our search text, it can be only insert or update, not both. So in code, I could match a statement like this:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">Regex regex = new Regex("insert into ([a-zA-Z0-9_]+)|update ([a-zA-Z0-9_]+) ", RegexOptions.IgnoreCase);

if (regex.IsMatch(sql_command))
{
    string table_name = regex.Match(sql_command).Groups[1].Value;
}</pre>
<p>The Groups collection contains the sub matches starting with the second element.  This is handy; so you don&#8217;t have to re-search your match with a second expression. In our scenario, only one group match will ever exist, so using Groups[1] gets me the table name.</p>
<p>You can get more info from <a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.groupcollection.aspx" target="_blank">the MSDN docs.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.integratedwebsystems.com/2009/05/regex-groups-for-tagged-expressions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

