<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" media="screen" href="/styles/xslt/rss.xslt"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:media="http://search.yahoo.com/mrss/" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:c9="http://channel9.msdn.com">
<channel>
	<title>Channel 9</title>
    <atom:link rel="self" type="application/rss+xml" href="http://channel9.msdn.com/Niners/c4f.Jerry-Brunning/Posts/RSS"></atom:link>
    <itunes:summary></itunes:summary>
    <itunes:author>Microsoft</itunes:author>
    <itunes:subtitle></itunes:subtitle>
    <image>
      <url>http://mschnlnine.vo.llnwd.net/d1/Dev/App_Themes/C9/images/feedimage.png</url>
      <title>Channel 9</title>
      <link>http://channel9.msdn.com/Niners/c4f.Jerry-Brunning/Posts</link>
    </image>
    <itunes:image href=""></itunes:image>
    <itunes:category text="Technology"></itunes:category>
    <description>Channel 9 keeps you up to date with the latest news and behind the scenes info from Microsoft that developers love to keep up with. From LINQ to SilverLight – Watch videos and hear about all the cool technologies coming and the people behind them.</description>
    <link>http://channel9.msdn.com/Niners/c4f.Jerry-Brunning/Posts</link>
    <language>en</language>
    <pubDate>Wed, 19 Jun 2013 19:44:37 GMT</pubDate>
    <lastBuildDate>Wed, 19 Jun 2013 19:44:37 GMT</lastBuildDate>
    <generator>Rev9</generator>
    <c9:totalResults>3</c9:totalResults>
    <c9:pageCount>1</c9:pageCount>
    <c9:pageSize>25</c9:pageSize>
  <item>
      <title>Stall Status: Know before you go</title>
      <description><![CDATA[<span id="c4fmetadata">
<table cellspacing="0" cellpadding="1" width="100%" border="0">
<tbody>
<tr class="entry_overview">
<td width="50">&nbsp;<a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8859880/icon.png"><img height="85" alt="icon" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8859880/icon_thumb.png" width="75" border="0"></a>
</td>
<td><span class="entry_description">Stall Status is a Silverlight-based Vista Sidebar Gadget that uses the Z-Wave wireless protocol and door sensors to notify you of the occupied/available state of the bathroom stalls.</span></td>
</tr>
<tr>
<td colspan="2">
<div class="entry_author">Jerry Brunning</div>
<div class="entry_company"><a href="http://www.claritycon.com">Clarity Consulting, Inc</a></div>
<br>
<div class="entry_details"><b>Difficulty: </b><span class="entry_details_input">Easy</span></div>
<div class="entry_details"><b>Time Required:</b> <span class="entry_details_input">
1-3 hours</span></div>
<div class="entry_details"><b>Cost: </b><span class="entry_details_input">$50-$100</span></div>
<div class="entry_details"><b>Software: </b><span class="entry_details_input"><a href="http://www.microsoft.com/express/">Visual C# Express Edition</a></span></div>
<div class="entry_details"><b>Hardware: </b><span class="entry_details_input"><a href="http://www.controlthink.com/zwavesdk.htm">ControlThink Z-Wave SDK</a>,&nbsp;
<a href="http://www.amazon.com/Hawking-HRDS1-HomeRemote-Wireless-Window/dp/B0012W9EUW/ref=sr_1_1?ie=UTF8&amp;s=electronics&amp;qid=1218645148&amp;sr=8-1">
Hawking Technologies Z-Wave HRDS1 door sensor</a></span></div>
<div class="entry_details"><b>Download: </b><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8859880/stallstatus_src.zip">Download</a>
<ul>
</ul>
</div>
</td>
</tr>
</tbody>
</table>
</span>
<h2>Stall Status </h2>
<p>Every now and then someone throws out an idea for a completely off-the-wall application that just has to be built. When Jon Rauschenberger, Clarity’s CTO, came into my office with his “brilliant idea” for a monitoring system to track the “occupied/available”
 state of our washroom stalls, I immediately recognized it as one of those moments. I had been doing some research on the Z-Wave wireless protocol for a client project earlier that week, and I thought “Stall Status” would be a fun way to get some hands on experience
 using Z-Wave.</p>
<p>In this article I will walk you through how to write managed code that interacts with Z-Wave devices. I’ll also show how to use Silverlight 2.0’s access policies to write “connected clients”: client applications that establish a persistent TCP connection
 to a remote server and thereby avoid having to poll the server for status changes. Finally, I’ll walk through the steps necessary to deploy a Silverlight 2.0 application as a Windows Vista Sidebar Gadget.</p>
<h3><b>What is Z-Wave?</b></h3>
<p>Z-Wave is a wireless communication protocol that works over radio frequency and is specifically designed for low-power, low-bandwidth usage scenarios. Typical usage scenarios for Z-Wave devices are monitoring and control applications – such as home automation.
 Available devices include door sensors, switches, and motors. Z-Wave devices are interoperable - devices labeled as Z-Wave compliant should all work together.</p>
<p>A Z-Wave network consists of one or more devices and a centralized controller. A controller can be a standalone (often hand held) hardware unit or a software-based kit. Devices on a Z-Wave network handle the routing of messages automatically without the
 need to set up pre-defined routes. This means that if you have several devices in your network that need to communicate together (e.g. a door sensor and an alarm), the devices can route messages through each other. This “mesh” communication capability allows
 you to extend the range of your network much farther than you would be able to if the devices all required direct connections to each other.&nbsp; For example, if you have three devices, A, B and C, device A can communicate with device C, even if C is outside of
 A's range, by routing its messages through device B.&nbsp; This all works automatically.</p>
<p>My simple Z-Wave network for Stall Status consists of door sensors to notify me when a stall door is opened and closed, and a software based controller. I used Hawking Technologies’ HRDS1 battery powered door sensors for each stall door in the washroom.
 The HRDS1 is considered an “occasionally on” device – it quietly sits in sleep mode until it detects an open/close event from the door. This is the same type of device you would use, for example, when building an alarm system for monitoring windows and doors.&nbsp;
 For the Z-Wave controller I used an excellent software-based controller and SDK from
<a href="http://www.controlthink.com/">ControlThink</a>, which you can purchase for $70. The controller consists of a USB dongle and a set of APIs for connecting to and communicating with devices. ControlThink includes a number of .Net sample applications,
 but be warned that the sample applications are not device specific, and the available devices usually assume you are integrating them into an existing hardware-controlled environment, so the documentation surrounding their usage tends to be sparse.</p>
<p>Using the ControlThink SDK is very straight forward. You simply plug in the USB dongle, reference their DLL from your .Net application, and connect to the controller with a single line of code. Once connected, you can manage your network by adding devices,
 removing devices, iterating the list of devices, etc. </p>
<p>I ended up writing three applications to support Stall Status:</p>
<ol>
<li>An administrative application for adding/removing/listing the Z-Wave devices on my network.&nbsp; This is called StallStatusAdmin.
</li><li>A Windows Service to listen for open/close events from the door sensors and notify any connected client.&nbsp; This is called StallStatusController.
</li><li>A Silverlight 2.0 client application (the end-user interface) that connects to the Windows Service to receive event notifications.&nbsp; This is called StallStatusSilverlight.
</li></ol>
<h3><b>Setting up the Z-Wave network</b></h3>
<p>The administration application is a simple Windows Forms EXE that allows me to manage the network by adding, removing and listing the devices. This is simple to do using the ControlThink SDK – in most cases involving just a couple lines of code. Each Z-Wave
 device has some mechanism to put the device into “programming mode” . The HRDS1 has a button on the back that when pressed, puts the device into programming mode and allows the device to accept programming codes from the controller.</p>
<p>Listing 1 shows how to add a device to the network. Adding a device consists of registering the device with the controller, and then creating a relationship between the controller and the device's association group to enable the device to route messages
 to the controller. Once a device is registered, the controller assigns a unique NodeID that we will use to differentiate the three sensors from each other.</p>
<p><em>C#</em></p>
<pre class="csharpcode">ZWaveController controller = Connect(); 
MessageBox.Show(<span class="str">&quot;After pressing OK, press the \&quot;programming\&quot; button on your device.&quot;</span>);
ZWaveDevice device = controller.AddDevice();
            
device.Groups[1].Clear();
device.Groups[1].Add(controller.Devices.GetByNodeID(controller.NodeID));</pre>
<pre class="csharpcode"><em>VB.Net</em></pre>
<pre class="csharpcode"><span class="kwrd">Dim</span> controller <span class="kwrd">As</span> ZWaveController = Connect()
MessageBox.Show(<span class="str">&quot;After pressing OK, press the &quot;</span><span class="str">&quot;programming&quot;</span><span class="str">&quot; button on your device.&quot;</span>)
<span class="kwrd">Dim</span> device <span class="kwrd">As</span> ZWaveDevice = controller.AddDevice()

device.Groups(1).Clear()
device.Groups(1).Add(controller.Devices.GetByNodeID(controller.NodeID))</pre>
<p><i>Listing 1 – Adding a device to the network.</i></p>
<p>&nbsp;</p>
<p>Getting a list of the registered devices on the network is as easy a iterating through the Devices collection on the controller.</p>
<p><span class="kwrd"><em>C#</em></span></p>
<pre class="csharpcode"><span class="kwrd">string</span> result = <span class="str">&quot;&quot;</span>;
ZWaveController controller = Connect();

<span class="kwrd">if</span> (controller.Devices.Count &gt; 0) {
   <span class="kwrd">foreach</span> (ZWaveDevice d <span class="kwrd">in</span> controller.Devices)    {
    result &#43;= d.GetType().ToString() &#43; <span class="str">&quot; as Node #&quot;</span> &#43; d.NodeID &#43; <span class="str">&quot; PollEnabled = &quot;</span> &#43; d.PollEnabled &#43; <span class="str">&quot;\r\n&quot;</span>;
   }
}
<span class="kwrd">else </span>{
   result = <span class="str">&quot;No devices found on the network&quot;</span>;                
}
MessageBox.Show(result);</pre>
<pre class="csharpcode"><span class="kwrd"><em>VB.Net</em></span></pre>
<pre class="csharpcode"><span class="kwrd">Dim</span> result <span class="kwrd">As</span> <span class="kwrd">String</span> = <span class="str">&quot;&quot;</span>
<span class="kwrd">Dim</span> controller <span class="kwrd">As</span> ZWaveController = Connect()

<span class="kwrd">If</span> controller.Devices.Count &gt; 0 <span class="kwrd">Then</span>
   <span class="kwrd">For</span> <span class="kwrd">Each</span> d <span class="kwrd">As</span> ZWaveDevice <span class="kwrd">In</span> controller.Devices
    result &amp;= d.<span class="kwrd">GetType</span>().ToString() &amp; <span class="str">&quot; as Node #&quot;</span> &amp; d.NodeID &amp; <span class="str">&quot; PollEnabled = &quot;</span> &amp; d.PollEnabled &amp; Constants.vbCrLf
   <span class="kwrd">Next</span> d
<span class="kwrd">Else</span>
   result = <span class="str">&quot;No devices found on the network&quot;</span>
<span class="kwrd">End</span> <span class="kwrd">If</span>
MessageBox.Show(result)</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><i>Listing 2 – Listing the devices in the network.</i></p>
<p><b></b></p>
<h3><b></b></h3>
<h3><b></b></h3>
<h3><b>Receiving Z-Wave Events</b></h3>
<p>Once the devices are registered on the network, they will send event notifications back to the controller each time the sensor is triggered. The next steps for us are to write code to receive the events and forward them to any client applications that are
 connected. To do this we’ll write a Windows Service that listens for events from the sensors.</p>
<p>All of the work for listening for events from the Z-Wave devices is handled for us by the ControlThink SDK. We simply connect to the controller and sink the LevelChanged event. We do this in our Run method, which is called from within our service’s OnStart
 function.</p>
<pre class="csharpcode"><span class="kwrd"><em>C#</em></span></pre>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> Run() {
   <span class="kwrd">try</span>  {
       _controller = <span class="kwrd">new</span> ZWaveController();
       <span class="kwrd">try</span>  {
          _controller.Connect();
       }
       <span class="kwrd">catch</span> (Exception ex) {
          <span class="kwrd">throw</span> <span class="kwrd">new</span> Exception(<span class="str">&quot;Unable to connect.\r\n&quot;</span> &#43; ex.ToString());
       }

       _controller.LevelChanged &#43;= <span class="kwrd">new</span> ZWaveController.LevelChangedEventHandler(_controller_LevelChanged);

       _policyListener = <span class="kwrd">new</span> PolicyListener();
       _listener = <span class="kwrd">new</span> SocketListener();
       _listener.Port = 4530;
             
        <span class="kwrd">new</span> System.Threading.Thread(<span class="kwrd">new</span> System.Threading.ThreadStart(_listener.StartSocketServer)).Start();
        <span class="kwrd">new</span> System.Threading.Thread(<span class="kwrd">new</span> System.Threading.ThreadStart(_policyListener.StartSocketServer)).Start();
        <span class="kwrd">new</span> System.Threading.Thread(<span class="kwrd">new</span> System.Threading.ThreadStart(ClearRecent)).Start();
   }
   <span class="kwrd">catch</span> (Exception ex) {
       Logger.WriteException(ex);
   }
}</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style><style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><em>VB.Net</em></p>
<pre class="csharpcode"><span class="kwrd">Public</span> <span class="kwrd">Sub</span> Run()
   <span class="kwrd">Try</span>
       _controller = <span class="kwrd">New</span> ZWaveController()
       <span class="kwrd">Try</span>
          _controller.Connect()
       <span class="kwrd">Catch</span> ex <span class="kwrd">As</span> Exception
          <span class="kwrd">Throw</span> <span class="kwrd">New</span> Exception(<span class="str">&quot;Unable to connect.&quot;</span> &amp; Constants.vbCrLf &amp; ex.ToString())
       <span class="kwrd">End</span> <span class="kwrd">Try</span>

       <span class="kwrd">AddHandler</span> _controller.LevelChanged, <span class="kwrd">AddressOf</span> _controller_LevelChanged

       _policyListener = <span class="kwrd">New</span> PolicyListener()
       _listener = <span class="kwrd">New</span> SocketListener()
       _listener.Port = 4530

        <span class="kwrd">CType</span>(<span class="kwrd">New</span> System.Threading.Thread(<span class="kwrd">New</span> System.Threading.ThreadStart(<span class="kwrd">AddressOf</span> _listener.StartSocketServer)), System.Threading.Thread).Start()
        <span class="kwrd">CType</span>(<span class="kwrd">New</span> System.Threading.Thread(<span class="kwrd">New</span> System.Threading.ThreadStart(<span class="kwrd">AddressOf</span> _policyListener.StartSocketServer)), System.Threading.Thread).Start()
        <span class="kwrd">CType</span>(<span class="kwrd">New</span> System.Threading.Thread(<span class="kwrd">New</span> System.Threading.ThreadStart(<span class="kwrd">AddressOf</span> ClearRecent)), System.Threading.Thread).Start()
   <span class="kwrd">Catch</span> ex <span class="kwrd">As</span> Exception
       Logger.WriteException(ex)
   <span class="kwrd">End</span> <span class="kwrd">Try</span>
<span class="kwrd">End</span> Sub</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><i>Listing 3 – Listening for Z-Wave events when our service starts up.</i></p>
<p>&nbsp;</p>
<p>In addition to listening for events from the ZWave Controller, our Run method also sets up socket listeners for talking to the Silverlight client application, which we will talk about later. An important detail to note, however, is the use of threading in
 the Run method. Remember that this is called directly from our service’s OnStart code which we should not block - if you block OnStart, you’ll see the service stuck at “Starting...” in the Service Control Manager. Anything that will block or that is long running
 (such as a socket listener) needs to run on a separate thread.</p>
<p>When the controller detects that one of the sensors has changed its state, it throws the LevelChanged event to our service. Our service handles LevelChanged in the _controller_LevelChanged method. The signature for the LevelChanged event looks like this:</p>
<blockquote>
<pre class="csharpcode"><span class="kwrd">void</span> _controller_LevelChanged(<span class="kwrd">object</span> sender, ZWaveController.LevelChangedEventArgs e)</pre>
</blockquote>
<p>The LevelChangeEventArgs contains the original device that raised the event. We have three door sensors connected to our network. When any of them are triggered, LevelChanged is raised and we can inspect the LevelChangedEventArgs to get the NodeID of the
 unique identifier of the device. That’s all there is to interacting with the Z-Wave network.</p>
<h2>Silverlight 2.0</h2>
<p>Now that we’ve got the server infrastructure set up it is time to build a client application so we can actually start using Stall Status. I built the client application in Silverlight as an exercise to show how to use Silverlight 2.0’s access policy to make
 cross domain network calls from a Silverlight client application. I also knew that it is simple to deploy a Silverlight application as a Windows Vista Gadget, and the Sidebar was to be my preferred deployment model for the application.</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8859880/StallStatus2.png"><img height="149" alt="StallStatus2" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8859880/StallStatus2_thumb.png" width="131" border="0"></a>
</p>
<p><i>Figure 1 – Stall Status interface</i></p>
<p>The main UI for the application is pretty simple – three ellipses, one for each stall, colored green if the stall is available and red if the stall is occupied. Most of the challenge with building the client piece has to do with connecting to the service
 and listening for updates. To do this, we create a persistent TCP connection and wait for data to be sent from the service over the socket. This is much better than a polling approach for an application like this because of the way the Z-Wave door sensors
 work. They are in sleep mode most of the time, and are only using power when they transmit a signal due to the door opening or closing. If we polled the devices frequently, it would kill the batteries in the device. Also, most of the time there is no change
 to the state of the doors, so polling would really be a waste.</p>
<p>Silverlight contains certain security mechanisms around network connectivity, especially TCP sockets. This is due to the fact that a Silverlight application runs in the context of the user’s browser, so special controls need to be in place to limit the type
 of connectivity that Silverlight applications can initiate. For socket-based connections, Silverlight 2.0 requires an access policy to be in place on the target server. This access policy essentially is a challenge/response mechanism that prevents a Silverlight
 application from connecting to an arbitrary server, potentially masquerading as the end user.</p>
<h3>Access Policy</h3>
<p>An Access Policy must be in place on the server for in order to enable a Silverlight 2.0 client to connect using sockets. The Silverlight framework handles all of the validation for the presence of the access policy, so your client application does not need
 to do anything. However, if the proper policy is not in place on the target server, Silverlight will throw an Access Denied exception, so your client application should be prepared to handle this situation. This is all very similar to how network access in
 Flash applications work. In fact, Silverlight can consume Flash policy files directly, as well as Silverlight policy files. In the Stall Status application, we’re going to be using Silverlight policy.</p>
<p>When a Silverlight application attempts to open a socket to a target server, Silverlight will automatically look for an access policy on the server by establishing a TCP connection over port 943, and sending a policy request. The policy request is simply
 an XML-style string: &lt;policy-file-request/&gt;. It is up to the author of the service that is receiving the request to ensure that they properly respond to this request, or else Silverlight will raise an exception on the client. All of this is described in detail
 in the <a href="http://msdn.microsoft.com/en-us/library/cc645032(VS.95).aspx">MSDN documentation</a> on the new network security restrictions in Silverlight 2.0.</p>
<p>In order to respond to a request for an access policy on our server, we need to implement a network listener on port 943 that responds to Silverlight’s policy file request.
<a href="http://weblogs.asp.net/dwahlin/archive/2008/04/10/pushing-data-to-a-silverlight-client-with-sockets-part-i.aspx">
Dan Wahlin</a> wrote a multi-part blog post showing exactly how to do this, and the listener I used for Stall Status, plus much of the other socket code, is copied from his example. I recommend reading his post - it is a great primer on writing TCP socket clients
 in Silverlight 2.0.</p>
<p>Our listener class run in our windows service and simply sets up a listener on port 943. When it receives a policy file request, it returns the appropriate response, as shown below.</p>
<blockquote>
<pre class="csharpcode"><span class="kwrd">&lt;?</span><span class="html">xml</span> <span class="attr">version</span><span class="kwrd">=&quot;1.0&quot;</span> <span class="attr">encoding</span> <span class="kwrd">=&quot;utf-8&quot;</span>?<span class="kwrd">&gt;</span>
<span class="kwrd">&lt;</span><span class="html">access-policy</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">cross-domain-access</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">policy</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">allow-from</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">domain</span> <span class="attr">uri</span><span class="kwrd">=&quot;*&quot;</span> <span class="kwrd">/&gt;</span>
      <span class="kwrd">&lt;/</span><span class="html">allow-from</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">grant-to</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">socket-resource</span> <span class="attr">port</span><span class="kwrd">=&quot;4530&quot;</span> <span class="attr">protocol</span><span class="kwrd">=&quot;tcp&quot;</span> <span class="kwrd">/&gt;</span>
      <span class="kwrd">&lt;/</span><span class="html">grant-to</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">policy</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">cross-domain-access</span><span class="kwrd">&gt;</span>
 <span class="kwrd">&lt;/</span><span class="html">access-policy</span><span class="kwrd">&gt;</span></pre>
</blockquote>
<p>This response tells Silverlight to allow incoming connections to port 4530, which is the port that our service is listening on to accept connections from our Silverlight client.</p>
<p>Why is this important? Well, without access policy in place, there is nothing that prevents a malicious Silverlight application from connecting to a server without permission. For example:</p>
<ul>
<li>Suppose you have an active session with your online bank. A malicious Silverlight application served up from Site A could attempt to connect to your bank using your existing login token (which may be stored as a cookie). With access policy in place, your
 bank would need to have a policy stating that it allowed Silverlight applications originating from Site A to connect to your bank.
</li><li>Suppose you connect to Site A and download a malicious Silverlight application. The application can potentially connect to your corporate intranet and because you are on a corporate domain, the Silverlight app impersonates you. With the access policy rules
 in place, this would be prevented. </li></ul>
<h3>Persistent client connections</h3>
<p>Now that we’ve got our access policy in place, we’re ready to code up our Silverlight client to connect to our server and wait for updates. Silverlight 2.0 can only connect using sockets over the port range 4502-4534. Our Windows Service uses 4530. It creates
 a listener on this port and then sits and waits for connections from our Silverlight clients.</p>
<p>C#</p>
<pre class="csharpcode">_listener = <span class="kwrd">new</span> TcpListener(IPAddress.Any, Port);
_listener.Start();
<span class="kwrd">while</span> (<span class="kwrd">true</span>)
{
   _waitEvent.Reset();
   _listener.BeginAcceptTcpClient(<span class="kwrd">new</span> AsyncCallback(OnBeginAccept), <span class="kwrd">null</span>);
   _waitEvent.WaitOne();
}</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><em>VB.Net</em></p>
<pre class="csharpcode">_listener = <span class="kwrd">New</span> TcpListener(IPAddress.Any, Port)
_listener.Start()
<span class="kwrd">Do</span>
   _waitEvent.Reset()
   _listener.BeginAcceptTcpClient(<span class="kwrd">New</span> AsyncCallback(<span class="kwrd">AddressOf</span> OnBeginAccept), <span class="kwrd">Nothing</span>)
   _waitEvent.WaitOne()
Loop</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><i>Listing 4 – Our main listener for client connections</i></p>
<p>&nbsp;</p>
<p>We’re using asynchronous sockets, so we’ve set up a delegate – OnBeginAccept – to accept and process our connections. The code to process the connects is listed below.</p>
<p><em>C#</em></p>
<pre class="csharpcode">_waitEvent.Set();
TcpListener listener = _listener;
TcpClient client = listener.EndAcceptTcpClient(ar);

<span class="kwrd">if</span> (client.Connected)
{
   Logger.WriteLine(<span class="str">&quot;Accepted a connection from &quot;</span> &#43; client.Client.RemoteEndPoint.ToString());

   StreamWriter writer = <span class="kwrd">new</span> StreamWriter(client.GetStream());
   writer.AutoFlush = <span class="kwrd">true</span>;
   _clients.Add(writer);
   writer.WriteLine(<span class="str">&quot;Connected.&quot;</span>);

   <span class="kwrd">if</span> (ClientConnected != <span class="kwrd">null</span>)
   {
     ClientConnected(<span class="kwrd">this</span>, <span class="kwrd">null</span>);
   }
}</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p><em>VB.Net</em></p>
<pre class="csharpcode">_waitEvent.<span class="kwrd">Set</span>()
<span class="kwrd">Dim</span> listener <span class="kwrd">As</span> TcpListener = _listener
<span class="kwrd">Dim</span> client <span class="kwrd">As</span> TcpClient = listener.EndAcceptTcpClient(ar)

<span class="kwrd">If</span> client.Connected <span class="kwrd">Then</span>
   Logger.WriteLine(<span class="str">&quot;Accepted a connection from &quot;</span> &amp; client.Client.RemoteEndPoint.ToString())

   <span class="kwrd">Dim</span> writer <span class="kwrd">As</span> <span class="kwrd">New</span> StreamWriter(client.GetStream())
   writer.AutoFlush = <span class="kwrd">True</span>
   _clients.Add(writer)
   writer.WriteLine(<span class="str">&quot;Connected.&quot;</span>)

   <span class="kwrd">If</span> ClientConnected IsNot <span class="kwrd">Nothing</span> <span class="kwrd">Then</span>
     ClientConnected(<span class="kwrd">Me</span>, <span class="kwrd">Nothing</span>)
   <span class="kwrd">End</span> <span class="kwrd">If</span>
<span class="kwrd">End</span> If</pre>
<p><i>Listing 5 – Accepting a new client connection</i></p>
<p>&nbsp;</p>
<p>Here we are simply adding a StreamWriter for each connected client to a List. We do this so when we receive events from the door sensors, we can loop through this List and notify all of the clients. We notify them by writing a tokenized string to the StreamWriter.
 We also have code to remove any clients from the list if we fail to write to their stream. This way we can catch the situation where the client disconnected.</p>
<pre class="csharpcode"><span class="kwrd"><em>C#</em></span></pre>
<pre class="csharpcode"><span class="kwrd">for</span> (<span class="kwrd">int</span> i=_clients.Count-1;i&gt;=0;i--)
{
   <span class="kwrd">try</span>
   {
      _clients[i].WriteLine(eventText);
   }
   <span class="kwrd">catch</span> (Exception ex)
   {
      Logger.WriteException(ex);
      Logger.WriteLine(<span class="str">&quot;Removing client # &quot;</span> &#43; i &#43; <span class="str">&quot; because we failed to send them data.&quot;</span>);
      _clients.Remove(_clients[i]);
   }
}</pre>
<p><em>VB.Net</em></p>
<pre class="csharpcode"><span class="kwrd">For</span> i <span class="kwrd">As</span> <span class="kwrd">Integer</span> = _clients.Count-1 <span class="kwrd">To</span> 0 <span class="kwrd">Step</span> -1
   <span class="kwrd">Try</span>
      _clients(i).WriteLine(eventText)
   <span class="kwrd">Catch</span> ex <span class="kwrd">As</span> Exception
      Logger.WriteException(ex)
      Logger.WriteLine(<span class="str">&quot;Removing client # &quot;</span> &amp; i &amp; <span class="str">&quot; because we failed to send them data.&quot;</span>)
      _clients.Remove(_clients(i))
   <span class="kwrd">End</span> <span class="kwrd">Try</span>
<span class="kwrd">Next</span> i</pre>
<p><i>Listing 6 – Sending an update to all clients</i></p>
<p>&nbsp;</p>
<p>The text we pass to each client (represented in the code above by the eventText variable) is simply the NodeID of the sensor that triggered the event and the state (open/closed) on the sensor. The Silverlight client receives this text, parses it out, and
 updates the color of the ellipse accordingly.</p>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style><style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<pre class="csharpcode"><span class="kwrd"><em>C#</em></span></pre>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> UpdateText(<span class="kwrd">string</span> text)
{
    <span class="kwrd">string</span>[] parts = text.Split(<span class="str">' '</span>);

    <span class="kwrd">if</span> (parts.Length != 2) {
        <span class="kwrd">return</span>;
    }

    <span class="kwrd">int</span> stallNumber = Convert.ToInt32(parts[0]);
    <span class="kwrd">string</span> status = parts[1].ToLower();

    StatusIndicator thisStall = <span class="kwrd">null</span>;
    <span class="kwrd">switch</span> (stallNumber) {
        <span class="kwrd">case</span> 1:
            thisStall = <span class="kwrd">this</span>.Stall1;
            <span class="kwrd">break</span>;
        <span class="kwrd">case</span> 2:
            thisStall = <span class="kwrd">this</span>.Stall2;
            <span class="kwrd">break</span>;
        <span class="kwrd">default</span>:
            thisStall = <span class="kwrd">this</span>.Stall3;
            <span class="kwrd">break</span>;
    }

    <span class="kwrd">if</span> (status.Trim() == <span class="str">&quot;open&quot;</span>) {
        thisStall.Status = StallStatus.Open;
    }
    <span class="kwrd">else</span> <span class="kwrd">if</span> (status.Trim() == <span class="str">&quot;closed&quot;</span>) {
        thisStall.Status = StallStatus.Closed;
    }
    <span class="kwrd">else</span> <span class="kwrd">if</span> (status.Trim() == <span class="str">&quot;recent&quot;</span>) {
        thisStall.Status = StallStatus.Recent;
    }
    <span class="kwrd">else</span> {
        thisStall.Status = StallStatus.Unknown;
    }
}</pre>
<pre class="csharpcode"><em>VB.Net</em></pre>
<pre class="csharpcode"><span class="kwrd">Private</span> <span class="kwrd">Sub</span> UpdateText(<span class="kwrd">ByVal</span> text <span class="kwrd">As</span> <span class="kwrd">String</span>)
    <span class="kwrd">Dim</span> parts() <span class="kwrd">As</span> <span class="kwrd">String</span> = text.Split(<span class="str">&quot; &quot;</span>c)

    <span class="kwrd">If</span> parts.Length &lt;&gt; 2 <span class="kwrd">Then</span>
        <span class="kwrd">Return</span>
    <span class="kwrd">End</span> <span class="kwrd">If</span>

    <span class="kwrd">Dim</span> stallNumber <span class="kwrd">As</span> <span class="kwrd">Integer</span> = Convert.ToInt32(parts(0))
    <span class="kwrd">Dim</span> status <span class="kwrd">As</span> <span class="kwrd">String</span> = parts(1).ToLower()

    <span class="kwrd">Dim</span> thisStall <span class="kwrd">As</span> StatusIndicator = <span class="kwrd">Nothing</span>
    <span class="kwrd">Select</span> <span class="kwrd">Case</span> stallNumber
        <span class="kwrd">Case</span> 1
            thisStall = <span class="kwrd">Me</span>.Stall1
        <span class="kwrd">Case</span> 2
            thisStall = <span class="kwrd">Me</span>.Stall2
        <span class="kwrd">Case</span> <span class="kwrd">Else</span>
            thisStall = <span class="kwrd">Me</span>.Stall3
    <span class="kwrd">End</span> <span class="kwrd">Select</span>

    <span class="kwrd">If</span> status.Trim() = <span class="str">&quot;open&quot;</span> <span class="kwrd">Then</span>
        thisStall.Status = StallStatus.Open
    <span class="kwrd">ElseIf</span> status.Trim() = <span class="str">&quot;closed&quot;</span> <span class="kwrd">Then</span>
        thisStall.Status = StallStatus.Closed
    <span class="kwrd">ElseIf</span> status.Trim() = <span class="str">&quot;recent&quot;</span> <span class="kwrd">Then</span>
        thisStall.Status = StallStatus.Recent
    <span class="kwrd">Else</span>
        thisStall.Status = StallStatus.Unknown
    <span class="kwrd">End</span> <span class="kwrd">If</span>
<span class="kwrd">End</span> Sub</pre>
<p><i>Listing 7 – Receiving the update on the client from the server</i></p>
<p>&nbsp;</p>
<p>The only other thing the application contains is the concept of &quot;recently occupied&quot;. Once a stall has been vacated, we track it as recently occupied. This shows up on the client application as a yellow ellipse. To do this we keep track of a timestamp whenever
 the door opens.&nbsp; Our Service contains a dedicated thread that checks for doors opened more than 2 minutes ago. If it finds any, it changes the door's status from “Recent” to a status of “Opened”.</p>
<pre class="csharpcode"><span class="kwrd"><em>C#</em></span></pre>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> ClearRecent()
{
  <span class="kwrd">while</span> (!_wait.WaitOne(10000,<span class="kwrd">false</span>))
  {
    var q = from stall <span class="kwrd">in</span> _stalls
      <span class="kwrd">where</span> stall.Timestamp.AddMinutes(2) &lt; DateTime.Now &amp;&amp; stall.State.Equals(DoorState.Recent)
      select stall;

    <span class="kwrd">foreach</span> (Stall stall <span class="kwrd">in</span> q)
    {
      <span class="kwrd">if</span> (stall.State.Equals(DoorState.Recent)) {
        stall.State = DoorState.Open;
        Broadcast(stall.NodeID, DoorState.Open);
      }
    }
  }
}</pre>
<pre class="csharpcode"><em>VB.Net</em></pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<pre class="csharpcode"><span class="kwrd">Private</span> <span class="kwrd">Sub</span> ClearRecent()
  <span class="kwrd">Do</span> <span class="kwrd">While</span> <span class="kwrd">Not</span> _wait.WaitOne(10000,<span class="kwrd">False</span>)
    <span class="kwrd">Dim</span> q = From stall <span class="kwrd">In</span> _stalls _
            Where stall.Timestamp.AddMinutes(2) &lt; DateTime.Now <span class="kwrd">AndAlso</span> stall.State.Equals(DoorState.Recent) _
            <span class="kwrd">Select</span> stall

    <span class="kwrd">For</span> <span class="kwrd">Each</span> stall <span class="kwrd">As</span> Stall <span class="kwrd">In</span> q
      <span class="kwrd">If</span> stall.State.Equals(DoorState.Recent) <span class="kwrd">Then</span>
        stall.State = DoorState.Open
        Broadcast(stall.NodeID, DoorState.Open)
      <span class="kwrd">End</span> <span class="kwrd">If</span>
    <span class="kwrd">Next</span> stall
  <span class="kwrd">Loop</span>
<span class="kwrd">End</span> Sub</pre>
<p><i>Listing 8 – Clearing the “recently opened” flag</i></p>
<h2><b></b></h2>
<h2><b>Vista Sidebar Gadget</b></h2>
<p>Once I had the Service and Silverlight client apps written, it was time to deploy the client as a Vista Sidebar Gadget. This is actually pretty simple to do with a Silverlight application, but there are a couple things to work through for 64-bit versions
 of Vista.</p>
<p>Packaging a Silverlight application to run as a Gadget is not that different than running it locally or via a web page. You simple collect all of the files for your application, add a manifest file, zip them up, and rename the ZIP file so it has a .gadget
 file extension.</p>
<p>One easy way to create the manifest file is to start from an existing file from one of your existing gadgets. You can find your installed gadgets in the folder \Users\&lt;user name&gt;\AppData\Local\Microsoft\Windows Sidebar\Gadgets. Note that by default the AppData
 folder is hidden. Check the folders of any of your gadgets and you’ll see that they all contain an gadget.xml file. Copy one of these, open it, and make any changes that you need to. Most of the elements in the file are self explanatory, but for a full explanation,
 check out <a href="http://www.microsoft.com/technet/scriptcenter/topics/vista/gadgets-pt1.mspx#ENH">
this article</a>.</p>
<p>Once you’ve got your files and manifest packaged up, you can distribute your gadget. Users can run .gadget files directly in Vista and Vista automatically installs them into the sidebar.</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8859880/StallStatusGadget2.png"><img height="244" alt="StallStatusGadget2" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8859880/StallStatusGadget2_thumb.png" width="164" border="0"></a>
</p>
<p><i>Figure 2 – Stall Status deployed as a Vista Sidebar gadget</i></p>
<p>One note with Silverlight-based gadgets and the 64-bit version of Windows Vista: Since Silverlight is a 32-bit application, you cannot directly host Silverlight-based gadgets in the 64-bit version of Sidebar.exe (which is the running by default on 64-bit
 Vista). As a work around, you can run the 32-bit version of Sidebar.exe, which is located in the \Program Files (x86)\Windows Sidebar\ folder.</p>
<p>As we’ve seen in this article it is easy to use .Net to control a Z-Wave network, and there are tons of creative uses for the technology. Writing network-enabled Silverlight applications has become much more powerful in Silverlight 2.0. And deploying Silverlight-based
 applications as Vista Sidebar Gadgets is pretty simple.</p>
<p></p>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style><style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style><style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style><style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style><style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style> <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Jerry-Brunning/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:e26739758487407580bc9e7600ceb34b">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Stall-Status-Know-before-you-go</comments>
      <itunes:summary>



&amp;nbsp;

Stall Status is a Silverlight-based Vista Sidebar Gadget that uses the Z-Wave wireless protocol and door sensors to notify you of the occupied/available state of the bathroom stalls.



Jerry Brunning
Clarity Consulting, Inc

Difficulty: Easy
Time Required: 
1-3 hours
Cost: $50-$100
Software: Visual C# Express Edition
Hardware: ControlThink Z-Wave SDK,&amp;nbsp;

Hawking Technologies Z-Wave HRDS1 door sensor
Download: Download








Stall Status 
Every now and then someone throws out an idea for a completely off-the-wall application that just has to be built. When Jon Rauschenberger, Clarity’s CTO, came into my office with his “brilliant idea” for a monitoring system to track the “occupied/available”
 state of our washroom stalls, I immediately recognized it as one of those moments. I had been doing some research on the Z-Wave wireless protocol for a client project earlier that week, and I thought “Stall Status” would be a fun way to get some hands on experience
 using Z-Wave. 
In this article I will walk you through how to write managed code that interacts with Z-Wave devices. I’ll also show how to use Silverlight 2.0’s access policies to write “connected clients”: client applications that establish a persistent TCP connection
 to a remote server and thereby avoid having to poll the server for status changes. Finally, I’ll walk through the steps necessary to deploy a Silverlight 2.0 application as a Windows Vista Sidebar Gadget. 
What is Z-Wave?
Z-Wave is a wireless communication protocol that works over radio frequency and is specifically designed for low-power, low-bandwidth usage scenarios. Typical usage scenarios for Z-Wave devices are monitoring and control applications – such as home automation.
 Available devices include door sensors, switches, and motors. Z-Wave devices are interoperable - devices labeled as Z-Wave compliant should all work together. 
A Z-Wave network consists of one or more devices and a centralized controller. A controller can b</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Stall-Status-Know-before-you-go</link>
      <pubDate>Wed, 13 Aug 2008 15:03:27 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Stall-Status-Know-before-you-go</guid>      
      <dc:creator>Jerry Brunning</dc:creator>
      <itunes:author>Jerry Brunning</itunes:author>
      <slash:comments>1</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Stall-Status-Know-before-you-go/RSS</wfw:commentRss>
      <category>utility</category>
      <category>Home Automation</category>
    </item>
  <item>
      <title>Bluetooth ScreenLock</title>
      <description><![CDATA[ <table width="100%" border="0" cellspacing="0" cellpadding="1"><tbody><tr class="entry_overview"><td width="50">&nbsp;</td><td><span class="entry_description">Bluetooth ScreenLock is a sample application built on top of the Bluetooth managed wrappers that are included in the Coding4Fun Developer Toolkit.</span></td></tr><tr><td colspan="2"><div class="entry_author">Jerry Brunning</div><div class="entry_company"><a href="http://www.claritycon.com">Clarity Consulting, Inc.</a></div><br><div class="entry_details"><strong>Difficulty: </strong><span class="entry_details_input">Easy</span></div><div class="entry_details"><strong>Time Required:</strong> <span class="entry_details_input">1-3 hours</span></div><div class="entry_details"><strong>Cost: </strong><span class="entry_details_input">Free</span></div><div class="entry_details"><strong>Software: </strong><span class="entry_details_input"><a href="http://msdn2.microsoft.com/en-us/express/default.aspx">Visual Studio 2008 Express Editions Beta 2</a>, <a href="http://www.codeplex.com/C4FDevKit">Coding4Fun Developer Toolkit</a><a> (Bluetooth assemblies) </a></span></div><div class="entry_details"><strong>Hardware: </strong><span class="entry_details_input">Bluetooth-enabled laptop and phone.</span></div><div class="entry_details"><strong>Download: </strong><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/4474153/screenlock.zip">Download</a></div></td></tr></tbody></table><p>The <a href="http://www.codeplex.com/C4FDevKit">Coding4Fun Developer Kit</a> that was released to CodePlex last month contains a bunch of neat libraries and components for jumpstarting development against some of the new features of Vista. Included in the kit is a managed wrapper around Bluetooth communication that is designed to run in non-mobile environments – something that has not previously been widely available. With most newer laptops shipping with Bluetooth radios, and the proliferation of Bluetooth devices and receivers, I looked forward to trying this out. To get familiar with the managed wrappers, I built a simple screen locking application that I call Bluetooth Screenlock. The Bluetooth ScreenLock application runs on your PC, connects to your phone, and when it detects that you've walked out of range, locks your workstation. Using the Bluetooth wrappers included in the Coding4Fun Developer Toolkit makes this pretty simple.</p><h3>Bluetooth Profiles</h3><p>The managed Bluetooth wrapper classes that are part of the Coding4Fun Developer Kit (C4F Kit) contain libraries for connecting to three different Bluetooth profiles: Serial Port, File Transfer and Object Push. A profile is a standardized interface specification that devices comply to in order to communicate with each other. For the Bluetooth ScreenLock application I used the Serial Port profile to establish a connection and then send heartbeat messages across the Bluetooth channel periodically. If any heartbeat were to fail, the program will lock the user's workstation.</p><h3>Discovery and Pairing</h3><p>Discovery is the process of detecting nearby Bluetooth devices and potentially asking them to enumerate their supported services. In order to discover a device and enumerate its services, one of two things must happen: The phone must be set to discovery mode, which enables any other Bluetooth device to see it, or the two devices must be paired. Note for security reasons you generally don't want to leave your phone set up as discoverable.</p><p>Pairing is the process of establishing a trust relationship between two devices. Pairing usually involves the exchange of a key pair – a pin-like series of digits that must be entered on both devices before the trust relationship is established. In order to use the Bluetooth ScreenLock application you must pair your phone to your PC. You can start this from the PC, or from your phone. In Vista you can start the pairing process by opening the Bluetooth Devices utility and clicking the Add button on the Devices tab (see Figure 1).&nbsp; Note that I built and tested the application with a Motorola Q smartphone.</p><p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/4474153/BluetoothDevices2.jpg"><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/4474153/BluetoothDevices_thumb.jpg" alt="" width="373" height="480" border="0"></a></p><p><em>Figure 1 - The Bluetooth Devices utility in Vista</em></p><p>Once you've paired your phone to your PC, you can use the application. I decided to build the application as a Windows Forms application, but it just as easily could have been a Windows Service set to start automatically. The form is simple – just a combo box listing nearby devices and a button to enable the ScreenLock feature. It would be&nbsp;a pretty easy exercise to configure the application to automatically enable itself at Windows startup.</p><p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/4474153/ScreenLock6.jpg"><img src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/4474153/ScreenLock_thumb2.jpg" alt="" width="300" height="160" border="0"></a></p><p><em>Figure 2 - The ScreenLock window</em></p><h3>Connecting to a device</h3><p>The code for the ScreenLock application uses just two of the functions in the C4F toolkit – DiscoverDeviceByName and DiscoverServicesByType. DiscoverDeviceByName is used to get an instance of a Device, which is&nbsp;a managed class exposed through the C4F.DevKit.Bluetooth.DeviceAndServiceDiscovery assembly.</p><p><strong>C#</strong></p><pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">bool</span> DiscoverDevice(<span class="kwrd">string</span> deviceName){    <span class="kwrd">bool</span> returnValue = <span class="kwrd">false</span>;    <span class="kwrd">try</span>    {        DeviceServicesManager _manager = <span class="kwrd">new</span> DeviceServicesManager();        SelectedDevice = _manager.DiscoverDeviceByName(deviceName);        <span class="kwrd">if</span> (SelectedDevice != <span class="kwrd">null</span>)        {            returnValue = <span class="kwrd">true</span>;        }    }    <span class="kwrd">catch</span> (Exception ex)    {        <span class="kwrd">throw</span> <span class="kwrd">new</span> Exception(<span class="str">&quot;An unexpected error was raised during device discovery.&quot;</span> &#43; Environment.NewLine &#43; ex.Message);    }    <span class="kwrd">return</span> returnValue;} </pre><p><strong>VB.Net</strong></p><pre class="csharpcode"><span class="kwrd">Public</span> <span class="kwrd">Function</span> DiscoverDevice(<span class="kwrd">ByVal</span> deviceName <span class="kwrd">As</span> <span class="kwrd">String</span>) <span class="kwrd">As</span> <span class="kwrd">Boolean</span>    <span class="kwrd">Dim</span> returnValue <span class="kwrd">As</span> <span class="kwrd">Boolean</span> = <span class="kwrd">False</span>    <span class="kwrd">Try</span>        <span class="kwrd">Dim</span> _manager <span class="kwrd">As</span> DeviceServicesManager = <span class="kwrd">New</span> DeviceServicesManager()        SelectedDevice = _manager.DiscoverDeviceByName(deviceName)        <span class="kwrd">If</span> <span class="kwrd">Not</span> SelectedDevice <span class="kwrd">Is</span> <span class="kwrd">Nothing</span> <span class="kwrd">Then</span>            returnValue = <span class="kwrd">True</span>        <span class="kwrd">End</span> <span class="kwrd">If</span>    <span class="kwrd">Catch</span> ex <span class="kwrd">As</span> Exception        <span class="kwrd">Throw</span> <span class="kwrd">New</span> Exception(<span class="str">&quot;An unexpected error was raised during device discovery.&quot;</span> &amp; Environment.NewLine &amp; ex.Message)    <span class="kwrd">End</span> <span class="kwrd">Try</span>    <span class="kwrd">Return</span> returnValue <span class="kwrd">End</span> <span class="kwrd">Function</span></pre><pre class="csharpcode">&nbsp;</pre><p>Once you have an instance of a Device, you can get a handle to the serial port service by calling DiscoverServicesByType.&nbsp; After that you could connect directly to the service on the device:</p><p><strong>C#</strong></p><pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">bool</span> Connect(){    <span class="kwrd">bool</span> returnValue = <span class="kwrd">false</span>;    List&lt;RemoteService&gt; serviceList = _manager.DiscoverServicesByType(SelectedDevice, ServiceType.SerialPortProfile);    RemoteService remoteService = <span class="kwrd">null</span>;    <span class="kwrd">try</span>    {        remoteService = serviceList[0];        _stream = remoteService.Connect();        _connectedService = remoteService;        returnValue = <span class="kwrd">true</span>;    }    <span class="kwrd">catch</span> (ServiceConnectionException servEx)    {        <span class="kwrd">throw</span> <span class="kwrd">new</span> Exception(<span class="str">&quot;An error occurred while trying to connect to &quot;</span> &#43; remoteService.Name &#43; Environment.NewLine &#43; <span class="str">&quot;Error Details: &quot;</span> &#43; servEx.Message);    }    <span class="kwrd">catch</span>    {        <span class="kwrd">throw</span>;    }    <span class="kwrd">return</span> returnValue;}</pre><pre class="csharpcode"><strong>VB.Net</strong></pre><pre class="csharpcode"><span class="kwrd">Public</span> <span class="kwrd">Function</span> Connect() <span class="kwrd">As</span> <span class="kwrd">Boolean</span>    <span class="kwrd">Dim</span> returnValue <span class="kwrd">As</span> <span class="kwrd">Boolean</span> = <span class="kwrd">False</span>    <span class="kwrd">Dim</span> serviceList <span class="kwrd">As</span> List(Of RemoteService) = _manager.DiscoverServicesByType(SelectedDevice, ServiceType.SerialPortProfile)    <span class="kwrd">Dim</span> remoteService <span class="kwrd">As</span> RemoteService = <span class="kwrd">Nothing</span>    <span class="kwrd">Try</span>        remoteService = serviceList(0)        _stream = remoteService.Connect()        _connectedService = remoteService        returnValue = <span class="kwrd">True</span>    <span class="kwrd">Catch</span> servEx <span class="kwrd">As</span> ServiceConnectionException        <span class="kwrd">Throw</span> <span class="kwrd">New</span> Exception(<span class="str">&quot;An error occurred while trying to connect to &quot;</span> &amp; remoteService.Name &amp; Environment.NewLine &amp; <span class="str">&quot;Error Details: &quot;</span> &amp; servEx.Message)    <span class="kwrd">Catch</span>        <span class="kwrd">Throw</span>    <span class="kwrd">End</span> <span class="kwrd">Try</span>    <span class="kwrd">Return</span> returnValue <span class="kwrd">End</span> Function</pre><p>Bluetooth devices are recognized by their 48-bit address, but most devices use a friendly name to identify themselves. The friendly name can usually be changed by the owner of the device. The ScreenLock application allows the user to specify&nbsp;the friendly name to use to connect, or to search for paired devices (in the case where they don't know the device name). To search for nearby devices the app uses the DiscoverAllDevices function with returns a list of Device objects. Since we only need the device names to populate our combo box, we use a simple LINQ query to extract the names and project them into a List of type string:</p><p><strong>C#</strong></p><pre class="csharpcode"><span class="kwrd">public</span> List&lt;<span class="kwrd">string</span>&gt; DiscoverDevices(){    var q =        from device <span class="kwrd">in</span> _manager.DiscoverAllDevices()        select device.Name;    <span class="kwrd">return</span> q.ToList&lt;<span class="kwrd">string</span>&gt;();}</pre><p><strong>VB.Net</strong></p><pre class="csharpcode"><span class="kwrd">Public</span> <span class="kwrd">Function</span> DiscoverDevices() <span class="kwrd">as</span> List(Of <span class="kwrd">String</span>)   <span class="kwrd">Dim</span> result <span class="kwrd">As</span> List(Of <span class="kwrd">String</span>) = <span class="kwrd">New</span> List(Of <span class="kwrd">String</span>)   <span class="kwrd">For</span> <span class="kwrd">Each</span> d <span class="kwrd">As</span> Device <span class="kwrd">in</span> _manager.DiscoverAllDevices()      result.Add(d.Name)   <span class="kwrd">Next</span>   <span class="kwrd">Return</span> result <span class="kwrd">End</span> <span class="kwrd">Function</span></pre><p>Once a device is connected to the serial port profile, the application simply uses a timer to periodically write a byte of text to the port. If the transmission fails for any reason, the application will lock the workstation by calling the LockWorkstation API call from user32.dll.</p><p><strong>C#</strong></p><pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">bool</span> Ping(){    <span class="kwrd">bool</span> returnValue = <span class="kwrd">true</span>;    <span class="kwrd">if</span> (!<span class="kwrd">object</span>.Equals(_stream,<span class="kwrd">null</span>)) {        <span class="kwrd">try</span>        {            _stream.WriteByte(1);        }        <span class="kwrd">catch</span> (Exception ex)        {            returnValue = <span class="kwrd">false</span>;        }    }    <span class="kwrd">return</span> returnValue;}</pre><p><strong>VB.Net</strong></p><pre class="csharpcode"><span class="kwrd">Public</span> <span class="kwrd">Function</span> Ping() <span class="kwrd">As</span> <span class="kwrd">Boolean</span>    <span class="kwrd">Dim</span> returnValue <span class="kwrd">As</span> <span class="kwrd">Boolean</span> = <span class="kwrd">True</span>    <span class="kwrd">If</span> (<span class="kwrd">Not</span> <span class="kwrd">Object</span>.Equals(_stream,<span class="kwrd">Nothing</span>)) <span class="kwrd">Then</span>        <span class="kwrd">Try</span>            _stream.WriteByte(1)        <span class="kwrd">Catch</span> ex <span class="kwrd">As</span> Exception            returnValue = <span class="kwrd">False</span>        <span class="kwrd">End</span> <span class="kwrd">Try</span>    <span class="kwrd">End</span> <span class="kwrd">If</span>    <span class="kwrd">Return</span> returnValue <span class="kwrd">End</span> <span class="kwrd">Function</span> </pre><p>The excellent Coding4Fun Developer Toolkit hides all of the complexity of setting up socket connections using the Bluetooth protocol and exposes a few simple but useful functions for interacting with Bluetooth devices from managed code. If you're interested in writing Bluetooth apps in managed code, I suggest you take a look at it – it includes several detailed samples. In addition to the Bluetooth wrapper, there several other cool samples, such as those showing you how to write your own Preview Handlers and interact with Windows Vista Contacts.</p> <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Jerry-Brunning/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:e372a6f1fb5648f695c29e7600d2bd3f">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Bluetooth-ScreenLock</comments>
      <itunes:summary> &amp;nbsp;Bluetooth ScreenLock is a sample application built on top of the Bluetooth managed wrappers that are included in the Coding4Fun Developer Toolkit.Jerry BrunningClarity Consulting, Inc.Difficulty: EasyTime Required: 1-3 hoursCost: FreeSoftware: Visual Studio 2008 Express Editions Beta 2, Coding4Fun Developer Toolkit (Bluetooth assemblies) Hardware: Bluetooth-enabled laptop and phone.Download: DownloadThe Coding4Fun Developer Kit that was released to CodePlex last month contains a bunch of neat libraries and components for jumpstarting development against some of the new features of Vista. Included in the kit is a managed wrapper around Bluetooth communication that is designed to run in non-mobile environments – something that has not previously been widely available. With most newer laptops shipping with Bluetooth radios, and the proliferation of Bluetooth devices and receivers, I looked forward to trying this out. To get familiar with the managed wrappers, I built a simple screen locking application that I call Bluetooth Screenlock. The Bluetooth ScreenLock application runs on your PC, connects to your phone, and when it detects that you&#39;ve walked out of range, locks your workstation. Using the Bluetooth wrappers included in the Coding4Fun Developer Toolkit makes this pretty simple. Bluetooth ProfilesThe managed Bluetooth wrapper classes that are part of the Coding4Fun Developer Kit (C4F Kit) contain libraries for connecting to three different Bluetooth profiles: Serial Port, File Transfer and Object Push. A profile is a standardized interface specification that devices comply to in order to communicate with each other. For the Bluetooth ScreenLock application I used the Serial Port profile to establish a connection and then send heartbeat messages across the Bluetooth channel periodically. If any heartbeat were to fail, the program will lock the user&#39;s workstation. Discovery and PairingDiscovery is the process of detecting nearby Bluetooth devices and potent</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Bluetooth-ScreenLock</link>
      <pubDate>Mon, 20 Aug 2007 02:58:40 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Bluetooth-ScreenLock</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/4474153_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/4474153_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>Jerry Brunning</dc:creator>
      <itunes:author>Jerry Brunning</itunes:author>
      <slash:comments>25</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Bluetooth-ScreenLock/RSS</wfw:commentRss>
      <category>Hardware</category>
      <category>utility</category>
    </item>
  <item>
      <title>WPF Dartboard scoring application</title>
      <description><![CDATA[<span id="c4fmetadata">
<table border="0" cellspacing="0" cellpadding="1" width="100%">
<tbody>
<tr class="entry_overview">
<td width="50">&nbsp;</td>
<td><span class="entry_description">In this article I'll review the steps to creating a WPF-based touch-screen scoreboard application that we use in our Clarity Cricket recreational dart league. In doing so, I'll show some examples of how to create custom animations
 in Visual Studio .NET and wire them up to StoryBoards in XAML </span></td>
</tr>
<tr>
<td colspan="2">
<div class="entry_author">Jerry Brunning</div>
<div class="entry_company"><a href="http://www.claritycon.com/">Clarity Consulting, Inc.</a></div>
<br>
<div class="entry_details"><b>Difficulty: </b><span class="entry_details_input">Advanced</span></div>
<div class="entry_details"><b>Time Required:</b> <span class="entry_details_input">
Greater than 10 hours (to build custom animations)</span></div>
<div class="entry_details"><b>Cost: </b><span class="entry_details_input">Free</span></div>
<div class="entry_details"><b>Software: </b><span class="entry_details_input">Microsoft Visual Studio 2005 .NET Framework, 3.0 November 2006 CTP of the Visual Studio 2005 extensions for .NET Framework 3.0, Microsoft Expression Blend 2 May Preview</span></div>
<div class="entry_details"><b>Download: </b><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/3425360/WPFDartboard.zip">Source code</a>
<ul>
</ul>
</div>
</td>
</tr>
</tbody>
</table>
</span>In this article I'll review the steps to creating a WPF-based touch-screen scoreboard application that we use in our Clarity Cricket recreational dart league.&nbsp; In doing so, I'll show some examples of how to create custom animations&nbsp;in Visual Studio .Net
 and wire them up to StoryBoards in XAML
<p>Back in October one of my co-workers at Clarity, Kevin Marshall, wrote an article about how he modified the foosball table in our employee lounge to allow us to track game results and individual player statistics (see article
<a href="http://blogs.msdn.com/coding4fun/archive/2006/10/31/910302.aspx">here</a>). Statistics are the basis for bragging rights, and at a competitive software development company, we're big on bragging rights. Following in the tradition of the foosball, we
 next set out to make similar capabilities to track scoring and statistics for our recreational dart board. We ended up building a WPF-enabled windows form-based application to use as our virtual scoreboard, attached it to a touch screen monitor, and hooked
 it up to a database to track statistics. This article will show how we went about building a Cricket scoreboard application.&nbsp;
</p>
<p>Since the application makes heavy use of animations, a video works better to convey some of the features.&nbsp; You can view a video of the dart board application in action
<a href="http://employees.claritycon.com/jbrunning/coding4fun/dartboard.wmv">here</a>.</p>
<h3>Windows Presentation Foundation</h3>
<p>Windows Presentation Foundation (WPF) is Microsoft's next generation framework for building rich user experiences for both forms-based and web-based applications. At the core of WPF is the Extensible Application Markup Language (XAML – pronounced “Zamel”)
 which allows developers to lay out a user interface using XML in a hierarchical tree structure. If you're not familiar with WPF, you may want to stop reading this article and first read an overview of WPF on
<a href="http://msdn2.microsoft.com/en-us/library/ms754130.aspx">MSDN</a>. This article assumes you have a basic understanding of the concepts of WPF. I built the application in this article using the November 2006 CTP of the Visual Studio 2005 extensions for
 .NET Framework 3.0. Make sure you install the .NET 3.0 runtime prior to installing the Visual Studio extensions.</p>
<h3>Laying out the main form</h3>
<p>In support of WPF, Microsoft has released a slew of tools that make writing WPF applications easier. Expression Studio is a suite of tools that Microsoft market's towards “creative designers”, but these tools are equally important for developers, especially
 with the WPF framework's designer glitches in the current release. In many cases you cannot use the designers built into Visual Studio. For example, if your forms use controls that you create, you will not be able to open your XAML file in the visual designer
 in Visual Studio. To get around this, you can use Expression Blend to open your Visual Studio project and view your form (Expression Blend can natively open Visual Studio project and solution files).</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/3425360/Scoreboard_Expression2.jpg"><img border="0" alt="Scoreboard_Expression2" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/3425360/Scoreboard_Expression2_thumb.jpg" width="500" height="300"></a>
</p>
<p><strong>Figure 1: Microsoft Expression Blend XAML editor</strong></p>
<p>Expression Blend is great for editing XAML and creating Storyboard (animations) but it is important to note that the tool is not a code editor.&nbsp; You cannot edit the .NET code behind files or even HTML or Javascript files from within Expression Blend.&nbsp; However,
 there is nice integration with Visual Studio .NET - opening a code file from within Expression Blend will automatically kick off an instance of Visual Studio, open your solution, and present you with the source file to edit.</p>
<p>Our application contains just a few screens - the main dartboard form, plus a couple forms used to manage the players in the game and view statistics. Our scoreboard application will be run in a kiosk and use a touch screen monitor as the main interface.
 The idea is that a player throws the dart, and then touches the appropriate section of the screen to indicate where the dart landed. The scoreboard then tracks the score and statistics based on the accumulated data.<br>
To create the main form I started with a vector image of a dartboard and used Expression Design to export the image to XAML. The vector image consists of paths for each individual component so the resulting XAML will contain the details for each path. Below
 is a sample snippet from a one of the Path elements in the scoreboard's XAML. Each individual Path element makes up a second of the image.
</p>
<blockquote>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">Path</span> <span class="attr">x:Name</span><span class="kwrd">=&quot;Path&quot;</span> <span class="attr">Width</span><span class="kwrd">=&quot;93.8075&quot;</span> <span class="attr">Height</span><span class="kwrd">=&quot;113.784&quot;</span> <span class="attr">Canvas</span>.<span class="attr">Left</span><span class="kwrd">=&quot;120.154&quot;</span> <span class="attr">Canvas</span>.<span class="attr">Top</span><span class="kwrd">=&quot;641.654&quot;</span> <span class="attr">Stretch</span><span class="kwrd">=&quot;Fill&quot;</span> <span class="attr">Fill</span><span class="kwrd">=&quot;#FFFF1A00&quot;</span> <span class="attr">Data</span>=&quot;<span class="attr">F1</span> <span class="attr">M</span>... <span class="kwrd">/&gt;</span></pre>
</blockquote>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style><style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>Once I have the XAML representation of the board, I can rename the individual Path elements and make them “clickable” by simply adding the appropriate attributes to each Path element, and then writing the event handler in the code behind file. In this case,
 I added the OnLeftMouseUp attribute to each Path element which would be raised for each section whenever the player clicks on the board.</p>
<blockquote>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">Path</span> <span class="attr">x:Name</span><span class="kwrd">=&quot;Double16&quot;</span> <span class="attr">MouseLeftButtonUp</span><span class="kwrd">=&quot;Double16Click&quot;</span> <span class="attr">Width</span><span class="kwrd">=&quot;93.8075&quot;</span> <span class="attr">Height</span><span class="kwrd">=&quot;113.784&quot;</span> <span class="attr">Canvas</span>.<span class="attr">Left</span><span class="kwrd">=&quot;120.154&quot;</span> <span class="attr">Canvas</span>.<span class="attr">Top</span><span class="kwrd">=&quot;641.654&quot;</span> <span class="attr">Stretch</span><span class="kwrd">=&quot;Fill&quot;</span> <span class="attr">Fill</span><span class="kwrd">=&quot;#FFFF1A00&quot;</span> <span class="attr">Data</span>=&quot;<span class="attr">F1</span> <span class="attr">M</span>... <span class="kwrd">/&gt;</span></pre>
</blockquote>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>In the example Path above – the Double16 – the resulting code behind that would handle the event looks like this:</p>
<blockquote>
<pre class="csharpcode">C#</pre>
</blockquote>
<pre class="csharpcode">        <span class="kwrd">void</span> Double16Click(<span class="kwrd">object</span> sender, EventArgs e)
        {
            OnDartThrown(Darts.Dart16, 2);
        }</pre>
<blockquote>
<pre class="csharpcode">VB</pre>
</blockquote>
<pre class="csharpcode">        <span class="kwrd">Private</span> <span class="kwrd">Sub</span> Double16Click(<span class="kwrd">ByVal</span> sender <span class="kwrd">As</span> <span class="kwrd">Object</span>, <span class="kwrd">ByVal</span> e <span class="kwrd">As</span> MouseButtonEventArgs)
            OnDartThrown(Data.Darts.Dart16, 2)
        <span class="kwrd">End</span> Sub</pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>The OnDartThrown method simply performs a swtich on the Dart enum and performs the appropriate animation followed by notifying the game class to record the score.
<br>
</p>
<h3>Scoring and Rules</h3>
<p>Since we envision using this framework to support multiple dart games, we created a BaseGame class and derived a CricketGame class from BaseGame. Our scoreboard has a member variable of type BaseGame that is set to an instance of the current game type (note:
 we didn't implement multiple game types yet –that could be done by adding an additional screen to choose the type of game to play – so for this version all games are of type Cricket). Our BaseGame has a virtual method called UpdateGame that is called after
 every dart is thrown. This gives the game class a change to update any game data, player scores, statitistics, or other state as required. Since our game is Cricket, CricketGame class manages the scoring rules specific to Cricket, such as maintaining open/close
 state of each target number: </p>
<blockquote>
<p>C#</p>
</blockquote>
<blockquote>
<pre class="csharpcode"><span class="kwrd">   if</span> (lastDartThrown != Darts.DartOutOfBounds)
   {
       score = UpdateScores(lastDartThrown, numberThrown);
       UpdateClosedStatus(lastDartThrown);
   }

   List&lt;<span class="kwrd">int</span>&gt; dartMarks = _players[_currentPlayerIndex].MarkDart(lastDartThrown, numberThrown);
   _dartHistory.Push(<span class="kwrd">new</span> DartHistoryItem(score, lastDartThrown, numberThrown,wasClosed, _currentPlayerIndex, _round, dartMarks));</pre>
</blockquote>
<blockquote>
<pre class="csharpcode">VB</pre>
</blockquote>
<pre class="csharpcode">        <span class="kwrd">If</span> lastDartThrown &lt;&gt; Darts.DartOutOfBounds <span class="kwrd">Then</span>
            score = UpdateScores(lastDartThrown, numberThrown)
            UpdateClosedStatus(lastDartThrown)
        <span class="kwrd">End</span> <span class="kwrd">If</span>
</pre>
<pre class="csharpcode">        <span class="kwrd">Dim</span> dartMarks <span class="kwrd">As</span> List(Of <span class="kwrd">Integer</span>) = _players(_currentPlayerIndex).MarkDart(lastDartThrown, numberThrown)
        _dartHistory.Push(<span class="kwrd">New</span> DartHistoryItem(score, lastDartThrown, numberThrown, _
        wasClosed, _currentPlayerIndex, _round, dartMarks))</pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style><style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style><style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<h3>Setting up the animations</h3>
<p>One of the key new capabilities WPF gives to developers is a way to add animations to their applications. For the dartboard framework, we wanted to add animations after each scoring throw. To give us a good variety, we played around with several different
 types of animations as part of the storyboards in our application.&nbsp; For the dartboard scoreboard we built custom animations for various events that occur during the game – scoring throws, transitions between the scoreboard and the settings screens, and transitions
 between rounds during the game. We implemented our animations in .Net and referenced the .Net classes from within the XAML by adding a namespace declaration in the root node of our scoreboard XAML file. Referencing .Net code from within XAML (and also referencing
 XAML-defined elements from within .Net) is an important concept to understand when writing complex WPF applications.</p>
<blockquote>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">UserControl</span>
    <span class="attr">xmlns</span><span class="kwrd">=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;</span>
    <span class="attr">xmlns:x</span><span class="kwrd">=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;</span>
    <span class="attr">xmlns:uc</span><span class="kwrd">=&quot;clr-namespace:DartScoreboard.GUI.Controls&quot;</span> 
    <span class="attr">xmlns:CustomAnimations</span><span class="kwrd">=&quot;clr-namespace:DartScoreboard.Animations&quot;</span> ...<span class="kwrd">/&gt;</span>
</pre>
</blockquote>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style><style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>With the namespace for our custom animations declared, we can reference them via storyboards in the XAML. For example, the XAML below is a storyboard that refers to our BounceDoubleAnimation.
</p>
<pre class="csharpcode">      <span class="kwrd">&lt;</span><span class="html">Storyboard</span> <span class="attr">x:Key</span><span class="kwrd">=&quot;roundChangedAnimation&quot;</span> <span class="attr">SpeedRatio</span><span class="kwrd">=&quot;2.0&quot;</span><span class="kwrd">&gt;</span>               
              <span class="kwrd">&lt;</span><span class="html">CustomAnimations:BounceDoubleAnimation</span>
                    <span class="attr">From</span><span class="kwrd">=&quot;-500&quot;</span> <span class="attr">To</span><span class="kwrd">=&quot;0&quot;</span> <span class="attr">Duration</span><span class="kwrd">=&quot;0:0:5&quot;</span> <span class="attr">EdgeBehavior</span><span class="kwrd">=&quot;EaseOut&quot;</span> 
            <span class="attr">Storyboard</span>.<span class="attr">TargetName</span><span class="kwrd">=&quot;roundChangedBounce&quot;</span> 
            <span class="attr">Storyboard</span>.<span class="attr">TargetProperty</span><span class="kwrd">=&quot;(TranslateTransform.Y)&quot;</span><span class="kwrd">/&gt;</span>
      <span class="kwrd">&lt;/</span><span class="html">StoryBoard</span><span class="kwrd">&gt;</span></pre>
<pre class="csharpcode"><span class="kwrd"></span>&nbsp;</pre>
<p>This animation is used during the transition from one round to the next, and results in the text bouncing as it moves from the top of the screen to the bottom.
</p>
<h4>DependencyProperties</h4>
<p>One of the steps in implementing the animation in a .Net code-behind class is to define DependencyProperties. DependencyProperties are special types of properties that can be used by WPF to perform things like data binding, animations, inheritance, and styling.
 It is DependencyProperties, for example, that allow the WPF runtime to render the styling of a child element based on where it is nested in the XAML tree.&nbsp; For our custom animations, any properties we want to add to our classes that affect or control the animation
 behavior must be defined as DependencyProperties.&nbsp; For example, our BounceDoubleAnimation has a property called EdgeBehavior that controls whether the animation starts on the screen and moves off the screen (EdgeOut) or starts off the screen and moves onto
 the screen (EdgeIn).&nbsp; We define this as a DependencyProperty below.</p>
<p>Creating a DependencyProperty in your code required two steps: First, you need to register the property with WPF. Second, you need to define property Get and Set methods that call the special GetValue and SetValue functions used to read and write DependencyProperties.
 The example below shows how to register the “EdgeBehavior” DependencyProperty used by the BounceDoubleAnimation:
</p>
<blockquote>
<p>C#</p>
</blockquote>
<p>&nbsp;</p>
<pre class="csharpcode">        <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> DependencyProperty EdgeBehaviorProperty =
            DependencyProperty.Register(<span class="str">&quot;EdgeBehavior&quot;</span>,
                <span class="kwrd">typeof</span>(EdgeBehaviorEnum),
                <span class="kwrd">typeof</span>(BounceDoubleAnimation),
                <span class="kwrd">new</span> PropertyMetadata(EdgeBehaviorEnum.EaseInOut));</pre>
<blockquote>
<pre class="csharpcode">VB</pre>
</blockquote>
<pre class="csharpcode">        <span class="kwrd">Public</span> <span class="kwrd">Shared</span> EdgeBehaviorProperty <span class="kwrd">As</span> DependencyProperty = _
            DependencyProperty.Register(<span class="str">&quot;EdgeBehavior&quot;</span>, _
                <span class="kwrd">GetType</span>(EdgeBehaviorEnum), _
                <span class="kwrd">GetType</span>(BounceDoubleAnimation), _
                <span class="kwrd">New</span> PropertyMetadata(EdgeBehaviorEnum.EaseInOut))</pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>This snippet below shows how to create the property Get and Set methods for a DependencyProperty. Notice the calls to the GetValue and SetValue methods.&nbsp;</p>
<blockquote>
<p>C#</p>
</blockquote>
<pre class="csharpcode">        <span class="rem">/// &lt;summary&gt;</span>
        <span class="rem">/// Specifies which side of the transition gets the &quot;bounce&quot; effect.</span>
        <span class="rem">/// &lt;/summary&gt;</span>
        <span class="kwrd">public</span> EdgeBehaviorEnum EdgeBehavior
        {
            get
            {
                <span class="kwrd">return</span> (EdgeBehaviorEnum)GetValue(EdgeBehaviorProperty);
            }
            set
            {
                SetValue(EdgeBehaviorProperty, <span class="kwrd">value</span>);
            }
        }</pre>
<blockquote>
<pre class="csharpcode">VB</pre>
</blockquote>
<pre class="csharpcode">        <span class="kwrd">Public</span> <span class="kwrd">Property</span> EdgeBehavior() <span class="kwrd">As</span> EdgeBehaviorEnum
            <span class="kwrd">Get</span>
                <span class="kwrd">Return</span> <span class="kwrd">CType</span>(GetValue(EdgeBehaviorProperty), EdgeBehaviorEnum)
            <span class="kwrd">End</span> <span class="kwrd">Get</span>
            <span class="kwrd">Set</span>(<span class="kwrd">ByVal</span> Value <span class="kwrd">As</span> EdgeBehaviorEnum)
                SetValue(EdgeBehaviorProperty, Value)
            <span class="kwrd">End</span> <span class="kwrd">Set</span>
        <span class="kwrd">End</span> Property</pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<h4>Invoking Animations from managed code</h4>
<p>Like most things in WPF, animations can be defined declaratively in the XAML, or via managed code.&nbsp; Similarly, they can be triggered from within the XAML, or dynmaically from .NET.&nbsp; In this case, we've defined the animations in Storyboard elements in the
 XAML, but we'll call them from .NET (for example, as a result of a dart being thrown).&nbsp; It is easy to get a reference to a Storyboard and invoke methods against the managed Storyboard class:&nbsp;</p>
<blockquote>
<p>C#</p>
</blockquote>
<pre class="csharpcode">        <span class="kwrd">private</span> <span class="kwrd">void</span> AnimateDoubleBull()
        {
            Storyboard doubleBullAnimation = (Storyboard)FindResource(<span class="str">&quot;doubleBullAnimation&quot;</span>);
            doubleBullAnimation.Begin(<span class="kwrd">this</span>);
        }</pre>
<blockquote>
<pre class="csharpcode">VB</pre>
</blockquote>
<pre class="csharpcode">        <span class="kwrd">Private</span> <span class="kwrd">Sub</span> AnimateDoubleBull()
            <span class="kwrd">Dim</span> doubleBullAnimation <span class="kwrd">As</span> Storyboard = <span class="kwrd">CType</span>(FindResource(<span class="str">&quot;doubleBullAnimation&quot;</span>), Storyboard)
            doubleBullAnimation.Begin(<span class="kwrd">Me</span>)
        <span class="kwrd">End</span> <span class="kwrd">Sub</span>
</pre>
<style type="text/css">
<!--
.csharpcode
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{background-color:#ffffff;
	font-family:consolas,"Courier New",courier,monospace;
	color:black;
	font-size:small}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	margin:0em;
	width:100%}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<h3>Putting it all together</h3>
<p>While all the WPF related features were fun to build, the real purpose of the framework is to track statistics. For our purposes we will track the typical win/loss record, plus player efficiency, which is the ratio of darts thrown to scoring throws. Since
 a “scoring throw” has a different meaning depending on what game is being played, we write the code to handle scoring in the derived BaseCricket class. For example, for Cricket we define a scoring throw as any throw that hits a 15 or higher, or a bullseye.
 We store this per player in a simple database and then compile statistics on the most efficient players. This isn't perfect of course but it works well for what we wanted. With a little work (and some interruption to the game's flow), you could compile statistics
 on a per target level to answer questions like who is the best at hitting the triple 20.
</p>
<p>With the game framework coded and looking good we next looked to find a good place to position the touch screen monitor. We wanted a place that was convenient to the thrower, but yet not in the way. At first we mounted the monitor on the wall adjacent to
 the thrower. This worked well but we didn't have a good place to put the PC. We eventually ended up building a kiosk to house the PC with an angled top containing the touch screen monitor.
</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/3425360/P6190002.jpg"><img border="0" alt="P6190002" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/3425360/P6190002_thumb.jpg" width="360" height="480"></a>
<a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/3425360/P6190004.jpg">
<img border="0" alt="P6190004" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/3425360/P6190004_thumb.jpg" width="360" height="480"></a>
</p>
<p>This made the whole presentation seem a little nicer and with the addition of some color and a couple Clarity logos it could make a great conversation piece when it comes to recruiting.</p>
<pre></pre>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Jerry-Brunning/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:c1f09b20b8724fc18ab69e7600d38ddd">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/WPF-Dartboard-scoring-application</comments>
      <itunes:summary>



&amp;nbsp;
In this article I&#39;ll review the steps to creating a WPF-based touch-screen scoreboard application that we use in our Clarity Cricket recreational dart league. In doing so, I&#39;ll show some examples of how to create custom animations
 in Visual Studio .NET and wire them up to StoryBoards in XAML 



Jerry Brunning
Clarity Consulting, Inc.

Difficulty: Advanced
Time Required: 
Greater than 10 hours (to build custom animations)
Cost: Free
Software: Microsoft Visual Studio 2005 .NET Framework, 3.0 November 2006 CTP of the Visual Studio 2005 extensions for .NET Framework 3.0, Microsoft Expression Blend 2 May Preview
Download: Source code







In this article I&#39;ll review the steps to creating a WPF-based touch-screen scoreboard application that we use in our Clarity Cricket recreational dart league.&amp;nbsp; In doing so, I&#39;ll show some examples of how to create custom animations&amp;nbsp;in Visual Studio .Net
 and wire them up to StoryBoards in XAML
Back in October one of my co-workers at Clarity, Kevin Marshall, wrote an article about how he modified the foosball table in our employee lounge to allow us to track game results and individual player statistics (see article
here). Statistics are the basis for bragging rights, and at a competitive software development company, we&#39;re big on bragging rights. Following in the tradition of the foosball, we
 next set out to make similar capabilities to track scoring and statistics for our recreational dart board. We ended up building a WPF-enabled windows form-based application to use as our virtual scoreboard, attached it to a touch screen monitor, and hooked
 it up to a database to track statistics. This article will show how we went about building a Cricket scoreboard application.&amp;nbsp;
 
Since the application makes heavy use of animations, a video works better to convey some of the features.&amp;nbsp; You can view a video of the dart board application in action
here. 
Windows Presentation Foundation
Windows Presentation Founda</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/WPF-Dartboard-scoring-application</link>
      <pubDate>Wed, 20 Jun 2007 11:34:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/WPF-Dartboard-scoring-application</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/3425360_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/3425360_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>Jerry Brunning</dc:creator>
      <itunes:author>Jerry Brunning</itunes:author>
      <slash:comments>13</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/WPF-Dartboard-scoring-application/RSS</wfw:commentRss>
      <category>Gaming</category>
      <category>Windows</category>
      <category>arcade</category>
    </item>    
</channel>
</rss>