<?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>Nullable Code</title>
	<atom:link href="http://nullablecode.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://nullablecode.com</link>
	<description>Software Design, Architecture Microsoft .Net &#38; SQL Server solutions!</description>
	<lastBuildDate>Thu, 05 Jan 2012 05:15:03 +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>Consuming a REST Service</title>
		<link>http://nullablecode.com/2011/11/consuming-a-rest-service/</link>
		<comments>http://nullablecode.com/2011/11/consuming-a-rest-service/#comments</comments>
		<pubDate>Tue, 01 Nov 2011 10:28:06 +0000</pubDate>
		<dc:creator>nullablecode</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Everything]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[Service]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://nullablecode.com/?p=642</guid>
		<description><![CDATA[THERE are certainly lots of articles around that explain how to create your own WCF REST service. However, I couldn&#8217;t<a href="http://nullablecode.com/2011/11/consuming-a-rest-service/" class="searchmore">Read the Rest...</a><div class="clr"></div>]]></description>
			<content:encoded><![CDATA[<p>THERE are certainly lots of articles around that explain how to create your own WCF REST service. However, I couldn&#8217;t find many that explained how to consume a REST service. So this is what I&#8217;ll concentrate on in this article&#8230; so read on..</p>
<p><span id="more-642"></span></p>
<p><span style="text-decoration: underline;"><strong><span style="font-size: medium;">Background Info</span></strong></span></p>
<p>The reason I&#8217;m writing this article is because I recently designed an solution that utilises a RESTful API Service. This solution communicates with the RESTful service to GET and POST data using their given API. Here is a quick link to the wiki if you want to learn more about the <a href="http://en.wikipedia.org/wiki/Representational_State_Transfer">REST architecture</a>.</p>
<p><strong><span style="font-size: medium;">REST API</span></strong></p>
<p>REST APIs are pretty cool when you think about it. There are already lots of sites out there provide an API for developers to communicate with to access their services. Below is a quick list to some well known sites and their API documentation:</p>
<ul>
<li><a href="https://dev.twitter.com/docs/api" target="_blank">Twitter API</a></li>
<li><a href="https://developer.linkedin.com/rest" target="_blank">LinkedIn API</a></li>
<li><a href="http://code.google.com/apis/maps/documentation/webservices/index.html" target="_blank">Google Maps API</a></li>
<li><a href="http://www.flickr.com/services/api/" target="_blank">Flickr API</a></li>
<li><a href="https://www.dropbox.com/developers/reference/api" target="_blank">Dropbox API</a></li>
</ul>
<p>With APIs you can integrate any data service exposed over the web and have it seemlessly integrated into your very own application!</p>
<p><span style="font-size: medium;"><strong>REST API &#8211; Requests</strong></span></p>
<p>Accessing the API is pretty easy. Especially if you just want to grab data from the RESTful service. Communication with a REST API is done using basic HTTP GET, POST, PUT and DELETE requests. And for this reason, a REST API can be access via your web browser for all GET requests.</p>
<p>:: Here&#8217;s a <strong>Twitter </strong>example &#8211; <a href="http://search.twitter.com/search.json?q=clouds" target="_blank">http://search.twitter.com/search.json?q=clouds</a><br />
Navigating to the above URL, you are basically executing a Twitter search on the word &#8216;clouds&#8217;. Twitter then provides you a response to your HTTP GET request in the form of JSON text. JSON and XML are two most common REST response types.</p>
<p>::Here&#8217;s a <strong>Google Maps </strong>example - <a href="http://maps.googleapis.com/maps/api/directions/xml?origin=sydney city&amp;destination=melbourne&amp;sensor=false" target="_blank">http://maps.googleapis.com/maps/api/directions/xml?origin=sydney city&amp;destination=melbourne&amp;sensor=false</a><br />
Navigating to the above URL, you are querying the Google Map directions API for directions to Melbourne from Sydney! Here the response is provided as XML</p>
<p><span style="text-decoration: underline;"><strong><span style="font-size: medium;">Steps to consume a REST service</span></strong></span></p>
<p>Here is a the list of topics that will be covered, and by the end of this article, hopefully you have enough information to integrate this solution into your own applications!</p>
<ol>
<li>Setting up the WCF REST Starter Kit for Visual Studio</li>
<li>Building your HttpClient</li>
<li>Initiate HTTP GET requests</li>
<li>Generate .Net classes from the REST Response (XML)</li>
<li>Transform the response into your .Net classes</li>
<li>Sample POST</li>
<li>Sample PUT</li>
<li>Sample DELETE</li>
</ol>
<p><span style="font-size: medium;"><strong>1. Setting up the WCF REST Starter Kit for Visual Studio</strong></span></p>
<p>First up you will need some Microsoft libraries&#8230; Goto the <a href="http://msdn.microsoft.com/en-us/netframework/cc950529" target="_blank">Microsoft WCF REST website</a> and download the latest WCF REST Starter Kit. Install the kit.  Once done, you will have 2 libraries that you will need to reference, these DLLs are located in the folder C:\Program Files\Microsoft WCF REST\WCF REST Starter Kit Preview 2\Assemblies\</p>
<p>These are:</p>
<ul>
<li>Microsoft.Http and</li>
<li>Microsoft.Http.Extensions</li>
</ul>
<p>Add these as library references to your project.</p>
<p><span style="font-size: medium;"><strong>2. Building your HttpClient</strong></span></p>
<p>Next up, lets create a static method to return a httpClient. You will be using the httpClient object to create and process all your API calls to the REST Service. Create a class called <strong>HttpClientManager </strong>and add the following <em><strong>&#8216;using&#8217; </strong></em>statement for the two libraries you just referenced.</p>
<pre class="brush: csharp; title: ; notranslate">

using Microsoft.Http;
using System.Xml.Serialization;
</pre>
<p>This class will have one static method that returns a HttpClient object all set up and ready to go. There are 3 main parts to this function, and depending on your environment and infrastructure you can choose to include or skip certain sections. The 3 sections are:</p>
<ol>
<li>Setting the base url for the httpClient</li>
<li>Setting the Proxy configurations</li>
<li>Setting the Authentication headers for the REST service</li>
</ol>
<p><strong>1. Setting the base url for the httpClient</strong></p>
<p>Each API library will have a standard base url for which all other API calls are &#8216;nested&#8217; under this url. For example, our Google Map directions API has a base URL of:  <a href="http://maps.googleapis.com/maps/api/">http://maps.googleapis.com/maps/api/</a></p>
<p><strong>2. Setting the Proxy configurations</strong></p>
<p>If your corporate network contains a firewall/proxy. You may need to configure your httpClient to use the correct Proxy Credentials.  You can optionally skip this step if no proxy is required.</p>
<p><strong>3. Setting the Authentication headers for the REST service</strong></p>
<p>Most API services out there will require some sort of authentication. This will most likely be a token or some sort, which may or may not include MD5 hashes, other encryption, salts and/or other secure data transfers in order for the remote service to recognise who you really are. You can optionally skip this step if no authentication is required by the API service.</p>
<p>Below is the snippet that covers point one and two above.</p>
<pre class="brush: csharp; title: ; notranslate">
public class HttpClientManager
{

    public static Microsoft.Http.HttpClient GetHttpClient()
    {
        string clientURL = &quot;http://maps.googleapis.com/maps/api/&quot;;
        Microsoft.Http.HttpClient httpClient = new Microsoft.Http.HttpClient(clientURL);
        httpClient.DefaultHeaders.ContentType = &quot;application/xml&quot;;

        // PROXY - If required
        System.Net.WebProxy p = new System.Net.WebProxy(proxy, int.Parse(proxyPort));
        p.Credentials = new System.Net.NetworkCredential(userName, password, domain);
        httpClient.TransportSettings.Proxy = p;

        return httpClient;
    }
}
</pre>
<p>If Authentication is required, you will need to determine what data to pass with the HTTP Request; and how. In the following code, we add the &#8216;authentication string&#8217; as part of the HTTP Request Header called &#8216;Authorization&#8217;.</p>
<pre class="brush: csharp; title: ; notranslate">
        // PROXY - If required
        // .....

        // AUTHENTICATION
        string authString = &quot;xxxxxxxx&quot;;
        httpClient.DefaultHeaders[&quot;Authorization&quot;] = &quot;Basic &quot; + Convert.ToBase64String(Encoding.Default.GetBytes(authString));

        return httpClient;
</pre>
<p>Keep in mind, the API service you use will outline what data needs to be passed; the format they expect, and any additional processing that is required from the authentication string.</p>
<p>That&#8217;s it.  Now you have a re-usable static method to call whenever you need a new HttpClient object.</p>
<p>Next up, you will be using the method above to grab a HttpClient object, and then writing a few additional lines of code to perform the various API calls for GET, POST, PUT and DELETE requests!</p>
<p><span style="font-size: medium;"><strong>3. Initiate HTTP GET requests</strong></span></p>
<p>Lets jump right into the GET request.  Your first API GET request will programmatically call Google Maps&#8217; Directions API and perform a search. The structure of your method will be of the following:</p>
<ul>
<li>Grab a new HttpClient</li>
<li>Determine the URL of the API call &#8211; and add this to the HttpClient&#8217;s Base URL address</li>
<li>Determine any Query String Parameters that need to be passed through &#8211; add this to the API path</li>
<li>Perform the API GET request</li>
<li>Read the Response</li>
</ul>
<p>Below is the simplest GET request you can have. It adds to the Base URL &#8211; the API location &#8216;directions/xml&#8217;. And then appends the search parameters as query strings.  The Base URL + the API location + the Parameter string makes up the full URL to Google&#8217;s Direction Search API.</p>
<p>To initiate the request, we invoke the Get() method on the httpClient object.<br />
This returns a HttpResponseMessage object for us to interpret, and handle the response data as necessary. Here we are just storing the returned XML response into a local string variable.<span style="font-size: medium;"><strong> </strong></span></p>
<pre class="brush: csharp; title: ; notranslate">
    public static class GoogleDirectionsManager
    {

        public static void GetDirections(string origin, string destination)
        {
            HttpClient httpClient = HttpClientManager.GetHttpClient();

            // I'm sure you can think of a better way of managing these parameters!
            string url = &quot;directions/xml&quot;;
            string param = &quot;?origin=&quot; + origin + &quot;&amp;destination=&quot; + destination + &quot;&amp;sensor=false&quot;;

            HttpResponseMessage resp = httpClient.Get(url + param);
            string respString = resp.Content.ReadAsString();
        }
    }
</pre>
<p>To finish off our GetDirections() method, we are missing one elegant part&#8230; the Entity (or POCO) transformation.</p>
<p>The above method returns the response as XML. If your application wants to manipulate the XML directly, then thats all you require. However going one step further I will show how you can easily transfrom the XML into .Net Entity Classes. Not only does this provide extra readability, you can pass these entity objects to other layers of your application in a nice and clean manner.</p>
<p><span style="font-size: medium;"><strong>3. Generate .Net classes from the REST Response (XML)</strong></span></p>
<ul>
<li>First up: Run your application, and grab the XML response as a string. Copy this into Notepad.  And save the file. Lets call it &#8220;Direction.xml&#8221;.</li>
<li>Open up Visual Studio&#8217;s command prompt (this is not the stand windows cmd promt). You will find the shortcut in your Start Menu -&gt; Microsoft Visual Studio -&gt; Visual Studio Tools -&gt; Visual Studio Command Prompt menu</li>
<li>Goto the directory that you saved the &#8220;Direction.xml&#8221; file into</li>
<li>Run the following two commands in order, one after the other:
<ul>
<li>xsd Direction.xml</li>
<li>xsd Direction.xsd /c</li>
</ul>
</li>
<li>The first command creates a XSD file from the XML file</li>
<li>The second command creates a CS class file from the XSD file</li>
</ul>
<p>Once you have done that, you will find a &#8220;Directions.CS&#8221; file &#8211; Copy/Paste the contents of the CS file into your application.  That&#8217;s it!!  You have generated a &#8216;Direction&#8217; C# class from your XML response!</p>
<p><span style="font-size: medium;"><strong>5. Transform the response into your .Net classes</strong></span></p>
<p>To do this, instead of reading the <strong>HttpResponseMessage </strong>as a string, we need to use the <strong>ReadAsXmlSerializable</strong>() method, and then define the type of object we want to transform the response text into. To achieve this, replace the above <strong>ReadAsString</strong>() method with a call to <strong>ReadAsXmlSerializable</strong>() as shown below.  Declare the Class type we generated in step.4 &#8212; and thats it.</p>
<p>The ReadAsXMLSerializable() method will do all the work, and at the end, you will have a fully functional <strong>Direction Object </strong>with all properties and nested classes in one!!</p>
<pre class="brush: csharp; title: ; notranslate">
    public static class GoogleDirectionsManager
    {
        public static void GetDirections(string origin, string destination)
        {
            HttpClient httpClient = HttpClientManager.GetHttpClient();

            // I'm sure you can think of a better way of managing these parameters!
            string url = &quot;directions/xml&quot;;
            string param = &quot;?origin=&quot; + origin + &quot;&amp;destination=&quot; + destination + &quot;&amp;sensor=false&quot;;

            HttpResponseMessage resp = httpClient.Get(url + param);

            Entities.Direction d = resp.Content.ReadAsXmlSerializable&lt;Entities.Direction&gt;();
        }
    }
</pre>
<p><span style="font-size: medium;"><strong>6. Sample POST</strong></span></p>
<p>That&#8217;s all the hard part done!  The other Http Request methods are pretty straight foward, all you need to do is invoke the corresponding httpClient method of either Post(), Put() or Delete().</p>
<p>A Http POST request is all about &#8216;creating&#8217; new data via the REST Service. Where a Http PUT request is all about &#8216;updating&#8217; existing data. And of course Http DELETE removes existing data.</p>
<p>Http POST  and PUT will require ONE additional step. And that is to include the data you want to create or update with the API call. In the examples below, I will refer to a generic Ticketing system instead of Google Map.  POST will allow our system to POST a Ticket via XML to the API &#8211; in order to create a new ticket in their system.  Likewise a PUT will allow our system to UPDATE a Ticket (also via XML) to the API &#8211; in order to update an existing record.</p>
<p>Sending data via a POST/PUT command requires the data to be included in the Http Request as part of its <strong>Http Content</strong>. Also known as the Http Body.  Just like sending an email, there is a subject section and a body section!</p>
<p>Below is an example of how you will POST a new Ticket with 2 simple properties (Email and Comment) to the API located in the sub-path (tickets.xml). :</p>
<p><span style="color: #ff0000;"><strong>note</strong></span>: The structure of the content is purely dependant on the REST Service. You will need to consult the API to know what structure and data to pass through.</p>
<pre class="brush: csharp; title: ; notranslate">
        public static void CreateTicket(Entities.Ticket ticket)
        {
            HttpClient httpClient = HttpClientManager.GetHttpClient();

            // I'm sure you can think of a better way of generating the XML! <img src='http://nullablecode.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />
            HttpContent content = Microsoft.Http.HttpContent.Create(&quot;&lt;ticket&gt;&lt;email&gt;test@test.com&lt;/email&gt;&lt;comment&gt;my comments are here!&lt;/comment&gt;&lt;/ticket&gt;&quot;
                                                            , &quot;application/xml&quot;);

            string url = &quot;tickets.xml&quot;;
            HttpResponseMessage resp = httpClient.Post(url, content);

            string respString = resp.Content.ReadAsString();
        }
</pre>
<p><span style="font-size: medium;"><strong>7. Sample PUT</strong></span></p>
<p>Http PUT is similar to a Http POST.  The differences would be the API path to navigate to, and the XML data that you send across the wire. Below we update a Ticket, sending over the email and comment we wish to update the record with.  Everything else&#8230; remains the same as above!</p>
<pre class="brush: csharp; title: ; notranslate">
        public static void UpdateTicket(Entities.Ticket ticket)
        {
            HttpClient httpClient = HttpClientManager.GetHttpClient();

            // I'm sure you can think of a better way of generating the XML! <img src='http://nullablecode.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />
            HttpContent content = Microsoft.Http.HttpContent.Create(&quot;&lt;ticket&gt;&lt;email&gt;test@test.com&lt;/email&gt;&lt;comment&gt;UPDATED comments!&lt;/comment&gt;&lt;/ticket&gt;&quot;
                                                            , &quot;application/xml&quot;);

            string url = &quot;tickets/&quot; + ticket.ID + &quot;.xml&quot;;
            HttpResponseMessage resp = httpClient.Put(url, content);

            string respString = resp.Content.ReadAsString();
        }
</pre>
<p><span style="font-size: medium;"><strong>8. Sample DELETE</strong></span><br />
A Http DELETE is alot simpler than a Http POST and PUT.  All we need to do is grab the API path to navigate to (which coincidentally will most likely contain the record ID) and execute the httpClient DELETE method.</p>
<p>Below is a snippet that shows you how this is done.</p>
<pre class="brush: csharp; title: ; notranslate">
        public static void DeleteTicket(Entities.Ticket ticket)
        {
            HttpClient httpClient = HttpClientManager.GetHttpClient();

            string url = &quot;tickets/&quot; + ticket.ID + &quot;.xml&quot;;
            HttpResponseMessage resp = httpClient.Delete(url);

            string respString = resp.Content.ReadAsString();
        }
</pre>
<p><span style="text-decoration: underline;"><strong><span style="font-size: medium;">Conclusion</span></strong></span></p>
<p>Well there you have it!!  You now have all the knowledge you need to create you own apps and integrate them with 3rd party APIs out there. It may be alot of information to consume, but once you complete the GET request, you will see how everything clicks in!  Then its smooth sailing from there onwards <img src='http://nullablecode.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>Hope this article helped! Have fun!</p>
]]></content:encoded>
			<wfw:commentRss>http://nullablecode.com/2011/11/consuming-a-rest-service/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RIA Services: File uploading &#8211; service method</title>
		<link>http://nullablecode.com/2011/08/ria-services-file-uploading-service-method/</link>
		<comments>http://nullablecode.com/2011/08/ria-services-file-uploading-service-method/#comments</comments>
		<pubDate>Tue, 09 Aug 2011 07:00:23 +0000</pubDate>
		<dc:creator>nullablecode</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Everything]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Domain Service]]></category>
		<category><![CDATA[file]]></category>
		<category><![CDATA[file upload]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[stream]]></category>

		<guid isPermaLink="false">http://nullablecode.com/?p=619</guid>
		<description><![CDATA[THE final part to our File Uploading via RIA Services exercise is the Domain Service itself. This article continues from<a href="http://nullablecode.com/2011/08/ria-services-file-uploading-service-method/" class="searchmore">Read the Rest...</a><div class="clr"></div>]]></description>
			<content:encoded><![CDATA[<p><strong>THE </strong>final part to our File Uploading via RIA Services exercise is the Domain Service itself. This article continues from <a title="RIA Services: File uploading" href="http://nullablecode.com/2011/03/ria-services-file-uploading/" target="_blank">RIA Services: File uploading</a>. Before reading this article, I encourage you to have a glimpse of the prerequisite articles list below:</p>
<p><span style="text-decoration: underline; font-size: medium;"><strong>Prerequisites</strong></span></p>
<ul>
<li><a title="How to enable SQL FileStream Types" href="http://nullablecode.com/2011/02/how-to-enable-sql-filestream-types/">How to enable SQL FileStream Types</a></li>
<li><a title="Using SQL FileStream Types in your Databases" href="http://nullablecode.com/2011/02/using-sql-filestream-types-in-your-databases/">Using SQL FileStream Types in your Databases</a></li>
<li><a title="MaxRequestLength – Packet sizes: Size isnt everything" href="http://nullablecode.com/2011/02/maxrequestlength-packet-sizes-size-isnt-everything/">MaxRequestLength – Packet sizes: Size isn&#8217;t everything</a></li>
<li><a title="RIA Services: File uploading" href="http://nullablecode.com/2011/03/ria-services-file-uploading/">RIA Services: File uploading<br />
</a></li>
</ul>
<p>Here I will go into detail on how to code your domain service class to receive data packets sent across the wire from the <a title="File Buffering and Streaming" href="http://nullablecode.com/2011/03/file-buffering-and-streaming/" target="_blank">File Stream Uploader generic handler</a> class.</p>
<p><span id="more-619"></span></p>
<p><span style="text-decoration: underline;"><strong><span style="font-size: medium;">Attachment Service</span></strong></span></p>
<p>Ok first up &#8211; The Domain Service.  I called it &#8216;Attachment Service&#8217;.  This example will include two basic functions: Reading streamed data from a SQL FileStream type, and Uploading streamed data to a SQL FileStream type.</p>
<p>The service is pretty basic.. just pipe your data packet parameters from the client, into the <strong>Manager </strong>class. Here&#8217;s the code:</p>
<pre class="brush: csharp; title: ; notranslate">
   [EnableClientAccess()]
    public class AttachmentService : LinqToEntitiesDomainService&lt;MyEntities&gt;
    {
        private Manager.IAttachmentManager attachmentManager;

        public AttachmentService()
        {
            this.attachmentManager = new Manager.AttachmentManager();
        }

        [Invoke(HasSideEffects = false)]
        public byte[] ReadStreamed(Guid fileID, int offset, int lengthToRead)
        {
            return attachmentManager.ReadStreamed(fileID, offset, lengthToRead);
        }

        [Invoke(HasSideEffects = false)]
        public Guid UploadStreamed(Guid attachmentID, string newFileName, string originalFileName, byte[] fileData, int position)
        {
            return attachmentManager.UploadStreamed(attachmentID, newFileName, originalFileName, fileData, position);
        }

    }
</pre>
<p><span style="text-decoration: underline;"><strong><span style="font-size: medium;">Manager Class:</span></strong></span></p>
<p>Our manager class is also pretty straight forward. There is nothing tricky that is needed here, so we again simply pipe our input parameters into the <strong>Repository </strong>class.</p>
<pre class="brush: csharp; title: ; notranslate">
    public class AttachmentManager : IAttachmentManager
    {
        private Repository.IAttachmentRepository attachmentRep { get; set; }

        public AttachmentManager()
        {
            this.attachmentRep = new Repository.AttachmentRepository();
        }

        public byte[] ReadStreamed(Guid fileID, int offset, int lengthToRead)
        {
            AttachmentRepository rep = new AttachmentRepository();
            return rep.ReadStreamed(fileID, offset, lengthToRead);
        }

        public Guid UploadStreamed(Guid attachmentID, string newFileName, string originalFileName, byte[] fileData, int position)
        {
            AttachmentRepository rep = new AttachmentRepository();
            return rep.UploadStreamed(attachmentID, newFileName, originalFileName, fileData, position);
        }

    }
</pre>
<p><span style="text-decoration: underline;"><strong><span style="font-size: medium;">The Repository:</span></strong></span></p>
<p>This is where the fun starts!  Our repository will contain the bulk of the code; and the majority of it is the actual communication with the Data tier.  Our class will contain 3 methods instead of just 2.  The extra method is called &#8216;InsertAttachmentStub&#8217;. This method will be used to create the initial attachment &#8216;stub&#8217; in our database table.  As you will see below, the stored procedure for this insertion will simply create the record with the AttachmentID, and set the necessary file names and other data fields.</p>
<p><strong>Note: </strong>Our AttachmentID being a GUID was generated in the code beforehand, and passed into the Generic Handler.</p>
<p><strong>Note: </strong>This stub method is only needed for the very first data packet. Subsequent data packets will re-use the same Attachment record, and update the data component of the FileStream type accordingly.</p>
<p>Without further or do, here&#8217;s the signature for our 3 functions:</p>
<pre class="brush: csharp; title: ; notranslate">
    public class AttachmentRepository
    {

        public Entities.AttachmentPM InsertAttachmentStub(System.Guid attachmentID, string newFileName, string originalFileName)
        { ... }

        public byte[] ReadStreamed(Guid fileID, int offset, int lengthToRead)
        { ... }

        public Guid UploadStreamed(Guid attachmentID, string newFileName, string originalFileName, byte[] fileData, int position)
        { ... }
    }
</pre>
<p><strong><span style="font-size: medium;">Inserting the stub:</span></strong></p>
<p>As mentioned above, pretty simple Repository function here.  Just pipe all the basic details for your Attachment record into the <strong>InsertAttachmentStub </strong>Stored Proc:</p>
<pre class="brush: csharp; title: ; notranslate">
        public Entities.AttachmentPM InsertAttachmentStub(System.Guid attachmentID, string newFileName, string originalFileName)
        {
            var list = DataAccessUtility.ExecuteStoredProcedure(&quot;uspAttachment_InsertAttachmentStub&quot;
                                        , new SqlParameter(&quot;ID&quot;, attachmentID)
                                        , new SqlParameter(&quot;NewFileName&quot;, newFileName)
                                        , new SqlParameter(&quot;OriginalFileName&quot;, originalFileName)
                                        , new SqlParameter(&quot;UpdatedDateTime&quot;, System.DateTime.Now)
                                        , new SqlParameter(&quot;UpdatedBy&quot;, System.Data.SqlDbType.Int) { Value = 0 }
                                     );
            return list.FirstOrDefault();
        }
</pre>
<p>Here&#8217;s the SQL proc for InsertAttachmentStub. Once we complete this insert, we will have a database record to store to re-use when uploading the next packets of data!</p>
<pre class="brush: sql; title: ; notranslate">
CREATE PROCEDURE [dbo].[uspAttachment_InsertAttachmentStub]
	@ID						AS UNIQUEIDENTIFIER
	, @NewFileName			AS NVARCHAR(255)
	, @OriginalFileName		AS NVARCHAR(255)
	, @UpdatedDateTime		DATETIME2(7)
	, @UpdatedBy			AS INT
AS
BEGIN

	INSERT INTO Attachment (ID, NewFileName, OriginalFileName, FileData, UpdatedDateTime, UpdatedBy)
	OUTPUT inserted.FileData.PathName()		AS LogicalFilePath
			, inserted.ID					AS ID
	VALUES (@ID, @NewFileName, @OriginalFileName, 0x, @UpdatedDateTime, @UpdatedBy)
END
</pre>
<p><span style="font-size: medium;"><strong>Reading SQL Filestream data:</strong></span></p>
<p>Lets begin with the easier of the two methods.. the reading of data.</p>
<p>Our input parameters will identify which AttachmentID we are interested in. It also tells us which byte offset to start our reading from; and how many bytes we want to read and return back to the calling method.</p>
<p>So here&#8217;s the reading method, and it performs the following steps:</p>
<ul>
<li>Create a Transaction Context so that SQL knows who you are when reading the FileStream data</li>
<li>Make an additional call to grab the File attachment record.  Include in this select the FilePath that we will use later on.</li>
<li>Using the Transaction Context AND the FilePath of the file we are interested in reading, create and open your connection to the SQLFileStream.</li>
<li>Once the SQLFileStream is opened, we can now read our required data packet.</li>
<li>Read the data from the SQLFileStream object into a MemoryStream object</li>
<li>Return the data back to the caller</li>
</ul>
<pre class="brush: csharp; title: ; notranslate">
        public byte[] ReadStreamed(Guid fileID, int offset, int lengthToRead)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();

            using (var transScope = new System.Transactions.TransactionScope())
            {

                    byte[] txContext = (byte[])DataAccessUtility.ExecuteScalar(System.Data.CommandType.Text, &quot;SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()&quot;);

                    var list = DataAccessUtility.ExecuteStoredProcedure(&quot;uspAttachment_GetAttachmentByID&quot;
                                         , new SqlParameter(&quot;ID&quot;, fileID)
                                         );
                    string filePath = list.FirstOrDefault().LogicalFilePath;

                    System.Data.SqlTypes.SqlFileStream sqlFS = new System.Data.SqlTypes.SqlFileStream(filePath, txContext, System.IO.FileAccess.Read);

                    byte[] buffer = new byte[lengthToRead];

                    sqlFS.Position = offset;
                    sqlFS.Read(buffer, 0, lengthToRead);
                    ms.Write(buffer, 0, lengthToRead);
                    ms.Flush();

                    ms.Close();

                    sqlFS.Close();

                transScope.Complete();
            }
            return ms.ToArray();

        }
</pre>
<p><strong><span style="font-size: medium;">Uploading to a SQL FileStream:</span></strong></p>
<p>Uploading is simply the opposite of what you have accomplished above.</p>
<p>To upload a data packet we perform the following steps:</p>
<ul>
<li>Check if this is the first packet uploaded</li>
<li>If yes &#8211; call the InsertAttachmentStub method to generate an AttachmentID</li>
<li>If not &#8211; grab the AttachmentID (and its corresponding FilePath data) from the database</li>
<li>Create a Transaction Context so that SQL knows who you are.</li>
<li>Using the Transaction Context AND the FilePath of the file we are interested in writing to, create and open your connection to the SQLFileStream.</li>
<li>Once the SQLFileStream is opened, we can now write our required data packet.</li>
<li>Grab the data packet from our input parameters, and write into the SQLFileStream object</li>
<li>Once written, we can close the SQLFileStream object safely and return from this function.</li>
</ul>
<pre class="brush: csharp; title: ; notranslate">
        public Guid UploadStreamed(Guid attachmentID, string newFileName, string originalFileName, byte[] fileData, int position)
        {
            Entities.AttachmentPM attachment;

            using (var transScope = new System.Transactions.TransactionScope())
            {
                    // If Position = 0, then we are inserting the first data packet.
                    if (position == 0)
                    {
                        attachment = this.InsertAttachmentStub(attachmentID, newFileName, originalFileName);
                    }
                    else    // Else Attachment record already exists. Just retrieve the details
                    {
                        var list = DataAccessUtility.ExecuteStoredProcedure(&quot;uspAttachment_GetAttachmentByID&quot;
                                        , new SqlParameter(&quot;ID&quot;, attachmentID)
                                        );
                        attachment = list.FirstOrDefault();
                    }
                    string filePath = attachment.LogicalFilePath;

                    byte[] txContext = (byte[])DataAccessUtility.ExecuteScalar(System.Data.CommandType.Text, &quot;SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()&quot;);

                    using (System.Data.SqlTypes.SqlFileStream sqlFS = new System.Data.SqlTypes.SqlFileStream(filePath, txContext, System.IO.FileAccess.ReadWrite))
                    {
                        byte[] buffer = new byte[fileData.Length];

                        sqlFS.Position = sqlFS.Length;
                        sqlFS.Write(fileData, 0, fileData.Length);
                    }

                transScope.Complete();
            }
            return attachment.ID;
        }
</pre>
<p><span style="text-decoration: underline;"><strong>Conclusion:</strong></span></p>
<p>Well that&#8217;s pretty much all there is to it!  <img src='http://nullablecode.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>If you have any question, please let me know!  Hope this article helped!</p>
<p>Cheers.</p>
]]></content:encoded>
			<wfw:commentRss>http://nullablecode.com/2011/08/ria-services-file-uploading-service-method/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Querying ActiveDirectory using LDAP</title>
		<link>http://nullablecode.com/2011/07/querying-activedirectory-using-ldap/</link>
		<comments>http://nullablecode.com/2011/07/querying-activedirectory-using-ldap/#comments</comments>
		<pubDate>Mon, 25 Jul 2011 06:24:56 +0000</pubDate>
		<dc:creator>nullablecode</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Everything]]></category>
		<category><![CDATA[.net]]></category>

		<guid isPermaLink="false">http://nullablecode.com/?p=608</guid>
		<description><![CDATA[MANY corporate environments rely on a backbone system that controls access to the entire corporate network. One of the more<a href="http://nullablecode.com/2011/07/querying-activedirectory-using-ldap/" class="searchmore">Read the Rest...</a><div class="clr"></div>]]></description>
			<content:encoded><![CDATA[<p><strong>MANY</strong> corporate environments rely on a backbone system that controls access to the entire corporate network. One of the more common systems out there is <strong>Microsoft&#8217;s Active Directory</strong>. Active Directory is a directory service. It is a hierarchical system of objects where each object can be a phyical or virtual entity within the corporate environment.  Entities can range from being a meeting room, a person, a printer, or a computer system.</p>
<p>These entities can then be grouped together to form organisational units. <strong>Organisational Units </strong>are created to tie common entities together; whether it be a geographical grouping or a structure grouping. Each entity is comprised of many attributes. These attributes provide additional information about the entity. For example a Person entity will have their Login, Firstname, Surname and Department etc as attributes.</p>
<p>Developing a software solution for a corporate environment will most likely entail Active Directory access for various reason. In this article I will explain how you can create your own Active Directory querying utility to suit your requirements&#8230;</p>
<p><span id="more-608"></span></p>
<p><span style="text-decoration: underline; font-size: medium;"><strong>System.DirectoryServices Namespace</strong></span></p>
<p>The first thing you&#8217;d want to do is include a reference to the <strong>System.DirectoryServices </strong>namespace. This is the system library that contains all the objects needed to query your Active Directory service.</p>
<p><span style="text-decoration: underline;"><span style="font-size: medium;"><strong>Making the connection</strong></span></span></p>
<p>Once that is done; its time to connect to your Directory Service using LDAP.<br />
<strong>LDAP </strong>stands for <strong>L</strong>ightweight <strong>D</strong>irectory <strong>A</strong>ccess <strong>P</strong>rotocol. It is one of many access protocols available to communicate with Acitve Directory.</p>
<p>Knowledge of the following .Net classes will be helpful in understanding how communication between your .Net application and the Active Directory service is achieved:</p>
<ul>
<li>DirectoryEntry &#8211; The main connection to your Active Directory server</li>
<li>DirectorySearcher &#8211; The object passed into our LDAP query to filter for the required entity objects</li>
<li>SearchResultCollection &#8211; A collection that stores multiple AD entities if more than one is found</li>
<li>SearchResult &#8211; A single AD entity with its corresponding attributes</li>
</ul>
<p>First up, create a connection to your Active Directory service. The ADServer should be something similar to &#8220;<strong>LDAP://my-server.com.au/dc=com,dc=au</strong>&#8220;.</p>
<pre class="brush: csharp; title: ; notranslate">
            DirectoryEntry directoryEntry = new DirectoryEntry(this.ADServer.Text
                                                            , this.ADUsername.Text
                                                            , this.ADPassword.Text);
</pre>
<p>Create a new <strong>DirectorySearcher </strong>object to query the AD server with. For now, just a new object is sufficient. Later on in this article I will explain how to select which attributes to obtain from the AD server. Without explicitly listing your attributes the DirectorySearcher will simply return all attributes for all entities matching your filter criteria.</p>
<pre class="brush: csharp; title: ; notranslate">
DirectorySearcher searcher = new DirectorySearcher(directoryEntry);
</pre>
<p><span style="text-decoration: underline;"><strong><span style="font-size: medium;"><br />
Filtering the data</span></strong></span></p>
<p>The next step is to write our filter criteria for our query. This is simply the DirectorySearcher.<strong>Filter </strong>property of your DirectorySearcher object. The filter you will use is going to tell the AD Server to only query the &#8220;user&#8221; entities, that lie within the &#8220;person&#8221; category, where the sAMAccountName attribute equals to our input value. We also specify AD to search all sub-trees of the hierarchical structure.</p>
<pre class="brush: csharp; title: ; notranslate">
            searcher.Filter = &quot;(&amp;(objectClass=user)(objectCategory=person)(samaccountname=&quot; + this.UsernameTextBox.Text + &quot;))&quot;;
            searcher.SearchScope = System.DirectoryServices.SearchScope.Subtree;
</pre>
<p>That&#8217;s pretty much it!!  The final is step is to execute the search..</p>
<p><span style="text-decoration: underline;"><strong><span style="font-size: medium;">Searching</span></strong></span></p>
<p>Below is a snippet of the code that traverses all the entities in the ResultCollection. Spitting out all the attributes in the Entity object to a local String variable.  Then displaying the output as textbox text.</p>
<pre class="brush: csharp; title: ; notranslate">
            SearchResultCollection resultCollection = searcher.FindAll();

            foreach (SearchResult result in resultCollection)
            {
                string str = &quot;&quot;;
                foreach (string propertyName in result.Properties.PropertyNames)
                {
                    try
                    {
                        str += propertyName + &quot;:&quot; + (string)(result.Properties[propertyName][0]) + System.Environment.NewLine;
                    }
                    catch
                    {
                    }

                }

                this.OutputTextBox.Text += str;
            }
</pre>
<p>To access a specific attribute from an entity; refer to the &#8216;<strong>Properties</strong>&#8216; property object, which is an array of values indexed by the attribute name.  The value of the attribute is the first item in the array returned.</p>
<p>I have listed some examples below:</p>
<pre class="brush: csharp; title: ; notranslate">
result.Properties[&quot;GivenName&quot;][0]
result.Properties[&quot;Sn&quot;][0]
result.Properties[&quot;Mail&quot;][0]
</pre>
<p>Try out the code above. You may notice that it takes a few seconds to return just one entity. That is because in our DirectorySearcher object we didn&#8217;t limit the data we really wanted. So our query returned all AD attributes for us.  You will most certainly only want to grab the data that is necessary for your situation. This will dramatically increase its performance.</p>
<p>The above code is useful if you want to check out all the available attributes within Active Directory.</p>
<p><span style="text-decoration: underline;"><strong><span style="font-size: medium;">Filtering the attributes</span></strong></span></p>
<p>Let&#8217;s say we are only interested in the two attributes: sAMAccountName and Mail<br />
Before we execute our query with the AD Server, we can optimise the search to only return these two attributes with the following lines of code:</p>
<pre class="brush: csharp; title: ; notranslate">
            DirectorySearcher searcher = new DirectorySearcher(directoryEntry);
            searcher.PropertiesToLoad.Add(&quot;sAMAccountname&quot;);
            searcher.PropertiesToLoad.Add(&quot;Mail);

            searcher.Filter = &quot;(&amp;(objectClass=user)(objectCategory=person)(samaccountname=&quot; + this.UsernameTextBox.Text + &quot;))&quot;;
            searcher.SearchScope = System.DirectoryServices.SearchScope.Subtree;
</pre>
<p>With this new code, our Output string will only contain the two attributes we requested for.<br />
Also take note of the time the query takes &#8211; it should be alot quicker than before!</p>
<p><img class="alignnone size-full wp-image-612" title="20110725_161501" src="http://nullablecode.com/wp-content/uploads/2011/07/20110725_161501.png" alt="" width="644" height="486" /></p>
]]></content:encoded>
			<wfw:commentRss>http://nullablecode.com/2011/07/querying-activedirectory-using-ldap/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WCF RIA Services Validation</title>
		<link>http://nullablecode.com/2011/06/wcf-ria-services-validation/</link>
		<comments>http://nullablecode.com/2011/06/wcf-ria-services-validation/#comments</comments>
		<pubDate>Thu, 09 Jun 2011 07:09:24 +0000</pubDate>
		<dc:creator>nullablecode</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Everything]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[Domain Service]]></category>
		<category><![CDATA[RIA]]></category>
		<category><![CDATA[Service]]></category>

		<guid isPermaLink="false">http://nullablecode.com/?p=581</guid>
		<description><![CDATA[ONE of the annoying aspects with traditional ASP.Net development was that validation logic which seemed well fitted to be in<a href="http://nullablecode.com/2011/06/wcf-ria-services-validation/" class="searchmore">Read the Rest...</a><div class="clr"></div>]]></description>
			<content:encoded><![CDATA[<p><strong>ONE </strong>of the annoying aspects with traditional ASP.Net development was that validation logic which seemed well fitted to be in the mid-tier would often be replicated into the UI-tier. One does this to provide instant feedback to application users; increasing user experience and the application&#8217;s usability. The drawback is of course the doubling up of this logic. No only that, but quite often you would have the duplication of logic across different languages; for example mid-tier validation would be coded in C# whereas UI-tier validation would be coded in Javascript &#8211; causing a myriad of headaches with code maintenance.</p>
<p>So along comes WCF RIA Services and its validation framework. In this article I&#8217;ll provide details on how WCF RIA Services approachs validation; and how it has been designed to resolve issues of its predecessors..</p>
<p><span id="more-581"></span></p>
<p>There are two main categories of Validation within RIA Services:</p>
<ol>
<li>Client side validation</li>
<li>Server side validation</li>
</ol>
<p><strong><span style="font-size: medium;"><br />
Client side Validation</span></strong></p>
<p>So we all know the benefits of Client-side validation.. Instant data validation without the need for any service or database calls. Because it&#8217;s extremely call-efficient it provides great performance gains in the system. But with one limitation &#8211; the client side must have all the necessary data for it to complete its validation logic. Which kind of makes sense when you think about it.. without having all its parameters to validate with it won&#8217;t be able to complete successfully.</p>
<p><span style="font-size: medium;"><strong>Server side Validation</strong></span></p>
<p>This is where it gets interesting. If your validation requires data not available on the Client, then server side validation is the definitely way to go. You can achieve server side validation by exposing <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.domainservices.server.invokeattribute(v=vs.91).aspx" target="_blank">Invoke methods</a> in your Domain Service. The Client can explicitly make the domain service call on-demand. This fits into the traditional way of validation; and in many cases works absolutely fine. Of course, with RIA services you can go one step further.. using Custom Validation.</p>
<p>There are two styles of Validation available:</p>
<ol>
<li>Declarative validation</li>
<li>Custom validation</li>
</ol>
<p><span style="font-size: medium;"><strong><br />
<span style="text-decoration: underline;">Declarative Validation</span></strong></span></p>
<p>Declarative Validation is the simplest of the two forms of Validation. It provides simple and easy to maintain validation logic triggered on the Client. This is achieved by using <strong>Metadata Annotations</strong> with your Entity object Properties that require the validation. These annotations are part of the <strong>System.ComponentModel.DataAnnotations</strong> namespace and are derivative classes of <strong>ValidationAttribute</strong>. There&#8217;s only a small list of these but they should suffice for simple validation logic:</p>
<ul>
<li>StringLength</li>
<li>Required</li>
<li>Range</li>
<li>RegularExpression</li>
</ul>
<p><span><br />
Below is an example of how to use declarative validation in an Entity class called Person.</span></p>
<pre class="brush: csharp; title: ; notranslate">
using System.ComponentModel.DataAnnotations;

    public class Person
    {
        [Key]
        public int ID { get; set; }

        [Required]
        [StringLength(50, ErrorMessage=&quot;Forename cannot exceed 50 characters.&quot;)]
        public string Forename { get; set; }

        [Required]
        [StringLength(50, ErrorMessage=&quot;Surname cannot exceed 50 characters.&quot;)]
        public string Surname { get; set; }

        [Range(1, 150, ErrorMessage=&quot;Age must be between 1 and 150.&quot;)]
        public int Age { get; set; }

        public int StreetNumber { get; set; }
        public string StreetName { get; set; }

        public int PostCode { get; set; }
    }
</pre>
<p><span style="text-decoration: underline;"><span style="font-size: medium;"><strong>Custom Validation</strong></span></span></p>
<p>Custom Validation can be used for both Client and Server side validation. Depending on your logic you will need to split your Client and Server side validation code into different classes. The basic principle should be:</p>
<ul>
<li>If the logic is simple enough to be covered by the Declarative Validation method &#8211; then use the available <strong>Declarative Validation</strong> attributes.</li>
<li>However, if the logic is slightly more complicated + all validation parameters are available on the Client &#8211; then follow the <strong>Client Side Custom Validation</strong> method</li>
<li>Lastly, if the logic is slightly more complicated + not all validation parameters are available on the Client &#8211; then follow the <strong>Server Side Custom Validation</strong> method.</li>
</ul>
<p><strong><span style="font-size: medium;"><br />
Custom Validation &#8211; Client side</span></strong></p>
<p>With Client side Custom Validation you will need to be defined in a *.shared file to ensure the code is generated on the Client. Along with this, your class needs to be declared as <strong>public static partial</strong>, and your validation methods declared as <strong>public static </strong>returning a <strong>ValidationResult </strong>object.</p>
<p>As an example, say you wanted to ensure that the <strong>StreetNumber</strong> property has a positive non-zero value. You can probably use the RANGE attribute to ensure it has a minimum value of 1.  But there really isn&#8217;t a maximum figure that you can put in. So by using declaring Custom Validation for the StreetNumber, you can simply check that it is not less than zero.</p>
<p>Below is the validation class that will be generated for the Client:</p>
<ul>
<li>File must be in the format of a shared file, eg: PersonClientValidation.shared.cs</li>
<li>Class declared as <strong>public static partial class &#8230;</strong></li>
<li>Validation method declared as <strong>public static ValidationResult </strong> &#8230;</li>
<li>Return ValidationResult.Success if validation passes</li>
<li>Return a new ValidationResult object if validation fails</li>
</ul>
<pre class="brush: csharp; title: ; notranslate">
using System.ComponentModel.DataAnnotations;

    public static partial class PersonClientValidation
    {
        public static ValidationResult StreetNumberPositive(int streetNumber, ValidationContext validationContext)
        {
            if (streetNumber&lt; 0)
            {
                return new ValidationResult(&quot;Street Number must be positive and non-zero.&quot;);
            }
            return ValidationResult.Success;
        }
    }
</pre>
<p>Once that is done, we&#8217;re ready to add the CustomValidation attribute to the <strong>StreetNumber </strong> property, and point it to the StreetNumberPositive(&#8230;) method. Just put this attribute above the Property, and that&#8217;s it! When the user enters a StreetNumber &lt; 0 the application will automatically throw the validation error and display the message to the user.</p>
<pre class="brush: csharp; title: ; notranslate">
using System.ComponentModel.DataAnnotations;

    public class Person
    {
        [Key]
        public int ID { get; set; }

        //... other properties hidden ... //

        [CustomValidation(typeof(PersonClientValidation), &quot;StreetNumberPositive&quot;)]
        public int StreetNumber { get; set; }

        public string StreetName { get; set; }
    }
</pre>
<p><span style="font-size: medium;"><strong>Custom Validation &#8211; Server side</strong></span></p>
<p>With Server side Custom Validation the opportunities are limitless. Because the validation is processed on the Server you can utilise all your mid-tier code for data retrieval or additional processing while performing the required validation logic. One main reason we need to split the Server side Custom Validation from the Client side Custom Validation code is because the Server side logic may contain references to mid-tier code that is inaccessible by the Client. If we placed it in the same *.shared.cs class there will be a compilation error when creating mid-tier objects and service classes.</p>
<p>So create another class that we will use for the Server side validation of the Person class:</p>
<ul>
<li>This is just a mid-tier class, so the naming format is just a basic class file. ie don&#8217;t use *.shared.cs</li>
<li>Class declared as <strong>public static class</strong>&#8230;</li>
<li>Validation method declared as <strong>public static ValidationResult </strong>(obj propertyValue, ValidationContext ctx)</li>
<li>Return ValidationResult.Success if validation passes</li>
<li>Return a new ValidationResult object if validation fails</li>
</ul>
<pre class="brush: csharp; title: ; notranslate">
using System.ComponentModel.DataAnnotations;

    public static class PersonServerValidation
    {
        public static ValidationResult PostCodeExists(int postCode, ValidationContext validationContext)
        {
            // Here we call a Manager class that will return our boolean value
            // Any additional calls to class methods, or other services can be done here.

            AddressManager mgr = new AddressManager();
            bool exists = mgr.DoesPostCodeExist(postCode);

            if (!exists)
            {
                return new ValidationResult(&quot;The postcode entered is invalid.
                                            , new[] { validationContext.MemberName });
            }

            return ValidationResult.Success;
        }
    }
</pre>
<p>Finally, we can now update our <strong>PostCode </strong>property with the CustomValidation Attrubute. When RIA Services determine that validation of this property is needed, it will execute the Validation Method we declared above.</p>
<pre class="brush: csharp; title: ; notranslate">
using System.ComponentModel.DataAnnotations;

    public class Person
    {
        //... other properties hidden ... //

        [CustomValidation(typeof(PersonServerValidation), &quot;PostCodeExists&quot;)]
        public int PostCode { get; set; }
    }
</pre>
<p>So far we have been dealing with individual Entity Properties and its underlying validation processes. Alot of the times Property validation may be dependant on other Properties. For example, say that you wanted to validate the StreetName is a valid street in the Postcode specified; and that the street number is within the number of houses on that street. This is where we go one step beyond Property Validation to utilising <strong>Entity Validation</strong>.</p>
<p><span style="text-decoration: underline;"><span style="font-size: medium;"><strong>Entity Validation</strong></span></span></p>
<p>Entity Validation is pretty straight forward. It simply refers to the validation that takes place on an Entity Object as a whole, as opposed to validating individual Properties of that object. Entity Validation works in conjunction with Property Validation. Meaning that the Property Validations that you have defined in your class is still true and valid, and will automatically validate when required. Once all Property validation passes, the framework will then perform Entity Validation if one or more exist.</p>
<p>The process of defining a Validation Method for use with Entity Validation is similar to that described earlier. The only difference is that rather than having a parameter with the same type as the Property itself, we require a parameter of the Entity object instead. A sample Entity level Validation method is provided below:</p>
<pre class="brush: csharp; title: ; notranslate">
using System.ComponentModel.DataAnnotations;

    public static class PersonServerValidation
    {
        public static ValidationResult StreetNameValid(Person person, ValidationContext validationContext)
        {
            AddressManager mgr = new AddressManager();
            bool validStreet = mgr.IsStreetValid(person.StreetName, person.PostCode);

            if (!validStreet)
            {
                return new ValidationResult(&quot;The street entered is not valid for with that postcode.&quot;
                                            , new[] { validationContext.MemberName });
            }

            return ValidationResult.Success;
        }

        public static ValidationResult StreetNumberValid(Person person, ValidationContext validationContext)
        {
            AddressManager mgr = new AddressManager();
            bool validStreetnumber = mgr.IsStreetNumberValid(person.StreetNumber
                                                            , person.StreetName
                                                            , person.PostCode);
            if (!validStreetnumber )
            {
                return new ValidationResult(&quot;The street number entered is not valid for that street
                                            , new[] { validationContext.MemberName });
            }

            return ValidationResult.Success;
        }
    }
</pre>
<p>The final step is to declare the Entity Validation for the Person class and link it to the corresponding Validation methods above:</p>
<pre class="brush: csharp; title: ; notranslate">
using System.ComponentModel.DataAnnotations;

    [CustomValidation(typeof(PersonServerValidation), &quot;StreetNameValid&quot;)]
    [CustomValidation(typeof(PersonServerValidation), &quot;StreetNumberValid&quot;)]
    public class Person
    {
        //... other properties hidden ... //
    }
</pre>
<p><span style="font-size: medium;"><strong>Validation via Invoke Methods</strong></span></p>
<p>As briefly mentioned previously in this article, you can as a last resort create an Invoke method that will contain the logic you require for your validation. Using invoke methods for validation is often useful when you need to validate across entities, or if your design calls for out-of-the-ordinary situations that don&#8217;t tie into the scenarios listed above.</p>
<p><span style="text-decoration: underline;"><span style="font-size: medium;"><strong>Conclusion</strong></span></span></p>
<p>Well there you have it &#8211; a explanation of the validation framework available for you to use with the WCF RIA Services framework. As you can see, this validation framework works very well if you want to declare and keep all your validation logic within the mid-tier code that has been developed by your mid-tier developers. This removes the need for your UI developers to concern themselves with any of the business rules and validation logic that comes with it.</p>
<p>Traditional ASP.Net would have seen the duplication of your validation logic to the UI-tier making code maintenance extremely troublesome.</p>
<p>I hope this article has given you enough information to implement your own validation logic moving forward! <img src='http://nullablecode.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://nullablecode.com/2011/06/wcf-ria-services-validation/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>SQL: How to search all procs for a string</title>
		<link>http://nullablecode.com/2011/05/sql-how-to-search-all-procs-for-a-string/</link>
		<comments>http://nullablecode.com/2011/05/sql-how-to-search-all-procs-for-a-string/#comments</comments>
		<pubDate>Thu, 26 May 2011 23:57:08 +0000</pubDate>
		<dc:creator>nullablecode</dc:creator>
				<category><![CDATA[Everything]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://nullablecode.com/?p=574</guid>
		<description><![CDATA[This is a micro-post to show you how easy it is to search through all objects of a SQL Server<a href="http://nullablecode.com/2011/05/sql-how-to-search-all-procs-for-a-string/" class="searchmore">Read the Rest...</a><div class="clr"></div>]]></description>
			<content:encoded><![CDATA[<p><strong>T</strong>his is a micro-post to show you how easy it is to search through all objects of a SQL Server Database for a specific string. Say that you want to rename a function and you want to know how many procedures are using this function &#8211; instead of opening all procedures trying to find the matching string, this article will give you a solution that simplifies the matter ten fold!</p>
<p><span id="more-574"></span></p>
<p><span style="text-decoration: underline;"><strong><span style="font-size: medium;">Introduction</span></strong></span></p>
<p>All your databases have a SYS schema; and within this schema is a view called OBJECTS.</p>
<p>It is in this OBJECTS view where all your database elements are stored and referenced; including Table names, Primary/Foreign Key constraints, Procedures, Functions, View.. everything!</p>
<p><span style="text-decoration: underline;"><strong><span style="font-size: medium;">Basic Query</span></strong></span></p>
<p>So here&#8217;s the basic query&#8230;</p>
<p>This will list every element associated to the Database you run the query under:</p>
<pre class="brush: sql; title: ; notranslate">
SELECT *
FROM SYS.OBJECTS O
</pre>
<p><span style="text-decoration: underline; font-size: medium;"><strong>Filtering by Element Type</strong></span></p>
<p>To narrow down your search, you can filter the above query using the [type] column that is returned from the OBJECTS view. Below is a short list of the different type codes available and what they refer to:</p>
<ul>
<li>P = Stored Procedure</li>
<li>U = User Table</li>
<li>V = View</li>
<li>TT = Type Table</li>
<li>FN = Scalar Function</li>
<li>IF = Inline Table Function</li>
<li>PK = Primary Key Constraint</li>
<li>F = Foreign Key Constraint</li>
</ul>
<pre class="brush: sql; title: ; notranslate">
SELECT *
FROM SYS.OBJECTS O
WHERE [type] = 'P'
</pre>
<p><span style="text-decoration: underline;"><strong><span style="font-size: medium;">Searching the Element Text</span></strong></span></p>
<p>The final step is to locate the data content of your database elements to complete your search. Here we need the help of a second View called SYSCOMMENTS.  This view returns a &#8216;text&#8217; component to your database elements. Specifically for Stored Procedures, Function and View this component holds the code counterpart for those elements.</p>
<p>To proceed, join your OBJECTS view with the SYSCOMMENTS view on the <strong>object_id </strong>and <strong>id </strong>columns respectively as shown below:</p>
<pre class="brush: sql; title: ; notranslate">
SELECT *
FROM SYS.OBJECTS O
INNER JOIN SYS.syscomments C on C.id = O.object_id
WHERE O.[type] = 'P'
	AND C.text LIKE '%xyz%'
</pre>
<p><span style="text-decoration: underline;"><span style="font-size: medium;"><strong>Conclusion</strong></span></span></p>
<p>There you go. So whenever you need to search your database for strings, you know how it&#8217;s done!!</p>
<p>Hope this was helpful, make use of it well!! <img src='http://nullablecode.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://nullablecode.com/2011/05/sql-how-to-search-all-procs-for-a-string/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SQL Server Hierarchyid</title>
		<link>http://nullablecode.com/2011/05/sql-server-hierarchyid/</link>
		<comments>http://nullablecode.com/2011/05/sql-server-hierarchyid/#comments</comments>
		<pubDate>Tue, 03 May 2011 07:13:46 +0000</pubDate>
		<dc:creator>nullablecode</dc:creator>
				<category><![CDATA[Everything]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://nullablecode.com/?p=529</guid>
		<description><![CDATA[HIERARCHICAL structures are everywhere! Your family structure, Ancestral history, your phone and address books, corporate structures &#8211; all resemble a<a href="http://nullablecode.com/2011/05/sql-server-hierarchyid/" class="searchmore">Read the Rest...</a><div class="clr"></div>]]></description>
			<content:encoded><![CDATA[<p><strong>HIERARCHICAL</strong> structures are everywhere! Your family structure, Ancestral history, your phone and address books, corporate structures &#8211; all resemble a well defined hierarchy.</p>
<p>The simplest representation of hierarchies is in the form of an upside down &#8216;<strong>Tree</strong>&#8216;.  The &#8216;<strong>root</strong>&#8216; of the tree is where it all begins, the &#8216;root&#8217; expands into multiple &#8216;<strong>tree nodes</strong>&#8216;, these &#8216;tree nodes&#8217; may contain other tree nodes; and at the end of each &#8216;tree node&#8217; is a &#8216;<strong>leaf node</strong>&#8216;..  for more information on data tree structures please refer to this article: <a href="http://en.wikipedia.org/wiki/Tree_(data_structure)" target="_blank">Tree (data structure)</a></p>
<p>In software development, no doubt you would have come across tree structures, and specifically hierarchical data structures, in your career. One pitfall that you would have experienced is that computing the entire tree structure on the fly for any system is a costly process. As the saying goes &#8216;..the apple never falls far from the tree&#8217;, and thus even computing the structure of a single tree node can be just as costly.</p>
<p>This is where a special data type in SQL comes to play: the <a href="http://technet.microsoft.com/en-us/library/bb677290.aspx" target="_blank">hierarchyid type</a>!  In this article I will explain what the herierachyid type is, and provide examples on how you can use this in your database design for a clean, succinct data structure, and how you will benefit from the massive performance gains by doing so..</p>
<p><span id="more-529"></span></p>
<p><span style="text-decoration: underline; font-size: medium;"><strong>The Basics</strong></span></p>
<p><em><span style="font-size: medium;"><strong>Tree Structures</strong></span></em></p>
<p>A well defined hierarchical structure can be achieved in many different ways within SQL server; ranging from simple self-referencing tables, to more complex one-to-one, or one-to-many relation tables. No matter what your design is you cannot move away from having an EntityID column and a ParentEntityID column (or a similar field referencing its parent entity).  These two fields are the fundamental properties that define your hierarchical structure&#8230; think of them as your link between one &#8216;tree branch&#8217; to the next &#8216;tree branch&#8217;. You can traverse up the tree and ultimately reach the &#8216;root&#8217; entity (remember the tree is upside down!). Or you can traverse down the tree and ultimately reach the &#8216;leaf nodes&#8217;.</p>
<p><em><span style="font-size: medium;"><strong>Time consuming computations</strong></span></em></p>
<p>Computing the structure on-the-fly is pretty demanding, even if its processing within SQL Server. The idea is that if you have a random tree node, and wish to retrieve all descendants (ie every other tree node and leaf node below the current selected node) then the system needs to traverse quite possibly a large number of nodes.. processing each node recursively as it goes, until it ultimately reaches nodes without any child nodes (aka the leaf node).</p>
<p>In practice, if you consider an organisation structure with Managers (represented by tree nodes) and Employees (represented by leaf nodes).. then this is analogous to retrieving all Employees under a certain Manager..  say the CIO and all employees reporting underneath him/her.</p>
<p>The same logic applies if you wish to go up the tree to find all the ancestors of a given leaf node. With the organisation example above, this is like grabbing all Upper Managers for an Employee.</p>
<p>Whatever your requirement is, there is bound to be a need for tree traversal. Often is the case that if you have a poorly designed database structure then your system will be plagued by poor performance.</p>
<p><span style="font-size: medium;"><em><strong>The Alternative Solution</strong></em></span></p>
<p>One way of achieving great performance in such a scenario is by the use of SQL hierarchyid types. hierarchyid types help alleviate the computation stress on your server by pre-computing the relationship amongst records at the time of insertion.</p>
<p>What is stored in the hierarchyid column is the binary representation of the full entity path from its root entity. This is near-identical to the <a href="http://en.wikipedia.org/wiki/Path_(computing)#Unix_style">Unix File system</a> and how they represent file paths:</p>
<ul>
<li>&#8216;/&#8217; &#8211; denotes the root entity path</li>
<li>&#8216;/Files&#8217; &#8211; denotes the path to the Files folder</li>
<li>&#8216;/Files/test.log&#8217; &#8211; denotes the path to a file called test.log inside the Files folder.. and so on</li>
</ul>
<p>Instead of using alphanumeric values for pathing, SQL Server hierarchyids are represented by numeric values:</p>
<ul>
<li>&#8216;/&#8217; &#8211; denotes the root entity path</li>
<li>&#8216;/1/&#8217; &#8211; denotes the first child added to the structure</li>
<li>&#8216;/2/&#8217; &#8211; denotes the second child added to the structure</li>
<li>&#8216;/2/1/&#8217; &#8211; denotes the first sub child added underneath the second child of the root entity</li>
</ul>
<p>SQL Server automatically calculates the logical path of the entity being inserted. It does this by inspecting the hierarchyid of the Parent entity for which the new entity is to be attached to.</p>
<p><span style="font-size: medium;"><strong><em>Hierarchyid Methods</em></strong></span></p>
<p>SQL Server has built in functions that help you navigate and retrieve data tied to hierarchyid fields.</p>
<ul>
<li><strong>GetAncestor </strong>(int n) &#8211; Gets the n&#8217;th ancestor of the entity</li>
<li><strong>IsDescendantOf </strong>(hierarhcyid h) &#8211; Returns true if the current entity is a descendant of &#8216;h&#8217;</li>
<li><strong>ToString </strong>() &#8211; Returns the logical path of the entity in string format</li>
<li><strong>GetDescendant </strong>(child1, child2) &#8211; Returns a child hierarchyid of the current entity. The output varies based on the value of the two input parameters.</li>
</ul>
<p>These are some of the more common methods that you will be using. The usage syntax is pretty straight forward. All you need to do is simply call the method on a hierarchyid variable or field.</p>
<p>For example:</p>
<pre class="brush: sql; title: ; notranslate">
DECLARE @Manager hierarchyid
SELECT @Manager = CAST('/3/1' AS hierarchyid)

-- Returns all Employees that is a descendant of @Manager
SELECT *
FROM Employee E
WHERE E.Hierarchy.IsDescendantOf(@Manager) = 1
</pre>
<p><span style="text-decoration: underline;"><strong><span style="font-size: medium;">Practical Example</span></strong></span></p>
<p>Consider the following database schema:</p>
<p><img title="20110503_002147" src="http://nullablecode.com/wp-content/uploads/2011/05/20110503_002147.png" alt="" width="282" height="198" /></p>
<p>Before we proceed to insert sample data, lets visit the INSERT logic for this table.</p>
<p><span style="font-size: medium; text-decoration: underline;"><strong>Insert Logic</strong></span></p>
<p>The general idea is as follows:</p>
<ol>
<li>Check if this is the first &#8216;root&#8217; entity to be inserted.</li>
<li>If true: the hierarchyid = to the root path of &#8216;/&#8217;.</li>
<li>If false: we need to grab the Manager record and use its hierarchyid to determine the next hierarchyid for its next child.</li>
<li>Once we determine the new child hierarchyid, we can proceed with the insert.</li>
</ol>
<p>The complex part is determining the next hierarchyid to insert for this new child record.</p>
<ul>
<li><strong>GetAncestor(1) = @ManagerHierarchyID:</strong> This formula simply filters the records and returns all the children of the record identified with hierarchyid = @ManagerHierarchyID</li>
<li><strong>NewHierarchyID = MAX(Hierarchy):</strong> Returns the last child record in the list</li>
<li><strong>GetDescendant(@NewHierarchyID, NULL): </strong>Generates the next hierarchyid AFTER that of @NewHierarchyID. In other words, whatever the path is defined as the last child record, generate the subsequent hierarchyid. So if @NewHierarchyID = &#8216;/1/2/&#8217;, this method call will return &#8217;1/3/&#8217;</li>
</ul>
<p><span style="font-size: medium;"><em><strong><span style="text-decoration: underline;">Insert</span></strong></em></span></p>
<pre class="brush: sql; title: ; notranslate">
CREATE PROC [dbo].[uspEmployee_Insert]
	@EmployeeID		VARCHAR(5)
	, @Firstname	VARCHAR(50)
	, @Surname		VARCHAR(50)
	, @PositionTitle	VARCHAR(50)
	, @ManagerID		VARCHAR(5)
AS
BEGIN

	DECLARE @ManagerHierarchyID hierarchyid
	DECLARE @NewHierarchyID hierarchyid

	IF @ManagerID IS NULL
	BEGIN
		SET @NewHierarchyID = hierarchyid::GetRoot()
	END
	ELSE
	BEGIN

		-- [1] Identify the Manager Record
		-- [2] Find the LAST child attached to the Manager Record (we need this when calling the GetDescendant method)
		-- [3] Generate the next hierarchyid that is AFTER the LAST child retrieved above
		-- [4] Insert the new Employee with the newly generated hierarchyid

		-- [1]
		SELECT @ManagerHierarchyID = E.Hierarchy
		FROM Employee E
		WHERE E.EmployeeID = @ManagerID

		-- [2]
		SELECT @NewHierarchyID = MAX(Hierarchy)
		FROM Employee E
		WHERE E.Hierarchy.GetAncestor(1) = @ManagerHierarchyID

		-- [3]
		SELECT @NewHierarchyID = @ManagerHierarchyID.GetDescendant(@NewHierarchyID, NULL)
	END

	-- [4]
	INSERT INTO Employee
	SELECT @EmployeeID
			, @Firstname
			, @Surname
			, @PositionTitle
			, @NewHierarchyID

END
</pre>
<p>With this completed, we can now create a hierarchical structure for our table!</p>
<p><span style="font-size: medium;"><em><strong>Data Insert</strong></em></span></p>
<p>The follow SQL will generate a small organisation structure as depicted below:</p>
<p><img title="20110503-220039" src="http://nullablecode.com/wp-content/uploads/2011/05/20110503-220039.png" alt="" width="573" height="349" /></p>
<pre class="brush: sql; title: ; notranslate">
EXEC [dbo].[uspEmployee_Insert] @EmployeeID = N'E0001',	@Firstname = N'David',		@Surname = N'Smith',		@PositionTitle = N'CEO',			@ManagerID = NULL
EXEC [dbo].[uspEmployee_Insert] @EmployeeID = N'E0002',	@Firstname = N'Peter',		@Surname = N'Levy',			@PositionTitle = N'COO',			@ManagerID = 'E0001'
EXEC [dbo].[uspEmployee_Insert] @EmployeeID = N'E0003',	@Firstname = N'Trevor',		@Surname = N'Bailey',		@PositionTitle = N'GTS Manager',	@ManagerID = 'E0001'
EXEC [dbo].[uspEmployee_Insert] @EmployeeID = N'E0004',	@Firstname = N'Kurt',		@Surname = N'Douglas',		@PositionTitle = N'Sales Director',	@ManagerID = 'E0001'
EXEC [dbo].[uspEmployee_Insert] @EmployeeID = N'E0005',	@Firstname = N'Ken',		@Surname = N'Kumar',		@PositionTitle = N'CIO',			@ManagerID = 'E0002'
EXEC [dbo].[uspEmployee_Insert] @EmployeeID = N'E0006',	@Firstname = N'Samantha',	@Surname = N'Dwellings',	@PositionTitle = N'HR General Manager',	@ManagerID = 'E0002'
EXEC [dbo].[uspEmployee_Insert] @EmployeeID = N'E0007',	@Firstname = N'Verity',		@Surname = N'McDonald',		@PositionTitle = N'IT Manager',		@ManagerID = 'E0005'
EXEC [dbo].[uspEmployee_Insert] @EmployeeID = N'E0008',	@Firstname = N'Douglas',	@Surname = N'Morgan',		@PositionTitle = N'IT Developer',	@ManagerID = 'E0007'
EXEC [dbo].[uspEmployee_Insert] @EmployeeID = N'E0009',	@Firstname = N'Paul',		@Surname = N'Lynch',		@PositionTitle = N'BI Developer',	@ManagerID = 'E0007'
EXEC [dbo].[uspEmployee_Insert] @EmployeeID = N'E0010',	@Firstname = N'Jenny',		@Surname = N'Davison',		@PositionTitle = N'DB Developer',	@ManagerID = 'E0007'
EXEC [dbo].[uspEmployee_Insert] @EmployeeID = N'E0011',	@Firstname = N'Monica',		@Surname = N'Adams',		@PositionTitle = N'HR Manager',		@ManagerID = 'E0006'
EXEC [dbo].[uspEmployee_Insert] @EmployeeID = N'E0012',	@Firstname = N'Bree',		@Surname = N'Lucas',		@PositionTitle = N'HR Advisor',		@ManagerID = 'E0011'
</pre>
<p>You should now have the following records in your Employee table:</p>
<p><img title="20110503_113900" src="http://nullablecode.com/wp-content/uploads/2011/05/20110503_113900.png" alt="" width="481" height="297" /></p>
<p><span style="font-size: medium; text-decoration: underline;"><strong>Retrieval Logic</strong></span></p>
<p>This is where the fun starts&#8230; In the examples below, I will use Employee E0006 (HR General Manager) as a point of reference.</p>
<p><span style="font-size: medium;"><em><strong>All Child records</strong></em></span></p>
<p>Firstly, to retrieve all the Children for an Employee we use ﻿﻿﻿the logic: ﻿﻿</p>
<ul>
<li>item.GetAncestor(1) = @SourceHierarchyID</li>
</ul>
<p>The GetAncestor() method returns all records that is an ancestor (ie parent) of the current item. The parameter defines how far up the hierarchy you wish to go. So the above logic returns records &#8216;one level&#8217; above the current item which is our queried E0006 Employee.</p>
<pre class="brush: sql; title: ; notranslate">
	DECLARE @SourceHierarchyID AS hierarchyid

	SELECT @SourceHierarchyID = E.Hierarchy
	FROM Employee E
	WHERE E.EmployeeID = 'E0006'

	SELECT 'E0006'				AS EmployeeID
			, E.EmployeeID		AS ChildEmployeeID
			, E.Firstname		AS ChildFirstname
			, E.Surname			AS ChildSurname
			, E.PositionTitle	AS ChildPositionTitle
			, E.Hierarchy		AS ChildHierarchy
			, E.Hierarchy.GetLevel()	AS Level
	FROM Employee E
	WHERE E.Hierarchy.GetAncestor(1) = @SourceHierarchyID
	ORDER BY E.Hierarchy.GetLevel() ASC
</pre>
<p>Wrapping this into a completed function:</p>
<pre class="brush: sql; title: ; notranslate">
CREATE FUNCTION [dbo].[udfEmployee_GetAllChildrenByEmployeeID]
(
	@SourceEmployeeID AS VARCHAR(5)
)
RETURNS @tbl TABLE (EmployeeID				VARCHAR(5)
					, ChildEmployeeID		VARCHAR(5)
					, ChildFirstname		VARCHAR(50)
					, ChildSurname			VARCHAR(50)
					, ChildPositionTitle	VARCHAR(50)
					, ChildHierarchy		hierarchyid
					, ChildLevel			INT
					)

AS
BEGIN

	DECLARE @SourceHierarchyID AS hierarchyid

	SELECT @SourceHierarchyID = E.Hierarchy
	FROM Employee E
	WHERE E.EmployeeID = @SourceEmployeeID

	INSERT INTO @tbl
	SELECT @SourceEmployeeID	AS EmployeeID
			, E.EmployeeID		AS ChildEmployeeID
			, E.Firstname		AS ChildFirstname
			, E.Surname			AS ChildSurname
			, E.PositionTitle	AS ChildPositionTitle
			, E.Hierarchy		AS ChildHierarchy
			, E.Hierarchy.GetLevel()	AS Level
	FROM Employee E
	WHERE E.Hierarchy.GetAncestor(1) = @SourceHierarchyID
	ORDER BY E.Hierarchy.GetLevel() ASC

	RETURN

END
</pre>
<p>To call this new function, pass it the EmployeeID of the reference entity you want to start with; and it should return all child records as requested:</p>
<pre class="brush: sql; title: ; notranslate">
SELECT *
FROM dbo.udfEmployee_GetAllChildrenByEmployeeID ('E0006') t
</pre>
<p><span style="font-size: medium;"><em><strong>All Child records: output</strong></em></span></p>
<p><em><img title="20110503_114403" src="http://nullablecode.com/wp-content/uploads/2011/05/20110503_114403.png" alt="" width="632" height="73" /></em></p>
<p><span style="font-size: medium;"><em><strong>All Descendant records</strong></em></span></p>
<p>Another common function is the retrieval of all child records, done recursively until the bottom of the tree structure is reached. This is referred to as all the descendants of an entity.</p>
<p><span style="color: #ff0000;"><strong>note</strong></span>: <strong>﻿IsDescendantOf (@SourceHierarchyID)</strong> will return true if the parameter object is a sub child, or the parameter object itself. In otherwords, an entity is a descendant of itself&#8230;!</p>
<pre class="brush: sql; title: ; notranslate">
CREATE FUNCTION [dbo].[udfEmployee_GetAllDescendantsByEmployeeID]
(
	@SourceEmployeeID AS VARCHAR(5)
)
RETURNS @tbl TABLE (EmployeeID				VARCHAR(5)
					, ChildEmployeeID		VARCHAR(5)
					, ChildFirstname		VARCHAR(50)
					, ChildSurname			VARCHAR(50)
					, ChildPositionTitle	VARCHAR(50)
					, ChildHierarchy		hierarchyid
					, ChildLevel			INT
					)

AS
BEGIN

	DECLARE @SourceHierarchyID AS hierarchyid

	SELECT @SourceHierarchyID = E.Hierarchy
	FROM Employee E
	WHERE E.EmployeeID = @SourceEmployeeID

	INSERT INTO @tbl
	SELECT @SourceEmployeeID	AS EmployeeID
			, E.EmployeeID		AS ChildEmployeeID
			, E.Firstname		AS ChildFirstname
			, E.Surname			AS ChildSurname
			, E.PositionTitle	AS ChildPositionTitle
			, E.Hierarchy		AS ChildHierarchy
			, E.Hierarchy.GetLevel()	AS Level
	FROM Employee E
	WHERE E.Hierarchy.IsDescendantOf(@SourceHierarchyID) = 1
	ORDER BY E.Hierarchy.GetLevel() ASC

	RETURN

END
</pre>
<p>&nbsp;</p>
<pre class="brush: sql; title: ; notranslate">
SELECT *
FROM dbo.udfEmployee_GetAllDescendantsByEmployeeID ('E0006') t
</pre>
<p><span style="font-size: medium;"><em><strong>All Descendant records: output</strong></em></span></p>
<p><em><img title="20110503_114504" src="http://nullablecode.com/wp-content/uploads/2011/05/20110503_114504.png" alt="" width="650" height="107" /></em></p>
<p><span style="font-size: medium;"><em><strong>All Ancestor records</strong></em></span></p>
<p>This is the opposite of All Descendants and simply goes up the tree until the root entity is returned.</p>
<pre class="brush: sql; title: ; notranslate">
CREATE FUNCTION [dbo].[udfEmployee_GetAllAncestorsByEmployeeID]
(
	@SourceEmployeeID AS VARCHAR(5)
)
RETURNS @tbl TABLE (EmployeeID				VARCHAR(5)
					, ChildEmployeeID		VARCHAR(5)
					, ChildFirstname		VARCHAR(50)
					, ChildSurname			VARCHAR(50)
					, ChildPositionTitle	VARCHAR(50)
					, ChildHierarchy		hierarchyid
					, ChildLevel			INT
					)

AS
BEGIN

	DECLARE @SourceHierarchyID AS hierarchyid

	SELECT @SourceHierarchyID = E.Hierarchy
	FROM Employee E
	WHERE E.EmployeeID = @SourceEmployeeID

	INSERT INTO @tbl
	SELECT @SourceEmployeeID	AS EmployeeID
			, E.EmployeeID		AS ChildEmployeeID
			, E.Firstname		AS ChildFirstname
			, E.Surname			AS ChildSurname
			, E.PositionTitle	AS ChildPositionTitle
			, E.Hierarchy		AS ChildHierarchy
			, E.Hierarchy.GetLevel()	AS Level
	FROM Employee E
	WHERE @SourceHierarchyID.IsDescendantOf(E.Hierarchy) = 1
	ORDER BY E.Hierarchy.GetLevel() DESC

	RETURN

END
</pre>
<p><span style="font-size: medium;"><em><strong>All Ancestor records: output</strong></em></span></p>
<p><em><img title="20110503_114605" src="http://nullablecode.com/wp-content/uploads/2011/05/20110503_114605.png" alt="" width="648" height="110" /></em></p>
<p><span style="font-size: medium;"><em><strong>All Sibling records</strong></em></span></p>
<p>A Sibling is considered all entities with the same parent entitiy. So in this example, all siblins of E0006 has the same Manager of E0006 which is E0002.</p>
<pre class="brush: sql; title: ; notranslate">
CREATE FUNCTION [dbo].[udfEmployee_GetAllSiblingsByEmployeeID]
(
	@SourceEmployeeID AS VARCHAR(5)
)
RETURNS @tbl TABLE (EmployeeID				VARCHAR(5)
					, ChildEmployeeID		VARCHAR(5)
					, ChildFirstname		VARCHAR(50)
					, ChildSurname			VARCHAR(50)
					, ChildPositionTitle	VARCHAR(50)
					, ChildHierarchy		hierarchyid
					, ChildLevel			INT
					)

AS
BEGIN

	DECLARE @ManagerHierarchyID AS hierarchyid

	SELECT @ManagerHierarchyID = E.Hierarchy.GetAncestor(1)
	FROM Employee E
	WHERE E.EmployeeID = @SourceEmployeeID

	INSERT INTO @tbl
	SELECT @SourceEmployeeID	AS EmployeeID
			, E.EmployeeID		AS ChildEmployeeID
			, E.Firstname		AS ChildFirstname
			, E.Surname			AS ChildSurname
			, E.PositionTitle	AS ChildPositionTitle
			, E.Hierarchy		AS ChildHierarchy
			, E.Hierarchy.GetLevel()	AS Level
	FROM Employee E
	WHERE @ManagerHierarchyID = E.Hierarchy.GetAncestor(1)
	ORDER BY E.Hierarchy.GetLevel() DESC

	RETURN

END
</pre>
<p><span style="font-size: medium;"><em><strong>All Sibling records: output</strong></em></span></p>
<p><img title="20110503_114706" src="http://nullablecode.com/wp-content/uploads/2011/05/20110503_114706.png" alt="" width="648" height="88" /></p>
<p><span style="font-size: medium; text-decoration: underline;"><strong>Update / Move Logic</strong></span></p>
<p>Finally, one last thing to cover&#8230; is the ability to move an entity and its entire sub-hierarchy into a different branch of the tree. E0006 (HR General Manager) currently reports to E0002 (COO). If we wanted to move E0006 to report under say E0005 (CIO), we need to perform the following logic:</p>
<ol>
<li>﻿Grab the Manager record and use its hierarchyid to determine the next hierarchyid for its next child.</li>
<li>Once we determine the new child hierarchyid, we use ﻿GetReparentedValue(@oldH, @newH) to restructure the current entity and its entire sub-tree.</li>
</ol>
<p>The complete logic to achieve this update is as follows:</p>
<pre class="brush: sql; title: ; notranslate">
ALTER PROCEDURE [dbo].[uspEmployee_Move](
	@EmployeeID			AS VARCHAR(5)
	, @NewManagerID		AS VARCHAR(5)
)
AS
BEGIN

	DECLARE @oldH hierarchyid
	DECLARE @newH hierarchyid
	DECLARE @ManagerHierarchyID hierarchyid

	SELECT @oldH = E.Hierarchy
	FROM Employee E
	WHERE E.EmployeeID = @EmployeeID

	SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
	BEGIN TRANSACTION

		-- [1] Identify the Manager Record
		-- [2] Find the LAST child attached to the Manager Record (we need this when calling the GetDescendant method)
		-- [3] Generate the next hierarchyid that is AFTER the LAST child retrieved above
		-- [4] Insert the new Employee with the newly generated hierarchyid

		-- [1]
		SELECT @ManagerHierarchyID = Hierarchy
		FROM Employee e
		WHERE E.EmployeeID = @NewManagerID

		-- [2]
		SELECT @newH = MAX(Hierarchy)
		FROM Employee E
		WHERE E.Hierarchy.GetAncestor(1) = @ManagerHierarchyID

		-- [3]
		SELECT @newH = @ManagerHierarchyID.GetDescendant(@newH, NULL)

		UPDATE Employee
		SET Hierarchy = Hierarchy.GetReparentedValue(@oldH, @newH)
		WHERE Hierarchy.IsDescendantOf(@oldH) = 1

	COMMIT
END
</pre>
<p>Once we have this Stored Procedure created, we can now safely test it out. As above, lets move the entire sub-tree of E0006 to report to E0005.  Below you will find the snippet that does this, along with the reversal back to the original structure.</p>
<pre class="brush: sql; title: ; notranslate">
-- Move E0006 (HR General Manager) to report under E0005 (CIO)
-- Note the recursive native of the update will also change the hierarhcy for descendants of E0006
EXEC	[dbo].[uspEmployee_Move]
		@EmployeeID = N'E0006',
		@NewManagerID = N'E0005'

-- Move back E0006 (HR General Manager) to report under E0002 (COO)
EXEC	[dbo].[uspEmployee_Move]
		@EmployeeID = N'E0006',
		@NewManagerID = N'E0002'
</pre>
<p><span style="font-size: medium;"><em><strong>Update / Move: Before the change</strong></em></span></p>
<p><img title="20110503_113901" src="http://nullablecode.com/wp-content/uploads/2011/05/20110503_113901.png" alt="" width="484" height="296" /></p>
<p><span style="font-size: medium;"><em><strong>Update / Move: After the change</strong></em></span></p>
<p><em><img title="20110503_114102" src="http://nullablecode.com/wp-content/uploads/2011/05/20110503_114102.png" alt="" width="483" height="296" /></em></p>
<p><span style="font-size: medium; text-decoration: underline;"><strong>Conclusion</strong></span></p>
<p>If you&#8217;ve come this far, well done!  Hope this article has given you insight into the SQL Server hierarchyid types. Along with that, you should now be in a better position to decide whether hierarchyid types is well suited for your system, or whether you prefer traditional data relationships to define your data structure.</p>
<p>If you have any questions, let me know. <img src='http://nullablecode.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://nullablecode.com/2011/05/sql-server-hierarchyid/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Pagination and Sorting via SQL</title>
		<link>http://nullablecode.com/2011/04/pagination-and-sorting-via-sql/</link>
		<comments>http://nullablecode.com/2011/04/pagination-and-sorting-via-sql/#comments</comments>
		<pubDate>Sun, 03 Apr 2011 00:18:02 +0000</pubDate>
		<dc:creator>nullablecode</dc:creator>
				<category><![CDATA[Everything]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[pagination]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://nullablecode.com/?p=463</guid>
		<description><![CDATA[PAGINATION is the concept of splitting a larger data set into several smaller sets before transferring and displaying to the<a href="http://nullablecode.com/2011/04/pagination-and-sorting-via-sql/" class="searchmore">Read the Rest...</a><div class="clr"></div>]]></description>
			<content:encoded><![CDATA[<p><strong>PAGINATION </strong>is the concept of splitting a larger data set into several smaller sets before transferring and displaying to the user. What this means is that instead of sending large bulks of information across the wire, that would otherwise consume a lot of resources (network traffic, memory/cache etc), we split the large bulks into smaller manageable chunks and only handle as much data that is needed.</p>
<p>Pagination can be seen everywhere; from Blogs and Forums, to News sites. All these use some form of pagination or another. Without pagination Forums would be showing thousands of topics at once instead of showing 20 topics per page; Blogs would be showing hundreds of blog posts per page instead of 10 posts per page. News sites&#8230; well.. they would take a rather long time to load if they displayed all of articles at once!</p>
<p>There are several forms of Pagination available; and no doubt you would have come across one or more already:</p>
<ul>
<li>The first is what I refer to as <strong>Preemptive Loading</strong></li>
<li>The second is <strong>On Demand Loading</strong></li>
</ul>
<p>In this article I will explain each of these in detail. I will explain the short comings of Preemptive Loading, and the benefits of On Demand Loading; and also explain how On Demand Loading can be achieved via SQL Server&#8230;</p>
<p><span id="more-463"></span></p>
<p><span style="text-decoration: underline;"><span style="font-size: medium;"><strong>Different Types of Pagination</strong></span></span></p>
<p><span style="font-size: medium;"><strong>Preemptive Loading:</strong></span><span style="text-decoration: underline;"><span style="font-size: medium;"><strong> </strong></span></span></p>
<p><strong> </strong></p>
<p>The First, and easiest type of Pagination is Client side pagination. This is when all the data that &#8216;may be&#8217; required to be displayed is transferred from the Server to the Client all one go; and then pagination is achieved on the Client side through local components (such as data grids, data pagers, or custom logic). I call it <strong>Preemptive Loading</strong>. The key point in preemptive loading is that all entities available to the paged component are loaded even before the data is visible to the user. Is this good or bad ?</p>
<p>There&#8217;s no distinctive answer because some times, preloading is amazing from a usability point of view.  But preloading can also mean trouble when loading massive amounts of unnecessary data.</p>
<p><span style="font-size: medium;"><strong>Preemptive Loading &#8211; When it&#8217;s Good:</strong></span></p>
<p>Take an Image Gallery application for example. You click on a thumbnail to preview the full sized image; navigation options allow you to view Previous and Next images in the gallery. This is a great example where preloading the next image is great! When the user clicks next, the image is already preloaded for viewing immediately; and this would then trigger another preload for the next image in the list and so forth.  From a usability point of view, the images appear right away instead of waiting for the system to transfer the file &#8216;after&#8217; the user has clicked &#8216;next&#8217;.</p>
<p><span style="font-size: medium;"><strong>Preemptive Loading &#8211; When it&#8217;s Bad:</strong></span></p>
<p>Hypothetically, say that you have a Blog that stores 1mb of data for each page; and that the system has been built to preload a total of 5 pages (refer to the image below). A total of 5mb is transferred on initial load. What would happen if the user only wanted to view the 1st page. The system would have processed and transferred a total of 5mb when only 1mb of data was really needed by the user. Multiply this with 100 concurrent users, and you will being to see the impact this will have on the overall system performance.</p>
<p><strong>Premptive Loading: Total = 5 pages. 1mb per page.</strong></p>
<p><img title="20110403-233626" src="http://nullablecode.com/wp-content/uploads/2011/04/20110403-233626.png" alt="" width="500" height="265" /></p>
<p><span style="font-size: medium;"><strong>On Demand Loading:</strong></span></p>
<p>The second type of Pagination is what I call <strong>On Demand Loading</strong>; and this is the opposite of Preemptive Loading. On Demand Loading refers to a &#8216;delayed&#8217; loading of the data, and when loads it only loads enough data that has been requested by the user.</p>
<p>Take for example a Forum that holds a total of 5000 topics. The Forum has been Paginated to show the first 1000 topics (lets say 1000 topics = 1mb for example). With <strong>Preemptive Loading</strong>, 5 pages of 1000 topics each would have been transferred at once; a total of 5mb. On the other hand, with <strong>On Demand Loading</strong>, a mere 1 page with 1000 topics are transferred; saving the system 4mb of unnecessary bandwidth! In contrast to the above diagram, the diagram below depicts On Demand Loading with 1mb of data transfer per page, per request.</p>
<p>Examples like this is exactly where you should prefer a system with On Demand Loading over Preemptive Loading!</p>
<p><strong>On Demand Loading: Total = 1 page. 1mb per page.</strong></p>
<p><img title="20110403-233900" src="http://nullablecode.com/wp-content/uploads/2011/04/20110403-233900.png" alt="" width="500" height="265" /></p>
<p><span style="text-decoration: underline; font-size: medium;"><strong>Is it really necessary ?</strong></span></p>
<p>For small to medium sized applications <strong>On Demand Loading </strong>might not be necessary; and it could be more trouble than what it is worth. However <strong>On Demand Loading </strong>in the essence of pagination is critical to Enterprise development as a means of achieving high efficiency and performance output in the system.</p>
<p><span style="text-decoration: underline; font-size: medium;"><strong>So how do I get it done ?</strong></span></p>
<p>Here I will show you how you can achieve <strong>On Demand Loading </strong>using SQL Server.</p>
<p>A) Start by creating a <span style="text-decoration: underline;"><strong>Product</strong></span><strong> </strong>table in your database. You can use the following script to do so&#8230;:</p>
<p><img title="20110330-230259" src="http://nullablecode.com/wp-content/uploads/2011/04/20110330-230259.png" alt="" width="346" height="253" /></p>
<pre class="brush: sql; title: ; notranslate">
CREATE TABLE [dbo].[Product](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](50) NOT NULL,
	[Price] [decimal](18, 2) NOT NULL,
	[CurrentProduct] [bit] NOT NULL,
	[Quantity] [int] NOT NULL,
	[ExpiryDate] [datetime] NOT NULL,
	[Supplier] [nvarchar](50) NULL,
	[Ranking] [int] NOT NULL,
 CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
</pre>
<p>B) Script out a few hundred records and insert them into the Product table.</p>
<p>C) Once you&#8217;ve done that create a stored procedure with the following signature:</p>
<pre class="brush: sql; title: ; notranslate">
CREATE PROCEDURE [dbo].[uspProduct_GetAllProducts]
	@SearchString				AS VARCHAR(50)
	, @SortColumn				AS VARCHAR(100)
	, @SortAscending			AS BIT
	, @PageIndex				AS INT
	, @PageSize					AS INT
	, @TotalCount				AS INT OUTPUT
AS
BEGIN
END
</pre>
<p>Parameters:</p>
<ul>
<li>@SearchString: A filtering parameter to limit our data (optional).</li>
<li>@SortColumn: The name of the data column for which our data set will be ordered by.</li>
<li>@SortAscending: A boolean value specifying whether to sort ascending or not.</li>
<li>@PageIndex: The page index of the data that we want returned.</li>
<li>@PageSize: The number of entities per page</li>
<li>@TotalCount: Output parameter that will hold the total number entities that matched the query</li>
</ul>
<p><strong> </strong></p>
<p><span style="font-size: medium;"><strong>The Design</strong></span></p>
<p>Before I dive into the body, let me give you the overall design for this stored procedure.</p>
<p>The concept behind SQL Pagination is as follows:</p>
<ol>
<li>Create <strong>temporary </strong>table to hold ALL the records matching your query. This table is to hold a column called RowNumber which will be unique per row.</li>
<li>Insert ALL records that match your query into the temporary table. For the RowNumber column use the SQL &#8216;<strong>OVER</strong>&#8216; clause to sort and order the records</li>
<li>Set the <strong>@TotalCount</strong> output parameter from the temporary table by using a simple SELECT COUNT(*)</li>
<li>Paginate the data in your temporary table by using the <strong>RowNumber</strong>, <strong>@PageIndex</strong> and <strong>@PageSize</strong> values to return all records GREATER THAN [first entity] AND LESS THEN [last entity]</li>
</ol>
<p>Now that we have the concept at hand, lets check out the code..</p>
<p>D) Declare your temporary table as follows. Note the RowNumber field in this temporary table that will store the sort order of the records.</p>
<pre class="brush: sql; title: ; notranslate">
	DECLARE @tmp AS TABLE (
			RowNumber				INT
			, ProductID				INT
			, Name					NVARCHAR(50)
			, Price					DECIMAL(18,2)
			, CurrentProduct		BIT
			, Quantity				INT
			, ExpiryDate			DATETIME
			, Supplier				NVARCHAR(50)
			, Ranking				INT
			)
</pre>
<p>Below is the main query. This should be changed to your own custom logic to filter out the records prior to pagination. For this example, we simply filter all products that match our <strong>@SearchString</strong> parameter.</p>
<pre class="brush: sql; title: ; notranslate">
			-- The main SQL query that returns ALL the valid data
			SELECT *
			FROM Product P
			WHERE P.Name like '%' + ISNULL(@SearchString, '') + '%'
</pre>
<p><span style="font-size: medium;"><strong>Sorting using the SQL &#8216;OVER&#8217; clause:</strong></span></p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/ms189461.aspx" target="_blank">SQL Server &#8216;OVER&#8217;</a> clause allows you to order your record set and generate row rankings across an ORDER BY subquery. What this means is that you have an ORDER BY clause that will sort based on the input parameters <strong>@SortColumn</strong> and <strong>@SortAscending</strong>. Then based on this ordering, your record set (ie your main query records) are then ordered by the <strong>ROW_NUMBER</strong> function based on the ORDER BY subquery.  The end result is that your temporary table will be populated with RowNumbers 1 to xxx in the sort order specified by your <strong>@Sort</strong> Parameters.</p>
<p>E) Below is a snippet on how to number our records based on the &#8216;ID&#8217; column:</p>
<pre class="brush: sql; title: ; notranslate">
	INSERT INTO @tmp
	SELECT ROW_NUMBER() OVER
	( ORDER BY
		CASE		-- Numeric ASC
			WHEN @SortColumn = 'ID' AND @SortAscending = 1 THEN Q.ID
			ELSE NULL
		END ASC
		, CASE		-- Numeric DESC
			WHEN @SortColumn = 'ID' AND @SortAscending = 0 THEN Q.ID
			ELSE NULL
		END DESC
	) AS RowNumber
	, Q.ID
	, Q.Name
	, Q.Price
	, Q.CurrentProduct
	, Q.Quantity
	, Q.ExpiryDate
	, Q.Supplier
	, Q.Ranking
	FROM (
			-- The main SQL query that returns ALL the valid data
			SELECT *
			FROM Product P
			WHERE P.Name like '%' + ISNULL(@SearchString, '') + '%'
	) AS Q
</pre>
<p>F) Once you have all the records in your temporary table. You can now set the <strong>@TotalCount</strong> output parameter as follows:</p>
<pre class="brush: sql; title: ; notranslate">
	SET @TotalCount = ISNULL((SELECT COUNT(RowNumber) FROM @tmp), 0)
</pre>
<p>G) Finally, you can now safely paginate your temporary table data and return the paginated data as per the <strong>@PageIndex</strong> and <strong>@PageSize </strong>values.  There&#8217;s some small logic here to grab the correct minimum RowNumber and maximum RowNumber values.. but other than that, it should be straight forward:</p>
<p><span style="color: #ff0000;"><strong>NOTE: </strong></span>Passing in <strong>@PageIndex</strong> = -1, <strong>@PageSize</strong> = -1 will return ALL records from your query un-paginated. This can be changed as you see fit in the logic below. But I have added this logic incase it was needed.</p>
<pre class="brush: sql; title: ; notranslate">
	-- The final SQL query that returns:
	--		The PAGINATED data only, Sorted as specified
	SELECT *
	FROM @tmp T
	WHERE T.RowNumber &gt; CASE WHEN ISNULL(@PageIndex, 0) * ISNULL(@PageSize, 0) &lt;= 0 THEN 0
							ELSE ISNULL((@PageIndex)*@PageSize, 0)
						END
		AND T.RowNumber &lt;= CASE WHEN ISNULL(@PageIndex+1, 0) * ISNULL(@PageSize, 0) &lt;= 0 THEN @TotalCount
								ELSE ISNULL((@PageIndex+1)*@PageSize, 100)
							END
</pre>
<p><span style="text-decoration: underline; font-size: medium;"><strong> Testing it all out</strong></span><span style="font-size: medium;"><strong> </strong></span></p>
<p>Once that&#8217;s done, that&#8217;s it!  You can now run your stored procedure to see the results</p>
<pre class="brush: sql; title: ; notranslate">
DECLARE	@TotalCount int

EXEC	[dbo].[uspProduct_GetAllProducts]
		@SearchString = N'a',
		@SortColumn = N'ID',
		@SortAscending = 1,
		@PageIndex = 0,
		@PageSize = 10,
		@TotalCount = @TotalCount OUTPUT

SELECT	@TotalCount as N'@TotalCount'
</pre>
<p><span style="font-size: medium;"><strong><span style="text-decoration: underline;">Summary</span></strong></span></p>
<p>Hopefully everything worked out fine!  Congratulations, you have created a procedure that returns paginated data with Sorting integrated into its logic.</p>
<p><span style="color: #ff0000;"><strong>NOTE: </strong></span>The Sorting can be extended to all the fields you require. In the snippet below I have included the entire Stored Procedure logic that allows sorting on all columns of the Product table.</p>
<pre class="brush: sql; title: ; notranslate">
CREATE PROCEDURE [dbo].[uspProduct_GetAllProducts]
	@SearchString				AS VARCHAR(50)
	, @SortColumn				AS VARCHAR(100)
	, @SortAscending			AS BIT
	, @PageIndex				AS INT
	, @PageSize					AS INT
	, @TotalCount				AS INT OUTPUT
AS
BEGIN
	DECLARE @tmp AS TABLE (
			RowNumber				INT
			, ProductID				INT
			, Name					NVARCHAR(50)
			, Price					DECIMAL(18,2)
			, CurrentProduct		BIT
			, Quantity				INT
			, ExpiryDate			DATETIME
			, Supplier				NVARCHAR(50)
			, Ranking				INT
			)
	INSERT INTO @tmp
	SELECT ROW_NUMBER() OVER
	( ORDER BY
		CASE		-- Numeric ASC
			WHEN @SortColumn = 'ID' AND @SortAscending = 1 THEN Q.ID
			WHEN @SortColumn = 'Quantity' AND @SortAscending = 1 THEN Q.Quantity
			WHEN @SortColumn = 'Price' AND @SortAscending = 1 THEN Q.Price
			ELSE NULL
		END ASC
		, CASE		-- Numeric DESC
			WHEN @SortColumn = 'ID' AND @SortAscending = 0 THEN Q.ID
			WHEN @SortColumn = 'Quantity' AND @SortAscending = 0 THEN Q.Quantity
			WHEN @SortColumn = 'Price' AND @SortAscending = 0 THEN Q.Price
			ELSE NULL
		END DESC
		, CASE		-- Text	ASC
			WHEN @SortColumn = 'Name' AND @SortAscending = 1 THEN Q.Name
			WHEN @SortColumn = 'Supplier' AND @SortAscending = 1 THEN Q.Supplier
			ELSE NULL
		END ASC
		, CASE		-- Text DESC
			WHEN @SortColumn = 'Name' AND @SortAscending = 0 THEN Q.Name
			WHEN @SortColumn = 'Supplier' AND @SortAscending = 0 THEN Q.Supplier
			ELSE NULL
		END DESC
		, CASE		-- Date ASC
			WHEN @SortColumn = 'ExpiryDate' AND @SortAscending = 1 THEN Q.ExpiryDate
			ELSE NULL
		END ASC
		, CASE		-- Date DESC
			WHEN @SortColumn = 'ExpiryDate' AND @SortAscending = 0 THEN Q.ExpiryDate
			ELSE NULL
		END DESC
	) AS RowNumber
	, Q.ID
	, Q.Name
	, Q.Price
	, Q.CurrentProduct
	, Q.Quantity
	, Q.ExpiryDate
	, Q.Supplier
	, Q.Ranking
	FROM (
			-- The main SQL query that returns ALL the valid data
			SELECT *
			FROM Product P
			WHERE P.Name like '%' + ISNULL(@SearchString, '') + '%'
	) AS Q

	SET @TotalCount = ISNULL((SELECT COUNT(RowNumber) FROM @tmp), 0)
	-- The final SQL query that returns:
	--		The PAGINATED data only, Sorted as specified
	SELECT *
	FROM @tmp T
	WHERE T.RowNumber &gt; CASE WHEN ISNULL(@PageIndex, 0) * ISNULL(@PageSize, 0) &lt;= 0 THEN 0
							ELSE ISNULL((@PageIndex)*@PageSize, 0)
						END
		AND T.RowNumber &lt;= CASE WHEN ISNULL(@PageIndex+1, 0) * ISNULL(@PageSize, 0) &lt;= 0 THEN @TotalCount
								ELSE ISNULL((@PageIndex+1)*@PageSize, 100)
							END
END
</pre>
<p><span style="text-decoration: underline;"><span style="font-size: medium;"><strong>Conclusion</strong></span></span></p>
<p>Hope this article has helped explain the different types of Pagination. Both <strong>Preemptive Loading </strong>and <strong>On Demand Loading</strong> has its uses; and you will need to make a judgment call on which is best suited to your application design. Please take into consideration the performance impact that both types of Pagination could have in your environment.</p>
<p>Have fun! <img src='http://nullablecode.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://nullablecode.com/2011/04/pagination-and-sorting-via-sql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RIA Services: File uploading</title>
		<link>http://nullablecode.com/2011/03/ria-services-file-uploading/</link>
		<comments>http://nullablecode.com/2011/03/ria-services-file-uploading/#comments</comments>
		<pubDate>Sat, 05 Mar 2011 09:51:16 +0000</pubDate>
		<dc:creator>nullablecode</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Everything]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[Domain Service]]></category>
		<category><![CDATA[file]]></category>
		<category><![CDATA[file upload]]></category>
		<category><![CDATA[RIA]]></category>

		<guid isPermaLink="false">http://nullablecode.wordpress.com/?p=205</guid>
		<description><![CDATA[RIA Services is a relatively new addition to Microsoft&#8217;s repertoire of frameworks and services for Application Development; and the understanding<a href="http://nullablecode.com/2011/03/ria-services-file-uploading/" class="searchmore">Read the Rest...</a><div class="clr"></div>]]></description>
			<content:encoded><![CDATA[<p><strong>RIA </strong>Services is a relatively new addition to Microsoft&#8217;s repertoire of frameworks and services for Application Development; and the understanding of Domain services is the core concept behind it all.</p>
<p>In this article I will explain the architecture that combines a Silverlight Client Application to a RIA services solution. The solution will connect to a SQL Database back-end that uses SQL Server FileStream types for file storage.</p>
<p>Specifically I will explain how you can transfer files in a Silverlight + RIA Services architecture to and from a SQL Server Database using FileStream Types&#8230;</p>
<p><span id="more-205"></span></p>
<p><span style="text-decoration: underline; font-size: medium;"><strong>Prerequisites</strong></span></p>
<ul>
<li><a title="How to enable SQL FileStream Types" href="http://nullablecode.com/2011/02/how-to-enable-sql-filestream-types/">How to enable SQL FileStream Types</a></li>
<li><a title="Using SQL FileStream Types in your Databases" href="http://nullablecode.com/2011/02/using-sql-filestream-types-in-your-databases/">Using SQL FileStream Types in your Databases</a></li>
<li><a title="MaxRequestLength – Packet sizes: Size isnt everything" href="http://nullablecode.com/2011/02/maxrequestlength-packet-sizes-size-isnt-everything/">MaxRequestLength – Packet sizes: Size isn&#8217;t everything</a></li>
</ul>
<p><span style="text-decoration: underline; font-size: medium;"><strong><br />
The Basics</strong></span></p>
<p>To begin with let me explain some of the basic components:</p>
<ul>
<li>You have a Silverlight Client Application with XAML pages</li>
<li>You have Domain Services exposed to the Client Application with servicing methods</li>
<li>The mid-tier traverses through a communications layer to reach Repository Classes</li>
<li>Repository Classes are used to connect to the Database to set and retrieve information</li>
</ul>
<p>With this in mind, the diagram below represents a Request from the Client to the Database Server:</p>
<p><strong>RIA Services &#8211; Client to Server Request:</strong></p>
<p><img title="20110225-001642" src="http://nullablecode.com/wp-content/uploads/2011/02/20110225-001642.png" alt="" /></p>
<p><span style="text-decoration: underline; font-size: medium;"><strong>Downloading</strong></span></p>
<p>Before we consider File Uploading via RIA Services lets consider its easier counter-part:  File Downloading via RIA Services! Please take 5 minutes to read my article on <a title="File Buffering and Streaming" href="http://nullablecode.com/2011/03/file-buffering-and-streaming/">File Buffering and Streaming</a> because the concepts used here are exactly the same&#8230;</p>
<p>Below is the initial Download Request from the Client Application. The Request passes through a File Handler. This File Handler is the key component for Streaming data between two systems. The Request is pretty straight forward, the File Handler pipes the Request to the Domain Service &#8211; which in turn calls our Manager Class and Repository Classes.</p>
<p>The Repository Class is responsible for querying the SQL Database to get the File Stream data from the SQL Table.</p>
<p>Later in this article there is a code-snippet that explains how I achieved this.</p>
<p><strong>File Download &#8211; Client to Server Request:</strong></p>
<p><img title="20110225-001716" src="http://nullablecode.com/wp-content/uploads/2011/02/20110225-001716.png" alt="" width="590" height="330" /></p>
<p>Once the Repository has a reference to the File entity. The Repository passes the Byte[] array data through all of the channels back via the Domain Service to the File Handler. The diagram below is a representation of this process:</p>
<p><span style="color: #ff0000;"><strong>note: </strong></span>The RED arrows indicate that Streaming is happening and shows the direction that the streamed data is moving.</p>
<p><strong>File Download (Streamed) &#8211; Server to Client Response:</strong></p>
<p><strong><img title="20110225-001735" src="http://nullablecode.com/wp-content/uploads/2011/02/20110225-0017351.png" alt="" width="590" height="332" /></strong></p>
<p><span style="text-decoration: underline; font-size: medium;"><strong>Uploading</strong></span></p>
<p>Now lets discuss the File Upload counter-part. When I first designed the solution I ran into performance issues. To give you a better understanding I will describe my original design below:</p>
<ul>
<li>The XAML page loads a <strong>BackgroundWorker </strong>to upload packets of data to the File Handler.</li>
<li>On the <strong>ProcessRequest</strong>() method of the File Handler I piped the data through the Domain Service</li>
<li>Which in turn piped the data to the Repository</li>
<li>The Repository opened a data stream to the Database and flushed the data into this steam.</li>
<li>The Repository then closes the database connection.</li>
<li>This repeats for as many upload Packets as necessary.</li>
</ul>
<p>The performance hit that got me was that the BackgroundWorker&#8217;s processing method needed to wait until the File Handler completed its entire process; and this happens after all the steps above have finished &#8211; including open and closing the database connection and writing the contents to the FileStream table column.</p>
<p>So an alternate approch was devised&#8230;</p>
<p>File uploading via RIA Service is split into 2 parts:</p>
<ol>
<li>Transferring the file from the Client Application to the Web Server via the File Handler</li>
<li>Transferring the file from the Web Server to the Database Server as a SQL FileStream Type</li>
</ol>
<p><span style="font-size: medium;"><em><strong><br />
1. File Transfer (Client Application to Web Server)</strong></em></span></p>
<p>This first process is identical to the steps explained in the article: <a title="File Buffering and Streaming" href="http://nullablecode.com/2011/03/file-buffering-and-streaming/">File Buffering and Streaming</a></p>
<p><strong> </strong></p>
<p><strong> </strong></p>
<p><strong>File Upload (Streamed) &#8211; Client to Web Server:</strong></p>
<p><img title="20110225-001810" src="http://nullablecode.com/wp-content/uploads/2011/02/20110225-001810.png" alt="" width="590" height="322" /></p>
<p><span style="font-size: medium;"><em><strong>2. File Transfer (Web Server to DB Server)</strong></em></span></p>
<p>This diagram is the representation on how the File Handler transfers data packets to the SQL Database via Domain Services:</p>
<p><strong>File Upload (Streamed) &#8211; Web Server to DB Server:</strong></p>
<p><strong><img title="20110225-001830" src="http://nullablecode.com/wp-content/uploads/2011/02/20110225-0018301.png" alt="" width="590" height="332" /></strong></p>
<p>We extend what we previously had in the File Handler <strong>ProcessRequest</strong>() method by adding extra functionality that executes when the last file packet is retrieved and appended to the Web Server file. Below is the entire <strong>ProcessRequest</strong>() method &#8211; you will notice an additional call is made on detection of the &#8220;<span style="text-decoration: underline;">completed</span>&#8221; flag to a private method <strong>TransferFileToDB</strong>().</p>
<pre class="brush: csharp; title: ; notranslate">
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.QueryString.AllKeys.Contains(&quot;attachmentid&quot;)
                    &amp;&amp; context.Request.QueryString.AllKeys.Contains(&quot;filename&quot;)
                    &amp;&amp; context.Request.QueryString.AllKeys.Contains(&quot;uniquefilename&quot;))
            {
                // Write to the Upload Folder
                System.IO.FileInfo fi = new System.IO.FileInfo(@&quot;C:\MyUploads&quot;
                                                + context.Request.QueryString[&quot;uniquefilename&quot;]);
                System.IO.FileStream fs;

                try
                {
                    if (fi.Exists)
                    {
                        fs = new System.IO.FileStream(fi.FullName
                                                          , System.IO.FileMode.Append);
                    }
                    else
                    {
                        fs = new System.IO.FileStream(fi.FullName
                                                          , System.IO.FileMode.OpenOrCreate
                                                          , System.IO.FileAccess.Write);
                    }

                    // Insert the data chunk into the file
                    byte[] b = new byte[context.Request.InputStream.Length];
                    context.Request.InputStream.Read(b, 0, b.Length);
                    fs.Write(b, 0, b.Length);
                    fs.Close();

                    // Check if this is the last data packet.
                    // If so, call TransferFileToDB() to upload to the DB
                    if (context.Request.QueryString.AllKeys.Contains(&quot;completed&quot;))
                    {
                        TransferFileToDB(
                                        System.Guid.Parse(
                                              context.Request.QueryString[&quot;attachmentid&quot;]
                                        )
                                        , fi.FullName
                                        , context.Request.QueryString[&quot;uniquefilename&quot;]
                                        , context.Request.QueryString[&quot;filename&quot;]);
                    }
                }
                catch (Exception ex)
                {
                    //Handle Error - Remove the temporary file etc
                }
            }
        }
</pre>
<p>The <strong>TransferFileToDB </strong>method is responsible for streamlining the local Web Server file contents to a Domain Service method that has been coded to accept data packets. So we continuously call the UploadStreamed() method of the Domain Service until we reach the end of the file.</p>
<p>When we transfer the final packet to the SQL Server we can safely clean up by deleting the temporary file on the Web Server &#8211; as we are now sure that the entire contents have been uploaded to the SQL Server Database.</p>
<p>But if any exception is thrown you need to clean up the partially uploaded file on the SQL Database. Plus remove the temporary file on the Web Server, and alert the User accordingly.</p>
<pre class="brush: csharp; title: ; notranslate">
        private void TransferFileToDB(
                                            System.Guid attachmentID
                                            , string filePath
                                            , string newFileName
                                            , string originalFileName)
        {
            AttachmentService svc = new AttachmentService();
            System.IO.FileStream fs;

            // Get the file from the Upload Folder
            System.IO.FileInfo fi = new System.IO.FileInfo(filePath);

            if (fi.Exists)
            {
                try
                {
                    byte[] buffer;
                    int position = 0;
                    int packetSize = 10 * 1000 * 1024;

                    // Open the file for reading
                    fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open);
                    long length = fs.Length;

                    // Stream the data packets to the Domain Service for storage
                    while (position &lt; length)                     {                          if (position + packetSize &gt; length)
                        {
                            buffer = new byte[length - position];
                        }
                        else
                        {
                            buffer = new byte[packetSize];
                        }

                        fs.Read(buffer, 0, buffer.Length);
                        svc.UploadStreamed(attachmentID
                                            , newFileName
                                            , originalFileName
                                            , buffer
                                            , position);
                        position += buffer.Length;
                    }
                    fs.Close();

                    // Once all data packets are uploaded, clean up the file.
                    fi.Delete();

                }
                catch (Exception ex)
                {
                    //Handle error here
                }
            }
        }
</pre>
<p>Next up&#8230;. the <a title="RIA Services: File uploading – service method" href="http://nullablecode.com/2011/08/ria-services-file-uploading-service-method/">Domain Service implementation</a>!</p>
<p>Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://nullablecode.com/2011/03/ria-services-file-uploading/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>File Buffering and Streaming</title>
		<link>http://nullablecode.com/2011/03/file-buffering-and-streaming/</link>
		<comments>http://nullablecode.com/2011/03/file-buffering-and-streaming/#comments</comments>
		<pubDate>Mon, 28 Feb 2011 22:09:12 +0000</pubDate>
		<dc:creator>nullablecode</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Everything]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[buffering]]></category>
		<category><![CDATA[file]]></category>
		<category><![CDATA[file upload]]></category>
		<category><![CDATA[stream]]></category>

		<guid isPermaLink="false">http://nullablecode.wordpress.com/?p=294</guid>
		<description><![CDATA[FOLLOWING on from my article about Packet Sizes I hope it has given you insight on how smaller packets are<a href="http://nullablecode.com/2011/03/file-buffering-and-streaming/" class="searchmore">Read the Rest...</a><div class="clr"></div>]]></description>
			<content:encoded><![CDATA[<p><strong>FOLLOWING </strong>on from my article about <a title="MaxRequestLength – Packet sizes: Size isnt everything" href="http://nullablecode.com/2011/02/maxrequestlength-packet-sizes-size-isnt-everything/">Packet Sizes</a> I hope it has given you insight on how smaller packets are much more ideal over larger packets of data. Not only is it safer for your Web server, it also gives you control how much traffic you want your applications to use in your network.</p>
<p>In this article I will provide an example on how to stream data from a Silverlight Client to the Web Server using the Buffered and Steaming approach. A general knowledge of .Net Generic Handlers is ideal because this solution relies heavily on custom handlers to feed data to and from our Web server.</p>
<p><span style="font-size: medium;"><strong>Prerequisites</strong></span>:</p>
<ul>
<li><a title="MaxRequestLength – Packet sizes: Size isnt everything" href="http://nullablecode.com/2011/02/maxrequestlength-packet-sizes-size-isnt-everything/">MaxRequestLength – Packet sizes: Size isn&#8217;t everything<br />
</a></li>
</ul>
<p><span id="more-294"></span></p>
<p><span style="font-size: medium;"><strong><span style="text-decoration: underline;">The Environment</span></strong></span></p>
<p>Consider the environment below:</p>
<p><img title="20110225-001810" src="http://nullablecode.com/wp-content/uploads/2011/02/20110225-001810.png" alt="" width="590" height="322" /></p>
<ul>
<li>We have a Client Application with a XAML page.</li>
<li>The XAML page makes a request to the Handler which is responsible for transferring the file to the Web Server.</li>
</ul>
<p><span style="text-decoration: underline;"><strong><br />
<span style="font-size: medium;">Bulk Insert</span></strong></span><em><strong><br />
</strong></em></p>
<p><span style="font-size: medium;"><em><strong>The Client</strong></em></span></p>
<p>In the XAML page, we have an <strong>OnClick</strong>() event handler&#8230; This handler grabs the selected file using the <strong>OpenFileDialog</strong>() method and then instantiates a <a href="http://msdn.microsoft.com/en-us/library/8xs8549b.aspx" target="_blank"><strong>BackgroundWorker</strong></a> to process the file. The BackgroundWorker then calls a private function called <strong>ProcessFileUpload</strong>() which does all the necessary processing. Here the BackgroundWorker is used to make an <span style="text-decoration: underline;">asynchronous</span> call to the processing function rather than blocking off the UI thread.</p>
<pre class="brush: csharp; title: ; notranslate">
        private void browse_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            OpenFileDialog d = new OpenFileDialog();
            d.Multiselect = false;
            d.Filter = &quot;All Files|*.*&quot;;

            if ((bool)d.ShowDialog())
            {
                // Construct URI to the File upload Handler ASHX file
                System.UriBuilder ub = new System.UriBuilder(
                     System.Windows.Browser.HtmlPage.Document.DocumentUri.Scheme
                     , System.Windows.Browser.HtmlPage.Document.DocumentUri.Host
                     , System.Windows.Browser.HtmlPage.Document.DocumentUri.Port
                     , &quot;FileStreamUploader.ashx&quot;);

                // Set any parameters the Handler will require.
                // Here we pass in the original + unique file name
                ub.Query = &quot;filename=&quot; + d.File.Name
                            + &quot;&amp;uniquefilename=&quot; + System.DateTime.Now.ToString(&quot;yyyyMMdd_HHmmss_&quot;)
                            + d.File.Name;

                // Initiate a background worker so we don't hold up the UI of the Client App
                BackgroundWorker bw = new BackgroundWorker();

                bw.DoWork += (bw_sender, bw_e) =&gt;
                {
                    // The function that does the background work
                    ProcessFileUpload(ub.Uri
                                        , (System.IO.FileInfo)bw_e.Argument
                                        , (System.ComponentModel.BackgroundWorker)bw_sender
                                        , bw_e);
                };

                bw.RunWorkerAsync(d.File);
            }
            else //cancel
            {

            }
        }
</pre>
<p>When the code enters into the <strong>ProcessFileUpload</strong>() function the following things need to happen:</p>
<ul>
<li>Open the file for reading.</li>
<li>Grab its length.</li>
<li>Set a Byte[] array variable to store the file contents.</li>
<li>Open a connection to the File Handler</li>
<li>Pass this Byte[] array into the File Handler&#8217;s data stream</li>
<li>Close the stream</li>
</ul>
<p>This is handled by the following code snippet:</p>
<pre class="brush: csharp; title: ; notranslate">
        private void ProcessFileUpload(System.Uri uri
                                            , System.IO.FileInfo fileInfo
                                            , System.ComponentModel.BackgroundWorker worker
                                            , System.ComponentModel.DoWorkEventArgs e)
        {
            System.IO.Stream fs = fileInfo.OpenRead();

            long length = fs.Length;

            byte[] buffer;
            buffer = new byte[length];

            // Read the contents of the file into the buffer
            fs.Read(buffer, 0, buffer.Length);

            // Open a connection to the Request Stream to the file Handler
            // Then pipe the data across..
            System.Net.WebClient wc = new System.Net.WebClient();
            wc.OpenWriteCompleted += (wc_s, wc_e) =&gt;
            {
                UploadPacketToHandler(buffer, wc_e.Result);
                wc_e.Result.Close();
            };

            wc.OpenWriteAsync(uri);
            fs.Close();
        }
</pre>
<pre class="brush: csharp; title: ; notranslate">
        private void UploadPacketToHandler(byte[] fileData, System.IO.Stream outputStream)
        {
            // Pipe the packet into the Steam to the Server
            outputStream.Write(fileData, 0, fileData.Length);
            outputStream.Close();
        }
</pre>
<p>At the end of this process, what has happened is that the file contents have now been sent to the Web Server via the File Handler&#8217;s input stream.</p>
<p>Next, it is up to the File Handler logic to process this data whichever way it needs to..</p>
<p><span style="font-size: medium;"><em><strong>The File Handler</strong></em></span></p>
<pre class="brush: csharp; title: ; notranslate">
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.QueryString.AllKeys.Contains(&quot;filename&quot;)
                    &amp;&amp; context.Request.QueryString.AllKeys.Contains(&quot;uniquefilename&quot;))
            {
                // Write to the Upload Folder
                System.IO.FileInfo fi = new System.IO.FileInfo(@&quot;C:\MyUploads&quot;;
                                                + context.Request.QueryString[&quot;uniquefilename&quot;]);
                System.IO.FileStream fs;

                try
                {
                    if (fi.Exists)
                    {
                        fs = new System.IO.FileStream(fi.FullName
                                                          , System.IO.FileMode.Append);
                    }
                    else
                    {
                        fs = new System.IO.FileStream(fi.FullName
                                                          , System.IO.FileMode.OpenOrCreate
                                                          , System.IO.FileAccess.Write);
                    }

                    // Insert the data into the file
                    byte[] b = new byte[context.Request.InputStream.Length];
                    context.Request.InputStream.Read(b, 0, b.Length);
                    fs.Write(b, 0, b.Length);
                    fs.Close();
                }
            }
        }
</pre>
<p>The entry point for the File Handler is the <strong>ProcessRequest</strong>() function. We grab the filename parameters from the QueryString and then open up a <strong>FileInfo </strong>object to the path of the uploaded file. Then we write the entire contents of the input stream into the FileInfo object, and close the stream. Pretty simple! <img src='http://nullablecode.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p><span style="text-decoration: underline;"><strong><span style="font-size: medium;">Conclusion</span>:</strong></span><em><strong><br />
</strong></em></p>
<p>That&#8217;s it!  You have successfully implemented an upload function using a Silverlight Client and a Generic Handler.</p>
<p>But what do packet size and streaming have to do with this example you ask??</p>
<p>Well you&#8217;re right.  With this example, the largest file you can upload without reaching the Request Limit is 4MB. Try uploading a 10MB file and you should see the HTTP Request object throwing an exception about your request being too large and reaching its maximum limit. This is because we used the default maxRequestLength value of 4MB, and without any streaming..</p>
<p>Next I will explain how you change this code to allow for ANY file size, while still preserving the 4MB maxRequestLength property.</p>
<p><span style="font-size: medium;"><span style="text-decoration: underline;"><strong>Streaming</strong></span><em><strong> </strong></em></span></p>
<p>This is easily accomplished with a few lines of extra code to the snippets above.<br />
This is the overview of the changes we need to make:</p>
<ul>
<li>The BackgoundWorker&#8217;s processing function needs to make several calls to the File Handler instead of one call.</li>
<li>With each call to the File Handler, the BackgroundWorker&#8217;s processing functions will send ONE packet of data.</li>
<li>This process repeats itself until the BackgroundWorker processing functions reach the end of the input file.</li>
<li>On the File Handler side of things, the main <strong>ProcessRequest</strong>() function will need to APPEND data to an existing file for subsequent writes. So that the input data is written to the same file in 4MB packets.</li>
<li>Once the File Handler has detected the end-of-file (from a parameter) the File Handler can then use the file for further process like sending it as an email attachment etc.</li>
</ul>
<p><strong><em>BackgroundWorker Modifications</em></strong></p>
<p>Below is the first change we need to make to the BackgroundWorker processing functions:</p>
<pre class="brush: csharp; title: ; notranslate">
        private void ProcessFileUpload(System.Uri uri
                                    , System.IO.FileInfo fileInfo
                                    , System.ComponentModel.BackgroundWorker worker
                                    , System.ComponentModel.DoWorkEventArgs e)
        {
            try
            {
                System.IO.Stream fs = fileInfo.OpenRead();

                long length = fs.Length;

                byte[] buffer;
                int position = 0;
                int packetSize = 5 * 1000 * 1024;

                while (position &lt; length)                 {
                    if (position + packetSize &gt; length)
                    {
                        buffer = new byte[length - position];

                        // If this is the last buffer for this file..
                        // .. set the completed flag for the handler
                        System.UriBuilder ub = new System.UriBuilder(uri);
                        if (ub.Query == string.Empty) { ub.Query = &quot;completed=1&quot;; }
                        else { ub.Query = ub.Query.TrimStart('?') + &quot;&amp;completed=1&quot;; }
                        uri = ub.Uri;
                    }
                    else
                    {
                        buffer = new byte[packetSize];
                    }

                    fs.Read(buffer, 0, buffer.Length);
                    position += buffer.Length;

                    // Mutex to ensure packets are sent in order
                    System.Threading.AutoResetEvent mutex =
                                        new System.Threading.AutoResetEvent(false);

                    System.Net.WebClient wc = new System.Net.WebClient();
                    wc.OpenWriteCompleted += (wc_s, wc_e) =&gt;
                    {
                        UploadPacketToHandler(buffer, wc_e.Result);
                    };
                    wc.WriteStreamClosed += (ws_s, ws_e) =&gt;
                    {
                        mutex.Set();
                    };
                    wc.OpenWriteAsync(uri);
                    mutex.WaitOne();
                }

                fs.Close();
            }
            catch (Exception ex)
            {
                //Handle errors here
            }
        }
</pre>
<p><span style="font-size: medium;"><em><strong>File Handler modifications</strong></em></span></p>
<p>In the File Handler code, we need to CREATE the file for the very first packet.<br />
Then on subsequent packets APPEND the packet to the end of the file.</p>
<p>Once the &#8216;completed&#8217; parameter is detected the File Handler knows this is the final packet to be appended. After this we can continue processing the file as we need to&#8230;</p>
<pre class="brush: csharp; title: ; notranslate">
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.QueryString.AllKeys.Contains(&quot;filename&quot;)
                    &amp;&amp; context.Request.QueryString.AllKeys.Contains(&quot;uniquefilename&quot;))
            {
                // Write to the Upload Folder
                System.IO.FileInfo fi = new System.IO.FileInfo(@&quot;C:\MyUploads&quot;
                                                + context.Request.QueryString[&quot;uniquefilename&quot;]);
                System.IO.FileStream fs;

                try
                {
                    if (fi.Exists)
                    {
                        fs = new System.IO.FileStream(fi.FullName
                                                          , System.IO.FileMode.Append);
                    }
                    else
                    {
                        fs = new System.IO.FileStream(fi.FullName
                                                          , System.IO.FileMode.OpenOrCreate
                                                          , System.IO.FileAccess.Write);
                    }

                    // Insert the data into the file
                    byte[] b = new byte[context.Request.InputStream.Length];
                    context.Request.InputStream.Read(b, 0, b.Length);
                    fs.Write(b, 0, b.Length);
                    fs.Close();

                    // Check if this is the last data packet.
                    // If so do additional processing as needed...
                    if (context.Request.QueryString.AllKeys.Contains(&quot;completed&quot;))
                    {
                        // Additional process as required by your application:
                        // Send as attachment
                        // or Send to Database etc
                    }
                }
            }
        }
</pre>
<p><span style="text-decoration: underline; font-size: medium;"><strong>Conclusion</strong></span></p>
<p>That&#8217;s it!! You have now successfully implemented a buffered/streaming file uploading component.<br />
Pretty easy huh?</p>
<p>If you have any questions, feel free to drop a message <img src='http://nullablecode.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Hope this article helped!</p>
<p> <img src='http://nullablecode.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://nullablecode.com/2011/03/file-buffering-and-streaming/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>MaxRequestLength &#8211; Packet sizes: Size isnt everything</title>
		<link>http://nullablecode.com/2011/02/maxrequestlength-packet-sizes-size-isnt-everything/</link>
		<comments>http://nullablecode.com/2011/02/maxrequestlength-packet-sizes-size-isnt-everything/#comments</comments>
		<pubDate>Sun, 27 Feb 2011 11:58:08 +0000</pubDate>
		<dc:creator>nullablecode</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Everything]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[buffering]]></category>
		<category><![CDATA[file]]></category>
		<category><![CDATA[stream]]></category>

		<guid isPermaLink="false">http://nullablecode.wordpress.com/?p=207</guid>
		<description><![CDATA[IF you have coded a file upload component in .Net before you would have probably used the Asp.Net File Upload<a href="http://nullablecode.com/2011/02/maxrequestlength-packet-sizes-size-isnt-everything/" class="searchmore">Read the Rest...</a><div class="clr"></div>]]></description>
			<content:encoded><![CDATA[<p><strong>IF </strong>you have coded a file upload component in .Net before you would have probably used the Asp.Net File Upload control. You would  have also come across the fact that the default HTTP Request size for a Web Application is set to 4MB. A search thereafter would have introduced you to the <a href="http://msdn.microsoft.com/en-us/library/system.web.configuration.httpruntimesection.maxrequestlength.aspx" target="_blank">maxRequestLength Attribute</a> that is configurable in your Web.config.</p>
<p>Increasing this value to say 40,960 will allow 10x the default file size to be posted to your web server. This will fix your immediate file size limitation to 40MB. But what it also means is that you have now opened your Web application to accept any request 10x the standard request length. The question you need to ask yourself is, is this a good thing or is this a bad thing.. ?</p>
<p>In this article I will explain how to go one step further and show how you can implement a buffered and streaming approach to file downloading and uploading&#8230;</p>
<p><span id="more-207"></span></p>
<p><span style="text-decoration: underline; font-size: medium;"><strong>Background Information</strong></span></p>
<p>The quickest way to resolve file upload limitations in a ASP.Net Application is to increase the maxRequestLength attribute in the Web.Config.  Below is the snippet that is required to accomplish this:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;system.web&gt;
  &lt;httpRuntime maxRequestLength=&quot;40960&quot;/&gt;     &lt;!-- 40MB limit, instead of 4MB limit --&gt;
&lt;/system.web&gt;
</pre>
<p>So is this good or bad.. ? In short, I believe this is a bad.</p>
<p>It&#8217;s a very quick solution, and if your application is relatively small to medium then this solution is quite possible and fairly robust. One important consideration is the side-effect this will have to your Web application. Instead of accepting a maximum web request size of 4mb, you have now allowed the server to be bombarded with up to 40mb of data per request.  You need to decide if this makes your server prone to attacks and security mishaps..</p>
<p>The solution I propose is to understand how packet sizes, buffering and streaming work. Once you understand how this works, I promise you will never go back! <img src='http://nullablecode.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p><span style="text-decoration: underline; font-size: medium;"><strong>Packet Sizes</strong></span></p>
<p>The core concept behind streaming is the ability send many small packets of data as opposed to large packets of data across the wire.</p>
<p>Consider the following example:</p>
<ul>
<li>You have a total network bandwidth of 100megabits/sec.  Which is equivalent to 12.5 MB/sec.<br />
Lets use 12MB for simplicity</li>
<li>You have 2 concurrent users.</li>
<li>Each user wants to transfer a 100MB file</li>
</ul>
<p>The image below is a visual representation of our 12MB/sec network split into 3 sections.<br />
Each section can handle 4MB.</p>
<p><img title="20110225-223745" src="http://nullablecode.com/wp-content/uploads/2011/02/20110225-223745.png" alt="" width="560" height="205" /></p>
<p><em><strong>4MB Example:</strong></em></p>
<p>With maxRequestLength = 4MB, our 2 Users each use up 4MB out of the available 12MB bandwidth.<br />
BLUE and GREEN successfully transfers 100MB each, totalilng 200MB in 25 secs.</p>
<p><span style="color: #ff0000;"><strong>note</strong>: </span>Our network still has 4MB (RED) of bandwidth remaining for other traffic</p>
<p><img title="20110225-223816" src="http://nullablecode.com/wp-content/uploads/2011/02/20110225-2238161.png" alt="" width="560" height="205" /></p>
<p><em><strong>40MB Example:</strong></em></p>
<p>Now consider what happens if we increase maxRequestLength to 40MB.</p>
<ul>
<li>BLUE has 100MB to transfer.</li>
<li>Each packet is 40MB because of our maxRequestLength value set to 40MB</li>
<li>A total of 2.5 packets need to be sent</li>
</ul>
<p>BLUE uses up the entire 12MB bandwidth for a total of 100MB/12MB per sec = 8.33 secs.<br />
So in 8.33 secs BLUE completes its data transfer.</p>
<ul>
<li>GREEN also has 100MB to transfer.</li>
<li>Each packet is also 40MB</li>
<li>A total of 2.5 packets need to be sent</li>
</ul>
<p>GREEN needs to wait for BLUE to finish before GREEN can begin its data transfer.<br />
GREEN also takes 8.33 secs to transfer 100MB.</p>
<p>The entire process takes 16.6 secs to transfer a total of 200mb.</p>
<p><img title="20110225-223840" src="http://nullablecode.com/wp-content/uploads/2011/02/20110225-2238403.png" alt="" width="560" height="205" /></p>
<ul>
<li>A 4MB environment takes 25 secs to send 200MB for 2 users.</li>
<li>A 40MB environment takes 16.6 secs to send 200MB for 2 users.</li>
</ul>
<p>The latter would seem the better solution as it completes sooner. But your Network Infrastructure is crippled for a total of 16.6 secs as no bandwidth is available for other traffic across the network.</p>
<p>So hopefully this example has given you the information needed to understand why smaller packets are preferred over larger packets.</p>
]]></content:encoded>
			<wfw:commentRss>http://nullablecode.com/2011/02/maxrequestlength-packet-sizes-size-isnt-everything/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

