RSS 2.0
# Thursday, January 24, 2008

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 (/backRow) 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.

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 AnimationBehaviors 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.

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.

The first thing to do was to create a place to store the current animation behavior:

public class NavigationAnimation : INotifyPropertyChanged
{
    // Singleton class
    private NavigationAnimation() { }
    public enum NavigationDirection
    {
        Forward,
        Backward
    };
    private static NavigationAnimation _instance = new NavigationAnimation();
    public static NavigationAnimation Instance
    {
        get { return NavigationAnimation._instance; }
        set { NavigationAnimation._instance = value; }
    }
    public static void SetNavigationDirection(NavigationDirection direction)
    {
        if(NavigationDirection.Forward==direction)
        {
            Instance.AnimationBehavior = LoadedBehavior.SlideInFromRight;
        }
        else
        {
            Instance.AnimationBehavior = LoadedBehavior.SlideInFromLeft;
        }
    }
    private LoadedBehavior _animationBehavior = LoadedBehavior.SlideInFromRight;
    public LoadedBehavior AnimationBehavior
    {
        get { return _animationBehavior; }
        set {
            _animationBehavior = value;
            OnPropertyChanged("AnimationBehavior");
        }
    }
    private void OnPropertyChanged(string propertyName)
    {
        if (null != PropertyChanged)
        {
            PropertyChangedEventArgs e = new PropertyChangedEventArgs(propertyName);
            PropertyChanged(this,e);
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

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:

private void OnNavigating(object sender, NavigatingCancelEventArgs e)
{
    if (e.NavigationMode == NavigationMode.Back)
    {
        NavigationAnimation.SetNavigationDirection(NavigationAnimation.NavigationDirection.Backward);
    }
    else
    {
        NavigationAnimation.SetNavigationDirection(NavigationAnimation.NavigationDirection.Forward);
    }
}

Finally, we bind our AnimationBehaviorHost.LoadedBehavior to our current animation behavior.

private void OnNavigating(object sender, NavigatingCancelEventArgs e)
{
    if (e.NavigationMode == NavigationMode.Back)
    {
        NavigationAnimation.SetNavigationDirection(NavigationAnimation.NavigationDirection.Backward);
    }
    else
    {
        NavigationAnimation.SetNavigationDirection(NavigationAnimation.NavigationDirection.Forward);
    }
}

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!

Thursday, January 24, 2008 3:45:17 PM (Pacific Standard Time, UTC-08:00)  #    Comments [0] -
Windows Media Player
# Wednesday, January 23, 2008

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.

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.

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:

private System.Windows.Media.Imaging.BitmapSource FromBitmap(System.Drawing.Bitmap bitmap)
{
    return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
        bitmap.GetHbitmap(), 
        IntPtr.Zero, 
        System.Windows.Int32Rect.Empty, 
        System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
}

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?

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 excellent book on COM Interop. 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.

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:

private System.Windows.Media.Imaging.BitmapSource BitmapSourceFromImage(System.Drawing.Image img)
{
    System.IO.MemoryStream memStream = new System.IO.MemoryStream();
    img.Save(memStream, System.Drawing.Imaging.ImageFormat.Png);
    System.Windows.Media.Imaging.PngBitmapDecoder decoder = 
            new System.Windows.Media.Imaging.PngBitmapDecoder(
            memStream, 
            System.Windows.Media.Imaging.BitmapCreateOptions.PreservePixelFormat, 
            System.Windows.Media.Imaging.BitmapCacheOption.Default);
    return decoder.Frames[0];
}

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.

Wednesday, January 23, 2008 3:44:40 PM (Pacific Standard Time, UTC-08:00)  #    Comments [0] -
Windows Media Player
# Tuesday, January 22, 2008

This is the eighth in a series, but the numbering is getting confusing, so I'm going to stop counting.

The first step I took in creating my pretty WMP remote control UI was to steal 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:

public class MediaLibrary : ObservableCollection<Song>
{
    public MediaLibrary()
    {
        GetSongs();
    }
    private void GetSongs()
    {
        IMediaLibraryService mediaLibrary = new MediaLibraryServiceClient();
        int librarySize = mediaLibrary.GetSongCount();
        int i = 0;
        while (i < (librarySize + _pageSize))
        {
            List<Guid> currentIds = mediaLibrary.GetSongs(i, _pageSize);
            foreach (Guid id in currentIds)
            {
                Song currentItem = mediaLibrary.GetMediaInfo(id);
                if (null != currentItem)
                {
                    this.Add(currentItem);
                }
            }
            i += _pageSize;
        }
    }
}
public class Factory
{
    /// <summary>
    /// 
    /// </summary>
    static Factory()
    {
        Songs = new MediaLibrary();
    }
    public static MediaLibrary Songs { get; private set; }
}

And I bound the contents to the UI using syntax like this:

<Grid>
  <Grid.Resources>
    <ObjectDataProvider x:Key="FactoryDS" ObjectType="{x:Type local:Factory}"/>
    <DataTemplate x:Key="SongTemplate">
      <StackPanel>
        <TextBlock Text="{Binding Title}"/>
      </StackPanel>
    </DataTemplate>
  </Grid.Resources>
  <ListBox x:Name="songListBox" 
           ItemsSource="{Binding Songs, Mode=Default, Source={StaticResource FactoryDS}}" 
           RenderTransformOrigin="0.5,0.5" 
           DisplayMemberPath="Title" />
</Grid>

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:

public MediaLibrary()
{
    System.Threading.Thread thread = 
        new System.Threading.Thread(new System.Threading.ThreadStart(GetSongs));
    thread.Priority = ThreadPriority.BelowNormal;
    thread.Start();
}

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 ILoggable. 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?

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.

The solution I finally came up with (borrowed heavily from here) was a MediaLibrary with these changes:

   public classMediaLibrary : List<Song>, INotifyCollectionChanged
  
{
        private const int _pageSize = 5;
        privateIMediaLibraryService _mediaLibrary = newMediaLibraryServiceClient();
        privateSynchronizationContext _synchronizationContext;

        /// <summary>
        ///
        /// </summary>
       
publicMediaLibrary(SynchronizationContext sync)
        {
            _synchronizationContext = sync;
            System.Threading.Threadthread =
                newSystem.Threading.Thread(newSystem.Threading.ThreadStart(GetSongs));
            thread.Priority = ThreadPriority.BelowNormal;
            thread.Start();
        }
        private voidGetSongs()
        {
            IMediaLibraryService mediaLibrary = newMediaLibraryServiceClient();
            int librarySize = mediaLibrary.GetSongCount();
            int i = 0;
            while(i < (librarySize + _pageSize))
            {
                List<Guid> currentIds = mediaLibrary.GetSongs(i, _pageSize);
                foreach (Guid id incurrentIds)
                {
                    SongcurrentItem = mediaLibrary.GetMediaInfo(id);
                    if(null!= currentItem)
                    {
                        this.Add(currentItem);
                        SafeCollectionChangedNotification(currentItem);
                    }
                }
                i += _pageSize;
            }
        }

        private voidSafeCollectionChangedNotification(SongcurrentItem)
        {
            if(_synchronizationContext != null)
            {
                _synchronizationContext.Post(delegate
              
{
                    OnCollectionChanged(currentItem);
                }, null);
            }
            else
          
{
                OnCollectionChanged(currentItem);
            }
        }

        private voidOnCollectionChanged(SongcurrentItem)
        {
            if(null!= CollectionChanged)
            {
                CollectionChanged(this, newNotifyCollectionChangedEventArgs(
                    NotifyCollectionChangedAction.Add, currentItem));
            }
        }

        #regionINotifyCollectionChanged Members

        public eventNotifyCollectionChangedEventHandler CollectionChanged;

        #endregion

and passing in the context from the factory:

Songs = new MediaLibrary(
    new System.Windows.Threading.DispatcherSynchronizationContext(
        System.Windows.Application.Current.Dispatcher));

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.

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...

Tuesday, January 22, 2008 3:43:45 PM (Pacific Standard Time, UTC-08:00)  #    Comments [0] -
Windows Media Player

This is the seventh in a series.

As of Part 5, we had a functional end to end solution (let's call it version 1.0) that I deployed across my enterprise 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.

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.

So far, the biggest complaint 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.

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 /backRow. 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.

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:

MusicLibrary

NowPlaying

Tuesday, January 22, 2008 3:42:11 PM (Pacific Standard Time, UTC-08:00)  #    Comments [0] -
Windows Media Player
# Thursday, January 03, 2008

This is the sixth in a series.

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.

Chris Sells wrote a wonderful article series on the benefits of multithreading in WinForms version 1 (here, here, and here). 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 Windows Forms 2.0 Programming. 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.

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 here.

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).

That means changing our MediaLibraryService contract to look something like this:

[ServiceContract(Namespace="http://www.cavinconsulting.com/MediaPlayerRemote/")]
public interface IMediaLibraryService
{
    [OperationContract]
    List<Guid> GetMediaLibrary();
    [OperationContract]
    int GetSongCount();
    [OperationContract]
    List<Guid> GetSongs(int startRow, int rowCount);
    [OperationContract]
    List<Guid> GetSongsByAlbum(string albumID, int startRow, int rowCount);
    [OperationContract]
    List<Guid> GetSongsByGenre(string genre, int startRow, int rowCount);
    [OperationContract]
    List<Guid> GetSongsByArtist(string artist, int startRow, int rowCount);
    [OperationContract]
    Song GetMediaInfo(Guid songID);
}

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 string to Guid 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.

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:

private void _mediaLibraryBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    // Populate the library
    int librarySize = _mediaLibraryService.GetSongCount();
    int i = 0;
    while (i < (librarySize + _pageSize))
    {
        List<Guid> currentIds = _mediaLibraryService.GetSongs(i, _pageSize);
        foreach (Guid id in currentIds)
        {
            Song currentItem = _mediaLibraryService.GetMediaInfo(id);
            if (null != currentItem)
            {
                AddSong(currentItem);
            }
        }
        i += _pageSize;
    }
}

Where the AddSong() method looks something like this:

private delegate void AddSongDelegate(Song song);

private void AddSong(Song song)
{
    if (InvokeRequired)
    {
        // Invoke AddSong on the UI thread (since this gets called from the worker thread)
        this.BeginInvoke(new AddSongDelegate(AddSong), new object[] { song });
    }
    else
    {
        if (null != song)
        {
            _mediaLibrary.Add(song);
            
            // {... Add the appropriate TreeNodes to the TreeView ...}
        }
    }
}

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<Song> class. Of course, I could be wrong, and often am.

The source for this version is available here. 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.

Thursday, January 03, 2008 3:05:20 PM (Pacific Standard Time, UTC-08:00)  #    Comments [0] -
Windows Media Player
# Monday, December 31, 2007

This is the fifth in a series.

This time, let's concentrate on the manipulations a user will want to do on the media library (retrieving songs, genres, artists, etc.). For this, we'll add another WCF Service to the MediaPlayerRemoteListener project called MediaLibraryService. The service contract for this will looks something like:

[ServiceContract]
public interface IMediaLibraryService
{
    [OperationContract]
    List<Song> GetMediaLibrary();
}

With that, all we need to do is plug in the implementation on the server side and start making use of it on the client side. Of course, this is were things get difficult.

Once again, I find myself at odds with the tools. I've labeled both service contracts with the "ServiceContract" attribute. I've also been very careful to use the "DataContract" attribute for any data items returned from our service (in this case, the Song data contract). However, when adding references from the client via the Add Service Reference option, I am faced with two copies of the Song data contract on the client -- one in the MediaLibrary namespace, and one in the NowPlaying namespace. So, if I get a List<Song> from my MediaLibrary service, and I want to send them to the Play() method of the NowPlaying service, I have to convert the MediaLibrary.Song to a NowPlaying.Song. This leads to a large number of mapper classes (or one cleverly designed generic mapper that uses reflection). I recall similar difficulties with the old .NET 2.0 webservices, and I had hoped this challenge had been overcome in the new tool set. Apparently not.

I supposed it's prudent to talk about the idea of a data contract. Should separate services need to share the exact same data definition as an input or an output? One could argue that if they're so similar, they should be a part of the same service. However, the simple truth is that it happens quite often in the real world. For example I'd like to host one interface for read only access and one interface for read/write access. This allows separate levels of permissions / authentication / protocol for each interface.

One solution is to revert to command line tools with the new /shareTypes parameter to wsdl.exe (via http://www.theserverside.net/tt/blogs/showblog.tss?id=WSStrikesBackP6). But, this makes the already tedious task of updating our service reference all the more tedious. Every time I change my contract (which has happened several times so far), I have to run the hosted version of my service library, escape to the command line and run a batch file refreshing the service reference in our client application. Of course, now that I write it down, it's not that much more difficult than changing the port numbers in my app.config and running the built-in refresh command.

Here's another option. Given our current implementation, we may be able to change the interfaces to remove any need to share data contracts. Does the Play method really need the entire song, or just some form of unique identifier to allow the media player to add it to the play list? It seems like we may be able to get by with a single GetMediaInfo method returning all of the Song information, and simply passing around some form of unique identifier for all of the rest of the methods. So we end up with interfaces like this:

[ServiceContract(Namespace = "http://www.cavinconsulting.com/MediaPlayerRemote/")]
public interface INowPlayingService
{
    [OperationContract]
    PlayState GetPlayState();
    [OperationContract]
    string GetCurrentSong();
    [OperationContract]
    List<string> GetCurrentPlaylist();
    [OperationContract]
    void VolumeUp(int amount);
    [OperationContract]
    void VolumeDown(int amount);
    [OperationContract]
    void SetVolume(int volume);
    [OperationContract]
    void MoveNext();
    [OperationContract]
    void MovePrevious();
    [OperationContract]
    void MoveToSong(string song);
    [OperationContract]
    void Play();
    [OperationContract]
    void Pause();
    [OperationContract]
    void Stop();
    [OperationContract]
    void SetRandom(bool random);
    [OperationContract]
    void SetRepeat(bool repeat);
    [OperationContract]
    void SetMute(bool mute);
    [OperationContract]
    void PlayPlaylist(List<string> playlist, bool appendToCurrentPlaylist);
}
[ServiceContract(Namespace="http://www.cavinconsulting.com/MediaPlayerRemote/")]
public interface IMediaLibraryService
{
    [OperationContract]
    List<string> GetMediaLibrary();
    [OperationContract]
    Song GetMediaInfo(string song);
}

This has the advantage of sending around significantly less data than our previous version. It has the downside of passing primary keys around as strings (I think WMP uses a 128 bit GUID). This isn't exactly what I had in mind for a solution, but it seems to be the direction the tools are pushing me. I'm still not sure this makes sense from a practical standpoint, but we'll keep on following this path for a while longer.

The source for this post is available here. There is a really bad implementation of a ListBox that supports being a DragDrop source as well as destination, and a horrible implementation of displaying a media library in a TreeView (BTW, Drag and Drop on playlists only works for songs in this example).

Monday, December 31, 2007 3:02:51 PM (Pacific Standard Time, UTC-08:00)  #    Comments [0] -
Windows Media Player
# Friday, December 21, 2007

This is the fourth in a series.

With our "design" out of the way, we can start digging in to the actual implementation. Our first draft will be somewhat exploratory in nature. Given my limited knowledge of the Windows Media Player plug-in architecture, I have decided to start by hosting the WMP ActiveX control in a standalone WinForms application, and have this WinForms application host a WCF service. So, here goes:

We'll start off by designing the communication contract through which our client controls and queries our media player. For now, we'll concentrate on controlling the media player. For this, we'll use a WCF contract called INowPlayingService:

[ServiceContract]
public interface INowPlayingService
{
    [OperationContract]
    PlayState GetPlayState();
    [OperationContract]
    Song GetCurrentSong();
    [OperationContract]
    List<Song> GetCurrentPlaylist();
    [OperationContract]
    void VolumeUp(int amount);
    [OperationContract]
    void VolumeDown(int amount);
    [OperationContract]
    void SetVolume(int volume);
    [OperationContract]
    void MoveNext();
    [OperationContract]
    void MovePrevious();
    [OperationContract]
    void Play();
    [OperationContract]
    void Pause();
    [OperationContract]
    void Stop();
    [OperationContract]
    void SetRandom(bool random);
    [OperationContract]
    void SetRepeat(bool repeat);
    [OperationContract]
    void SetMute(bool mute);
    [OperationContract]
    List<Song> AddToCurrentPlaylist(List<Song> playlist);
    [OperationContract]
    void PlayInPlaylist(Song song);
    [OperationContract]
    void ReplaceCurrentPlaylist(List<Song> playlist);
}

That looks like a pretty comprehensive list of operations we would want to perform on a media player. So, let's get down to the business of actually implementing this in Visual Studio 2008. I start a new solution and add three projects, a WinForms host application, a WinForms Client application, and WCF Service Library. I add a project reference from the host application to the service library. Then, I notice I can add a service reference from the client application to the service library. Right click on the project, click add service reference, click discover->services in this solution, and choose the service of interest. Nice! Or, so I thought.

Here's where the first problem arises. Remember, I'm using this as an exercise to get my head around the new technologies. The WCF service library project type does a nice job of housing the service components as well as publishing the appropriate meta data for things like adding service references. However, when I go to debug this application, VS automatically spins up the WcfSvcHost process to host our service library. But, remember, I want to host the WCF endpoint within my host WinForms application. No matter what projects you tell VS to start up (or not start up) on debug, it ALWAYS runs the WcfSvcHost application and starts hosting my service library.

It turns out, I'm not the first person to have this problem: Visual Studio 2008, WCF Service Libraries, and CTRL-F5. It appears that the solution is to "remove the project type GUID" that tells VS that it's a WCF Service Library. What? So, in order to host a WCF service library in my own application, I have to disable all of the helpful aspects of VS regarding WCF endpoints (like, say, updating my service reference as the contract changes over time). Ridiculous.

Here's how I finally resolved it. Leave it as a WCF service library, but change the port values in the app.conf sections so my host uses a different port than the WCF service library. That way, in the course of normal debugging, the client points to the ports opened by my host. When I need to update the reference, I change the port to the VS host port, update the reference, and then change it back. It's a nasty bit of kludgery, but it works for my needs. It seems like I must be making a habit of doing things Microsoft doesn't expect. First, I expected a standard windows application to be simple in WPF, now this.

Anyway, source code (so far) is available here. You'll want to change the URL property of the media player control in the host application. You'll also want to set the startup projects so that the host and the client are both started. It's a pretty basic remote control with standard navigation utilities. Next, we'll flesh out some of the media library functionality so we can change what gets played.

Friday, December 21, 2007 2:56:46 PM (Pacific Standard Time, UTC-08:00)  #    Comments [0] -
Windows Media Player
# Friday, December 14, 2007

This is the third in a series.

Design

As with any good development effort, we begin by designing the solution, complete with an assessment of the pros and cons of each option. Of course, as with any good development effort, we begin with every intention of designing the solution, but we usually skip right past this to writing the code since designs are never any fun. Design: There is a server and there are 0 or more clients that want to control what the server spits out the sound card.

Right. With the design done, let's talk about implementation options:

As I see it, there are two options for implementing the functionality as exhaustively enumerated in Part 0 of our series: 1) A standalone application in which we host and automate a Windows Media Player control, 2) A plug-in to the existing standalone Windows Media Player in which we automate the instance of Windows Media Player in which we are hosted.

So, which of these approaches is better? I have no idea. So, we'll design the approach in such a way that the end user (client machine) doesn't care. How? SOA, WCF, and other TLA's. I figure I can hide my media playing component/service/application behind a WCF connection point. Then, if hosting the ActiveX control fails miserably or creating the WMP plug-in doesn't play nicely with .NET, then I'll always be able to call some arcane WIN32 function to dump directly to the sound card or convert to Linux, convert all of my WMA's to raw .au files and just cat [file.au] > /dev/audio.

Of course, that's an exaggeration. I'm sure one of the two approaches will work fine. I just don't know which. So, hiding the solution behind a WCF connection point should give me the flexibility to try both approaches without rewriting the clients.

At this point, I find that there are a couple of interesting questions to which I do not know the answer. This, of course, will not keep me from plunging headlong into the implementation. They're just questions.

  • If I host an instance of the WMP ActiveX control, does it still do all of the clever background work of sniffing media information from the Internet, listening for changes in my media library, and downloading album art or is it just a numb playback machine using the existing media library?
  • What are the multi-threading characteristics of the WMP library? Will I have to perform the read/write locks, or will WMP take care of that for me?
Friday, December 14, 2007 2:54:53 PM (Pacific Standard Time, UTC-08:00)  #    Comments [0] -
Windows Media Player
# Tuesday, December 11, 2007

Build or Buy decision

This is the second in a series. The overview is here.

State of the industry:

So far, I can find a bunch of solutions to stream media to a client. That is, given a server containing a bunch of media, Spit it out to a client machine (PC, cell phone, television, etc.) so you can consume it wherever you are. This doesn't cut it for our purposes. Instead, we want the media to play at the source, but be able to change the behavior of the media player at the host from a client somewhere.

Items of interest:

So far, that's all I have. So, if I want a remote control to work on a laptop, pocket pc, smartphone, (and maybe a website), it looks like I'm out of luck in the commercial market. So, it looks like the build option is the one for me.

Of course, that's what I expected to choose. Otherwise, this would have been a really short series.

Tuesday, December 11, 2007 2:51:22 PM (Pacific Standard Time, UTC-08:00)  #    Comments [0] -
Windows Media Player
# Monday, December 10, 2007

This is the beginning in a series of unknown length regarding controlling the Windows Media Player from remote machines. So far, I'm at the requirements phase. Next will come industry research (buy or build), but I'm pretty sure I'm going to build something anyway (even if there are perfectly usable buy options -- I'm just stubborn that way).

Here are the requirements in no particular format or order:

  • I have a Server 2003 machine running with its audio output hooked up to the whole house audio system (okay, it's just two speakers in a different room, but there's a volume control in there, so I can call it what I want). The server houses the media collection and runs a uPnP server (TwonkyMedia) for the rest of the machines in the house to stream.
  • I can play audio through the server if I remote terminal to the server, run media player, and choose some songs. That, of course, completely fails the Wife Acceptance Factor (WAF).
  • What I would like is a service or application running on the server to be ready to play at all times, and have the rest of the machines (including handheld and smartphone) be able to dynamically change the playlist, start, stop, fast forward (most important) and rewind.
  • I'd like this to run as part of Media Player. I'm not sure why, since SOA dictates that we're just exposing a service, not a particular technology. I think it's mainly because I'm used to maintaining the media library in WMP and I don't want to change.
  • An added bonus is if there were a sidebar gadget for my wife's Vista machine (yes, I'm still on XP until some of the performance issues are worked out), and a 10' UI for the media center PC in the family room.
  • Since the uPnP server streams media to all of the important places (laptop and media center), there's no reason to mess around with streaming the actual audio to the remote control client, though the now-playing art would be nice.

That's it. In those few, short paragraphs, I have managed to cut out a lot of work for myself. I'm looking for a media player with remote controls that run on smartphone, pda, xp, and as a sidebar gadget. I'd like it to run on server 2003 every time it starts up, be multi-remote control robust, and extremely fault tolerant.

Now, to the buy or build comparisons...

Monday, December 10, 2007 7:48:37 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0] -
Windows Media Player
Navigation
Categories
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2012
Cavin Consulting
Sign In
Statistics
Total Posts: 28
This Year: 0
This Month: 0
This Week: 0
Comments: 4
All Content © 2012, Cavin Consulting
DasBlog theme 'Business' created by Christoph De Baene (delarou)