<?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:wfw="http://wellformedweb.org/CommentAPI/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" version="2.0">
  <channel>
    <title>Samurai Programmer.com - .NET 4</title>
    <link>http://www.samuraiprogrammer.com/blog/</link>
    <description>I know kung fu</description>
    <language>en-us</language>
    <copyright>Greg Varveris</copyright>
    <lastBuildDate>Sat, 19 Nov 2011 13:45:14 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.3.9074.18820</generator>
    <managingEditor>greg@samuraiprogrammer.com</managingEditor>
    <webMaster>greg@samuraiprogrammer.com</webMaster>
    <item>
      <trackback:ping>http://www.samuraiprogrammer.com/blog/Trackback.aspx?guid=640974ce-fd96-4cad-bcd0-6c45ed248018</trackback:ping>
      <pingback:server>http://www.samuraiprogrammer.com/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.samuraiprogrammer.com/blog/PermaLink,guid,640974ce-fd96-4cad-bcd0-6c45ed248018.aspx</pingback:target>
      <dc:creator>Greg Varveris</dc:creator>
      <wfw:comment>http://www.samuraiprogrammer.com/blog/CommentView,guid,640974ce-fd96-4cad-bcd0-6c45ed248018.aspx</wfw:comment>
      <wfw:commentRss>http://www.samuraiprogrammer.com/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=640974ce-fd96-4cad-bcd0-6c45ed248018</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
So in a code-base I was working in yesterday, we use PInvoke to call out to the Performance
Data Helper (PDH) API’s to collect performance information for machines without using
Perfmon.  One of those PInvoke calls looked like this:
</p>
        <pre class="c#" name="code">/*<br />
PDH_STATUS PdhExpandCounterPath(<br />
LPCTSTR szWildCardPath,<br />
LPTSTR mszExpandedPathList,<br />
LPDWORD pcchPathListLength<br />
);<br />
*/<br />
[DllImport("pdh.dll", CharSet = CharSet.Unicode)]<br />
private static extern PdhStatus PdhExpandCounterPath(<br />
string szWildCardPath,<br />
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] char[] mszExpandedPathList,<br />
ref uint pcchPathListLength<br />
);</pre>
        <p>
In .NET 3.5 and below, this PInvoke call works perfectly fine.  In .NET 4.0,
though, I saw this exception:
</p>
        <pre>System.Runtime.InteropServices.MarshalDirectiveException: 
<br />
Cannot marshal 'parameter #2': Array size control parameter index is out of range. 
<br />
at System.Runtime.InteropServices.Marshal.InternalPrelink(IRuntimeMethodInfo m) 
<br />
at System.Runtime.InteropServices.Marshal.Prelink(MethodInfo m)</pre>
        <p>
So, can you identify what’s wrong in the code above?
</p>
        <p>
Well, the Array size control parameter index indicates the zero-based parameter that
contains the count of the array elements, similar to size_is in COM.  Because
the marshaler cannot determine the size of an unmanaged array, you have to pass it
in as a separate parameter.  So in the call above, parameter #2, we specify “SizeParamIndex
= 3” to reference the pcchPathListLength parameter to set the length of the array. 
So what’s the catch?
</p>
        <p>
Well, since the SizeParamIndex is a zero-based index, the 3rd parameter doesn’t really
exist.  So, to fix this, we just change the “SizeParamIndex=3” to “SizeParamIndex=2”
to reference the pcchPathListLength:
</p>
        <pre class="c#" name="code">/*<br />
PDH_STATUS PdhExpandCounterPath(<br />
LPCTSTR szWildCardPath,<br />
LPTSTR mszExpandedPathList,<br />
LPDWORD pcchPathListLength<br />
);<br />
*/<br />
[DllImport("pdh.dll", CharSet = CharSet.Unicode)]<br />
private static extern PdhStatus PdhExpandCounterPath(<br />
string szWildCardPath,<br />
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] char[] mszExpandedPathList,<br />
ref uint pcchPathListLength<br />
);</pre>
        <p>
It looks like in .NET 3.5 and below, though, we allowed you to reference either 1-based
index or a zero-based index but in .NET 4.0, we buttoned that up a bit and force you
to use the zero-based index.    Big thanks to my co-worker and frequent
collaborator, <a href="http://blogs.msdn.com/b/pfedev/" target="_blank">Zach Kramer</a> for
his assistance in looking at this issue.
</p>
        <p>
Until Next Time!
</p>
      </body>
      <title>PInvoke Error in .NET 4: Array size control parameter index is out of range</title>
      <guid isPermaLink="false">http://www.samuraiprogrammer.com/blog/PermaLink,guid,640974ce-fd96-4cad-bcd0-6c45ed248018.aspx</guid>
      <link>http://www.samuraiprogrammer.com/blog/2011/11/19/PInvokeErrorInNET4ArraySizeControlParameterIndexIsOutOfRange.aspx</link>
      <pubDate>Sat, 19 Nov 2011 13:45:14 GMT</pubDate>
      <description>&lt;p&gt;
So in a code-base I was working in yesterday, we use PInvoke to call out to the Performance
Data Helper (PDH) API’s to collect performance information for machines without using
Perfmon.&amp;#160; One of those PInvoke calls looked like this:
&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;/*&lt;br /&gt;
PDH_STATUS PdhExpandCounterPath(&lt;br /&gt;
LPCTSTR szWildCardPath,&lt;br /&gt;
LPTSTR mszExpandedPathList,&lt;br /&gt;
LPDWORD pcchPathListLength&lt;br /&gt;
);&lt;br /&gt;
*/&lt;br /&gt;
[DllImport(&amp;quot;pdh.dll&amp;quot;, CharSet = CharSet.Unicode)]&lt;br /&gt;
private static extern PdhStatus PdhExpandCounterPath(&lt;br /&gt;
string szWildCardPath,&lt;br /&gt;
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] char[] mszExpandedPathList,&lt;br /&gt;
ref uint pcchPathListLength&lt;br /&gt;
);&lt;/pre&gt;
&lt;p&gt;
In .NET 3.5 and below, this PInvoke call works perfectly fine.&amp;#160; In .NET 4.0,
though, I saw this exception:
&lt;/p&gt;
&lt;pre&gt;System.Runtime.InteropServices.MarshalDirectiveException: 
&lt;br /&gt;
Cannot marshal 'parameter #2': Array size control parameter index is out of range. 
&lt;br /&gt;
at System.Runtime.InteropServices.Marshal.InternalPrelink(IRuntimeMethodInfo m) 
&lt;br /&gt;
at System.Runtime.InteropServices.Marshal.Prelink(MethodInfo m)&lt;/pre&gt;
&lt;p&gt;
So, can you identify what’s wrong in the code above?
&lt;/p&gt;
&lt;p&gt;
Well, the Array size control parameter index indicates the zero-based parameter that
contains the count of the array elements, similar to size_is in COM.&amp;#160; Because
the marshaler cannot determine the size of an unmanaged array, you have to pass it
in as a separate parameter.&amp;#160; So in the call above, parameter #2, we specify “SizeParamIndex
= 3” to reference the pcchPathListLength parameter to set the length of the array.&amp;#160;
So what’s the catch?
&lt;/p&gt;
&lt;p&gt;
Well, since the SizeParamIndex is a zero-based index, the 3rd parameter doesn’t really
exist.&amp;#160; So, to fix this, we just change the “SizeParamIndex=3” to “SizeParamIndex=2”
to reference the pcchPathListLength:
&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;/*&lt;br /&gt;
PDH_STATUS PdhExpandCounterPath(&lt;br /&gt;
LPCTSTR szWildCardPath,&lt;br /&gt;
LPTSTR mszExpandedPathList,&lt;br /&gt;
LPDWORD pcchPathListLength&lt;br /&gt;
);&lt;br /&gt;
*/&lt;br /&gt;
[DllImport(&amp;quot;pdh.dll&amp;quot;, CharSet = CharSet.Unicode)]&lt;br /&gt;
private static extern PdhStatus PdhExpandCounterPath(&lt;br /&gt;
string szWildCardPath,&lt;br /&gt;
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] char[] mszExpandedPathList,&lt;br /&gt;
ref uint pcchPathListLength&lt;br /&gt;
);&lt;/pre&gt;
&lt;p&gt;
It looks like in .NET 3.5 and below, though, we allowed you to reference either 1-based
index or a zero-based index but in .NET 4.0, we buttoned that up a bit and force you
to use the zero-based index.&amp;#160;&amp;#160;&amp;#160; Big thanks to my co-worker and frequent
collaborator, &lt;a href="http://blogs.msdn.com/b/pfedev/" target="_blank"&gt;Zach Kramer&lt;/a&gt; for
his assistance in looking at this issue.
&lt;/p&gt;
&lt;p&gt;
Until Next Time!
&lt;/p&gt;</description>
      <comments>http://www.samuraiprogrammer.com/blog/CommentView,guid,640974ce-fd96-4cad-bcd0-6c45ed248018.aspx</comments>
      <category>.NET 4</category>
      <category>Perfmon</category>
      <category>Performance</category>
    </item>
    <item>
      <trackback:ping>http://www.samuraiprogrammer.com/blog/Trackback.aspx?guid=90aee052-b425-4e42-82ee-2b736c506e39</trackback:ping>
      <pingback:server>http://www.samuraiprogrammer.com/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.samuraiprogrammer.com/blog/PermaLink,guid,90aee052-b425-4e42-82ee-2b736c506e39.aspx</pingback:target>
      <dc:creator>Greg Varveris</dc:creator>
      <wfw:comment>http://www.samuraiprogrammer.com/blog/CommentView,guid,90aee052-b425-4e42-82ee-2b736c506e39.aspx</wfw:comment>
      <wfw:commentRss>http://www.samuraiprogrammer.com/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=90aee052-b425-4e42-82ee-2b736c506e39</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="http://www.hanselman.com/blog/BackToParallelBasicsDontBlockYourThreadsMakeAsyncIOWorkForYou.aspx">Read
a great blog entry by Scott Hanselman</a> recently talking about the parallel dilemma
that I’m sure we’ll see folks face in the future with the (old/new) Parallel classes. 
I wanted to add a few things to this discussion as he focused on the mechanics of
the parallel requests but maybe not the potential effects it could have on the macro
view of your application.  This was originally written as an e-mail I sent to
my team but thought others might find it interesting.
</p>
        <p>
There will be an inclination by people to use the new Parallel functionality in .NET
4.0 to easily spawn operations onto numerous background threads.  That will generally
be okay for console/winform/wpf apps – but could also be potentially bad for ASP.NET
apps as the spawned threads could take away from the processing power and threads
available to process new webpage requests.  I’ll explain more on that later.  
</p>
        <p>
For example, by default, when you do something like Parallel.ForEach(…) or some such,
the parallel library starts firing Tasks to the thread pool so that it can best utilize
the processing power available on your machine (oversimplification but you get the
idea).  The downside is that the thread pool contains a finite number of worker
threads threads available to a process.  Granted, you have about 100 threads
per logical processor in .NET 4 – but it’s worth noting.
</p>
        <p>
While Scott’s entry talks about the new way to implement the Async pattern, I’ve already
seen a bunch of folks use the “Parallel” class because it abstracts away some of the
plumbing of the Async operations and that ease of use could become problematic.  
</p>
        <p>
For example, consider this code:
</p>
        <pre class="c#" name="code">string[] myStrings = { "hello", "world", "you", "crazy", "pfes", "out", "there" };<br /><br />
Parallel.ForEach(myStrings, myString =&gt;<br />
{<br /><br />
System.Console.WriteLine(DateTime.Now + ":" + myString + 
<br />
" - From Thread #" + 
<br />
Thread.CurrentThread.ManagedThreadId);<br />
Thread.Sleep(new Random().Next(1000, 5000));<br /><br />
});<br /></pre>
        <p>
This is a very simple implementation of Parallel’izing a foreach that just writes
some string output with an artificial delay.  Output would be something like:
</p>
        <blockquote>
          <p>
11/16/2010 2:40:05 AM:hello - From Thread #10 
<br />
11/16/2010 2:40:05 AM:crazy - From Thread #11 
<br />
11/16/2010 2:40:05 AM:there - From Thread #12 
<br />
11/16/2010 2:40:06 AM:world - From Thread #13 
<br />
11/16/2010 2:40:06 AM:pfes - From Thread #14 
<br />
11/16/2010 2:40:06 AM:you - From Thread #12 
<br />
11/16/2010 2:40:07 AM:out - From Thread #11  
</p>
        </blockquote>
        <p>
Note the multiple thread ids and extrapolate that out to a server that has more than
just my paltry 2 CPUs.  This can be potentially problematic for ASP.NET applications
as you have a finite number of worker threads available in your worker process and
they must be shared across not just one user but hundreds (or even thousands). 
So, we might see that spawning an operation across tons of threads can potentially
reduce the scalability of your site.
</p>
        <p>
Fortunately, there is a ParallelOptions class where you can set the degree of parallel’ism. 
Updated code as follows:
</p>
        <pre class="c#" name="code">string[] myStrings = { "hello", "world", "you", "crazy", "pfes", "out", "there" };<br /><br />
ParallelOptions options = new ParallelOptions();<br />
options.MaxDegreeOfParallelism = 1;<br /><br />
Parallel.ForEach(myStrings,options, myString =&gt;<br />
{<br /><br />
// Nothing changes here<br />
...<br /><br />
});<br /></pre>
        <p>
This would then output something like:
</p>
        <blockquote>
          <p>
11/16/2010 2:40:11 AM:hello - From Thread #10 
<br />
11/16/2010 2:40:12 AM:world - From Thread #10 
<br />
11/16/2010 2:40:16 AM:you - From Thread #10 
<br />
11/16/2010 2:40:20 AM:crazy - From Thread #10 
<br />
11/16/2010 2:40:23 AM:pfes - From Thread #10 
<br />
11/16/2010 2:40:26 AM:out - From Thread #10 
<br />
11/16/2010 2:40:29 AM:there - From Thread #10
</p>
        </blockquote>
        <p>
Since I set the MaxDegreeOfParallelism to “1”, we see that it just uses the same thread
over and over.  Within reason, that setting *should* correspond to the number
of threads it will use to handle the request.  
</p>
        <h2>Applying to a website
</h2>
        <p>
So, let’s apply the code from the above to a simple website and compare the difference
between the full parallel implementation and the non-parallel implementation. 
The test I used ran for 10 minutes with a consistent load of 20 users on a dual-core
machine running IIS 7. <strong><em></em></strong></p>
        <p>
          <strong>
            <em>In all of the images below, the blue line (or baseline) represents the
single-threaded implementation and the purple line (or compared) represents the parallel
implementation</em>
          </strong>.  
</p>
        <p>
We’ll start with the <strong>request execution time</strong>.  As we’d expect,
the time to complete the request decreases significantly with the parallel implementation.
</p>
        <p>
          <a href="http://www.samuraiprogrammer.com/blog/content/binary/Windows-Live-Writer/df4a939434b1_CB17/__GREGVAR-PC_ASP_NETv4_0_30319_RequestExecutionTime_2.gif">
            <img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="__GREGVAR-PC_ASP_NETv4_0_30319_RequestExecutionTime" border="0" alt="__GREGVAR-PC_ASP_NETv4_0_30319_RequestExecutionTime" src="http://www.samuraiprogrammer.com/blog/content/binary/Windows-Live-Writer/df4a939434b1_CB17/__GREGVAR-PC_ASP_NETv4_0_30319_RequestExecutionTime_thumb.gif" width="484" height="364" />
          </a>
        </p>
        <p>
But what is the cost from a thread perspective?  For that, we’ll look at the <strong>number
of physical threads</strong>: 
</p>
        <p>
          <a href="http://www.samuraiprogrammer.com/blog/content/binary/Windows-Live-Writer/df4a939434b1_CB17/__GREGVAR-PC__NETCLRLocksAndThreads_w3wp__NumofcurrentphysicalThreads_2.gif">
            <img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="__GREGVAR-PC__NETCLRLocksAndThreads_w3wp__NumofcurrentphysicalThreads" border="0" alt="__GREGVAR-PC__NETCLRLocksAndThreads_w3wp__NumofcurrentphysicalThreads" src="http://www.samuraiprogrammer.com/blog/content/binary/Windows-Live-Writer/df4a939434b1_CB17/__GREGVAR-PC__NETCLRLocksAndThreads_w3wp__NumofcurrentphysicalThreads_thumb.gif" width="484" height="364" />
          </a>
        </p>
        <p>
As we’d also expect, there is a significant increase in the number of threads used
in the process.  We go from ~20 threads in the process to a peak of almost 200
threads throughout the test.  Seeing as this was run on a dual-core machine,
we’ll have a maximum of 200 worker threads available in the thread pool.  After
those threads become depleted, you often see requests start getting queued, waiting
for a thread to become available.  So, what happened in our simple test? 
We’re look at the <strong>requests queued</strong> value for that:
</p>
        <p>
          <a href="http://www.samuraiprogrammer.com/blog/content/binary/Windows-Live-Writer/df4a939434b1_CB17/__GREGVAR-PC_ASP_NETv4_0_30319_RequestsQueued_2.gif">
            <img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="__GREGVAR-PC_ASP_NETv4_0_30319_RequestsQueued" border="0" alt="__GREGVAR-PC_ASP_NETv4_0_30319_RequestsQueued" src="http://www.samuraiprogrammer.com/blog/content/binary/Windows-Live-Writer/df4a939434b1_CB17/__GREGVAR-PC_ASP_NETv4_0_30319_RequestsQueued_thumb.gif" width="484" height="364" />
          </a>  
</p>
        <p>
We did, in-fact, start to see a small number of requests become queued throughout
our test.  This indicates that some requests started to pile up waiting for an
available thread to become available.  
</p>
        <p>
Please note that I’m <strong>NOT</strong> saying that you should not use Parallel
operations in your website.  <strong>You saw in the first image that the actual
request execution time decreased significantly from the non-parallel implementation
to the parallel implementation.</strong> But it’s important to note that nothing is
free and while parallelizing your work can and will improve the performance of a single
request, it should also be weighed against the potential performance of your site
overall.
</p>
        <p>
Until next time.
</p>
      </body>
      <title>The (potentially) dark side of parallelism…</title>
      <guid isPermaLink="false">http://www.samuraiprogrammer.com/blog/PermaLink,guid,90aee052-b425-4e42-82ee-2b736c506e39.aspx</guid>
      <link>http://www.samuraiprogrammer.com/blog/2010/12/05/ThePotentiallyDarkSideOfParallelism.aspx</link>
      <pubDate>Sun, 05 Dec 2010 18:52:17 GMT</pubDate>
      <description>&lt;p&gt;
&lt;a href="http://www.hanselman.com/blog/BackToParallelBasicsDontBlockYourThreadsMakeAsyncIOWorkForYou.aspx"&gt;Read
a great blog entry by Scott Hanselman&lt;/a&gt; recently talking about the parallel dilemma
that I’m sure we’ll see folks face in the future with the (old/new) Parallel classes.&amp;#160;
I wanted to add a few things to this discussion as he focused on the mechanics of
the parallel requests but maybe not the potential effects it could have on the macro
view of your application.&amp;#160; This was originally written as an e-mail I sent to
my team but thought others might find it interesting.
&lt;/p&gt;
&lt;p&gt;
There will be an inclination by people to use the new Parallel functionality in .NET
4.0 to easily spawn operations onto numerous background threads.&amp;#160; That will generally
be okay for console/winform/wpf apps – but could also be potentially bad for ASP.NET
apps as the spawned threads could take away from the processing power and threads
available to process new webpage requests.&amp;#160; I’ll explain more on that later.&amp;#160; 
&lt;/p&gt;
&lt;p&gt;
For example, by default, when you do something like Parallel.ForEach(…) or some such,
the parallel library starts firing Tasks to the thread pool so that it can best utilize
the processing power available on your machine (oversimplification but you get the
idea).&amp;#160; The downside is that the thread pool contains a finite number of worker
threads threads available to a process.&amp;#160; Granted, you have about 100 threads
per logical processor in .NET 4 – but it’s worth noting.
&lt;/p&gt;
&lt;p&gt;
While Scott’s entry talks about the new way to implement the Async pattern, I’ve already
seen a bunch of folks use the “Parallel” class because it abstracts away some of the
plumbing of the Async operations and that ease of use could become problematic.&amp;#160; 
&lt;/p&gt;
&lt;p&gt;
For example, consider this code:
&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;string[] myStrings = { &amp;quot;hello&amp;quot;, &amp;quot;world&amp;quot;, &amp;quot;you&amp;quot;, &amp;quot;crazy&amp;quot;, &amp;quot;pfes&amp;quot;, &amp;quot;out&amp;quot;, &amp;quot;there&amp;quot; };&lt;br /&gt;
&lt;br /&gt;
Parallel.ForEach(myStrings, myString =&amp;gt;&lt;br /&gt;
{&lt;br /&gt;
&lt;br /&gt;
System.Console.WriteLine(DateTime.Now + &amp;quot;:&amp;quot; + myString + 
&lt;br /&gt;
&amp;quot; - From Thread #&amp;quot; + 
&lt;br /&gt;
Thread.CurrentThread.ManagedThreadId);&lt;br /&gt;
Thread.Sleep(new Random().Next(1000, 5000));&lt;br /&gt;
&lt;br /&gt;
});&lt;br /&gt;
&lt;/pre&gt;
&lt;p&gt;
This is a very simple implementation of Parallel’izing a foreach that just writes
some string output with an artificial delay.&amp;#160; Output would be something like:
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
11/16/2010 2:40:05 AM:hello - From Thread #10 
&lt;br /&gt;
11/16/2010 2:40:05 AM:crazy - From Thread #11 
&lt;br /&gt;
11/16/2010 2:40:05 AM:there - From Thread #12 
&lt;br /&gt;
11/16/2010 2:40:06 AM:world - From Thread #13 
&lt;br /&gt;
11/16/2010 2:40:06 AM:pfes - From Thread #14 
&lt;br /&gt;
11/16/2010 2:40:06 AM:you - From Thread #12 
&lt;br /&gt;
11/16/2010 2:40:07 AM:out - From Thread #11&amp;#160; 
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
Note the multiple thread ids and extrapolate that out to a server that has more than
just my paltry 2 CPUs.&amp;#160; This can be potentially problematic for ASP.NET applications
as you have a finite number of worker threads available in your worker process and
they must be shared across not just one user but hundreds (or even thousands).&amp;#160;
So, we might see that spawning an operation across tons of threads can potentially
reduce the scalability of your site.
&lt;/p&gt;
&lt;p&gt;
Fortunately, there is a ParallelOptions class where you can set the degree of parallel’ism.&amp;#160;
Updated code as follows:
&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;string[] myStrings = { &amp;quot;hello&amp;quot;, &amp;quot;world&amp;quot;, &amp;quot;you&amp;quot;, &amp;quot;crazy&amp;quot;, &amp;quot;pfes&amp;quot;, &amp;quot;out&amp;quot;, &amp;quot;there&amp;quot; };&lt;br /&gt;
&lt;br /&gt;
ParallelOptions options = new ParallelOptions();&lt;br /&gt;
options.MaxDegreeOfParallelism = 1;&lt;br /&gt;
&lt;br /&gt;
Parallel.ForEach(myStrings,options, myString =&amp;gt;&lt;br /&gt;
{&lt;br /&gt;
&lt;br /&gt;
// Nothing changes here&lt;br /&gt;
...&lt;br /&gt;
&lt;br /&gt;
});&lt;br /&gt;
&lt;/pre&gt;
&lt;p&gt;
This would then output something like:
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
11/16/2010 2:40:11 AM:hello - From Thread #10 
&lt;br /&gt;
11/16/2010 2:40:12 AM:world - From Thread #10 
&lt;br /&gt;
11/16/2010 2:40:16 AM:you - From Thread #10 
&lt;br /&gt;
11/16/2010 2:40:20 AM:crazy - From Thread #10 
&lt;br /&gt;
11/16/2010 2:40:23 AM:pfes - From Thread #10 
&lt;br /&gt;
11/16/2010 2:40:26 AM:out - From Thread #10 
&lt;br /&gt;
11/16/2010 2:40:29 AM:there - From Thread #10
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
Since I set the MaxDegreeOfParallelism to “1”, we see that it just uses the same thread
over and over.&amp;#160; Within reason, that setting *should* correspond to the number
of threads it will use to handle the request.&amp;#160; 
&lt;/p&gt;
&lt;h2&gt;Applying to a website
&lt;/h2&gt;
&lt;p&gt;
So, let’s apply the code from the above to a simple website and compare the difference
between the full parallel implementation and the non-parallel implementation.&amp;#160;
The test I used ran for 10 minutes with a consistent load of 20 users on a dual-core
machine running IIS 7. &lt;strong&gt;&lt;em&gt;&lt;/em&gt;&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;&lt;em&gt;In all of the images below, the blue line (or baseline) represents the
single-threaded implementation and the purple line (or compared) represents the parallel
implementation&lt;/em&gt;&lt;/strong&gt;.&amp;#160; 
&lt;/p&gt;
&lt;p&gt;
We’ll start with the &lt;strong&gt;request execution time&lt;/strong&gt;.&amp;#160; As we’d expect,
the time to complete the request decreases significantly with the parallel implementation.
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.samuraiprogrammer.com/blog/content/binary/Windows-Live-Writer/df4a939434b1_CB17/__GREGVAR-PC_ASP_NETv4_0_30319_RequestExecutionTime_2.gif"&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="__GREGVAR-PC_ASP_NETv4_0_30319_RequestExecutionTime" border="0" alt="__GREGVAR-PC_ASP_NETv4_0_30319_RequestExecutionTime" src="http://www.samuraiprogrammer.com/blog/content/binary/Windows-Live-Writer/df4a939434b1_CB17/__GREGVAR-PC_ASP_NETv4_0_30319_RequestExecutionTime_thumb.gif" width="484" height="364" /&gt;&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
But what is the cost from a thread perspective?&amp;#160; For that, we’ll look at the &lt;strong&gt;number
of physical threads&lt;/strong&gt;: 
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.samuraiprogrammer.com/blog/content/binary/Windows-Live-Writer/df4a939434b1_CB17/__GREGVAR-PC__NETCLRLocksAndThreads_w3wp__NumofcurrentphysicalThreads_2.gif"&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="__GREGVAR-PC__NETCLRLocksAndThreads_w3wp__NumofcurrentphysicalThreads" border="0" alt="__GREGVAR-PC__NETCLRLocksAndThreads_w3wp__NumofcurrentphysicalThreads" src="http://www.samuraiprogrammer.com/blog/content/binary/Windows-Live-Writer/df4a939434b1_CB17/__GREGVAR-PC__NETCLRLocksAndThreads_w3wp__NumofcurrentphysicalThreads_thumb.gif" width="484" height="364" /&gt;&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
As we’d also expect, there is a significant increase in the number of threads used
in the process.&amp;#160; We go from ~20 threads in the process to a peak of almost 200
threads throughout the test.&amp;#160; Seeing as this was run on a dual-core machine,
we’ll have a maximum of 200 worker threads available in the thread pool.&amp;#160; After
those threads become depleted, you often see requests start getting queued, waiting
for a thread to become available.&amp;#160; So, what happened in our simple test?&amp;#160;
We’re look at the &lt;strong&gt;requests queued&lt;/strong&gt; value for that:
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.samuraiprogrammer.com/blog/content/binary/Windows-Live-Writer/df4a939434b1_CB17/__GREGVAR-PC_ASP_NETv4_0_30319_RequestsQueued_2.gif"&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="__GREGVAR-PC_ASP_NETv4_0_30319_RequestsQueued" border="0" alt="__GREGVAR-PC_ASP_NETv4_0_30319_RequestsQueued" src="http://www.samuraiprogrammer.com/blog/content/binary/Windows-Live-Writer/df4a939434b1_CB17/__GREGVAR-PC_ASP_NETv4_0_30319_RequestsQueued_thumb.gif" width="484" height="364" /&gt;&lt;/a&gt;&amp;#160; 
&lt;/p&gt;
&lt;p&gt;
We did, in-fact, start to see a small number of requests become queued throughout
our test.&amp;#160; This indicates that some requests started to pile up waiting for an
available thread to become available.&amp;#160; 
&lt;/p&gt;
&lt;p&gt;
Please note that I’m &lt;strong&gt;NOT&lt;/strong&gt; saying that you should not use Parallel
operations in your website.&amp;#160; &lt;strong&gt;You saw in the first image that the actual
request execution time decreased significantly from the non-parallel implementation
to the parallel implementation.&lt;/strong&gt; But it’s important to note that nothing is
free and while parallelizing your work can and will improve the performance of a single
request, it should also be weighed against the potential performance of your site
overall.
&lt;/p&gt;
&lt;p&gt;
Until next time.
&lt;/p&gt;</description>
      <comments>http://www.samuraiprogrammer.com/blog/CommentView,guid,90aee052-b425-4e42-82ee-2b736c506e39.aspx</comments>
      <category>.NET 4</category>
      <category>ASP.NET</category>
      <category>Parallel</category>
      <category>Performance</category>
    </item>
    <item>
      <trackback:ping>http://www.samuraiprogrammer.com/blog/Trackback.aspx?guid=694e9ac5-36f0-4e29-9c10-861f2ef23098</trackback:ping>
      <pingback:server>http://www.samuraiprogrammer.com/blog/pingback.aspx</pingback:server>
      <pingback:target>http://www.samuraiprogrammer.com/blog/PermaLink,guid,694e9ac5-36f0-4e29-9c10-861f2ef23098.aspx</pingback:target>
      <dc:creator>Greg Varveris</dc:creator>
      <wfw:comment>http://www.samuraiprogrammer.com/blog/CommentView,guid,694e9ac5-36f0-4e29-9c10-861f2ef23098.aspx</wfw:comment>
      <wfw:commentRss>http://www.samuraiprogrammer.com/blog/SyndicationService.asmx/GetEntryCommentsRss?guid=694e9ac5-36f0-4e29-9c10-861f2ef23098</wfw:commentRss>
      <slash:comments>3</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Often, I’ll have a customer that wants to utilize a new feature in the .NET framework
but they don’t necessarily know where to start or they have a large investment in
another area and they’re afraid of the amount of rework required to get something
working.  This week, for example, I was teaching a customer about WPF and they
asked:
</p>
        <blockquote>
          <p>
“We have several class libraries and we’d like to expose them as WCF services. 
How can we do it?”
</p>
        </blockquote>
        <p>
Yes, it was a bit off-topic from WPF but not really.  I’ve found that when a
customer chooses to start investing in a newer technology, like WPF, I’ve found that
they also want to look at ways to revamp their existing applications to use other
new features.  But I digress… 
</p>
        <p>
In pre-.NET 4.0, if you wanted to expose a class as a WCF endpoint and make it available
in IIS as an SVC file, you would have to do the following:
</p>
        <ol>
          <li>
Create a new WCF Service (in the same category as WebSite). 
</li>
          <li>
Add  a bunch of new “WCF Service” classes (files with an extension of “.SVC”). 
</li>
          <li>
Write some code to call out to your existing class library from the WCF Service. 
</li>
        </ol>
        <p>
It’s not exactly a painful experience but would require a bit of work to get everything
up and running.  In many cases, if you have a huge investment in something like
a class library, the amount of work may be incredibly daunting.  Fortunately,
using some of the features in WCF 4 (part of .NET 4), this type of story is ridiculously
easy.  The steps that we’ll follow are the following:
</p>
        <ol>
          <li>
Decorate your existing class. 
</li>
          <li>
Add configuration. 
</li>
          <li>
Deploy to IIS 
</li>
        </ol>
        <p>
Then, I’ll discuss additional options for debugging your new service.
</p>
        <h3>Step 1:  Decorate your existing class
</h3>
        <p>
So, I’m sure we all have a class in some Class Library somewhere that looks like this:
</p>
        <pre class="c#" name="code">public class MyBusinessLogic<br />
{<br /><br />
public string GetName(int id)<br />
{<br /><br />
return "My ID is: " + id;<br /><br />
}<br /><br />
public MyDataClass GetEmpInformation(int id)<br />
{<br /><br />
return new MyDataClass() 
<br />
{ 
<br />
FirstName = "Greg", 
<br />
LastName = "Varveris", 
<br />
Occupation = "Developer" 
<br />
};<br /><br /><br />
}<br />
}</pre>
        <p>
This is just a simple little business logic class that exposes two public methods
– GetName and GetEmpInformation.  So, let’s say we wanted to make this class
accessible as a WCF service.  The first thing we need to do is add a reference
to the .NET 4 version of System.ServiceModel in our Class Library project.  
</p>
        <p>
          <a href="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_4.png">
            <img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" class="wlDisabledImage" title="image" border="0" alt="image" src="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_thumb_1.png" width="214" height="161" />
          </a>
        </p>
        <p>
I’ve included a screenshot to our left just to further show that there is no special
sauce here.  All of the assemblies being referenced in this project are straight
up class library defaults.  Now that we have the assembly referenced, let’s decorate
our class with two attributes:
</p>
        <ul>
          <li>
ServiceContract – This decorates our class and tells .NET that we have a WCF Service. 
</li>
          <li>
OperationContract – This decorates our methods and tells .NET which methods/functions
we want to expose in our service. 
</li>
        </ul>
        <p>
The decorated class will now look like:
</p>
        <pre class="c#" name="code">[ServiceContract]<br />
public class MyBusinessLogic<br />
{<br /><br />
[OperationContract]<br />
public string GetName(int id)<br />
{<br /><br />
return "My ID is: " + id;<br /><br />
}<br /><br />
[OperationContract]<br />
public MyDataClass GetEmpInformation(int id)<br />
{<br /><br />
return new MyDataClass() 
<br />
{ 
<br />
FirstName = "Greg", 
<br />
LastName = "Varveris", 
<br />
Occupation = "Developer" 
<br />
};<br /><br /><br />
}<br />
}</pre>
        <p>
And <strong>really </strong>that’s all you have to do from the code side.
</p>
        <h3>Step 2:  Add Configuration
</h3>
        <p>
WCF configuration has always been synonymous with “WOAH” before.  Even using
the great configuration editor tool, you may end up with a large amount of XML in
your .config file.  This is mostly because WCF is just so darn extensible. 
Well, for our scenario, we’ll use some great new features in WCF 4 to make the configuration
a breeze:
</p>
        <ul>
          <li>
File-less Activation 
</li>
          <li>
Default Configuration model 
</li>
        </ul>
        <p>
          <a href="http://msdn.microsoft.com/en-us/library/ee354381.aspx">You can read-up about
each of these features in the nice MSDN documentation.</a> Basically, WCF 4 exposes
the ability to map a file-name to a class and then it can expose a default endpoint
(using BasicHttpBinding).  For our scenario my entire config file is:
</p>
        <pre class="xml" name="code">&lt;configuration&gt;<br />
&lt;system.serviceModel&gt;<br />
&lt;serviceHostingEnvironment&gt;<br />
&lt;serviceActivations&gt;<br />
&lt;add relativeAddress="MyBusinessLogic.svc" service="WCFSample.Library.MyBusinessLogic"/&gt;<br />
&lt;/serviceActivations&gt;<br />
&lt;/serviceHostingEnvironment&gt;<br />
&lt;behaviors&gt;<br />
&lt;serviceBehaviors&gt;<br />
&lt;behavior&gt;<br />
&lt;serviceMetadata httpGetEnabled="true"/&gt;<br />
&lt;/behavior&gt;<br />
&lt;/serviceBehaviors&gt;<br />
&lt;/behaviors&gt;<br />
&lt;/system.serviceModel&gt;<br />
&lt;/configuration&gt;</pre>
        <p>
That’s it.  In the first snippet, we are adding a relative address of “MyBusinessLogic.svc”
which will point to our MyBusinessLogic class we defined above.  The second section
along the bottom is just to enable the service metadata.  
</p>
        <p>
The only minor manual snafu you’ll need to handle is that Visual Studio won’t let
you add a web.config to a Class Library project.  This can be easily remedied
in a variety of ways.  I just added an app.config to my project and then changed
the name from “app.config” to “web.config”.  Then, you just need to tell it to
Copy to the output directory.  This makes our project look like the following:
</p>
        <p>
          <a href="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_12.png">
            <img style="border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="image" border="0" alt="image" src="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_thumb_5.png" width="533" height="155" />
          </a>
        </p>
        <h3>Step 3:  Deploy to IIS
</h3>
        <p>
Now that we have our minuscule configuration and trivial decorations to our class,
we need to host our service somewhere.  For this, we’ll just use IIS with an
ASP.NET 4.0 application pool.  The structure of this folder will need to have
the assemblies in a “bin” folder and the web.config in the root.
</p>
        <p>
          <a href="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_14.png">
            <img style="border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="image" border="0" alt="image" src="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_thumb_6.png" width="502" height="186" />
          </a>
        </p>
        <p>
The bin folder is required so that the IIS engine can find your assembly.  Once
you configure this in IIS, you can simply navigate to your service (make sure you
include the SVC in your url) in a browser and you’ll see the glorious WCF Service
start page. For example, on my machine, when I navigate to: <strong><em>http://localhost/SampleWCFService/MyBusinessLogic.svc, </em></strong>I’ll
see:
</p>
        <p>
          <a href="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_16.png">
            <img style="border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="image" border="0" alt="image" src="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_thumb_7.png" width="493" height="254" />
          </a>
        </p>
        <h3>Debugging your service
</h3>
        <p>
So you have created your service, added configuration to it and deployed it to your
hosting environment and everything is running smoothly.  What if you want to
debug the service in Visual Studio?  Well, you really have 3 different options:
</p>
        <ol>
          <li>
Attach to the instance of w3wp hosting your WCF service. 
</li>
          <li>
Cassini…errr, the ASP.NET Development Server. 
</li>
          <li>
IIS Express 
</li>
        </ol>
        <p>
I personally prefer either options 2 or 3 as it provides that seamless debugging experience
we all crave where we just hit the “Green Arrow” to start the debugging session. 
With either option you select, we’ll need to make one or two minor configuration changes.
</p>
        <p>
First, we’ll need to tell the solution to start our process.  For this, you can
right-click on your solution file in the Solution explorer and select “Properties”. 
In this window, you’ll need to select the Multiple Startup Projects radio button and
set both of your projects (the Client and the Service) to the “Start” option.
</p>
        <p>
          <a href="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_22.png">
            <img style="border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="image" border="0" alt="image" src="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_thumb_10.png" width="640" height="399" />
          </a>
        </p>
        <p>
Second, you’ll need to add a pre/post-build step for your service to structure the
output folder correctly.  Since we will deleting the contents of the “Bin” folder
wherever our assemblies are being output, the command we will use is:
</p>
        <blockquote>
          <p>
if exist "$(TargetDir)bin" del /q "$(TargetDir)bin\*.*"
</p>
        </blockquote>
        <p>
Then, for our post-build step, we will need to create the bin folder if it doesn’t
exist and then copy over our DLL’s into that bin folder.  Those commands will
be:
</p>
        <blockquote>
          <p>
if not exist "$(TargetDir)bin" mkdir "$(TargetDir)bin" 
<br />
copy "$(TargetDir)\*.dll" "$(TargetDir)\bin" 
<br />
copy "$(TargetDir)\*.pdb" "$(TargetDir)\bin" 
<br />
del "$(TargetDir)\*.dll" 
<br />
del "$(TargetDir)\*.pdb"
</p>
        </blockquote>
        <p>
That will take our output directory from zero to hero quite nicely:
</p>
        <p>
          <a href="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_20.png">
            <img style="border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="image" border="0" alt="image" src="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_thumb_9.png" width="638" height="103" />
          </a>
        </p>
        <p>
Now that the prerequisites are met, we just need to point our local hosting tool (either
the Development Server or IIS Express) at that folder.  We’ll do this in the
Debug tab of the project properties.   Set the “Start External Program”
radio button and set the path to:
</p>
        <blockquote>
          <p>
C:\Program Files (x86)\Common Files\microsoft shared\DevServer\10.0\WebDev.WebServer40.EXE
</p>
        </blockquote>
        <p>
Then, in the Command Line Arguments, specify the following:
</p>
        <blockquote>
          <p>
/port:12345 
<br />
/path:"&lt;path to folder containing bin &amp; web.config&gt;" 
<br />
/vpath:/myservice
</p>
        </blockquote>
        <p>
Then, you can set a Service Reference on whatever vpath you chose above.  For
example, my service reference points to:  <strong><em>http://localhost:12345/myservice/MyBusinessLogic.svc</em></strong></p>
        <p>
Once the service reference is set, you can just hit the fancy green arrow to start
debugging:
</p>
        <p>
          <a href="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_24.png">
            <img style="border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="image" border="0" alt="image" src="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_thumb_11.png" width="449" height="356" />
          </a>
        </p>
Enjoy! 
</body>
      <title>Exposing any class as a WCF endpoint…</title>
      <guid isPermaLink="false">http://www.samuraiprogrammer.com/blog/PermaLink,guid,694e9ac5-36f0-4e29-9c10-861f2ef23098.aspx</guid>
      <link>http://www.samuraiprogrammer.com/blog/2010/09/03/ExposingAnyClassAsAWCFEndpoint.aspx</link>
      <pubDate>Fri, 03 Sep 2010 06:41:11 GMT</pubDate>
      <description>&lt;p&gt;
Often, I’ll have a customer that wants to utilize a new feature in the .NET framework
but they don’t necessarily know where to start or they have a large investment in
another area and they’re afraid of the amount of rework required to get something
working.&amp;#160; This week, for example, I was teaching a customer about WPF and they
asked:
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
“We have several class libraries and we’d like to expose them as WCF services.&amp;#160;
How can we do it?”
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
Yes, it was a bit off-topic from WPF but not really.&amp;#160; I’ve found that when a
customer chooses to start investing in a newer technology, like WPF, I’ve found that
they also want to look at ways to revamp their existing applications to use other
new features.&amp;#160; But I digress… 
&lt;/p&gt;
&lt;p&gt;
In pre-.NET 4.0, if you wanted to expose a class as a WCF endpoint and make it available
in IIS as an SVC file, you would have to do the following:
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
Create a new WCF Service (in the same category as WebSite). 
&lt;/li&gt;
&lt;li&gt;
Add&amp;#160; a bunch of new “WCF Service” classes (files with an extension of “.SVC”). 
&lt;/li&gt;
&lt;li&gt;
Write some code to call out to your existing class library from the WCF Service. 
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
It’s not exactly a painful experience but would require a bit of work to get everything
up and running.&amp;#160; In many cases, if you have a huge investment in something like
a class library, the amount of work may be incredibly daunting.&amp;#160; Fortunately,
using some of the features in WCF 4 (part of .NET 4), this type of story is ridiculously
easy.&amp;#160; The steps that we’ll follow are the following:
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
Decorate your existing class. 
&lt;/li&gt;
&lt;li&gt;
Add configuration. 
&lt;/li&gt;
&lt;li&gt;
Deploy to IIS 
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
Then, I’ll discuss additional options for debugging your new service.
&lt;/p&gt;
&lt;h3&gt;Step 1:&amp;#160; Decorate your existing class
&lt;/h3&gt;
&lt;p&gt;
So, I’m sure we all have a class in some Class Library somewhere that looks like this:
&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;public class MyBusinessLogic&lt;br /&gt;
{&lt;br /&gt;
&lt;br /&gt;
public string GetName(int id)&lt;br /&gt;
{&lt;br /&gt;
&lt;br /&gt;
return &amp;quot;My ID is: &amp;quot; + id;&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public MyDataClass GetEmpInformation(int id)&lt;br /&gt;
{&lt;br /&gt;
&lt;br /&gt;
return new MyDataClass() 
&lt;br /&gt;
{ 
&lt;br /&gt;
FirstName = &amp;quot;Greg&amp;quot;, 
&lt;br /&gt;
LastName = &amp;quot;Varveris&amp;quot;, 
&lt;br /&gt;
Occupation = &amp;quot;Developer&amp;quot; 
&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
}&lt;/pre&gt;
&lt;p&gt;
This is just a simple little business logic class that exposes two public methods
– GetName and GetEmpInformation.&amp;#160; So, let’s say we wanted to make this class
accessible as a WCF service.&amp;#160; The first thing we need to do is add a reference
to the .NET 4 version of System.ServiceModel in our Class Library project.&amp;#160; 
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_4.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" class="wlDisabledImage" title="image" border="0" alt="image" src="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_thumb_1.png" width="214" height="161" /&gt;&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
I’ve included a screenshot to our left just to further show that there is no special
sauce here.&amp;#160; All of the assemblies being referenced in this project are straight
up class library defaults.&amp;#160; Now that we have the assembly referenced, let’s decorate
our class with two attributes:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
ServiceContract – This decorates our class and tells .NET that we have a WCF Service. 
&lt;/li&gt;
&lt;li&gt;
OperationContract – This decorates our methods and tells .NET which methods/functions
we want to expose in our service. 
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
The decorated class will now look like:
&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;[ServiceContract]&lt;br /&gt;
public class MyBusinessLogic&lt;br /&gt;
{&lt;br /&gt;
&lt;br /&gt;
[OperationContract]&lt;br /&gt;
public string GetName(int id)&lt;br /&gt;
{&lt;br /&gt;
&lt;br /&gt;
return &amp;quot;My ID is: &amp;quot; + id;&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
[OperationContract]&lt;br /&gt;
public MyDataClass GetEmpInformation(int id)&lt;br /&gt;
{&lt;br /&gt;
&lt;br /&gt;
return new MyDataClass() 
&lt;br /&gt;
{ 
&lt;br /&gt;
FirstName = &amp;quot;Greg&amp;quot;, 
&lt;br /&gt;
LastName = &amp;quot;Varveris&amp;quot;, 
&lt;br /&gt;
Occupation = &amp;quot;Developer&amp;quot; 
&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
}&lt;/pre&gt;
&lt;p&gt;
And &lt;strong&gt;really &lt;/strong&gt;that’s all you have to do from the code side.
&lt;/p&gt;
&lt;h3&gt;Step 2:&amp;#160; Add Configuration
&lt;/h3&gt;
&lt;p&gt;
WCF configuration has always been synonymous with “WOAH” before.&amp;#160; Even using
the great configuration editor tool, you may end up with a large amount of XML in
your .config file.&amp;#160; This is mostly because WCF is just so darn extensible.&amp;#160;
Well, for our scenario, we’ll use some great new features in WCF 4 to make the configuration
a breeze:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
File-less Activation 
&lt;/li&gt;
&lt;li&gt;
Default Configuration model 
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
&lt;a href="http://msdn.microsoft.com/en-us/library/ee354381.aspx"&gt;You can read-up about
each of these features in the nice MSDN documentation.&lt;/a&gt; Basically, WCF 4 exposes
the ability to map a file-name to a class and then it can expose a default endpoint
(using BasicHttpBinding).&amp;#160; For our scenario my entire config file is:
&lt;/p&gt;
&lt;pre class="xml" name="code"&gt;&amp;lt;configuration&amp;gt;&lt;br /&gt;
&amp;lt;system.serviceModel&amp;gt;&lt;br /&gt;
&amp;lt;serviceHostingEnvironment&amp;gt;&lt;br /&gt;
&amp;lt;serviceActivations&amp;gt;&lt;br /&gt;
&amp;lt;add relativeAddress=&amp;quot;MyBusinessLogic.svc&amp;quot; service=&amp;quot;WCFSample.Library.MyBusinessLogic&amp;quot;/&amp;gt;&lt;br /&gt;
&amp;lt;/serviceActivations&amp;gt;&lt;br /&gt;
&amp;lt;/serviceHostingEnvironment&amp;gt;&lt;br /&gt;
&amp;lt;behaviors&amp;gt;&lt;br /&gt;
&amp;lt;serviceBehaviors&amp;gt;&lt;br /&gt;
&amp;lt;behavior&amp;gt;&lt;br /&gt;
&amp;lt;serviceMetadata httpGetEnabled=&amp;quot;true&amp;quot;/&amp;gt;&lt;br /&gt;
&amp;lt;/behavior&amp;gt;&lt;br /&gt;
&amp;lt;/serviceBehaviors&amp;gt;&lt;br /&gt;
&amp;lt;/behaviors&amp;gt;&lt;br /&gt;
&amp;lt;/system.serviceModel&amp;gt;&lt;br /&gt;
&amp;lt;/configuration&amp;gt;&lt;/pre&gt;
&lt;p&gt;
That’s it.&amp;#160; In the first snippet, we are adding a relative address of “MyBusinessLogic.svc”
which will point to our MyBusinessLogic class we defined above.&amp;#160; The second section
along the bottom is just to enable the service metadata.&amp;#160; 
&lt;/p&gt;
&lt;p&gt;
The only minor manual snafu you’ll need to handle is that Visual Studio won’t let
you add a web.config to a Class Library project.&amp;#160; This can be easily remedied
in a variety of ways.&amp;#160; I just added an app.config to my project and then changed
the name from “app.config” to “web.config”.&amp;#160; Then, you just need to tell it to
Copy to the output directory.&amp;#160; This makes our project look like the following:
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_12.png"&gt;&lt;img style="border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="image" border="0" alt="image" src="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_thumb_5.png" width="533" height="155" /&gt;&lt;/a&gt;
&lt;/p&gt;
&lt;h3&gt;Step 3:&amp;#160; Deploy to IIS
&lt;/h3&gt;
&lt;p&gt;
Now that we have our minuscule configuration and trivial decorations to our class,
we need to host our service somewhere.&amp;#160; For this, we’ll just use IIS with an
ASP.NET 4.0 application pool.&amp;#160; The structure of this folder will need to have
the assemblies in a “bin” folder and the web.config in the root.
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_14.png"&gt;&lt;img style="border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="image" border="0" alt="image" src="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_thumb_6.png" width="502" height="186" /&gt;&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
The bin folder is required so that the IIS engine can find your assembly.&amp;#160; Once
you configure this in IIS, you can simply navigate to your service (make sure you
include the SVC in your url) in a browser and you’ll see the glorious WCF Service
start page. For example, on my machine, when I navigate to: &lt;strong&gt;&lt;em&gt;http://localhost/SampleWCFService/MyBusinessLogic.svc, &lt;/em&gt;&lt;/strong&gt;I’ll
see:
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_16.png"&gt;&lt;img style="border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="image" border="0" alt="image" src="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_thumb_7.png" width="493" height="254" /&gt;&lt;/a&gt;
&lt;/p&gt;
&lt;h3&gt;Debugging your service
&lt;/h3&gt;
&lt;p&gt;
So you have created your service, added configuration to it and deployed it to your
hosting environment and everything is running smoothly.&amp;#160; What if you want to
debug the service in Visual Studio?&amp;#160; Well, you really have 3 different options:
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
Attach to the instance of w3wp hosting your WCF service. 
&lt;/li&gt;
&lt;li&gt;
Cassini…errr, the ASP.NET Development Server. 
&lt;/li&gt;
&lt;li&gt;
IIS Express 
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
I personally prefer either options 2 or 3 as it provides that seamless debugging experience
we all crave where we just hit the “Green Arrow” to start the debugging session.&amp;#160;
With either option you select, we’ll need to make one or two minor configuration changes.
&lt;/p&gt;
&lt;p&gt;
First, we’ll need to tell the solution to start our process.&amp;#160; For this, you can
right-click on your solution file in the Solution explorer and select “Properties”.&amp;#160;
In this window, you’ll need to select the Multiple Startup Projects radio button and
set both of your projects (the Client and the Service) to the “Start” option.
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_22.png"&gt;&lt;img style="border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="image" border="0" alt="image" src="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_thumb_10.png" width="640" height="399" /&gt;&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
Second, you’ll need to add a pre/post-build step for your service to structure the
output folder correctly.&amp;#160; Since we will deleting the contents of the “Bin” folder
wherever our assemblies are being output, the command we will use is:
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
if exist &amp;quot;$(TargetDir)bin&amp;quot; del /q &amp;quot;$(TargetDir)bin\*.*&amp;quot;
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
Then, for our post-build step, we will need to create the bin folder if it doesn’t
exist and then copy over our DLL’s into that bin folder.&amp;#160; Those commands will
be:
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
if not exist &amp;quot;$(TargetDir)bin&amp;quot; mkdir &amp;quot;$(TargetDir)bin&amp;quot; 
&lt;br /&gt;
copy &amp;quot;$(TargetDir)\*.dll&amp;quot; &amp;quot;$(TargetDir)\bin&amp;quot; 
&lt;br /&gt;
copy &amp;quot;$(TargetDir)\*.pdb&amp;quot; &amp;quot;$(TargetDir)\bin&amp;quot; 
&lt;br /&gt;
del &amp;quot;$(TargetDir)\*.dll&amp;quot; 
&lt;br /&gt;
del &amp;quot;$(TargetDir)\*.pdb&amp;quot;
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
That will take our output directory from zero to hero quite nicely:
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_20.png"&gt;&lt;img style="border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="image" border="0" alt="image" src="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_thumb_9.png" width="638" height="103" /&gt;&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
Now that the prerequisites are met, we just need to point our local hosting tool (either
the Development Server or IIS Express) at that folder.&amp;#160; We’ll do this in the
Debug tab of the project properties.&amp;#160;&amp;#160; Set the “Start External Program”
radio button and set the path to:
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
C:\Program Files (x86)\Common Files\microsoft shared\DevServer\10.0\WebDev.WebServer40.EXE
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
Then, in the Command Line Arguments, specify the following:
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
/port:12345 
&lt;br /&gt;
/path:&amp;quot;&amp;lt;path to folder containing bin &amp;amp; web.config&amp;gt;&amp;quot; 
&lt;br /&gt;
/vpath:/myservice
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
Then, you can set a Service Reference on whatever vpath you chose above.&amp;#160; For
example, my service reference points to:&amp;#160; &lt;strong&gt;&lt;em&gt;http://localhost:12345/myservice/MyBusinessLogic.svc&lt;/em&gt;&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
Once the service reference is set, you can just hit the fancy green arrow to start
debugging:
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_24.png"&gt;&lt;img style="border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="image" border="0" alt="image" src="http://www.samuraiprogrammer.com/blog/content/binary/WindowsLiveWriter/909f14b2c894_E17C/image_thumb_11.png" width="449" height="356" /&gt;&lt;/a&gt;
&lt;/p&gt;
Enjoy!


</description>
      <comments>http://www.samuraiprogrammer.com/blog/CommentView,guid,694e9ac5-36f0-4e29-9c10-861f2ef23098.aspx</comments>
      <category>.NET 4</category>
      <category>WCF</category>
    </item>
  </channel>
</rss>