<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:georss="http://www.georss.org/georss" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>DotNetDude.com - WCF</title>
    <link>http://www.dotnetdude.com/</link>
    <description>Miguel A. Castro's Blog</description>
    <image>
      <url>http://www.dotnetdude.com/feed-icon-24x24.gif</url>
      <title>DotNetDude.com - WCF</title>
      <link>http://www.dotnetdude.com/</link>
    </image>
    <language>en-us</language>
    <copyright>Miguel A. Castro</copyright>
    <lastBuildDate>Fri, 20 Aug 2010 21:14:53 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.3.9074.18820</generator>
    <managingEditor>miguelcastro67@gmail.com</managingEditor>
    <webMaster>miguelcastro67@gmail.com</webMaster>
    <item>
      <trackback:ping>http://www.dotnetdude.com/Trackback.aspx?guid=e7db86ec-8bd9-4886-ba80-ae14ff6aa11c</trackback:ping>
      <pingback:server>http://www.dotnetdude.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.dotnetdude.com/PermaLink,guid,e7db86ec-8bd9-4886-ba80-ae14ff6aa11c.aspx</pingback:target>
      <dc:creator>Miguel A. Castro</dc:creator>
      <wfw:comment>http://www.dotnetdude.com/CommentView,guid,e7db86ec-8bd9-4886-ba80-ae14ff6aa11c.aspx</wfw:comment>
      <wfw:commentRss>http://www.dotnetdude.com/SyndicationService.asmx/GetEntryCommentsRss?guid=e7db86ec-8bd9-4886-ba80-ae14ff6aa11c</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Callback functionality in WCF allows the service to call back to the client and send
information or notification back.  In essence, reversing the client-service roles. 
It’s a rather simple model with great benefits, specially if you want to keep the
client notified on a long running process and display said notifications on the UI. 
However, it’s not a trivial matter to deal with proper thread handling when using
this functionality.  Most WCF callback demos will simply popup message boxes
to show you when a callback has taken place, but if you need to do something more
substantial that is UI-related, there’s a few other things you need to take into consideration.
</p>
        <p>
In the second installment of “This Week In Code”, I’ll give you a demonstration of
a typical callback demo that you may run into often.  Then I’ll change it to
a more real-world scenario and introduce additional thread-handling details that you
must undertake.
</p>
        <p>
I’m not going to turn this posting into a WCF callback tutorial so I’m going to assume
that you know how callbacks work and how to set them up.  Here’s some client
code that calls a service:
</p>
        <p>
 
</p>
        <pre class="brush: csharp;">private void btnSimpleCall_Click(object sender, EventArgs e)
{
    using (MyDuplexClient proxy = new MyDuplexClient(new InstanceContext(this)))
    {
        proxy.SimpleTest();
    }
}

</pre>
        <p>
 
</p>
        <p>
As you can see, it’s called from a button’s <strong>Click</strong> event.  This
will become important later.
</p>
        <p>
And here’s the service operation that calls back to the client:
</p>
        <p>
 
</p>
        <pre class="brush: csharp;">public bool SimpleTest()
{
    Console.WriteLine("Serviced called.  Performing callback.");
    IMyCallback callback = OperationContext.Current.GetCallbackChannel&lt;IMyCallback&gt;();
    if(callback != null)
    {
        callback.PerformCallback();
    }
    Console.WriteLine("Callback performed.");

    return true; 
}

</pre>
        <p>
 
</p>
        <p>
The client that made the service call is a Windows Form and as I stated, it was a
button that fired off the event.  The form itself is the implementor of the callback
contract, which is why the <strong>InstanceContext</strong> instance wraps <strong>this</strong>. 
Of course, the form needs the callback contract’s implementation because that’s what
gets called when the service executes the callback operation.  Here’s that implementation
now.
</p>
        <p>
 
</p>
        <pre class="brush: csharp;">public void PerformCallback()
{
    MessageBox.Show("Callback from service on the client");
}
</pre>
        <p>
 
</p>
        <p>
This simple example will work just fine because the callback is simply throwing up
a message box.  This mean it’s not accessing the actual form’s UI so there will
not be any threading issues.  Unfortunately, most examples you see on WCF callbacks
do only this and as soon as the developer mimics this pattern but performs some UI
update to the actual form, they run into problems.  Let me alter my code example
and explain why.
</p>
        <p>
Ok, so this next example is supposed to make a service call from the form’s button,
then the service will perform a potentially long iteration and every so many items
in the loop, it will call back to the client to report progress.  The client
simply wants to use the value in the callback to update a progress bar o the form:
</p>
        <p>
 
</p>
        <pre class="brush: csharp;">private void button1_Click(object sender, EventArgs e)
{
    int max = Convert.ToInt32(txtMax.Text);
    int step = Convert.ToInt16(txtStep.Text);

     progressBar1.Minimum = 0;
     progressBar1.Maximum = max;

     MyDuplexClient proxy = new MyDuplexClient(new InstanceContext(this));

     int[] numbers = proxy.GetNumbers(max, step);

     foreach (int number in numbers)
     {
        lstNumbers.Items.Add(number.ToString());
     }
}

public void ReportProgress(int progress)
{
    progressBar1.Value = progress;
}

</pre>
        <p>
 
</p>
        <p>
So what do you think is going to happen here?  Well we have a potential catch-22
with this scenario.  By default the callback will me automatically be marshaled
to the UI thread before it gets executed on the client.  If that happens, accessing
the progress bar directly from the callback operation is perfectly fine, except that
the UI thread is currently in the middle of a service call, since it was initiated
in the button click, so we have a deadlock scenario there.
</p>
        <p>
One thing I can do is decorate the form (as the implementor of callback contract)
with the <strong>CallbackBehavior</strong> attribute and tell it to not use the form’s <strong>Synchronization
Context</strong>:
</p>
        <p>
 
</p>
        <pre class="brush: csharp;">[CallbackBehavior(UseSynchronizationContext = false)]
public partial class Form1 : Form, IMyCallback

</pre>
        <p>
 
</p>
        <p>
This means that the callback will now be executed on a background thread and not the
same thread as the one that made the service call initially (which is the default
behavior).  But now I’ve introduced another problem.  The <strong>ReportProgress</strong> callback
operation can no longer directly access the UI since it’s not on the UI thread, so
I need to marshal up to the UI thread in order to access the progress bar.
</p>
        <p>
The best way to do this is to use the form’s <strong>Synchronization Context</strong>;
a feature introduced back in .NET 2.0 but still relatively unknown.  Rather than
use the old “invoke” technique, I’m going to grab the form’s synchronization context
as early as possible and store it in a class-wide variable.  It doesn’t get any
earlier than the form’s constructor, so I’ll do it there:
</p>
        <p>
 
</p>
        <pre class="brush: csharp;">public Form1()
{
    InitializeComponent();
    _SyncContext = SynchronizationContext.Current;
}
        
SynchronizationContext _SyncContext = null;

</pre>
        <p>
 
</p>
        <p>
Now I have accessible to me at any time, a variable that represents the form’s thread
execution context; and I can use this variable from any thread I want since it will
always point back to the UI thread.
</p>
        <p>
Next, I’ll modify the callback operation to use the <strong>_SyncContext</strong> object
in order to fire code to the thread it represents, in this case the UI thread:
</p>
        <p>
 
</p>
        <pre class="brush: csharp;">public void ReportProgress(int progress)
{
    SendOrPostCallback setText = delegate
    {
        progressBar1.Value = progress;
    };

     _SyncContext.Post(setText, null);
}

</pre>
        <p>
 
</p>
        <p>
Well, that takes care of my marshaling task, but I’ve just introduced the old problem
all over again.  Remember, the UI thread was in use by the button’s event which
is not over yet.  It seems I’m going round and round with nowhere to go. 
Well, I do have a way out of this.  The solution to the problem lies in the way
I fired off the service operation.  If you recall, my goal was to fire off the
operation, receive occasional callbacks, and then once the service call was complete,
I want to display results to a list box.  What I need to do is not lock up the
UI while I make the service call so I’m going to fire off the service call on another
thread; but not just the service call, the update to the list box as well.  If
I don’t do both, then the service call will fire on another thread and the list box
will attempt to update right away.  So the button’s <strong>Click</strong> event
will make the service call on a separate thread, after which, on that same thread
it will update the list box with the service operation results.  But since that’s
a UI operation, it needs to marshal that little bit up to the UI.  But never
fear, I have my old friend, _<strong>SynchronizationContext</strong> at my disposal.
</p>
        <p>
Here’s the new button <strong>Click</strong> event:
</p>
        <p>
 
</p>
        <pre class="brush: csharp;">private void button1_Click(object sender, EventArgs e)
{
    int max = Convert.ToInt32(txtMax.Text);
    int step = Convert.ToInt16(txtStep.Text);

    progressBar1.Minimum = 0;
    progressBar1.Maximum = max;

    int[] numbers;

    MyDuplexClient proxy = new MyDuplexClient(new InstanceContext(this));

    Thread thread = new Thread(delegate()
    {
        numbers = proxy.GetNumbers(max, step);

        SendOrPostCallback addListItem = delegate
        {
            foreach (int number in numbers)
                lstNumbers.Items.Add(number.ToString());
        };

        _SyncContext.Post(addListItem, null);
    });

    thread.Start();
}

</pre>
        <p>
 
</p>
        <p>
The only drawback with this technique is that as soon as the button is clicked, the
user will have control of the UI returned.  This may or may not be a good thing. 
As you can see, there’s a lot to be concerned about when you’re using WCF callback’s
to update UI.  The solution that immediately comes to mind to control the UI
fully, is to use an asynchronous delegate instead of a <strong>Thread</strong> object. 
in fact, the <strong>Thread</strong> object is not a good idea anyway because it doesn’t
use the thread pool and thread initiation carries a lot of weight.  If I change
the code to use an asynchronous delegate, I can declare the <strong>IAsyncResult</strong> object
that the invoking the delegate will return, at a class level.  Doing this, gives
me access to the state of the asynchronous call anywhere on the form.  Then I
can check for the <strong>IsCompleted</strong> property before allowing other UI activity
to occur.
</p>
        <p>
Here’s the re-work using an asynchronous delegate instead.  Notice that thanks
to the <strong>Func</strong> delegate and its overloads, I didn’t need to create my
own delegate for this.  Also notice that true to the async delegate pattern,
I use a callback method (not to be confused with the service callback) that will get
fired after the task of the delegate is completed.  And it is here where I’ll
update my list box.  The async delegate callback method gets fired on the same
background thread that the delegate did its work, so I still need to marshal up to
the UI thread in order to update it.
</p>
        <p>
 
</p>
        <pre class="brush: csharp;">private void button2_Click(object sender, EventArgs e)
{
    int max = Convert.ToInt32(txtMax.Text);
    int step = Convert.ToInt16(txtStep.Text);

    progressBar1.Minimum = 0;
    progressBar1.Maximum = max;

    MyDuplexClient proxy = new MyDuplexClient(new InstanceContext(this));

    Func&lt;int, int, int[]&gt; proxyCall = new Func&lt;int, int, int[]&gt;(proxy.GetNumbers);

    asyncProxy = proxyCall.BeginInvoke(max, step, ServiceCallComplete, proxyCall);
}

void ServiceCallComplete(IAsyncResult ar)
{
    Func&lt;int, int, int[]&gt; proxyCall = (Func&lt;int, int, int[]&gt;)ar.AsyncState;

    int[] numbers = proxyCall.EndInvoke(ar);

    SendOrPostCallback addListItem = delegate
    {               
        foreach (int number in numbers)
            lstNumbers.Items.Add(number.ToString());
    };

    _SyncContext.Send(addListItem, null);
}

</pre>
        <p>
 
</p>
        <p>
Now from anywhere else in the form where a user action might take place, I can check
the service call thread like this:
</p>
        <p>
 
</p>
        <pre class="brush: csharp;">private void btnClear_Click(object sender, EventArgs e)
{
    if (_AsyncProxy.IsCompleted)
    {
        lstNumbers.Items.Clear();
        progressBar1.Value = 0;
    }
}

</pre>
        <p>
 
</p>
        <p>
As you can see, using WCF callbacks, while easy, is not trivial when the work you
want to do back at the client is UI related.  The first thing you should always
ask yourself is, “do I really need to do this?”.  There’s a lot of details to
take care of and even then, you may not get the effect that you would like. 
In this last example, pressing the Clear button will simply do nothing.  In reality,
you may want to disable controls on the form while the service call is taking place. 
See, there’s quite a lot of worry about.
</p>
        <p>
 
</p>
        <h3>
          <em>Until next time…</em>
        </h3>
        <img width="0" height="0" src="http://www.dotnetdude.com/aggbug.ashx?id=e7db86ec-8bd9-4886-ba80-ae14ff6aa11c" />
      </body>
      <title>Dealing With Threading When Using WCF Callbacks</title>
      <guid isPermaLink="false">http://www.dotnetdude.com/PermaLink,guid,e7db86ec-8bd9-4886-ba80-ae14ff6aa11c.aspx</guid>
      <link>http://www.dotnetdude.com/2010/08/20/DealingWithThreadingWhenUsingWCFCallbacks.aspx</link>
      <pubDate>Fri, 20 Aug 2010 21:14:53 GMT</pubDate>
      <description>&lt;p&gt;
Callback functionality in WCF allows the service to call back to the client and send
information or notification back.&amp;nbsp; In essence, reversing the client-service roles.&amp;nbsp;
It’s a rather simple model with great benefits, specially if you want to keep the
client notified on a long running process and display said notifications on the UI.&amp;nbsp;
However, it’s not a trivial matter to deal with proper thread handling when using
this functionality.&amp;nbsp; Most WCF callback demos will simply popup message boxes
to show you when a callback has taken place, but if you need to do something more
substantial that is UI-related, there’s a few other things you need to take into consideration.
&lt;/p&gt;
&lt;p&gt;
In the second installment of “This Week In Code”, I’ll give you a demonstration of
a typical callback demo that you may run into often.&amp;nbsp; Then I’ll change it to
a more real-world scenario and introduce additional thread-handling details that you
must undertake.
&lt;/p&gt;
&lt;p&gt;
I’m not going to turn this posting into a WCF callback tutorial so I’m going to assume
that you know how callbacks work and how to set them up.&amp;nbsp; Here’s some client
code that calls a service:
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;private void btnSimpleCall_Click(object sender, EventArgs e)
{
    using (MyDuplexClient proxy = new MyDuplexClient(new InstanceContext(this)))
    {
        proxy.SimpleTest();
    }
}

&lt;/pre&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
As you can see, it’s called from a button’s &lt;strong&gt;Click&lt;/strong&gt; event.&amp;nbsp; This
will become important later.
&lt;/p&gt;
&lt;p&gt;
And here’s the service operation that calls back to the client:
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;public bool SimpleTest()
{
    Console.WriteLine("Serviced called.  Performing callback.");
    IMyCallback callback = OperationContext.Current.GetCallbackChannel&amp;lt;IMyCallback&amp;gt;();
    if(callback != null)
    {
        callback.PerformCallback();
    }
    Console.WriteLine("Callback performed.");

    return true; 
}

&lt;/pre&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
The client that made the service call is a Windows Form and as I stated, it was a
button that fired off the event.&amp;nbsp; The form itself is the implementor of the callback
contract, which is why the &lt;strong&gt;InstanceContext&lt;/strong&gt; instance wraps &lt;strong&gt;this&lt;/strong&gt;.&amp;nbsp;
Of course, the form needs the callback contract’s implementation because that’s what
gets called when the service executes the callback operation.&amp;nbsp; Here’s that implementation
now.
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;public void PerformCallback()
{
    MessageBox.Show("Callback from service on the client");
}
&lt;/pre&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
This simple example will work just fine because the callback is simply throwing up
a message box.&amp;nbsp; This mean it’s not accessing the actual form’s UI so there will
not be any threading issues.&amp;nbsp; Unfortunately, most examples you see on WCF callbacks
do only this and as soon as the developer mimics this pattern but performs some UI
update to the actual form, they run into problems.&amp;nbsp; Let me alter my code example
and explain why.
&lt;/p&gt;
&lt;p&gt;
Ok, so this next example is supposed to make a service call from the form’s button,
then the service will perform a potentially long iteration and every so many items
in the loop, it will call back to the client to report progress.&amp;nbsp; The client
simply wants to use the value in the callback to update a progress bar o the form:
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;private void button1_Click(object sender, EventArgs e)
{
    int max = Convert.ToInt32(txtMax.Text);
    int step = Convert.ToInt16(txtStep.Text);

     progressBar1.Minimum = 0;
     progressBar1.Maximum = max;

     MyDuplexClient proxy = new MyDuplexClient(new InstanceContext(this));

     int[] numbers = proxy.GetNumbers(max, step);

     foreach (int number in numbers)
     {
        lstNumbers.Items.Add(number.ToString());
     }
}

public void ReportProgress(int progress)
{
    progressBar1.Value = progress;
}

&lt;/pre&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
So what do you think is going to happen here?&amp;nbsp; Well we have a potential catch-22
with this scenario.&amp;nbsp; By default the callback will me automatically be marshaled
to the UI thread before it gets executed on the client.&amp;nbsp; If that happens, accessing
the progress bar directly from the callback operation is perfectly fine, except that
the UI thread is currently in the middle of a service call, since it was initiated
in the button click, so we have a deadlock scenario there.
&lt;/p&gt;
&lt;p&gt;
One thing I can do is decorate the form (as the implementor of callback contract)
with the &lt;strong&gt;CallbackBehavior&lt;/strong&gt; attribute and tell it to not use the form’s &lt;strong&gt;Synchronization
Context&lt;/strong&gt;:
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;[CallbackBehavior(UseSynchronizationContext = false)]
public partial class Form1 : Form, IMyCallback

&lt;/pre&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
This means that the callback will now be executed on a background thread and not the
same thread as the one that made the service call initially (which is the default
behavior).&amp;nbsp; But now I’ve introduced another problem.&amp;nbsp; The &lt;strong&gt;ReportProgress&lt;/strong&gt; callback
operation can no longer directly access the UI since it’s not on the UI thread, so
I need to marshal up to the UI thread in order to access the progress bar.
&lt;/p&gt;
&lt;p&gt;
The best way to do this is to use the form’s &lt;strong&gt;Synchronization Context&lt;/strong&gt;;
a feature introduced back in .NET 2.0 but still relatively unknown.&amp;nbsp; Rather than
use the old “invoke” technique, I’m going to grab the form’s synchronization context
as early as possible and store it in a class-wide variable.&amp;nbsp; It doesn’t get any
earlier than the form’s constructor, so I’ll do it there:
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;public Form1()
{
    InitializeComponent();
    _SyncContext = SynchronizationContext.Current;
}
        
SynchronizationContext _SyncContext = null;

&lt;/pre&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
Now I have accessible to me at any time, a variable that represents the form’s thread
execution context; and I can use this variable from any thread I want since it will
always point back to the UI thread.
&lt;/p&gt;
&lt;p&gt;
Next, I’ll modify the callback operation to use the &lt;strong&gt;_SyncContext&lt;/strong&gt; object
in order to fire code to the thread it represents, in this case the UI thread:
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;public void ReportProgress(int progress)
{
    SendOrPostCallback setText = delegate
    {
        progressBar1.Value = progress;
    };

     _SyncContext.Post(setText, null);
}

&lt;/pre&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
Well, that takes care of my marshaling task, but I’ve just introduced the old problem
all over again.&amp;nbsp; Remember, the UI thread was in use by the button’s event which
is not over yet.&amp;nbsp; It seems I’m going round and round with nowhere to go.&amp;nbsp;
Well, I do have a way out of this.&amp;nbsp; The solution to the problem lies in the way
I fired off the service operation.&amp;nbsp; If you recall, my goal was to fire off the
operation, receive occasional callbacks, and then once the service call was complete,
I want to display results to a list box.&amp;nbsp; What I need to do is not lock up the
UI while I make the service call so I’m going to fire off the service call on another
thread; but not just the service call, the update to the list box as well.&amp;nbsp; If
I don’t do both, then the service call will fire on another thread and the list box
will attempt to update right away.&amp;nbsp; So the button’s &lt;strong&gt;Click&lt;/strong&gt; event
will make the service call on a separate thread, after which, on that same thread
it will update the list box with the service operation results.&amp;nbsp; But since that’s
a UI operation, it needs to marshal that little bit up to the UI.&amp;nbsp; But never
fear, I have my old friend, _&lt;strong&gt;SynchronizationContext&lt;/strong&gt; at my disposal.
&lt;/p&gt;
&lt;p&gt;
Here’s the new button &lt;strong&gt;Click&lt;/strong&gt; event:
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;private void button1_Click(object sender, EventArgs e)
{
    int max = Convert.ToInt32(txtMax.Text);
    int step = Convert.ToInt16(txtStep.Text);

    progressBar1.Minimum = 0;
    progressBar1.Maximum = max;

    int[] numbers;

    MyDuplexClient proxy = new MyDuplexClient(new InstanceContext(this));

    Thread thread = new Thread(delegate()
    {
        numbers = proxy.GetNumbers(max, step);

        SendOrPostCallback addListItem = delegate
        {
            foreach (int number in numbers)
                lstNumbers.Items.Add(number.ToString());
        };

        _SyncContext.Post(addListItem, null);
    });

    thread.Start();
}

&lt;/pre&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
The only drawback with this technique is that as soon as the button is clicked, the
user will have control of the UI returned.&amp;nbsp; This may or may not be a good thing.&amp;nbsp;
As you can see, there’s a lot to be concerned about when you’re using WCF callback’s
to update UI.&amp;nbsp; The solution that immediately comes to mind to control the UI
fully, is to use an asynchronous delegate instead of a &lt;strong&gt;Thread&lt;/strong&gt; object.&amp;nbsp;
in fact, the &lt;strong&gt;Thread&lt;/strong&gt; object is not a good idea anyway because it doesn’t
use the thread pool and thread initiation carries a lot of weight.&amp;nbsp; If I change
the code to use an asynchronous delegate, I can declare the &lt;strong&gt;IAsyncResult&lt;/strong&gt; object
that the invoking the delegate will return, at a class level.&amp;nbsp; Doing this, gives
me access to the state of the asynchronous call anywhere on the form.&amp;nbsp; Then I
can check for the &lt;strong&gt;IsCompleted&lt;/strong&gt; property before allowing other UI activity
to occur.
&lt;/p&gt;
&lt;p&gt;
Here’s the re-work using an asynchronous delegate instead.&amp;nbsp; Notice that thanks
to the &lt;strong&gt;Func&lt;/strong&gt; delegate and its overloads, I didn’t need to create my
own delegate for this.&amp;nbsp; Also notice that true to the async delegate pattern,
I use a callback method (not to be confused with the service callback) that will get
fired after the task of the delegate is completed.&amp;nbsp; And it is here where I’ll
update my list box.&amp;nbsp; The async delegate callback method gets fired on the same
background thread that the delegate did its work, so I still need to marshal up to
the UI thread in order to update it.
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;private void button2_Click(object sender, EventArgs e)
{
    int max = Convert.ToInt32(txtMax.Text);
    int step = Convert.ToInt16(txtStep.Text);

    progressBar1.Minimum = 0;
    progressBar1.Maximum = max;

    MyDuplexClient proxy = new MyDuplexClient(new InstanceContext(this));

    Func&amp;lt;int, int, int[]&amp;gt; proxyCall = new Func&amp;lt;int, int, int[]&amp;gt;(proxy.GetNumbers);

    asyncProxy = proxyCall.BeginInvoke(max, step, ServiceCallComplete, proxyCall);
}

void ServiceCallComplete(IAsyncResult ar)
{
    Func&amp;lt;int, int, int[]&amp;gt; proxyCall = (Func&amp;lt;int, int, int[]&amp;gt;)ar.AsyncState;

    int[] numbers = proxyCall.EndInvoke(ar);

    SendOrPostCallback addListItem = delegate
    {               
        foreach (int number in numbers)
            lstNumbers.Items.Add(number.ToString());
    };

    _SyncContext.Send(addListItem, null);
}

&lt;/pre&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
Now from anywhere else in the form where a user action might take place, I can check
the service call thread like this:
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;private void btnClear_Click(object sender, EventArgs e)
{
    if (_AsyncProxy.IsCompleted)
    {
        lstNumbers.Items.Clear();
        progressBar1.Value = 0;
    }
}

&lt;/pre&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
As you can see, using WCF callbacks, while easy, is not trivial when the work you
want to do back at the client is UI related.&amp;nbsp; The first thing you should always
ask yourself is, “do I really need to do this?”.&amp;nbsp; There’s a lot of details to
take care of and even then, you may not get the effect that you would like.&amp;nbsp;
In this last example, pressing the Clear button will simply do nothing.&amp;nbsp; In reality,
you may want to disable controls on the form while the service call is taking place.&amp;nbsp;
See, there’s quite a lot of worry about.
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;h3&gt;&lt;em&gt;Until next time…&lt;/em&gt;
&lt;/h3&gt;
&lt;img width="0" height="0" src="http://www.dotnetdude.com/aggbug.ashx?id=e7db86ec-8bd9-4886-ba80-ae14ff6aa11c" /&gt;</description>
      <comments>http://www.dotnetdude.com/CommentView,guid,e7db86ec-8bd9-4886-ba80-ae14ff6aa11c.aspx</comments>
      <category>Dev Stuff</category>
      <category>WCF</category>
    </item>
    <item>
      <trackback:ping>http://www.dotnetdude.com/Trackback.aspx?guid=7f97d63e-24c6-4455-a7c8-6452e0b23b19</trackback:ping>
      <pingback:server>http://www.dotnetdude.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.dotnetdude.com/PermaLink,guid,7f97d63e-24c6-4455-a7c8-6452e0b23b19.aspx</pingback:target>
      <dc:creator>Miguel A. Castro</dc:creator>
      <wfw:comment>http://www.dotnetdude.com/CommentView,guid,7f97d63e-24c6-4455-a7c8-6452e0b23b19.aspx</wfw:comment>
      <wfw:commentRss>http://www.dotnetdude.com/SyndicationService.asmx/GetEntryCommentsRss?guid=7f97d63e-24c6-4455-a7c8-6452e0b23b19</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <strong>
            <font color="#ff0000">Note: Using a Console app for hosting should be done
for development only !</font>
          </strong>
        </p>
        <p>
Now that the disclaimer is out of the way, I currently doing some development work
for a customer and I had the need to know every time any of my services receives a
call.  Since I do my development using a console application for service hosting,
it was easy enough to write out to the console from each service operation. 
Of course, putting code in every method was possible but not only would it be time
consuming, to turn it off later would be a pain.  The answer needed to be something
that gets hit on every operation.  Since WCF is essentially one giant inversion
of control container, I knew there was a point I could tap into before any operation
call.
</p>
        <p>
Enter behaviors !
</p>
        <p>
This turned out to be a multi-step process but once it’s in my library of WCF stuff,
I can reuse it and it actually turned out to be quite cool.  I’ll explain each
step and the reasons for the step.<br /></p>
        <p>
          <strong>
            <font size="2">Step 1 – Write a custom Parameter Inspector</font>
          </strong>
        </p>
        <p>
The first class you need to write is one that implements the <strong>IParameterInspector</strong> which
is in the <strong>System.ServiceModel.Dispatcher</strong> namespace.  This class
will later be installed in such a way that it gets hit on every operation call. 
The operation name is one of the arguments you have access to, as well as all the
operation arguments which I don’t need in this case.
</p>
        <p>
The methods in this implementation are <strong>BeforeCall</strong> and <strong>AfterCall</strong>,
and it is the <strong>BeforeCall</strong> that I’m interested in.  The code I’ll
place in this method very simply outputs something out to the console using <strong>Console.Writeline</strong>.
</p>
        <p>
Unfortunately the name of the service is not passed into this method so I need to
get that into this class using a custom constructor; you’ll see how I’ll get it to
the class later.
</p>
        <p>
Here’s the code for my <strong>ConsoleReportInspector</strong> class:
</p>
        <p>
 
</p>
        <pre class="brush: csharp;">public class ConsoleReportInspector : IParameterInspector
{
    public ConsoleReportInspector(string serviceName)
    {
        _ServiceName = serviceName;
    }

    string _ServiceName = string.Empty;

    void IParameterInspector.AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
    {
    }

    object IParameterInspector.BeforeCall(string operationName, object[] inputs)
    {
        Console.WriteLine(string.Format("{0} - '{1}.{2}' operation called.", DateTime.Now.ToLongTimeString(), _ServiceName, operationName));

        return null;
    }
}

</pre>
        <p>
          <br />
 
</p>
        <p>
          <font size="2">
            <strong>Step 2 – Install the class using an Operation Behavior</strong>
          </font>
        </p>
        <p>
In order to install the parameter inspector, I’ll need to write a custom operation
behavior class.  This is a class that implements the <strong>IOperationBehavior</strong> interface. 
You need to remove the throw to <strong>NotImplementedException</strong> from all
the methods; and the method of concern here is <strong>ApplyDispatchBehavior</strong>.
</p>
        <p>
The name of the service being called is accessible through the <strong>Parent</strong> property
of the <strong>dispatchOperation</strong> argument.  I need to instantiate my <strong>ConsoleReportInspector</strong> class
and send the service name into the constructor I added earlier.  Afterward, I
just need to add my parameter inspector class to the list of parameter inspectors
accessible in this behavior. 
</p>
        <p>
I also inherited this class from the <strong>System.Attribute</strong> class so I
can use it as an operation behavior attribute on individual operations if I wanted. 
This is just for flexibility since I plan on hooking this into a service so it affects
all operations.
</p>
        <p>
Here’s the code for my <strong>ConsoleReportOperationBehaviorAttribute</strong> class:
</p>
        <p>
 
</p>
        <pre class="brush: csharp;">[AttributeUsage(AttributeTargets.Method)]
public class ConsoleReportOperationBehaviorAttribute : Attribute, IOperationBehavior
{
    void IOperationBehavior.AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
    {
    }

    void IOperationBehavior.ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
    {
    }

    void IOperationBehavior.ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
    {
        string serviceName = dispatchOperation.Parent.Type.Name;
        dispatchOperation.ParameterInspectors.Add(new ConsoleReportInspector(serviceName));
    }

    void IOperationBehavior.Validate(OperationDescription operationDescription)
    {
    }
}

</pre>
        <br />
        <p>
As-is, I can simply decorate a service operation with [ConsoleReportOperationBehavior]
and if hosted on a console application, you’ll see output to the console when the
decorated operation is called.
</p>
        <p>
 
</p>
        <p>
          <strong>
            <font size="2">Step 3 – Install the operation behavior on all operations using
a Service Behavior</font>
          </strong>
        </p>
        <p>
Next I need to write a service behavior.  This is a behavior that gets installed
when the service loads (the host is opened).  The job of this behavior is to
install my operation behavior on all the service operations.  A service behavior
is a class that implement the <strong>IServiceBehavior</strong> interface.  Like
before, I’ll remove the exception calls and once again the method I’m interested in
is <strong>ApplyDispatchBehavior</strong>.
</p>
        <p>
I’m going to iterate through all the endpoints of this service, which are accessible
through the serviceDescription argument, and for each endpoint I will iterate through
the operations of the contract of each endpoint.  To each operation I will add
an instance of my ConsoleReportOperationBehaviorAttribute class.
</p>
        <p>
This class too I will inherit from <strong>Attribute</strong> so I can use it to decorate
a service in the case that I wanted to take this approach at some time.  
</p>
        <p>
Here’s the code for my <strong>ConsoleReportServiceBehaviorAttribute</strong> class:
</p>
        <p>
 
</p>
        <pre class="brush: csharp;">[AttributeUsage(AttributeTargets.Class)]
public class ConsoleReportServiceBehaviorAttribute : Attribute, IServiceBehavior
{
    void IServiceBehavior.AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection&lt;ServiceEndpoint&gt; endpoints, BindingParameterCollection bindingParameters)
    {
    }

    void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        foreach (ServiceEndpoint endpoint in serviceDescription.Endpoints)
            foreach (OperationDescription operation in endpoint.Contract.Operations)
                operation.Behaviors.Add(new ConsoleReportOperationBehaviorAttribute());
    }

    void IServiceBehavior.Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
    }
}

</pre>
        <p>
 
</p>
        <p>
          <font size="2">
            <strong>Step 4 – Apply the service behavior to any service I want programmatically
at the host</strong>
          </font>
        </p>
        <p>
Whatever approach you take to hosting, all you need to do is access each instance
of <strong>ServiceHost</strong> and add the service behavior to the list of behaviors
in the host.  I have my own techniques for hosting which include some custom
declarative stuff to allow me to turn hosting on and off at will through config. 
I also like to separate the accumulation of my <strong>ServiceHost</strong> instances
from the actual application that will do the hosting.  This way I can move it
to a Windows Service when I’m ready to go to production.
</p>
        <p>
Here’s the code that installs the behavior:
</p>
        <p>
 
</p>
        <p>
 
</p>
        <pre class="brush: csharp;">ConsoleReportServiceBehaviorAttribute behavior = serviceHost.Host.Description.Behaviors.Find&lt;ConsoleReportServiceBehaviorAttribute&gt;();
if (behavior == null)
    host.Description.Behaviors.Add(new ConsoleReportServiceBehaviorAttribute());
</pre>
        <br />
        <p>
 
</p>
        <p>
The <strong>host</strong> variable is an instance of <strong>ServiceHost</strong>. 
I perform the code above in between a config check so I can toggle it off at will.
</p>
        <p>
The end result is quite cool since when turned on, every call to any of your services
will be shown on the console.
</p>
        <p>
 
</p>
        <h3>
          <em>Until next time…</em>
        </h3>
        <img width="0" height="0" src="http://www.dotnetdude.com/aggbug.ashx?id=7f97d63e-24c6-4455-a7c8-6452e0b23b19" />
      </body>
      <title>A Cool Technique For Reporting WCF Operation Calls On Your Host Console (dev-only of course)</title>
      <guid isPermaLink="false">http://www.dotnetdude.com/PermaLink,guid,7f97d63e-24c6-4455-a7c8-6452e0b23b19.aspx</guid>
      <link>http://www.dotnetdude.com/2010/07/28/ACoolTechniqueForReportingWCFOperationCallsOnYourHostConsoleDevonlyOfCourse.aspx</link>
      <pubDate>Wed, 28 Jul 2010 02:57:11 GMT</pubDate>
      <description>&lt;p&gt;
&lt;strong&gt;&lt;font color="#ff0000"&gt;Note: Using a Console app for hosting should be done
for development only !&lt;/font&gt;&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
Now that the disclaimer is out of the way, I currently doing some development work
for a customer and I had the need to know every time any of my services receives a
call.&amp;nbsp; Since I do my development using a console application for service hosting,
it was easy enough to write out to the console from each service operation.&amp;nbsp;
Of course, putting code in every method was possible but not only would it be time
consuming, to turn it off later would be a pain.&amp;nbsp; The answer needed to be something
that gets hit on every operation.&amp;nbsp; Since WCF is essentially one giant inversion
of control container, I knew there was a point I could tap into before any operation
call.
&lt;/p&gt;
&lt;p&gt;
Enter behaviors !
&lt;/p&gt;
&lt;p&gt;
This turned out to be a multi-step process but once it’s in my library of WCF stuff,
I can reuse it and it actually turned out to be quite cool.&amp;nbsp; I’ll explain each
step and the reasons for the step.&lt;br&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;&lt;font size="2"&gt;Step 1 – Write a custom Parameter Inspector&lt;/font&gt;&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
The first class you need to write is one that implements the &lt;strong&gt;IParameterInspector&lt;/strong&gt; which
is in the &lt;strong&gt;System.ServiceModel.Dispatcher&lt;/strong&gt; namespace.&amp;nbsp; This class
will later be installed in such a way that it gets hit on every operation call.&amp;nbsp;
The operation name is one of the arguments you have access to, as well as all the
operation arguments which I don’t need in this case.
&lt;/p&gt;
&lt;p&gt;
The methods in this implementation are &lt;strong&gt;BeforeCall&lt;/strong&gt; and &lt;strong&gt;AfterCall&lt;/strong&gt;,
and it is the &lt;strong&gt;BeforeCall&lt;/strong&gt; that I’m interested in.&amp;nbsp; The code I’ll
place in this method very simply outputs something out to the console using &lt;strong&gt;Console.Writeline&lt;/strong&gt;.
&lt;/p&gt;
&lt;p&gt;
Unfortunately the name of the service is not passed into this method so I need to
get that into this class using a custom constructor; you’ll see how I’ll get it to
the class later.
&lt;/p&gt;
&lt;p&gt;
Here’s the code for my &lt;strong&gt;ConsoleReportInspector&lt;/strong&gt; class:
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;public class ConsoleReportInspector : IParameterInspector
{
    public ConsoleReportInspector(string serviceName)
    {
        _ServiceName = serviceName;
    }

    string _ServiceName = string.Empty;

    void IParameterInspector.AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
    {
    }

    object IParameterInspector.BeforeCall(string operationName, object[] inputs)
    {
        Console.WriteLine(string.Format("{0} - '{1}.{2}' operation called.", DateTime.Now.ToLongTimeString(), _ServiceName, operationName));

        return null;
    }
}

&lt;/pre&gt;
&lt;p&gt;
&lt;br&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
&lt;font size="2"&gt;&lt;strong&gt;Step 2 – Install the class using an Operation Behavior&lt;/strong&gt;&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
In order to install the parameter inspector, I’ll need to write a custom operation
behavior class.&amp;nbsp; This is a class that implements the &lt;strong&gt;IOperationBehavior&lt;/strong&gt; interface.&amp;nbsp;
You need to remove the throw to &lt;strong&gt;NotImplementedException&lt;/strong&gt; from all
the methods; and the method of concern here is &lt;strong&gt;ApplyDispatchBehavior&lt;/strong&gt;.
&lt;/p&gt;
&lt;p&gt;
The name of the service being called is accessible through the &lt;strong&gt;Parent&lt;/strong&gt; property
of the &lt;strong&gt;dispatchOperation&lt;/strong&gt; argument.&amp;nbsp; I need to instantiate my &lt;strong&gt;ConsoleReportInspector&lt;/strong&gt; class
and send the service name into the constructor I added earlier.&amp;nbsp; Afterward, I
just need to add my parameter inspector class to the list of parameter inspectors
accessible in this behavior. 
&lt;/p&gt;
&lt;p&gt;
I also inherited this class from the &lt;strong&gt;System.Attribute&lt;/strong&gt; class so I
can use it as an operation behavior attribute on individual operations if I wanted.&amp;nbsp;
This is just for flexibility since I plan on hooking this into a service so it affects
all operations.
&lt;/p&gt;
&lt;p&gt;
Here’s the code for my &lt;strong&gt;ConsoleReportOperationBehaviorAttribute&lt;/strong&gt; class:
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;[AttributeUsage(AttributeTargets.Method)]
public class ConsoleReportOperationBehaviorAttribute : Attribute, IOperationBehavior
{
    void IOperationBehavior.AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
    {
    }

    void IOperationBehavior.ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
    {
    }

    void IOperationBehavior.ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
    {
        string serviceName = dispatchOperation.Parent.Type.Name;
        dispatchOperation.ParameterInspectors.Add(new ConsoleReportInspector(serviceName));
    }

    void IOperationBehavior.Validate(OperationDescription operationDescription)
    {
    }
}

&lt;/pre&gt;
&lt;br&gt;
&lt;p&gt;
As-is, I can simply decorate a service operation with [ConsoleReportOperationBehavior]
and if hosted on a console application, you’ll see output to the console when the
decorated operation is called.
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;&lt;font size="2"&gt;Step 3 – Install the operation behavior on all operations using
a Service Behavior&lt;/font&gt;&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
Next I need to write a service behavior.&amp;nbsp; This is a behavior that gets installed
when the service loads (the host is opened).&amp;nbsp; The job of this behavior is to
install my operation behavior on all the service operations.&amp;nbsp; A service behavior
is a class that implement the &lt;strong&gt;IServiceBehavior&lt;/strong&gt; interface.&amp;nbsp; Like
before, I’ll remove the exception calls and once again the method I’m interested in
is &lt;strong&gt;ApplyDispatchBehavior&lt;/strong&gt;.
&lt;/p&gt;
&lt;p&gt;
I’m going to iterate through all the endpoints of this service, which are accessible
through the serviceDescription argument, and for each endpoint I will iterate through
the operations of the contract of each endpoint.&amp;nbsp; To each operation I will add
an instance of my ConsoleReportOperationBehaviorAttribute class.
&lt;/p&gt;
&lt;p&gt;
This class too I will inherit from &lt;strong&gt;Attribute&lt;/strong&gt; so I can use it to decorate
a service in the case that I wanted to take this approach at some time.&amp;nbsp; 
&lt;/p&gt;
&lt;p&gt;
Here’s the code for my &lt;strong&gt;ConsoleReportServiceBehaviorAttribute&lt;/strong&gt; class:
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;[AttributeUsage(AttributeTargets.Class)]
public class ConsoleReportServiceBehaviorAttribute : Attribute, IServiceBehavior
{
    void IServiceBehavior.AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection&amp;lt;ServiceEndpoint&amp;gt; endpoints, BindingParameterCollection bindingParameters)
    {
    }

    void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        foreach (ServiceEndpoint endpoint in serviceDescription.Endpoints)
            foreach (OperationDescription operation in endpoint.Contract.Operations)
                operation.Behaviors.Add(new ConsoleReportOperationBehaviorAttribute());
    }

    void IServiceBehavior.Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
    }
}

&lt;/pre&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
&lt;font size="2"&gt;&lt;strong&gt;Step 4 – Apply the service behavior to any service I want programmatically
at the host&lt;/strong&gt;&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
Whatever approach you take to hosting, all you need to do is access each instance
of &lt;strong&gt;ServiceHost&lt;/strong&gt; and add the service behavior to the list of behaviors
in the host.&amp;nbsp; I have my own techniques for hosting which include some custom
declarative stuff to allow me to turn hosting on and off at will through config.&amp;nbsp;
I also like to separate the accumulation of my &lt;strong&gt;ServiceHost&lt;/strong&gt; instances
from the actual application that will do the hosting.&amp;nbsp; This way I can move it
to a Windows Service when I’m ready to go to production.
&lt;/p&gt;
&lt;p&gt;
Here’s the code that installs the behavior:
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;&lt;pre class="brush: csharp;"&gt;ConsoleReportServiceBehaviorAttribute behavior = serviceHost.Host.Description.Behaviors.Find&amp;lt;ConsoleReportServiceBehaviorAttribute&amp;gt;();
if (behavior == null)
    host.Description.Behaviors.Add(new ConsoleReportServiceBehaviorAttribute());
&lt;/pre&gt;
&lt;br&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
The &lt;strong&gt;host&lt;/strong&gt; variable is an instance of &lt;strong&gt;ServiceHost&lt;/strong&gt;.&amp;nbsp;
I perform the code above in between a config check so I can toggle it off at will.
&lt;/p&gt;
&lt;p&gt;
The end result is quite cool since when turned on, every call to any of your services
will be shown on the console.
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;h3&gt;&lt;em&gt;Until next time…&lt;/em&gt;
&lt;/h3&gt;
&lt;img width="0" height="0" src="http://www.dotnetdude.com/aggbug.ashx?id=7f97d63e-24c6-4455-a7c8-6452e0b23b19" /&gt;</description>
      <comments>http://www.dotnetdude.com/CommentView,guid,7f97d63e-24c6-4455-a7c8-6452e0b23b19.aspx</comments>
      <category>Dev Stuff</category>
      <category>WCF</category>
    </item>
    <item>
      <trackback:ping>http://www.dotnetdude.com/Trackback.aspx?guid=6f2ef28b-fbd6-4f3c-b978-b999b4c230c4</trackback:ping>
      <pingback:server>http://www.dotnetdude.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.dotnetdude.com/PermaLink,guid,6f2ef28b-fbd6-4f3c-b978-b999b4c230c4.aspx</pingback:target>
      <dc:creator>Miguel A. Castro</dc:creator>
      <wfw:comment>http://www.dotnetdude.com/CommentView,guid,6f2ef28b-fbd6-4f3c-b978-b999b4c230c4.aspx</wfw:comment>
      <wfw:commentRss>http://www.dotnetdude.com/SyndicationService.asmx/GetEntryCommentsRss?guid=6f2ef28b-fbd6-4f3c-b978-b999b4c230c4</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
WCF 4.0 incorporates the features previously only obtainable via the REST Starter
kit for .NET 3.5.  Among the features included is the ability to cache REST requests
using a similar technique to caching ASP.NET pages.
</p>
        <p>
The 4.0 version of the <strong>System.ServiceModel.Web</strong> assembly includes
an attribute called <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.web.aspnetcacheprofileattribute.aspx" target="_blank">AspNetCacheProfile</a> which
takes a string as an argument.  The attribute is to be used on a service contract
operation as follows:
</p>
        <pre class="brush: csharp; ruler: true;">[OperationContract]
[WebGet(UriTemplate = "/{name}/getGreeting.xml",
        BodyStyle = WebMessageBodyStyle.Bare,
        RequestFormat = WebMessageFormat.Xml,
        ResponseFormat = WebMessageFormat.Xml)]
[AspNetCacheProfile("CacheFor10Seconds")]
string GetGreetingXml(string name);
</pre>
        <p>
 
</p>
        <p>
The string points to a cache profile to be defined in the <strong><system.web></system.web></strong>config section as follows:
</p>
        <pre class="brush: xml; ruler: true;">
          <caching>
            <outputcachesettings>
              <outputcacheprofiles>
                <add varybyparam="format" duration="10" name="CacheFor10Seconds" />
              </outputcacheprofiles>
            </outputcachesettings>
          </caching>
        </pre>
        <p>
 
</p>
        <p>
As you can see, this is pretty much identical to setting up cache profiles for ASPX
pages.  The effect is pretty much what you would expect, the caching of a REST
request.  This can be proven and tested by implementing the above contract as
such:
</p>
        <pre class="brush: csharp; ruler: true;">public string GetGreetingXml(string name)
{
    return string.Format("Hello {0}.  The time is {1}", name, DateTime.Now.ToLongTimeString());
}
</pre>
        <p>
 
</p>
        <p>
Now you can refresh the request and you’ll see the same time for 10 seconds before
it changes; once again, the same effect as in caching an ASPX page.
</p>
        <p>
So what did I learn the hard way you ask?  Well, common sense dictates that the
request go through ASP.NET in order to use its caching capability.  This not
only means that you have to host in IIS or WAS, but also that you need to turn on
ASP.NET compatibility mode.  This shifts the processing of the REST request over
to an HTTP handler that also sets an HTTP Context for you, something not normally
done with conventional IIS hosting for REST services.  To turn this on, you must
enable it in the <strong><servicehostingenvironment></servicehostingenvironment></strong>section under the <strong><system.servicemodel></system.servicemodel></strong>section using the <strong>aspNetCompatibilityEnabled</strong> attribute. 
Not only that, but you have to “allow” it on the service using the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.activation.aspnetcompatibilityrequirementsattribute.aspx" target="_blank">AspNetCompatibilityRequirements</a> attribute.
</p>
        <p>
This part was not a surprise for me since I was already familiar with this technique
and the added scope your service receives because it.  I’m referring to the entire
HTTP Context including session, application, cache, etc.  Keep in mind that this
is not for everything and should be used in very specific scenarios as it ties the
service to the hosting style quite tightly.
</p>
        <p>
What drove me crazy is something I’m surprised I did not notice in the past and that
is the fact that your REST requests will not work while using the Visual Studio development
server.  Meaning you need to create an application in IIS and run it that way. 
No big deal but it drove me a little crazy since the meta data exposure worked fine,
and so did the new HTML Help pages (another new feature in WCF 4.0 For REST). 
But the second I tried to request one of my URLs, it bombed out.  Once I set
up my application under IIS, everything was fine.
</p>
        <p>
I have to give credit where it’s due and thank Jon Flanders.  I found the answer
in his book <a href="http://www.amazon.com/RESTful-NET-Build-Consume-Services/dp/0596519206/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1274734177&amp;sr=1-1" target="_blank">Restful
.NET</a> from O’Reilly press.
</p>
        <h3>
          <em>Until next time…</em>
        </h3>
        <img width="0" height="0" src="http://www.dotnetdude.com/aggbug.ashx?id=6f2ef28b-fbd6-4f3c-b978-b999b4c230c4" />
      </body>
      <title>What I learned the hard way about WCF REST Services Caching</title>
      <guid isPermaLink="false">http://www.dotnetdude.com/PermaLink,guid,6f2ef28b-fbd6-4f3c-b978-b999b4c230c4.aspx</guid>
      <link>http://www.dotnetdude.com/2010/05/24/WhatILearnedTheHardWayAboutWCFRESTServicesCaching.aspx</link>
      <pubDate>Mon, 24 May 2010 20:50:14 GMT</pubDate>
      <description>&lt;p&gt;
WCF 4.0 incorporates the features previously only obtainable via the REST Starter
kit for .NET 3.5.&amp;nbsp; Among the features included is the ability to cache REST requests
using a similar technique to caching ASP.NET pages.
&lt;/p&gt;
&lt;p&gt;
The 4.0 version of the &lt;strong&gt;System.ServiceModel.Web&lt;/strong&gt; assembly includes
an attribute called &lt;a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.web.aspnetcacheprofileattribute.aspx" target="_blank"&gt;AspNetCacheProfile&lt;/a&gt; which
takes a string as an argument.&amp;nbsp; The attribute is to be used on a service contract
operation as follows:
&lt;/p&gt;
&lt;pre class="brush: csharp; ruler: true;"&gt;[OperationContract]
[WebGet(UriTemplate = "/{name}/getGreeting.xml",
        BodyStyle = WebMessageBodyStyle.Bare,
        RequestFormat = WebMessageFormat.Xml,
        ResponseFormat = WebMessageFormat.Xml)]
[AspNetCacheProfile("CacheFor10Seconds")]
string GetGreetingXml(string name);
&lt;/pre&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
The string points to a cache profile to be defined in the &lt;strong&gt;
&lt;system.web&gt;
&lt;/strong&gt;config section as follows:
&lt;/p&gt;
&lt;pre class="brush: xml; ruler: true;"&gt;
&lt;caching&gt;
&lt;outputcachesettings&gt;
&lt;outputcacheprofiles&gt;
&lt;add varybyparam="format" duration="10" name="CacheFor10Seconds" /&gt;
&lt;/outputcacheprofiles&gt;
&lt;/outputcachesettings&gt;
&lt;/caching&gt;
&lt;/pre&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
As you can see, this is pretty much identical to setting up cache profiles for ASPX
pages.&amp;nbsp; The effect is pretty much what you would expect, the caching of a REST
request.&amp;nbsp; This can be proven and tested by implementing the above contract as
such:
&lt;/p&gt;
&lt;pre class="brush: csharp; ruler: true;"&gt;public string GetGreetingXml(string name)
{
    return string.Format("Hello {0}.  The time is {1}", name, DateTime.Now.ToLongTimeString());
}
&lt;/pre&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
Now you can refresh the request and you’ll see the same time for 10 seconds before
it changes; once again, the same effect as in caching an ASPX page.
&lt;/p&gt;
&lt;p&gt;
So what did I learn the hard way you ask?&amp;nbsp; Well, common sense dictates that the
request go through ASP.NET in order to use its caching capability.&amp;nbsp; This not
only means that you have to host in IIS or WAS, but also that you need to turn on
ASP.NET compatibility mode.&amp;nbsp; This shifts the processing of the REST request over
to an HTTP handler that also sets an HTTP Context for you, something not normally
done with conventional IIS hosting for REST services.&amp;nbsp; To turn this on, you must
enable it in the &lt;strong&gt;
&lt;servicehostingenvironment&gt;
&lt;/strong&gt;section under the &lt;strong&gt;
&lt;system.servicemodel&gt;
&lt;/strong&gt;section using the &lt;strong&gt;aspNetCompatibilityEnabled&lt;/strong&gt; attribute.&amp;nbsp;
Not only that, but you have to “allow” it on the service using the &lt;a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.activation.aspnetcompatibilityrequirementsattribute.aspx" target="_blank"&gt;AspNetCompatibilityRequirements&lt;/a&gt; attribute.
&lt;/p&gt;
&lt;p&gt;
This part was not a surprise for me since I was already familiar with this technique
and the added scope your service receives because it.&amp;nbsp; I’m referring to the entire
HTTP Context including session, application, cache, etc.&amp;nbsp; Keep in mind that this
is not for everything and should be used in very specific scenarios as it ties the
service to the hosting style quite tightly.
&lt;/p&gt;
&lt;p&gt;
What drove me crazy is something I’m surprised I did not notice in the past and that
is the fact that your REST requests will not work while using the Visual Studio development
server.&amp;nbsp; Meaning you need to create an application in IIS and run it that way.&amp;nbsp;
No big deal but it drove me a little crazy since the meta data exposure worked fine,
and so did the new HTML Help pages (another new feature in WCF 4.0 For REST).&amp;nbsp;
But the second I tried to request one of my URLs, it bombed out.&amp;nbsp; Once I set
up my application under IIS, everything was fine.
&lt;/p&gt;
&lt;p&gt;
I have to give credit where it’s due and thank Jon Flanders.&amp;nbsp; I found the answer
in his book &lt;a href="http://www.amazon.com/RESTful-NET-Build-Consume-Services/dp/0596519206/ref=sr_1_1?ie=UTF8&amp;amp;s=books&amp;amp;qid=1274734177&amp;amp;sr=1-1" target="_blank"&gt;Restful
.NET&lt;/a&gt; from O’Reilly press.
&lt;/p&gt;
&lt;h3&gt;&lt;em&gt;Until next time…&lt;/em&gt;
&lt;/h3&gt;
&lt;img width="0" height="0" src="http://www.dotnetdude.com/aggbug.ashx?id=6f2ef28b-fbd6-4f3c-b978-b999b4c230c4" /&gt;</description>
      <comments>http://www.dotnetdude.com/CommentView,guid,6f2ef28b-fbd6-4f3c-b978-b999b4c230c4.aspx</comments>
      <category>Dev Stuff</category>
      <category>WCF</category>
    </item>
    <item>
      <trackback:ping>http://www.dotnetdude.com/Trackback.aspx?guid=6ddef1f4-fe6a-4e1e-b207-3af8bf4290dc</trackback:ping>
      <pingback:server>http://www.dotnetdude.com/pingback.aspx</pingback:server>
      <pingback:target>http://www.dotnetdude.com/PermaLink,guid,6ddef1f4-fe6a-4e1e-b207-3af8bf4290dc.aspx</pingback:target>
      <dc:creator>Miguel A. Castro</dc:creator>
      <wfw:comment>http://www.dotnetdude.com/CommentView,guid,6ddef1f4-fe6a-4e1e-b207-3af8bf4290dc.aspx</wfw:comment>
      <wfw:commentRss>http://www.dotnetdude.com/SyndicationService.asmx/GetEntryCommentsRss?guid=6ddef1f4-fe6a-4e1e-b207-3af8bf4290dc</wfw:commentRss>
      <title>NYC WCF Firestarter – Saturday June 19, 2010</title>
      <guid isPermaLink="false">http://www.dotnetdude.com/PermaLink,guid,6ddef1f4-fe6a-4e1e-b207-3af8bf4290dc.aspx</guid>
      <link>http://www.dotnetdude.com/2010/05/18/NYCWCFFirestarterSaturdayJune192010.aspx</link>
      <pubDate>Tue, 18 May 2010 20:25:36 GMT</pubDate>
      <description>&lt;p&gt;
&lt;a href="https://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032452076&amp;Culture=en-US"&gt;&lt;img style="display: block; float: none; margin-left: auto; margin-right: auto" title="WCFFirestarterNYC" border="0" alt="WCFFirestarterNYC" src="http://blogs.msdn.com/blogfiles/peterlau/WindowsLiveWriter/NYCWCFFirestarterSaturdayJune192010_E10F/WCFFirestarterNYC_1.png" width="737" height="76"&gt;&lt;/a&gt;
&lt;br&gt;
&lt;/p&gt;
&lt;p&gt;
Stop starting new projects with ASMX Web Services or .NET Remoting! OK, now that we
have your attention, let’s get serious. These two
&lt;/p&gt;
&lt;p&gt;
technologies are so 2002! You need to start learning Windows Communication Foundation
(WCF) if you haven't already. This is &lt;i&gt;the &lt;/i&gt;platform for connected applications
on the Windows platform going forward, and you know what? It's easier to use than
you may think. 
&lt;p&gt;
Even if you've been tinkering with writing basic services in WCF for a while but haven't
dived into anything more advanced, you should come in for the &lt;a href="https://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032452076&amp;Culture=en-US"&gt;NYC
WCF Firestarter&lt;/a&gt;. 
&lt;p&gt;
Join us for a full day of nothing but WCF sessions. Ranging from an introductory so
you can hit the ground running, and with best practices, continuing with topics involving
the most important features of WCF, and ending with some cutting edge material on
REST &amp; Microsoft's new service bus and Azure technology in .NET 4.0. 
&lt;p&gt;
We’ve got a great line up of speakers! Presenting at the &lt;a href="https://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032452076&amp;Culture=en-US"&gt;NYC
WCF Firestarter&lt;/a&gt; will be &lt;a href="http://dotnetdude.com/"&gt;Miguel Castro&lt;/a&gt;, &lt;a href="http://www.donxml.com"&gt;Don
Demsak&lt;/a&gt;, and myself (&lt;a href="http://www.peterlaudati.com"&gt;Peter Laudati&lt;/a&gt;). 
&lt;p&gt;
&lt;a href="http://www.bing.com/maps/default.aspx?v=2&amp;cp=40.76059~-73.97855&amp;lvl=15&amp;style=r&amp;sp=aN.40.76085_-73.9794_Microsoft%2520NYC%2520Office_1290%2520Ave%2520Of%2520The%2520Americas&amp;mkt=en-us&amp;FORM=LLWR"&gt;&lt;img style="display: inline; margin-left: 0px; margin-right: 0px" alt="Microsoft NYC Office - 1290 Ave of the Americas - 6th Floor" align="right" src="http://blogs.msdn.com/blogfiles/peterlau/WindowsLiveWriter/NYCWCFFirestarterSaturdayJune192010_E10F/map-8028836e8932.jpg" width="320" height="240"&gt;&lt;/a&gt;
&lt;br&gt;
Microsoft NYC Office - 1290 Ave of the Americas - 6th Floor 
&lt;h5&gt;Event Details
&lt;/h5&gt;
&lt;p&gt;
&lt;strong&gt;Event Date:&lt;/strong&gt; Saturday June 19&lt;sup&gt;th&lt;/sup&gt;, 2010 
&lt;p&gt;
&lt;b&gt;Event Location:&lt;/b&gt; 
&lt;p&gt;
Microsoft NYC Offices&lt;br&gt;
1290 Ave of the Americas 6&lt;sup&gt;th&lt;/sup&gt; Floor&lt;br&gt;
New York, NY 10104 
&lt;h3&gt;&lt;a href="https://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032452076&amp;Culture=en-US"&gt;REGISTER
HERE!&lt;/a&gt;
&lt;/h3&gt;
&lt;h5&gt;Event Agenda
&lt;/h5&gt;
&lt;p&gt;
Doors open 8:30am. Sessions run from 9:00am – 5:00pm. Lunch will be served. 
&lt;ul&gt;
&lt;li&gt;
Session 1: Keynote – Intro to SOA &amp; WCF 
&lt;li&gt;
Session 2: Most Common WCF Usage Scenarios 
&lt;li&gt;
LUNCH 
&lt;li&gt;
Session 3: REST Programming with WCF 
&lt;li&gt;
Session 4: WCF Made Easy – Data &amp; RIA Services 
&lt;li&gt;
Session 5: What’s New With WCF 4.0&lt;/li&gt;
&lt;/ul&gt;
&lt;h5&gt;Session Details
&lt;/h5&gt;
&lt;blockquote&gt; 
&lt;p&gt;
&lt;b&gt;Intro to SOA &amp; WCF&lt;/b&gt; 
&lt;p&gt;
Jump right in to understanding what service orientation is and how WCF is the preferred
technology for this architecture. You'll see how services get written in WCF from
scratch and using best practices from the beginning. 
&lt;p&gt;
&lt;b&gt;Most Common WCF Usage Configurations&lt;/b&gt; 
&lt;p&gt;
WCF has many characteristics, each with several options. There are however some optimal
settings for the most common scenarios. In this session you'll learn the whys and
hows for configuring WCF services to work optimally in the areas of instantiation,
concurrency, transactions, security, and bindings. 
&lt;p&gt;
&lt;b&gt;REST Programming With WCF&lt;/b&gt; 
&lt;p&gt;
With .NET 3.5 came the addition of the System.Service.Web assembly and the addition
of REST capabilities to WCF. REST is an HTTP-based messaging protocol that is common
in web applications today and even more common in non-.NET services that expose API
(think Twitter &amp; Google). In this session, you'll learn how to expose your services
using REST and also how to consume non-.NET REST APIs using WCF. 
&lt;p&gt;
&lt;b&gt;WCF Made Easy - Data &amp; RIA Services&lt;/b&gt; 
&lt;p&gt;
You have seen all the various ways you can leverage WCF, but what if all you want
to do is expose your data via HTTP? In that case, you can simplify your development,
by using WCF Data Services or WCF RIA Services. In this session we will learn how
to easily expose your data using Entity Framework in a RESTful fashion using WCF Data
Services, how to consume WCF Data Services, and then dive into WCF RIA Services.&lt;br&gt;
&lt;b&gt;
&lt;br&gt;
What's New With WCF 4.0&lt;/b&gt; 
&lt;p&gt;
No Day-Of-WCF would be complete without letting you know what's new with .NET 4.0
and Visual Studio 2010. This session will give you a heads up on several new and powerful
features introduced in WCF 4.0. Among these are "Configuration-less Hosting", "Discovery",
"Routing", and an intro to the new Azure Service Bus.
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;h5&gt;Swag &amp; Prizes
&lt;/h5&gt;
&lt;p&gt;
We hope you come to attend the &lt;a href="https://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032452076&amp;Culture=en-US"&gt;NYC
WCF Firestarter&lt;/a&gt; for the unique content, providing a FREE opportunity to advance
your skills by learning a new technology. However, like many events, we’ll have some
fun stuff to giveaway at the end. If you stick around, you will have the chance TO
BE THE LUCKY WINNER OF A MICROSOFT ZUNE! YOU MUST BE PRESENT TO WIN. &lt;img width="0" height="0" src="http://www.dotnetdude.com/aggbug.ashx?id=6ddef1f4-fe6a-4e1e-b207-3af8bf4290dc" /&gt;</description>
      <comments>http://www.dotnetdude.com/CommentView,guid,6ddef1f4-fe6a-4e1e-b207-3af8bf4290dc.aspx</comments>
      <category>Speaking Events</category>
      <category>WCF</category>
    </item>
  </channel>
</rss>