<?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>Brian Dobberteen &#187; Code</title>
	<atom:link href="http://brian.dobberteen.com/category/code/feed/" rel="self" type="application/rss+xml" />
	<link>http://brian.dobberteen.com</link>
	<description>Fun With Web Development!</description>
	<lastBuildDate>Thu, 31 Jan 2013 04:05:38 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Enhancing the TypeSafe Enum Pattern</title>
		<link>http://brian.dobberteen.com/code/enhancing-the-typesafe-enum-pattern/</link>
		<comments>http://brian.dobberteen.com/code/enhancing-the-typesafe-enum-pattern/#comments</comments>
		<pubDate>Fri, 23 Sep 2011 17:57:15 +0000</pubDate>
		<dc:creator>brian</dc:creator>
				<category><![CDATA[Code]]></category>

		<guid isPermaLink="false">http://brian.dobberteen.com/?p=185</guid>
		<description><![CDATA[As I mentioned in my last post about the Typesafe Enum Pattern in C#/VB.NET, I left out a few features that I had originally wanted to include in that post. Namely, these features were nothing more than implementing the IComparable&#60;T&#62; and IEquatable&#60;T&#62; interfaces. Upon further investigation, I&#8217;ve found that there is no need to implement [...]]]></description>
				<content:encoded><![CDATA[<p>As I mentioned in my last post about the <a href="http://brian.dobberteen.com/code/typesafe-enum-pattern-in-cvb-net/">Typesafe Enum Pattern in C#/VB.NET</a>, I left out a few features that I had originally wanted to include in that post.</p>
<p>Namely, these features were nothing more than implementing the IComparable&lt;T&gt; and IEquatable&lt;T&gt; interfaces.</p>
<p>Upon further investigation, I&#8217;ve found that there is no need to implement IEquatable&lt;T&gt; here, as we&#8217;ll see in an example in just a moment.</p>
<p>Also, I&#8217;m not sure how often we&#8217;d find ourselves needing to sort collections of our enum-esque class.</p>
<p>Here&#8217;s the original class from the previous post:</p>
<h3 style="text-decoration: underline;">The &#8216;Enum&#8217; Class</h3>
<p>This will be our baseline to begin implementing the interface(s):</p>
<pre class="brush: csharp;">
public class UselessItem
{
    public string ItemName { get; private set; }
    public Guid ItemId { get; private set; }

    private UselessItem() { }

    private UselessItem(string itemName, Guid itemId)
    {
        ItemName = itemName;
        ItemId = itemId;
    }

    // Define the 'Enum' members
    public static UselessItem MacBook =
        new UselessItem(&quot;MacBook/MacBook Pro&quot;, new GUID(&quot;EAD0014A-3733-DD11-9DCA-0019B9B42749&quot;));

    public static UselessItem ScreenDoorOnASubmarine =
        new UselessItem(&quot;Screen Door on a Submarine&quot;, new GUID(&quot;EAD0014A-3733-DD11-9DCA-0019B9852F2E&quot;));

    public static UselessItem DehydratedWater =
        new UselessItem(&quot;Dehydrated Water&quot;, new GUID(&quot;EAD0014A-3733-DD11-9DCA-0019B2635342&quot;));
}
</pre>
<p>Again, if you&#8217;d like to re-familiarize yourself with the above code and its features, check out the original post: <a href="http://brian.dobberteen.com/code/typesafe-enum-pattern-in-cvb-net/">Typesafe Enum Pattern in C#/VB.NET</a>.</p>
<h3 style="text-decoration: underline;">Do We Need IEquatable&lt;T&gt;?</h3>
<p>See for yourself:</p>
<pre class="brush: csharp;">
var ui1 = UselessItem.MacBook;
var ui2 = UselessItem.DehydratedWater;

var r1 = (ui1 == UselessItem.MacBook);  // r1 = true
var r2 = (ui1 == ui2); // r2 = false
var r3 = (ui2 == UselessItem.MacBook); // r3 = false
</pre>
<p>This behaves just as a normal Enum would. Clearly, there is no need to implement IEquatable&lt;T&gt; in this case.</p>
<h3 style="text-decoration: underline;">Do We Need IComparable&lt;T&gt;</h3>
<p>IComparable&lt;T&gt;, on the other hand, might prove useful if we ever find ourselves wanting to sort an Array, etc, of UselessItem pseudo-Enums.</p>
<p>Without implementing IComparable&lt;T&gt;, we are not able to do:</p>
<pre class="brush: csharp;">
var uis = new[]
              {
                  UselessItem.MacBook,
                  UselessItem.DehydratedWater,
                  UselessItem.ScreenDoorOnASubmarine,
                  UselessItem.MacBook
              };

var s = string.Empty;

foreach (var ui in uis)
{
    s += ui.ItemName + &quot; &quot;;
}

// s = MacBook DehydratedWater ScreenDoorOnASubmarine MacBook

// And this won't work (yet):
Array.Sort(uis, (ui1, ui2) =&gt; ui1.CompareTo(ui2));  // CompareTo not defined for type UselessItem!

</pre>
<h3 style="text-decoration: underline;">Implementing IComparable&lt;T&gt;</h3>
<p>IComparable&lt;T&gt; is definitely one of the easier interfaces to implement &#8211; it only requires the implementation of a single method:</p>
<p><b>int CompareTo(T other);</b></p>
<p>CompareTo returns:</p>
<div style="border: 1px solid #000; background-color: #fff; padding: 5px;">
If <i>this</i> object is less than the <i>other</i> argument, the method returns a negative integer.</p>
<p>If <i>this</i> object is equal to the <i>other</i> argument, the method returns zero.</p>
<p>If <i>this</i> object is greater than the <i>other</i> argument, the method returns a positive integer.
</div>
<p>See <a href="http://msdn.microsoft.com/en-us/library/43hc6wht.aspx">MSDN&#8217;s Entry on IComparable&lt;T&gt;</a> for more information.</p>
<p>This mechanism is what allows, for example, Array.Sort() to work easily with a simple lambda expression.</p>
<p>So let&#8217;s implement it!</p>
<pre class="brush: csharp; highlight: [18];">
// The 'enum' members have been omitted for brevity
public class UselessItem : IComparable&lt;UselessItem&gt;
{
    public string ItemName { get; private set; }
    public Guid ItemId { get; private set; }

    private UselessItem() { }

    private UselessItem(string itemName, Guid itemId)
    {
        ItemName = itemName;
        ItemId = itemId;
    }

    // Implementing interface method here
    public int CompareTo(UselessItem other)
    {
        return this.ItemName.CompareTo(other.ItemName);
    }

// ... snip ...
</pre>
<p>In line 18, you can see that we want to be able to sort by our ItemName property.  Sorting the GUID ItemIDs is probably something of little interest, but it certainly can be done as well. In fact, this pattern can be used to make our enum-esque Class sortable by whatever property/datatype we might need for our purposes.</p>
<p>Let&#8217;s try a sample sort:</p>
<pre class="brush: csharp;">
var uis = new[]
              {
                  UselessItem.MacBook,
                  UselessItem.DehydratedWater,
                  UselessItem.ScreenDoorOnASubmarine,
                  UselessItem.MacBook
              };

var s = string.Empty;

foreach (var ui in uis)
{
    s += ui.ItemName + &quot; &quot;;
}

// s = MacBook DehydratedWater ScreenDoorOnASubmarine MacBook

// Now this works!
Array.Sort(uis, (ui1, ui2) =&gt; ui1.CompareTo(ui2));

s = string.Empty;

foreach (var ui in uis)
{
    s += ui.ItemName + &quot; &quot;;
}

// s = DehydratedWater MacBook MacBook ScreenDoorOnASubmarine

// Sort in the other direction
Array.Sort(uis, (ui1, ui2) =&gt; ui2.CompareTo(ui1));

var s2 = string.Empty;

foreach (var ui in uis)
{
    s2 += ui.ItemName + &quot; &quot;;
}

// s2 = &quot;ScreenDoorOnASubmarine MacBook MacBook DehydratedWater&quot;

</pre>
<p>Not too shabby!</p>
<h3 style="text-decoration: underline;">Conclusion</h3>
<p>Well, we haven&#8217;t added a ton of real-world useful functionality to our enum-esque Class, though it was an easy way to demonstrate the implementation and usefulness of IComparable&lt;T&gt;.  Initially, I had thought that implementing IEquatable&lt;T&gt; was also necessary to do simple operations such as:</p>
<pre class="brush: csharp;">
var ui1 = UselessItem.DehydratedWater;

if (ui1 == UselessItem.MacBook)
{
    Console.WriteLine(&quot;Sorry you ended up w/a MacBook! Dehydrated Water is slightly more useful!&quot;);
}
else
{
    Console.WriteLine(&quot;Your item might be worthless, but at least it's not a MacBook!&quot;);
}
</pre>
<p>But, as it turns out, the nature of our enum-esque class gives us the above capability out-of-the-box.</p>
<p>And free stuff, that works as expected? A rarity these days!</p>
]]></content:encoded>
			<wfw:commentRss>http://brian.dobberteen.com/code/enhancing-the-typesafe-enum-pattern/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Setting up VisualSVN for Local Projects</title>
		<link>http://brian.dobberteen.com/code/setting-up-visualsvn-for-local-projects/</link>
		<comments>http://brian.dobberteen.com/code/setting-up-visualsvn-for-local-projects/#comments</comments>
		<pubDate>Thu, 22 Sep 2011 18:22:05 +0000</pubDate>
		<dc:creator>brian</dc:creator>
				<category><![CDATA[Code]]></category>

		<guid isPermaLink="false">http://brian.dobberteen.com/?p=175</guid>
		<description><![CDATA[This one is pretty straightforward, but potentially useful to those of you not yet familiar with source control. In a nutshell, source control allows us to keep a historical record of any changes we&#8217;ve made to files over the course of time. This is beneficial because if multiple people are working on the same project, [...]]]></description>
				<content:encoded><![CDATA[<p>This one is pretty straightforward, but potentially useful to those of you not yet familiar with source control.</p>
<p>In a nutshell, source control allows us to keep a historical record of any changes we&#8217;ve made to files over the course of time. This is beneficial because if multiple people are working on the same project, it can be very easy to accidentally overwrite someone else&#8217;s changes that you may not have been aware of. It also gives some peace of mind to know that copies of your teams&#8217; work are safe from accidental local deletion, corruption, and other such maladies.</p>
<p>The source control system that we will be using today is known as Subversion.</p>
<p>Subversion (SVN) is an open-source, widely used, and in my experience, very solid choice for a version control system (VCS). To be sure, there are many others out there, such as Git, Mercurial, Team Foundation Server, CVS&#8230; the list goes on.</p>
<p>We&#8217;re going to quickly learn how to get an SVN server up and running on your Windows box with the aid of two software packages: VisualSVN Server and TortoiseSVN (which will serve as our client).</p>
<p>First, let&#8217;s grab these two packages &#8211; try and be sure to grab the latest stable release offered at each site.</p>
<p>VisualSVN Server: <a href="http://www.visualsvn.com/server/download/">http://www.visualsvn.com/server/download/</a></p>
<p>TortoiseSVN: <a href="http://tortoisesvn.net/downloads.html">http://tortoisesvn.net/downloads.html</a></p>
<h3 style="text-decoration: underline;">Installing VisualSVN Server</h3>
<p>Fire up the VisualSVN Server installer that you downloaded from the above link. Follow the on-screen prompts &#8211; the default settings should be fine. Once that&#8217;s done, it should offer to take you right to the VisualSVN Server Manager Console &#8211; click OK and we&#8217;ll find ourselves at a screen that should look similar to:</p>
<p><img src="http://brian.dobberteen.com/wp-content/uploads/2011/09/svn01.jpg" alt="VisualSVN Server Management Console" title="svn01" width="818" height="618" class="aligncenter size-full wp-image-176" /></p>
<p>The next step is to create at least one user and one repository:</p>
<p><img src="http://brian.dobberteen.com/wp-content/uploads/2011/09/svn02.jpg" alt="Adding Users and Repositories" title="svn02" width="256" height="180" class="aligncenter size-full wp-image-177" /></p>
<p>Creating a new user couldn&#8217;t be simpler &#8211; just decide on a username and enter/confirm a password.</p>
<p>Setting up a new repository is equally simple &#8211; all you need to do at this point is give it a name, preferably something meaningful to you and your team. For now, don&#8217;t worry about the &#8216;Create default structure&#8217; checkbox and make sure that it&#8217;s not checked.</p>
<p>And that&#8217;s it! Told you it was simple!</p>
<h3 style="text-decoration: underline;">Installing and Using TortoiseSVN</h3>
<p>Again, first step will be to run the TortoiseSVN installer that you downloaded earlier. Just accept any default settings. Once the installer is done, it will prompt you to reboot &#8211; go ahead and do so.</p>
<p>Once back in Windows, we find that our right-click context menu has some new additions:</p>
<p><img src="http://brian.dobberteen.com/wp-content/uploads/2011/09/svn03.jpg" alt="" title="svn03" width="326" height="55" class="aligncenter size-full wp-image-178" /></p>
<p>Next, we&#8217;ll want to create a folder to create what is known as our &#8216;working copy&#8217; of the project that will now be under source control.</p>
<p>In whatever location you deem appropriate, create a new folder, preferably with a name that matches the name of the repository you created earlier in VisualSVN Server.</p>
<p>Once that&#8217;s done, right click the new folder, and then click on &#8216;SVN Checkout&#8230;&#8217; in the context menu, which brings us to:</p>
<p><img src="http://brian.dobberteen.com/wp-content/uploads/2011/09/svn04.jpg" alt="" title="svn04" width="468" height="368" class="aligncenter size-full wp-image-179" /></p>
<p>All that&#8217;s needed for this screen is to type the URL of the repository you&#8217;ve created. I&#8217;m using localhost here, and this may or may not work. If it does not, replace localhost with the name of your machine.</p>
<p>Finally, replace where I show &#8216;Site1&#8242; with the name of the repository you created earlier.</p>
<p>Leave all other settings as they are, then click OK.</p>
<p>Because we&#8217;re connecting over SSL, TortoiseSVN will prompt you about whether or not you want to accept the security certificate. Choose &#8216;Accept Permanently&#8217; and you&#8217;ll be good to go for now and in the future.</p>
<p>Now, you have an active &#8216;working copy&#8217; that is under version control by SVN!</p>
<h3 style="text-decoration: underline;">Adding Project Files to SVN</h3>
<p>If you already have an existing project, made up of files and directories, the first step will be to copy those items to the folder you just did the SVN Checkout to.</p>
<p>Note that it is easy to tell at a glance what folders/files are under source control, and what their current status is:</p>
<p><img src="http://brian.dobberteen.com/wp-content/uploads/2011/09/svn05.jpg" alt="" title="svn05" width="468" height="93" class="aligncenter size-full wp-image-180" /></p>
<p>So, let&#8217;s add some files to our working copy folder and place them in to the repository.</p>
<p>The first step is to select the files that you want to place in the repository by first selecting those files/folders, right clicking your selection, and choosing TortoiseSVN -> Add&#8230;</p>
<p><img src="http://brian.dobberteen.com/wp-content/uploads/2011/09/svn06.jpg" alt="" title="svn06" width="808" height="367" class="aligncenter size-full wp-image-181" /></p>
<p>Which brings us to:</p>
<p><img src="http://brian.dobberteen.com/wp-content/uploads/2011/09/svn07.jpg" alt="" title="svn07" width="380" height="286" class="aligncenter size-full wp-image-182" /></p>
<p>Leave everything checked, then click OK.</p>
<p>TortoiseSVN will show the progress of the Add &#8211; if everything went ok, it should say so. Click OK to close the window.</p>
<p>Note that now each file/folder icon will be overlaid with a blue plus sign, indicating that it has been <b>added</b> but not <b>committed</b>.</p>
<p>The final step is to Commit these added files/folders by again, first selecting the ones you&#8217;ve just added, right-clicking that selection, and choosing &#8216;SVN Commit&#8230;&#8217;:</p>
<p><img src="http://brian.dobberteen.com/wp-content/uploads/2011/09/svn08.jpg" alt="" title="svn08" width="581" height="184" class="aligncenter size-full wp-image-183" /></p>
<p>Which brings us to:</p>
<p><img src="http://brian.dobberteen.com/wp-content/uploads/2011/09/svn09.jpg" alt="" title="svn09" width="519" height="511" class="aligncenter size-full wp-image-184" /></p>
<p>The area circled in red above is a text area to enter a log message detailing what you are committing. Personally, I think it best to always try to include some meaningful comment about what you&#8217;ve included/changed in the commit.</p>
<p>Messages like: &#8216;Pulled the javascript out of index.html and placed it in scripts/myscript.js&#8221; can definitely be of help.</p>
<p>Though the log message is optional for us, some shops may require a log message on each commit.</p>
<p>Don&#8217;t be lazy &#8211; always enter a commit log message!</p>
<p>Once you&#8217;re done entering your message, click OK. TortoiseSVN will show the progress of the commit, ending with a display of what revision you are now on. Since this was the very first commit, it makes sense that you should see that you are now at Revision 1.</p>
<h3 style="text-decoration: underline;">Day to Day Usage of SVN</h3>
<p>Frequently Updating and Commiting your project files is an excellent habit to get into. We already know what a Commit does, and I bet you can guess what an Update does.</p>
<p>To try it, select any files you&#8217;d like to have the latest copy of so that you can be sure that you&#8217;ve picked up any changes by other members of your team. Right click these selected files and click SVN Update&#8230;</p>
<p>Since you are the only one who has committed anything to this point, you&#8217;ll see that nothing has changed and that you are still on Revision 1.</p>
<h3 style="text-decoration: underline;">Next Steps</h3>
<p>Add more users, one for each member of your team.</p>
<p>Add more repositories, one for each of your projects.</p>
<p>Individually make and commit changes, being sure to update after each one to ensure you have the latest code.</p>
<p>Experiment with features such as &#8216;Locking&#8217; which will prevent other team members from modifying the locked file until you release that lock.</p>
<p>Hopefully this has been of some use to you CVS n00bs out there &#8211; next time, we&#8217;ll go over conflict resolution, an important tenet of version control.</p>
]]></content:encoded>
			<wfw:commentRss>http://brian.dobberteen.com/code/setting-up-visualsvn-for-local-projects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Typesafe Enum Pattern in C#/VB.NET</title>
		<link>http://brian.dobberteen.com/code/typesafe-enum-pattern-in-cvb-net/</link>
		<comments>http://brian.dobberteen.com/code/typesafe-enum-pattern-in-cvb-net/#comments</comments>
		<pubDate>Tue, 20 Sep 2011 23:18:16 +0000</pubDate>
		<dc:creator>brian</dc:creator>
				<category><![CDATA[Code]]></category>

		<guid isPermaLink="false">http://brian.dobberteen.com/?p=173</guid>
		<description><![CDATA[Been doing some thinking about Enum and a couple of its shortcomings. First, let&#8217;s create a simple Enum: // C# public enum UsefulItem { Unknown = 0, Foo, Bar, Baz } ' VB.NET Public Enum UsefulItem Unknown = 0 Foo Bar Baz End Enum From here on out, we&#8217;ll stick to C# in these examples [...]]]></description>
				<content:encoded><![CDATA[<p>Been doing some thinking about Enum and a couple of its shortcomings. </p>
<p>First, let&#8217;s create a simple Enum:</p>
<pre class="brush: csharp;">
// C#
public enum UsefulItem {
    Unknown = 0,
    Foo,
    Bar,
    Baz
}
</pre>
<pre class="brush: vb;">
' VB.NET
Public Enum UsefulItem
    Unknown = 0
    Foo
    Bar
    Baz
End Enum
</pre>
<p>From here on out, we&#8217;ll stick to C# in these examples (VB.NET source available for download soon!).</p>
<p>A recent project prompted me to create a number of Enums, as I have done in the past in many other projects.</p>
<p>For this project, however, I had a desire to have tighter control over the usage of the Enum type, as it dawned on me that:</p>
<pre class="brush: csharp;">
var ui1 = UsefulItem.Foo;
var ui2 = (UsefulItem) 256;

var s1 = ui1.ToString(); // s1 = &quot;Foo&quot;
var s2 = ui2.ToString(); // s2 = &quot;256&quot;
</pre>
<p>Ok, well that&#8217;s kinda disconcerting, but I&#8217;m sure .NET has a library function to check if an Enum value is defined. Not surprisingly, they do, and even less suprisingly, it is:</p>
<p><strong>Enum.IsDefined(Type enumType, Object value)</strong></p>
<p>Works great:</p>
<pre class="brush: csharp;">
var ui1 = UsefulItem.Bar;
var ui2 = (UsefulIem) 1;  // Equal to 'Foo'
var ui3 = (UsefulItem) 256; // Again, undefined

var r1 = Enum.IsDefined(typeof(UsefulItem), ui1); // r1 = true
var r2 = Enum.IsDefined(typeof(UsefulItem), ui2); // r2 = true
var r3 = Enum.IsDefined(typeof(UsefulItem), ui3); // r3 = false
</pre>
<p>No surprises here, right? Well&#8230; maybe not so fast.</p>
<p>Hit up Google for some research and immediately found widespread concern over the performance of Enum.IsDefined().</p>
<p>It turns out that Enum.IsDefined() uses Reflection and must access metadata in order to do its magic. Neither of these operations are real speed demons, to be sure, and when using IsDefined in a loop with a ton of iterations, these performance problems may manifest themselves in an attention-getting way.</p>
<p>No, I never bothered to test this.</p>
<p>An alternative method for checking if an in-range UsefulItem variable was given:</p>
<pre class="brush: csharp;">
var ui1 = UsefulItem.Foo;
var ui2 = (UsefulItem) 256;

var r1 = (ui1 &lt; UsefulItem.Unknown &amp;&amp; ui1 &gt; UsefulItem.Baz);  // r1 = false, ui1 is defined
var r2 = (ui2 &lt; UsefulItem.Unknown &amp;&amp; url &gt; UsefulItem.Baz);  // r2 = true, ui2 is not defined
</pre>
<p>This works, but what about when you add another UsefulItem to your Enum definition?  The code above suddenly goes stale, maintenance nighmare ensues, company goes under, and you begin your unlimited unemployment benefit checks!</p>
<p>And the above was for a simple enum that had integer values in the Enum definition that matched the integer values in the DB lookup table. (The use of Enums to represent DB lookup table values can be discussed at another time).</p>
<p>The next Enum I needed to create didn&#8217;t have any integer values to line up with. The next lookup table that I wanted to represent used GUIDs as its primary key (PK) and this doesn&#8217;t work:</p>
<pre class="brush: csharp;">
public enum UselessItem {
    Unknown = new Guid(&quot;00000000-0000-0000-0000-000000000000&quot;),
    MacBook = new Guid(&quot;FAE0D3E4-9996-473B-8EEB-00001A5AC22F&quot;)
}
</pre>
<p>I get that last snippet was a bit gratuitous &#8211; we all know by now that Enums use integers as their underlying datatype.</p>
<p>And not only did I want to have a GUID represent each of my quasi-Enums, but I also wanted string representation beyond the camelcase names in the Enum. I won&#8217;t bother with another silly example &#8211; clearly a string is not an int, and can in no way be tied to the members of an Enum.</p>
<p>During my earlier research that revealed .NET&#8217;s willingness to allow any integer to be assigned to an Enum, I stumbled across something called the Typesafe Enum Pattern.</p>
<p>For reasons unknown to me, Java apparently doesn&#8217;t do Enums. That may not be entirely true, but for the sake of argument, let&#8217;s just over-simplify things here and agree that Java doesn&#8217;t do Enums.</p>
<p>I ended up finding <a href="http://java.sun.com/developer/Books/shiftintojava/page1.html#replaceenums">Replace Enums with Classes [sun.java.com]</a> and was inspired by what I read.</p>
<p>It led me to develop:</p>
<pre class="brush: csharp;">
public class UselessItem
{
    public string ItemName { get; private set; }
    public Guid ItemId { get; private set; }

    private UselessItem() { }

    private UselessItem(string itemName, Guid itemId)
    {
        ItemName = itemName;
        ItemId = itemId;
    }

    // Define the 'Enum' members
    public static UselessItem MacBook =
        new UselessItem(&quot;MacBook/MacBook Pro&quot;, new GUID(&quot;EAD0014A-3733-DD11-9DCA-0019B9B42749&quot;));

    public static UselessItem ScreenDoorOnASubmarine =
        new UselessItem(&quot;Screen Door on a Submarine&quot;, new GUID(&quot;EAD0014A-3733-DD11-9DCA-0019B9852F2E&quot;));

    public static UselessItem DehydratedWater =
        new UselessItem(&quot;Dehydrated Water&quot;, new GUID(&quot;EAD0014A-3733-DD11-9DCA-0019B2635342&quot;));
}
</pre>
<p>Note that the version above has been somewhat stripped down for clarity &#8211; originally I had implemented both IComparable<T> and IEquatable<T> as well as overridden the &#8216;==&#8217; and &#8216;!=&#8217; operators and the ToString() and GetHashCode() methods. These changes are left as an exercise for the reader <img src='http://brian.dobberteen.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>Using this newly created struct, let&#8217;s check out some of its characteristics:</p>
<pre class="brush: csharp;">
var ui1 = UselessItem.MacBook;

var in1 = ui1.ItemName; // in1 = &quot;MacBook/MacBook Pro'
var g1 = ui1.ItemId; // g1 = {EAD0014A-3733-DD11-9DCA-0019B9B42749}
</pre>
<p>Could a disgruntled fanboi do this?</p>
<pre class="brush: csharp;">
ui1.ItemName = &quot;MacBooks Rule! PCs suxx!&quot;;
ui1.ItemID = Guid.NewGuid();
</pre>
<p>Definitely not! Note lines 3 and 4 of our UselessItem Class definition &#8211; they only allow setting of these two properties from within the class itself. This is caught at compile time and simply not allowed.</p>
<p>Other things that the compiler will keep us safe from:</p>
<pre class="brush: csharp; highlight: [1,3,5];">
var macIsRad = new UselessItem(&quot;PCs and Windoze&quot;, Guid.NewGuid());

var haxxor1 = (UselessItem) Guid.NewGuid();

var haxxor2 = (UselessItem) &quot;pwnt!!!&quot;;
</pre>
<p>In line one above, we cannot create new UselessItem objects, thanks to our private explicit default contructor:</p>
<pre class="brush: csharp; light: true;">
private UselessItem() { }
</pre>
<p>Lines 3 and 5 will fail to compile as nothing but UselessItem objects can be cast to UselessItem.</p>
<p>Though this, as contrived as it is, will only be caught at runtime:</p>
<pre class="brush: csharp;">
object o1 = string.Empty;

var ui1 = (UselessItem) o1;
</pre>
<p>Try the above code and get an InvalidCastException at runtime, killing the application if not caught.</p>
<p>And we even get the same behavior out of our class as we would a traditional Enum:</p>
<pre class="brush: csharp;">
var ui1 = UsefulItem.Foo;
var ui2 = ui1;
var ui1 = UsefulItem.Baz;

// Final Result: ui1 = UsefulItem.Baz, ui2 = UsefulItem.Foo

var ui3 = UselessItem.MacBook;
var ui4 = ui3;
var ui3 = UselessItem.ScreenDoorOnASubmarine;

// Final Result: ui3 = UselessItem.ScreenDoorOnASubmarine, ui4 = UselessItem.MacBook
</pre>
<p>For some reason, this surprised me. At first, I thought that using a struct rather than a class would be prudent here, seeing as how structs are value types and classes are reference types.</p>
<p>After giving it a bit of thought, I believe it is because we cannot actually even instantiate a UselessItem object, we don&#8217;t have to worry about usual reference type behavior.</p>
<p>There is some tradeoff, I suppose.</p>
<p>Because a class can contain an explicit parameterless constructor, and a struct cannot, we end up the following difference between the two approaches:</p>
<p>Assume for a moment that UselessItem is indeed a struct:</p>
<p>Because structs are value types, they can never be set to null. This is partly the reason why they cannot have explicit parameterless constructors. Calling new on a struct is no different than declaring a new struct variable without assigning a value:</p>
<pre class="brush: csharp; light: true;">
var ui1 = new UselessItem();
UselessItem ui2;
</pre>
<p>Though you aren&#8217;t able to use the ui2 variable here (compile-time error &#8211; Use of unassigned local variable &#8216;ui2&#8242;) it is plain to see during debugging that after line 2 above has run, both ui1 and ui2 contain the same values, which for structs, are all the default values for each type contained within (in this case, null for the ItemName and {00000000-0000-0000-0000-000000000000} for the ItemId.</p>
<p>On the other hand, using a class, we end up with:</p>
<pre class="brush: csharp; light: true;">
var ui1 = new UselessItem(); // Illegal! Private parameterless constructor!
UselessItem ui2;
</pre>
<p>Obviously, the code in line 1 above is not an issue, since it fails at compile time.  ui2, though, is actually equal to null following this initial declaration. Again, this is contrast to a struct, who ends up with default values for all of its members.</p>
<p>I, for one, think the use of a class here is a bit cleaner, as we can just check the whole object against null rather than checking some/all of the struct members against default values to determine if our object represents an unknown, or null, UselessItem.</p>
<p>Pretty cool!</p>
<p>Would love to hear comments on this approach &#8211; go ahead, tear me a new one, I can take it.</p>
]]></content:encoded>
			<wfw:commentRss>http://brian.dobberteen.com/code/typesafe-enum-pattern-in-cvb-net/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using PHP and MySQL to Create a Simple Contact Form and Results Browser</title>
		<link>http://brian.dobberteen.com/code/using-php-and-mysql-to-create-a-simple-contact-form-and-results-browser/</link>
		<comments>http://brian.dobberteen.com/code/using-php-and-mysql-to-create-a-simple-contact-form-and-results-browser/#comments</comments>
		<pubDate>Sat, 17 Sep 2011 07:10:28 +0000</pubDate>
		<dc:creator>brian</dc:creator>
				<category><![CDATA[Code]]></category>

		<guid isPermaLink="false">http://brian.dobberteen.com/?p=169</guid>
		<description><![CDATA[By request, let&#8217;s build a simple Contact Form with a PHP/MySQL backend! (Disclaimer: I don&#8217;t pretend to be an expert in PHP [nor .NET for that matter!], so please understand that the way I go about this might be sub-optimal. Whatever, sue me.) Building the HTML Contact Form This part is as straightforward as can [...]]]></description>
				<content:encoded><![CDATA[<p>By request, let&#8217;s build a simple Contact Form with a PHP/MySQL backend!</p>
<p>(Disclaimer: I don&#8217;t pretend to be an expert in PHP [nor .NET for that matter!], so please understand that the way I go about this might be sub-optimal. Whatever, sue me.)</p>
<h3 style="text-decoration: underline;">Building the HTML Contact Form</h3>
<p>This part is as straightforward as can be. We&#8217;re going to create a &#8216;Contact Form&#8217; with a grand total of THREE fields &#8211; extending this model is left as an exercise for the reader (lol, always wanted to write that!)</p>
<p>For brevity, we&#8217;re going to use the HTML5 doctype and a table-based (gasp!) layout. Feel free to change it to whatever you want.</p>
<p>Here goes:</p>
<pre class="brush: xml; highlight: [10];">
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;title&gt;My Rad Contact Form&lt;/title&gt;
    &lt;style type=&quot;text/css&quot;&gt;
        table tr &gt; td { text-align: right; }
        table tr &gt; td + td { text-align: left; }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;form action=&quot;ContactFormHandler.php&quot; method=&quot;post&quot;&gt;
        &lt;table&gt;
            &lt;tr&gt;
                &lt;td&gt;
                    Your Name:
                &lt;/td&gt;
                &lt;td&gt;
                    &lt;input type=&quot;text&quot; id=&quot;Name&quot; name=&quot;Name&quot; /&gt;
                &lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td&gt;
                    Your Email:
                &lt;/td&gt;
                &lt;td&gt;
                    &lt;input type=&quot;text&quot; id=&quot;Email&quot; name=&quot;Email&quot; /&gt;
                &lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td&gt;
                    Least Favorite Color:
                &lt;/td&gt;
                &lt;td&gt;
                    &lt;select id=&quot;LeastFavoriteColor&quot; name=&quot;LeastFavoriteColor&quot;&gt;
                        &lt;option value=&quot;&quot;&gt;- Choose -&lt;/option&gt;
                        &lt;option value=&quot;Blue&quot;&gt;Blue&lt;/option&gt;
                        &lt;option value=&quot;Green&quot;&gt;Green&lt;/option&gt;
                        &lt;option value=&quot;Orange&quot;&gt;Orange&lt;/option&gt;
                        &lt;option value=&quot;Red&quot;&gt;Red&lt;/option&gt;
                        &lt;option value=&quot;Yellow&quot;&gt;Yellow&lt;/option&gt;
                    &lt;/select&gt;
                &lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td colspan=&quot;2&quot; style=&quot;text-align: center;&quot;&gt;
                    &lt;input type=&quot;submit&quot; id=&quot;submit&quot; value=&quot;Contact Me!&quot; /&gt;
                    &lt;input type=&quot;reset&quot; id=&quot;reset&quot; value=&quot;Start Over!&quot; /&gt;
                &lt;/td&gt;
            &lt;/tr&gt;
        &lt;/table&gt;
    &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Which, in IE9 renders as:</p>
<p><img src="http://brian.dobberteen.com/wp-content/uploads/2011/09/ContactForm01.jpg" alt="" title="ContactForm01" width="347" height="148" class="aligncenter size-full wp-image-171" /></p>
<p>I&#8217;ve highlighted line 10 above to bring attention to the &#8216;action&#8217; attribute of our opening form element. Whatever the form&#8217;s action is set to is where, on submission, the form &#8216;posts&#8217; its values to. To read more about HTTP POST, please visit <a href="google.com">google</a>.</p>
<p>And that completes the form!</p>
<h3 style="text-decoration: underline;">Creating a MySQL Table to Store Form Values</h3>
<p>Again, as a Microsoft fanboy &copy;, I rarely spend much time with MySQL in any real capacity. You have been warned.</p>
<p>We are going to assume that you have a MySQL instance installed and available to you. And that you know how to login and arrive at the MySQL &#8216;command line.&#8217;</p>
<p>Once logged in, we&#8217;ll first need to create a new database to store our new table which in turn will store our contact form values:</p>
<pre class="brush: sql; gutter: false;">
mysql&gt; CREATE DATABASE MyRadContactForm;
</pre>
<p>Not surprisingly, this creates a new database with the name MyRadContactForm. The ALL CAPS is not required, but SQL is typically written in this fashion.</p>
<p>Next, we must let MySQL know what database we want to use:</p>
<pre class="brush: sql; gutter: false;">
mysql&gt; USE MyRadContactForm;
</pre>
<p>Now our new DB is the active one, and we can create our table in it:</p>
<pre class="brush: sql;">
mysql&gt; CREATE TABLE MyRadContacts (
    -&gt; ContactID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    -&gt; ContactName VARCHAR(100),
    -&gt; ContactEmail VARCHAR(100),
    -&gt; ContactLeastFavoriteColor VARCHAR(10)
    -&gt; ContactDateCreated DATETIME
    -&gt; );
</pre>
<p>Quickly, <b>ContactID</b> is what we call a Primary Key &#8211; it is used to uniquely identify each record in the table.</p>
<p>It is an INT (Integer) type, meaning it can store whole numbers.</p>
<p>It is a NOT NULL column, meaning that it <b>must</b> contain a value for each row in the table.</p>
<p>And finally, it is an AUTO_INCREMENT column &#8211; this means that each time we add a new record to this table, MySQL will ensure that each ID is unique by essentially adding one to the highest existing ID at the time of a new insert.</p>
<p>VARCHAR(100) means that we can store a string (sequence of letters, numbers, etc) up to 100 characters in length.</p>
<p>DATETIME&#8230; well, that should be obvious.</p>
<p>Our new table should now be in place, though to quickly check, we can try:</p>
<pre class="brush: plain; light: true;">
mysql&gt; SHOW TABLES;
+----------------------------+
| Tables in MyRadContactForm |
+----------------------------+
| MyRadContacts              |
+----------------------------+
</pre>
<h3 style="text-decoration: underline;">Creating PHP Server-Side Code to Store New Values</h3>
<p>Well, now we have something the client sees (the HTML form) and something buried deep within the bowels of a database to store values input by the client.</p>
<p>How, then, do we manage to bridge the gap between these two pieces?</p>
<p>In this case, we&#8217;ll use PHP.</p>
<p>We assume that you have a functioning PHP installation. Check out <a href="http://www.apachefriends.org/en/xampp.html">xampp</a> for a relatively painless way to get up and running with PHP/MySQL/Apache on various platforms.</p>
<p>Right, without further delay:</p>
<pre class="brush: php; highlight: [4,11,15,23,25,28];">
&lt;?php
    // Grab our POSTed form values
    // Note that whatever is enclosed by $_POST[&quot;&quot;] matches the form input elements
    $contactName = $_POST[&quot;ContactName&quot;];
    $contactEmail = $_POST[&quot;ContactEmail&quot;];
    $contactLeastFavoriteColor = $_POST[&quot;ContactLeastFavoriteColor&quot;];

    // Connect to our DB with mysql_connect(&lt;server&gt;, &lt;username&gt;, &lt;password&gt;)
    $sql_connection = mysql_connect(&quot;localhost&quot;, &quot;root&quot;, &quot;root&quot;);

    mysql_select_db(&quot;MyRadContactForm&quot;, $sql_connection);

    // Probably should check to make sure the connection was successful
    // But I'm too lazy...
    $sql = &quot;INSERT INTO MyRadContacts (
                ContactName,
                ContactEmail,
                ContactLeastFavoriteColor,
                ContactDateCreated
            )
            VALUES (
                '$contactName',
                '$contactEmail',
                '$contactLeastFavoriteColor',
                NOW()
            )&quot;;

    mysql_query($sql, $sql_connection);

    mysql_close($sql_connection);
?&gt;
</pre>
<p>This example is lacking in a number of areas, but we aren&#8217;t going to care about SQL Injection or error-checking at this point.</p>
<p>Brief rundown of the above code:</p>
<p><b>Lines 4-6:</b> We are creating three variables to store the values of our incoming form. Note that each item matches the &#8216;name&#8217; attributes of our form inputs.</p>
<p><b>Line 11:</b> This is the equivalent of the <b>USE MyRadContactForm</b> command that we issued earlier to our MySQL server prior to creating our table.<br />
<b>Line 13:</b> This is the beginning of an SQL INSERT statement. Not surprisingly, this command inserts new records into our table. In the first set of parentheses, we specify which table columns that we want to store our data in. The second set of parentheses represent the actual values to store in the table.</p>
<p><b>Lines 20-22:</b> PHP makes life a bit easier for us here, as it will automatically detect our variable names and replace them with the values they contain. NB: The $sql string we&#8217;ve created is surrounded with <b>&#8220;</b> aka double quotes. This is crucial to get this behavior. The variable names are themselves surrounded by <b>&#8216;</b> aka single quotes, as this is standard SQL for indicating that you are working with string values (aka VARCHAR).</p>
<p><b>Line 23:</b> We call the MySQL built-in function <b>NOW()</b> to store the current date/time in ContactDateCreated at the time our insert is performed. There are other ways of handling this (such as declaring a variable in PHP), but this is easy.</p>
<p><b>Line 26:</b> mysql_query does the actual work of sending our INSERT statement to our DB via the $sql_connection we created earlier.</p>
<p>Remember, this is just a primer (and not much of one at that!). Writing code like this will likely draw ire from your peers and pink slips from your employers.</p>
<h3 style="text-decoration: underline;">Creating an HTML Contact Form Submission Viewer</h3>
<p>So, we&#8217;ve got our form, database, table, and server-side PHP script. If all is well, we should now be adding new records to the table with each form submission.</p>
<p>But what good does this data do anyone if it is tucked safely away in the bowels of our MySQL server?</p>
<p>Let&#8217;s make a quick-and-dirty PHP <b>page</b> to display the input values:</p>
<pre class="brush: php; highlight: [12,14,17,19,26]; html-script: true;">
&lt;!DOCTYPE html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;title&gt;My Rad Contacts&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
&lt;?php
    $sql_connection = mysql_connect(&quot;localhost&quot;, &quot;root&quot;, &quot;root&quot;);

    mysql_select_db(&quot;MyRadContactForm&quot;, $sql_connection);

    $result = mysql_query(&quot;SELECT * FROM MyRadContacts&quot;);

    echo &quot;&lt;table&gt;&quot;;
    echo &quot;&lt;tr&gt;&lt;td&gt;Name&lt;/td&gt;&lt;td&gt;Email&lt;/td&gt;&lt;td&gt;Least Favorite Color&lt;/td&gt;&lt;td&gt;Created On&lt;/td&gt;&lt;/tr&gt;&quot;;

    while ($row = mysql_fetch_array($result)) {
        echo &quot;&lt;tr&gt;&quot;;
        echo &quot;&lt;td&gt;&quot; . $row[&quot;ContactName&quot;] . &quot;&lt;/td&gt;&quot;;
        echo &quot;&lt;td&gt;&quot; . $row[&quot;ContactEmail&quot;] . &quot;&lt;/td&gt;&quot;;
        echo &quot;&lt;td&gt;&quot; . $row[&quot;ContactLeastFavoriteColor&quot;] . &quot;&lt;/td&gt;&quot;;
        echo &quot;&lt;td&gt;&quot; . $row[&quot;ContactDateCreated&quot;] . &quot;&lt;/td&gt;&quot;;
        echo &quot;&lt;/tr&gt;&quot;;
    }

    echo &quot;&lt;/table&gt;&quot;;

    mysql_close($sql_connection);
?&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre>
<p><b>Line 12:</b> This time, since we want to display data already in our DB, rather than insert new records, we issue a <b>SELECT</b> statement.  The <b>*</b> (asterisk) tells SQL that we want every column for each row we get back. We store the data we receive in a variable named <b>$result</b>.</p>
<p><b>Line 14:</b> Using PHP&#8217;s <b>echo</b> command, we begin the definition of our HTML table. PHP <b>echo</b>es its argument to the HTML page seen by the end user.</p>
<p><b>Line 17:</b> The keyword <b>while</b> indicates to PHP that we want to start a <b>loop</b>, in which we will output the values stored in each row of our DB. When we reach the last row, the <b>while</b> statement is no longer true, and the loop exits.</p>
<p><b>Line 19:</b> Again, we use echo to get our stuff out on to the HTML page. Here, we are building a table cell (&lt;td&gt;) that contains whatever is stored in the ContactName field for this record. Note that PHP uses a single <b>.</b> (dot) character to stitch strings together. This is often referred to as &#8216;string concatenation.&#8217;</p>
<p><b>Line 26:</b> Finally, we use echo one last time to close our &lt;table&gt; tag.</p>
<p><b>UPDATE</b></p>
<p>By request, I&#8217;ve put together a zip file containing the PHP/HTML source seen above. I haven&#8217;t actually run it to verify its accuracy, so please keep that in mind.</p>
<p><a href="http://brian.dobberteen.com/wp-content/uploads/2011/09/ContactFormDemoSource.zip">ContactFormDemoSource</a></p>
]]></content:encoded>
			<wfw:commentRss>http://brian.dobberteen.com/code/using-php-and-mysql-to-create-a-simple-contact-form-and-results-browser/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
		<item>
		<title>Using Nullable Types to Handle Possible NULL Values From Database</title>
		<link>http://brian.dobberteen.com/code/using-nullable-types-to-handle-possible-null-values-from-database/</link>
		<comments>http://brian.dobberteen.com/code/using-nullable-types-to-handle-possible-null-values-from-database/#comments</comments>
		<pubDate>Tue, 22 Mar 2011 14:43:27 +0000</pubDate>
		<dc:creator>brian</dc:creator>
				<category><![CDATA[Code]]></category>

		<guid isPermaLink="false">http://brian.dobberteen.com/?p=158</guid>
		<description><![CDATA[I&#8217;d like to describe a techinque that I&#8217;ve come up with to handle the ever-present issue of the easiest (best?) way to handle building an object from a database query that may or may not contain NULL values. I feel compelled to post this because I haven&#8217;t seen this approach detailed elsewhere online. First, let&#8217;s [...]]]></description>
				<content:encoded><![CDATA[<p>I&#8217;d like to describe a techinque that I&#8217;ve come up with to handle the ever-present issue of the easiest (best?) way to handle building an object from a database query that may or may not contain NULL values.  I feel compelled to post this because I haven&#8217;t seen this approach detailed elsewhere online.</p>
<p>First, let&#8217;s create a simple class to demonstrate our needs:</p>
<pre class="brush: csharp; highlight: [5,7];">
public class Person {
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int? Age { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime? DateModified { get; set; }
}
</pre>
<p>Note the use of nullable value types on lines 5 and 7 above.  For those not familiar with the concept of nullable types, have a look at: <a href="http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx">Using Nullable Types &#8211; MSDN</a>.</p>
<p>In our class, we are anticipating that there may be NULL values stored for a Person&#8217;s Age and Last Modified Date.</p>
<p>Simple enough.  But how to best build a Person object from a SqlDataReader?  I&#8217;ve seen tons of different approaches, such as:</p>
<pre class="brush: csharp;">
var people = new List&lt;Person&gt;();

using (var dr = cmd.ExecuteReader()) {
    while (dr.Read()) {
        people.Add(new Person {
            Id = (int) dr[&quot;Id&quot;],
            FirstName = dr[&quot;FirstName&quot;].ToString(),
            LastName = dr[&quot;LastName&quot;].ToString(),
            Age = Convert.IsDbNull(dr[&quot;Age&quot;]) ? null : (int?) dr[&quot;Age&quot;],
            DateCreated = (DateTime) dr[&quot;DateCreated&quot;],
            DateModified = Convert.IsDbNull(dr[&quot;DateModified&quot;])
                                                 ? null
                                                 : (DateTime?) dr[&quot;DateModified&quot;]
        });
    }
}
</pre>
<p>This approach certainly isn&#8217;t that bad, and seems to be a very common method for handling NULLs via nullable types.</p>
<p>But we&#8217;re not content with something that&#8217;s only &#8216;not bad,&#8217; are we?  Of course not.</p>
<p>Let&#8217;s try another way:</p>
<pre class="brush: csharp; highlight: [9,11];">
var people = new List&lt;Person&gt;();

using (var dr = cmd.ExecuteReader()) {
    while (dr.Read()) {
        people.Add(new Person {
            Id = (int) dr[&quot;Id&quot;],
            FirstName = dr[&quot;FirstName&quot;].ToString(),
            LastName = dr[&quot;LastName&quot;].ToString(),
            Age = dr[&quot;Age&quot;] as int?,
            DateCreated = (DateTime) dr[&quot;DateCreated&quot;],
            DateModified = dr[&quot;DateModified&quot;] as DateTime?
        });
    }
}
</pre>
<p>Check out lines 9 and 11 &#8211; we are using the &#8216;as&#8217; operator rather than the clunky ternary, resulting in code that, IMHO, is more concise, clear, and therefore easier to read and maintain.</p>
<p>I&#8217;m surprised that I haven&#8217;t seen others doing this&#8230; I know I&#8217;m not the only one to have stumbled across this approach!</p>

]]></content:encoded>
			<wfw:commentRss>http://brian.dobberteen.com/code/using-nullable-types-to-handle-possible-null-values-from-database/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting Value of NEWSEQUENTIALID() on Insert</title>
		<link>http://brian.dobberteen.com/code/getting-value-of-newsequentialid-on-insert/</link>
		<comments>http://brian.dobberteen.com/code/getting-value-of-newsequentialid-on-insert/#comments</comments>
		<pubDate>Fri, 18 Mar 2011 19:23:25 +0000</pubDate>
		<dc:creator>brian</dc:creator>
				<category><![CDATA[Code]]></category>

		<guid isPermaLink="false">http://brian.dobberteen.com/?p=155</guid>
		<description><![CDATA[Recently, I was writing a stored procedure that, at one point, performs an insert into a table that has a GUID (uniqueidentifier) primary key. The default value for this column is set to NEWSEQUENTIALID(). Further along in the stored procedure, I needed the value of this newly-inserted GUID to use in another INSERT statement. Fortunately, [...]]]></description>
				<content:encoded><![CDATA[<p>Recently, I was writing a stored procedure that, at one point, performs an insert into a table that has a GUID (uniqueidentifier) primary key.  The default value for this column is set to NEWSEQUENTIALID().</p>
<p>Further along in the stored procedure, I needed the value of this newly-inserted GUID to use in another INSERT statement.  Fortunately, T-SQL provides us with precisely what we need &#8211; the OUTPUT clause.</p>
<p>A quick demo:</p>
<p>The table DDL:</p>
<pre class="brush: sql; gutter: false;">
CREATE TABLE [dbo].[MyTable] (
	[MyId] [uniqueidentifier] NOT NULL,
	[FirstName] [varchar](50) NULL,
	[LastName] [varchar](50) NULL,
	CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED ([MyId] ASC)
)
GO

ALTER TABLE [dbo].[MyTable] ADD CONSTRAINT [DF_MyTable_MyId] DEFAULT (newsequentialid()) FOR [MyId]
GO
</pre>
<p>Example portion of sproc:</p>
<pre class="brush: sql; highlight: [7,15];">
DECLARE @MyTempTable table (MyTempId uniqueidentifier);

INSERT INTO MyTable (
    FirstName
    , LastName
)
OUTPUT inserted.MyId INTO @MyTempTable
VALUES (
    'Brian'
    , 'Dobberteen'
);

DECLARE @NewlyInsertedId uniqueidentifier;

SELECT @NewlyInsertedId = MyTempId FROM @MyTempTable;
</pre>
<p>Thanks to the bit highlighted above on lines 7 and 15, we now have a reference to the newly inserted GUID and can use it as needed.</p>
<p>Additionally, the use of newsequentialid() here lessens the impact of using a GUID clustered index.</p>

]]></content:encoded>
			<wfw:commentRss>http://brian.dobberteen.com/code/getting-value-of-newsequentialid-on-insert/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Check Existing Values with ASP.NET CustomValidator + jQuery $.ajax()</title>
		<link>http://brian.dobberteen.com/code/jquery_ajax_custom_validator/</link>
		<comments>http://brian.dobberteen.com/code/jquery_ajax_custom_validator/#comments</comments>
		<pubDate>Sat, 06 Mar 2010 17:28:58 +0000</pubDate>
		<dc:creator>brian</dc:creator>
				<category><![CDATA[Code]]></category>

		<guid isPermaLink="false">http://brian.dobberteen.com/?p=146</guid>
		<description><![CDATA[This was selected as an ASP.NET Article of the Day for June 18, 2010 &#8216;SjAJ&#8217; ASP.NET CustomValidator SjAJ?! Sorry, I couldn&#8217;t resist. I had started with AJAX, but thinking now&#8230; hmmm, the method being described here is Synchronous jQuery And JSON. Something tells me that SjAJ is not going to make it to buzzword status. Oh [...]]]></description>
				<content:encoded><![CDATA[<p>
<p style="padding: 2px; border: 1px solid #000; background-color: #fff; margin-top: 10px; margin-bottom: -15px;">This was selected as an <a href="http://www.asp.net">ASP.NET</a> Article of the Day for June 18, 2010</p>
<h2><span style="text-decoration: underline;">&#8216;SjAJ&#8217; ASP.NET CustomValidator</span></h2>
<p>SjAJ?! Sorry, I couldn&#8217;t resist. I had started with AJAX, but thinking now&#8230; hmmm, the method being described here is Synchronous jQuery And JSON.</p>
<p>Something tells me that SjAJ is not going to make it to buzzword status. Oh well, I tried.</p>
<p>We will try to quickly outline a method for using the ASP.NET CustomValidator control in conjunction with jQuery and the AJAX Control Toolkit.</p>
<p>Initially, I had tried to use other APIs to call my web services and/or page methods. Problem was, at least that I could tell, was that the asynchronous nature of these operations cause an issue inside the ClientValidationFunction specified in the CustomValidator control.  Eventually, I revisted the code in my earlier posts, and once again, jQuery came to the rescue! Details follow.</p>
<h3><span style="text-decoration: underline;">ASP.NET CustomValidator Control</span></h3>
<p>For those not familiar with the CustomValidator control, let me give a brief explanation.</p>
<pre class="brush: xml; gutter: false;">
&lt;asp:CustomValidator runat=&quot;server&quot; ID=&quot;UserNameExistsValidator&quot;
    OnServerValidate=&quot;UserNameExistsValidator_ServerValidate&quot;
    ControlToValidate=&quot;UserNameTextBox&quot;
    ClientValidationFunction=&quot;doesUserExist&quot; /&gt;
</pre>
<p>The bit we&#8217;re most concerned with here is the ClientValidationFunction. This will fire during client-side page validation, receiving two arguments.</p>
<pre class="brush: jscript; gutter: false;">
function doesUserExist(source, arguments) { }
</pre>
<p><strong>source</strong> contains the &lt;span&gt; element rendered for the validation control. Since we are going to use the ASP.NET Ajax Control Toolkit&#8217;s ValidatorCalloutExtender we will ignore the argument <strong>source</strong>.</p>
<p><strong>arguments</strong> is much more interesting here, as it contains two properties: <strong>IsValid</strong> and <strong>Value</strong></p>
<p>As you might expect, <strong>Value</strong> contains the value contained in the ControlToValidate that we&#8217;ve specified in our validator control. <strong>IsValid</strong> is what we&#8217;ll use to indicate whether or not the value we&#8217;re checking exists or not.</p>
<p>Here&#8217;s a simple, albeit very contrived, example of how the ClientValidationFunction works:</p>
<pre class="brush: xml;">
&lt;asp:CustomValidator runat=&quot;server&quot; ID=&quot;ZipCodeCustomValidator&quot;
    ControlToValidate=&quot;ZipCodeTextBox&quot;
    ClientValidationFunction=&quot;isValidZipCode&quot; /&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
    function isValidZipCode(source, arguments) {
        var zipCode = arguments.Value;
        var zipCodeValid = /^\d{5}(-\d{4})$/.test(zipCode);

        arguments.IsValid = zipCodeValid;
    }
&lt;/script&gt;
</pre>
<p>Again, very contrived, and quite silly, actually &#8211; we would be much better off using a RegularExpressionValidator for this particular case&#8230; but I digress. </p>
<p>Briefly, this CustomValidator uses client-side code to test the value entered in a text box (ZipCodeTextBox in this case) against the regex <b>/^\d{5}(-\d{4})?$/</b> which will allow values such as 95060 or 95060-1234 but not 950-0000 nor 95064-0.</p>
<h3><span style="text-decoration: underline;">Checking for An Existing Value</span></h3>
<p>As mentioned earlier, I was having trouble getting things to work using a few asynchronous techniques. It seemed that if <strong>arguments.IsValid</strong> is set inside a callback function, it doesn&#8217;t register properly, and the control always appears valid.</p>
<p>Luckily, jQuery&#8217;s <strong>$.ajax()</strong> function has a handy option: <strong>async</strong>, which when set to <strong>false</strong> does what we need &#8211; it waits for the response from the server before continuing to our <strong>success</strong> function.  Without further ado&#8230;</p>
<pre class="brush: jscript; highlight: [6,9,14];">
function doesUsernameExist(source, arguments) {
    var exists;
    $.ajax({
        type: &quot;POST&quot;,
        contentType: &quot;application/json; charset=utf-8&quot;,
        url: &quot;Default.aspx/DoesUserExist&quot;,
        data: &quot;{'username': '&quot; + arguments.Value + &quot;'}&quot;,
        dataType: &quot;json&quot;,
        async: false,
        success: function(result) {
            exists = result.d;
        }
    });
    arguments.IsValid = !exists;
}
</pre>
<p>In line 6, we specify the name of our PageMethod contained inside our Default.aspx page. This is only one of many ways to accomplish this, of course. See <a href="http://brian.dobberteen.com/code/responding-to-jquery-ajax-request-with-php/">http://brian.dobberteen.com/code/responding-to-jquery-ajax-request-with-php/</a> for my treatment of using PHP as a &#8216;web service&#8217; of sorts.</p>
<p>Line 9 is the all-important <b>async: false</b> that seems to provide the needed magic to get this all working.</p>
<p>Finally, on line 14, we set our CustomValidator&#8217;s IsValid property to true only if the value we are checking for did not exist.</p>
<p>To make things easy, let&#8217;s use the ASP.NET membership system to check for an existing username. This has the benefit of providing the method for both server and client side validation.  Here goes:</p>
<pre class="brush: csharp; highlight: [13];">
using System;
using System.Web.Security;
using System.Web.Services;
using System.Web.UI;

public partial class _Default : Page 
{
    protected void Page_Load(object sender, EventArgs e) { }

    [WebMethod]
    public static bool DoesUserExist(string username)
    {
        return Membership.GetUser(username) != null;
    }

    protected void UserNameExistsValidator_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = !DoesUserExist(args.Value);
    }
}
</pre>
<p>The logic here is very simple. On line 13, we use the ASP.NET Membership system to check for an existing username. This logic also serves us well for our OnServerValidate event handler, starting on line 16.</p>
<p>The .aspx page:</p>
<pre class="brush: jscript; html-script: true;">
&lt;%@ Page Language=&quot;C#&quot; AutoEventWireup=&quot;true&quot;  CodeFile=&quot;Default.aspx.cs&quot; Inherits=&quot;_Default&quot; %&gt;

&lt;%@ Register Assembly=&quot;AjaxControlToolkit&quot; Namespace=&quot;AjaxControlToolkit&quot; TagPrefix=&quot;cc1&quot; %&gt;

&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;

&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
&lt;head runat=&quot;server&quot;&gt;
    &lt;title&gt;Check Existing Usernames&lt;/title&gt;
    &lt;style type=&quot;text/css&quot;&gt;
        .invalid {
            border: solid 1px #ff0000;
            background-color: #ffcccc;
        }
    &lt;/style&gt;
    &lt;script type=&quot;text/javascript&quot; src=&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;&gt;
    &lt;/script&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;
        function doesUsernameExist(source, arguments) {
            var exists;
            $.ajax({
                type: &quot;POST&quot;,
                contentType: &quot;application/json; charset=utf-8&quot;,
                url: &quot;Default.aspx/DoesUserExist&quot;,
                data: &quot;{'username': '&quot; + arguments.Value + &quot;'}&quot;,
                dataType: &quot;json&quot;,
                async: false,
                success: function(result) {
                    exists = result.d;
                }
            });
            arguments.IsValid = !exists;
        }
    &lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;form id=&quot;form1&quot; runat=&quot;server&quot;&gt;
    &lt;asp:ScriptManager runat=&quot;server&quot; ID=&quot;sm1&quot; /&gt;
    &lt;div&gt;
        Username:
        &lt;asp:TextBox runat=&quot;server&quot; ID=&quot;UserNameTextBox&quot; CausesValidation=&quot;true&quot; /&gt;
        &lt;asp:Button runat=&quot;server&quot; ID=&quot;ClientSubmitButton&quot; Text=&quot;Check Username Client Side&quot;
            OnClientClick=&quot;Page_ClientValidate(); return false;&quot; /&gt;
        &lt;asp:Button runat=&quot;server&quot; ID=&quot;ServerSubmitButton&quot; Text=&quot;Check Username Server Side&quot;
            OnClientClick=&quot;ValidatorEnable(UserNameExistsValidator, false);&quot; /&gt;
    &lt;/div&gt;
    &lt;asp:CustomValidator runat=&quot;server&quot;
        ID=&quot;UserNameExistsValidator&quot;
        ControlToValidate=&quot;UserNameTextBox&quot;
        ClientValidationFunction=&quot;doesUsernameExist&quot;
        OnServerValidate=&quot;UserNameExistsValidator_ServerValidate&quot;
        Display=&quot;None&quot;
        ErrorMessage=&quot;Username Already Exists&quot; /&gt;
    &lt;cc1:ValidatorCalloutExtender runat=&quot;server&quot;
        ID=&quot;UserNameExistsValidator_CalloutExtender&quot;
        TargetControlID=&quot;UserNameExistsValidator&quot;
        HighlightCssClass=&quot;invalid&quot;
        PopupPosition=&quot;BottomLeft&quot; /&gt;
    &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>And finally, a screenshot of what the validator looks like when I enter &#8216;bdobberteen&#8217; for the username &#8211; an account I created minutes earlier:</p>
<p><a href="http://brian.dobberteen.com/wp-content/uploads/2010/03/UserNameExistsValidator.jpg"><img src="http://brian.dobberteen.com/wp-content/uploads/2010/03/UserNameExistsValidator.jpg" alt="" title="UserNameExistsValidator" width="672" height="326" class="aligncenter size-full wp-image-152" /></a></p>
<p>I am not sure if this degrades gracefully in the face of a non-javascript browser. Namely, the ValidatorCalloutExtender won&#8217;t display. A possible solution would be to add a ValidationSummary control, initially set its visibility to false, and, upon postback, if the server-side validation fails (<b>!Page.IsValid</b>), set that same ValidationSummary to visible, allowing downstream browsers to view the various error message(s).</p>
<p>Hope this helps someone!</p>
<p>- brian -</p>
<p><a href='http://brian.dobberteen.com/wp-content/uploads/2010/03/CustomValidatorJquerySample.zip' >Sample Code for Article</a></p>

]]></content:encoded>
			<wfw:commentRss>http://brian.dobberteen.com/code/jquery_ajax_custom_validator/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Calling a Web Service with ASP.NET AJAX Client Script</title>
		<link>http://brian.dobberteen.com/code/calling-a-web-service-with-asp-net-ajax-client-script/</link>
		<comments>http://brian.dobberteen.com/code/calling-a-web-service-with-asp-net-ajax-client-script/#comments</comments>
		<pubDate>Sat, 17 Oct 2009 21:46:58 +0000</pubDate>
		<dc:creator>brian</dc:creator>
				<category><![CDATA[Code]]></category>

		<guid isPermaLink="false">http://brian.dobberteen.com/?p=117</guid>
		<description><![CDATA[Wow! It&#8217;s been waaaaay too long since my last installment &#8211; been busy with latest programming contract, not that you care. Since beating the proverbial dead horse is my specialty, this brief post is going to cover making a call to the Yahoo! Maps API via an ASP.NET web service (.asmx) which we then call [...]]]></description>
				<content:encoded><![CDATA[<p>Wow! It&#8217;s been waaaaay too long since my last installment &#8211; been busy with latest programming contract, not that you care.</p>
<p>Since beating the proverbial dead horse is my specialty, this brief post is going to cover making a call to the Yahoo! Maps API via an ASP.NET web service (.asmx) which we then call from client script with the aid of the Microsoft ASP.NET AJAX library(ies).</p>
<p>In order to access the necessary JavaScript script libraries, we must first include the customary ScriptManager object in our page:</p>
<pre class="brush: xml; gutter: false;">
&lt;asp:ScriptManager runat=&quot;server&quot; ID=&quot;sm1&quot;&gt;
    &lt;Services&gt;
        &lt;asp:ServiceReference Path=&quot;~/ZipCodeService.asmx&quot; /&gt;
    &lt;/Services&gt;
&lt;/asp:ScriptManager&gt;
</pre>
<p>As you may have already guessed, this declaration creates a ScriptManager for our page and includes a reference to the web service (which we will create momentarily) used for fetching the City and State upon user input of a US Zip Code.</p>
<p>Without further ado, here&#8217;s the complete web service code:</p>
<pre class="brush: csharp;">
using System.Linq;
using System.Web.Script.Services;
using System.Web.Services;
using System.Xml.Linq;

namespace YahooMapsZipCodeLookup
{
    [WebService(Namespace = &quot;http://tempuri.org/&quot;)]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class ZipCodeService : System.Web.Services.WebService
    {
        private static readonly string MAP_URL = &quot;http://local.yahooapis.com/MapsService/V1/geocode?appid=&quot;;
        private static readonly string MAP_APP_ID = &quot;&lt;YOUR ID HERE&gt;&quot;;

        [WebMethod]
        public CityState GetCityStateByZip(string zipCode)
        {
            XDocument xdoc = XDocument.Load(MAP_URL + MAP_APP_ID + &quot;&amp;zip=&quot; + zipCode);

            var state = root.Descendants().Where(el =&gt; el.Name.LocalName == &quot;City&quot;).Single().Value;
            var city = root.Descendants().Where(el =&gt; el.Name.LocalName == &quot;State&quot;).Single().Value;

            return new CityState { City = city; State = state; };
        }
    }
    public class CityState
    {
        public string City { get; set; }
        public string State { get; set; }
    }
}
</pre>
<p>After our ScriptManager registers this service, we now have access to proxy(ies) that can be called from the client side.  To do so, we can create a wrapper to the service call:</p>
<pre class="brush: jscript; gutter: false; highlight: [4,5];">
function getCityStateByZip(zip) {
    YahooMapsZipCodeLookup.ZipCodeService.GetCityStateByZip(
                    zip,
                    onZipLookupSuccess,
                    onZipLookupError,
                    &quot;&lt;%= DateTime.Now %&gt;&quot;  // Passing as the context
         );
}
</pre>
<p>It&#8217;s not as simple as just including the above call &#8211; we need to provide the methods named in the second and third parameters (the two lines highlighted in green above).  Which would look something like:</p>
<pre class="brush: jscript; gutter: false;">
function getCityStateByZip(zip) {
    YahooMapsZipCodeLookup.ZipCodeService.GetCityStateByZip(
                    zip,
                    onZipLookupSuccess,
                    onZipLookupError,
                    &quot;&lt;%= DateTime.Now %&gt;&quot;  // Passing as the context
         );
}
function onZipLookupSuccess(result, context, methodName) {
    // Note how we can access the properties of the returned CityState object
    // The ScriptManager takes care of all of this for us!
    $get(&quot;CityStateResult&quot;).innerHTML = result.City + &quot;, &quot; + result.State;
}
function onZipLookupError(error, context, methodName) {
    // The error object's most interesting method is probably get_message(), which
    // will, in this case, return the message of any ASP.NET exceptions that may
    // have occured on the server side webservice.
    $get(&quot;CityStateResult&quot;).innerHTML = &quot;Error: &quot; + error.get_message();
}
</pre>
<p>Though we aren&#8217;t making any use of the context and methodName parameters being passed to our callback functions, I&#8217;ll just point out that the context is whatever was set when calling the webservice &#8211; in this case, the date and time were used.  The context can be very useful to track asynchronous calls in a stateless environment.</p>
<p>The methodName, cleverly enough, returns the name of the web service method that we&#8217;ve called &#8211; in this case, methodName contains <b>GetCityStateByZip</b> which, as we all know, is the name of the only method exposed by our YahooMapsZipCodeLookup.ZipCodeService.</p>
<p>There is another option to writing explicit callback methods, and one that I prefer (probably due to my experience with jQuery). If we don&#8217;t want to write explicit methods, we can use anonymous functions as parameters in the call to our web service:</p>
<pre class="brush: jscript; first-line: 21; highlight: [24,30];">
function getCityStateByZip(zip) {
    YahooMapsZipCodeLookup.ZipCodeService.GetCityStateByZip(
                zip,
                function(result, context, methodName) {
                    $get(&quot;CityStateResult&quot;).innerHTML =
                            result.City + &quot;, &quot; + result.State + &quot;&lt;br /&gt;&quot;
                          + &quot;context: &quot; + context + &quot;&lt;br /&gt;&quot;
                          + &quot;methodName: &quot; + methodName;
                },
                function(error, context, methodName) {
                    $get(&quot;CityStateResult&quot;).innerHTML =
                        &quot;error: &quot; + error.get_message();
                },
                &quot;&lt;%= DateTime.Now %&gt;&quot;  // Passing as the context
        );
}
</pre>
<p>The two highlighted lines indicate where we&#8217;ve replace the names of functions with anonymous functions.  NB: the line numbers in the above snippet are supposed to correspond with the actual aspx page.</p>
<p>To hook everything up on our actual page, we need to add an event handler to, in this case, a textbox:</p>
<pre class="brush: xml; first-line: 16;">
&lt;input type=&quot;text&quot; onchange=&quot;getCityStateByZip(this.value);&quot; /&gt;
&lt;input type=&quot;submit&quot; value=&quot;Get City and State&quot; onclick=&quot;return false;&quot; /&gt;
&lt;div id=&quot;CityStateResult&quot;&gt;&lt;/div&gt;
</pre>
<p>I also snuck in the CityStateResult div that is the target of our DOM manipulation upon receipt of a response from the web service. I also added a do-nothing submit button to demonstrate that a button press will fire the textbox&#8217;s onchange event.</p>
<p>The entire aspx page:</p>
<pre class="brush: xml;">
&lt;%@ Page Language=&quot;C#&quot; %&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; 
 &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; &gt;
&lt;head runat=&quot;server&quot;&gt;
    &lt;title&gt;Calling a Web Service from ASP.NET AJAX Client Script&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;form id=&quot;form1&quot; runat=&quot;server&quot;&gt;
    &lt;div&gt;
    &lt;asp:ScriptManager runat=&quot;server&quot; ID=&quot;sm1&quot;&gt;
        &lt;Services&gt;
            &lt;asp:ServiceReference Path=&quot;~/ZipCodeService.asmx&quot; /&gt;
        &lt;/Services&gt;
    &lt;/asp:ScriptManager&gt;
    &lt;input type=&quot;text&quot; name=&quot;ziptxt&quot; id=&quot;ziptxt&quot; onchange=&quot;getCityState(this.value);&quot; /&gt;
    &lt;input type=&quot;submit&quot; value=&quot;Get City and State&quot; onclick=&quot;return false;&quot; /&gt;
    &lt;div id=&quot;cityStateResult&quot;&gt;&lt;/div&gt;
    &lt;/div&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;
        function getCityState(zip) {
            var citystate =
                YahooMapsZipCodeLookup.ZipCodeService.GetCityStateByZip(
                    zip,
                    function(result, context, methodName) {
                        $get(&quot;cityStateResult&quot;).innerHTML = 
                            result.City + &quot;, &quot; + result.State + &quot;&lt;br /&gt;&quot;
                         + &quot;context: &quot; + context + &quot;&lt;br /&gt;&quot;
                         + &quot;method name: &quot; + methodName;
                    },
                    function(error, context, methodName) {
                        $get(&quot;cityStateResult&quot;).innerHTML =
                            &quot;error: &quot; + error.get_message();
                    },
                    &quot;&lt;%= DateTime.Now %&gt;&quot;  // Passing as the context
                 );
        }
    &lt;/script&gt;
    &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>In a nutshell, when the user triggers the onchange event of our textbox, the event is handled by our wrapper function <b>getCityStateByZip(zip)</b>, to which we pass <b>this.value</b>, which contains the changed value of the textbox. This value is then passed to the web service, which returns a CityState object &#8211; ASP.NET AJAX handles all of the serialization and other such details for us in a nearly transparent way.  We can refer to the <b>CityState</b> object returned by our web service as if the object was a normal .NET object, i.e. <b>result.City</b> or <b>result.State</b>.</p>
<p>And I think that covers it!  No more posts on zip code lookups, I promise!</p>
<p>Before I forget, here is the source to the samples seen above: <a href="http://brian.dobberteen.com/wp-content/uploads/2009/10/YahooMapsZipCodeLookup.zip">Calling a Web Service with ASP.NET AJAX Client Script Source Code</a><br />
</p>
]]></content:encoded>
			<wfw:commentRss>http://brian.dobberteen.com/code/calling-a-web-service-with-asp-net-ajax-client-script/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Using LINQ to XML instead of XmlReader</title>
		<link>http://brian.dobberteen.com/code/using-linq-to-xml-instead-of-xmlreader/</link>
		<comments>http://brian.dobberteen.com/code/using-linq-to-xml-instead-of-xmlreader/#comments</comments>
		<pubDate>Fri, 10 Jul 2009 16:04:35 +0000</pubDate>
		<dc:creator>brian</dc:creator>
				<category><![CDATA[Code]]></category>

		<guid isPermaLink="false">http://brian.dobberteen.com/?p=87</guid>
		<description><![CDATA[Previously, I mentioned that I wasn&#8217;t sure if using an XmlReader was the best way to fetch the City and State values from the XML response from the Yahoo Maps API: Using reader As XmlReader = XmlReader.Create(MAP_URL &#38; MAP_APP_ID &#38; &#34;&#38;zip=&#34; &#38; zip) While reader.Read If reader.Name = &#34;City&#34; And reader.IsStartElement Then ret.City = reader.ReadElementString(&#34;City&#34;) [...]]]></description>
				<content:encoded><![CDATA[<p>Previously, I mentioned that I wasn&#8217;t sure if using an XmlReader was the best way to fetch the City and State values from the XML response from the Yahoo Maps API:</p>
<pre class="brush: vb;">
Using reader As XmlReader = XmlReader.Create(MAP_URL &amp; MAP_APP_ID &amp; &quot;&amp;zip=&quot; &amp; zip)
  While reader.Read
    If reader.Name = &quot;City&quot; And reader.IsStartElement Then
      ret.City = reader.ReadElementString(&quot;City&quot;)
    End If

    If reader.Name = &quot;State&quot; And reader.IsStartElement Then
      ret.State = reader.ReadElementString(&quot;State&quot;)
    End If
  End While
End Using
</pre>
<p>We were using the above to basically read the XML response line-by-line, checking for the two elements we are interested in, and storing their values in our simple CityState object &#8216;ret.&#8217; Again, the XML we are processing looks like:</p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; ?&gt; 
&lt;ResultSet -xmlns omitted for clarity-&gt;
  &lt;Result precision=&quot;zip&quot;&gt;
    &lt;Latitude&gt;36.993591&lt;/Latitude&gt; 
    &lt;Longitude&gt;-122.060199&lt;/Longitude&gt; 
    &lt;Address /&gt; 
    &lt;City&gt;Santa Cruz&lt;/City&gt; 
    &lt;State&gt;CA&lt;/State&gt; 
    &lt;Zip&gt;95064&lt;/Zip&gt; 
    &lt;Country&gt;US&lt;/Country&gt; 
  &lt;/Result&gt;
&lt;/ResultSet&gt;
&lt;!--  ws05.ydn.gq1.yahoo.com compressed/chunked Thu Jul  9 14:54:33 PDT 2009 --&gt;
</pre>
<p>Though our XmlReader method works fine, it seemed a bit clunky to me, so I set out to check out LINQ to XML to see if we can clean the code up a little bit.</p>
<p>LINQ is still somewhat of a new concept for me, as I haven&#8217;t had much chance to work with it given the nature of much of the work I do. Its potential usefulness, however, seems pretty clear to me, and definitely look forward to working with it as much as possible &#8211; at least until the next latest, greatest thing comes along! I&#8217;ve always felt the LINQ syntax to be a bit unusual, and &#8211; unlike I&#8217;d first hoped &#8211; not that close to SQL. Of course, LINQ <i>isn&#8217;t</i> SQL, so I suppose I shouldn&#8217;t be surprised that LINQ doesn&#8217;t look more like:</p>
<pre class="brush: sql; light: true;">SELECT element FROM elements WHERE element.name = 'City'</pre>
<p>Of course, this is an incredibly trivial example, and the only difference between a similar LINQ query is the arrangement of the three components of the query (SELECT, FROM, and WHERE). But in reading that I&#8217;ve done, LINQ can get pretty cryptic at times&#8230; though I used to feel the same way about complex SQL, which now is very easy for me to comprehend.</p>
<p>At any rate, we&#8217;ll be dropping our use of the XmlReader class and instead opt for a LINQ-to-XML XDocument object. We need to change our Imports declaration slightly, removing <b>System.Xml</b> and replacing it with <b>System.Xml.Linq</b>.  Much the same as we did with the XmlReader, we use XDocument&#8217;s static function <b>Load</b> to grab our XML from the Yahoo Maps API (<a href="http://brian.dobberteen.com/using-a-pagemethod-to-look-up-city-and-state-based-on-zip-code/">more about accessing the Yahoo Maps API</a>).</p>
<pre class="brush: vb; light: true;">Dim xdoc As XDocument = XDocument.Load(MAP_URL &amp; MAP_APP_ID &amp; &quot;&amp;zip&quot; = &amp; zip)</pre>
<p>Just like our earlier examples, this is contained within a PageMethod that accepts &#8216;zip&#8217; as its only parameter and returns a simple CityState object. After the XDocument is loaded, we can now perform a LINQ query on it, allowing for us to easily specify what elements (City and State, in this case) we&#8217;d like the value of.</p>
<pre class="brush: vb;">
Dim city = (From el in xdoc.Descendants _
              Where el.Name.LocalName = &quot;City&quot; _
              Select el.Value).Single
</pre>
<p>Because we&#8217;re interested in the City and State elements, which are descendants of the root &#8216;ResultSet&#8217;, we&#8217;re using the cleverly named property Descendants of our XDocument object. Descendants is an IEnumerable collection of XElement objects which is what makes our LINQ operations possible. As you can see, the LINQ query first specifies where to look for something (akin to the FROM clause in an SQL SELECT statement), then we set the criteria to be sure we find the &#8216;City&#8217; element. I discovered that <b>el.Name</b> won&#8217;t work for us, as the <b>Name</b> property of an XElement object is an XName object. The LocalName property of an XElement refers to the elements unqualified name, without any namespace info included. The LINQ statement next &#8216;Selects&#8217; the element matching our criteria. Finally, since we are only expecting a single city to exist in our XML response, we wrap the whole LINQ query in parentheses and use <b>.Single</b> to return the one-and-only value we&#8217;re after. <b>.Single</b> will throw an exception if more than one element was found by our query. To get the value of the State element, just replace <b>Where el.Name.LocalName = &#8220;City&#8221;</b> to <b>Where el.Name.LocalName = &#8220;State&#8221;</b>.</p>
<p>I&#8217;ve experimented with polling both the City and State elements in one pass, i.e.</p>
<pre class="brush: vb; light: true;">Where el.Name.LocalName = &quot;City&quot; Or el.Name.LocalName = &quot;State&quot;</pre>
<p>But this just seemse to necessitate another query to be sure that we&#8217;re getting the right values from our new, albeit smaller, collection of XElements. So, for now, we&#8217;ll just perform two seperate LINQ operations&#8230; please let me know if there are better ways of going about this (and I&#8217;m sure that there are!)</p>
<p>Finally, let&#8217;s take a quick look at using a Lambda expression to streamline this whole thing a bit more. The following gives us the same result as the first LINQ query above:</p>
<pre class="brush: vb; gutter: false;">
Dim city = xdoc.Descendants.Where(Function(el) el.Name.LocalName = &quot;City&quot;).Single.Value
</pre>
<p>The call to <b>.Where</b> from our <b>xdoc.Descendants</b> is a call to an &#8216;extension method.&#8217; These extension methods are central to the functionality of LINQ. In this case, we&#8217;re passing an &#8216;anonymous function&#8217; to the Where extension method that we will be using to apply our criteria. The anonymous function is passed <b>el</b> which is an XElement object. And again, we want an element with a LocalName of City, so the body of our anonymous function does just this, compares the LocalName to &#8216;City&#8217;, and if it matches, the expression continues by fetching the Single city element&#8217;s Value.</p>
<p>Clearly, we&#8217;ve only just scratched the surface of LINQ and LINQ to XML, but we gotta start somewhere, no?<br />
</p>
]]></content:encoded>
			<wfw:commentRss>http://brian.dobberteen.com/code/using-linq-to-xml-instead-of-xmlreader/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Responding to jQuery AJAX Request with PHP</title>
		<link>http://brian.dobberteen.com/code/responding-to-jquery-ajax-request-with-php/</link>
		<comments>http://brian.dobberteen.com/code/responding-to-jquery-ajax-request-with-php/#comments</comments>
		<pubDate>Thu, 09 Jul 2009 19:46:15 +0000</pubDate>
		<dc:creator>brian</dc:creator>
				<category><![CDATA[Code]]></category>

		<guid isPermaLink="false">http://brian.dobberteen.com/?p=60</guid>
		<description><![CDATA[I will start by saying that my experience with PHP is somewhat limited, so this is more of an exercise for my benefit. I&#8217;d like to take ASP.NET out of the formula for a bit here, and instead resort to a simple PHP page to answer AJAX requests from jQuery. Earlier, we used ASP.NET PageMethods, [...]]]></description>
				<content:encoded><![CDATA[<p>I will start by saying that my experience with PHP is somewhat limited, so this is more of an exercise for my benefit. I&#8217;d like to take ASP.NET out of the formula for a bit here, and instead resort to a simple PHP page to answer AJAX requests from jQuery.</p>
<p>Earlier, we used ASP.NET PageMethods, but let&#8217;s see a possible PHP solution.</p>
<p>Again, we&#8217;ll just be performing the trivial task of retrieving a city/state location based on a zip code entered on our form.</p>
<pre class="brush: xml;">
...
&lt;form id=&quot;form1&quot;&gt;
  &lt;input type=&quot;text&quot; name=&quot;ZipCodeTextBox&quot; id=&quot;ZipCodeTextBox&quot; /&gt;
&lt;/form&gt;
...
</pre>
<p>Since we&#8217;ll use jQuery to bind this textbox to the onchange event, there are no additional attributes needed in our markup here.</p>
<pre class="brush: jscript; highlight: [2]; html-script: false;">
&lt;script type=&quot;text/javascript&quot;&gt;
$(function() {
});
&lt;/script&gt;
</pre>
<p>A quick note on jQuery for those new to it: in line 2 above, the rather terse statement <b>$(function()</b> is shorthand for &#8220;wait until the page&#8217;s document object model (DOM) is loaded so that we can bind event handlers, set CSS properties, etc. to page elements.&#8221;  The DOM loads before the images on a page are done downloading, so this allows for our jQuery to work as soon as it is able to. <b>$</b> is essentially shorthand for jQuery itself and is central to its operation. Wrapping an element in <b>$()</b> bestows upon that element with all the power of jQuery, allowing for extensive manipulation through chaining of functions.</p>
<p>jQuery also allows for us to create new DOM elements by using the syntax:</p>
<pre class="brush: jscript; light: true;">$(&quot;&lt;div id='div1'&gt;&lt;/div&gt;&quot;)</pre>
<p>In this example we have created a div with an id attribute of &#8217;1&#8242;. Even though this element now &#8220;exists,&#8221; it is not actually <i>in</i> the DOM. Rather than include an <b>&lt;input&gt;</b> in our XHTML, let&#8217;s instead create it with jQuery. With chaining, we can handle not only the creation, but the binding of the onchange event, some simple CSS styling, and finally, the insertion of the new element into the page.</p>
<p>Because ASP.NET is pretty specific about a PageMethod can respond to a client-side reqest, we used the <b>$.ajax()</b> function in our earlier example, as it allows for the most granular approach to sending an AJAX request. But now, since we are going to build a simple PHP script to respond to a GET request, there is a very handy jQuery function, namely <b>$.getJSON()</b>:</p>
<pre class="brush: jscript; highlight: [2,5,6];">
$(function() {
  $(&quot;&lt;input type='text' id='ZipCodeTextBox' name='ZipCodeTextBox' /&gt;&quot;)
    .bind('change', function(event) {
      if (/^\d{5}(-\d{4})?$/.test($(this).valI())) {
        $.getJSON(&quot;ZipCodeService.php&quot;, {zip: $(this).val()}, function(msg) {
          $(&quot;&lt;label /&gt;&quot;).text(msg.City + &quot;, &quot; + msg.State).appendTo(&quot;#form1&quot;);
        });
      }
    })
    .appendTo(&quot;#form1&quot;);
});
</pre>
<p>Lines 2 and 6 demonstrate jQuery&#8217;s ability to generate new DOM elements on the fly &#8211; in this case a new textbox and a new label &#8211; and perform various operations on them, including inserting them into the page. Here we use <b>appendTo()</b> to place our new elements after the last child element of what we&#8217;ve selected, in this case <b>#form1</b>.</p>
<p>Line 5 is the call to $.getJSON, whose signature looks like:</p>
<pre class="brush: jscript; light: true;">$.getJSON(url, parameters, callback)</pre>
<p>In our example, we use ZipCodeService.php as our URL, which refers to the script we&#8217;re about to create that will reside in the same location as our XHTML file. For parameters, I chose to create a simple object using JSON notation, <b>{zip: $(this).val()}</b>, which will be turned into proper query string parameters by jQuery. We could also have set our parameters as they would appear in a query string, i.e. <b>&#8220;zip=&#8221; + $(this).val()</b> &#8211; in this simple GET request, this is a pretty trivial point, but if you were working with a more complicated javascript object, it would be a lot easier to simply pass it as a whole rather than trying to manually serialize it. Finally, the callback parameter to $.getJSON() is the name of a function that will fire following completion of the AJAX request &#8211; it features two parameters, the first containing the javascript object returned and the second the status of the request. We are going to ignore the status parameter, so our anonymous callback function looks like:</p>
<pre class="brush: jscript; light: true;">function(msg) { $(&quot;&lt;label /&gt;&quot;).text(msg.City + &quot;, &quot; + msg.State).appendTo(&quot;#form1&quot;); }</pre>
<p>Doesn&#8217;t get much easier! All we had to do was return a JSON encoded object from our PHP function and in two lines of javascript, we have direct access to the City and State properties that we requested.</p>
<p>Now, let&#8217;s check out ZipCodeService.php &#8211; please note: this is my first foray into the world of PHP and XML, so if I&#8217;ve badly butchered anything, please let me know!</p>
<pre class="brush: php; highlight: [28,34];">
&lt;?php
// Check to make sure 'zip' was sent in the GET request
if (!empty($_GET[&quot;zip&quot;])) {

  // Set a couple of constants
  define(&quot;MAP_URL&quot;, &quot;http://local.yahooapis.com/MapsService/V1/geocode?appid=&quot;);
  define(&quot;MAP_APP_ID&quot;, &quot;&lt;YOUR APP ID&gt;&quot;);

  // Retrieve the query string parameter 'zip' and store it in $zip
  $zip = $_GET[&quot;zip&quot;];
  
  // Run *another* Regular Expression test on the input
  if (preg_match(&quot;/^\d{5}(-\d{4})?$/&quot;, $zip)) {

    // Use simplexml_load_file to grab our XML response from Yahoo
    // This works much the same as when we loaded the XML in our ASP.NET
    $xml = @simplexml_load_file(MAP_URL . MAP_APP_ID . &quot;&amp;zip=&quot; . $zip);

    // Make sure that our request actually succeeded!
    if ($xml)
    
      // Because the Yahoo Maps API will give some funky responses to some
      // strings that *look* like US zip codes but are somehow classified as foreign
      // we are going to check that the zipcode is indeed a US postal code and that
      // the Zip element is set in the response - something which is absent on the
      // postal codes deemed to be located outside the US by Yahoo Maps
      if (!empty($xml-&gt;Result-&gt;Zip) &amp;&amp; $xml-&gt;Result-&gt;Country == &quot;US&quot;)
        $ret = array('City' =&gt; (string)$xml-&gt;Result-&gt;City, 'State' =&gt; (string)$xml-&gt;Result-&gt;State);
      else
        return false;
    else
      return false;


  echo json_encode($ret);
}
	} 
?&gt;
</pre>
<p>On line 28, we are using <b>array()</b> to construct a new associative array (aka hash) with the keys &#8216;City&#8217; and &#8216;State&#8217; (big surprise, right?!) and their respective values. I found that our simplexml object exhibits some interesting behavior when it comes to casting. It seems that it is smart enough to know to cast to a string automatically when used in some scenarios, such as in a comparison:</p>
<pre class="brush: php; light: true;">if ($xml-&gt;Result-&gt;City == &quot;Anytown&quot;)</pre>
<p>But if we try and assign <b>$xml->Result->City</b> to a key in our associative array, it instead assigns the entire simplexml object rather than its string contents. So, in our call to <b>array()</b> we need to cast the two elements as such:</p>
<pre class="brush: php; first-line: 28;">
$ret = array('City' =&gt; (string)$xml-&gt;Result-&gt;City, 'State' =&gt; (string)$xml-&gt;Result-&gt;State);
</pre>
<p>To cast our objects, we simply prepend them with the type to cast to enclosed in parentheses &#8211; a lot less verbose than VB&#8217;s clunky <b>CType()</b> function!</p>
<p>Now, all we need to do for our client-side <b>$.getJSON()</b> call to be happy is to write back a string representing a JSON object, which is where the handy <b>json_encode()</b> function comes into play. We just pass it our hash <b>$ret</b> and voila! Out pops a JSON string that we simply <b>echo</b> to our client, and that&#8217;s it on the server side!</p>
<p>All that&#8217;s left now is for the callback function we specified in our call to <b>$.getJSON()</b> to fire, in which a new <b>&lt;label /&gt;</b> is created, has its text set to City, State and is finally appended to our form.</p>
<p>Was this easier that doing it with ASP.NET? Was it lighter-weight? Faster? For something as trivial as this, I think that performance is not much of a consideration at all. Especially since the entire thing bottlenecks on our request to Yahoo Maps. In terms of ease of coding, I think I slightly prefer the ASP.NET PageMethod, though that is probably because I am such a Visual Studio fanboy. The .NET solution still requires two files as does the jQuery/PHP that we&#8217;ve concocted here. The XML handling routines in PHP seem just as capable as those in .NET. One thing I can say I like more about the PHP solution is that I feel much more in control of exactly what is going on in terms of generated code (there is none for our PHP solution!). I am not sure how much weight is added to a page when ASP.NET AJAX builds proxies for our client code to talk to a PageMethod, and I do know that jQuery, in minified and gzipped form, only takes 19K &#8211; which is awfully small&#8230; how close does ASP.NET AJAX come to that number?</p>
<p>I think we&#8217;ve pretty much exhausted this whole zipcode lookup thing, so next time I want to examine using nested ASP.NET data controls such as the Repeater, FormView, etc.<br />
</p>
]]></content:encoded>
			<wfw:commentRss>http://brian.dobberteen.com/code/responding-to-jquery-ajax-request-with-php/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
