<?xml version="1.0" encoding="utf-8"?>
<feed xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xml:lang="en-us" xmlns="http://www.w3.org/2005/Atom">
  <title>Colby Cavin</title>
  <link rel="alternate" type="text/html" href="http://www.cavinconsulting.com/Colby/" />
  <link rel="self" href="http://www.cavinconsulting.com/Colby/SyndicationService.asmx/GetAtom" />
  <icon>favicon.ico</icon>
  <updated>2008-08-18T13:15:55.4871356-07:00</updated>
  <author>
    <name>Cavin Consulting</name>
  </author>
  <subtitle />
  <id>http://www.cavinconsulting.com/Colby/</id>
  <generator uri="http://dasblog.info/" version="2.1.8102.813">DasBlog</generator>
  <entry>
    <title>I am unique (just like everyone else)</title>
    <link rel="alternate" type="text/html" href="http://www.cavinconsulting.com/Colby/2008/08/18/IAmUniqueJustLikeEveryoneElse.aspx" />
    <id>http://www.cavinconsulting.com/Colby/PermaLink,guid,0501c350-d994-4242-a49f-e50b180aa367.aspx</id>
    <published>2008-08-18T13:15:25.8143111-07:00</published>
    <updated>2008-08-18T13:15:55.4871356-07:00</updated>
    <category term="Misc" label="Misc" scheme="http://www.cavinconsulting.com/Colby/CategoryView,category,Misc.aspx" />
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <div style="color: #000">
          <table style="background-color: white; text-align: center" cellspacing="0" cellpadding="1" width="350" bgcolor="#ffffff" border="0">
            <tbody>
              <tr>
                <td style="font: 16px/1.1 verdana, arial, helvetica, sans-serif; color: white; background-color: #0066b3">
HowManyOfMe.com</td>
              </tr>
              <tr>
                <td style="border-right: black 1px solid; border-top: black 1px solid; border-left: black 1px solid; border-bottom: black 1px solid">
                  <table style="background-color: white; text-align: center" cellspacing="0" cellpadding="0" width="100%" bgcolor="#ffffff" border="0">
                    <tbody>
                      <tr>
                        <td style="padding-top: 2px" width="120">
                          <a style="text-decoration: none" href="http://howmanyofme.com">
                            <img style="border-top-width: 1px; border-left-width: 1px; border-left-color: black; border-bottom-width: 1px; border-bottom-color: black; border-top-color: black; border-right-width: 1px; border-right-color: black" height="100" alt="Logo" src="http://extimg.howmanyofme.com/extimages/howmany-logo.png" width="100" />
                          </a>
                        </td>
                        <td>
                          <span style="font: 16px/1.1 verdana, arial, helvetica, sans-serif; color: #000">There
are<br /><span style="font-weight: bold; color: red">1</span><br /><b>or fewer</b> people with my name in the U.S.A.</span>
                          <br />
                        </td>
                      </tr>
                    </tbody>
                  </table>
                  <a style="font: bold 16px/1.8 verdana, arial, helvetica, sans-serif; color: #0066b3; text-decoration: underline" href="http://howmanyofme.com">How
many have your name?</a>
                </td>
              </tr>
            </tbody>
          </table>
          <br />
        </div>
        <img width="0" height="0" src="http://www.cavinconsulting.com/Colby/aggbug.ashx?id=0501c350-d994-4242-a49f-e50b180aa367" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Windows Media Player Supplemental</title>
    <link rel="alternate" type="text/html" href="http://www.cavinconsulting.com/Colby/2008/07/17/WindowsMediaPlayerSupplemental.aspx" />
    <id>http://www.cavinconsulting.com/Colby/PermaLink,guid,8ee77b09-5f5f-4921-814d-daf0360f6ba3.aspx</id>
    <published>2008-07-17T08:00:16.5009017-07:00</published>
    <updated>2008-07-17T08:00:16.5009017-07:00</updated>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
In the several months I've been procrastinating on the media player remote project,
the industry has continued to advance. I just ran across <a href="http://www.autonomichome.com/Mirage.htm">Mirage</a>,
a remote control application that appears to target the exact problem I am trying
to solve with my little application. But, I'm too cheap to shell out $200 for something
I know I can write myself. Let's see if this adds any motivation to the development
effort.
</p>
        <img width="0" height="0" src="http://www.cavinconsulting.com/Colby/aggbug.ashx?id=8ee77b09-5f5f-4921-814d-daf0360f6ba3" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Windows Media Player Remote Control - 7a - Online / Offline Detection with the SCSF</title>
    <link rel="alternate" type="text/html" href="http://www.cavinconsulting.com/Colby/2008/07/09/WindowsMediaPlayerRemoteControl7aOnlineOfflineDetectionWithTheSCSF.aspx" />
    <id>http://www.cavinconsulting.com/Colby/PermaLink,guid,e23b3b4e-84e3-448c-8acd-5ed18a63f930.aspx</id>
    <published>2008-07-09T04:44:04-07:00</published>
    <updated>2008-07-14T07:21:50.5874219-07:00</updated>
    <category term="Windows Media Player" label="Windows Media Player" scheme="http://www.cavinconsulting.com/Colby/CategoryView,category,WindowsMediaPlayer.aspx" />
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <strong>Update </strong>- The source for this article is available at <a href="http://www.cavinconsulting.com/Code/MediaPlayerRemote7a.zip">http://www.cavinconsulting.com/Code/MediaPlayerRemote7a.zip</a>. 
</p>
        <p>
The current version of the Smart Client Software Factory comes with a clever WCF service
proxy recipe called the Disconnected Service Agent recipe. This recipe is a much nicer
version of the webservice proxy shipped with the prior version of the toolkit. One
of the nice parts of this recipe is the automatic online/offline detection capabilities.
At its root, the recipe uses a RequestManager to queue up and dispatch webservice
requests. Attached to the RequestManager is an IConnectionMonitor. By default, this
connection monitor automatically keeps track of a client's connection status.
</p>
        <p>
Unfortunately, this only determines if a client has a connection to the Internet,
not whether the client can actually call the webservice of interest. What we want
is to make sure the client is really "Online" with respect to the webservice it is
calling. There are a couple of ways we can do this. The toolkit allows us to plug
in our own service that implements IConnecitionMonitor. We could implement IConnectionMonitor
in our own custom service and add an attribute to the ConnectionMonitor tag in the
app.config file that would make the framework spin up our own, custom definition of
what it means to be "online". That's probably the right way to do things, but I decided
to implement a WebserviceMonitor service that simply polls the desired webservice
to make sure it is available.
</p>
        <p>
I added IConnectionMonitor.cs to Infrastructure.Interface/Services as an interface
with a single, read only property -- IsConnected, and a single event -- ConnectionStatusChanged.
Then, I added ConnectionMonitor.cs to Infrastructure.Module/Services as a class that
implements both IConnectionMonitor and IBuilderAware:
</p>
        <blockquote>
          <pre class="code">
            <span style="COLOR: blue">public class </span>
            <span style="COLOR: #2b91af">WebserviceMonitor </span>: <span style="COLOR: #2b91af">IWebserviceMonitor</span>, <span style="COLOR: #2b91af">IBuilderAware </span>{
... }</pre>
        </blockquote>
        <p>
The constructor of the class uses the existing IConnectionMonitor as a service dependency:
</p>
        <blockquote>
          <pre class="code">
            <span style="COLOR: blue">private </span>
            <span style="COLOR: #2b91af">IConnectionMonitor </span>_connectionMonitor; <span style="COLOR: blue">public </span>WebserviceMonitor([<span style="COLOR: #2b91af">ServiceDependency</span>] <span style="COLOR: #2b91af">IConnectionMonitor </span>connectionMonitor)
{ _connectionMonitor = connectionMonitor; _connectionMonitor.ConnectionStatusChanged
+= <span style="COLOR: blue">new </span><span style="COLOR: #2b91af">EventHandler</span>(connectionMonitor_ConnectionStatusChanged);
}</pre>
        </blockquote>
        <p>
The IConnectionMonitor manages whether the machine is online or offline. So, we need
to manage the other half (whether we can get to the webservice). So, we implement
a member method to answer the question: 
</p>
        <blockquote>
          <pre class="code">
            <span style="COLOR: blue">private void </span>UpdateConnectedStatus()
{ <span style="COLOR: blue">bool </span>wasConnected = _connected; _connected = _connectionMonitor.IsConnected
&amp;&amp; WebserviceAvailable(); <span style="COLOR: blue">if </span>(wasConnected
!= _connected) OnConnectionStatusChanged(_connected); }</pre>
        </blockquote>
        <p>
With that, we can call UpdateConnectedStatus on creation as well as any time ConnectionStatusChanged
is fired by the connection manager. When we sense a connection change, we fire our
own ConnectionStatusChanged event using the built-in event mechanism:
</p>
        <blockquote>
          <pre class="code">[<span style="COLOR: #2b91af">EventPublication</span>(<span style="COLOR: #2b91af">EventTopicNames</span>.OnlineOfflineUpdate,<span style="COLOR: #2b91af">PublicationScope</span>.Global)] <span style="COLOR: blue">public
event </span><span style="COLOR: #2b91af">EventHandler</span>&lt;<span style="COLOR: #2b91af">EventArgs</span>&lt;<span style="COLOR: blue">bool</span>&gt;&gt;
ConnectionStatusChanged;</pre>
        </blockquote>
        <p>
But this doesn't solve the problem completely. Why not? The webservice status is only
updated in the event of a connection status change as fired by the IConnectionMonitor.
So, how do we make sure the webservice status is updated periodically, even if the
connection status doesn't change? One solution is to use a thread timer in the service
to make periodic calls to the webservice. We can implement this by taking advantage
of our IBuilderAware methods:
</p>
        <blockquote>
          <pre class="code">
            <span style="COLOR: blue">public void </span>OnBuiltUp(<span style="COLOR: blue">string </span>id)
{ _connectionCheckTimer = <span style="COLOR: blue">new </span>System.Threading.<span style="COLOR: #2b91af">Timer</span>(<span style="COLOR: blue">new </span>System.Threading.<span style="COLOR: #2b91af">TimerCallback</span>(Tick), <span style="COLOR: blue">null</span>,
0, PingDelay); } <span style="COLOR: blue">public void </span>OnTearingDown() { <span style="COLOR: blue">if </span>(<span style="COLOR: blue">null </span>!=
_connectionCheckTimer) { _connectionCheckTimer.Dispose(); _connectionCheckTimer = <span style="COLOR: blue">null</span>;
} }</pre>
        </blockquote>
        <p>
There are the basic steps for producing a webservice monitor within the SCSF. I'm
sure there are better ways of solving the problem, but this one works pretty well
for my needs. Of course, subscribing to the service is as easy as getting a reference
to the service or subscribing to the global event:
</p>
        <blockquote>
          <pre class="code">[<span style="COLOR: #2b91af">EventSubscription</span>(<span style="COLOR: #2b91af">EventTopicNames</span>.OnlineOfflineUpdate, <span style="COLOR: #2b91af">ThreadOption</span>.UserInterface)] <span style="COLOR: blue">public
void </span>OnlineOfflineUpdateHandler(<span style="COLOR: blue">object </span>sender, <span style="COLOR: #2b91af">EventArgs</span>&lt;<span style="COLOR: blue">bool</span>&gt;
e) { _onlineOfflineLabel.Text = e.Data ? <span style="COLOR: #a31515">"Online" </span>: <span style="COLOR: #a31515">"Offline"</span>;
}</pre>
        </blockquote>
        <p>
Hope this helps.
</p>
        <img width="0" height="0" src="http://www.cavinconsulting.com/Colby/aggbug.ashx?id=e23b3b4e-84e3-448c-8acd-5ed18a63f930" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Windows Media Player Remote Control - 7</title>
    <link rel="alternate" type="text/html" href="http://www.cavinconsulting.com/Colby/2008/06/03/WindowsMediaPlayerRemoteControl7.aspx" />
    <id>http://www.cavinconsulting.com/Colby/PermaLink,guid,61f11d1f-bc88-4117-9ec9-bc3d46c9d964.aspx</id>
    <published>2008-06-03T09:50:56.0218172-07:00</published>
    <updated>2008-06-03T09:50:56.0218172-07:00</updated>
    <category term="Windows Media Player" label="Windows Media Player" scheme="http://www.cavinconsulting.com/Colby/CategoryView,category,WindowsMediaPlayer.aspx" />
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
After using version 1.5 in the real world, I've realized it's time to make the solution
more robust, with higher performance. The 1.5 implementation is so bad, in fact, that
I'm not going to offer the source code as promised -- it just isn't release (even
alpha) quality. As implemented, if the server goes down or there is a momentary network
outage, I have to restart the client (the WCF channel faults and no longer functions).
What I really need is a way to make the communication channel more fault tolerant.
I can approach this several ways, but by drawing on the toolkits I know best, I have
decided to use the Smart Client Software Factory as a base implementation framework
for the product. This is probably overkill for what I'm doing, but I really like the
automatic offline/online detection and the modular nature of the services layers.
</p>
        <p>
Since we already have something resembling a UI, the next thing is to take a serious
look at the business / data access layers. They're pretty co-mingled right now, and
experts in the field tell me that isn't a good idea. For the Data Access layer, I
see two different approaches: 1) Direct webservice access (like we've done in our
previous examples) using the Disconnected Service Agent block provided by the SCSF,
or 2) employing the services of 1) for real-time information (now playing) and handling
the large volume of media library information via a local, cached data store, regularly
updated via ADO.NET synchronization services.
</p>
        <p>
Of course, 2) is my favorite, but we'll start with 1) and move to 2). The nice bit
about the SCSF in this case is that changing the data access layer at a later time
should have minimal impact on either the business layer or the UI. So long as the
data access layer continues to implement the same service interface, the actual implementation
shouldn't matter.
</p>
        <p>
So, here goes. We'll start by downloading and installing the most recent version of <a href="http://www.codeplex.com/smartclient">SCSF</a>, <a href="http://www.microsoft.com/downloads/details.aspx?familyid=DF79C099-4753-4A59-91E3-5020D9714E4E&amp;displaylang=en">Guidance
Automation Extensions (GAX)</a>, and <a href="http://www.microsoft.com/downloads/details.aspx?familyid=4C557C63-708F-4280-8F0C-637481C31718&amp;displaylang=en">Enterprise
Library</a> for VS2008.
</p>
        <p>
With that out of the way, we start with a brand new smart client project with WPF
UI components enabled. By default, if you want to enable WPF UI components, it creates
a WinForms application that allows WPF parts to be hosted. I'm not sure I like this
hybrid solution, and may look into using the techniques in the <a href="http://www.codeplex.com/scsfcontrib">SCSFContrib</a> CodePlex
project to get a truly WPF application at the end of the day.
</p>
        <p>
Here's the plan of attack:
</p>
        <ol>
          <li>
Implement the Data Access layer as an online/offline fault tolerant service. 
</li>
          <li>
Implement some form of business layer using a yet-to-be-determined approach. 
</li>
          <li>
Drop in the existing front-row clone as a UI layer for the time being. 
</li>
          <li>
Implement a client-side cache for the media library (seldom changing) data. 
</li>
          <li>
Replace the UI with a purely WPF implementation, possibly using the SCSFContrib libraries.</li>
        </ol>
        <p>
Sounds simple. Rather than walking through the entire solution, I'll post the areas
where I have problems and (possibly) some solutions to these problems.
</p>
        <img width="0" height="0" src="http://www.cavinconsulting.com/Colby/aggbug.ashx?id=61f11d1f-bc88-4117-9ec9-bc3d46c9d964" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Windows Media Player Remote Control - 6e - Solving the WcfScvHost.exe Problem Without Losing Auto-Update</title>
    <link rel="alternate" type="text/html" href="http://www.cavinconsulting.com/Colby/2008/01/26/WindowsMediaPlayerRemoteControl6eSolvingTheWcfScvHostexeProblemWithoutLosingAutoUpdate.aspx" />
    <id>http://www.cavinconsulting.com/Colby/PermaLink,guid,b2026707-d132-41a9-830c-dc7c7c75ad4b.aspx</id>
    <published>2008-01-26T16:46:31-07:00</published>
    <updated>2008-06-03T09:48:16.8625114-07:00</updated>
    <category term="Windows Media Player" label="Windows Media Player" scheme="http://www.cavinconsulting.com/Colby/CategoryView,category,WindowsMediaPlayer.aspx" />
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
In segment <strike>3</strike><strike>4</strike><a href="http://www.cavinconsulting.com/Colby/2007/12/21/WindowsMediaPlayerRemoteControl3.aspx">here</a> of
this series, I discovered a distinct problem with Visual Studio's treatment of WCF
Library projects. Specifically, any WCF Library project in Visual Studio is automatically
hosted in a test harness during a debug session -- even if you have explicitly told
visual studio not to start that particular project or deleted any reference to WcfSvcHost.exe
in any of the project files! 
</p>
        <p>
This caused problems when I was explicitly hosting my service in an outside application
(like my WinForm app). If I had the service, service host, and client application
in the same VS solution (and who wouldn't?), I couldn't use the same configuration
information in the WCF host library as the WinForms host. If I did, one of two would
fail to initialize, and it was always my hosting application that started up after
the WcfSvcHost.exe application that failed. But, changing port numbers between the
projects meant that I couldn't use the automatic "Update Service Reference" tool within
Visual Studio without manually changing port numbers before I updated. Convincing
VS that this wasn't a WCF Library (by removing the project type guid) meant that the
automatic update tool wasn't even an option. 
</p>
        <p>
The solution was a side effect of my attempt to re-architect my application for re-use.
The "Update Service Reference" tool uses the App.Config file within the project <em><u>where
the service reference lives</u></em>. The applications use the App.Config within the
project <em><u>where the applications live</u></em>. So, the simple solution is to
extract the service references into a different .dll from the client application like
this: 
<table cellspacing="0" cellpadding="2" width="562" border="0"><tbody><tr><td valign="top" width="90">
Project 
</td><td valign="top" width="137">
WCF Host Application 
</td><td valign="top" width="83">
WCF Library 
</td><td valign="top" width="123">
Service Access .dll 
</td><td valign="top" width="127">
Client Application 
</td></tr><tr><td valign="top" width="90">
App.Config 
</td><td valign="top" width="137">
Port 3132 
</td><td valign="top" width="83">
Port 3131 
</td><td valign="top" width="123">
Port 3131 
</td><td valign="top" width="127">
Port 3132</td></tr></tbody></table></p>
        <p>
If you do that, then you can change the port numbers in the host application and client
application projects without disturbing the port numbers in the WCF Library or the
Service Access library. So, the "Update Service Reference" tool continues to work.
The WCF service is still spun up twice on a debug session, but only once on the ports
listed in the host application's app.config.
</p>
        <img width="0" height="0" src="http://www.cavinconsulting.com/Colby/aggbug.ashx?id=b2026707-d132-41a9-830c-dc7c7c75ad4b" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Windows Media Player Remote Control - 6d - Managing the Background NowPlaying Thread</title>
    <link rel="alternate" type="text/html" href="http://www.cavinconsulting.com/Colby/2008/01/25/WindowsMediaPlayerRemoteControl6dManagingTheBackgroundNowPlayingThread.aspx" />
    <id>http://www.cavinconsulting.com/Colby/PermaLink,guid,c18d9dce-257f-4a56-8abc-da79a94704a5.aspx</id>
    <published>2008-01-25T16:46:01-07:00</published>
    <updated>2008-06-03T09:46:22.2978118-07:00</updated>
    <category term="Windows Media Player" label="Windows Media Player" scheme="http://www.cavinconsulting.com/Colby/CategoryView,category,WindowsMediaPlayer.aspx" />
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
This one may seem a little rudimentary, but it caused me to think a little about the
right pattern for handling background worker threads. That is, in .NET 2.0, I could
take advantage of the BackgroundWorker control. This control did a nice job of spawning
a thread to do some work and alerting the application (on the UI thread) when it was
complete. It also got Disposed when the containing control got disposed, alleviating
the need for any end of life thread synchronization. In WPF, however, this control
doesn't exist, but a class called BackgroundWorker does.
</p>
        <p>
My usual approach to something like this is to create a class level ManualResetEvent
and then initialize the BackgroundWorker in the constructor with something like this:
</p>
        <blockquote>
          <pre class="code">_backgroundWorker = <span style="color: blue">new </span><span style="color: #2b91af">BackgroundWorker</span>();
_threadStopEvent = <span style="color: blue">new </span><span style="color: #2b91af">ManualResetEvent</span>(<span style="color: blue">false</span>);
_backgroundWorker.DoWork += <span style="color: blue">new </span><span style="color: #2b91af">DoWorkEventHandler</span>(GetNowPlaying);
_backgroundWorker.WorkerSupportsCancellation = <span style="color: blue">true</span>;
_backgroundWorker.RunWorkerAsync();</pre>
        </blockquote>
        <p>
Then, have the periodic worker do a timed wait on the ManualResetEvent. When the wait
times out, perform the action, and when the wait is triggered, exit the loop (ending
the worker thread). This usually looks something like this:
</p>
        <blockquote>
          <pre class="code">
            <span style="color: blue">private void </span>GetNowPlaying()
{ <span style="color: blue">while </span>(!_threadStopEvent.WaitOne(500,<span style="color: blue">false</span>))
{ <span style="color: green">// Do some work</span> } } </pre>
        </blockquote>
        <p>
In the normal case, I tell the thread to stop when the owning object's dispose method
is called like this:
</p>
        <blockquote>
          <pre class="code">
            <span style="color: blue">protected void </span>Dispose(<span style="color: blue">bool </span>disposing)
{ <span style="color: blue">if </span>(disposing) { <span style="color: blue">if </span>(!_disposed)
{ _threadStopEvent.Set(); _disposed = <span style="color: blue">true</span>; } } }</pre>
        </blockquote>
        <p>
This didn't seem to work in our case. Another alternative was to call the BackgroundWorkder's
CancelAsync() method. That didn't work either. The reason? Our Factory has a static
NowPlaying object. So, when should we dispose our NowPlaying object? There are many
instances of the Factory class created. We don't want each instance to have its own
copy of the media library, so we share it across all instances. But, how do we know
when to dispose of it?
</p>
        <p>
It turns out, it doesn't really matter. The BackgroundWorker class does a pretty good
job of cleaning up after itself. So, we can just get rid of the Dispose altogether.
The BackgroundWorker takes care of terminating all of our background threads automatically.
Best Practice? I'm not sure. It seems like we're not doing a very nice job of disposing
of our resources, but it's pretty slick.
</p>
        <img width="0" height="0" src="http://www.cavinconsulting.com/Colby/aggbug.ashx?id=c18d9dce-257f-4a56-8abc-da79a94704a5" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Windows Media Player Remote Control - 6c - The AnimationBehaviors Project</title>
    <link rel="alternate" type="text/html" href="http://www.cavinconsulting.com/Colby/2008/01/24/WindowsMediaPlayerRemoteControl6cTheAnimationBehaviorsProject.aspx" />
    <id>http://www.cavinconsulting.com/Colby/PermaLink,guid,802fea74-be0b-417e-96d6-15023dc7c7b7.aspx</id>
    <published>2008-01-24T16:45:17-07:00</published>
    <updated>2008-06-03T09:45:34.3281408-07:00</updated>
    <category term="Windows Media Player" label="Windows Media Player" scheme="http://www.cavinconsulting.com/Colby/CategoryView,category,WindowsMediaPlayer.aspx" />
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
While producing my new, pretty WMP remote control, I wanted to have clever navigation
animations similar to those found in FrontRow. The example I used (<a href="http://www.mperfect.net/backRow/">/backRow</a>)
accomplished this in a pretty ugly way.  All of the controls were set up off-screen
and flown on-screen according to some animation trigger. This worked, but it made
it impossible to edit the contents of the pages with Expression Blend or the Visual
Studio editor. So, I decided to use page navigation instead.
</p>
        <p>
The trick was to figure out how to change the look and feel of the page navigation.
By default, windows just appear over the old windows with no magical transitional
WPF-ness. In comes the <a href="http://www.codeplex.com/AnimationBehaviors">AnimationBehaviors</a> Project
on CodePlex. This clever little project allows me to control how a window is loaded
and unloaded. So, in our case, we can define a page, the contents of which are an
AnimationBehaviorHost, and set the AnimationBehaviorHost.LoadedBehavior to LoadedBehavior.SlideInFromRight. 
</p>
        <p>
That worked great, except that everything slide in from the right even if we were
navigating backwards! It just didn't look right. What would be great is if the LoadedBehavior
dynamically changed based on the direction of navigation. Sounds like a great used
of Binding.
</p>
        <p>
The first thing to do was to create a place to store the current animation behavior:
</p>
        <blockquote>
          <pre class="code">
            <span style="color: blue">public class </span>
            <span style="color: #2b91af">NavigationAnimation </span>: <span style="color: #2b91af">INotifyPropertyChanged </span>{ <span style="color: green">//
Singleton class </span><span style="color: blue">private </span>NavigationAnimation()
{ } <span style="color: blue">public enum </span><span style="color: #2b91af">NavigationDirection </span>{
Forward, Backward }; <span style="color: blue">private static </span><span style="color: #2b91af">NavigationAnimation </span>_instance
= <span style="color: blue">new </span><span style="color: #2b91af">NavigationAnimation</span>(); <span style="color: blue">public
static </span><span style="color: #2b91af">NavigationAnimation </span>Instance { <span style="color: blue">get </span>{ <span style="color: blue">return </span><span style="color: #2b91af">NavigationAnimation</span>._instance;
} <span style="color: blue">set </span>{ <span style="color: #2b91af">NavigationAnimation</span>._instance
= <span style="color: blue">value</span>; } } <span style="color: blue">public static
void </span>SetNavigationDirection(<span style="color: #2b91af">NavigationDirection </span>direction)
{ <span style="color: blue">if</span>(<span style="color: #2b91af">NavigationDirection</span>.Forward==direction)
{ Instance.AnimationBehavior = <span style="color: #2b91af">LoadedBehavior</span>.SlideInFromRight;
} <span style="color: blue">else </span>{ Instance.AnimationBehavior = <span style="color: #2b91af">LoadedBehavior</span>.SlideInFromLeft;
} } <span style="color: blue">private </span><span style="color: #2b91af">LoadedBehavior </span>_animationBehavior
= <span style="color: #2b91af">LoadedBehavior</span>.SlideInFromRight; <span style="color: blue">public </span><span style="color: #2b91af">LoadedBehavior </span>AnimationBehavior
{ <span style="color: blue">get </span>{ <span style="color: blue">return </span>_animationBehavior;
} <span style="color: blue">set </span>{ _animationBehavior = <span style="color: blue">value</span>;
OnPropertyChanged(<span style="color: #a31515">"AnimationBehavior"</span>); } } <span style="color: blue">private
void </span>OnPropertyChanged(<span style="color: blue">string </span>propertyName)
{ <span style="color: blue">if </span>(<span style="color: blue">null </span>!= PropertyChanged)
{ <span style="color: #2b91af">PropertyChangedEventArgs </span>e = <span style="color: blue">new </span><span style="color: #2b91af">PropertyChangedEventArgs</span>(propertyName);
PropertyChanged(<span style="color: blue">this</span>,e); } } <span style="color: blue">public
event </span><span style="color: #2b91af">PropertyChangedEventHandler </span>PropertyChanged;
}</pre>
        </blockquote>
        <p>
Next, we need to change the animation behavior based on our navigation state so we
add an event handler to the NavigationFrame's Navigating event that looks something
like this:
</p>
        <blockquote>
          <pre class="code">
            <span style="color: blue">private void </span>OnNavigating(<span style="color: blue">object </span>sender, <span style="color: #2b91af">NavigatingCancelEventArgs </span>e)
{ <span style="color: green"></span><span style="color: blue">if </span>(e.NavigationMode
== <span style="color: #2b91af">NavigationMode</span>.Back) { <span style="color: #2b91af">NavigationAnimation</span>.SetNavigationDirection(<span style="color: #2b91af">NavigationAnimation</span>.<span style="color: #2b91af">NavigationDirection</span>.Backward);
} <span style="color: blue">else </span>{ <span style="color: #2b91af">NavigationAnimation</span>.SetNavigationDirection(<span style="color: #2b91af">NavigationAnimation</span>.<span style="color: #2b91af">NavigationDirection</span>.Forward);
} }</pre>
        </blockquote>
        <p>
Finally, we bind our AnimationBehaviorHost.LoadedBehavior to our current animation
behavior.
</p>
        <blockquote>
          <pre class="code">
            <span style="color: blue">private void </span>OnNavigating(<span style="color: blue">object </span>sender, <span style="color: #2b91af">NavigatingCancelEventArgs </span>e)
{ <span style="color: green"></span><span style="color: blue">if </span>(e.NavigationMode
== <span style="color: #2b91af">NavigationMode</span>.Back) { <span style="color: #2b91af">NavigationAnimation</span>.SetNavigationDirection(<span style="color: #2b91af">NavigationAnimation</span>.<span style="color: #2b91af">NavigationDirection</span>.Backward);
} <span style="color: blue">else </span>{ <span style="color: #2b91af">NavigationAnimation</span>.SetNavigationDirection(<span style="color: #2b91af">NavigationAnimation</span>.<span style="color: #2b91af">NavigationDirection</span>.Forward);
} }</pre>
        </blockquote>
        <p>
That's it! Navigating forward slides the windows in from the right, while navigating
backward slides the windows in from the left. I may finally be getting the hang of
this stuff!
</p>
        <img width="0" height="0" src="http://www.cavinconsulting.com/Colby/aggbug.ashx?id=802fea74-be0b-417e-96d6-15023dc7c7b7" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Windows Media Player Remote Control - 6b - System.Bitmap and the Background Thread</title>
    <link rel="alternate" type="text/html" href="http://www.cavinconsulting.com/Colby/2008/01/23/WindowsMediaPlayerRemoteControl6bSystemBitmapAndTheBackgroundThread.aspx" />
    <id>http://www.cavinconsulting.com/Colby/PermaLink,guid,622d656f-1142-4dcd-8d71-eb7d0270af90.aspx</id>
    <published>2008-01-23T16:44:40-07:00</published>
    <updated>2008-06-03T09:44:56.7180437-07:00</updated>
    <category term="Windows Media Player" label="Windows Media Player" scheme="http://www.cavinconsulting.com/Colby/CategoryView,category,WindowsMediaPlayer.aspx" />
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
Once I figured out how to update data-bound collections from a background thread,
things progressed rather smoothly. But, when it was time to implement the "Now Playing"
pane, I wasn't working with a collection of items anymore. No worry, just implement
INotifyPropertyChanged the same way we did INotifyCollectionChanged (with the SynchronizationContext
"hack") and all was well. Or so I thought. 
</p>
        <p>
The NowPlayingService exposes the album art for the media item currently being played
as a System.Bitmap. I chose that because it appeared to navigate nicely across WCF
services. While that is true, they don't bind very nicely to any property of a WPF
Image control. As far as I can tell, there are a few options to solve this problem:
implement a System.Bitmap to System.Windows.Media.Imaging.BitmapSource TypeConverter.
dig through the documented converter classes to see if there might actually be one
implemented for you (still possible, but I couldn't find one), or just do the conversion
in the business object and expose the image property as the appropriate System.Windows.Media.Imaging.BitmapSource. 
</p>
        <p>
I decided the last option was easiest. So, I exposed a BitmapSource property called
AlbumArt and assigned it from the System.Bitmap with something like this: 
</p>
        <blockquote>
          <pre>
            <span style="color: blue">private </span>System.Windows.Media.Imaging.<span style="color: #2b91af">BitmapSource </span>FromBitmap(System.Drawing.<span style="color: #2b91af">Bitmap </span>bitmap)
{ <span style="color: blue">return </span>System.Windows.Interop.<span style="color: #2b91af">Imaging</span>.CreateBitmapSourceFromHBitmap(
bitmap.GetHbitmap(), <span style="color: #2b91af">IntPtr</span>.Zero, System.Windows.<span style="color: #2b91af">Int32Rect</span>.Empty,
System.Windows.Media.Imaging.<span style="color: #2b91af">BitmapSizeOptions</span>.FromEmptyOptions());
}</pre>
        </blockquote>
        <p>
That worked great, synchronously. When I started updating it in the background thread
(on a periodic timer), I got a "System.Windows.Xaml.XamlParseException: System.Windows.Data.BindingExpression'
value cannot be assigned to property 'Source' of object 'System.Windows.Controls.Image'.
The calling thread cannot access this object because a different thread owns it. 
Error at object 'System.Windows.Data.Binding' in markup file ...". What? I'm marshalling
across threads correctly. Everything else works. What could be going on here, and
why? 
</p>
        <blockquote>
          <p>
            <em>Non sequitur - In a previous life, I was a C++, Win32, COM, and ATL developer.
I was also an ESRI ArcObjects (a pretty large COM API for automating ESRI ArcMap)
developer. As soon as I started working with .NET, I grabbed a copy of Adam Nathan's <a href="http://www.amazon.com/NET-COM-Complete-Interoperability-Guide/dp/067232170X">excellent
book on COM Interop</a>. With that, I sought to understand as much as I could regarding
the interoperability between COM and .NET for I wanted to take advantage of the .NET
UI from within my COM business model.</em>
          </p>
        </blockquote>
        <p>
The inclusion of things like .Interop. in the namespace and GetHbitmap() in the arguments
immediately led me to the potential that the returned BitmapSource reference was a
simple wrapper around the HBITMAP in the System.Bitmap reference. By the fact that
the UI is complaining about accessing an object in a different thread, I surmise that
the HBITMAP of the System.Bitmap is in Thread Local Storage rather than global memory.
So, I altered the conversion process to something like this: 
</p>
        <blockquote>
          <pre>
            <span style="color: blue">private </span>System.Windows.Media.Imaging.<span style="color: #2b91af">BitmapSource </span>BitmapSourceFromImage(System.Drawing.<span style="color: #2b91af">Image </span>img)
{ System.IO.<span style="color: #2b91af">MemoryStream </span>memStream = <span style="color: blue">new </span>System.IO.<span style="color: #2b91af">MemoryStream</span>(); <span style="color: green"></span>img.Save(memStream,
System.Drawing.Imaging.<span style="color: #2b91af">ImageFormat</span>.Png); <span style="color: green"></span>System.Windows.Media.Imaging.<span style="color: #2b91af">PngBitmapDecoder </span>decoder
= <span style="color: blue">new </span>System.Windows.Media.Imaging.<span style="color: #2b91af">PngBitmapDecoder</span>(
memStream, System.Windows.Media.Imaging.<span style="color: #2b91af">BitmapCreateOptions</span>.PreservePixelFormat,
System.Windows.Media.Imaging.<span style="color: #2b91af">BitmapCacheOption</span>.Default); <span style="color: green"></span><span style="color: blue">return </span>decoder.Frames[0];
}</pre>
        </blockquote>
        <p>
With the business object exposing a copy of the bitmap, all is well. However, I am
finding myself, once again, questioning whether it should be the job of the business
object to know whether it's being used from a different thread. I guess it's a question
of determining who is responsible for ensuring thread safety. Ultimately, it was the
business object's fault for exposing a wrapper around thread local storage rather
than heap storage.
</p>
        <img width="0" height="0" src="http://www.cavinconsulting.com/Colby/aggbug.ashx?id=622d656f-1142-4dcd-8d71-eb7d0270af90" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Windows Media Player Remote Control - 6a - Cross-Threading Exceptions</title>
    <link rel="alternate" type="text/html" href="http://www.cavinconsulting.com/Colby/2008/01/22/WindowsMediaPlayerRemoteControl6aCrossThreadingExceptions.aspx" />
    <id>http://www.cavinconsulting.com/Colby/PermaLink,guid,6f370665-4125-4322-8c6c-e4651e4f6048.aspx</id>
    <published>2008-01-22T16:43:45-07:00</published>
    <updated>2008-06-03T09:43:58.7794313-07:00</updated>
    <category term="Windows Media Player" label="Windows Media Player" scheme="http://www.cavinconsulting.com/Colby/CategoryView,category,WindowsMediaPlayer.aspx" />
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
This is the eighth in a series, but the numbering is getting confusing, so I'm going
to stop counting. 
</p>
        <p>
The first step I took in creating my pretty WMP remote control UI was to <strike>steal</strike> design
the pretty UI. Once I had the UI, it was a matter of binding the media library entries
to the appropriate WPF elements (a listbox). I used some pretty standard dataset creation
/ binding logic I found somewhere that makes use of the ObjectDataProvider. To implement
this, I created a MediaLibrary and Factory class that looked something like this:
</p>
        <blockquote>
          <pre class="code">
            <span style="color: blue">public class </span>
            <span style="color: #2b91af">MediaLibrary </span>: <span style="color: #2b91af">ObservableCollection</span>&lt;<span style="color: #2b91af">Song</span>&gt;
{ <span style="color: blue">public </span>MediaLibrary() { GetSongs(); } <span style="color: blue">private
void </span>GetSongs() { <span style="color: #2b91af">IMediaLibraryService </span>mediaLibrary
= <span style="color: blue">new </span><span style="color: #2b91af">MediaLibraryServiceClient</span>(); <span style="color: blue">int </span>librarySize
= mediaLibrary.GetSongCount(); <span style="color: blue">int </span>i = 0; <span style="color: blue">while </span>(i
&lt; (librarySize + _pageSize)) { <span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Guid</span>&gt;
currentIds = mediaLibrary.GetSongs(i, _pageSize); <span style="color: blue">foreach </span>(<span style="color: #2b91af">Guid </span>id <span style="color: blue">in </span>currentIds)
{ <span style="color: #2b91af">Song </span>currentItem = mediaLibrary.GetMediaInfo(id); <span style="color: blue">if </span>(<span style="color: blue">null </span>!=
currentItem) { <span style="color: blue">this</span>.Add(currentItem); } } i += _pageSize;
} } }</pre>
          <pre class="code">
            <span style="color: blue">public class </span>
            <span style="color: #2b91af">Factory </span>{ <span style="color: gray">///
&lt;summary&gt; /// /// &lt;/summary&gt; </span><span style="color: blue">static </span>Factory()
{ Songs = <span style="color: blue">new </span><span style="color: #2b91af">MediaLibrary</span>();
} <span style="color: gray"></span><span style="color: blue">public static </span><span style="color: #2b91af">MediaLibrary </span>Songs
{ <span style="color: blue">get</span>; <span style="color: blue">private set</span>;
} }</pre>
        </blockquote>
        <p>
And I bound the contents to the UI using syntax like this:
</p>
        <blockquote>
          <pre class="code">
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">Grid</span>
            <span style="color: blue">&gt;
&lt;</span>
            <span style="color: #a31515">Grid.Resources</span>
            <span style="color: blue">&gt;
&lt;</span>
            <span style="color: #a31515">ObjectDataProvider </span>
            <span style="color: red">x</span>
            <span style="color: blue">:</span>
            <span style="color: red">Key</span>
            <span style="color: blue">="FactoryDS" </span>
            <span style="color: red">ObjectType</span>
            <span style="color: blue">="{</span>
            <span style="color: #a31515">x</span>
            <span style="color: blue">:</span>
            <span style="color: #a31515">Type </span>
            <span style="color: red">local</span>
            <span style="color: blue">:</span>
            <span style="color: red">Factory</span>
            <span style="color: blue">}"/&gt;
&lt;</span>
            <span style="color: #a31515">DataTemplate </span>
            <span style="color: red">x</span>
            <span style="color: blue">:</span>
            <span style="color: red">Key</span>
            <span style="color: blue">="SongTemplate"&gt;
&lt;</span>
            <span style="color: #a31515">StackPanel</span>
            <span style="color: blue">&gt;
&lt;</span>
            <span style="color: #a31515">TextBlock </span>
            <span style="color: red">Text</span>
            <span style="color: blue">="{</span>
            <span style="color: #a31515">Binding </span>
            <span style="color: red">Title</span>
            <span style="color: blue">}"/&gt;
&lt;/</span>
            <span style="color: #a31515">StackPanel</span>
            <span style="color: blue">&gt;
&lt;/</span>
            <span style="color: #a31515">DataTemplate</span>
            <span style="color: blue">&gt;
&lt;/</span>
            <span style="color: #a31515">Grid.Resources</span>
            <span style="color: blue">&gt;
&lt;</span>
            <span style="color: #a31515">ListBox </span>
            <span style="color: red">x</span>
            <span style="color: blue">:</span>
            <span style="color: red">Name</span>
            <span style="color: blue">="songListBox" </span>
            <span style="color: red">ItemsSource</span>
            <span style="color: blue">="{</span>
            <span style="color: #a31515">Binding </span>
            <span style="color: red">Songs</span>
            <span style="color: blue">, </span>
            <span style="color: red">Mode</span>
            <span style="color: blue">=Default, </span>
            <span style="color: red">Source</span>
            <span style="color: blue">={</span>
            <span style="color: #a31515">StaticResource </span>
            <span style="color: red">FactoryDS</span>
            <span style="color: blue">}}" </span>
            <span style="color: red">RenderTransformOrigin</span>
            <span style="color: blue">="0.5,0.5" </span>
            <span style="color: red">DisplayMemberPath</span>
            <span style="color: blue">="Title"
/&gt; &lt;/</span>
            <span style="color: #a31515">Grid</span>
            <span style="color: blue">&gt;</span>
          </pre>
        </blockquote>
        <p>
That worked great -- synchronously. But, as we already found out, a synchronous call
to the media library webservice isn't the best option (we'd rather page through the
results asynchronously, updating the UI while we go). So, I add a background thread,
changing the constructor to something like this:
</p>
        <blockquote>
          <pre class="code">
            <span style="color: blue">public </span>MediaLibrary()
{ System.Threading.<span style="color: #2b91af">Thread </span>thread = <span style="color: blue">new </span>System.Threading.<span style="color: #2b91af">Thread</span>(<span style="color: blue">new </span>System.Threading.<span style="color: #2b91af">ThreadStart</span>(GetSongs));
thread.Priority = <span style="color: #2b91af">ThreadPriority</span>.BelowNormal;
thread.Start(); } </pre>
        </blockquote>
        <p>
Run this, and you get a nasty cross-thread exception: "System.NotSupportedException:
This type of CollectionView does not support changes to its SourceCollection from
a thread different from the Dispatcher thread." Huh? What does my business layer need
to know about threading? I'm just updating a collection. But, not to be intimidated
easily, I try other options. How about implementing INotifyCollectionChanged rather
than inheriting from ObservableCollection? Same problem. So, Google reveals a nice
discussion by <a href="http://www.claassen.net/geek/blog/labels/INotifyPropertyChanged.html">ILoggable</a>.
He's as frustrated as I am. Really, should my data access layer know whether it's
running on the UI thread? I don't think so. Shouldn't the Binding mechanism in WPF
assume that I will be updating my business objects in background threads? After all,
what's the cost of a 4 core processor nowadays?
</p>
        <p>
I found a bunch of solutions to this problem that relied on explicitly making calls
to Application.Current.Dispatcher.BeginInvoke. That seems sleazy to me. One, slightly
less sleazy solution I found was to pass in a SynchronizationContext to the MediaLibrary
class. This still sounds like the business objects need to know too much about the
runtime, but at least SynchronizationContext is in the System.Windows.Threading namespace,
so it doesn't completely destroy my hopes of separating UI, business, and data.
</p>
        <p>
The solution I finally came up with (borrowed heavily from <a href="http://andyclymer.blogspot.com/2006/10/synchronizationcontext-assists.html">here</a>)
was a MediaLibrary with these changes:
</p>
        <blockquote>
          <p>
   <span style="color: blue">public class</span><span style="color: #2b91af">MediaLibrary </span>: <span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Song</span>&gt;, <span style="color: #2b91af">INotifyCollectionChanged<br />
   </span>{<br />
        <span style="color: blue">private const
int </span>_pageSize = 5;<br />
        <span style="color: blue">private</span><span style="color: #2b91af">IMediaLibraryService </span>_mediaLibrary
= <span style="color: blue">new</span><span style="color: #2b91af">MediaLibraryServiceClient</span>();<br />
        <span style="color: blue">private</span><span style="color: #2b91af">SynchronizationContext </span>_synchronizationContext;<br /><br />
        <span style="color: gray">/// &lt;summary&gt;<br />
        /// 
<br />
        /// &lt;/summary&gt;<br />
        </span><span style="color: blue">public</span>MediaLibrary(<span style="color: #2b91af">SynchronizationContext </span>sync)<br />
        {<br />
            _synchronizationContext
= sync;<br />
            System.Threading.<span style="color: #2b91af">Thread</span>thread
= 
<br />
                <span style="color: blue">new</span>System.Threading.<span style="color: #2b91af">Thread</span>(<span style="color: blue">new</span>System.Threading.<span style="color: #2b91af">ThreadStart</span>(GetSongs));<br />
            thread.Priority
= <span style="color: #2b91af">ThreadPriority</span>.BelowNormal;<br />
            thread.Start();<br />
        }<br />
        <span style="color: blue">private void</span>GetSongs()<br />
        {<br />
            <span style="color: #2b91af">IMediaLibraryService </span>mediaLibrary
= <span style="color: blue">new</span><span style="color: #2b91af">MediaLibraryServiceClient</span>();<br />
            <span style="color: blue">int </span>librarySize
= mediaLibrary.GetSongCount();<br />
            <span style="color: blue">int </span>i
= 0;<br />
            <span style="color: blue">while</span>(i
&lt; (librarySize + _pageSize))<br />
            {<br />
                <span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Guid</span>&gt;
currentIds = mediaLibrary.GetSongs(i, _pageSize);<br />
                <span style="color: blue">foreach </span>(<span style="color: #2b91af">Guid </span>id <span style="color: blue">in</span>currentIds)<br />
               
{<br />
                    <span style="color: #2b91af">Song</span>currentItem
= mediaLibrary.GetMediaInfo(id);<br />
                    <span style="color: blue">if</span>(<span style="color: blue">null</span>!=
currentItem)<br />
                   
{<br />
                        <span style="color: blue">this</span>.Add(currentItem);<br />
                       
SafeCollectionChangedNotification(currentItem);<br />
                   
}<br />
               
}<br />
               
i += _pageSize;<br />
            }<br />
        }<br /><br />
        <span style="color: blue">private void</span>SafeCollectionChangedNotification(<span style="color: #2b91af">Song</span>currentItem)<br />
        {<br />
            <span style="color: blue">if</span>(_synchronizationContext
!= <span style="color: blue">null</span>)<br />
            {<br />
               
_synchronizationContext.Post(<span style="color: blue">delegate<br />
               </span>{<br />
                   
OnCollectionChanged(currentItem);<br />
               
}, <span style="color: blue">null</span>);<br />
            }<br />
            <span style="color: blue">else<br />
           </span>{<br />
               
OnCollectionChanged(currentItem);<br />
            }<br />
        }<br /><br />
        <span style="color: blue">private void</span>OnCollectionChanged(<span style="color: #2b91af">Song</span>currentItem)<br />
        {<br />
            <span style="color: blue">if</span>(<span style="color: blue">null</span>!=
CollectionChanged)<br />
            {<br />
               
CollectionChanged(<span style="color: blue">this</span>, <span style="color: blue">new</span><span style="color: #2b91af">NotifyCollectionChangedEventArgs</span>(<br />
                    <span style="color: #2b91af">NotifyCollectionChangedAction</span>.Add,
currentItem));<br />
            }<br />
        }<br /><br />
        <span style="color: blue">#region</span>INotifyCollectionChanged
Members<br /><br />
        <span style="color: blue">public event</span><span style="color: #2b91af">NotifyCollectionChangedEventHandler </span>CollectionChanged;<br /><br />
        <span style="color: blue">#endregion</span></p>
        </blockquote>
        <p>
and passing in the context from the factory:
</p>
        <blockquote>
          <pre class="code">Songs = <span style="color: blue">new </span><span style="color: #2b91af">MediaLibrary</span>( <span style="color: blue">new </span>System.Windows.Threading.<span style="color: #2b91af">DispatcherSynchronizationContext</span>(
System.Windows.<span style="color: #2b91af">Application</span>.Current.Dispatcher)); </pre>
        </blockquote>
        <p>
Of course, this means the factory needs to know what context to pass in, but I wasn't
convinced the factory needed to be in the service layer anyway. Really, it's just
there so WPF has some form of static class to bind to. 
</p>
        <p>
I'm still not sure what I think about this approach. While it works, and can even
be used within a WinForms application (and probably even in ASP.NET), it seems like
we're putting the onus on the event producer rather than the even consumer (who is,
after all, the one who knows whether the event should be caught on a particular thread).
I guess that is one of the things I like about the event model in the Smart Client
Software Factory (SCSF). The producer just raises the even. If the consumer has specific
thread constraints on consuming that event, they declare them explicitly. Hmm. Maybe
I should start looking at using the SCSF to implement this thing...
</p>
        <img width="0" height="0" src="http://www.cavinconsulting.com/Colby/aggbug.ashx?id=6f370665-4125-4322-8c6c-e4651e4f6048" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Windows Media Player Remote Control - 6</title>
    <link rel="alternate" type="text/html" href="http://www.cavinconsulting.com/Colby/2008/01/22/WindowsMediaPlayerRemoteControl6.aspx" />
    <id>http://www.cavinconsulting.com/Colby/PermaLink,guid,a04fc2fb-b5f6-41e1-bcda-bf307e64e6de.aspx</id>
    <published>2008-01-22T16:42:11-07:00</published>
    <updated>2008-06-03T09:42:58.9345323-07:00</updated>
    <category term="Windows Media Player" label="Windows Media Player" scheme="http://www.cavinconsulting.com/Colby/CategoryView,category,WindowsMediaPlayer.aspx" />
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
This is the seventh in a series. 
</p>
        <ul>
          <li>
            <a href="http://www.cavinconsulting.com/Colby/2008/06/03/WindowsMediaPlayerRemoteControl0.aspx">Part
0</a>
          </li>
          <li>
            <a href="http://www.cavinconsulting.com/Colby/2007/12/11/WindowsMediaPlayerRemoteControl1.aspx">Part
1</a>
          </li>
          <li>
            <a href="http://www.cavinconsulting.com/Colby/2007/12/14/WindowsMediaPlayerRemoteControl2.aspx">Part
2</a>
          </li>
          <li>
            <a href="http://www.cavinconsulting.com/Colby/2007/12/21/WindowsMediaPlayerRemoteControl3.aspx">Part
3</a>
          </li>
          <li>
            <a href="http://www.cavinconsulting.com/Colby/2007/12/31/WindowsMediaPlayerRemoteControl4.aspx">Part
4</a>
          </li>
          <li>
            <a href="http://www.cavinconsulting.com/Colby/2008/01/03/WindowsMediaPlayerRemoteControl5.aspx">Part
5</a>
          </li>
        </ul>
        <p>
As of Part 5, we had a functional end to end solution (let's call it version 1.0)
that I deployed across my <strike>enterprise</strike> household. So, what's next?
As with any product, we know things don't stop here -- the clients have additional
expectations for functionality, the developers find new technology that would be cool
to use, and the QA team finds bugs. Now that it is deployed, however, I'll have to
pay special attention to version handling within our data and operation contracts.
</p>
        <p>
Before making many changes, I decided it might be nice to have some unit tests to
make sure I didn't break anything when rolling out new versions. A few tests later
and I was glad I did. It turns out, I didn't write perfect code during my initial
creation (shocking, I know). There were a few off by one errors, some stupid copy
and paste errors, and a couple of functions that were just plain wrong. So, even though
I didn't do test driven design, per say, I did gain the benefits of a module with
reasonable unit test coverage.
</p>
        <p>
So far, the biggest <strike>complaint</strike> observation from the user base has
been that the client application sucks. While it's functional, it certainly isn't
pretty. Additionally, it isn't the most robust implementation. For example, if you
close the server application and start it back up, the client never reconnects. This
is because, once a WCF service proxy faults, it stays faulted until you do something
about it. So, the next phase will be to write a more robust, prettier version of the
desktop client. Let's start with pretty.
</p>
        <p>
The first step in creating a prettier application is, as is standard in our industry,
to poach someone else's look and feel. While I certainly make my living within the
Microsoft camp, the innovative UI solutions fall solidly within the Macintosh camp.
So, let's take a look at Front Row. There's a great WPF implementation based on some
of the Front Row functionality in a "tutorial" called <a href="http://www.mperfect.net/backRow/">/backRow</a>.
It's been a while since the author updated the article, and the Macintosh camp could
do nothing but complain about the features that were missing. But, I'm no artist,
so I figure I'll start with the look and feel as presented in his article but with
a slightly different animation implementation. More on that later.
</p>
        <p>
Source for this article will be available as it becomes ready. The next few segments
will cover some of the challenges I ran into while developing the newer, prettier
UI. In the mean time, here are a couple of screen shots:
</p>
        <p>
          <a href="http://www.cavinconsulting.com/Colby/content/binary/WindowsLiveWriter/WindowsMediaPlayerRemoteControl6_C308/MusicLibrary_2.jpg">
            <img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="484" alt="MusicLibrary" src="http://www.cavinconsulting.com/Colby/content/binary/WindowsLiveWriter/WindowsMediaPlayerRemoteControl6_C308/MusicLibrary_thumb.jpg" width="637" border="0" />
          </a>
        </p>
        <p>
          <a href="http://www.cavinconsulting.com/Colby/content/binary/WindowsLiveWriter/WindowsMediaPlayerRemoteControl6_C308/NowPlaying_2.jpg">
            <img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="484" alt="NowPlaying" src="http://www.cavinconsulting.com/Colby/content/binary/WindowsLiveWriter/WindowsMediaPlayerRemoteControl6_C308/NowPlaying_thumb.jpg" width="637" border="0" />
          </a>
        </p>
        <img width="0" height="0" src="http://www.cavinconsulting.com/Colby/aggbug.ashx?id=a04fc2fb-b5f6-41e1-bcda-bf307e64e6de" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Windows Media Player Remote Control - 5</title>
    <link rel="alternate" type="text/html" href="http://www.cavinconsulting.com/Colby/2008/01/03/WindowsMediaPlayerRemoteControl5.aspx" />
    <id>http://www.cavinconsulting.com/Colby/PermaLink,guid,0a32e3a7-3392-4508-af74-949817e6ffff.aspx</id>
    <published>2008-01-03T16:05:20-07:00</published>
    <updated>2008-06-03T09:05:34.2039343-07:00</updated>
    <category term="Windows Media Player" label="Windows Media Player" scheme="http://www.cavinconsulting.com/Colby/CategoryView,category,WindowsMediaPlayer.aspx" />
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
This is the sixth in a series. 
</p>
        <ul>
          <li>
            <a href="http://www.cavinconsulting.com/Colby/2008/06/03/WindowsMediaPlayerRemoteControl0.aspx">Part
0</a>
          </li>
          <li>
            <a href="http://www.cavinconsulting.com/Colby/2007/12/11/WindowsMediaPlayerRemoteControl1.aspx">Part
1</a>
          </li>
          <li>
            <a href="http://www.cavinconsulting.com/Colby/2007/12/14/WindowsMediaPlayerRemoteControl2.aspx">Part
2</a>
          </li>
          <li>
            <a href="http://www.cavinconsulting.com/Colby/2007/12/21/WindowsMediaPlayerRemoteControl3.aspx">Part
3</a>
          </li>
          <li>
            <a href="http://www.cavinconsulting.com/Colby/2007/12/31/WindowsMediaPlayerRemoteControl4.aspx">Part
4</a>
          </li>
        </ul>
        <p>
With the completion of the previous article, I finally have a media player remote
control that allows a client to do most of the things set out in the original requirements
specification. So, what happened when I deployed it to my production server? Clicking
on the Playlist button causes all sorts of problems. Why? Unlike my test environment,
my production environment has several thousand songs in its media library. So, the
call to GetMediaLibrary() fails spectacularly. Even if it didn't fail completely,
an individual call to GetMediaInfo for each song would take prohibitively long if
I had a sizeable media library.
</p>
        <p>
Chris Sells wrote a wonderful article series on the benefits of multithreading in
WinForms version 1 (<a href="http://msdn2.microsoft.com/en-us/library/ms951089.aspx">here</a>, <a href="http://msdn2.microsoft.com/en-us/library/ms951109.aspx">here</a>,
and <a href="http://msdn2.microsoft.com/en-us/library/ms993020.aspx">here</a>). While
these methods are still applicable, multithreading has gotten easier in version 2
by using the BackgroundWorker component and a few other approaches outlined in Chris'
excellent book <a href="http://www.amazon.com/Windows-Forms-Programming-Microsoft-Development/dp/0321267966">Windows
Forms 2.0 Programming</a>. Additionally, the service reference I added to our client
application has asynchronous calls built-in, so I may be able to make use of those
to keep from freezing the UI.
</p>
        <p>
As far as I can tell, there are two popular ways to solve our problem: 1) take care
of paging in the UI, 2) take care of paging at the service level. There is a nice
discussion of some reasons for each <a href="http://davidpallmann.spaces.live.com/Blog/cns!E95EF9DC3FDB978E!275.entry">here</a>. 
</p>
        <p>
So, what's the answer? Our original goal was to allow client applications to run on
a variety of platforms, including via a web page. So, not all of our clients will
be able to solve the problem by multithreading the UI or using asynchronous calls.
I guess I have to figure out how to implement a service which will allow paging to
the client. That will allow us to solve the client responsiveness issue in whatever
way is most apparent for the client. Our WinForms application can call a huge get-all
type of solution in a background thread while showing a please wait message, 
our web application can page the current n records to the display, and our WPF front-end
can change animations and button themes by directly databinding to the service connection
state by injecting dependency objects into its visualization tree (or whatever it
is that the WPF kids are doing these days).
</p>
        <p>
That means changing our MediaLibraryService contract to look something like this:
</p>
        <blockquote>
          <pre class="code">[<span style="color: #2b91af">ServiceContract</span>(Namespace=<span style="color: #a31515">"http://www.cavinconsulting.com/MediaPlayerRemote/"</span>)] <span style="color: blue">public
interface </span><span style="color: #2b91af">IMediaLibraryService </span>{ [<span style="color: #2b91af">OperationContract</span>] <span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Guid</span>&gt;
GetMediaLibrary(); [<span style="color: #2b91af">OperationContract</span>] <span style="color: blue">int </span>GetSongCount();
[<span style="color: #2b91af">OperationContract</span>] <span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Guid</span>&gt;
GetSongs(<span style="color: blue">int </span>startRow, <span style="color: blue">int </span>rowCount);
[<span style="color: #2b91af">OperationContract</span>] <span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Guid</span>&gt;
GetSongsByAlbum(<span style="color: blue">string </span>albumID, <span style="color: blue">int </span>startRow, <span style="color: blue">int </span>rowCount);
[<span style="color: #2b91af">OperationContract</span>] <span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Guid</span>&gt;
GetSongsByGenre(<span style="color: blue">string </span>genre, <span style="color: blue">int </span>startRow, <span style="color: blue">int </span>rowCount);
[<span style="color: #2b91af">OperationContract</span>] <span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Guid</span>&gt;
GetSongsByArtist(<span style="color: blue">string </span>artist, <span style="color: blue">int </span>startRow, <span style="color: blue">int </span>rowCount);
[<span style="color: #2b91af">OperationContract</span>] <span style="color: #2b91af">Song </span>GetMediaInfo(<span style="color: #2b91af">Guid </span>songID);
} </pre>
        </blockquote>
        <p>
I've left the GetMediaLibrary() method to support the non-paged version of getting
all of the songs from our library. Also, I switched the song ID type from <span style="color: blue">string </span>to <span style="color: #2b91af">Guid</span> since
they will pass nicely across a WCF ServiceContract and DataContract. Lastly, I have
omitted some potentially useful methods such as GetGenres and GetArtists. That is
because the underlying media library doesn't really support this easily. We may add
this later, depending on the requirements of our client applications, but it will
be less than trivial.
</p>
        <p>
The implementation of the paged back-end was relatively straight forward, though the
implementation I came up with may not be the fastest. Now, we can take a look at how
make use of them from the BackgroundWorker control. Here's what I did: drop a BackgroundWorker
control on the form, add a DoWork event handler, add a DoWorkAsync call to the form
load. Here's what I ended up with for the DoWork event handler:
</p>
        <blockquote>
          <pre class="code">
            <span style="color: blue">private void </span>_mediaLibraryBackgroundWorker_DoWork(<span style="color: blue">object </span>sender, <span style="color: #2b91af">DoWorkEventArgs </span>e)
{ <span style="color: green">// Populate the library </span><span style="color: blue">int </span>librarySize
= _mediaLibraryService.GetSongCount(); <span style="color: blue">int </span>i = 0; <span style="color: blue">while </span>(i
&lt; (librarySize + _pageSize)) { <span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Guid</span>&gt;
currentIds = _mediaLibraryService.GetSongs(i, _pageSize); <span style="color: blue">foreach </span>(<span style="color: #2b91af">Guid </span>id <span style="color: blue">in </span>currentIds)
{ <span style="color: #2b91af">Song </span>currentItem = _mediaLibraryService.GetMediaInfo(id); <span style="color: blue">if </span>(<span style="color: blue">null </span>!=
currentItem) { AddSong(currentItem); } } i += _pageSize; } } </pre>
        </blockquote>
        <p>
Where the AddSong() method looks something like this:
</p>
        <blockquote>
          <pre class="code">
            <span style="color: blue">private delegate void </span>
            <span style="color: #2b91af">AddSongDelegate</span>(<span style="color: #2b91af">Song </span>song); <span style="color: blue">private
void </span>AddSong(<span style="color: #2b91af">Song </span>song) { <span style="color: blue">if </span>(InvokeRequired)
{ <span style="color: green">// Invoke AddSong on the UI thread (since this gets called
from the worker thread) </span><span style="color: blue">this</span>.BeginInvoke(<span style="color: blue">new </span><span style="color: #2b91af">AddSongDelegate</span>(AddSong), <span style="color: blue">new
object</span>[] { song }); } <span style="color: blue">else </span>{ <span style="color: blue">if </span>(<span style="color: blue">null </span>!=
song) { _mediaLibrary.Add(song); <span style="color: green">// {... Add the appropriate
TreeNodes to the TreeView ...} </span> } } }</pre>
          <a href="http://11011.net/software/vspaste">
          </a>
        </blockquote>
        <p>
That's it. Now, the playlist UI comes up immediately and the library pane is updated
a few songs at a time, while still remaining responsive to the user. One thing to
note -- the only time we access our member collection (_mediaLibrary) is after we
know we're on the UI thread. So, we shouldn't have any problems with concurrent access
to the collection (reader / writer problem). As a result, we don't have to mess around
with locking the collection or using the SynchronizedCollection&lt;Song&gt; class.
Of course, I could be wrong, and often am.
</p>
        <p>
The source for this version is available <a href="http://www.cavinconsulting.com/Code/MediaPlayerRemote5.zip">here</a>.
Now that things are functional (i.e., we've proven the concept), it's probably time
to revisit the design and implementation with an eye for error handling, testing,
usability, etc. Since the service layer is the foundation for a potentially large
number of clients, we should probably start there.
</p>
        <img width="0" height="0" src="http://www.cavinconsulting.com/Colby/aggbug.ashx?id=0a32e3a7-3392-4508-af74-949817e6ffff" />
      </div>
    </content>
  </entry>
</feed>