


<?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>Fresh Click Media &#187; C#</title>
	<atom:link href="http://www.freshclickmedia.com/blog/category/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.freshclickmedia.com</link>
	<description></description>
	<lastBuildDate>Wed, 17 Mar 2010 18:27:39 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Programmatic impersonation in C#</title>
		<link>http://www.freshclickmedia.com/blog/2008/11/programmatic-impersonation-in-c/</link>
		<comments>http://www.freshclickmedia.com/blog/2008/11/programmatic-impersonation-in-c/#comments</comments>
		<pubDate>Thu, 27 Nov 2008 20:08:47 +0000</pubDate>
		<dc:creator>Shane</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://www.freshclickmedia.com/?p=115</guid>
		<description><![CDATA[<img src="http://farm4.static.flickr.com/3054/3064284648_4a04bbfbed_o.jpg" alt="Impersonation" width="590" height="100" />

I recently deployed a WPF app on a server that allowed the user to stop and start some application-related services.  The purpose of the app was to allow users with administrative rights an easy way to manage the services that they needed to manage.  Granted, they could manage the services through the services MMC, but the little WPF app was a requirement, and it's our job as developers to make things easier for our clients - right?  

All went well until a change of requirements meant that a user without administrative rights needed to use the program to stop and start the required services.  When I tried to use the app, I got an exception - quite rightly, stopping and starting the services required admin rights.  We needed the restricted user to be able to log on and use the app, but still needed to restrict their permissions.

So - step in programmatic impersonation in C# - a way to give restricted users the power that that's required, all within the confines of your application.]]></description>
			<content:encoded><![CDATA[<p><img src="http://farm4.static.flickr.com/3054/3064284648_4a04bbfbed_o.jpg" alt="Impersonation" width="590" height="100" /></p>
<p>I recently deployed a WPF app on a server that allowed the user to stop and start some application-related services.  The purpose of the app was to allow users with administrative rights an easy way to manage the services that they needed to manage.  Granted, they could manage the services through the services MMC, but the little WPF app was a requirement, and it&#8217;s our job as developers to make things easier for our clients &#8211; right?  </p>
<p>All went well until a change of requirements meant that a user without administrative rights needed to use the program to stop and start the required services.  When I tried to use the app, I got an exception &#8211; quite rightly, stopping and starting the services required admin rights.  We needed the restricted user to be able to log on and use the app, but still needed to restrict their permissions.</p>
<p>So &#8211; step in programmatic impersonation in C# &#8211; a way to give restricted users the power that that&#8217;s required, all within the confines of your application.</p>
<p>The first thing to point out is that I got quite a bit of this code from a google search, but I had to do a bit of work to get things in a state that I found really useful.</p>
<pre class="code">using System;
using System.Collections.Generic;
using System.Configuration;
using System.Runtime.InteropServices;
using System.Linq;
using System.Security.Principal;
using System.Text;

namespace ServiceControllerApp.Security
{
    public class Impersonator : IDisposable
    {
        private WindowsImpersonationContext _impersonatedUser = null;
        private IntPtr _userHandle;

        public Impersonator()
        {
            _userHandle = new IntPtr(0);

            string user = &quot;servicecontroller&quot;;
            string userDomain = ConfigurationManager.AppSettings[&quot;MachineDomain&quot;];
            string password = &quot;yourpassword&quot;;

            bool returnValue = LogonUser(user, userDomain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref _userHandle);

            if (!returnValue)
                throw new ApplicationException(&quot;Could not impersonate user&quot;);

            WindowsIdentity newId = new WindowsIdentity(_userHandle);
            _impersonatedUser = newId.Impersonate();
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (_impersonatedUser != null)
            {
                _impersonatedUser.Undo();
                CloseHandle(_userHandle);
            }
        }

        #endregion

        #region Interop imports/constants
        public const int LOGON32_LOGON_INTERACTIVE = 2;
        public const int LOGON32_LOGON_SERVICE = 3;
        public const int LOGON32_PROVIDER_DEFAULT = 0;

        [DllImport(&quot;advapi32.dll&quot;, CharSet = CharSet.Auto)]
        public static extern bool LogonUser(String lpszUserName, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

        [DllImport(&quot;kernel32.dll&quot;, CharSet = CharSet.Auto)]
        public extern static bool CloseHandle(IntPtr handle);
        #endregion
    }
}
</pre>
<p>Impersonator is a simple class that uses interop to call Win32 LogonUser and CloseHandle functions.  We have to use interop because .NET doesn&#8217;t provide the equivalent methods.</p>
<p>The code shown above has a user, domain and password actually in the code &#8211; for some situations this is a security risk, so the credentials should be obtained in another manner, but for my needs, it was satisfactory, and their direct inclusion simplifies this example.  </p>
<p>The class has a WindowsImpersonationContext to manage the impersonation, and the constructor sets up the required logon rights using the LogonUser interop.</p>
<p>Crucially, the impersonation must end, with an equivalent Log Off &#8211; and the class implements IDisposable to call the required log off code.  Using the class is easy.</p>
<pre class="code">
using (Impersonator impersonator = new Impersonator())
{
    // code in here
}
</pre>
<p>The good thing is that because the class implements IDisposable, you don&#8217;t have to pepper your code with the log off code equivalent.  I hope it&#8217;s of use to somebody wishing to implement impersonation.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.freshclickmedia.com/blog/2008/11/programmatic-impersonation-in-c/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Gravatar Control Update</title>
		<link>http://www.freshclickmedia.com/blog/2008/03/gravatar-control-update/</link>
		<comments>http://www.freshclickmedia.com/blog/2008/03/gravatar-control-update/#comments</comments>
		<pubDate>Tue, 18 Mar 2008 19:08:58 +0000</pubDate>
		<dc:creator>Shane</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Blogging]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.freshclickmedia.com/blog/2008/03/gravatar-control-update/</guid>
		<description><![CDATA[The guys over at <a href="http://www.gravatar.com">Gravatar.com</a> have been hard at work <a href="http://blog.gravatar.com/2008/03/14/big-changes-afoot/">updating their service</a>, and I've updated the <a href="http://www.freshclickmedia.com/blog/2008/02/gravatar-aspnet-control/">ASP.NET control I developed</a> to reflect the changes.]]></description>
			<content:encoded><![CDATA[<h3>Update &#8211; 12 June 2008</h3>
<p>An updated version of this post, containing full source for the control and explanation is available <a href="http://www.freshclickmedia.com/blog/2008/06/aspnet-gravatar-control-update-full-source-included/">here</a>.</p>
<h3>Original Post</h3>
<p>The guys over at <a href="http://www.gravatar.com">Gravatar.com</a> have been hard at work <a href="http://blog.gravatar.com/2008/03/14/big-changes-afoot/">updating their service</a>, and I&#8217;ve updated the <a href="http://www.freshclickmedia.com/blog/2008/02/gravatar-aspnet-control/">ASP.NET control I developed</a> to reflect the changes.</p>
<p>The maximum size of Gravatars has now been increased from 80 to 512, so there&#8217;s a code change in the Render method:</p>
<pre class="code">
// if the size property has been specified, and in the range
// 1..512:
try
{
    // if it's not in the allowed range, throw an exception:
    if (Size < 1 || Size > 512)
        throw new ArgumentOutOfRangeException();
}
catch
{
    Size = 80;
}
</pre>
<p>So, a default of 80 will still be used if the value specified is not within the 1 to 512 range, or it is not specified, but allows for a larger size.</p>
<p>The avatar.php URL serving the images <a href="http://blog.gravatar.com/2008/03/14/big-changes-afoot/">now supports abbreviation</a>, but the code in the control has not been changed.</p>
<p><img src="http://farm3.static.flickr.com/2303/2343923834_a85fa1e873_o.gif" alt="Design time view of the control" width="505" height="429" /></p>
<p>The image shows the Design time view of the control, with the width set at the default value of 80.  I&#8217;ve checked the control at 512 pixels, but my Gravatar doesn&#8217;t look too good expanded out to that size, so I&#8217;ve decided to stick at size 80 for the screenshot!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.freshclickmedia.com/blog/2008/03/gravatar-control-update/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Gravatar ASP.NET Control</title>
		<link>http://www.freshclickmedia.com/blog/2008/02/gravatar-aspnet-control/</link>
		<comments>http://www.freshclickmedia.com/blog/2008/02/gravatar-aspnet-control/#comments</comments>
		<pubDate>Fri, 22 Feb 2008 20:59:08 +0000</pubDate>
		<dc:creator>Shane</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Blogging]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.freshclickmedia.com/blog/2008/02/gravatar-aspnet-control/</guid>
		<description><![CDATA[I just got myself a freshclickmedia.com Gravatar over at <a href="http://site.gravatar.com/" title="Get your own Gravatar">gravatar.com</a>.  A Gravatar is a little avatar associated with an email address, and quite a few blogs use them to decorate post comments.  Signing up is easy - all you need to do is supply an email address, and image, and give your image a content rating.

The source of the gravatar image tag points to gravatar.com's image generator and includes an MD5 hash of the email address to prevent email harvesting.  A 'max rating' parameter prevents the display of unsavoury content.

There are a wide number of blogging gravatar plugins, so I decided to write an ASP.NET custom control to do the job.  Here I present the control and its features.
]]></description>
			<content:encoded><![CDATA[<h3>Update &#8211; 12 June 2008</h3>
<p>An updated version of this post, containing full source for the control and explanation is available <a href="http://www.freshclickmedia.com/blog/2008/06/aspnet-gravatar-control-update-full-source-included/">here</a>.</p>
<h3>Original Post</h3>
<p>I just got myself a freshclickmedia.com Gravatar over at <a href="http://site.gravatar.com/" title="Get your own Gravatar">gravatar.com</a>.  A Gravatar is a little avatar associated with an email address, and quite a few blogs use them to decorate post comments.  Signing up is easy &#8211; all you need to do is supply an email address, and image, and give your image a content rating.</p>
<p>The source of the gravatar image tag points to gravatar.com&#8217;s image generator and includes an MD5 hash of the email address to prevent email harvesting.  A &#8216;max rating&#8217; parameter prevents the display of unsavoury content.</p>
<p>There are a wide number of blogging gravatar plugins, so I decided to write an ASP.NET custom control to do the job.  Here I present the control and its features.</p>
<p><span id="more-80"></span></p>
<h3>Using the Control</h3>
<p>To get up and running, the control requires an email address:</p>
<pre class="code">
&lt;fcm:Gravatar ID=&apos;Gravatar1&apos; runat=&apos;server&apos; Email=&apos;username@domain.com&apos; /&gt;
</pre>
<p>For my email address, I get the following:</p>
<p><img src="http://farm3.static.flickr.com/2181/2283724305_24797cd8d5_o.gif" width="505" height="208" alt="Output for my email address" /></p>
<p>And if we look at the generated source:</p>
<pre class="code">
&lt;a id=&quot;Gravatar1&quot; href=&quot;http://www.gravatar.com&quot; title=&quot;Get your avatar&quot;&gt;&lt;img width=&quot;80&quot; height=&quot;80&quot; src=&quot;http://www.gravatar.com/avatar.php?gravatar_id=ccf3b8c638f15d005e5d070aeb1a3923&amp;rating=G&amp;size=80&quot; alt=&quot;Gravatar&quot; /&gt;&lt;/a&gt;
</pre>
<p>The default produces a hyperlink off to the <a href="http://www.gravatar.com">Gravatar</a> site with a title &#8220;Get your avatar&#8221;.  The image contains the MD5 email hash, a rating of &#8220;G&#8221; (suitable for all audience types), and a size of 80.</p>
<h3>Customisation</h3>
<p>The control supports a number of properties supporting the customisation of its output.</p>
<h4>Size</h4>
<p>The size property of the control can be in the range 1 to 80.  If it is outside this range, a default of 80 will be used.</dd>
<h4>MaxAllowedRating</h4>
<p>The &#8216;highest&#8217; allowed rating of image.</p>
<ul>
<li>A G rated gravatar is suitable for display on all websites with any audience type.</li>
<li>PG rated gravatars contain may contain rude gestures, provocatively dressed individuals, the lesser swear words, or mild violence.</li>
<li>R rated gravatars may contain such things as harsh profanity, intense violence, nudity, or hard drug use.</li>
<li>X rated gravatars may contain hardcore sexual imagery or extremely disturbing violence.</li>
</ul>
<h4>OutputGravatarSiteLink</h4>
<p>True by default, determines whether a hyperlink linking to the gravatar website will be output around the image.</p>
<h4>LinkTitle</h4>
<p>&#8220;Get your avatar&#8221; by default, allows the customisation of the &#8216;title&#8217; attribute of the link (obviously doesn&#8217;t apply if OutputGravatarSiteLink property is set to false.)</p>
<h4>DefaultImage</h4>
<p>URL encoded URL, protocol included, of a GIF, JPEG, or PNG image that should be returned if either the requested email address has no associated gravatar, or that gravatar has a rating higher than is allowed by the &#8220;MaxAllowedRating&#8221; property.</p>
<p>The code snippet below shows the associated properties.</p>
<pre class="code">
&lt;fcm:Gravatar ID=&quot;Gravatar1&quot; runat=&quot;server&quot;
    Email=&quot;username@domain.com&quot;
    DefaultImage=&quot;http://www.site.com/default.jpg&quot;
    OutputGravatarSiteLink=&quot;true&quot; Size=&quot;40&quot; /&gt;
</pre>
<h3>Download and Get Started</h3>
<p>You can <a href='http://www.freshclickmedia.com/wp-content/uploads/2008/02/gravatar.zip' title='gravatar.zip'>download the Gravatar Custom Control here</a>.  Once you&#8217;ve extracted the assembly from the ZIP file, add to the Visual Studio toolbox by right clicking on the toolbox and selecting &#8220;Choose Items&#8221; from the context menu.  Browse to the assembly (Freshclickmedia.Web.dll), and click &#8220;OK&#8221; to add.</p>
<p><img src="http://farm3.static.flickr.com/2064/2283724303_c96532e03b_o.gif" alt="Adding the control to the toolbox" width="505" height="361"  /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.freshclickmedia.com/blog/2008/02/gravatar-aspnet-control/feed/</wfw:commentRss>
		<slash:comments>37</slash:comments>
		</item>
		<item>
		<title>A quick tour of C# 3.0&#8217;s new language features</title>
		<link>http://www.freshclickmedia.com/blog/2007/12/a-quick-tour-of-c-30s-new-language-features/</link>
		<comments>http://www.freshclickmedia.com/blog/2007/12/a-quick-tour-of-c-30s-new-language-features/#comments</comments>
		<pubDate>Wed, 05 Dec 2007 13:37:41 +0000</pubDate>
		<dc:creator>Shane</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://www.freshclickmedia.com/blog/2007/12/a-quick-tour-of-c-30s-new-language-features/</guid>
		<description><![CDATA[With Visual Studio 2008 now fully released, I take a quick look at some of the new language features in C# 3.0.

I&#8217;ll start the overview with the introduction of two classes, Person, and MyExtensions.

    public partial class Person
    {
        public Person()
  [...]]]></description>
			<content:encoded><![CDATA[<p>With Visual Studio 2008 now <a href="http://weblogs.asp.net/scottgu/archive/2007/11/19/visual-studio-2008-and-net-3-5-released.aspx">fully released</a>, I take a quick look at some of the new language features in C# 3.0.</p>
<p><span id="more-73"></span><br />
I&#8217;ll start the overview with the introduction of two classes, Person, and MyExtensions.</p>
<pre class="code">
    public partial class Person
    {
        public Person()
        {
            LogCreation();
        }

        // automatic properties:
        public int Age { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public short NumberOfChildren { get; set; }

        // partial method:
        partial void LogCreation();
    }

    // this could (and probably would) be in a different file:
    public partial class Person
    {
        // partial method implementation:
        partial void LogCreation()
        {
            Console.WriteLine("Person created");
        }
    }
</pre>
<p>The Person class introduces two new language features.</p>
<h3>Partial Methods</h3>
<p>The LogCreation method in the Person class has been decorated with the &#8216;partial&#8217; keyword, meaning that it is a &#8216;partial method&#8217;.  </p>
<p>Partial methods add a lightweight event handling mechanism to C#.  They&#8217;re basically methods where the declaration or prototype is specified in the declaration of a partial class, but the implementation can only be provided in another declaration for that partial class.  In other words, a partial method will only compile if it is specified in one partial class definition and is the implementation is provided in another partial class definition, as shown above.</p>
<p>The &#8216;clever&#8217; thing is that because no definition for the method is provided, no IL code is produced for that method, so the resulting assembly is no bigger or slower than if the partial method wasn&#8217;t there in the first place.  This then begs the question &#8211; if an implementation isn&#8217;t provided, why have the prototype at all?  Well, you could set up some &#8216;hooks&#8217; into your code for specific methods, that may or may not be implemented by a developer.</p>
<p>The Person class invokes the partial method LogCreation, and because an implementation is provided, the code is executed.  If the second partial class definition didn&#8217;t exist, or the method wasn&#8217;t implemented, the code would not be executed.  In practice, they are used by some new LINQ (more on that shortly) SQL entity classes as a hook for property value change notification.  A partial method is called before a property value changes, and a partial method is called after the property value has changed.  If you wish to hook into these, you can implement the methods in your partial class and be notified.  If not, the partial methods are &#8216;removed&#8217; from the assembly&#8217;s output.  </p>
<p>Syntactically, there are a few rules for partial methods:</p>
<ol>
<li>Can only be defined and implemented in partial classes</li>
<li>Must specify the partial modifer</li>
<li>Must not specify an access modifier, but are private.  If an access modifier (even if it&#8217;s private) is specified, you&#8217;ll get a compiler error</li>
<li>They must return void</li>
</ol>
<p>A little less strict in some other areas:</p>
<ol>
<li>They can have arguments</li>
<li>The don&#8217;t have to be implemented</li>
<li>They can be static</li>
</ol>
<p>The second class, MyExtensions, is shown below:</p>
<pre class="code">
    public static class MyExtensions
    {
        // extension method
        public static bool IsEven(this int number)
        {
            return number % 2 == 0;
        }
    }
</pre>
<p>The MyExtensions class shown above may look familiar at first glance, but the this keyword in the method arguments makes it stand out as an extension method.</p>
<h3>Extension Methods</h3>
<p>Basically, extension methods are a way of &#8216;extending&#8217; a .NET type with a method so that it may be called on an instance of that method.</p>
<p>The example shown illustrates the rules that an extension method must be defined as static, in a static class, and contain the this keyword in the method arguments list.  The type of argument is the .NET type that is being extended.</p>
<p>The nice thing is that when you have an extension method, you can do something like this:</p>
<p><img src="http://farm3.static.flickr.com/2286/2088223227_ab2e224bb1_o.png" alt="Extension methods in the Visual Studio 2008 IDE" /></p>
<p>Our example extends int, and the Visual Studio 2008 IDE indicates our extension method with a little icon and associated text.  Perhaps I need to get out a little more, but I find extension methods quite exciting.</p>
<h3>Collection and Object initialization</h3>
<pre class="code">
// collection initializer:
List<Person> people = new List< Person>
{
    // object initializer:
    new Person { Age = 6, FirstName = "Andy", LastName = "Andrews", NumberOfChildren = 0 },
    new Person { Age = 46, FirstName = "Bob", LastName = "Bobbins", NumberOfChildren = 3 },
    new Person { Age = 19, FirstName = "Charlie", LastName = "Charles", NumberOfChildren = 0 }
};
</pre>
<p>Collection initialization is a shorter way of creating a collection and initialising it.  Whereas before, the list would have to be created, and each item added separately, the whole thing can be done in one swoop.</p>
<p>Object initialization is very similar, and makes it easier to create an object and set property values at the same time.</p>
<h3>Lambda Expressions</h3>
<p>For the three Person instances added to the list, you could specify an anonymous method in C# 2.0 to extract items (in our case items of type Person) from the list based on a set of &#8216;matching criteria&#8217;:</p>
<pre class="code">
List< Person> children = people.FindAll( delegate( Person p) { return p.Age < 18; } );
</pre>
<p>This is all well and good, but the problem with anonymous methods is that they're a little bit, well, clunky.  </p>
<p>With lambda expressions, we can rewrite the above 'query' as follows:</p>
<pre class="code">
    IEnumerable&lt;Person&gt; children =
                people.Select(p =&gt; p).Where(p =&gt; p.Age &lt; 18);
</pre>
<p>Basically, we're referring to an item in the list as 'p', selecting 'p', and filtering using the Where method where the Age of the item is less than 18.  At first, I found them a little strange syntactically, but I've got used to them now, and don't typically use the old style anonymous methods.</p>
<h3>LINQ, var and anonymous type projection</h3>
<p><a href="http://msdn2.microsoft.com/netframework/aa904594.aspx">LINQ</a> is part of C# 3.0 and it's going to revolutionise the way that .NET developers access and manipulate data.  The previous example showed how the Select and Where methods seem familiar to a SQL way of dealing with data.</p>
<p>I attended a <a href="http://www.developerday.co.uk/ddd/default.asp">DDD</a> event last year, and was introduced to the 'var' keyword during a presentation.  I'm guessing that it was new to my fellow developers present because there were several loud gasps from the attendees.  </p>
<p>Aaaggggh!  It's like the old days of variants!</p>
<pre class="code">
var myName = "Shane";
</pre>
<p>The thing to really shout about here is that it is not a variant!  The compiler simply infers the type from the data on the right side of the assignment, in this case, a string.  It is a string!  It is not a variant!</p>
<p>The reason that this keyword is introduced is for anonymous types, and the following example, with some new LINQ syntax thrown in for good measure, will illustrate:</p>
<pre class="code">
var adults =
    from p in people
    where p.Age &gt;= 18
    select new { Name = p.FirstName + " " + p.LastName, Age = p.Age }; // anonymous type projection
</pre>
<p>The first thing to note is that from, where and select keywords are exactly as in a SQL query, but that the from occurs first.  This is mandatory, and it's unusual position is because Visual Studio's intellisense can only offer member information based on the data that is being queried.  Because this is first, Visual Studio can offer help for the where clause and the select clause (which appears last.)  There are a <a href="http://msdn2.microsoft.com/netframework/aa904594.aspx">number of other methods and keywords</a>, but I'll keep things brief here.</p>
<p>You'll notice that we're referring to an item in the list as 'p', referencing 'p' in the where clause with the Age property of the Person class, and then doing a select.</p>
<p>This select is doing something more interesting than the earlier example (which was just selecting people from the list).  It is using anonymous type projection, whereby an anonymous type is created as a result of a select on the data.</p>
<p>The type doesn't have a name (therefore it's anonymous), and its properties can be specified 'on the fly'.  Here, we're creating a new type to merge the first name and last name as 'Name', and creating an 'Age' property for the Person 'Age' property.</p>
<p>Because this type is anonymous, we need to specify the var keyword, and let the compiler work things out by inferring the type.</p>
<pre class="code">
// local variable type inference:
foreach (var currentAdult in adults)
{
    Console.WriteLine(currentAdult.Name + ".  Their age is " +
          (currentAdult.Age.IsEven() ? "" : "not ") + "even");
}
</pre>
<p>Once again, type inference comes into play, and we loop through the selected adults.  Note that the previously demonstrated int extension method is used (IsEven).</p>
<p>Remember that the Person class had a LogCreation partial method that was implemented?  Well, that is called every time a Person is constructed, so for our collection, object initialization and output, we get the following:</p>
<p><img src="http://farm3.static.flickr.com/2398/2089056994_f4af8efd4b_o.png" alt="Program output with partial method implementation" /></p>
<p>If the partial method implementation is taken out of the Person class, everything still compiles, but we get the following:</p>
<p><img src="http://farm3.static.flickr.com/2086/2089056998_48705d82e0_o.png" alt="Program output with partial method implementation removed" /></p>
<p>So, that concludes my brief overview of new language features.  Without doubt, the var keyword is likely to cause some controversy, but it really isn't bad, and is in fact required for anonymous types (which I believe to be a very handy addition to the language.)</p>
<p>I'm certainly looking forward to using the new language features, and I hope you do too.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.freshclickmedia.com/blog/2007/12/a-quick-tour-of-c-30s-new-language-features/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Your first ASP.NET Custom Control</title>
		<link>http://www.freshclickmedia.com/blog/2007/12/your-first-aspnet-custom-control/</link>
		<comments>http://www.freshclickmedia.com/blog/2007/12/your-first-aspnet-custom-control/#comments</comments>
		<pubDate>Sun, 02 Dec 2007 19:44:50 +0000</pubDate>
		<dc:creator>Shane</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.freshclickmedia.com/blog/2007/12/your-first-aspnet-custom-control/</guid>
		<description><![CDATA[One of the strengths of ASP.NET is the ability to write your own reusable custom controls, deploy them, and use them by simply dragging them onto a form from the toolbox.  This tutorial walks through the implementation of a &#8216;TimePicker&#8217; custom control.

In particular, it pays attention to:

Deriving from the WebControl class, and customising the [...]]]></description>
			<content:encoded><![CDATA[<p>One of the strengths of ASP.NET is the ability to write your own reusable custom controls, deploy them, and use them by simply dragging them onto a form from the toolbox.  This tutorial walks through the implementation of a &#8216;TimePicker&#8217; custom control.</p>
<p><span id="more-3"></span></p>
<p>In particular, it pays attention to:</p>
<ul>
<li>Deriving from the WebControl class, and customising the control&#8217;s output using the HtmlTextWriter class;</li>
<li>Customising the control using properties;</li>
<li>Adding the control to the Visual Studio toolbox and adding to a page;</li>
<li>Dealing with Postback data;</li>
<li>Validating the control like a typical web control</li>
</ul>
<p>The TimePicker control is a drop down list containing times separated by a user-definable time-period, such as 15 minutes. The <a href="http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.webcontrol(VS.71).aspx" title="WebControl class documentation on MSDN" target="_blank">WebControl class</a> provides a good foundation for custom control development in that it provides a number of methods, properties and events common to web controls in ASP.NET.</p>
<p>To start, create a new class library in Visual Studio.  In this case, I&#8217;ll mimick the Microsoft naming standards and call it Freshclickmedia.Web.</p>
<p><img src="http://farm3.static.flickr.com/2198/2080836411_288894e9a6_o.gif" alt="Creating the control class library" /></p>
<p>To further mimick the Microsoft namespace hiearchy, I have created UI and WebControls folders.</p>
<p><img src="http://farm3.static.flickr.com/2163/2081638246_a94ba9d137_o.gif" alt="Initial Project Layout" /></p>
<p>One this has been done, right click on the project and select &#8216;add new item&#8217;.  Add a new item of type &#8216;Web Custom Control&#8217; called .</p>
<p><img src="http://farm3.static.flickr.com/2208/2081648644_8744737dcf_o.gif" alt="Adding a custom control to the project" /></p>
<p>Once the new control has been added, there will be a lot of default, but unwanted code.  Remove the class data so that you end up with something like this:</p>
<pre class="code">
[ToolboxData("&lt;{0}:TimePicker runat=server&gt;")]
public class TimePicker : WebControl{protected override void RenderContents(HtmlTextWriter output)
{

}</pre>
<p>The first line is an attribute that defines what text will be added to a webform when the control is dragged from the toolbox.  More on this later.</p>
<p>The class contains a single overridden WebControl method, RenderContents.   The HtmlTextWriter class parameter allows control developers to customise the HTML markup that is rendered by the control at runtime, and it is this method that we&#8217;ll look at first.</p>
<p>By default, a class inheriting from WebControl will have a default &#8216;outer&#8217; HTML element of type Span.  We&#8217;re looking to write a Select, so we&#8217;ll add a constructor to specify this outer HTML element type:</p>
<pre class="code">
///
/// Constructor defining outer HTML element type
///
public TimePicker() : base( HtmlTextWriterTag.Select)
{

}</pre>
<p>Now when the control is used, the outer tag will be of type Select, which is what we want.  However, to output our times, we&#8217;ll need to go back to the RenderContents method.  In this simple example, we&#8217;ll write out a list of times.  Before we do this, we need to specify some properties as follows:</p>
<ul>
<li>The default text, such as &#8216;Select time&#8217;;</li>
<li>The minute increment for the control</li>
<li>The selected value on a Page postback</li>
</ul>
<p>Shown below is the code for those properties.  Note that each one uses the ViewState to persist the information across postbacks, and have default values of &#8220;Select Time&#8221;, 15, and string.Empty respectively.</p>
<pre class="code">
///
/// Gets or sets the default selection text.
///
public string DefaultSelectionText
{
  get { return ViewState["DefaultSelectionText"] == null ? "Select time" : (string)ViewState["DefaultSelectionText"]; }
  set { ViewState["DefaultSelectionText"] = value; }
}

///
/// Gets or sets the minute increment.
///
public int MinuteIncrement
{
  get { return ViewState["MinuteIncrement"] == null ? 15 : (int)ViewState["MinuteIncrement"]; }
  set { ViewState["MinuteIncrement"] = value; }
}

///
/// Gets or sets the selected value.
///
public string SelectedValue
{
  get { return ViewState["SelectedValue"] == null ? string.Empty : (string)ViewState["SelectedValue"]; }
  set { ViewState["SelectedValue"] = value; }
}</pre>
<p>To keep things simple, the RenderContents method will simply loop from 00:00 to the last available time, based on the MinuteIncrement property value.   The code is shown below:</p>
<pre class="code">
protected override void RenderContents(HtmlTextWriter writer)
{
  // write out the options:
  writer.Write("&lt;option value=\"\"{0}&gt;{1}&lt;/option&gt;", string.IsNullOrEmpty(SelectedValue) ? " selected=\"selected\"" : "", DefaultSelectionText);

  int minuteIncrement = Convert.ToInt32(MinuteIncrement);

  // 24 hours in a day, 60 minutes in an hour, 24 * 60 = 1440
  for (int minuteLoop = 0; minuteLoop &lt; 1440; minuteLoop += minuteIncrement)
  {
    // convert the minuteLoop value to a meaningful time:
    int hours = minuteLoop / 60;
    int leftOverMinutes = minuteLoop % 60;

    string time = string.Format("{0:00}:{1:00}", hours, leftOverMinutes);

    writer.Write( "&lt;option{0} value=\"{1}\"&gt;{2}&lt;/option&gt;", time == SelectedValue ? " selected=\"selected\"" : "", time, time);
  }

  base.RenderContents(writer);
}</pre>
<p>The key points from the code are that a series of &lt;option&gt; tags are written to the browser.  Some logic is included to determine whether the current option is the selected value, in which case a &#8217;selected&#8217; attribute is written out for that option value.</p>
<p>Before using the control, let&#8217;s spend a moment on adding it to the toolbox, and also customising the default toolbox image for the control.  To use a custom toolbox image, add a 16&#215;16 image of type .bmp to the same directory as the control class.  After the image has been added to the project, select properties and select the &#8216;Build Action&#8217; to be &#8216;Embedded Resource&#8217;.</p>
<p><img src="http://farm3.static.flickr.com/2155/2080883539_f193403008_o.gif" alt="Customising the toolbox icon for the control" /></p>
<p>Once the control has been built, do the following to add the control to the toolbox.</p>
<ol>
<li>[Optional] Right click on the toolbox and select &#8216;Add tab&#8217;.  Enter a name for the tab and press enter.</li>
<li>Right click on a tab and select &#8216;Choose items&#8230;&#8217;</li>
<li>Browse for the control assembly</li>
<li>Click OK to add the control to the toolbox.<img src="http://www.freshclickmedia.com/blog/wp-content/uploads/2007/10/addingtotoolbox.gif" alt="Adding the custom control to the toolbox" /></li>
</ol>
<p>So, once the control has been added, using it is as simple as dragging it from the toolbox onto a web form.</p>
<pre class="code">
&lt;form id="form1" runat="server"&gt;
	&lt;cc1:timepicker id="TimePicker1" runat="server"&gt;&lt;/cc1:timepicker&gt;
	&lt;asp:button id="Button1" runat="server" text="Submit"&gt;&lt;/asp:button&gt;
&lt;/form&gt;</pre>
<p>The markup shown above shows a very simple ASPX page with a time picker control and a button that will initiate a postback.</p>
<p>When we view it in the browser, we get the following:</p>
<p><img src="http://farm3.static.flickr.com/2239/2081686310_1b33c2800e_o.gif" alt="TimePicker control rendering with property customisation" /></p>
<p>This all looks great &#8211; exactly what we wanted, but there is one huge remaining issue.  If we click the submit button, the selected time is lost, so the control may look right, but functionally it&#8217;s rather useless if we can&#8217;t access the selected time, and the selected time doesn&#8217;t persist visually on the page across page postbacks.</p>
<p>To sort out the postback issue, we must implement 3 things:</p>
<ul>
<li>Derive our control from IPostBackDataHandler, and implement the 2 interface methods, LoadPostData and RaisePostDataChangedEvent.</li>
<li>Output an HTML &#8216;name&#8217; attribute to the rendering output so that the form can pick up the control&#8217;s submitted data.</li>
<li>Call RegisterRequiresPostback to indicate that the control requires page postback data handling.</li>
</ul>
<p>Implementing the IPostBackDataHandler interface results in the following class definition change:</p>
<pre class="code">
public class TimePicker : WebControl, IPostBackDataHandler</pre>
<p>The 2 interface methods, LoadPostData and RaisePostDataChangedEvent are coded as follows:</p>
<pre class="code">
public virtual bool LoadPostData(string postDataKey, NameValueCollection values)
{
  SelectedValue = Convert.ToString(values[this.UniqueID]);
  return false;
}

public void RaisePostDataChangedEvent()
{
  // Part of the IPostBackDataHandler contract.  Invoked if we ever returned true from the
  // LoadPostData method (indicates that we want a change notification raised).  Since we
  // always return false, this method is just a no-op.
}</pre>
<p>The LoadPostData retrieves information from the posted form data and assigns it to the SelectedValue property of the control.</p>
<p>The RaisePostDataChangedEvent method is an essential method here, since we&#8217;re inheriting from IPostBackDataHandler.  However, it is only  invoked if the LoadPostData method returns true, and in our case it returns false.  Returning true can be used to raise event based on changed data, but that is beyond the scope of this tutorial.</p>
<p>We also need to output an HTML &#8216;name&#8217; attribute to the control&#8217;s output, since this is what will be used to identify the control&#8217;s data when the form is posted to the server.  To do this, override the base class&#8217; AddAttributesToRender method:</p>
<pre class="code">
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
  writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID);
  base.AddAttributesToRender(writer);
}</pre>
<p>The last thing is to override the base class&#8217; OnPreRender method, to allow us to notify the page on which the control is hosted that the control requires post back handling:</p>
<pre class="code">
protected override void OnPreRender(EventArgs e)
{
  base.OnPreRender(e);    

  if (Page != null)
  {
    Page.RegisterRequiresPostBack(this);
  }
}</pre>
<p>Rebuilding will now fix the posting back issue, and the control will retain it&#8217;s selected value property.</p>
<p>Another issue with the control that&#8217;s very easy to implement is validation.  Placing a RequiredFieldAttribute on the page and associating it to the TimePicker control will result in the following error:</p>
<p><img src="http://farm3.static.flickr.com/2217/2081706952_acaeb960b2_o.gif" alt="Validation error on the TimePicker Control" /></p>
<p>To resolve this issue, simply add a ValidationProperty attribute to the control class:</p>
<pre class="code">
[ValidationProperty("SelectedValue")]
public class TimePicker : WebControl, IPostBackDataHandler</pre>
<p>Adding this simple line will give us nice co-operation with the ASP.NET validator controls.</p>
<p><img src="http://farm3.static.flickr.com/2110/2080931083_0799de7bd0_o.gif" alt="Validation fixed" /></p>
<p>So, that&#8217;s it for a simple custom control.  In future, I&#8217;ll be doing something slightly more interesting, as I look at integrating JavaScript within a control.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.freshclickmedia.com/blog/2007/12/your-first-aspnet-custom-control/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>C#&#8217;s null coalescing operator</title>
		<link>http://www.freshclickmedia.com/blog/2007/11/cs-null-coalescing-operator/</link>
		<comments>http://www.freshclickmedia.com/blog/2007/11/cs-null-coalescing-operator/#comments</comments>
		<pubDate>Wed, 14 Nov 2007 14:53:54 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.freshclickmedia.com/blog/2007/11/cs-null-coalescing-operator/</guid>
		<description><![CDATA[I&#8217;ve been programming in C# for about five years, and today whilst reading the C# language specification v3.0, came across the null coalescing operator.
Much like T-SQL&#8217;s ISNULL function, the operator replaces null values with the specified replacement value.

So, in T-SQL

	SELECT
		ISNULL( Fieldname, '')
	FROM
		TableName
In C#, the ?? operator is the ISNULL equivalent.  So, we have the [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been programming in C# for about five years, and today whilst reading the <a href="http://download.microsoft.com/download/3/8/8/388e7205-bc10-4226-b2a8-75351c669b09/csharp%20language%20specification.doc">C# language specification v3.0</a>, came across the null coalescing operator.</p>
<p>Much like T-SQL&#8217;s <a href="http://msdn2.microsoft.com/en-us/library/ms184325.aspx" title="ISNULL (Transact-SQL)">ISNULL function</a>, the operator replaces null values with the specified replacement value.</p>
<p><span id="more-70"></span></p>
<p>So, in T-SQL</p>
<pre class="code">
	SELECT
		ISNULL( Fieldname, '')
	FROM
		TableName</pre>
<p>In C#, the ?? operator is the ISNULL equivalent.  So, we have the following in C#</p>
<pre class="code">
	string nullString = null;

	string anotherString = nullString ?? "It was null";

	// anotherString now contains "It was null"

	string myName = "Shane";

	anotherString = myName ?? "Name is null";

	// anotherString now contains "Shane"</pre>
<p>Hardly revolutionary stuff, but I&#8217;ve never seen the operator before, so either it&#8217;s been discussed and regarded as useless, or other people are unaware of it, like I was until about 10 minutes ago.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.freshclickmedia.com/blog/2007/11/cs-null-coalescing-operator/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Write your own Visual Studio .NET Snippets to improve your coding productivity</title>
		<link>http://www.freshclickmedia.com/blog/2007/11/write-your-own-visual-studio-net-snippets-to-improve-your-coding-productivity/</link>
		<comments>http://www.freshclickmedia.com/blog/2007/11/write-your-own-visual-studio-net-snippets-to-improve-your-coding-productivity/#comments</comments>
		<pubDate>Wed, 07 Nov 2007 21:03:37 +0000</pubDate>
		<dc:creator>Shane</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://www.freshclickmedia.com/blog/2007/11/write-your-own-visual-studio-net-snippets-to-improve-your-coding-productivity/</guid>
		<description><![CDATA[Chances are that if you&#8217;ve been using Visual Studio .NET, you&#8217;ll have come across the concept of snippets &#8211; useful reusable chunks of code that are inserted after typing in a small textual identifier for that snippet.   This tutorial describes Visual Studio .NET snippets and describes how you can create your own.

A snippet [...]]]></description>
			<content:encoded><![CDATA[<p>Chances are that if you&#8217;ve been using Visual Studio .NET, you&#8217;ll have come across the concept of snippets &#8211; useful reusable chunks of code that are inserted after typing in a small textual identifier for that snippet.   This tutorial describes Visual Studio .NET snippets and describes how you can create your own.</p>
<p><span id="more-20"></span></p>
<p>A snippet that I use probably the most is the &#8216;prop&#8217; snippet.  To activate it, type &#8216;prop&#8217; at class scope in a Visual C# project.</p>
<p><img src="http://farm3.static.flickr.com/2335/1907228239_f5d7adb12e_o.gif" width="521" height="325" alt="The ‘prop’ snippet for quickly inserting a property at class scope" /></p>
<p>Selecting &#8216;prop&#8217; from the list, or tabbing twice will then produce the following code:</p>
<p><img src="hhttp://farm3.static.flickr.com/2008/1907228245_676e149ef3_o.gif" width="250" height="191" alt="The initial code produced by the ‘prop’ snippet" /></p>
<p>The focus is initially over the private member&#8217;s data type &#8216;int&#8217;.  This, and all the other text highlighted in green can be typed over.  Each piece of text can be cycled through by pressing the tab key.</p>
<p>You&#8217;ll also notice that the property&#8217;s type is outlined with a dotted line.  This means that once something has been typed in the active selection, tabbing out will change the dotted selection&#8217;s text to be the same.  This makes sense, since a property and the member that it relates to must be the same type.</p>
<p>In this quick scenario, we&#8217;ll change the data type to be of type string, the member to be _name, and property to be Name.  Note that tabbing through will cycle through the highlighted text.  When you&#8217;re happy, press enter, and you have a property.  Once the method for using snippets becomes familiar, their use becomes second nature and you&#8217;ll wonder how you ever worked without them.</p>
<p>The &#8216;prop&#8217; example is just one of many that can be managed through the &#8216;Code Snippets Manager&#8217;, accessed from the Visual Studio Tools menu.</p>
<p><img src="http://farm3.static.flickr.com/2030/1907228231_7bbe0e30a7_o.gif" width="472" height="350" alt="The code snippets manager" /></p>
<p>The real fun with snippets (real fun? perhaps I need to get out more) comes with developing your own.  The rest of the tutorial will create a simple property snippet to write/read information to/from the ViewState on an ASP.NET page.</p>
<p>A snippet is just an XML file, and the default Visual Studio snippets can be found in C:\Program Files\Microsoft Visual Studio 8\VC#\Snippets\1033\Visual C# by default.</p>
<p><img src="http://farm3.static.flickr.com/2269/1907228297_2caed5d003_o.gif" width="472" height="320" alt="The default Visual Studio snippets folder" /></p>
<p>If we open the prop.snippet file, we get this:</p>
<pre class="code">
&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"&gt;
  &lt;CodeSnippet Format="1.0.0"&gt;
    &lt;Header&gt;
      &lt;Title&gt;prop&lt;/Title&gt;
      &lt;Shortcut&gt;prop&lt;/Shortcut&gt;
      &lt;Description&gt;Code snippet for property and backing field&lt;/Description&gt;
      &lt;Author&gt;Microsoft Corporation&lt;/Author&gt;
      &lt;SnippetTypes&gt;
      &lt;SnippetType&gt;Expansion&lt;/SnippetType&gt;
      &lt;/SnippetTypes&gt;
   &lt;/Header&gt;
   &lt;Snippet&gt;
     &lt;Declarations&gt;
        &lt;Literal&gt;
          &lt;ID&gt;type&lt;/ID&gt;
          &lt;ToolTip&gt;Property type&lt;/ToolTip&gt;
          &lt;Default&gt;int&lt;/Default&gt;
        &lt;/Literal&gt;
        &lt;Literal&gt;
          &lt;ID&gt;property&lt;/ID&gt;
          &lt;ToolTip&gt;Property name&lt;/ToolTip&gt;
          &lt;Default&gt;MyProperty&lt;/Default&gt;
        &lt;/Literal&gt;
        &lt;Literal&gt;
          &lt;ID&gt;field&lt;/ID&gt;
          &lt;ToolTip&gt;The variable backing this property&lt;/ToolTip&gt;
          &lt;Default&gt;myVar&lt;/Default&gt;
        &lt;/Literal&gt;
      &lt;/Declarations&gt;
      &lt;Code Language="csharp"&gt;&lt;![CDATA[private $type$ $field$;
	public $type$ $property$
	{
          get { return $field$;}
          set { $field$ = value;}
	}
	$end$]]&gt;
      &lt;/Code&gt;
    &lt;/Snippet&gt;
  &lt;/CodeSnippet&gt;
&lt;/CodeSnippets&gt;</pre>
<p>The two main areas are the Header and the Snippet elements, underneath the main CodeSnippet element.  The Header contains the snippet title, shortcut (what you type in the editor to invoke the snippet), the description, author, and the snippet types.  In our case, it&#8217;ll be an Expansion type, meaning it will expand to generate a piece of code.</p>
<p>The Snippet element contains a declarations section.  This section contains 0 or more (in this case 3) items, 1 for each item that can be customised.  Each of these items has a unique identifier, ID, a tooltip and a default value.  The Snippet element also contains a Code section.  Wrapped in a CDATA section (since it&#8217;s quite likely we&#8217;ll be using reserved xml characters in here), it contains the injected code.  The variables declared in the Declarations are referenced in $s.  The $end$ defines where the cursor will be when the user types enter.</p>
<p>When I develop my own snippets, I often find it useful to start with an example of the type of code that the snippet will produce, before developing the snippet and removing &#8216;configurable&#8217; items.</p>
<pre class="code">public string SelectedValue
{
  get { return ViewState["SelectedValue"] == null ? 15 : (int)ViewState["SelectedValue"]; }
  set { ViewState["SelectedValue"] = value; }
}</pre>
<p>So, thinking about a snippet, it would be good to define the type of the property (string), the property name (SelectedValue), which is also used as the ViewStateIdentifier, and the default value (15).</p>
<p>Translating that into the snippet code gives us:</p>
<pre class="code">
&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"&gt;
  &lt;CodeSnippet Format="1.0.0"&gt;
    &lt;Header&gt;
      &lt;Title&gt;propvs&lt;/Title&gt;
      &lt;Shortcut&gt;propvs&lt;/Shortcut&gt;
      &lt;Description&gt;Code snippet for property and ViewState backing&lt;/Description&gt;
      &lt;Author&gt;Shane Porter&lt;/Author&gt;
      &lt;SnippetTypes&gt;
        &lt;SnippetType&gt;Expansion&lt;/SnippetType&gt;
      &lt;/SnippetTypes&gt;
    &lt;/Header&gt;
    &lt;Snippet&gt;
      &lt;Declarations&gt;
        &lt;Literal&gt;
          &lt;ID&gt;type&lt;/ID&gt;
          &lt;ToolTip&gt;Property type&lt;/ToolTip&gt;
          &lt;Default&gt;string&lt;/Default&gt;
        &lt;/Literal&gt;
        &lt;Literal&gt;
          &lt;ID&gt;property&lt;/ID&gt;
          &lt;ToolTip&gt;Property name&lt;/ToolTip&gt;
          &lt;Default&gt;MyProperty&lt;/Default&gt;
        &lt;/Literal&gt;
        &lt;Literal&gt;
          &lt;ID&gt;default&lt;/ID&gt;
          &lt;ToolTip&gt;The default value, if the ViewState value is null&lt;/ToolTip&gt;
          &lt;Default&gt;string.Empty&lt;/Default&gt;
        &lt;/Literal&gt;
      &lt;/Declarations&gt;
      &lt;Code Language="csharp"&gt;&lt;![CDATA[public $type$ $property$
        {
          get { return ViewState["$property$"] == null ? $default$ : (int)ViewState["$property$"]; }
          set { ViewState["$property$"] = value; }
        }
	$end$]]&gt;
      &lt;/Code&gt;
    &lt;/Snippet&gt;
  &lt;/CodeSnippet&gt;
&lt;/CodeSnippets&gt;</pre>
<p>Things are pretty simple.  I took the code that I wanted, thought about what I needed, created a variable (Literal element) for each thing, and replaced the hard-coded values in the pasted C# code to the $variable$ syntax.  I called the snippet &#8216;propvs&#8217;, since it uses the View State, and doesn&#8217;t clash with the default &#8216;prop&#8217; snippet.  You can have multiple snippets with the same name, but it becomes a little harder to distinguish them at usage-time since the Visual Studio IDE simply presents the two in a menu.</p>
<p>To use the snippet, you&#8217;ll need to import it using the Visual Studio Tools -&gt; Code Snippets Manager menu item.  On the resulting dialog, click the &#8216;Import&#8217; button and browse for the snippet.  You will then see this dialog:</p>
<p><img src="http://farm3.static.flickr.com/2228/1907249717_4ee521a2c0_o.gif" width="472" height="384" alt="Importing the snippet" /></p>
<p>Once Finish is clicked, click OK on the previous dialog to return to the editor.  Then, we can use our newly developed snippet by typing propvs and tabbing, or by selecting from the menu.</p>
<p><img src="http://farm3.static.flickr.com/2224/1907228251_2ff0f7446e_o.gif" width="284" height="295" alt="Selecting ‘propvs’ from the intellisense menu" /></p>
<p>Once this has been selected, you will get the injected code:</p>
<p><a href="http://farm3.static.flickr.com/2014/1907228263_f3457083c9_o.gif" title="View full size image"><img src="http://farm3.static.flickr.com/2014/1907228263_86b1b709e6.jpg" width="500" height="62" alt="The ‘propvs’ injected code" /></a></p>
<p>Tabbing through, typing what we need, will give us a very quick and easy way to insert the viewstate property pattern into our code.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.freshclickmedia.com/blog/2007/11/write-your-own-visual-studio-net-snippets-to-improve-your-coding-productivity/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
