<?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>Invested Development &#187; .NET Framework</title>
	<atom:link href="http://devblog.stuartthompson.net/category/net-framework/feed/" rel="self" type="application/rss+xml" />
	<link>http://devblog.stuartthompson.net</link>
	<description>Thoughtful Approaches to Software Architecture</description>
	<lastBuildDate>Tue, 18 Oct 2011 17:08:09 +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>Serialize SQL parameters</title>
		<link>http://devblog.stuartthompson.net/2010/03/serialize-sql-parameters/</link>
		<comments>http://devblog.stuartthompson.net/2010/03/serialize-sql-parameters/#comments</comments>
		<pubDate>Mon, 15 Mar 2010 20:22:28 +0000</pubDate>
		<dc:creator>stuartthompson</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Snippets]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://devblog.stuartthompson.net/2010/03/serialize-sql-parameters/</guid>
		<description><![CDATA[Convert a collection of SQL parameters into a name:value string suitable for writing to a log. /// &#60;summary&#62; /// Serializes a collection of /// &#60;see cref=&#34;System.Data.SqlClient.SqlParameter&#34;/&#62;s. /// &#60;/summary&#62; /// &#60;param name=&#34;parameters&#34;&#62; /// The collection of parameters to serialize. /// &#60;/param&#62; /// &#60;returns&#62; /// A &#60;see cref=&#34;System.String&#34;/&#62; that contains the parameter values. /// &#60;/returns&#62; public string [...]]]></description>
			<content:encoded><![CDATA[<p>Convert a collection of SQL parameters into a name:value string suitable for writing to a log.</p>
</p>
<pre class="brush:csharp">/// &lt;summary&gt;
/// Serializes a collection of
/// &lt;see cref=&quot;System.Data.SqlClient.SqlParameter&quot;/&gt;s.
/// &lt;/summary&gt;
/// &lt;param name=&quot;parameters&quot;&gt;
/// The collection of parameters to serialize.
/// &lt;/param&gt;
/// &lt;returns&gt;
/// A &lt;see cref=&quot;System.String&quot;/&gt; that contains the parameter values.
/// &lt;/returns&gt;
public string SerializeSqlParameterCollection(
    SqlParameterCollection parameters)
{
    StringBuilder sb = new StringBuilder();
    foreach (SqlParameter parameter in parameters)
        sb.Append(
            String.Format(&quot;{0}:{1} &quot;,
                parameter.ParameterName, parameter.Value));
    return sb.ToString();
}</pre>
<div class="tweetthis" style="text-align:left;"><p> <a target="_blank" class="tt" href="http://twitter.com/home/?status=Serialize+SQL+parameters%3A+http%3A%2F%2Fdevblog.stuartthompson.net%2F%3Fp%3D141" title="Post to Twitter"><img class="nothumb" src="http://devblog.stuartthompson.net/wp-content/plugins/tweet-this/icons/en/twitter/tt-twitter-micro3.png" alt="Post to Twitter" /></a> <a target="_blank" class="tt" href="http://buzz.yahoo.com/buzz?targetUrl=http://devblog.stuartthompson.net/2010/03/serialize-sql-parameters/&amp;headline=Serialize+SQL+parameters" title="Post to Yahoo Buzz"><img class="nothumb" src="http://devblog.stuartthompson.net/wp-content/plugins/tweet-this/icons/en/buzz/tt-buzz-micro3.png" alt="Post to Yahoo Buzz" /></a> <a target="_blank" class="tt" href="http://delicious.com/post?url=http://devblog.stuartthompson.net/2010/03/serialize-sql-parameters/&amp;title=Serialize+SQL+parameters" title="Post to Delicious"><img class="nothumb" src="http://devblog.stuartthompson.net/wp-content/plugins/tweet-this/icons/en/delicious/tt-delicious-micro3.png" alt="Post to Delicious" /></a> <a target="_blank" class="tt" href="http://digg.com/submit?url=http://devblog.stuartthompson.net/2010/03/serialize-sql-parameters/&amp;title=Serialize+SQL+parameters" title="Post to Digg"><img class="nothumb" src="http://devblog.stuartthompson.net/wp-content/plugins/tweet-this/icons/en/digg/tt-digg-micro3.png" alt="Post to Digg" /></a> <a target="_blank" class="tt" href="http://www.facebook.com/share.php?u=http://devblog.stuartthompson.net/2010/03/serialize-sql-parameters/&amp;t=Serialize+SQL+parameters" title="Post to Facebook"><img class="nothumb" src="http://devblog.stuartthompson.net/wp-content/plugins/tweet-this/icons/en/facebook/tt-facebook-micro3.png" alt="Post to Facebook" /></a> <a target="_blank" class="tt" href="http://reddit.com/submit?url=http://devblog.stuartthompson.net/2010/03/serialize-sql-parameters/&amp;title=Serialize+SQL+parameters" title="Post to Reddit"><img class="nothumb" src="http://devblog.stuartthompson.net/wp-content/plugins/tweet-this/icons/en/reddit/tt-reddit-micro3.png" alt="Post to Reddit" /></a> <a target="_blank" class="tt" href="http://stumbleupon.com/submit?url=http://devblog.stuartthompson.net/2010/03/serialize-sql-parameters/&amp;title=Serialize+SQL+parameters" title="Post to StumbleUpon"><img class="nothumb" src="http://devblog.stuartthompson.net/wp-content/plugins/tweet-this/icons/en/su/tt-su-micro3.png" alt="Post to StumbleUpon" /></a></p></div>]]></content:encoded>
			<wfw:commentRss>http://devblog.stuartthompson.net/2010/03/serialize-sql-parameters/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Http Modules</title>
		<link>http://devblog.stuartthompson.net/2010/02/http-modules/</link>
		<comments>http://devblog.stuartthompson.net/2010/02/http-modules/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 20:07:31 +0000</pubDate>
		<dc:creator>stuartthompson</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[HttpModule]]></category>

		<guid isPermaLink="false">http://devblog.stuartthompson.net/2010/02/http-modules/</guid>
		<description><![CDATA[The .NET framework provides several mechanisms for extending the behaviors of web pages and other endpoints. One such technique is the http module. Modules are often either overlooked as a solution or are considered too heavyweight or scary for use. This is unfortunate as they are a powerful item in the ASP.NET development toolbox. An [...]]]></description>
			<content:encoded><![CDATA[<p align="justify">The <a title="Microsoft .NET Framework" href="http://www.microsoft.com/net/" target="_blank">.NET framework</a> provides several mechanisms for extending the behaviors of web pages and other endpoints. One such technique is the http module. Modules are often either overlooked as a solution or are considered too heavyweight or scary for use. This is unfortunate as they are a powerful item in the ASP.NET development toolbox.</p>
<p align="justify">An <a title="Http Modules on MSDN" href="http://msdn.microsoft.com/en-us/library/zec9k340(VS.71).aspx" target="_blank">http module</a> is a single unit of code that is executed as part of the web request pipeline. When a web request is received, the list of registered modules are afforded the opportunity to inject themselves at several stages in the execution pipeline. Each module has the opportunity to inspect or modify parts of the request before or after it is processed. This makes them a powerful mechanism for attaching custom behaviors. Modules also have a flexible activation model as they can be attached or detached via configuration allowing them to be enabled or disabled at will without affecting a production site.</p>
<p align="justify">The full source code for this example can be found <a title="Links to the http module sample in the code repository at stuartthompson.net." href="http://code.stuartthompson.net/public/Samples/Http%20Modules/">here</a>.</p>
<p align="justify"><strong>How to Create an HttpModule</strong>    <br />The ASP.NET Module type is in the Web category under the Add New Item dialog.</p>
<p><a href="http://devblog.stuartthompson.net/wp-content/uploads/2010/02/241229_tmp6C6D.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="241@229_tmp6C6D" border="0" alt="241@229_tmp6C6D" src="http://devblog.stuartthompson.net/wp-content/uploads/2010/02/241229_tmp6C6D_thumb.png" width="244" height="171" /></a></p>
<p align="justify">Remove the default sample code that is included in the template. The LogContext event handler is implemented in the template for demonstration purposes but is not used in this example. Your class should now look similar to the following:</p>
</p>
<pre class="brush:csharp">using System;
using System.Web;

namespace ModuleWebApp
{

    ///
<summary>
    /// Custom http module.
    /// </summary>

    public class MyNewModule : IHttpModule
    {

        #region IHttpModule Members

        public void Dispose() {}

        ///
<summary>
        /// Initializes the module.
        /// </summary>

        /// &lt;param name=&quot;context&quot;&gt;The application context.&lt;/param&gt;
        public void Init(HttpApplication context)
        {

        }

        #endregion

    }
}</pre>
</p>
<p align="justify"><strong>Initializing the Module</strong></p>
<p>Modules perform work by registering handlers for events in the request execution pipeline such as BeginRequest and EndRequest. It is within the event handlers that they perform their task. In the example below, the Init method is used to register handlers for the BeginRequest and EndRequest events.</p>
</p>
<pre class="brush:csharp">///
<summary>
/// Raised when the module is initialized.
/// </summary>

/// &lt;param name=&quot;context&quot;&gt;The application context.&lt;/param&gt;
public void Init(HttpApplication context)
{
    context.BeginRequest += new EventHandler(context_BeginRequest);
    context.EndRequest += new EventHandler(context_EndRequest);
}</pre>
</p>
<p align="justify"><strong>Implementing the Event Handlers and Finishing the Module</strong></p>
<p>Next provide implementations for the event handlers. This example module is going to calculate and display the time it takes to execute a page within the application. The code example below is for the completed module class. It contains the following changes:</p>
<ul>
<li>Declaration of a dictionary of stopwatches that stores the execution timers. </li>
<li>Implementation of the BeginRequest and EndRequest handlers to start and stop the timers. </li>
<li>Instantiation of the dictionary of timers in the Init method. </li>
</ul>
<pre class="brush:csharp">using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Web;

namespace ModuleWebApp
{

    /// &lt;summary&gt;
    /// A custom http module used to time request execution.
    /// &lt;/summary&gt;
    public class RequestTimer : IHttpModule
    {

        #region IHttpModule Members

        public void Dispose() { }

        /// &lt;summary&gt;
        /// Raised when the module is initialized.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;context&quot;&gt;The application context.&lt;/param&gt;
        public void Init(HttpApplication context)
        {
            _timers = new Dictionary&lt;Guid, Stopwatch&gt;();

            context.BeginRequest += new EventHandler(context_BeginRequest);
            context.EndRequest += new EventHandler(context_EndRequest);
        }

        #endregion

        #region Event Handlers

        /// &lt;summary&gt;
        /// Raised when the request begins.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;sender&quot;&gt;The source of the event; the &lt;see cref=&quot;System.Web.HttpApplication&quot; /&gt;.&lt;/param&gt;
        /// &lt;param name=&quot;e&quot;&gt;An &lt;see cref=&quot;System.EventsArgs&quot;/&gt; that contains event data.&lt;/param&gt;
        protected void context_BeginRequest(object sender, EventArgs e)
        {
            Guid timerId = Guid.NewGuid();
            Stopwatch timer = new Stopwatch();
            _timers.Add(timerId, timer);

            HttpContext.Current.Items.Add(EXECUTION_TIMER_KEY, timerId.ToString());

            timer.Start();
        }

        /// &lt;summary&gt;
        /// Raised when the request ends.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;sender&quot;&gt;The source of the event; the &lt;see cref=&quot;System.Web.HttpApplication&quot; /&gt;.&lt;/param&gt;
        /// &lt;param name=&quot;e&quot;&gt;An &lt;see cref=&quot;System.EventsArgs&quot;/&gt; that contains event data.&lt;/param&gt;
        protected void context_EndRequest(object sender, EventArgs e)
        {
            string timerId = HttpContext.Current.Items[EXECUTION_TIMER_KEY] as string;

            if (String.IsNullOrEmpty(timerId))
                return;

            Stopwatch timer = _timers[new Guid(timerId)];
            if (timer == null)
                return;

            timer.Stop();

            double elapsedSeconds = (timer.ElapsedMilliseconds) / (double)1000;

            HttpContext.Current.Response.Write(
                String.Format(
                    &quot;Request executed in {0} seconds ({1} ticks).&quot;,
                    elapsedSeconds.ToString(),
                    timer.ElapsedTicks.ToString()));
        }

        #endregion

        #region Fields

        /// &lt;summary&gt;
        /// The collection of execution timers.
        /// &lt;/summary&gt;
        private Dictionary&lt;Guid, Stopwatch&gt; _timers;

        #endregion

        #region Constants

        private const string EXECUTION_TIMER_KEY = &quot;__ExecutionTimer_Id&quot;;

        #endregion

    }

}</pre>
</p>
<p align="justify">Some of the concepts used here are beyond the scope of this discussion. Research the <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx">Stopwatch</a> class for more information on how to use timers. See the <a href="http://msdn.microsoft.com/en-us/library/system.web.httpcontext.aspx">HttpContext</a> class to learn more about <a href="http://msdn.microsoft.com/en-us/library/system.web.httprequest.aspx">request</a> and <a href="http://msdn.microsoft.com/en-us/library/system.web.httpresponse.aspx">response</a> objects. </p>
<p align="justify"><strong>Registering the Module</strong></p>
<p>The final step is to register the module so that it is instantiated and executed on every request. This is done via the web.config file. The &lt;system.web&gt; section contains an &lt;httpModules&gt; section. The registration configuration line for the module should be added to the &lt;httpModules&gt; section as shown below:</p>
</p>
<pre class="brush:xml"><system.web>
	<!-- ... other configuration information ... -->
	<httpmodules>
		<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
		<add name="CustomUrlParser" type="ModuleWebApp.CustomUrlParser, ModuleWebApp" />
    <add name="RequestTimer" type="ModuleWebApp.RequestTimer, ModuleWebApp" />
	</httpmodules>
</system.web></pre>
</p>
<p align="justify">That&#8217;s it! Running the web application should display the default.aspx page, which now shows the execution time in elapsed seconds (and ticks). This information is displayed at the end of every web request so it works on every page in the system. If you inspect the context_EndRequest handler you can see the following lines: </p>
<pre class="brush:csharp">
HttpContext.Current.Response.Write(
	String.Format(
		&quot;Request executed in {0} seconds ({1} ticks).&quot;,
		elapsedSeconds.ToString(),
		timer.ElapsedTicks.ToString()));</pre>
</p>
<p align="justify">The HttpContext class exposes the current Request and Response. These are the http request and response that are received from and sent to the client respectively. The execution time was displayed on the page because this handler wrote to the response object after the request had finished executing. The timer was started when the request started and stopped when the request ended. The time taken for the page to performing its processing and the request to finish is then displayed in the response. It is in this way that modules interact with all requests in the system and provide global level behaviors that are attached via configuration. </p>
<div class="tweetthis" style="text-align:left;"><p> <a target="_blank" class="tt" href="http://twitter.com/home/?status=Http+Modules%3A+http%3A%2F%2Fdevblog.stuartthompson.net%2F%3Fp%3D128" title="Post to Twitter"><img class="nothumb" src="http://devblog.stuartthompson.net/wp-content/plugins/tweet-this/icons/en/twitter/tt-twitter-micro3.png" alt="Post to Twitter" /></a> <a target="_blank" class="tt" href="http://buzz.yahoo.com/buzz?targetUrl=http://devblog.stuartthompson.net/2010/02/http-modules/&amp;headline=Http+Modules" title="Post to Yahoo Buzz"><img class="nothumb" src="http://devblog.stuartthompson.net/wp-content/plugins/tweet-this/icons/en/buzz/tt-buzz-micro3.png" alt="Post to Yahoo Buzz" /></a> <a target="_blank" class="tt" href="http://delicious.com/post?url=http://devblog.stuartthompson.net/2010/02/http-modules/&amp;title=Http+Modules" title="Post to Delicious"><img class="nothumb" src="http://devblog.stuartthompson.net/wp-content/plugins/tweet-this/icons/en/delicious/tt-delicious-micro3.png" alt="Post to Delicious" /></a> <a target="_blank" class="tt" href="http://digg.com/submit?url=http://devblog.stuartthompson.net/2010/02/http-modules/&amp;title=Http+Modules" title="Post to Digg"><img class="nothumb" src="http://devblog.stuartthompson.net/wp-content/plugins/tweet-this/icons/en/digg/tt-digg-micro3.png" alt="Post to Digg" /></a> <a target="_blank" class="tt" href="http://www.facebook.com/share.php?u=http://devblog.stuartthompson.net/2010/02/http-modules/&amp;t=Http+Modules" title="Post to Facebook"><img class="nothumb" src="http://devblog.stuartthompson.net/wp-content/plugins/tweet-this/icons/en/facebook/tt-facebook-micro3.png" alt="Post to Facebook" /></a> <a target="_blank" class="tt" href="http://reddit.com/submit?url=http://devblog.stuartthompson.net/2010/02/http-modules/&amp;title=Http+Modules" title="Post to Reddit"><img class="nothumb" src="http://devblog.stuartthompson.net/wp-content/plugins/tweet-this/icons/en/reddit/tt-reddit-micro3.png" alt="Post to Reddit" /></a> <a target="_blank" class="tt" href="http://stumbleupon.com/submit?url=http://devblog.stuartthompson.net/2010/02/http-modules/&amp;title=Http+Modules" title="Post to StumbleUpon"><img class="nothumb" src="http://devblog.stuartthompson.net/wp-content/plugins/tweet-this/icons/en/su/tt-su-micro3.png" alt="Post to StumbleUpon" /></a></p></div>]]></content:encoded>
			<wfw:commentRss>http://devblog.stuartthompson.net/2010/02/http-modules/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>.NET CLR in SQL Server 2005</title>
		<link>http://devblog.stuartthompson.net/2007/05/net-clr-in-sql-server-2005/</link>
		<comments>http://devblog.stuartthompson.net/2007/05/net-clr-in-sql-server-2005/#comments</comments>
		<pubDate>Fri, 04 May 2007 18:35:36 +0000</pubDate>
		<dc:creator>stuartthompson</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[CLR]]></category>
		<category><![CDATA[SQL Server 2005]]></category>

		<guid isPermaLink="false">http://stuartthompsontech.wordpress.com/?p=20</guid>
		<description><![CDATA[Of recent interest to me has been the ability to deploy user-defined managed functions, stored procedures, and other objects to SQL from within Visual Studio 2005. With the .NET CLR in SQL Server 2005, these managed functions can be written and deployed from within Visual Studio, even as part of an automated build process. In [...]]]></description>
			<content:encoded><![CDATA[<p>Of recent interest to me has been the ability to deploy user-defined managed functions, stored procedures, and other objects to SQL from within Visual Studio 2005. With the .NET CLR in SQL Server 2005, these managed functions can be written and deployed from within Visual Studio, even as part of an automated build process. In wanting to investigate this further, I&#8217;ve decided to write a few articles on how this technique is used and on how it may be useful to you. When I first heard about the ability to (essentially) deploy .NET assemblies into SQL Server and then have SQL Server make managed calls to them for use in queries I was skeptical, thinking this was yet another lost solution embarking upon a life quest for a problem to solve. However, several examples have since been drawn to my attention regarding the usefulness of this solution in exposing features of the richer .NET languages for use in advanced queries.</p>
<p>The first of these areas is that of regular expressions. Earlier this year, I came across an article describing how calls to the .NET 2.0 RegEx classes could be wrapped in a managed function for use in the where clause of a SQL query. My ears (eyes) perked up at this, for the idea of using regular expressions to match data in queries could add a massive amount of power to my SQL toolbox. Even better, because the call would be to the .NET classes, we already know that I&#8217;d be able to pre-compile the expressions if needed as that is a feature of that implementation. The rest of this article walks through a simple example for creating a C# Database Project in Visual Studio 2005, deploying a managed function developed in that project, and then writing a query to use that function for RegEx matching within the WHERE clause. For those interested in more information, the original article can be found here: <a href="http://msdn.microsoft.com/msdnmag/issues/07/02/SQLRegex/default.aspx">http://msdn.microsoft.com/msdnmag/issues/07/02/SQLRegex/default.aspx</a>.</p>
<p><strong>Creating a C# Database Project in Visual Studio </strong></p>
<p>First, open Visual Studio, then select File-&gt;New-&gt;Project. In the New Project dialog, expand the Visual C# node and select Database, then choose SQL Server Project from the list of templates. After the project is created, a dialog named Add Database Reference will ask for the specification of a database connection to work with for this project. This connection is used to deploy the project to SQL Server. Select a connection from the dialog or create a new one by clicking Add New Reference. I&#8217;ll assume for the brevity of this article that you either have a SQL database or can create a new one and that you can establish a database connection to it. Next, right-click the new SQL Server Project and select Add-&gt;New Item. Choose User-Defined Function from the Add New Item dialog and name it whatever you like; I used the class name RegexUtilities.cs in the test project I wrote for this article. This will add a snippet of code in the class that is a template for the function. Replace the entire contents of the code window with the following:</p>
<p><span style="font-size:10pt;font-family:Courier New;"><span style="color:blue;">using</span> System; </span><br />
<span style="font-size:10pt;font-family:Courier New;"><span style="color:blue;">using</span> System.Data; </span><br />
<span style="font-size:10pt;font-family:Courier New;"><span style="color:blue;">using</span> System.Data.SqlClient; </span><br />
<span style="font-size:10pt;font-family:Courier New;"><span style="color:blue;">using</span> System.Data.SqlTypes; </span><br />
<span style="font-size:10pt;font-family:Courier New;"><span style="color:blue;">using</span> System.Text.RegularExpressions; </span><br />
<span style="font-size:10pt;font-family:Courier New;"><span style="color:blue;">using</span> Microsoft.SqlServer.Server; </span></p>
<p><span style="font-size:10pt;font-family:Courier New;"><span style="color:blue;">public</span> <span style="color:blue;">partial</span> <span style="color:blue;">class</span> <span style="color:teal;">UserDefinedFunctions</span> { </span></p>
<p><span style="font-size:10pt;font-family:Courier New;">[Microsoft.SqlServer.Server.<span style="color:teal;">SqlFunction</span>] </span><br />
<span style="font-size:10pt;font-family:Courier New;"><span style="color:blue;">public</span> <span style="color:blue;">static</span> <span style="color:blue;">bool</span> Match(<span style="color:teal;">SqlChars</span> searchString, <span style="color:teal;">SqlString</span> regexPattern) { </span><br />
<span style="font-size:10pt;font-family:Courier New;"><span style="color:teal;">Regex</span> regex = <span style="color:blue;">new</span> <span style="color:teal;">Regex</span>(regexPattern.Value, <span style="color:teal;">RegexOptions</span>.Compiled | <span style="color:teal;">RegexOptions</span>.IgnorePatternWhitespace | <span style="color:teal;">RegexOptions</span>.Singleline); </span><br />
<span style="font-size:10pt;font-family:Courier New;"><span style="color:blue;">return</span> regex.IsMatch(<span style="color:blue;">new</span> <span style="color:blue;">string</span>(searchString.Value)); </span><br />
<span style="font-size:10pt;font-family:Courier New;">} </span></p>
<p><span style="font-size:10pt;font-family:Courier New;">} </span></p>
<p>The code here is a very simple wrapper around the Regex.IsMatch method and is adapted from the source code supplied by David Banister is his <a href="http://msdn.microsoft.com/msdnmag/issues/07/02/SQLRegex/default.aspx">original article</a>. I&#8217;ve cut a couple of things down for simplicity. Two parameters are passed to the method named Match: the string to search and the regex pattern to use in the match. The first line of the method creates a new compiled Regex object from the supplied pattern. The second line of codes returns a Boolean that indicates whether or not the supplied searchString was matched. First build the project with Ctrl+Shift+B and then right-click over the project in the Solution Explorer pane and select Deploy. This deploys the managed function to the SQL server you specified in the database connection for the project.</p>
<p>Now it&#8217;s time to test the function out in a query. First, let&#8217;s take the Social Security Number example and check that everything made it across OK. Open SQL Server Management Studio and connect to your database, then open a New Query window. Now type the following into the new query window:</p>
<p><span style="font-size:10pt;font-family:Courier New;"><span style="color:blue;">select</span> dbo<span style="color:gray;">.</span>Match<span style="color:gray;">(</span> N<span style="color:red;">&#8217;123-45-6789&#8242;</span><span style="color:gray;">,</span> N<span style="color:red;">&#8216;^\d{3}-\d{2}-\d{4}$&#8217;</span> <span style="color:gray;">) </span></span></p>
<p>You should receive the following error:</p>
<p><span style="font-size:8pt;font-family:Courier New;">Msg 6263, Level 16, State 1, Line 1 </span></p>
<p><span style="font-size:8pt;font-family:Courier New;">Execution of user code in the .NET Framework is disabled. Enable &#8220;clr enabled&#8221; configuration option. </span></p>
<p>This is because we have not yet enabled a state within SQL server that is disabled by default for security reasons. CLR code obviously wields great power and, as such, the ability to execute that code within the SQL process gives any would be malicious code a very nice process under which to run, and in an authenticated context. To run our example then, we must first instruct SQL server to allow CLR code to execute. This is achieved by running the following SQL within a query window:</p>
<p><span style="font-size:10pt;font-family:Courier New;"><span style="color:maroon;">sp_configure</span> <span style="color:red;">&#8216;clr enabled&#8217;</span><span style="color:gray;">,</span> 1 </span><br />
<span style="font-size:10pt;font-family:Courier New;">go </span></p>
<p><span style="font-size:10pt;color:blue;font-family:Courier New;">reconfigure </span><br />
<span style="font-size:10pt;font-family:Courier New;">go </span></p>
<p>A confirmation message should indicate that the &#8216;clr enabled&#8217; option was changed from 0 to 1. It indicates that RECONFIGURE should be run to install the change, hence the second SQL statement in the snippet above. Now we are ready to execute our Social Security Number example again. This time you should receive a single result for (No column name) with a value of 1. This indicates a match and was reported as a literal with no column name because of the structure of the statement we ran. Change part of the statement&#8217;s left parameter to be an invalid social security number and re-run the example to see that a 0 is received (indicating false) this time instead.</p>
<p>Now the real purpose of this article was the use of Regex in a WHERE clause and for this pick a table that contains a string column. Now construct a SQL statement similar to the following:</p>
<p><span style="font-size:10pt;font-family:Courier New;"><span style="color:blue;">select</span> dbo<span style="color:gray;">.</span>Match<span style="color:gray;">(</span>C<span style="color:gray;">.</span>[First Name]<span style="color:gray;">,</span> N<span style="color:red;">&#8216;^\w{8}$&#8217;</span><span style="color:gray;">),</span> C<span style="color:gray;">.</span>[First Name] </span><br />
<span style="font-size:10pt;font-family:Courier New;"><span style="color:blue;">from</span> C Customer </span></p>
<p>The statement above displays two columns of data, the first containing the result of the regular expression call, the second containing the customer first name. The regular expression in this example has been simplified to match words of eight characters in length (an oversimplification of the actual syntax, I know, but sufficient for the purposes of this article). Any customers with a first name of eight characters in length will be accompanied by a 1 in the left-hand column, the others with a 0.</p>
<p>That&#8217;s it for this article. A quick demonstration of how managed functions in SQL Server 2005 can open the power of the .NET class library for use within SQL.</p>
<div class="tweetthis" style="text-align:left;"><p> <a target="_blank" class="tt" href="http://twitter.com/home/?status=.NET+CLR+in+SQL+Server+2005%3A+http%3A%2F%2Fdevblog.stuartthompson.net%2F%3Fp%3D20" title="Post to Twitter"><img class="nothumb" src="http://devblog.stuartthompson.net/wp-content/plugins/tweet-this/icons/en/twitter/tt-twitter-micro3.png" alt="Post to Twitter" /></a> <a target="_blank" class="tt" href="http://buzz.yahoo.com/buzz?targetUrl=http://devblog.stuartthompson.net/2007/05/net-clr-in-sql-server-2005/&amp;headline=.NET+CLR+in+SQL+Server+2005" title="Post to Yahoo Buzz"><img class="nothumb" src="http://devblog.stuartthompson.net/wp-content/plugins/tweet-this/icons/en/buzz/tt-buzz-micro3.png" alt="Post to Yahoo Buzz" /></a> <a target="_blank" class="tt" href="http://delicious.com/post?url=http://devblog.stuartthompson.net/2007/05/net-clr-in-sql-server-2005/&amp;title=.NET+CLR+in+SQL+Server+2005" title="Post to Delicious"><img class="nothumb" src="http://devblog.stuartthompson.net/wp-content/plugins/tweet-this/icons/en/delicious/tt-delicious-micro3.png" alt="Post to Delicious" /></a> <a target="_blank" class="tt" href="http://digg.com/submit?url=http://devblog.stuartthompson.net/2007/05/net-clr-in-sql-server-2005/&amp;title=.NET+CLR+in+SQL+Server+2005" title="Post to Digg"><img class="nothumb" src="http://devblog.stuartthompson.net/wp-content/plugins/tweet-this/icons/en/digg/tt-digg-micro3.png" alt="Post to Digg" /></a> <a target="_blank" class="tt" href="http://www.facebook.com/share.php?u=http://devblog.stuartthompson.net/2007/05/net-clr-in-sql-server-2005/&amp;t=.NET+CLR+in+SQL+Server+2005" title="Post to Facebook"><img class="nothumb" src="http://devblog.stuartthompson.net/wp-content/plugins/tweet-this/icons/en/facebook/tt-facebook-micro3.png" alt="Post to Facebook" /></a> <a target="_blank" class="tt" href="http://reddit.com/submit?url=http://devblog.stuartthompson.net/2007/05/net-clr-in-sql-server-2005/&amp;title=.NET+CLR+in+SQL+Server+2005" title="Post to Reddit"><img class="nothumb" src="http://devblog.stuartthompson.net/wp-content/plugins/tweet-this/icons/en/reddit/tt-reddit-micro3.png" alt="Post to Reddit" /></a> <a target="_blank" class="tt" href="http://stumbleupon.com/submit?url=http://devblog.stuartthompson.net/2007/05/net-clr-in-sql-server-2005/&amp;title=.NET+CLR+in+SQL+Server+2005" title="Post to StumbleUpon"><img class="nothumb" src="http://devblog.stuartthompson.net/wp-content/plugins/tweet-this/icons/en/su/tt-su-micro3.png" alt="Post to StumbleUpon" /></a></p></div>]]></content:encoded>
			<wfw:commentRss>http://devblog.stuartthompson.net/2007/05/net-clr-in-sql-server-2005/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

