<?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/"
	>

<channel>
	<title>TadSharp .Net</title>
	<atom:link href="http://www.tadsharp.net/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://www.tadsharp.net</link>
	<description>WCF, .NET Architecture and More!</description>
	<pubDate>Fri, 20 Feb 2009 03:13:46 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.7.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Flickr WCF Part II - Hosting WCF Components In-Process</title>
		<link>http://www.tadsharp.net/?p=75</link>
		<comments>http://www.tadsharp.net/?p=75#comments</comments>
		<pubDate>Mon, 16 Feb 2009 22:38:08 +0000</pubDate>
		<dc:creator>Tad</dc:creator>
		
		<category><![CDATA[.net]]></category>

		<category><![CDATA[servicemodelex]]></category>

		<category><![CDATA[wcf]]></category>

		<category><![CDATA[csharp]]></category>

		<guid isPermaLink="false">http://www.tadsharp.net/?p=75</guid>
		<description><![CDATA[This is Part Two in an on-going series of articles about WCF components, all centered around a simple component I created to talk to the Flickr api.  You can find Part I here.
Now that we&#8217;ve hosted the Flickr WCF component in IIS, let&#8217;s take the same service definition and implementation and do something more [...]]]></description>
			<content:encoded><![CDATA[<p>This is Part Two in an on-going series of articles about WCF components, all centered around a simple component I created to talk to the Flickr api.  You can find Part I <a href="http://www.tadsharp.net/?p=41">here</a>.</p>
<p>Now that we&#8217;ve hosted the Flickr WCF component in IIS, let&#8217;s take the same service definition and implementation and do something more interesting with them than just spitting out a list of URLs.  It would be cool if we could see each of the pictures and cycle through them.  And, so that I can point out a potential WCF gotcha, let&#8217;s do this in a WinForms application.</p>
<p>Let&#8217;s also host the component in process.  In process components should always use named pipes.  I&#8217;ve found that the easiest possible way to host a component in process is by using Juval Lowy&#8217;s ServiceModelEx library.  You can download the library at this link.  We&#8217;ll use his InProcFactory class which he describes in some detail on pages 60-63 of his WCF Bible, &#8220;<a href="http://www.amazon.com/gp/product/0596521308?ie=UTF8&#038;tag=donaghehomepa-20&#038;linkCode=as2&#038;camp=1789&#038;creative=9325&#038;creativeASIN=0596521308">Programming WCF Services.&#8221;</a><img src="http://www.assoc-amazon.com/e/ir?t=donaghehomepa-20&#038;l=as2&#038;o=1&#038;a=0596521308" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /><br />
  With InProcFactory all you need to do is to add references to the class libraries which contain your component&#8217;s contracts and implementation.<br />
<span id="more-75"></span><br />
Then you can make calls like this:</p>
<pre name="code" class="csharp">

IMyContract proxy = InProcFactory.CreateInstance&lt;MyService, IMyContract&gt;();
proxy.MyMethod();
InProcFactory.CloseProxy(proxy);
</pre>
<p>Notice that when we use InProcFactory we don&#8217;t have to worry about setting up hosts, config files, or really worry about anything other than our interfaces and implementation classes.  This is almost as easy creating regular c# objects with the new keyword!  Using named pipes is also the fastest and most secure way to deal with WCF components.  </p>
<p>So, for this example, let&#8217;s create a new Windows Forms Application and name it WCFInProcFlickrApp.  Add references to your BasicFlickrWCFContracts and FlickrInfoService dlls as well as Juval Lowy&#8217;s ServiceModelEx library.  </p>
<p>Add a new Form and call it Viewer.  Add a PictureBox (picBox) and two buttons (btnNext and btnPrev).  Make your form look like this:</p>
<p><img alt="" src="http://farm4.static.flickr.com/3238/3285046911_9aec847c28.jpg" title="Viewer Form" class="alignnone" width="500" height="352" /></p>
<p>Now let&#8217;s make sure that we can connect to our WCF component without any problems.  Double click the View form and then add code to the Viewer_Load method that looks like this:</p>
<pre name="code" class="csharp">

        private void Viewer_Load(object sender, EventArgs e)
        {

            IFlickrInfo proxy = ServiceModelEx.InProcFactory.CreateInstance&lt;FlickrInfoService, IFlickrInfo&gt;();

            photos = proxy.GetRecentPhotos();

            ServiceModelEx.InProcFactory.CloseProxy(proxy);

            picBox.ImageLocation = photos[0].Url;
        }
</pre>
<p>Now try running the app.  When you run this you should expect the picture box to show the first image returned by component.  Instead the application hangs for a long time and eventually you&#8217;ll get an error message that looks like this:</p>
<p><img alt="" src="http://farm4.static.flickr.com/3365/3285092271_89a8b0711b_o.png" title="Error Message" class="alignnone" width="452" height="322" /></p>
<p>The problem here is that we&#8217;ve hosting the component in-process after the UI thread has started.  This causes the component to run on the UI thread associated with the form.  The UI thread&#8217;s message loop acts as a throttle for message processing.  When the form calls the service in-process like this that call blocks the UI thread while WCF posts a message to the UI thread to invoke the service.  We&#8217;re stuck in a loop now because of the blocking UI thread and hence we end up with this deadlock shown in the error above.</p>
<p>The problem is that WCF components have the UseSynchronizationContext attribute set to true by default.  When this behavior is set to true, the component gains thread affinity with the code that called it.  In our WinForms app this makes a big difference because of the message loop.  One really simple way to fix this would be to decorate our implementation class with the following attribute which sets that context to false:</p>
<pre name="code" class="csharp">

[ServiceBehavior(UseSynchronizationContext=false)]
</pre>
<p>This removes the thread affinity and lets our component run on its own thread, eliminating the blocking and deadlock issue.  In this example I don&#8217;t want to go this route, because I&#8217;ve already created my component and it works just fine.  I would only be adding this attribute to help it work in this one case.  This is starting to smell like coupling, which I try to avoid if at all possible.  Either way, now that my contracts and implementation are in dlls, I don&#8217;t want to have to go and recompile them just to get them to work for WinForms.  There&#8217;s got to be another way.</p>
<p>Fortunately there is.  All we need to do is to start hosting the component before the UI thread is set.  To do this, we need to create the host in the Main method that starts the WinForms app.  This method can be found in the Program.cs file in the solution.  Now we run into another problem.  The way that Lowy wrote InProcFactory, the service host is created, if needed, when you make the call to CreateInstance.  If I put this call in the Main method then I&#8217;ll need something like a global variable to hook into in my Viewer form that would be of no use to other forms in my project.  That&#8217;s a pretty stinky code smell too.</p>
<p>To solve this issue, I created a new static method on InProcFactory - CreateHost.  The method is as follows:</p>
<pre name="code" class="csharp">

      public static void CreateHost&lt;S, I&gt;()
          where I : class
          where S : class, I
      {
          if (m_Hosts.ContainsKey(typeof(S)))
          {
              return;
          }

          HostRecord hostRecord;
          ServiceHost host;

          if (m_Singletons.ContainsKey(typeof(S)))
          {
              S singleton = m_Singletons[typeof(S)] as S;
              Debug.Assert(singleton != null);
              host = new ServiceHost(singleton, BaseAddress);
          }
          else
          {
              host = new ServiceHost(typeof(S), BaseAddress);
          }

          string address = BaseAddress.ToString() + Guid.NewGuid().ToString();
          hostRecord = new HostRecord(host, address);

          m_Hosts.Add(typeof(S), hostRecord);

          host.AddServiceEndpoint(typeof(I), Binding, address);          

          if (m_Throttles.ContainsKey(typeof(S)))
          {
              host.SetThrottle(m_Throttles[typeof(S)]);
          }

          host.Open();
      }
</pre>
<p>This is almost a verbatim copy and paste of the GetHostRecord method that&#8217;s already in ServiceModelEx.  Yes, I can and should refactor out the similarities, but for the purposes of this article I think it&#8217;s helpful to see what&#8217;s going on.  CreateHost creates a new Named Pipe in-proc host just like CreateInstance does.  Since it&#8217;s a static method on a static class, the host will stick around after the Viewer form is created.  When CreateInstance is called, InProcFactory will see that our host has already been created and will use that one.  In this way we don&#8217;t gain thread affinity with the UI thread.  </p>
<p>So now, change the code in the Main method inside Program.cs to look like this:</p>
<pre name="code" class="csharp">

        [STAThread]
        static void Main()
        {
            InProcFactory.CreateHost&lt;FlickrInfoService, IFlickrInfo&gt;();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Viewer());
        }
</pre>
<p>You can now run the application again and you should see the first picture returned back in the picture box.  To round out our little app, hook in the buttons click events (by double clicking each of them) and then add code to them like this (as well as adding the ShowCurrentImage method):</p>
<pre name="code" class="csharp">

        private void btnNext_Click(object sender, EventArgs e)
        {
            currentIndex++;
            if (currentIndex &gt; 99)
            {
                currentIndex = 0;
            }
            ShowCurrentImage();
        }

        private void ShowCurrentImage()
        {
            picBox.ImageLocation = photos[currentIndex].Url;
        }

        private void btnPrev_Click(object sender, EventArgs e)
        {
            currentIndex--;
            if (currentIndex &lt; 0)
            {
                currentIndex = 99;
            }
            ShowCurrentImage();
        }
</pre>
<p>Now you can use the Next and Prev buttons to cycle through all of the interesting photos returned back from Flickr!  The part about all of this that I like the most is that we didn&#8217;t have to change our component at all in order to do any of this.  Hurray for component reuse!</p>
<p>All of this same information can be used in WPF applications as well.  I&#8217;m not really familiar with WPF applications, but I understand you can configure your WPF application to use a custom Main method by right-clicking the App.xaml file, selecting Properties, and setting the Build Action to &#8220;Page.&#8221;  Now create a static class Program.cs in the root and insert a Main() method like this:</p>
<pre name="code" class="csharp">

public static class Program
{
    [STAThread]
    static void Main()
    {
        WPFClient.App app = new WPFClient.App();
        app.InitializeComponent();
        app.Run();
    }
}
</pre>
<p>I haven&#8217;t actually tried this, but if you have any problems with this method in WPF, please leave a comment below and I&#8217;ll do some research for you.</p>
<p><a href='http://www.tadsharp.net/wp-content/uploads/2009/02/wcfinprocflickrapp.zip'>Here&#8217;s a copy of my WCFInProcFlickrApp source</a>.</p>
<p><a href='http://www.tadsharp.net/wp-content/uploads/2009/02/servicemodelex.zip'>Here&#8217;s a copy of my enhanced version of ServiceModelEx</a>.</p>
<p><strong>REFERENCES:</strong><br />
For a much better explanation of InProcFactory, please see &#8220;<a href="http://www.amazon.com/gp/product/0596521308?ie=UTF8&#038;tag=donaghehomepa-20&#038;linkCode=as2&#038;camp=1789&#038;creative=9325&#038;creativeASIN=0596521308">Programming WCF Services</a><img src="http://www.assoc-amazon.com/e/ir?t=donaghehomepa-20&#038;l=as2&#038;o=1&#038;a=0596521308" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />&#8221; pages 60-63.<br />
&#8220;<a href="http://www.amazon.com/gp/product/0596521308?ie=UTF8&#038;tag=donaghehomepa-20&#038;linkCode=as2&#038;camp=1789&#038;creative=9325&#038;creativeASIN=0596521308">Programming WCF Services</a><img src="http://www.assoc-amazon.com/e/ir?t=donaghehomepa-20&#038;l=as2&#038;o=1&#038;a=0596521308" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />&#8221; - Chapter 8 pages 388 through 413 were very helpful.<br />
<a href="http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/d8aba8ce-c31a-4a64-bcdb-94f6ceafbbc8">Peter De Jonghe&#8217;s post on the MSDN WCF forums</a>.<br />
Jeremy Wiebe&#8217;s &#8220;<a href="http://miscjibberish.blogspot.com/2008/11/wcf-service-blocking-when-self-hosting.html">WCF service blocking when self-hosting (or How the ServiceBehavior&#8217;s Use SynchronizationContext parameter saved me)</a>&#8221;<br />
Code Magazine&#8217;s article about <a href="http://www.code-magazine.com/article.aspx?quickid=0701041&#038;page=3">WCF Hosting, Page 3</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.tadsharp.net/?feed=rss2&amp;p=75</wfw:commentRss>
		</item>
		<item>
		<title>StackOverflow update</title>
		<link>http://www.tadsharp.net/?p=72</link>
		<comments>http://www.tadsharp.net/?p=72#comments</comments>
		<pubDate>Thu, 12 Feb 2009 05:40:06 +0000</pubDate>
		<dc:creator>Tad</dc:creator>
		
		<category><![CDATA[.net]]></category>

		<category><![CDATA[stackoverflow]]></category>

		<category><![CDATA[wcf]]></category>

		<guid isPermaLink="false">http://www.tadsharp.net/?p=72</guid>
		<description><![CDATA[
I have recently had two of my WCF related answers to questions on StackOverflow rated as top answers!  
Are Enterprise Level DataContracts a Good Practice?
Logic first, WCF security later?
I enjoy going through the StackOverflow questions that are tagged as WCF related on a near daily basis.  I have learned an awful lot just [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.stackoverflow.com"><img alt="" src="http://i.stackoverflow.com/Content/Img/stackoverflow-logo-250.png" title="Stack Overflow" class="alignnone" width="250" height="70" /></a></p>
<p>I have recently had two of my WCF related answers to questions on StackOverflow rated as top answers!  </p>
<p><a href="http://stackoverflow.com/questions/441216/are-enterprise-level-datacontracts-a-good-practice">Are Enterprise Level DataContracts a Good Practice?</a></p>
<p><a href="http://stackoverflow.com/questions/486000/logic-first-wcf-security-later">Logic first, WCF security later?</a></p>
<p>I enjoy going through the StackOverflow questions that are <a href="http://stackoverflow.com/questions/tagged/wcf">tagged as WCF</a> related on a near daily basis.  I have learned an awful lot just reading other people&#8217;s answers and sometimes the questions inspire me to go learn something I hadn&#8217;t thought about.</p>
<p>Also, tonight I asked:</p>
<p><a href="http://stackoverflow.com/questions/540173/what-are-your-favorite-resources-concerning-restful-wcf">What are your favorite resources concerning RESTful WCF?</a></p>
<p>If you have a good answer, I&#8217;d love to hear it!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.tadsharp.net/?feed=rss2&amp;p=72</wfw:commentRss>
		</item>
		<item>
		<title>Flickr WCF Part I - Basic Manual WCF Component</title>
		<link>http://www.tadsharp.net/?p=41</link>
		<comments>http://www.tadsharp.net/?p=41#comments</comments>
		<pubDate>Tue, 10 Feb 2009 16:46:40 +0000</pubDate>
		<dc:creator>Tad</dc:creator>
		
		<category><![CDATA[.net]]></category>

		<category><![CDATA[wcf]]></category>

		<category><![CDATA[wcf flickr .net csharp]]></category>

		<guid isPermaLink="false">http://www.tadsharp.net/?p=41</guid>
		<description><![CDATA[This is the first part in a series of blog posts where I see how many different aspects of WCF I can exercise with the same basic component definition. In this article we&#8217;re going to define our contracts, create a service, create a IIS host, hand-code a proxy and have a Console app spit out [...]]]></description>
			<content:encoded><![CDATA[<p>This is the first part in a series of blog posts where I see how many different aspects of WCF I can exercise with the same basic component definition. In this article we&#8217;re going to define our contracts, create a service, create a IIS host, hand-code a proxy and have a Console app spit out URLs to the 100 most recent photos uploaded to Flickr.</p>
<p>This and subsequent articles assume some basic working knowledge of WCF. If you&#8217;ve worked your way through a couple of tutorials, you&#8217;ll be fine.</p>
<p>The basic logic of the calling out to Flickr and the extension method I use are described in the previous blog post which is a prelude to this series. Please take a look at that article if you have trouble following along.</p>
<p>For simple cases like the one we&#8217;re working on here, I find that hand coding all of the WCF logic is the easiest and most straightforward way to make my code work. Using the svcutil.exe or the Add Service Reference feature in VS 2008 works, but both methods add unnecessary cruft that add to the complexity and understanding of the code. So, here we go!</p>
<p><span id="more-41"></span>Our objective is to call the Flickr API getting information about the 100 photos flickr deems interesting for the day, extract out of the XML the necessary information to create URLs to the medium sized jpg and then spit the URLs out to the console window. The first thing we&#8217;ll do is create a Class Library project called BasicFlickrWCFContracts in a solution named BasicFlickrWCFApp. Add references for System.ServiceModel and System.Runtime.Serializations.</p>
<p>In this solution, add a new class file named FlickrPhoto.cs. The code for FlickrPhoto will look like this:</p>
<pre name="code" class="csharp">
   &lt;br /&gt;using System;    &lt;br /&gt;using System.Runtime.Serialization;&lt;/p&gt;  &lt;p&gt;namespace Donaghe.FlickrInfoComponent   &lt;br /&gt;{    &lt;br /&gt;[DataContract]    &lt;br /&gt;public class FlickrPhoto    &lt;br /&gt;{    &lt;br /&gt;string farm = string.Empty;    &lt;br /&gt;string server = string.Empty;    &lt;br /&gt;string id = string.Empty;    &lt;br /&gt;string secret = string.Empty;    &lt;br /&gt;string owner = string.Empty;    &lt;br /&gt;string title = string.Empty;    &lt;br /&gt;string url = string.Empty;    &lt;br /&gt;string flickrUrl = string.Empty;&lt;/p&gt;  &lt;p&gt;[DataMember]   &lt;br /&gt;public string Farm    &lt;br /&gt;{    &lt;br /&gt;get { return farm; }    &lt;br /&gt;set { farm = value; }    &lt;br /&gt;}&lt;/p&gt;  &lt;p&gt;[DataMember]   &lt;br /&gt;public string Server    &lt;br /&gt;{    &lt;br /&gt;get { return server; }    &lt;br /&gt;set { server = value; }    &lt;br /&gt;}&lt;/p&gt;  &lt;p&gt;[DataMember]   &lt;br /&gt;public string Id    &lt;br /&gt;{    &lt;br /&gt;get { return id; }    &lt;br /&gt;set { id = value; }    &lt;br /&gt;}&lt;/p&gt;  &lt;p&gt;[DataMember]   &lt;br /&gt;public string Secret    &lt;br /&gt;{    &lt;br /&gt;get { return secret; }    &lt;br /&gt;set { secret = value; }    &lt;br /&gt;}&lt;/p&gt;  &lt;p&gt;[DataMember]   &lt;br /&gt;public string Owner    &lt;br /&gt;{    &lt;br /&gt;get { return owner; }    &lt;br /&gt;set { owner = value; }    &lt;br /&gt;}&lt;/p&gt;  &lt;p&gt;[DataMember]   &lt;br /&gt;public string Title    &lt;br /&gt;{    &lt;br /&gt;get { return title; }    &lt;br /&gt;set { title = value; }    &lt;br /&gt;}&lt;/p&gt;  &lt;p&gt;[DataMember]   &lt;br /&gt;public string Url    &lt;br /&gt;{    &lt;br /&gt;get { return url; }    &lt;br /&gt;set { url = value; }    &lt;br /&gt;}&lt;/p&gt;  &lt;p&gt;[DataMember]   &lt;br /&gt;public string FlickrUrl    &lt;br /&gt;{    &lt;br /&gt;get { return flickrUrl; }    &lt;br /&gt;set { flickrUrl = value; }    &lt;br /&gt;}    &lt;br /&gt;}    &lt;br /&gt;}&lt;/p&gt;  &lt;p&gt;
</pre>
<p>This class definition is basically just a plain vanilla WCF data contract. We will use this class to help us build our photo URLs.</p>
<p>Now add an interface file to your project. Name is IFlickrInfo.cs. This will define a single operation to return recent Flickr photos. The code is simple and looks like this:</p>
<pre name="code" class="csharp">
   &lt;br /&gt;using System;    &lt;br /&gt;using System.Collections.Generic;    &lt;br /&gt;using System.Linq;    &lt;br /&gt;using System.Text;    &lt;br /&gt;using System.ServiceModel;&lt;/p&gt;  &lt;p&gt;namespace Donaghe.FlickrInfoComponent   &lt;br /&gt;{    &lt;br /&gt;[ServiceContract]    &lt;br /&gt;public interface IFlickrInfo    &lt;br /&gt;{    &lt;br /&gt;[OperationContract]    &lt;br /&gt;List&lt;flickrphoto&gt; GetRecentPhotos();    &lt;br /&gt;}    &lt;br /&gt;}&lt;/p&gt;  &lt;p&gt;
</pre>
<p>The next step is to create the service which will give life to our new ServiceContract. Create a new Class Library project and name it FlickrInfoService. Add a reference to System.ServiceModel as well as a Project Reference to the BasicFlickrWCFContracts project.</p>
<p>I use an extension method that I created for System.Net.WebClient as described in the previous blog post. You can either create this yourself or download a copy of my extensions dll here. If you use my dll, add a reference to it and you&#8217;ll need to add a using statement in your code like this:</p>
<pre name="code" class="csharp">
   &lt;br /&gt;using TadsExtensions;    &lt;br /&gt;
</pre>
<p>Add a new class file to this project and name it FlickrInfoService.cs. Copy and paste this code into it:</p>
<pre name="code" class="csharp">
   &lt;br /&gt;using System;    &lt;br /&gt;using System.Collections.Generic;    &lt;br /&gt;using System.Linq;    &lt;br /&gt;using System.Net;    &lt;br /&gt;using System.ServiceModel;    &lt;br /&gt;using System.Text;    &lt;br /&gt;using System.Xml.Linq;    &lt;br /&gt;using TadsExtensions;&lt;/p&gt;  &lt;p&gt;namespace Donaghe.FlickrInfoComponent   &lt;br /&gt;{    &lt;br /&gt;public class FlickrInfoService : IFlickrInfo    &lt;br /&gt;{    &lt;br /&gt;#region IFlickrInfo Members&lt;/p&gt;  &lt;p&gt;public List&lt;flickrphoto&gt; GetRecentPhotos()   &lt;br /&gt;{    &lt;br /&gt;List&lt;flickrphoto&gt; photos = new List&lt;flickrphoto&gt;();&lt;/p&gt;  &lt;p&gt;XElement x = (new WebClient()).DownloadXElement(&quot;http://api.flickr.com/services/rest/?method=flickr.interestingness.getList&amp;amp;amp;amp;amp;amp;api_key=YOURFLICKRAPIKEYHERE&quot;);&lt;/p&gt;  &lt;p&gt;var query = from b in x.Elements(&quot;photos&quot;).Elements(&quot;photo&quot;)   &lt;br /&gt;select new FlickrPhoto    &lt;br /&gt;{    &lt;br /&gt;Farm = b.Attribute(&quot;farm&quot;).Value,    &lt;br /&gt;Id = b.Attribute(&quot;id&quot;).Value,    &lt;br /&gt;Secret = b.Attribute(&quot;secret&quot;).Value,    &lt;br /&gt;Server = b.Attribute(&quot;server&quot;).Value,    &lt;br /&gt;Owner = b.Attribute(&quot;owner&quot;).Value,    &lt;br /&gt;Title = b.Attribute(&quot;title&quot;).Value    &lt;br /&gt;};&lt;/p&gt;  &lt;p&gt;foreach (FlickrPhoto photo in query)   &lt;br /&gt;{    &lt;br /&gt;StringBuilder urlBuilder = new StringBuilder();&lt;/p&gt;  &lt;p&gt;urlBuilder.Append(&quot;http://farm&quot;);   &lt;br /&gt;urlBuilder.Append(photo.Farm);    &lt;br /&gt;urlBuilder.Append(&quot;.static.flickr.com/&quot;);    &lt;br /&gt;urlBuilder.Append(photo.Server);    &lt;br /&gt;urlBuilder.Append(&quot;/&quot;);    &lt;br /&gt;urlBuilder.Append(photo.Id);    &lt;br /&gt;urlBuilder.Append(&quot;_&quot;);    &lt;br /&gt;urlBuilder.Append(photo.Secret);    &lt;br /&gt;urlBuilder.Append(&quot;_m.jpg&quot;);&lt;/p&gt;  &lt;p&gt;photo.Url = urlBuilder.ToString();&lt;/p&gt;  &lt;p&gt;StringBuilder urlBuilder2 = new StringBuilder();&lt;/p&gt;  &lt;p&gt;urlBuilder2.Append(&quot;http://www.flickr.com/photos/&quot;);   &lt;br /&gt;urlBuilder2.Append(photo.Owner);    &lt;br /&gt;urlBuilder2.Append(&quot;/&quot;);    &lt;br /&gt;urlBuilder2.Append(photo.Id);&lt;/p&gt;  &lt;p&gt;photo.FlickrUrl = urlBuilder2.ToString();&lt;/p&gt;  &lt;p&gt;photos.Add(photo);   &lt;br /&gt;}&lt;/p&gt;  &lt;p&gt;return photos;   &lt;br /&gt;}&lt;/p&gt;  &lt;p&gt;#endregion   &lt;br /&gt;}    &lt;br /&gt;}&lt;/p&gt;  &lt;p&gt;
</pre>
<p>The bulk of this code is explained in the my previous blog entry. Please see it if you need a better understanding of what&#8217;s going on.</p>
<p>Of interest is the code that sets the photo.Url and photo.FlickrUrl. The Url is the link to the actual photograph and the FlickrUrl is a link to the page on Flickr where you can view the photo in the owner&#8217;s photostream. This code follows the simple recipe given by Flickr on this <a href="http://www.flickr.com/services/api/misc.urls.html">page</a>. For this solution we&#8217;re only interested in photo.Url. In my <a href="http://www.xelinprojects.com/FlickrToyInteresting/Default.aspx">Flickr Toy</a> app, I use photo.FlickrUrl to allow users to click a photo and go to its Flickr page.</p>
<p>Now it&#8217;s time to create a host for our component. In this case we&#8217;ll create an IIS host. I find IIS hosts very simple to implement and use. So, go to File-&gt;New-&gt;Project-&gt;ASP.NET Web Application. Name it FlickrInfoIISHost.</p>
<p>Delete the Default.aspx page - we won&#8217;t need it. Add Project references to BasicFlickrWCFContracts and FlickrInfoService. Now add a plain text file to the project. Name it FlickrInfoIISHost.svc. Edit the file to look like this:</p>
<p>[sourcecode language="asp"]<br />
&lt;%@ ServiceHost Service=&#8221;Donaghe.FlickrInfoComponent.FlickrInfoService&#8221; %&gt;<br />
[/sourcecode]</p>
<p>Open the Web.config file and paste the following code down at the bottom just before the configuration end node:</p>
<pre name="code" class="xml">
</pre>
<p>Find the compilation tag and set its debug attribute to true like this:</p>
<pre name="code" class="xml">
</pre>
<p>I like to specify the port for my IIS hosting projects manually. To do this, right click on the FlickrInfoIISHost project and choose Properties. Click the Web tab and make sure the &#8220;Specific Port&#8221; radio button is selected. For this example I set the port to 51030. You&#8217;ll see why when we create our client.</p>
<p>Now let&#8217;s try our host and see if it&#8217;s working properly. In Solution Explorer, right click the FlickrInfoIISHost project and chose &#8220;Set as Startup Project&#8221; from the context menu. Now run the solution by pressing ctrl-F5. This will start the service and will probably show a web page in your default browser just showing a directory listing. This isn&#8217;t what we&#8217;re interested in. Append FlickrInfoIISHost.svc to the end of the URL shown in the page that opened up. Now you should see the default WCF page showing how to set up Metadata Exchange which we&#8217;re going to ignore in this tutorial. This is good enough to let you know that your service is being hosted.</p>
<p>Next we need to create a proxy which will be used by our client to communicate with our new host. Most WCF tutorials have you create a proxy by adding a Service Reference or by using svcutil.exe. Here we&#8217;ll do it manually. It&#8217;s awfully simple, actually.</p>
<p>So, add a new Class Library project to your solution and name it FlickrInfoProxy. Change the name of the class file that&#8217;s been added for you to FlickrInfoProxy.cs. Add a Project Reference to BasicFlickrWCFContracts and a reference to System.ServiceModel. Now replace the code in your class with this code:</p>
<pre name="code" class="csharp">

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;

namespace Donaghe.FlickrInfoComponent
{
public class FlickrInfoProxy : ClientBase, IFlickrInfo
{
#region IFlickrInfo Members

public List GetRecentPhotos()
{
return Channel.GetRecentPhotos();
}

#endregion
}
}
</pre>
<p>Our proxy is a subclass of the ClientBase generic class based on our IFlickrInfo interface. Our proxy will also implement the IFlickrInfo interface. ClientBase gives us the proxy magic. It creates a WCF communications channel between our client (which specifies the host in its configuration) and our host. Implementing IFlickrInfo allows our proxy to call the proper method at the right time. We only have one method in our interface and our proxy just passes the call on to the host.</p>
<p>Building a proxy in this way allows us to reuse it with any number of other clients. It will be built as a dll and can be referenced whenever a client needs it without polluting the client project with irrelevant details. Proxies can become a lot more complex, as you can see if you ever create one by adding a ServiceReference, but in simple cases, why not use a simple proxy?</p>
<p>Now for the client. In this example we will create a super simple console application client. So, add a new Console Application to the solution and name it FlickrInfoClient. Add Project references to BasicFlickrWCFContracts and FlickrInfoProxy as well as a reference to System.ServiceModel.</p>
<p>Replace the code in Program.cs with this code:</p>
<pre name="code" class="csharp">

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Donaghe.FlickrInfoComponent
{
class Program
{
static void Main(string[] args)
{
FlickrInfoProxy proxy = new FlickrInfoProxy();

Console.WriteLine(&quot;Getting recent Flickr photos...&quot;);

using (proxy as IDisposable)
{
List photos = proxy.GetRecentPhotos();

foreach (FlickrPhoto photo in photos)
{
Console.WriteLine(photo.Url);
}
}

Console.WriteLine(&quot;Press the ENTER key to end this program...&quot;);

Console.ReadLine();
}
}
}
</pre>
<p>First we create a new instance of our proxy. The using line allows us to treat our Proxy as IDisposable. This lets us not need to worry about opening and closing the communications channel to the host. It&#8217;s done for us automatically. The rest of the code in the using block is straightfoward and shows just how easy it is to deal with a WCF component that&#8217;s hosted by IIS. Of course, we&#8217;d use the same exact code if the component was hosted on another machine in a Windows Service and accessed via NetTCP.</p>
<p>This isn&#8217;t everything we need though. Our client needs to contain information so that the proxy knows how to talk with the host. We&#8217;ll put this information into an App.config file. So, right click on the client project and chose Add New Item and in the dialog choose Application Configuration File. This will add a new file named App.config. Make your App.config file look like this:</p>
<pre name="code" class="xml">

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;

binding=&quot;wsHttpBinding&quot;
contract=&quot;Donaghe.FlickrInfoComponent.IFlickrInfo&quot;
/&gt;
</pre>
<p>In our client configuration we always need to specify the ABC&#8217;s of WCF. Address, Binding and Contract. The address is, unsurprisingly the address to the .svc file that we put in our IIS Host. Note that the port used is the same as the one we specified in the host. The binding is also the same as what we configured on the host side. The contract is the fully qualified name of our component&#8217;s interface.</p>
<p>Here&#8217;s how to run and test our WCF application. First, press ctrl-F5 to run the IIS host. Now, while the host is running, right click on the client project and chose Debug-&gt;Start new instance. This will open the Console window and run the client code. Your results should look something like this:</p>
<p><img class="alignnone" title="Console Results" src="http://farm4.static.flickr.com/3501/3269068081_a2aaa32ed1.jpg" alt="" width="500" height="251" /></p>
<p>In subsequent articles we&#8217;ll use this same component and extend it and exercise many WCF features with it. Coming up we&#8217;ll create a simple Windows Form application and use our component in-process.</p>
<p>I am by no means an expert in this, so please feel free to leave a comment if you&#8217;ve spotted a bug, or a better way to do something or even any criticism you have. I appreciate it!</p>
<p>Here is a zip file containing all of the source code in the application talked about above: <a href="http://www.tadsharp.net/wp-content/uploads/2009/02/basicflickrwcfapp.zip">Basic Flickr WCF App</a></p>
<div id="scid:C16BAC14-9A3D-4c50-9394-FBFEF7A93539:4ea1b619-266f-496e-9351-7d616daa8a21" class="wlWriterEditableSmartContent" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"><a href="http://www.dotnetkicks.com/kick/?url=http://www.tadsharp.net/?p=41"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://www.tadsharp.net/?p=41" border="0" alt="kick it on DotNetKicks.com" /></a></div>
]]></content:encoded>
			<wfw:commentRss>http://www.tadsharp.net/?feed=rss2&amp;p=41</wfw:commentRss>
		</item>
		<item>
		<title>Calling the Flickr API getRecent method with c# and Linq to XML</title>
		<link>http://www.tadsharp.net/?p=28</link>
		<comments>http://www.tadsharp.net/?p=28#comments</comments>
		<pubDate>Sat, 07 Feb 2009 18:05:02 +0000</pubDate>
		<dc:creator>Tad</dc:creator>
		
		<category><![CDATA[.net]]></category>

		<category><![CDATA[extensions]]></category>

		<category><![CDATA[linq]]></category>

		<category><![CDATA[api]]></category>

		<category><![CDATA[csharp]]></category>

		<category><![CDATA[flickr]]></category>

		<category><![CDATA[wcf]]></category>

		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://www.tadsharp.net/?p=28</guid>
		<description><![CDATA[UPDATE: I have updated this article to now use the flickr.interestingness.getList method instead of getRecent.  I love getRecent, but out of every 3 to 400 pictures there&#8217;s almost always one or two pictures that most audiences would consider offensive.  All of the photos returned by flickr.interestingness.getList are artistic and very few of them [...]]]></description>
			<content:encoded><![CDATA[<p>UPDATE: I have updated this article to now use the <a href="http://www.flickr.com/services/api/flickr.interestingness.getList.html">flickr.interestingness.getList</a> method instead of getRecent.  I love getRecent, but out of every 3 to 400 pictures there&#8217;s almost always one or two pictures that most audiences would consider offensive.  All of the photos returned by flickr.interestingness.getList are artistic and very few of them would be considered offensive by most people.</p>
<p>One of my favorite features of <a href="http://www.flickr.com">Flickr</a> is browsing through photos that have just been uploaded.  You can get a glimpse of this on Flickr&#8217;s home page, but I decided I&#8217;d write some code so I could look at a bunch of them all at once.  I also like making calls against other web API&#8217;s (like from Twitter, FriendFeed or delicious).</p>
<p><span id="more-28"></span></p>
<p>Here&#8217;s a sample of the kind of code you might write to call Flickr:</p>
<pre name="code" class="csharp">

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Net;

namespace CurrentFlickrPicsConsoleExample
{
class Program
{
static void Main(string[] args)
{
string currentPicsXML = GetCurrentFlickrPicsXML();
Console.WriteLine(currentPicsXML);
Console.WriteLine();
Console.WriteLine(&quot;Press ENTER to exit this app...&quot;);
Console.ReadLine();
}

private static string GetCurrentFlickrPicsXML()
{
string result = new WebClient().DownloadString(&quot;http://api.flickr.com/services/rest/?method=flickr.interestingness.getList&amp;amp;amp;api_key=YOURFLICKRAPIKEY&quot;);

return result;
}

}
}
</pre>
<p>If you want to execute this code, copy it and paste it into a new Console application and be sure to replace &#8216;YOURFLICKRAPIKEY&#8217; with your key.  Instructions to get a Flickr API key are here.</p>
<p>A subset of the XML returned from Flickr looks like this:</p>
<pre name="code" class="xml">

&lt;photos page=&quot;2&quot; pages=&quot;89&quot; perpage=&quot;10&quot; total=&quot;881&quot;&gt;
&lt;photo id=&quot;2636&quot; owner=&quot;47058503995@N01&quot;
secret=&quot;a123456&quot; server=&quot;2&quot; title=&quot;test_04&quot;
ispublic=&quot;1&quot; isfriend=&quot;0&quot; isfamily=&quot;0&quot; /&gt;
&lt;photo id=&quot;2635&quot; owner=&quot;47058503995@N01&quot;
secret=&quot;b123456&quot; server=&quot;2&quot; title=&quot;test_03&quot;
ispublic=&quot;0&quot; isfriend=&quot;1&quot; isfamily=&quot;1&quot; /&gt;
&lt;photo id=&quot;2633&quot; owner=&quot;47058503995@N01&quot;
secret=&quot;c123456&quot; server=&quot;2&quot; title=&quot;test_01&quot;
ispublic=&quot;1&quot; isfriend=&quot;0&quot; isfamily=&quot;0&quot; /&gt;
&lt;photo id=&quot;2610&quot; owner=&quot;12037949754@N01&quot;
secret=&quot;d123456&quot; server=&quot;2&quot; title=&quot;00_tall&quot;
ispublic=&quot;1&quot; isfriend=&quot;0&quot; isfamily=&quot;0&quot; /&gt;
&lt;/photos&gt;
</pre>
<p>In order to get the Linq to XML magic, you need to create a System.Linq.Xml.XElement object.  The XElement can parse the XML string.  I created this extension to System.Net.WebClient to make the process super simple:</p>
<pre name="code" class="csharp">

public static XElement DownloadXElement(this System.Net.WebClient webClient, string address)
{
string result = webClient.DownloadString(address);

XElement x = XElement.Parse(result);

return x;
}
</pre>
<p>Assuming I have a class created called Photo, I can write this super simple Linq to XML code to create an IEnumerable collection of photos (assuming x is of type XElement):</p>
<pre name="code" class="csharp">

XElement x = (new WebClient()).DownloadXElement(&quot;http://api.flickr.com/services/rest/?method=flickr.interestingness.getList&amp;amp;amp;api_key=YOURFLICKRAPIKEY&quot;);

var query = from b in x.Elements(&quot;photos&quot;).Elements(&quot;photo&quot;)
select new Photo
{
Farm = b.Attribute(&quot;farm&quot;).Value,
Id = b.Attribute(&quot;id&quot;).Value,
Secret = b.Attribute(&quot;secret&quot;).Value,
Server = b.Attribute(&quot;server&quot;).Value,
Owner = b.Attribute(&quot;owner&quot;).Value,
Title = b.Attribute(&quot;title&quot;).Value
};

foreach (Photo photo in query)
{
photos.Add(photo);
}
</pre>
<p>This query is very simple - we just loop through all of the <em>photo</em> elements which are children of the <em>photo</em> element.  At each photo, we create a new Photo object, reading its values from the attributes of the xml photo.  Those Photo objects then go into the result of the query, query, which we know implements IEnumerable.  Its actual type is irrelevant to use since we&#8217;re only interested in its IEnumerable implementation.</p>
<p>For the purposes of this article, we can put all these pieces together into one console app, call the Flickr API, receive the XML, parse it into a collection of Photo objects and then spit out the photo urls for each of those objects.</p>
<p>I have created a web application using this code.  I call it &#8220;Tad&#8217;s Flickr Toy - Interestingness.&#8221;  You can view this application <a href="http://www.xelinprojects.com/FlickrToyInteresting/Default.aspx">here</a>.</p>
<p>This article is sort of a prelude to a series of articles using a WCF component built around this code.  In the series I will be hosting and using the component in all sorts of scenarios, showing how to use WCF in many different ways.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.tadsharp.net/?feed=rss2&amp;p=28</wfw:commentRss>
		</item>
		<item>
		<title>Best of WCF, January 25, 2009</title>
		<link>http://www.tadsharp.net/?p=22</link>
		<comments>http://www.tadsharp.net/?p=22#comments</comments>
		<pubDate>Mon, 26 Jan 2009 04:00:44 +0000</pubDate>
		<dc:creator>Tad</dc:creator>
		
		<category><![CDATA[wcf]]></category>

		<category><![CDATA[wcf duplex 2-way]]></category>

		<guid isPermaLink="false">http://www.tadsharp.net/?p=22</guid>
		<description><![CDATA[Two way client server network communication
A question on StackOverflow about 2 way WCF communication.  The answers provide some excellent links to resources concerning WCF duplex messaging.  Chapter 5 of Juval Lowy&#8217;s excellent Programming WCF Services has a lengthy discussion on Duplex messenges including Server/Client event models - really cool stuff!
Async Operations in WCF: Event Based [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://stackoverflow.com/questions/476211/two-way-client-server-network-communication">Two way client server network communication</a></p>
<p>A question on StackOverflow about 2 way WCF communication.  The answers provide some excellent links to resources concerning WCF duplex messaging.  Chapter 5 of Juval Lowy&#8217;s excellent <a href="http://www.amazon.com/gp/product/0596521308?ie=UTF8&amp;tag=donaghehomepa-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0596521308">Programming WCF Services</a><img style="border:none !important; margin:0px !important;" src="http://www.assoc-amazon.com/e/ir?t=donaghehomepa-20&amp;l=as2&amp;o=1&amp;a=0596521308" border="0" alt="" width="1" height="1" /> has a lengthy discussion on Duplex messenges including Server/Client event models - really cool stuff!</p>
<p><a href="http://www.danrigsby.com/blog/index.php/2008/03/18/async-operations-in-wcf-event-based-model/">Async Operations in WCF: Event Based Model</a></p>
<p>Along the same lines, I found this gem of a 5 part series on two-way messaging in WCF the other day.  Excellent article - I hope to have a screencast and sample solution of my own concerning Events in WCF before long.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.tadsharp.net/?feed=rss2&amp;p=22</wfw:commentRss>
		</item>
		<item>
		<title>Manual WCF - An extension</title>
		<link>http://www.tadsharp.net/?p=9</link>
		<comments>http://www.tadsharp.net/?p=9#comments</comments>
		<pubDate>Mon, 19 Jan 2009 05:14:31 +0000</pubDate>
		<dc:creator>Tad</dc:creator>
		
		<category><![CDATA[screencast]]></category>

		<category><![CDATA[wcf]]></category>

		<category><![CDATA[wcf screencast]]></category>

		<guid isPermaLink="false">http://www.tadsharp.net/?p=9</guid>
		<description><![CDATA[While going through the WCF questions on StackOverflow a few days ago, I found a link to an excellent article on setting up WCF manually from bottom to top written by Miguel A. Castro for Code Magazine.&#160; You can find the article here.&#160; Please go and read it before proceeding.
The thrust of the article is [...]]]></description>
			<content:encoded><![CDATA[<p>While going through the WCF questions on StackOverflow a few days ago, I found a link to an excellent article on setting up WCF manually from bottom to top written by Miguel A. Castro for Code Magazine.&#160; You can find the article <a href="http://www.devx.com/codemag/Article/39837">here</a>.&#160; Please go and read it before proceeding.</p>
<p>The thrust of the article is to show how to create a WCF contract, service, host, proxy and client without relying on Visual Studio or other external tools to create anything for you.&#160; In particular Castro prefers to create his own .config files and proxies.</p>
<p>In the article, Castro shows two different ways to set up a client proxy for his service.&#160; The author of the question that lead me to the article had trouble with one of the proxies, shown below:   
<pre name="code" class="csharp">
    &lt;br /&gt;using System;    &lt;br /&gt;using System.ServiceModel;&lt;/p&gt;  &lt;p&gt;namespace CoDeMagazine.ServiceArticle   &lt;br /&gt;{    &lt;br /&gt;public class AdminClient : IProductAdmin    &lt;br /&gt;{    &lt;br /&gt;public AdminClient()    &lt;br /&gt;{    &lt;br /&gt;IProductAdmin productAdminChannel =    &lt;br /&gt;new ChannelFactory&lt;iproductadmin&gt;().    &lt;br /&gt;CreateChannel();    &lt;br /&gt;}&lt;/p&gt;  &lt;p&gt;IProductAdmin productAdminChannel = null;&lt;/p&gt;  &lt;p&gt;#region IProductAdmin Members&lt;/p&gt;  &lt;p&gt;public void UpdateProduct(   &lt;br /&gt;ProductData product)    &lt;br /&gt;{    &lt;br /&gt;productAdminChannel.UpdateProduct(    &lt;br /&gt;product);    &lt;br /&gt;}&lt;/p&gt;  &lt;p&gt;public void DeleteProduct(Guid productID)   &lt;br /&gt;{    &lt;br /&gt;productAdminChannel.DeleteProduct(    &lt;br /&gt;productID);    &lt;br /&gt;}&lt;/p&gt;  &lt;p&gt;#endregion   &lt;br /&gt;}&lt;/p&gt;  &lt;p&gt;}   &lt;br /&gt;
</pre>
</p>
<p>The problem here is that as far as I can see, I can only get this to work by referencing the endpoint name pointed to by the client. If I change constructor to look like this:</p>
<p>
<pre name="code" class="csharp">
&lt;/p&gt;  &lt;p&gt;public AdminClient()   &lt;br /&gt;{    &lt;br /&gt;IProductAdmin productAdminChannel =    &lt;br /&gt;new ChannelFactory&lt;iproductadmin&gt;(&quot;endpointName&quot;).    &lt;br /&gt;CreateChannel();    &lt;br /&gt;}    &lt;br /&gt;
</pre>
</p>
<p>given an endpoint configuration in the client like:</p>
<p>
<pre name="code" class="csharp">
&lt;/p&gt;  &lt;p&gt;&lt;endpoint address=&quot;&lt;br&quot; /&gt;http://localhost:9224/ProductService.svc   &lt;br /&gt;binding=&quot;wsHttpBinding&quot;    &lt;br /&gt;name=&quot;endpointName&quot;    &lt;br /&gt;contract=&quot;CoDeMagazine.ServiceArticle.    &lt;br /&gt;IProductBrowser&quot; /&gt;&lt;/p&gt;  &lt;p&gt;
</pre>
</p>
<p>it works! I&#8217;m not sure if Mr Castro is just wrong or if there&#8217;s something that I and the other folks on StackOverflow missed.</p>
<p>Either way, I created a sample project to share and a very brief screen cast to go along with it. My example is simpler, but fully working - you shouldn&#8217;t have to do any extra work to get it up and running and you can apply the concepts in your own work.</p>
<p><a href="http://www.tadsharp.net/wp-content/uploads/2009/01/manualcontracts.zip" target="_blank">ManualWCFExample</a></p>
<p><a href="http://www.screencast.com/users/TDonaghe/folders/Jing/media/09a6a9f2-ea71-4b80-9b21-67b95fd2391d" target="_blank">View the screencast here</a>.</p>
<p>I may well have made a goof or error in this post, the code linked, or in the screencast.&#160; If you find something you&#8217;d like to correct, feel free to leave a comment below.</p>
<p>Thanks for reading!   <br /><!–dotnetkickit–></p>
]]></content:encoded>
			<wfw:commentRss>http://www.tadsharp.net/?feed=rss2&amp;p=9</wfw:commentRss>
		</item>
	</channel>
</rss>
