<?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>Program With Dave</title>
	<atom:link href="http://www.daveandrews.org/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.daveandrews.org</link>
	<description>My Programming Tutorials and Experiments</description>
	<lastBuildDate>Fri, 19 Feb 2010 19:40:54 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Sending an Email in C# When Server Uses GREET_PAUSE</title>
		<link>http://www.daveandrews.org/2010/02/19/sending-an-email-in-c-when-server-uses-greet_pause/</link>
		<comments>http://www.daveandrews.org/2010/02/19/sending-an-email-in-c-when-server-uses-greet_pause/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 19:40:54 +0000</pubDate>
		<dc:creator>Dave Andrews</dc:creator>
				<category><![CDATA[CSharp]]></category>
		<category><![CDATA[Dot Net]]></category>

		<guid isPermaLink="false">http://www.daveandrews.org/?p=339</guid>
		<description><![CDATA[I wrote a process for a client which would send an email through their email server when a process completed. Their server did not require any kind of authentication or SSL, so the code to do this was very simple:

1
2
3
4
5
6
7
8
9
10
public static void SendEmail&#40;string to, string from, string subject, 
       [...]]]></description>
			<content:encoded><![CDATA[<p>I wrote a process for a client which would send an email through their email server when a process completed. Their server did not require any kind of authentication or SSL, so the code to do this was very simple:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> SendEmail<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> to, <span style="color: #FF0000;">string</span> from, <span style="color: #FF0000;">string</span> subject, 
                             <span style="color: #FF0000;">string</span> message, <span style="color: #FF0000;">string</span> host, <span style="color: #FF0000;">int</span> port<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    SmtpClient c <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> SmtpClient<span style="color: #000000;">&#40;</span>host, port<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    MailMessage m <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> MailMessage<span style="color: #000000;">&#40;</span>from, to, subject, message<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    m.<span style="color: #0000FF;">IsBodyHtml</span> <span style="color: #008000;">=</span> true<span style="color: #008000;">;</span>
&nbsp;
    c.<span style="color: #0000FF;">Send</span><span style="color: #000000;">&#40;</span>m<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>Simple, eh? But it would fail. If I telnet&#8217;ed into their server and typed the SMTP commands to send an email, I would get a 550 5.0.0 Command Rejected&#8221; error message at the point where I try to send a &#8220;RCPT TO:&#8221; SMTP command. What&#8217;s the deal?!</p>
<p>Well, apparently the server did have a restriction that I had so far not known about. It had been configured with a GREET_PAUSE value for all emails. Typically that setting should only be set for incoming emails from external servers, and not for internal emails like this. But it was set for all emails.</p>
<p>GREET_PAUSE means that once an SMTP connection is made, the client who is connecting must WAIT until the server recognizes their connection before &#8220;blasting&#8221; SMTP commands through. Apparently SMTPClient just blasts the commands through. If a SINGLE character is received in that timespan, the server will reply as normal, but will reject any and all emails that are sent through.</p>
<p>I tried a couple fancy ways to make SMTPClient wait for a few seconds before sending data, but could not find an easy way. Apparently it does not support this capability out of the box (such that I could find.) So I resolved to just writing the email code myself. It&#8217;s not hard to do.</p>
<p>I added a greet_delay_ms integer to my parameters on my function:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> SendEmail<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> to, <span style="color: #FF0000;">string</span> from, <span style="color: #FF0000;">string</span> subject, <span style="color: #FF0000;">string</span> message, 
                    <span style="color: #FF0000;">string</span> host, <span style="color: #FF0000;">int</span> port, <span style="color: #FF0000;">int</span> greet_delay_ms<span style="color: #000000;">&#41;</span></pre></td></tr></table></div>

<p>And replaced the simple SMTPClient code with this more complex code:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> SendEmail<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> to, <span style="color: #FF0000;">string</span> from, <span style="color: #FF0000;">string</span> subject, <span style="color: #FF0000;">string</span> message, 
                       <span style="color: #FF0000;">string</span> host, <span style="color: #FF0000;">int</span> port, <span style="color: #FF0000;">int</span> greet_delay_ms<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    TcpClient c <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> TcpClient<span style="color: #000000;">&#40;</span>host, port<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    StreamWriter sw <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StreamWriter<span style="color: #000000;">&#40;</span>c.<span style="color: #0000FF;">GetStream</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    StreamReader sr <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StreamReader<span style="color: #000000;">&#40;</span>c.<span style="color: #0000FF;">GetStream</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #FF0000;">string</span> data <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;&quot;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// Wait the specified amount of time before sending an email</span>
    <span style="color: #008080; font-style: italic;">// could probably also just do a sr.ReadLine() and let it block</span>
    <span style="color: #000000;">System.<span style="color: #0000FF;">Threading</span></span>.<span style="color: #0000FF;">Thread</span>.<span style="color: #0000FF;">Sleep</span><span style="color: #000000;">&#40;</span>greet_delay_ms<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    sw.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;helo &quot;</span> <span style="color: #008000;">+</span> from.<span style="color: #0000FF;">Substring</span><span style="color: #000000;">&#40;</span>from.<span style="color: #0000FF;">IndexOf</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;@&quot;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">+</span> <span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    sw.<span style="color: #0000FF;">Flush</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    data <span style="color: #008000;">=</span> sr.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    sw.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;MAIL FROM:&quot;</span> <span style="color: #008000;">+</span> from<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    sw.<span style="color: #0000FF;">Flush</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    data <span style="color: #008000;">=</span> sr.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    sw.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;RCPT TO:&quot;</span> <span style="color: #008000;">+</span> to<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    sw.<span style="color: #0000FF;">Flush</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    data <span style="color: #008000;">=</span> sr.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    sw.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;DATA&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    sw.<span style="color: #0000FF;">Flush</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    data <span style="color: #008000;">=</span> sr.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    sw.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Subject: &quot;</span> <span style="color: #008000;">+</span> subject<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    sw.<span style="color: #0000FF;">Flush</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    sw.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span>message<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    sw.<span style="color: #0000FF;">Flush</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    sw.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;.&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    sw.<span style="color: #0000FF;">Flush</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    data <span style="color: #008000;">=</span> sr.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    c.<span style="color: #0000FF;">Client</span>.<span style="color: #0000FF;">Close</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    c.<span style="color: #0000FF;">Close</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>Once I passed in 8000 or so as the time to wait, the emails poured through just fine. 8 seconds is a while to wait, but apparently that&#8217;s what this server requires.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.daveandrews.org/2010/02/19/sending-an-email-in-c-when-server-uses-greet_pause/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Binding a Dropdown List in ASP.Net Inside a ListView</title>
		<link>http://www.daveandrews.org/2009/12/08/binding-a-dropdown-list-in-asp-net-inside-a-listview/</link>
		<comments>http://www.daveandrews.org/2009/12/08/binding-a-dropdown-list-in-asp-net-inside-a-listview/#comments</comments>
		<pubDate>Tue, 08 Dec 2009 20:54:54 +0000</pubDate>
		<dc:creator>Dave Andrews</dc:creator>
				<category><![CDATA[CSharp]]></category>
		<category><![CDATA[Dot Net]]></category>

		<guid isPermaLink="false">http://www.daveandrews.org/?p=283</guid>
		<description><![CDATA[I like to blog things that I have to look up. Here&#8217;s a quickie which solves a problem I was having.
In my table, I have a field &#8220;PayType&#8221; which is a char(1) and has valid values &#8220;S&#8221; and &#8220;H&#8221;. These mean &#8220;Salary&#8221; and &#8220;Hourly&#8221;, respectively.
I am showing this in a ListView in my screen I&#8217;m [...]]]></description>
			<content:encoded><![CDATA[<p>I like to blog things that I have to look up. Here&#8217;s a quickie which solves a problem I was having.</p>
<p>In my table, I have a field &#8220;PayType&#8221; which is a char(1) and has valid values &#8220;S&#8221; and &#8220;H&#8221;. These mean &#8220;Salary&#8221; and &#8220;Hourly&#8221;, respectively.</p>
<p>I am showing this in a ListView in my screen I&#8217;m developing. So, when editing the record, I naturally wanted a dropdown box where you can choose &#8220;Hourly&#8221; or &#8220;Salary&#8221;. Note this will only work if you know what values you want in your dropdown box. If the selections are dynamic, then you will probably have to have a databound event and build the box manually.</p>
<p>I wanted it to default to the selected type for the record I&#8217;m editing when I click on edit, but could not find anything in the intellisence that looked correct for my Bind() call.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;asp:DropDownList 
      ID=&quot;ddPayType&quot; 
      runat=&quot;server&quot; 
      SelectedValue=&lt;%# Bind(&quot;PayType&quot;) %&gt;  &gt;;
          &lt;asp:ListItem Text=&quot;Salary&quot; Value = &quot;S&quot; /&gt;
          &lt;asp:ListItem Text=&quot;Hourly&quot; Value = &quot;H&quot; /&gt;
&lt;/asp:DropDownList&gt;</pre></td></tr></table></div>

<p>The answer was to Bind on the &#8220;SelectedValue&#8221; parameter. I was thrown off because SelectedValue does not seem to pull up in Visual Studio 2008 as an option on the list when writing code in the markup editor. But it correctly updates the value when the Update command is executed.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.daveandrews.org/2009/12/08/binding-a-dropdown-list-in-asp-net-inside-a-listview/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Chat Client/Server Part 3: The Connection Class</title>
		<link>http://www.daveandrews.org/2009/11/24/chat-clientserver-part-3-the-connection-class/</link>
		<comments>http://www.daveandrews.org/2009/11/24/chat-clientserver-part-3-the-connection-class/#comments</comments>
		<pubDate>Wed, 25 Nov 2009 02:05:42 +0000</pubDate>
		<dc:creator>Dave Andrews</dc:creator>
				<category><![CDATA[CSharp]]></category>
		<category><![CDATA[Dot Net]]></category>

		<guid isPermaLink="false">http://www.daveandrews.org/?p=142</guid>
		<description><![CDATA[If you have not read Part 1 and Part 2 of this network tutorial series, please do so now. The code in this post will build upon code from those posts.
The Connection Class: Beginning Network Code
We are going to get into the fun part of the network code in this part of the series. This [...]]]></description>
			<content:encoded><![CDATA[<p>If you have not read <a href="http://www.daveandrews.org/2009/09/14/chat-clientserver-part-1-network-programming-primer-and-packet-base-class/">Part 1</a> and <a href="http://www.daveandrews.org/2009/09/27/chat-clientserver-part-2-packet-extension-and-server/">Part 2</a> of this network tutorial series, please do so now. The code in this post will build upon code from those posts.</p>
<h3>The Connection Class: Beginning Network Code</h3>
<p>We are going to get into the fun part of the network code in this part of the series. This post will teach you how to use TcpClient to send and receive data over the network. TcpClient is a class in Microsoft Dot Net which instantiates a TCP connection and can send and receive data in the form of byte arrays.</p>
<p><strong>Step 1: Create our connection class.</strong> Right-click on our Chat class library and add a new class. Call that class &#8220;Connection&#8221;.  This class will use our Packet class to send and receive data.</p>
<p><strong>Step 2: Include the correct using statements.</strong> We need to include certain dot net classes to make our coding job easier. Add these using statements to the top of Connection.cs.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Net.Sockets</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Net</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>The TcpClient class we are going to use is included by using these statements. This will make our coding easier since we don&#8217;t have to fully qualify each time we use the TcpClient class.</p>
<p><strong>Step 3: Instantiate our TcpClient object.</strong> Inside of your Connection class, add the following line of code which will create our TcpClient class. By creating one here, it will be instantiated with our Connection object and always be available.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Connection
    <span style="color: #000000;">&#123;</span>
        TcpClient c <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> TcpClient<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>We now have a client object named &#8220;c&#8221; to work with in our network code.</p>
<p><strong>Step 4: Constructors.</strong> Let&#8217;s create a couple of constructors for our connection class. One constructor should take a TcpClient object as a parameter, so that it can accept one that&#8217;s already created. Another constructor should just take a server to connect to and the port to connect to, and open the connection.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">        <span style="color: #0600FF;">public</span> Connection<span style="color: #000000;">&#40;</span>TcpClient client<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            c <span style="color: #008000;">=</span> client<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> Connection<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> server, <span style="color: #FF0000;">int</span> port<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            c.<span style="color: #0000FF;">Connect</span><span style="color: #000000;">&#40;</span>server, port<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>As you can see from the second constructor, opening a TCP connection to a given server with a given port is very easy to do. The call to Connect is a &#8220;blocking&#8221; operation, which as you should remember from Part 1 of this series means it will wait until the connection has been created successfully before continuing with any further code.</p>
<p>If the connection fails for any reason, an exception will be thrown. Any client code written using the Connection class should be able to handle that exception. As a matter of fact, every function in this class could possibly throw an exception, so your client code should always wrap network calls in a try/catch statement.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.daveandrews.org/2009/11/24/chat-clientserver-part-3-the-connection-class/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using COALESCE() in Linq-To-SQL</title>
		<link>http://www.daveandrews.org/2009/11/23/using-coalesce-in-linq-to-sql/</link>
		<comments>http://www.daveandrews.org/2009/11/23/using-coalesce-in-linq-to-sql/#comments</comments>
		<pubDate>Mon, 23 Nov 2009 16:52:05 +0000</pubDate>
		<dc:creator>Dave Andrews</dc:creator>
				<category><![CDATA[CSharp]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.daveandrews.org/?p=270</guid>
		<description><![CDATA[I had a situation today where I wanted to return a user&#8217;s name using Linq. Sure, I could have easily written some code for this, but for the sake of keeping my code simple and readable I wanted Linq to handle the building of the name.
Users Table


UserID
FirstName
LastName


1
David
Andrews


2
Bob
NULL


The Linq seemed easy:

1
2
3
4
5
6
7
8
9
10
public static string GetNameOfUser&#40;int userID&#41;
  [...]]]></description>
			<content:encoded><![CDATA[<p>I had a situation today where I wanted to return a user&#8217;s name using Linq. Sure, I could have easily written some code for this, but for the sake of keeping my code simple and readable I wanted Linq to handle the building of the name.</p>
<p><strong>Users Table</strong></p>
<table cellpadding = 5 cellspacing = 2 border = 1 style = "border-collapse:collapse">
<tr>
<th>UserID</th>
<th>FirstName</th>
<th>LastName</th>
</tr>
<tr>
<td>1</td>
<td>David</td>
<td>Andrews</td>
</tr>
<tr>
<td>2</td>
<td>Bob</td>
<td><i>NULL</i></td>
</tr>
</table>
<p>The Linq seemed easy:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">string</span> GetNameOfUser<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> userID<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            DatabaseDataContext dc <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DatabaseDataContext<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            var user <span style="color: #008000;">=</span> from u <span style="color: #0600FF;">in</span> dc.<span style="color: #0000FF;">Users</span>
                       where u.<span style="color: #0000FF;">UserID</span> <span style="color: #008000;">==</span> userID
                       select u.<span style="color: #0000FF;">FirstName</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot; &quot;</span> <span style="color: #008000;">+</span> u.<span style="color: #0000FF;">LastName</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">return</span> <span style="color: #000000;">&#40;</span>user.<span style="color: #0000FF;">Count</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">==</span> <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">?</span> <span style="color: #666666;">&quot;Unknown User&quot;</span> <span style="color: #008000;">:</span> user.<span style="color: #0000FF;">First</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>However my results were not correct. Bob was left out because he did not have a last name value (it&#8217;s NULL in the database.) You will get results like this if you run that for each user (one at a time, but I put them in a table here.)</p>
<p><strong>Results</strong></p>
<table cellpadding = 5 cellspacing = 2 border = 1 style = "border-collapse:collapse">
<tr>
<th>Expected</th>
<th>Value Received</th>
</tr>
<tr>
<td>David Andrews</td>
<td>David Andrews</td>
</tr>
<tr>
<td>Bob</td>
<td><i>&lt;Empty String&gt;</i></td>
</tr>
</table>
<p>In SQL it is very common to use the COALESCE() function to handle problems with null values. But how can I do that in Linq? I didn&#8217;t want to write extra code to check for nulls and concatenate the values myself.</p>
<p>The answer is simple: <b>??</b>.  Yes, that&#8217;s right. Two question marks is the &#8220;coalesce&#8221; operator in Linq. It&#8217;s a good idea to wrap what you are testing in coalesce inside parenthesis as well.</p>
<p>What follows is my new function.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">string</span> GetNameOfUser<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> userID<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            DatabaseDataContext dc <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DatabaseDataContext<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            var user <span style="color: #008000;">=</span> from u <span style="color: #0600FF;">in</span> dc.<span style="color: #0000FF;">Users</span>
                       where u.<span style="color: #0000FF;">UserID</span> <span style="color: #008000;">==</span> userID
                       select <span style="color: #000000;">&#40;</span>u.<span style="color: #0000FF;">FirstName</span> <span style="color: #008000;">??</span> <span style="color: #666666;">&quot;&quot;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot; &quot;</span> <span style="color: #008000;">+</span> <span style="color: #000000;">&#40;</span>u.<span style="color: #0000FF;">LastName</span> <span style="color: #008000;">??</span> <span style="color: #666666;">&quot;&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">return</span> <span style="color: #000000;">&#40;</span>user.<span style="color: #0000FF;">Count</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">==</span> <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">?</span> <span style="color: #666666;">&quot;Unknown User&quot;</span> <span style="color: #008000;">:</span> user.<span style="color: #0000FF;">First</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>As you can see, I&#8217;ve added ?? &#8220;&#8221; after both FirstName and LastName. This translates to:</p>
<p>coalesce(FirstName, &#8221;)<br />
coalesce(LastName, &#8221;)</p>
<p>Which means that if FirstName is null you will get &#8221;, which adds correctly in SQL to another string. Same goes for LastName.</p>
<p>Here are my new results:</p>
<p><strong>Results</strong></p>
<table cellpadding = 5 cellspacing = 2 border = 1 style = "border-collapse:collapse">
<tr>
<th>Expected</th>
<th>Value Received</th>
</tr>
<tr>
<td>David Andrews</td>
<td>David Andrews</td>
</tr>
<tr>
<td>Bob</td>
<td>Bob</td>
</tr>
</table>
]]></content:encoded>
			<wfw:commentRss>http://www.daveandrews.org/2009/11/23/using-coalesce-in-linq-to-sql/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Join on Multiple Columns in Linq To SQL</title>
		<link>http://www.daveandrews.org/2009/11/20/join-on-multiple-columns-in-linq-to-sql/</link>
		<comments>http://www.daveandrews.org/2009/11/20/join-on-multiple-columns-in-linq-to-sql/#comments</comments>
		<pubDate>Fri, 20 Nov 2009 16:57:03 +0000</pubDate>
		<dc:creator>Dave Andrews</dc:creator>
				<category><![CDATA[CSharp]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.daveandrews.org/?p=241</guid>
		<description><![CDATA[Today I had to create a Linq-To-SQL query which joined two tables. These tables had compound primary keys (table simplified for example):
Table Referrers


ServerID (PK)
ReferrerID (PK)
Value


1
1
My value 1


1
2
My value 2


1
3
My value 3


Table ReferrerInfo


ServerID (PK)
ReferrerID (PK)
Value


1
1
More info&#8230; 1


1
2
More info&#8230; 2


1
3
More Info&#8230; 3


So I wanted to join these together using a Linq-To-SQL query. The first thought that occured [...]]]></description>
			<content:encoded><![CDATA[<p>Today I had to create a Linq-To-SQL query which joined two tables. These tables had compound primary keys (table simplified for example):</p>
<p><strong>Table Referrers</strong></p>
<table cellpadding = 5 cellspacing = 2 border = 1 style = "border-collapse:collapse;">
<tr>
<th>ServerID (PK)</th>
<th>ReferrerID (PK)</th>
<th>Value</th>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>My value 1</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>My value 2</td>
</tr>
<tr>
<td>1</td>
<td>3</td>
<td>My value 3</td>
</tr>
</table>
<p><strong>Table ReferrerInfo</strong></p>
<table cellpadding = 5 cellspacing = 2 border = 1 style = "border-collapse:collapse;">
<tr>
<th>ServerID (PK)</th>
<th>ReferrerID (PK)</th>
<th>Value</th>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>More info&#8230; 1</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>More info&#8230; 2</td>
</tr>
<tr>
<td>1</td>
<td>3</td>
<td>More Info&#8230; 3</td>
</tr>
</table>
<p>So I wanted to join these together using a Linq-To-SQL query. The first thought that occured to me was to use a join:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">var referrers <span style="color: #008000;">=</span> from r <span style="color: #0600FF;">in</span> Referrers
               join ri <span style="color: #0600FF;">in</span> ReferrerInfo on r.<span style="color: #0000FF;">ServerConnectionID</span> equals ri.<span style="color: #0000FF;">ServerConnectionID</span> ..... <span style="color: #008000;">??????</span>
               select r<span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>So, apparently in C# you cannot do multiple columns in your join. I have to join on both ServerConnectionID and ReferrerID.</p>
<p>This page: <a href="http://www.onedotnetway.com/linq-to-sql-join-on-multiple-conditions/">http://www.onedotnetway.com/linq-to-sql-join-on-multiple-conditions/</a> explains one method to do so, but unfortunately that Linq query only works in VB.</p>
<p>So, I ended up writing a Linq-To-SQL that just uses the old style of joining, by using the where clause!</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">var referrers <span style="color: #008000;">=</span> from r <span style="color: #0600FF;">in</span> Referrers
                from ri <span style="color: #0600FF;">in</span> Referrer_Info
                where r.<span style="color: #0000FF;">ServerConnectionID</span> <span style="color: #008000;">==</span> ri.<span style="color: #0000FF;">ServerConnectionID</span> <span style="color: #008000;">&amp;&amp;</span>
                   r.<span style="color: #0000FF;">ReferrerID</span> <span style="color: #008000;">==</span> ri.<span style="color: #0000FF;">ReferrerID</span>
                select r<span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>This successfully executes my multi-column join.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.daveandrews.org/2009/11/20/join-on-multiple-columns-in-linq-to-sql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Row_Number() to Enumerate and Partition Records in SQL Server</title>
		<link>http://www.daveandrews.org/2009/10/30/using-row_number-to-enumerate-and-partition-records-in-sql-server/</link>
		<comments>http://www.daveandrews.org/2009/10/30/using-row_number-to-enumerate-and-partition-records-in-sql-server/#comments</comments>
		<pubDate>Fri, 30 Oct 2009 11:25:15 +0000</pubDate>
		<dc:creator>Dave Andrews</dc:creator>
				<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.daveandrews.org/?p=171</guid>
		<description><![CDATA[I had a situation recently where I had a table full of people records, where the people were divided into families. The business logic that needed to be followed was that I had to assign a &#8220;Twin Code&#8221; to each record. This meant that for each family in the database, if two or more members [...]]]></description>
			<content:encoded><![CDATA[<p>I had a situation recently where I had a table full of people records, where the people were divided into families. The business logic that needed to be followed was that I had to assign a &#8220;Twin Code&#8221; to each record. This meant that for each family in the database, if two or more members were born on the same day they should be treated as twins. The twins should be assigned a number enumerating them in order of birth. If the member was not a twin, they should just receive the twin code of 1.</p>
<p>Here&#8217;s an example table:</p>
<table cellpadding = 5 cellspacing = 2 border = 1 style = "border-collapse:collapse;">
<tr>
<th>PersonID</th>
<th>FamilyID</th>
<th>FirstName</th>
<th>LastName</th>
<th>DateOfBirth</th>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>Joe</td>
<td>Johnson</td>
<td>2000-10-23 13:00:00</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>Jim</td>
<td>Johnson</td>
<td>2001-12-15 05:45:00</td>
</tr>
<tr>
<td>3</td>
<td>2</td>
<td>Karly</td>
<td>Matthews</td>
<td>2000-05-20 04:00:00</td>
</tr>
<tr>
<td>4</td>
<td>2</td>
<td>Kacy</td>
<td>Matthews</td>
<td>2000-05-20 04:02:00</td>
</tr>
<tr>
<td>5</td>
<td>2</td>
<td>Tom</td>
<td>Matthews</td>
<td>2001-09-15 11:52:00</td>
</tr>
</table>
<p>There are lots of ways to achieve the desired result, but the simplest is to just use a simple SELECT statement combined with the <b>ROW_NUMBER()</b> function with a couple parameters as to how to number the rows!</p>
<p>ROW_NUMBER() provides you with the number of a row in a given recordset, where you provide details on how to number the records. For example, if I just had to number the records above based solely upon the date of birth (ignoring families) then I would use this query:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span>
     <span style="color: #66cc66;">&#91;</span>PersonID<span style="color: #66cc66;">&#93;</span>
    <span style="color: #66cc66;">,</span><span style="color: #66cc66;">&#91;</span>FamilyID<span style="color: #66cc66;">&#93;</span>
    <span style="color: #66cc66;">,</span><span style="color: #66cc66;">&#91;</span>FirstName<span style="color: #66cc66;">&#93;</span>
    <span style="color: #66cc66;">,</span><span style="color: #66cc66;">&#91;</span>LastName<span style="color: #66cc66;">&#93;</span>
    <span style="color: #66cc66;">,</span><span style="color: #66cc66;">&#91;</span>DateOfBirth<span style="color: #66cc66;">&#93;</span>
    <span style="color: #66cc66;">,</span>ROW_NUMBER<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> over <span style="color: #66cc66;">&#40;</span><span style="color: #993333; font-weight: bold;">ORDER</span> <span style="color: #993333; font-weight: bold;">BY</span> DateOfBirth<span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">AS</span> Number
<span style="color: #993333; font-weight: bold;">FROM</span>
	People
<span style="color: #993333; font-weight: bold;">ORDER</span> <span style="color: #993333; font-weight: bold;">BY</span> 
	PersonID</pre></td></tr></table></div>

<p>This just tells the ROW_NUMBER() function to order its numbering ascending by DateOfBirth. Notice that I apply an order myself later on in the query, which is different than the row_number() order. I would get these results:</p>
<table cellpadding = 5 cellspacing = 2 border = 1 style = "border-collapse:collapse;">
<tr>
<th>PersonID</th>
<th>FamilyID</th>
<th>FirstName</th>
<th>LastName</th>
<th>DateOfBirth</th>
<th>Number</th>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>Joe</td>
<td>Johnson</td>
<td>2000-10-23 13:00:00</td>
<td>3</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>Jim</td>
<td>Johnson</td>
<td>2001-12-15 05:45:00</td>
<td>5</td>
</tr>
<tr>
<td>3</td>
<td>2</td>
<td>Karly</td>
<td>Matthews</td>
<td>2000-05-20 04:00:00</td>
<td>1</td>
</tr>
<tr>
<td>4</td>
<td>2</td>
<td>Kacy</td>
<td>Matthews</td>
<td>2000-05-20 04:02:00</td>
<td>2</td>
</tr>
<tr>
<td>5</td>
<td>2</td>
<td>Tom</td>
<td>Matthews</td>
<td>2001-09-15 11:52:00</td>
<td>4</td>
</tr>
</table>
<p>The number field that is assigned to each record is in the order of DateOfBirth.</p>
<p>Ordering my numbering by DateOfBirth is just half of the picture. I also need to &#8220;group&#8221; the records by the FamilyID. This is where a clause in T-SQL that you might not be very familiar with comes into play: &#8220;PARTITION BY&#8221;. The PARTITION BY clause allows us to group the results within the call to ROW_NUMBER() without grouping them ourselves via a GROUP BY. It just tells the ROW_NUMBER what groupings to use when it does its counting.</p>
<p>Here is our final SQL statement, which achieves the business logic we wanted to implement.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span> 
       <span style="color: #66cc66;">&#91;</span>PersonID<span style="color: #66cc66;">&#93;</span>
      <span style="color: #66cc66;">,</span><span style="color: #66cc66;">&#91;</span>FamilyID<span style="color: #66cc66;">&#93;</span>
      <span style="color: #66cc66;">,</span><span style="color: #66cc66;">&#91;</span>FirstName<span style="color: #66cc66;">&#93;</span>
      <span style="color: #66cc66;">,</span><span style="color: #66cc66;">&#91;</span>LastName<span style="color: #66cc66;">&#93;</span>
      <span style="color: #66cc66;">,</span><span style="color: #66cc66;">&#91;</span>DateOfBirth<span style="color: #66cc66;">&#93;</span>
      <span style="color: #66cc66;">,</span>ROW_NUMBER<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> over<span style="color: #66cc66;">&#40;</span>PARTITION <span style="color: #993333; font-weight: bold;">BY</span> FamilyID<span style="color: #66cc66;">,</span> 
                         CONVERT<span style="color: #66cc66;">&#40;</span>NVARCHAR<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">25</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">,</span> DateOfBirth<span style="color: #66cc66;">,</span> <span style="color: #cc66cc;">111</span><span style="color: #66cc66;">&#41;</span> 
                         <span style="color: #993333; font-weight: bold;">ORDER</span> <span style="color: #993333; font-weight: bold;">BY</span> DateOfBirth <span style="color: #993333; font-weight: bold;">ASC</span><span style="color: #66cc66;">&#41;</span> TwinCode
&nbsp;
  <span style="color: #993333; font-weight: bold;">FROM</span> <span style="color: #66cc66;">&#91;</span>People<span style="color: #66cc66;">&#93;</span>
<span style="color: #993333; font-weight: bold;">ORDER</span> <span style="color: #993333; font-weight: bold;">BY</span>
	PersonID</pre></td></tr></table></div>

<p>In the ROW_NUMBER function above, I am doing several things. I&#8217;m grouping on FamilyID, and also grouping on a converted DateOfBirth. I convert the DateOfBirth to an nvarchar using the 111 conversion code, because that gets results like &#8216;2009/10/11&#8242; and &#8216;2009/10/12&#8242; which can easily be grouped by to achieve distinct dates. </p>
<p>Grouping on the Family, DateOfBirth, and then sorting by DateOfBirth ascending achieves the desired result for the ROW_NUMBER. Here are the results of the query:</p>
<table cellpadding = 5 cellspacing = 2 border = 1 style = "border-collapse:collapse;">
<tr>
<th>PersonID</th>
<th>FamilyID</th>
<th>FirstName</th>
<th>LastName</th>
<th>DateOfBirth</th>
<th>TwinCode</th>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>Joe</td>
<td>Johnson</td>
<td>2000-10-23 13:00:00</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>Jim</td>
<td>Johnson</td>
<td>2001-12-15 05:45:00</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>2</td>
<td>Karly</td>
<td>Matthews</td>
<td>2000-05-20 04:00:00</td>
<td>1</td>
</tr>
<tr>
<td>4</td>
<td>2</td>
<td>Kacy</td>
<td>Matthews</td>
<td>2000-05-20 04:02:00</td>
<td>2</td>
</tr>
<tr>
<td>5</td>
<td>2</td>
<td>Tom</td>
<td>Matthews</td>
<td>2001-09-15 11:52:00</td>
<td>1</td>
</tr>
</table>
<p>As you can see, the two people who qualify as twins above (Karly and Kacy) are enumerated correctly, with Karly receiving a 1 and Kacy receiving a 2. All the records that are not twins properly receive a 1.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.daveandrews.org/2009/10/30/using-row_number-to-enumerate-and-partition-records-in-sql-server/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SQL Server &#8211; Using Computed or Calculated Columns in Tables</title>
		<link>http://www.daveandrews.org/2009/10/21/sql-server-using-computed-or-calculated-columns-in-tables/</link>
		<comments>http://www.daveandrews.org/2009/10/21/sql-server-using-computed-or-calculated-columns-in-tables/#comments</comments>
		<pubDate>Thu, 22 Oct 2009 02:34:11 +0000</pubDate>
		<dc:creator>Dave Andrews</dc:creator>
				<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.daveandrews.org/?p=160</guid>
		<description><![CDATA[You are probably used to writing views to access data in your tables when there is some sort of computation that must be made in a field. But did you know that you can have your tables make computations themselves, without running through a view?
This can be done with Computed (or Calculated) Columns. These columns [...]]]></description>
			<content:encoded><![CDATA[<p>You are probably used to writing views to access data in your tables when there is some sort of computation that must be made in a field. But did you know that you can have your tables make computations themselves, without running through a view?</p>
<p>This can be done with <strong>Computed (or Calculated) Columns.</strong> These columns are table-level expressions that can operate on the other fields in a given record.</p>
<p>Let&#8217;s create a table which uses computed columns. I am going to create a table called Programmers which allows me to store a programmer&#8217;s first name, last name, middle initial, and date of birth. The table will include two computed columns: one which combines the elements of the name into a FullName field, and a second column which tells me the programmer&#8217;s age. This will all be achieved directly in the table, without the use of a view.</p>
<p>First, let&#8217;s create the table. Here is the query to create all of the fields except the computed ones.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">TABLE</span> Programmers
<span style="color: #66cc66;">&#40;</span>
	ProgrammerID INT IDENTITY<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">,</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span>
	FirstName NVARCHAR<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">30</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">,</span>
	LastName NVARCHAR<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">30</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">,</span>
	MiddleInit NCHAR<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">,</span>
	DateOfBirth DATETIME<span style="color: #66cc66;">,</span></pre></td></tr></table></div>

<p>Now, let&#8217;s create our first computed column. The syntax is simple. Just begin with the name of the column, and then in parenthesis define the expression which will calculate the value of the column.</p>
<p>Let&#8217;s begin with the FullName calculation. Just add the LastName, a comma, FirstName, and MiddleInit, and then trim white space off the right to handle a missing initial.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;">        FullName <span style="color: #993333; font-weight: bold;">AS</span> <span style="color: #66cc66;">&#40;</span>rtrim<span style="color: #66cc66;">&#40;</span>coalesce<span style="color: #66cc66;">&#40;</span>LastName<span style="color: #66cc66;">,</span> <span style="color: #ff0000;">''</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">+</span> <span style="color: #ff0000;">', '</span> <span style="color: #66cc66;">+</span>
            coalesce<span style="color: #66cc66;">&#40;</span>FirstName<span style="color: #66cc66;">,</span> <span style="color: #ff0000;">''</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">+</span> <span style="color: #ff0000;">' '</span> <span style="color: #66cc66;">+</span> 
            coalesce<span style="color: #66cc66;">&#40;</span>MiddleInit<span style="color: #66cc66;">,</span> <span style="color: #ff0000;">''</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">,</span></pre></td></tr></table></div>

<p>There we have it, our FullName calculation. Each field is encapsulated in coalesce to handle NULL values properly.</p>
<p>The last calculation will be the age. The age is simply the difference in years of the current date from the birth date.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;">	Age <span style="color: #993333; font-weight: bold;">AS</span> <span style="color: #66cc66;">&#40;</span>datediff<span style="color: #66cc66;">&#40;</span>year<span style="color: #66cc66;">,</span> DateOfBirth<span style="color: #66cc66;">,</span> getdate<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#41;</span></pre></td></tr></table></div>

<p>We also add a following parenthesis to close out our &#8220;CREATE TABLE&#8221; statement.</p>
<p>Now lets insert some test data. I added a few records with some NULLs for good testing measure. All standard stuff here. Notice we are not inserting the FullName or Age values.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #993333; font-weight: bold;">INTO</span> Programmers<span style="color: #66cc66;">&#40;</span>FirstName<span style="color: #66cc66;">,</span> LastName<span style="color: #66cc66;">,</span> MiddleInit<span style="color: #66cc66;">,</span> DateOfBirth<span style="color: #66cc66;">&#41;</span>
     <span style="color: #993333; font-weight: bold;">VALUES</span> <span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'David'</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'Andrews'</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'C'</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'1984-09-20'</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #993333; font-weight: bold;">INTO</span> Programmers<span style="color: #66cc66;">&#40;</span>FirstName<span style="color: #66cc66;">,</span> LastName<span style="color: #66cc66;">,</span> MiddleInit<span style="color: #66cc66;">,</span> DateOfBirth<span style="color: #66cc66;">&#41;</span> 
     <span style="color: #993333; font-weight: bold;">VALUES</span> <span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'Billy'</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'Jenkins'</span><span style="color: #66cc66;">,</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'1990-01-20'</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #993333; font-weight: bold;">INTO</span> Programmers<span style="color: #66cc66;">&#40;</span>FirstName<span style="color: #66cc66;">,</span> LastName<span style="color: #66cc66;">,</span> MiddleInit<span style="color: #66cc66;">,</span> DateOfBirth<span style="color: #66cc66;">&#41;</span> 
     <span style="color: #993333; font-weight: bold;">VALUES</span> <span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'Robert'</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'Anderson'</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'K'</span><span style="color: #66cc66;">,</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">&#41;</span></pre></td></tr></table></div>

<p>Now lets test out our fields, using nothing more than a SELECT.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #66cc66;">*</span> <span style="color: #993333; font-weight: bold;">FROM</span> Programmers</pre></td></tr></table></div>

<p>We will get the following results:</p>
<table cellspacing = 2 cellpadding = 3 border = 1 style = 'border-collapse:collapse;'>
<tr>
<th>ProgrammerID</th>
<th>FirstName</th>
<th>LastName</th>
<th>MiddleInit</th>
<th>DateOfBirth</th>
<th>FullName</th>
<th>Age</th>
</tr>
<tr>
<td>1</td>
<td>David</td>
<td>Andrews</td>
<td>C</td>
<td>1984-09-20 00:00:00.000</td>
<td><strong>Andrews, David C</strong></td>
<td><strong>25</strong></td>
</tr>
<tr>
<td>2</td>
<td>Billy</td>
<td>Jenkins</td>
<td>NULL</td>
<td>1990-01-20 00:00:00.000</td>
<td><strong>Jenkins, Billy</strong></td>
<td><strong>19</strong></td>
</tr>
<tr>
<td>3</td>
<td>Robert</td>
<td>Anderson</td>
<td>K</td>
<td>NULL</td>
<td><strong>Anderson, Robert K</strong></td>
<td><strong>NULL</strong></td>
</tr>
</table>
<p>I emphasized the calculated fields above. Our query did not calculate them, they were considered to be just a part of the table since they are calculated fields.</p>
<p>One thing to keep in mind about calculated fields is that they are difficult to modify. You have to DROP the field and then ADD it back with the same name. This can change the order of fields in your query if you use SELECT *. It can also affect any triggers you may have which rely on the fields being in a certain order.</p>
<p>Also keep in mind any overhead that calculated fields may produce. It&#8217;s a good idea to use them for absolutely basic, atomic information, such as what I presented above. Complex calculations could become taxing to your queries.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.daveandrews.org/2009/10/21/sql-server-using-computed-or-calculated-columns-in-tables/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Understanding SQL Joins &#8211; The Left Join</title>
		<link>http://www.daveandrews.org/2009/10/21/understanding-sql-joins-the-left-join/</link>
		<comments>http://www.daveandrews.org/2009/10/21/understanding-sql-joins-the-left-join/#comments</comments>
		<pubDate>Thu, 22 Oct 2009 00:40:02 +0000</pubDate>
		<dc:creator>Dave Andrews</dc:creator>
				<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.daveandrews.org/?p=151</guid>
		<description><![CDATA[SQL joins are a crucial part of anything more than the simplest of queries. Many programmers who do not fully comprehend SQL joins end up writing bloated software which will pull information from one table, store it, then run another query to get the information they want to join on. They then use code to [...]]]></description>
			<content:encoded><![CDATA[<p>SQL joins are a crucial part of anything more than the simplest of queries. Many programmers who do not fully comprehend SQL joins end up writing bloated software which will pull information from one table, store it, then run another query to get the information they want to join on. They then use code to process the join. It is much more efficient to have the SQL server handle the joining and processing of these records for you than to create custom code which ties tables together.</p>
<p>Let&#8217;s use these tables as an example.</p>
<p><strong>AnimalTypes table</strong></p>
<table style="border-collapse:collapse;" border="1" cellspacing="2" cellpadding="5">
<tbody>
<tr>
<th>AnimalTypeID</th>
<th>Name</th>
</tr>
<tr>
<td>1</td>
<td>Dog</td>
</tr>
<tr>
<td>2</td>
<td>Cat</td>
</tr>
<tr>
<td>3</td>
<td>Turtle</td>
</tr>
<tr>
<td>4</td>
<td>Ferret</td>
</tr>
</tbody>
</table>
<p><strong>Animals table</strong></p>
<table style="border-collapse:collapse;" border="1" cellspacing="2" cellpadding="5">
<tbody>
<tr>
<th>AnimalID</th>
<th>AnimalTypeID</th>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>Dusty</td>
<td>5</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td>Jonesey</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>2</td>
<td>Bonnie</td>
<td>1</td>
</tr>
<tr>
<td>4</td>
<td>3</td>
<td>Fiddler</td>
<td>3</td>
</tr>
<tr>
<td>5</td>
<td>1</td>
<td>Marci</td>
<td>1</td>
</tr>
<tr>
<td>6</td>
<td>5</td>
<td>Tails</td>
<td>2</td>
</tr>
</tbody>
</table>
<p>Here we have a table called AnimalTypes which contains 4 types of animals, and a table called Animals which lists out animals and what type they are.</p>
<p>Let&#8217;s say we want to write a program which will display all the animals in our animals table, as well as the Name of the Type of the animal, not the ID of the type. If an animal has an unknown type, we want to display &#8220;UNKNOWN.&#8221; Here is the <strong>bad</strong> process that we want to avoid.</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #66cc66;">*</span> <span style="color: #993333; font-weight: bold;">FROM</span> AnimalTypes
<span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #66cc66;">*</span> <span style="color: #993333; font-weight: bold;">FROM</span> Animals</pre></div></div>

<p>The <strong>bad</strong> program will then loop through all the animals and print out the Name field in the AnimalTypes results which corresponds to the given type ID. If one does not exist in the AnimalTypes results, the code could then print &#8220;UNKNOWN.&#8221;</p>
<p>It also might occur to you that you can write a query like this one, which would also be incorrect.</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span>
      <span style="color: #66cc66;">*</span>
<span style="color: #993333; font-weight: bold;">FROM</span>
      Animals<span style="color: #66cc66;">,</span> AnimalTypes
<span style="color: #993333; font-weight: bold;">WHERE</span>
      Animals<span style="color: #66cc66;">.</span>AnimalTypeID <span style="color: #66cc66;">=</span> AnimalTypes<span style="color: #66cc66;">.</span>AnimalTypeID</pre></div></div>

<p>This is the basis of an <strong>inner join</strong>. It can be written as an inner join query, but I wrote it in the manner above as an example. This query will return results, however you will only get animals who have a corresponding correct AnimalType. Our program wants to display all animals, regardless of whether or not they have a valid type selected. Using the tables from above, you would get these results:</p>
<table border="1" cellspacing="2" cellpadding="5" style = "border-collapse:collapse;">
<tbody>
<tr>
<th>AnimalID</th>
<th>AnimalTypeID</th>
<th>Name</th>
<th>Age</th>
<th>AnimalTypeID</th>
<th>Name</th>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>Dusty</td>
<td>5</td>
<td>1</td>
<td>Dog</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td>Jonesey</td>
<td>2</td>
<td>3</td>
<td>Turtle</td>
</tr>
<tr>
<td>3</td>
<td>2</td>
<td>Bonnie</td>
<td>1</td>
<td>2</td>
<td>Cat</td>
</tr>
<tr>
<td>4</td>
<td>3</td>
<td>Fiddler</td>
<td>3</td>
<td>3</td>
<td>Turtle</td>
</tr>
<tr>
<td>5</td>
<td>1</td>
<td>Marci</td>
<td>1</td>
<td>1</td>
<td>Dog</td>
</tr>
</tbody>
</table>
<p>If you notice, the animal <strong>Tails</strong> is missing from the list. This is because Tails&#8217; AnimalTypeID of 5 did not have a corresponding AnimalTypeID in the AnimalTypes table. In a query such as this, both values have to exist in both tables. This is not the case in our data, even though we want all animals to display.</p>
<p>What we need to use in this case is a <strong>left join</strong> or a <strong>left outer join</strong>.  The left join will take each record from the left-hand side of the join, and tie it to records on the right-hand side. If the tie does not exist in the right-hand table, then the left-hand fields will still exist in the results, with NULL values for the right-hand.</p>
<p>Here is the query using a left join.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span> 
     <span style="color: #66cc66;">*</span> 
<span style="color: #993333; font-weight: bold;">FROM</span> 
     Animals
     <span style="color: #993333; font-weight: bold;">LEFT</span> <span style="color: #993333; font-weight: bold;">JOIN</span> AnimalTypes
          <span style="color: #993333; font-weight: bold;">ON</span> Animals<span style="color: #66cc66;">.</span>AnimalTypeID <span style="color: #66cc66;">=</span> AnimalTypes<span style="color: #66cc66;">.</span>AnimalTypeID</pre></td></tr></table></div>

<p>What you get here is every record from Animals, joined to the corresponding AnimalType record. In the case of Tails, we won&#8217;t get any AnimalType information.</p>
<table cellpadding = 5 cellspacing = 2 border = 1 style = 'border-collapse:collapse;'>
<tr>
<th>AnimalID</th>
<th>AnimalTypeID</th>
<th>Name</th>
<th>Age</th>
<th>AnimalTypeID</th>
<th>Name</th>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>Dusty</td>
<td>5</td>
<td>1</td>
<td>Dog</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td>Jonesey</td>
<td>2</td>
<td>3</td>
<td>Turtle</td>
</tr>
<tr>
<td>3</td>
<td>2</td>
<td>Bonnie</td>
<td>1</td>
<td>2</td>
<td>Cat</td>
</tr>
<tr>
<td>4</td>
<td>3</td>
<td>Fiddler</td>
<td>3</td>
<td>3</td>
<td>Turtle</td>
</tr>
<tr>
<td>5</td>
<td>1</td>
<td>Marci</td>
<td>1</td>
<td>1</td>
<td>Dog</td>
</tr>
<tr>
<td>6</td>
<td>5</td>
<td>Tails</td>
<td>2</td>
<td>NULL</td>
<td>NULL</td>
</tr>
</table>
<p>A very common use of this join is in financial transactions, where you might be missing the category of the transaction but still want the amount included.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.daveandrews.org/2009/10/21/understanding-sql-joins-the-left-join/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Conditional Sums in SQL Queries</title>
		<link>http://www.daveandrews.org/2009/09/29/conditional-sums-in-sql-queries/</link>
		<comments>http://www.daveandrews.org/2009/09/29/conditional-sums-in-sql-queries/#comments</comments>
		<pubDate>Tue, 29 Sep 2009 17:06:36 +0000</pubDate>
		<dc:creator>Dave Andrews</dc:creator>
				<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.daveandrews.org/?p=132</guid>
		<description><![CDATA[One thing that you may encounter frequently is a situation where you want to count the records in a table which are of a certain type. You want to do this as efficiently as possible, instead of running a new count query for each type. Let&#8217;s use the below table for reference.



Name
Type
Age


Buffy
Dog
10


Dusty
Dog
13


Clyde
Dog
2


Bonnie
Cat
1


Milky
Ferret
1



We have above a [...]]]></description>
			<content:encoded><![CDATA[<p>One thing that you may encounter frequently is a situation where you want to count the records in a table which are of a certain type. You want to do this as efficiently as possible, instead of running a new count query for each type. Let&#8217;s use the below table for reference.</p>
<table border="1" cellspacing="5" cellpadding="5" border="1" style="border-collapse:collapse">
<tbody>
<tr>
<th>Name</th>
<th>Type</th>
<th>Age</th>
</tr>
<tr>
<td>Buffy</td>
<td>Dog</td>
<td>10</td>
</tr>
<tr>
<td>Dusty</td>
<td>Dog</td>
<td>13</td>
</tr>
<tr>
<td>Clyde</td>
<td>Dog</td>
<td>2</td>
</tr>
<tr>
<td>Bonnie</td>
<td>Cat</td>
<td>1</td>
</tr>
<tr>
<td>Milky</td>
<td>Ferret</td>
<td>1</td>
</tr>
</tbody>
</table>
<p>We have above a table of animals. How can we determine the count of each type of animal? The simplest (and most inefficient) is to run a count() query for each type of animal. This would mean we have 3 queries to run, as there are 3 types of animals.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;">declare @numdogs int
declare @numcats int
declare @numferrets int
&nbsp;
<span style="color: #993333; font-weight: bold;">SELECT</span> @numdogs <span style="color: #66cc66;">=</span> COUNT<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">*</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">FROM</span> animals <span style="color: #993333; font-weight: bold;">WHERE</span> type <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'Dog'</span>
<span style="color: #993333; font-weight: bold;">SELECT</span> @numcats <span style="color: #66cc66;">=</span> COUNT<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">*</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">FROM</span> animals <span style="color: #993333; font-weight: bold;">WHERE</span> type <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'Cat'</span>
<span style="color: #993333; font-weight: bold;">SELECT</span> @numferrets <span style="color: #66cc66;">=</span> COUNT<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">*</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">FROM</span> animals <span style="color: #993333; font-weight: bold;">WHERE</span> type <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'Ferret'</span>
&nbsp;
<span style="color: #993333; font-weight: bold;">SELECT</span> @numdogs <span style="color: #993333; font-weight: bold;">AS</span> NumDogs<span style="color: #66cc66;">,</span> @numcats <span style="color: #993333; font-weight: bold;">AS</span> NumCats<span style="color: #66cc66;">,</span> @numferrets <span style="color: #993333; font-weight: bold;">AS</span> NumFerrets</pre></td></tr></table></div>

<p>We will get results from that query like this.</p>
<table border="1" cellspacing="5" cellpadding="5" border="1" style="border-collapse:collapse">
<tbody>
<tr>
<th>NumDogs</th>
<th>NumCats</th>
<th>NumFerrets</th>
</tr>
<tr>
<td>3</td>
<td>1</td>
<td>1</td>
</tr>
</tbody>
</table>
<p>As you can imagine, this is terribly inefficient. A good answer in this case is to use a &#8220;conditional&#8221; sum in the SQL query. So rather than running COUNT(*) we will be running SUM(&#8230;).  We will combine the SUM() call with a CASE statement, so that it counts correctly. This is the trick I hope to teach you. You can place CASE &#8230; END statements inside of aggregate functions.</p>
<p>Throw away all of our temporary variables, the 4 select statements involved, and let&#8217;s replace them with this single select.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span> 
	SUM<span style="color: #66cc66;">&#40;</span>CASE WHEN type<span style="color: #66cc66;">=</span><span style="color: #ff0000;">'Dog'</span> then <span style="color: #cc66cc;">1</span> else <span style="color: #cc66cc;">0</span> end<span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">AS</span> NumDogs<span style="color: #66cc66;">,</span>
	SUM<span style="color: #66cc66;">&#40;</span>CASE WHEN type<span style="color: #66cc66;">=</span><span style="color: #ff0000;">'Cat'</span> then <span style="color: #cc66cc;">1</span> else <span style="color: #cc66cc;">0</span> end<span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">AS</span> NumCats<span style="color: #66cc66;">,</span>
	SUM<span style="color: #66cc66;">&#40;</span>CASE WHEN type<span style="color: #66cc66;">=</span><span style="color: #ff0000;">'Ferret'</span> then <span style="color: #cc66cc;">1</span> else <span style="color: #cc66cc;">0</span> end<span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">AS</span> NumFerrets
<span style="color: #993333; font-weight: bold;">FROM</span> 
	animals</pre></td></tr></table></div>

<p>We get these results:</p>
<table border="1" cellspacing="5" cellpadding="5" style="border-collapse:collapse">
<tbody>
<tr>
<th>NumDogs</th>
<th>NumCats</th>
<th>NumFerrets</th>
</tr>
<tr>
<td>3</td>
<td>1</td>
<td>1</td>
</tr>
</tbody>
</table>
<p>Which is exactly what we got previously, but using a much more efficient method. The trick was to insert a CASE &#8230; END statement inside the SUM. The case will return a 1 when the type is the type we are looking for, and a 0 otherwise. The sum will then execute to add up all of those 0s and 1s. A 0 will not add anything, so we will effectively end up counting the values which match the type we are looking for.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.daveandrews.org/2009/09/29/conditional-sums-in-sql-queries/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Chat Client/Server Part 2: Packet Extension Class</title>
		<link>http://www.daveandrews.org/2009/09/27/chat-clientserver-part-2-packet-extension-and-server/</link>
		<comments>http://www.daveandrews.org/2009/09/27/chat-clientserver-part-2-packet-extension-and-server/#comments</comments>
		<pubDate>Mon, 28 Sep 2009 03:19:39 +0000</pubDate>
		<dc:creator>Dave Andrews</dc:creator>
				<category><![CDATA[CSharp]]></category>
		<category><![CDATA[Dot Net]]></category>

		<guid isPermaLink="false">http://www.daveandrews.org/?p=91</guid>
		<description><![CDATA[                                               ]]></description>
			<content:encoded><![CDATA[<p>If you have not read <a href="http://www.daveandrews.org/2009/09/14/chat-clientserver-part-1-network-programming-primer-and-packet-base-class/">Part 1 of this Multi-Post tutorial</a>, check it out now. This tutorial will rely on the code written in that tutorial.</p>
<p>This is the second installment of a multi-post tutorial on writing network software using the dot net framework and the C# programming language. In this installment we will be going over the ChatPacket class which implements the Packet abstract class.</p>
<h3>The ChatPacket Class</h3>
<p>If you recall, our Packet class had three important elements.</p>
<ol>
<li><strong>Type Code</strong>: This is an integer value which identifies the type of packet. It is transmitted across the connection for every packet, so that the receiving end knows how to interpret the packet it is receiving.</li>
<li><strong>Converts to Byte Array</strong>: Every packet which inherits from our base packet class should be able to convert itself into a byte array.</li>
<li><strong>Parses a Byte Array</strong>: The packet classes which inherit from the base class should implement a parse function which will take a byte array and read it into the proper packet structure.</li>
</ol>
<p>These capabilities should be implemented by any class which inherits from Packet, so that the library stays consistent.</p>
<p>Let&#8217;s begin by creating a new class. Right-click on your Chat class library and add a new class called ChatPacket.cs. This file will be our main class for sending chat data back and forth.</p>
<p><strong>Step 1: Inherit from Packet base class.</strong> Every packet class we create should inherit from the base Packet class. This is because the server and client code we will be using will use the base class in all of its operations.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> ChatPacket <span style="color: #008000;">:</span> Packet</pre></td></tr></table></div>

<p><strong>Step 2: Create the chat data property.</strong> Chat data is going to be just a string in our chat packet class. Let&#8217;s add a new property to our ChatPacket class.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> ChatData <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>Chatdata is going to basically be the text of each chat packet that gets sent around. When you type in text to send out to the server (and the server sends it to the other clients) then this is the data that gets sent out.</p>
<p><strong>Step 3: Constructor should set the Type of Packet.</strong> The next thing that must be done is that each packet must identify its type. This is so that the end point which receives every packet needs to know how to decode it into the correct class. In our constructor for each packet, we are going to tell the packet which type it is.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">        <span style="color: #0600FF;">public</span> ChatPacket<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> 
        <span style="color: #000000;">&#123;</span>
            _packetTypeCode <span style="color: #008000;">=</span> <span style="color: #FF0000;">1</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>Keep in mind that the type code should be unique to this type of packet. If we created another packet type in this application, its typecode should be set to 2 for each instance. ChatPacket is going to be packet type 1. </p>
<p>We are only going to send around ChatPackets, but it would be a good idea in a more complex program to use constants to make sure your packet types are consistent integer values.</p>
<p><strong>Step 4: Implement ToByteArray() method.</strong> This is the method that will be called by our server to convert a packet into a stream of bytes. The network code will then send the bytes of the network, and the code at the other end will reconstruct the bytes into a packet.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #FF0000;">byte</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> ToByteArray<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">return</span> Encoding.<span style="color: #0000FF;">ASCII</span>.<span style="color: #0000FF;">GetBytes</span><span style="color: #000000;">&#40;</span>ChatData<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>The above code uses the built-in ASCII encoding capabilities of dot net to convert our string of packet data into an array of bytes which can be transmitted.</p>
<p><strong>Step 5: Implement the Parse operation which reconstructs packets.</strong> The Parse function takes as input a series of bytes and should return the reconstructed packet object.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #008000;">new</span> ChatPacket Parse<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">byte</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> packetData<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            ChatPacket p <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ChatPacket<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">if</span><span style="color: #000000;">&#40;</span>packetData.<span style="color: #0000FF;">Length</span> <span style="color: #008000;">!=</span> <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
                p.<span style="color: #0000FF;">ChatData</span> <span style="color: #008000;">=</span> Encoding.<span style="color: #0000FF;">ASCII</span>.<span style="color: #0000FF;">GetString</span><span style="color: #000000;">&#40;</span>packetData<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
&nbsp;
            <span style="color: #0600FF;">return</span> p<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>As you can see, the above function is fairly simple. It just does the opposite of the ToByteArray function, in that it uses the built-in ASCII Encoding classes to construct a string from bytes rather than deconstruct a string into bytes.</p>
<p>It returns a new packet object.</p>
<h3>Completing the ChatPacket Class</h3>
<p>So what we have done here is to create a class which will our packet class. ChatPacket is a very simple packet class, because the only data that is sent in the packet is the text of the chat message. It is a good idea to keep your packets very simple, so they can be easily and quickly packaged and processed.</p>
<p>In the next portion of this tutorial series, we are going to move on to implement the Server class and program, which is where this all gets interesting!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.daveandrews.org/2009/09/27/chat-clientserver-part-2-packet-extension-and-server/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
