<?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; Sql Server</title>
	<atom:link href="http://www.integratedwebsystems.com/tag/sql-server/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>Connecting to Sql Server using Impersonation from Asp.Net</title>
		<link>http://www.integratedwebsystems.com/2009/06/connecting-to-sql-server-using-impersonation-from-asp-net/</link>
		<comments>http://www.integratedwebsystems.com/2009/06/connecting-to-sql-server-using-impersonation-from-asp-net/#comments</comments>
		<pubDate>Tue, 16 Jun 2009 16:13:03 +0000</pubDate>
		<dc:creator>Nathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[Sql Server]]></category>
		<category><![CDATA[Active Directory]]></category>
		<category><![CDATA[Delegation]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://www.integratedwebsystems.com/?p=276</guid>
		<description><![CDATA[So you have an Asp.Net application that needs to authenticate its users...]]></description>
			<content:encoded><![CDATA[<p>So you have an Asp.Net application that needs to authenticate its users to Active Directory, and you also want to use their credentials for connecting to a database server. It&#8217;s pretty logical thing to do in an enterprise environment where you would normally control all your user privileges using Active Directory. This is especially nice since you also don&#8217;t have to put sensitive credentials in your web.config file. </p>
<p> <span id="more-276"></span>Before I begin, here are a few links worth mentioning:
</p>
<p>How To: Use Impersonation and Delegation in ASP.NET 2.0    <br /><a title="http://msdn.microsoft.com/en-us/library/ms998351.aspx" href="http://msdn.microsoft.com/en-us/library/ms998351.aspx">http://msdn.microsoft.com/en-us/library/ms998351.aspx</a></p>
<p>How To: Use Protocol Transition and Constrained Delegation in ASP.NET 2.0    <br /><a title="http://msdn.microsoft.com/en-us/library/ms998355.aspx" href="http://msdn.microsoft.com/en-us/library/ms998355.aspx">http://msdn.microsoft.com/en-us/library/ms998355.aspx</a></p>
<p>How To: Use Windows Authentication in ASP.NET 2.0    <br /><a title="http://msdn.microsoft.com/en-us/library/ms998358.aspx" href="http://msdn.microsoft.com/en-us/library/ms998358.aspx">http://msdn.microsoft.com/en-us/library/ms998358.aspx</a></p>
<p>This turns out to be a very easy thing to do; it&#8217;s just hard to find any simple information about it. Authenticating to Asp.Net using Windows and using impersonation gives us the ability to let the worker process inherit privileges of the authenticated user. All it takes is a few web.config changes.</p>
<p>First, you need to change authentication mode to Windows. under &lt;system.web&gt; set &lt;authentication mode=&quot;Windows&quot;/&gt;</p>
<p>It&#8217;s also a good idea to force anonymous users to authentication. Do that by changing the &lt;authorization&gt; config.</p>
<p>Now we have users authenticating to the Windows network. Now lets enable impersonation so the worker process will adopt privileges for their requests. Set &lt;identity impersonation=&quot;true&quot;/&gt;</p>
<p>When you’re done, your web.config file should resemble this.</p>
<pre class="brush: xml; toolbar: false;">&lt;system.web&gt;

    &lt;authentication mode=&quot;Windows&quot;/&gt;

    &lt;identity impersonate=&quot;true&quot;/&gt;

    &lt;authorization&gt;
        &lt;deny users=&quot;?&quot;/&gt;
    &lt;/authorization&gt;

&lt;/system.web&gt;</pre>
<p>All that’s left is putting the proper delegation rules in place for your web server to hand out Windows tokens (at least that’s my understanding). In Active Directory Users and Computers from a domain controller or accessible machine, right click and go to the properties of the web server that will be using impersonation.&#160; Click the Delegation tab and select the third option. Trust this computer for delegation to specified services only.&#160; Select Use any authentication protocol.</p>
<p><a href="http://www.integratedwebsystems.com/wp-content/uploads/image10.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" border="0" alt="image" align="right" src="http://www.integratedwebsystems.com/wp-content/uploads/image_thumb.png" width="408" height="470" /></a>Then browse for a machine account for the database server you want to access with the impersonated accounts. Choose the MSSQLSvc with the port number next to it. (Ours had two services).&#160; Then click OK to apply the changes.</p>
<p>You may need to reset IIS or wait a few minutes for the AD changes to propagate. We reset ours from a command line with “iisreset”.</p>
<p>That should be it!&#160; You should now be able to browse your web app and access the database using your AD Windows Account.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.integratedwebsystems.com/2009/06/connecting-to-sql-server-using-impersonation-from-asp-net/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Fixing a Corrupt Sql Server 2005 Install</title>
		<link>http://www.integratedwebsystems.com/2009/04/fixing-a-corrupt-sql-server-2005-install/</link>
		<comments>http://www.integratedwebsystems.com/2009/04/fixing-a-corrupt-sql-server-2005-install/#comments</comments>
		<pubDate>Mon, 13 Apr 2009 17:14:40 +0000</pubDate>
		<dc:creator>Nathan</dc:creator>
				<category><![CDATA[2005]]></category>
		<category><![CDATA[Sql Server]]></category>
		<category><![CDATA[Install]]></category>

		<guid isPermaLink="false">http://www.integratedwebsystems.com/index.php/2009/04/fixing-a-corrupt-sql-server-2005-install/</guid>
		<description><![CDATA[Okay, so I&#39;ve been fighting with this workstation that has a corrupt...]]></description>
			<content:encoded><![CDATA[<p>Okay, so I&#39;ve been fighting with this workstation that has a corrupt Sql Server 2005 install, and I&#39;m unable to re-install or remove the old install. I&#39;ve tried manually removing registry keys and the whole nine. I even found a few references to articles posted about the topic.</p>
<p>I finally figured it out, so I thought I&#39;d share since I&#39;ve had to do this more than once. My situation is that I have a machine with Sql Management Studio Express installed and I needed the full Management Studio installed. So while uninstalling a few components, I must&#39;ve done it in the wrong order, my Sql Server Add/Remove just disappeared.&nbsp; So then I was unable to cleanly uninstall the software.</p>
<p>When I tried to re-install the client components, I kept getting this error:</p>
<blockquote>
<p>A component that you have specified in the ADD_LOCAL property is already installed. To upgrade the existing component, refer to the template.ini and set the UPGRADE property to the name of the component.</p>
</blockquote>
<p><a href="http://www.integratedwebsystems.com/wp-content/uploads/sqlerr.png"><img alt="sqlerr" src="http://www.integratedwebsystems.com/wp-content/uploads/sqlerr-thumb.png" style="border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; width: 644px; height: 89px; " /></a></p>
<p>Sounds a bit greek to me.&nbsp; But after a few minutes of reviewing google results for the subject, I found this article.</p>
<p><a href="http://www.techtalkz.com/microsoft-sql-server/163115-uninstall-sql-2005-studio-express-so-i-can-install-sql-2005-t.html" title="http://www.techtalkz.com/microsoft-sql-server/163115-uninstall-sql-2005-studio-express-so-i-can-install-sql-2005-t.html">http://www.techtalkz.com/microsoft-sql-server/163115-uninstall-sql-2005-studio-express-so-i-can-install-sql-2005-t.html</a></p>
<p>In the last post, he mentions that he downloaded the Windows Installer Cleanup Utility and it worked.&nbsp; So I thought I&#39;d give it a whirl since my local install was pretty much a handful of nastiness.&nbsp; So I downloaded the utility from <a href="http://support.microsoft.com/kb/290301" target="_blank">Microsoft&#39;s web site</a>.</p>
<p>After installing, I ran the utility, found the missing add/remove items and removed them.&nbsp; Easy peasy&#8230;</p>
<p>Finally I restarted the Sql 2005 installer as normal, and the Client Components install went through without a problem.</p>
<p>Now I can get some work done&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.integratedwebsystems.com/2009/04/fixing-a-corrupt-sql-server-2005-install/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

