<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Nathan Bridgewater &#187; WCF</title>
	<atom:link href="http://www.integratedwebsystems.com/category/dotnet/wcf/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.integratedwebsystems.com</link>
	<description>My Little .NET Sandbox</description>
	<lastBuildDate>Thu, 19 Jan 2012 20:37:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Silverlight, WCF REST and Streaming My Personal Music Repository from a Standalone EXE</title>
		<link>http://www.integratedwebsystems.com/2010/04/part-2-silverlight-wcf-rest-and-streaming-my-personal-music-repository-from-a-standalone-exe/</link>
		<comments>http://www.integratedwebsystems.com/2010/04/part-2-silverlight-wcf-rest-and-streaming-my-personal-music-repository-from-a-standalone-exe/#comments</comments>
		<pubDate>Tue, 27 Apr 2010 02:54:00 +0000</pubDate>
		<dc:creator>Nathan</dc:creator>
				<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[music]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[streaming]]></category>

		<guid isPermaLink="false">http://www.integratedwebsystems.com/?p=349</guid>
		<description><![CDATA[This is way cool. From time to time, I tend to screw...]]></description>
			<content:encoded><![CDATA[<link rel="stylesheet" type="text/css" href="/css/jquery.lightbox-0.5.css" />
<p> 	This is way cool. From time to time, I tend to screw around with stuff I enjoy that 	really has little productive value.&#160; A year ago this month, I recall wanting 	to continue writing about sharing your personal music without using IIS and hosting 	the music directly from a WCF standalone executable. Well it turns out this is a 	whole lot simpler than I originally thought.</p>
<p> 	<em><strong>Disclaimer: </strong>This probably isn’t best practice, and it’s ripe for 		enhancements. My hope is that it gets your imagination fired up and motivates you 		to continue where I left off.</em></p>
<p> 	<strong>Challenges:</strong></p>
<ul>
<li>How the heck do I stream an MP3 file to a media element via WCF (without having 		to download the whole file before playing it)? </li>
<li>Cross-site scripting policies are blocking my download requests. How can I serve 		these up via my self hosted WCF REST service? </li>
<li>Silverlight3 doesn’t support WCF REST yet. How do I deserialize the WCF REST contract 		messages? </li>
</ul>
<p> 	&#160;</p>
<h3> 	Changes Since Last Release</h3>
<p> 	<a title="Click to view full size" href="/resources/p349/player.jpg" class="lightbox"> 		<img title="Click to View" border="0" alt="player_small" align="right" src="http://www.integratedwebsystems.com/wp-content/uploads/2010/04/player_small.jpg" width="240" height="171" /></a> My original design was very simple.&#160; 	I hosted the Silverlight files and used WCF with an IIS server at home. The player 	pulled a list of files and locations. The player’s media element source was set 	directly to a music file hosted in an IIS virtual directory. All that works great 	until you are on a machine without a web server. Ultimately, I wanted to figure 	out a way for the user to host their music repository from their desktop with a 	simple executable and port forwarding. Which means it would have to serve up all 	the resources necessary to run the Silverlight player. It would also have to serve 	up the WCF services and actual music files themselves.</p>
<p> 	Since the last post a year ago, I’ve made quite a few little tweaks to the player 	like: regular expression search, random songs, random play order, and a volume control. 	I also integrated a compact SQLite database for searching so the server-side doesn’t 	have to do a file system search for each request.</p>
<h3> 	&#160;</h3>
<p> <span id="more-349"></span><br />
<h3> 	WCF REST</h3>
<p> 	So first, how to we host the resources and music files?&#160;&#160; This is where 	WCF REST comes into play. WCF REST allows us to host a service or respond to an 	HTTP GET request very easily. And since we can host any WCF service in an executable, 	it makes for a pretty easy standalone option.&#160; The only real caveats here are 	security and firewall access, which in this demo are <em><strong>non-existent</strong></em>. 	You will also need to enable port-forwarding in your firewall for whichever port 	you decide to host the WCF service app. For this sample, I’m using TCP port 8000.</p>
<p> 	I found in <a href="http://blogs.vertigo.com/personal/petar/Blog/archive/2008/03/26/wcf-calls-from-silverlight-applications-sl-2-0-b1.aspx" target="_blank">this article by Peter Vucetin</a> on how to serve up any request 	with a custom MIME type. I took what he had and tweaked it a little so I could serve 	up content like the silverlight package, html files and a javascript resources.</p>
<p> 	&#160;</p>
<h3> 	Playing Media</h3>
<p> 	Okay, so the first problem with playing media is… how do we stream audio files from 	a WCF service to a media element in Silverlight?&#160; Well, it’s as simple as setting 	the MediaElement source to a method endpoint in the WCF service, which returns a 	FileStream to the audio file. </p>
<p> 	For example, our service endpoint lives at: <em>http://localhost:8000/Music</em> 	for the MusicStreamerService. Our function endpoint is <em>Files(string filename)</em> 	using the route: /Files/{filename}.&#160; So our source for the media element becomes 	<em>http://localhost:8000/Music/Files/{filename}</em>. On the server side, I simply 	set the content type and returned a direct FileStream to the file. This allows the 	player to behave like a normal web server and stream the file, which allows the 	Media Element to immediately start reading the data as it comes down. I also tweaked 	the request path a little bit for the filename parameter, which contains full relative 	path.&#160; If using the WCF service to host the file, then I enable a base64 encode 	option that encodes the entire relative path so as not to confuse the WCF request 	routing.&#160; If I choose to serve it up with a normal web servr, then I can disable 	the base64 encode and use UrlEncode instead so it treats the request as a normal 	file system request against a virtual directory. </p>
<p> 	&#160;</p>
<h3> 	Hosting Policy Files</h3>
<p> 	Cross site scripting… That’s our next problem.&#160; Say your website with silverlight 	resources are hosted on one server and your music file server is hosted on another. 	If you host a silverlight app and access a web url across domains, then you’re going 	to need to serve up the cross site policy files. I wrote a simple file serve function 	that kicks out a local file when you request it. However I setup a separate service 	contract and endpoint since the policy files have to reside at the root of the host.</p>
<p> 	&#160;</p>
<h3> 	Deserializing DataContracts Manually</h3>
<p> 	Silverlight3 doesn’t like consuming WCF REST services yet. So for the functionality 	of searching and listing the files available, I’m manually retrieving the XML response 	over asynchronous HTTP calls and then use System.Runtime.Serialization.DataContractSerializer 	to do handle the data.&#160; On the client side, I copied data contract proxy classes 	from my service so their serialized definitions match.&#160; </p>
<p> 	&#160;</p>
<h3> 	Configure the Projects</h3>
<p> 	There are a few settings to be aware of. First, the Silverlight initializes with 	the location of the WCF endpoints. This is why we have a separate html file for 	the console app and the web app in the sample. The url is specified using the InitParams 	parameter on the html object. The standalone sample uses <em>console.html</em> whose 	initParams is set to: <em>baseuri=http://localhost:8000/Music </em>shown here.</p>
<pre class="brush: xml; gutter: false;">&lt;object data=&quot;data:application/x-silverlight-2,&quot; type=&quot;application/x-silverlight-2&quot; width=&quot;814px&quot; height=&quot;580px&quot;&gt;
  &lt;param name=&quot;source&quot; value=&quot;ClientBin/MusicPlayerCustom.xap&quot;/&gt;
  &lt;param name=&quot;onError&quot; value=&quot;onSilverlightError&quot; /&gt;
  &lt;param name=&quot;background&quot; value=&quot;white&quot; /&gt;
  &lt;param name=&quot;minRuntimeVersion&quot; value=&quot;3.0.40624.0&quot; /&gt;
  &lt;param name=&quot;autoUpgrade&quot; value=&quot;true&quot; /&gt;
  &lt;param name=&quot;initParams&quot; value=&quot;baseuri=http://localhost:8000/Music&quot; /&gt;
  &lt;a href=&quot;http://go.microsoft.com/fwlink/?LinkID=149156&amp;v=3.0.40624.0&quot; style=&quot;text-decoration:none&quot;&gt;
       &lt;img src=&quot;http://go.microsoft.com/fwlink/?LinkId=108181&quot; alt=&quot;Get Microsoft Silverlight&quot; style=&quot;border-style:none&quot;/&gt;
  &lt;/a&gt;
&lt;/object&gt;</pre>
<p>
	So the html file tells Silverlight how to get to the WCF service, now the app.config<br />
	tells the server side how to get to the music files using these settings. The server<br />
	side returns a list of files with the configured web root so the Silverlight client<br />
	knows where to make a request to for the actual file.&#160; Note that this is also<br />
	where you change the base64 encode flag (false for virtual directory, true for WCF).
</p>
<pre class="brush: xml; gutter: false;">&lt;MusicService.Properties.Settings&gt;
    &lt;setting name=&quot;LocalRootPath&quot; serializeAs=&quot;String&quot;&gt;
        &lt;value&gt;C:\music&lt;/value&gt;
    &lt;/setting&gt;
    &lt;setting name=&quot;WebRootUrl&quot; serializeAs=&quot;String&quot;&gt;
        &lt;value&gt;http://localhost:8000/Music/Files/&lt;/value&gt;
    &lt;/setting&gt;
    &lt;setting name=&quot;Base64EncodedFilePath&quot; serializeAs=&quot;String&quot;&gt;
        &lt;value&gt;True&lt;/value&gt;
    &lt;/setting&gt;
&lt;/MusicService.Properties.Settings&gt;</pre>
<p>
	&#160;</p>
<p>
	Next, for the database to work properly, I added the provider configuration for<br />
	System.Data.SQLite. This is mostly just an FYI that it’s there and that I clear<br />
	all existing ones during runtime. (In case you already have it installed to your<br />
	system). This will allow SubSonic (the data framework I chose for this project)<br />
	to load the provider for SQLite when the server performs searches.</p>
<pre class="brush: xml; gutter: false;">&lt;system.data&gt;
    &lt;DbProviderFactories&gt;
        &lt;add name=&quot;SQLite Data Provider&quot;
              invariant=&quot;System.Data.SQLite&quot;
              description=&quot;.Net Framework Data Provider for SQLite&quot;
              type=&quot;System.Data.SQLite.SQLiteFactory, System.Data.SQLite, Version=1.0.65.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139&quot;/&gt;
    &lt;/DbProviderFactories&gt;
&lt;/system.data&gt;</pre>
<p>
	&#160;</p>
<h3>
	Run the Standalone</h3>
<p>
	To make the standalone version run, follow these steps:</p>
<ol>
<li><a href="/resources/p349/source.zip" target="_blank">Get the files here</a>&#160;<br />
		(Released Open Source via Creative Commons. See below for more details) </li>
<li>Open the app.config in the MusicHost project. Check the <em>LocalRootPath</em><br />
		setting and set it to the root of your music folder (for example: C:\Music or \\Server\Share.
	</li>
<li>Also set the WebRootUrl setting to the public location where your music files are<br />
		available. For example: http://myhost.com/Music&#160;&#160; or for the standalone:</p>
<p>http://localhost:8000/Music/Files/</li>
<li>Run the MusicHost application. </li>
<li>Browse to http://localhost:8000/Music/console.html
	</li>
<li>For the first run, wait about 20 seconds for the indexer to index your music repository.<br />
		If you click Random or search for files with no results, it may still be empty.</li>
<li>Select an item in the list to start playing it. </li>
</ol>
<h3>
	&#160;</h3>
<h3>
	Hosting with IIS</h3>
<p>
	I left the functionality in there to host music files from a web server directly.&#160;<br />
	To see it, edit your Web.Config in the Web project and set <em>WebRootUrl</em> to<br />
	the IIS virtual directory of your music files. (For example: <em>http://some.web.server/Music/</em>).&#160;<br />
	Set <em>Base64EncodedFilePath</em> to False so it doesn’t encode the file request.<br />
	Then run the Web project and browse to Default.html. During the first run, click<br />
	Reindex and wait for the confirmation dialog, which make take awhile depending on<br />
	the size and location of your local repository.
</p>
<p>
	&#160;</p>
<p>
	Enjoy!</p>
<p>
	&#160;</p>
<p>
	<a href="http://creativecommons.org/licenses/by-nc/3.0/" rel="license"><br />
		<img style="border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px;<br />
			border-left-width: 0px" alt="Creative Commons License" src="http://i.creativecommons.org/l/by-nc/3.0/88x31.png" /></a></p>
<p>
	<span property="dc:title" xmlns:dc="http://purl.org/dc/elements/1.1/">MusicCenter</span><br />
	by <a href="http://www.integratedwebsystems.com" rel="cc:attributionURL" property="cc:attributionName" xmlns:cc="http://creativecommons.org/ns#">Nathan Bridgewater</a> is licensed<br />
	under a <a href="http://creativecommons.org/licenses/by-nc/3.0/" rel="license">Creative<br />
		Commons Attribution-Noncommercial 3.0 Unported License</a>.</p>
<p>
<script type="text/javascript" src="http://www.google.com/jsapi"></script><br />
<script type="text/javascript">
	google.load("jquery", "1.4.1");
	</script><br />
<script type="text/javascript" src="/js/jquery.lightbox-0.5.pack.js"></script><br />
<script type="text/javascript" src="/tools/js/lightbox.js"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.integratedwebsystems.com/2010/04/part-2-silverlight-wcf-rest-and-streaming-my-personal-music-repository-from-a-standalone-exe/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>WCF Data Contracts and &quot;k__BackingField&quot; Property Naming</title>
		<link>http://www.integratedwebsystems.com/2009/05/wcf-data-contracts-and-k__backingfield-property-naming/</link>
		<comments>http://www.integratedwebsystems.com/2009/05/wcf-data-contracts-and-k__backingfield-property-naming/#comments</comments>
		<pubDate>Thu, 28 May 2009 15:43:25 +0000</pubDate>
		<dc:creator>Nathan</dc:creator>
				<category><![CDATA[Serialization]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[DataContract]]></category>
		<category><![CDATA[DataMember]]></category>

		<guid isPermaLink="false">http://www.integratedwebsystems.com/?p=257</guid>
		<description><![CDATA[So recently, I was playing around with WCF, and I created a...]]></description>
			<content:encoded><![CDATA[<p>So recently, I was playing around with WCF, and I created a few classes that I wanted to expose in operations. Usually when I play with plain old objects, I tend to type them up pretty lazily and use any code shortcut I can. In this case I defined my properties using the 3.0 auto-generated field method, which looks like an interface property. The C# compiler automatically generates the backing field on the fly for me at compile time.&#160; Here is a sample class I&#8217;m using in the silverlight music project.   </p>
<pre class="brush: csharp; gutter: false; toolbar: false;">[Serializable]
public class FileBrowser
{
    public string LocalMusicRoot { get; set; }
    public string WebMusicRoot { get; set; }
    public List&lt;string&gt; Files { get; set; }
}</pre>
<p><a href="http://www.integratedwebsystems.com/wp-content/uploads/image8.png"><img style="border-bottom: 0pt; border-left: 0pt; border-top: 0pt; border-right: 0pt" border="0" alt="image" align="right" src="http://www.integratedwebsystems.com/wp-content/uploads/image-thumb7.png" /></a>The catch comes in when you expose it to WCF. When serializing these objects, the serializer will look at all FIELDS of the class no matter their scope:&#160; public, private, etc.&#160; This is because it uses System.Runtime.Serialization, not System.Xml.Serialization. It does not serialize properties since properties really are just accessor functions.&#160; So what you get is a funky looking proxy class with some properties you didn&#8217;t want and some cryptic naming. I.E. k__BackingField appended to your field names. The serializer simply takes what it has which is the auto-generated field name the C# compiler made for us.</p>
<p>So how do I clean this up?!?!&#160;&#160; Easy!&#160; Use a data contract.&#160;&#160; By defining your classes using the <a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractattribute.aspx" target="_blank">DataContract attribute</a> from System.Runtime.Serialization, the serializer will interpret your <a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datamemberattribute.aspx" target="_blank">DataMembers</a> as fields on the class and use your naming. It will also ignore anything that&#8217;s not defined as a DataMember; so that hidden stuff will remain hidden and not be included in the proxy class. Take a look at this.&#160; We modified our original class with these attributes and the generated proxy class on the right now uses the names and fields we want!&#160; Easy peasy!</p>
<p><span id="more-257"></span></p>
<pre class="brush: csharp; gutter: false; toolbar: false;">[DataContract]
public class FileBrowser
{
    [DataMember]
    public string LocalMusicRoot { get; set; }

    [DataMember]
    public string WebMusicRoot { get; set; }

    [DataMember]
    public List&lt;string&gt; Files { get; set; }
}</pre>
<p><a href="http://www.integratedwebsystems.com/wp-content/uploads/image9.png"><img style="border-bottom: 0pt; border-left: 0pt; border-top: 0pt; border-right: 0pt" border="0" alt="image" align="right" src="http://www.integratedwebsystems.com/wp-content/uploads/image-thumb8.png" /></a>So now&#8230;&#160; When you&#8217;re defining your entity classes that you want to pass around WCF; just be sure to take advantage of DataContract attributes to clean up the client proxy classes.</p>
<p>By the way&#8230; If you&#8217;re playing around with <a href="http://blog.wekeroad.com/subsonic/subsonic-3-alpha-updated/" target="_blank">SubSonic 3 Alpha</a>, this is a really sweet tweak you can make to your <a href="/classes.txt" target="_blank">classes.tt T4 template</a>.&#160; This will make them all Data Contracts and put DataMember attributes on each of the data fields. This will hide the foreign key properties from the WCF generated proxies.&#160; Good stuff! <img src='http://www.integratedwebsystems.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.integratedwebsystems.com/2009/05/wcf-data-contracts-and-k__backingfield-property-naming/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Silverlight Deployment and WCF Endpoints</title>
		<link>http://www.integratedwebsystems.com/2009/04/silverlight-deployment-and-wcf-endpoints/</link>
		<comments>http://www.integratedwebsystems.com/2009/04/silverlight-deployment-and-wcf-endpoints/#comments</comments>
		<pubDate>Mon, 27 Apr 2009 18:31:04 +0000</pubDate>
		<dc:creator>Nathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[deployment]]></category>
		<category><![CDATA[endpoint]]></category>

		<guid isPermaLink="false">http://www.integratedwebsystems.com/index.php/2009/04/silverlight-deployment-and-wcf-endpoints/</guid>
		<description><![CDATA[I&#8217;m sure this has been written about a ton, but why not...]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m sure this has been written about a ton, but why not repost some useful information.</p>
<p>When using Silverlight with WCF, you quickly learn about the cross-domain restrictions. It becomes a huge pain when deploying from dev to production because you have to deploy and configure your Silverlight using the prod endpoint address, which for me at least didn&#8217;t always work. So what I found was that quite a few people are setting their WCF client end points on the fly using the current host during runtime. It&#8217;s relatively easy to do, and since they both are typically deployed at the same time, it works out pretty well.</p>
<p>This snippet strips away the ClientBin/xxx.xap from the application source and retains the application root URL.</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">string full = Application.Current.Host.Source.AbsoluteUri;
full = full.Substring(0, full.LastIndexOf('/')) + "/../";</pre>
<p>You can then put this functionality into a utility class for your application and make it very easy to consume when using WCF services. Using the music manager service from a previous post, we have:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">MusicManagerService.MusicManagerServiceClient client;
client = new MusicPlayer.MusicManagerService.MusicManagerServiceClient();

//use dynamic endpoint
client.Endpoint.Address = new System.ServiceModel.EndpointAddress(full + "MusicManager.svc"); 

client.GetFilesCompleted +=new EventHandler&lt;MusicPlayer.MusicManagerService.GetFilesCompletedEventArgs&gt;(client_GetFilesCompleted);
client.GetFilesAsync(uxSearchString.Text.Trim());</pre>
<p>For deployment, you just xcopy your published web app to the deployment directory and you&#8217;re done. No reconfiguring/recompiling necessary.</p>
<p>Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.integratedwebsystems.com/2009/04/silverlight-deployment-and-wcf-endpoints/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Silverlight, WCF, and Streaming My Personal Music Repository from IIS</title>
		<link>http://www.integratedwebsystems.com/2009/04/silverlight-wcf-and-streaming-my-personal-music-repository-on-the-go/</link>
		<comments>http://www.integratedwebsystems.com/2009/04/silverlight-wcf-and-streaming-my-personal-music-repository-on-the-go/#comments</comments>
		<pubDate>Thu, 09 Apr 2009 04:34:25 +0000</pubDate>
		<dc:creator>Nathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[music]]></category>
		<category><![CDATA[streaming]]></category>

		<guid isPermaLink="false">http://www.integratedwebsystems.com/?p=161</guid>
		<description><![CDATA[Updates I&#8217;ve recently posted a new article continuing this topic:  Silverlight, WCF...]]></description>
			<content:encoded><![CDATA[<h3>Updates</h3>
<p>I&#8217;ve recently posted a new article continuing this topic:  <a rel="bookmark" href="http://www.integratedwebsystems.com/2010/04/part-2-silverlight-wcf-rest-and-streaming-my-personal-music-repository-from-a-standalone-exe/">Silverlight, WCF REST and Streaming My Personal Music Repository from a Standalone EXE</a> , which as an updated client with regex search and random play functionality.</p>
<p><img style="display: inline; margin-left: 0px; margin-right: 0px; border-width: 0px;" title="image" src="http://www.integratedwebsystems.com/wp-content/upload/image-thumb.png" border="0" alt="image" width="406" height="484" align="right" /></p>
<p>A buddy of mine recently had mentioned he wanted a web based program he could use to listen to his music from home.  As a contractor, we move around a lot. At some locations, we can’t install any software; others, we have firewall issues. Our mobile devices couldn’t hold every song we stored at home, and copying our music around everywhere just didn’t seem like a great idea.  So we thought… wouldn’t it be cool if we could have just a simple website that could stream our music from anywhere? It’s an easy install…</p>
<p>So I started digesting the idea and thought yeah, we could do that.  At first we’ll have to just use something simple like streaming the files directly from IIS in a silverlight music player of sorts.  But eventually, we can really take advantage of some cool WCF hosting features in windows and not require IIS at all, which would be great for most of us since everyone doesn’t have a windows server sitting around at home. After a tiny bit of research, I realize we could also take advantage of the Media Services component built into windows server and IIS, which from the sound of it are pretty comprehensive. But with our end goal in mind, we’ll want to find a way to stream it right out of a simple windows app available to any edition of Windows.</p>
<p>Having said all that, I decided to start writing about this little toy project.  To begin, we have a simple Silverlight application with a music player, list manager, and an IIS server hosting a virtual directly to our mp3 repository.</p>
<h3><span id="more-161"></span></h3>
<h3>Getting Started</h3>
<p>Of course you’ll need all the links and references to some handy Silverlight information.</p>
<p><a title="http://silverlight.net/GetStarted/" href="http://silverlight.net/GetStarted/">http://silverlight.net/GetStarted/</a> is an excellent starting point.</p>
<p>You may need the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=c22d6a7b-546f-4407-8ef6-d60c8ee221ed&amp;displaylang=en" target="_blank">Silverlight Tools for Visual Studio 2008 SP1</a>.</p>
<p>I’m using Expression Blend 2, and for my project templates to be correct, I needed <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=EB9B5C48-BA2B-4C39-A1C3-135C60BBBE66&amp;displaylang=en" target="_blank">Expression Blend 2 SP1</a>.</p>
<p><a title="Sample files for streaming mp3 to silverlight from IIS" href="http://www.integratedwebsystems.com/wp-content/upload/musiccenter.zip">Download the Sample</a></p>
<p>So here we have our simple player. It has a stop and play button and a list box.  It’s very, very, very simple.  The idea is to load the music list on startup, then as we choose an item in the list, it plays.  It also will auto-play the next song in the list when the current song ends, and it will recycle the whole list when the last song in the list ends. There are a TON of cool things we can do with this, but for now, we’re starting simple.</p>
<p>I started out by creating a new Silverlight Application in Expression Blend.  If you don’t have Expression Blend, you can create a new Silverlight Application using Visual Studio with Silverlight Tools. This creates a class library containing the Silverlight controls along with a website project containing sample run pages to load and test your Silverlight application. In this case, our project name is MusicPlayer and the auto-generated web project name is MusicPlayer.Web.</p>
<h3>The Player</h3>
<p>Add a new Silveright User Control to the MusicPlayer project called Player. Here’s the XAML for our new control.</p>
<pre class="brush: xml;">&lt;UserControl x:Class="MusicPlayer.Player"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="513" Height="613" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Name="ContentPanel"&gt;
    &lt;Grid x:Name="LayoutRoot" Background="#343434"&gt;
        &lt;MediaElement x:Name="MediaElement1" Margin="0,0,103,0" Height="26" VerticalAlignment="Top" Width="109" HorizontalAlignment="Right" AutoPlay="True" /&gt;
        &lt;Button HorizontalAlignment="Left" Width="95" Content="Stop" x:Name="uxStop" VerticalAlignment="Top" Height="26" /&gt;
        &lt;Button Content="Play" x:Name="uxPlay"  Height="26" VerticalAlignment="Top" Width="99" HorizontalAlignment="Right" MinHeight="0" UseLayoutRounding="True"/&gt;
        &lt;ListBox Margin="0,30,0,0" x:Name="uxPlayList" Background="#FF000000" BorderBrush="#FF345CA4" Foreground="#FF8FC0FF" Opacity="0.41"/&gt;
        &lt;TextBlock Margin="99,0,103,0" VerticalAlignment="Top" Text="" TextWrapping="Wrap" Foreground="#FFAEAEAE" x:Name="uxStatus" Height="30"/&gt;
    &lt;/Grid&gt;
&lt;/UserControl&gt;</pre>
<p>This should give you something similar to the control shown above. Start wiring up events for the simple things like the buttons and such. For their click event, you can control the MediaElement by asking it to Play(), Stop(), Pause(), etc.    I included a text block that just shows the current state of the media element.  Use the CurrentStateChanged event on the MediaElement to update its value.</p>
<h3><img class="alignright size-full wp-image-139" title="image.png" src="http://www.integratedwebsystems.com/wp-content/upload/image3.png" alt="image.png" width="259" height="181" align="right" /></h3>
<h3>Getting the Playlist</h3>
<p>Before we get into loading the list control, we’ll need to define its WCF services. I designed a very simple structure to handle the information we need for our Music in this exercise. For now, it contains only a list of filenames and their relative path to the root of the mp3 repository. It also contains the public web path configured on the server.</p>
<p>MusicManagerService will have one function for now: GetFiles(), which will return a FileBrowser filled with the information from the MP3 repository. Simple enough…</p>
<p>Within the FileBrowser we have our implementation of the LoadFiles() function where it actually seeks the local repository and collects its information.</p>
<p><strong> </strong></p>
<p><strong>//FileBrowser.cs</strong></p>
<pre class="brush: csharp;">public void LoadFiles()
{
    if (!string.IsNullOrEmpty(LocalMusicRoot) &amp;&amp; Directory.Exists(LocalMusicRoot))
    {
        if (this.Files == null)
            this.Files = new List&lt;string&gt;();

        this.Files.Clear();

        this.Files.AddRange(Directory.GetFiles(this.LocalMusicRoot, "*.mp3", SearchOption.AllDirectories));
        this.Files.AddRange(Directory.GetFiles(this.LocalMusicRoot, "*.wma", SearchOption.AllDirectories));

        //trim off the full path; leave only the relative one.
        List&lt;string&gt; newFiles = new List&lt;string&gt;();
        foreach (string file in this.Files)
        {
            newFiles.Add(file.Replace(LocalMusicRoot, string.Empty).Replace('\\','/'));
        }
        this.Files = newFiles;
    }
    else
        throw new ApplicationException("Cannot continue. No directory specified or the directory does not exist.");
}</pre>
<h3>WCF Setup</h3>
<p>The easiest way to do this is to add a new Silverlight-enabled WCF Service to your web project.  Change its service contract to resemble the following snippet.  This will also automatically configure your web.config as well. The funny thing about the Silverlight enabled web service is that it mixes the contract interface with the class implementation. You can optionally separate this out into a WCF library in a more traditional approach using the interface and class implementation separated. We’ve done this in our downloadable sample code.</p>
<pre class="brush: csharp;">[ServiceContract()]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MusicManager
{
    [OperationContract]
    public FileBrowser GetFiles()
    {
        FileBrowser fb = new FileBrowser();
        fb.LocalMusicRoot = Properties.Settings.Default.LocalRootPath;
        fb.WebMusicRoot = Properties.Settings.Default.WebRootUrl;
        fb.LoadFiles();

        fb.LocalMusicRoot = null; //clearing unnecessary local path from return value
        return fb;
    }
}</pre>
<p>You should be able to browse MusicManager.svc and see the service page. You can also reference the service in the MusicPlayer silverlight project. In the ContentPanel Loaded event, we will call out to the service.</p>
<pre class="brush: csharp;">private void ContentPanel_Loaded(object sender, RoutedEventArgs e)
{
    //load up the music files.
    MusicManagerService.MusicManagerServiceClient client = new MusicManagerService.MusicManagerServiceClient();
    client.GetFilesCompleted += new EventHandler&lt;MusicPlayer.MusicManagerService.GetFilesCompletedEventArgs&gt;(client_GetFilesCompleted);
    client.GetFilesAsync();
}</pre>
<p>Our async callback function for the service call will populate the list control.</p>
<pre class="brush: csharp;">void client_GetFilesCompleted(object sender, MusicPlayer.MusicManagerService.GetFilesCompletedEventArgs e)
{
    this.uxPlayList.Items.Clear();
    _Browser = e.Result;

    foreach (string file in _Browser.Filesk__BackingField)
    {
        this.uxPlayList.Items.Add(file);
    }
}</pre>
<p>To finish up, add implementation for the selected index changed on the list control to change the MediaElement’s Source to the selected file with its web path. For convenience, we AutoPlay to true on our MediaElement to autoplay its media. Anytime the Source property changes values, it will begin streaming and playing the audio.</p>
<pre class="brush: csharp;">private void uxPlayList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    //start streaming the file.
    MediaElement1.Source = new Uri(_Browser.WebMusicRootk__BackingField + uxPlayList.SelectedItem.ToString());
}</pre>
<p>When the media ends, we need to increment the playlist selection.</p>
<pre class="brush: csharp;">private void MediaElement1_MediaEnded(object sender, RoutedEventArgs e)
{
    //move to the next item
    int ix = uxPlayList.SelectedIndex;
    ix++;

    if (ix &gt;= uxPlayList.Items.Count)
        ix = 0;

    uxPlayList.SelectedIndex = ix;
}</pre>
<h3>Wrap Up</h3>
<p>So the end result will be our player initializing by pre-loading a playlist. Once the first song is played, the rest will auto-play as they increment through the list. With my MP3’s on a cable connection I’ve noticed it’s uploading around around 60KB/s.  So as long as the location you’re at can tolerate a little bit of bandwidth, it’s a pretty good start to a little remote music player. You might even be able to throttle IIS down so it doesn’t saturate the wire.</p>
<h3>Next Time</h3>
<p>The next round will be using a restful http request via WCF 3.5 to stream audio files rather than straight up IIS.  You can read more about that here:</p>
<p><a rel="bookmark" href="http://www.integratedwebsystems.com/2010/04/part-2-silverlight-wcf-rest-and-streaming-my-personal-music-repository-from-a-standalone-exe/">Part 2 – Silverlight, WCF REST and Streaming My Personal Music Repository from a Standalone EXE</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.integratedwebsystems.com/2009/04/silverlight-wcf-and-streaming-my-personal-music-repository-on-the-go/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

