<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>Programming tidbits: store &amp; retrieve</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/oanapl/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/oanapl/feed.xml</link>
    <description>Coding &amp;amp; debugging: The more you&amp;#039;ll do it, the better you&amp;#039;ll do it!</description>
    <lastBuildDate>Sat, 11 Apr 2015 03:35:12 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>From C# to C++: Creating a blog demo project – coding style rules</title>
      <link>https://docs.microsoft.com/archive/blogs/oanapl/from-c-to-c-creating-a-blog-demo-project-coding-style-rules</link>
      <pubDate>Tue, 05 Oct 2010 16:53:27 GMT</pubDate>
      <dc:creator><![CDATA[OanaPlaton]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/oanapl/2010/10/05/from-c-to-c-creating-a-blog-demo-project-coding-style-rules/</guid>
      <description><![CDATA[Like I mentioned in my previous post, for the last months I had to change my programming language...]]></description>
      <content:encoded><![CDATA[<p>Like I mentioned in my previous post, for the last months I had to change my programming language from C# to C++. To show you some of the things that surprised me in the process, I will write a short series of blog posts to emphasize the scenarios and the issues.</p>  <p>The code samples show a simple project that manages cache entries. Several cache entries can exist in a cache session, and cache sessions are managed by a cache manager. The project was created with <a href="http://www.microsoft.com/visualstudio/en-us/visual-studio-2010-launch?WT.mc_id=SEARCH&amp;WT.srch=1">Visual Studio 2010</a>. My Visual Studio 2010 has applied a color scheme from <a title="http://studiostyles.info/" href="http://studiostyles.info/">http://studiostyles.info/</a> to make it more attractive.</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/05/32/metablogapi/2577.VS2010-BlogSample-project_5B3443F6.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-05-32-metablogapi/2577.VS2010_2D00_BlogSample_2D00_project_5F00_5B3443F6.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="VS2010-BlogSample-project" border="0" alt="VS2010-BlogSample-project" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/05/32/metablogapi/0508.VS2010-BlogSample-project_thumb_30986319.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-05-32-metablogapi/0508.VS2010_2D00_BlogSample_2D00_project_5F00_thumb_5F00_30986319.png" width="498" height="397" /></a>&#160;</p>  <p>Some notes about the coding style I’m using:</p>  <ul>   <li><strong>Use precompiled header with default VS settings (StdAfx). </strong></li>    <li><strong>Use STL. All include statements for STL files are in StdAfx.h (the precompiled header)</strong></li> </ul>  <blockquote>   <pre class="code"><span style="color: green">// stdafx.h
</span><span style="color: blue">#pragma once
#include </span><span style="background: #ffffe6">&quot;targetver.h&quot;

</span><span style="color: blue">#include </span><span style="background: #ffffe6">&lt;map&gt;
</span><span style="color: blue">#include </span><span style="background: #ffffe6">&lt;memory&gt;
</span><span style="color: blue">#include </span><span style="background: #ffffe6">&lt;string&gt;
</span><span style="color: blue">#include </span><span style="background: #ffffe6">&lt;vector&gt;
…</span></pre>
</blockquote>


<ul>
  <li><strong>Never include using in header files.</strong></li>

  <li><strong>Declare all members as private and use properties for accessing them. Private member names start with prefix p.</strong></li>
</ul>

<blockquote>
  <p>Coming from a C# background, I came to appreciate the syntactic sugar that lets you write less code and helps with project readability. One of these features is the syntactic sugar for getter and setter accessors of object properties. Well, nothing is lost in C++: a <a href="http://msdn.microsoft.com/en-us/library/yhfk0thd.aspx">property</a> can be easily defined using <a href="http://msdn.microsoft.com/en-us/library/dabb5z75.aspx">__declspec</a>. You can read more about this <a href="http://blogs.msdn.com/b/ericflee/archive/2008/04/17/how-to-do-object-properties-in-c.aspx">in this blog post</a>. The properties look like this (snippet from CacheManager.h):</p>
</blockquote>

<blockquote>
  <pre class="code"><span style="color: navy">__declspec</span>(<span style="color: blue">property</span>(<span style="color: maroon">get</span>=<span style="color: maroon">get_Owner</span>)) <span style="color: maroon">std</span>::<span style="color: maroon">wstring </span><span style="color: navy">const </span>&amp; <span style="color: maroon">Owner</span>;
<span style="color: maroon">std</span>::<span style="color: maroon">wstring </span><span style="color: navy">const </span>&amp; <span style="color: maroon">get_Owner</span>() <span style="color: navy">const </span>{ <span style="color: navy">return </span><span style="color: maroon">pOwner</span>; }</pre>
</blockquote>

<ul>
  <li><strong>Use typedef whenever needed to make the code easier to read and understand.</strong> Example:</li>
</ul>

<blockquote>
  <pre class="code"><span style="color: navy">typedef </span><span style="color: maroon">std</span>::<span style="color: maroon">map</span>&lt;<span style="color: maroon">std</span>::<span style="color: maroon">wstring</span>, <span style="color: maroon">CacheEntry</span>&lt;<span style="color: maroon">std</span>::<span style="color: maroon">wstring</span>&gt;&gt; <span style="color: maroon">StringCacheEntryMap</span>;</pre>
</blockquote>


<ul>
  <li><strong>Use </strong><a href="http://msdn.microsoft.com/en-us/library/h1y7x448.aspx"><strong>explicit</strong></a><strong> whenever the constructor has one parameter to avoid implicit type conversion. </strong>Example:</li>
</ul>

<blockquote>
  <pre class="code"><span style="color: navy">explicit </span><span style="color: maroon">CacheManager</span>(<span style="color: maroon">std</span>::<span style="color: maroon">wstring </span><span style="color: navy">const </span>&amp; <span style="color: maroon">owner</span>);</pre>
</blockquote>


<ul>
  <li><strong>Prefer passing arguments by reference if at all possible to avoid copy unnecessary operations</strong><strong>. </strong>Exception: <a href="http://msdn.microsoft.com/en-us/library/cc953fe1(v=VS.80).aspx">fundamental types</a> and small structures, for which copy is inexpensive. </li>
</ul>

<blockquote>
  <pre class="code"><span style="color: navy">void </span><span style="color: maroon">Add</span>(<span style="color: maroon">StringCacheEntry </span><span style="color: navy">const </span>&amp; <span style="color: maroon">entry</span>);</pre>
</blockquote>


<ul>
  <li><strong>Always use </strong><a href="http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization"><strong>Resource Acquisition Is Initialization</strong></a><strong> (RAII).</strong> Avoid using raw pointers, wrap them in unique_ptr or shared_ptr to avoid memory leaks/corruption.</li>

  <li><strong>Whenever possible, use move constructors for expensive objects. </strong></li>
</ul>

<p>In interest of space, the code pasted in the blog entries may be compacted, in which case some of the rules may be abolished.</p>]]></content:encoded>
    </item>
    <item>
      <title>Back to C++: From managed to native</title>
      <link>https://docs.microsoft.com/archive/blogs/oanapl/back-to-c-from-managed-to-native</link>
      <pubDate>Tue, 05 Oct 2010 12:47:53 GMT</pubDate>
      <dc:creator><![CDATA[OanaPlaton]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/oanapl/2010/10/05/back-to-c-from-managed-to-native/</guid>
      <description><![CDATA[The project I’ve been working on for the last several months is using native C++. Since I haven’t...]]></description>
      <content:encoded><![CDATA[<p>The project I’ve been working on for the last several months is using native C++. Since I haven’t employed C++ in a long time (since school, to be precise), I had to “relearn” the language. As expected, the language grew a lot since last I was acquainted with it, and I was impressed with the new features (see <a href="http://open-std.org/JTC1/SC22/WG21/docs/papers/2008/n2798.pdf">Working Draft, Standard for Programming Language C++for more details on the changes</a>). Luckily, my project is a startup, and we are allowed to use the new futures without fears of back interoperability or style consistency. A big help with the learning curve was <a href="http://www.microsoft.com/visualstudio/en-us/buy">Visual Studio 2010</a>, which really improves both the coding and debugging experience. I must say, the transition from C# to C++ was much easier because I used the same tools.</p>  <p>Here are some resources I used to get back to native code (as you noticed, I haven’t use the keyword “unmanaged”: a lot of C++ users consider the term “unmanaged” degrading, because it somewhat implies that unmanaged is somewhat inferior to managed or developed after managed code):</p>  <ol>   <li><a title="Effective C++" href="http://www.amazon.com/Effective-Specific-Improve-Programs-ebook/dp/B000SEGMBO/ref=dp_kinw_strp_1?ie=UTF8&amp;m=AG56TWVU5XWC2">Effective C++</a> – <a href="http://www.amazon.com/Scott-Meyers/e/B000AQ3PDI/ref=ntt_athr_dp_pel_1">Scott Meyers</a></li>    <li><a href="http://www.amazon.com/More-Effective-Improve-Programs-ebook/dp/B0036QVOO6/ref=dp_kinw_strp_1?ie=UTF8&amp;m=AG56TWVU5XWC2">More Effective C++</a> – <a href="http://www.amazon.com/Scott-Meyers/e/B000AQ3PDI/ref=ntt_athr_dp_pel_1">Scott Meyers</a></li>    <li><a href="http://www.amazon.com/Effective-STL-Specific-Standard-ebook/dp/B0019HW0K6/ref=dp_kinw_strp_1?ie=UTF8&amp;m=AG56TWVU5XWC2">Effective STL</a> - <a href="http://www.amazon.com/Scott-Meyers/e/B000AQ3PDI/ref=ntt_athr_dp_pel_1">Scott Meyers</a>&#160;</li>    <li><a href="http://www.amazon.com/Windows-via-Pro-Jeffrey-Richter/dp/0735624240/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1286305400&amp;sr=1-1">Windows via C/C++ (Pro - Developer)</a> - <a href="http://www.amazon.com/s/ref=ntt_athr_dp_sr_1?_encoding=UTF8&amp;sort=relevancerank&amp;search-alias=books&amp;field-author=Jeffrey%20M.%20Richter">Jeffrey M. Richter</a></li>    <li><a href="http://www.amazon.com/Coding-Standards-Rules-Guidelines-Practices/dp/0321113586/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1286305450&amp;sr=1-1">C++ Coding Standards: 101 Rules, Guidelines, and Best Practices</a> - <a href="http://www.amazon.com/Herb-Sutter/e/B001ILHLCK/ref=ntt_athr_dp_pel_1">Herb Sutter</a></li>    <li><a href="http://www.amazon.com/Templates-Complete-Guide-David-Vandevoorde/dp/0201734842/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1286305577&amp;sr=1-1">C++ Templates: The Complete Guide</a> - <a href="http://www.amazon.com/David-Vandevoorde/e/B001HMNMMS/ref=sr_ntt_srch_lnk_1?qid=1286305577&amp;sr=1-1">David Vandevoorde</a> and <a href="http://www.amazon.com/Nicolai-M.-Josuttis/e/B001ITYMY2/ref=sr_ntt_srch_lnk_1?qid=1286305577&amp;sr=1-1">Nicolai M. Josuttis</a></li> </ol>  <p>These books helped me refresh my C++ memory. On top of this, I had to get familiar with the new 0x features: <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2009/n2927.pdf">lambdas</a> (unnamed function objects), <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1984.pdf">auto</a> (automatic type deduction), <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1720.html">static_assert</a> (trigger compiler errors with custom error messages), <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2118.html">RValue references</a> (move semantics and perfect forwarding) and <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2343.pdf">decltype</a>. Here are the articles I recommend from the Visual C++ team blog:</p>  <ol>   <li><a title="http://blogs.msdn.com/b/vcblog/archive/2008/10/28/lambdas-auto-and-static-assert-c-0x-features-in-vc10-part-1.aspx" href="http://blogs.msdn.com/b/vcblog/archive/2008/10/28/lambdas-auto-and-static-assert-c-0x-features-in-vc10-part-1.aspx">http://blogs.msdn.com/b/vcblog/archive/2008/10/28/lambdas-auto-and-static-assert-c-0x-features-in-vc10-part-1.aspx</a>&#160;</li>    <li><a title="http://blogs.msdn.com/b/vcblog/archive/2009/02/03/rvalue-references-c-0x-features-in-vc10-part-2.aspx" href="http://blogs.msdn.com/b/vcblog/archive/2009/02/03/rvalue-references-c-0x-features-in-vc10-part-2.aspx">http://blogs.msdn.com/b/vcblog/archive/2009/02/03/rvalue-references-c-0x-features-in-vc10-part-2.aspx</a></li>    <li><a title="http://blogs.msdn.com/b/vcblog/archive/2009/04/22/decltype-c-0x-features-in-vc10-part-3.aspx" href="http://blogs.msdn.com/b/vcblog/archive/2009/04/22/decltype-c-0x-features-in-vc10-part-3.aspx">http://blogs.msdn.com/b/vcblog/archive/2009/04/22/decltype-c-0x-features-in-vc10-part-3.aspx</a></li> </ol>  <p>Other materials:</p>  <ol>   <li>Stroustrup C++ language reference </li>    <li>The Design and Evolution of C++ – Stroustrup </li>    <li>The C++ Standard Library: A Tutorial and Reference by Nicolai M. Josuttis.</li>    <li>STL Tutorial and Reference – Musser </li> </ol>  <p>As in any process of learning, I made mistakes and I learned from them. Some mistakes were due to faulty expectations coming from the C# world – like <a title="http://blogs.msdn.com/b/oldnewthing/archive/2004/03/08/85901.aspx" href="http://blogs.msdn.com/b/oldnewthing/archive/2004/03/08/85901.aspx">C++ scoped static initialization is not thread-safe, on purpose!</a>. I’m still learning, and I’m still making mistakes. In future blogs I will share with you some of these mistakes.</p>]]></content:encoded>
    </item>
    <item>
      <title>Optimize for the Hot path</title>
      <link>https://docs.microsoft.com/archive/blogs/oanapl/optimize-for-the-hot-path</link>
      <pubDate>Thu, 04 Feb 2010 13:57:00 GMT</pubDate>
      <dc:creator><![CDATA[OanaPlaton]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/oanapl/2010/02/04/optimize-for-the-hot-path/</guid>
      <description><![CDATA[The Pareto principle (also known as the 80-20 rule, the law of the vital few, and the principle of...]]></description>
      <content:encoded><![CDATA[<P>The <A href="http://en.wikipedia.org/wiki/Pareto_principle" mce_href="http://en.wikipedia.org/wiki/Pareto_principle">Pareto principle</A> (also known as the <B>80-20 rule</B>, the <B>law of the vital few,</B> and the <B>principle of factor sparsity</B>) states that, for many events, roughly 80% of the effects come from 20% of the causes. This applies to programming as well: 80% of the people use 20% of the features, 80% of the execution paths go through 20% of the code etc.</P>
<P>Inside a program, the code paths that are executed most often belong to the <STRONG>hot path</STRONG> (with the remaining code paths being on the <STRONG>cold</STRONG> path). One can look at this at multiple levels: instruction, language statements, features. Over the years, multiple studies have shown how to optimize software for the hot path execution.</P>
<P>Here, I want to focus on the developer that’s writing the code. From the start, the developer can easily identify some cold code (for example, the exception handling code). Keeping in mind the usage pattern, the developer can improve the program so it runs faster most of the times.</P>
<P>Here is an example: let’s say that your application (called CalculatorService) keeps track of the number of Add or Subtract operations by incrementing performance counters. It expects that a performance counter category called CalculatorService already exists (for example, the installer of the service creates it). This is a requirement because it runs as Network Service, while creating the category takes Administrator privileges. Inside CalculatorService category we have 2 counters, AddCounter and SubtractCounter. If the category is not installed, CalculatorService must not throw – it just won’t save the counters.</P>
<P>You decide to create a class PerfCounterPublisher that deal with the performance counters. The service class keeps an instance of PerfCounterPublisher and calls methods on it when Add/Subtract operations are executed.</P><PRE class=code><SPAN style="COLOR: blue">class </SPAN><SPAN style="COLOR: #2b91af">CalculatorService
</SPAN>{
    <SPAN style="COLOR: #2b91af">PerfCounterPublisher </SPAN>publisher;

    <SPAN style="COLOR: blue">public </SPAN>CalculatorService()
    {
        <SPAN style="COLOR: blue">this</SPAN>.publisher = <SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">PerfCounterPublisher</SPAN>(<SPAN style="COLOR: #a31515">"CalculatorService"</SPAN>);
    }

    <SPAN style="COLOR: blue">public int </SPAN>Add(<SPAN style="COLOR: blue">int </SPAN>a, <SPAN style="COLOR: blue">int </SPAN>b)
    {
        <SPAN style="COLOR: blue">this</SPAN>.publisher.IncrementCounter(<SPAN style="COLOR: #a31515">"AddCounter"</SPAN>);
        <SPAN style="COLOR: blue">return </SPAN>a + b;
    }

    <SPAN style="COLOR: blue">public int </SPAN>Subtract(<SPAN style="COLOR: blue">int </SPAN>a, <SPAN style="COLOR: blue">int </SPAN>b)
    {
        <SPAN style="COLOR: blue">this</SPAN>.publisher.IncrementCounter(<SPAN style="COLOR: #a31515">"SubtractCounter"</SPAN>);
        <SPAN style="COLOR: blue">return </SPAN>a - b;
    }
}</PRE><A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"></A><FONT face="Courier New"></FONT><A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"></A>
<P>A simple implementation of the PerfCounterPublisher can look like this:</P><PRE class=code><SPAN style="COLOR: blue">class </SPAN><SPAN style="COLOR: #2b91af">PerfCounterPublisher
</SPAN>{
    <SPAN style="COLOR: blue">string </SPAN>categoryName;

    <SPAN style="COLOR: blue">public </SPAN>PerfCounterPublisher(<SPAN style="COLOR: blue">string </SPAN>categoryName)
    {
        <SPAN style="COLOR: blue">this</SPAN>.categoryName = categoryName;
    }

    <SPAN style="COLOR: blue">public bool </SPAN>IncrementCounter(<SPAN style="COLOR: blue">string </SPAN>counterName)
    {
        <SPAN style="COLOR: blue">if </SPAN>(<SPAN style="COLOR: #2b91af">PerformanceCounterCategory</SPAN>.Exists(<SPAN style="COLOR: blue">this</SPAN>.categoryName))
        {
            <SPAN style="COLOR: #2b91af">PerformanceCounter </SPAN>counter = <SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">PerformanceCounter</SPAN>(
                <SPAN style="COLOR: blue">this</SPAN>.categoryName,
                counterName,
                <SPAN style="COLOR: blue">false</SPAN>);
            counter.Increment();
            <SPAN style="COLOR: blue">return true</SPAN>;
        }

        <SPAN style="COLOR: blue">return false</SPAN>;
    }
}</PRE>
<P>So, if the category is installed, we increment the counter; otherwise, we just return false, letting the user know that the counter wasn’t incremented. </P>
<P>This code can be improved. PerformanceCounterCategory.Exists is a rather expensive operation. If we look at usage pattern, most of the time the counters are installed. So we penalize most of the scenarios by adding the check.</P>
<P>How can we optimize the code for the hot path?</P>
<P>Since we expect the category to exist, we will try to create the counter without the check; in the rare cases where the category doesn’t exist, creating the counter will throw InvalidOperationException – in this case, we catch the exception and return false (counters not incremented). IncrementCounter looks like this:</P><PRE class=code><SPAN style="COLOR: blue">public bool </SPAN>IncrementCounter(<SPAN style="COLOR: blue">string </SPAN>counterName)
{
    <SPAN style="COLOR: blue">try
    </SPAN>{
        <SPAN style="COLOR: #2b91af">PerformanceCounter </SPAN>counter = <SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">PerformanceCounter</SPAN>(
            <SPAN style="COLOR: blue">this</SPAN>.categoryName,
            counterName,
            <SPAN style="COLOR: blue">false</SPAN>);
        counter.Increment();
        <SPAN style="COLOR: blue">return true</SPAN>;
    }
    <SPAN style="COLOR: blue">catch </SPAN>(<SPAN style="COLOR: #2b91af">InvalidOperationException</SPAN>)
    {
        <SPAN style="COLOR: blue">return false</SPAN>;
    }
}</PRE>
<P><A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"></A>Depending on the application scenario, we can make further improvements. For example, if we don’t expect the category is installed after the service has been started, we can check if the category exists in the constructor and set a flag to disabled if it doesn’t. Or we can postpone the check to the first time a call to IncrementCounter is done and set the flag there. If the flag has been set, future IncrementCounter become NoOp.</P>
<P>This is a very simple example, but I hope it expresses what I tried to convey. When writing code, make sure you understand how it’s going to be used, identify the how path based on this and always optimize for the hot path.</P>]]></content:encoded>
    </item>
    <item>
      <title>[Multithreading] Asynchronous Sleep in Distributed applications</title>
      <link>https://docs.microsoft.com/archive/blogs/oanapl/multithreading-asynchronous-sleep-in-distributed-applications</link>
      <pubDate>Tue, 02 Feb 2010 16:48:00 GMT</pubDate>
      <dc:creator><![CDATA[OanaPlaton]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/oanapl/2010/02/02/multithreading-asynchronous-sleep-in-distributed-applications/</guid>
      <description><![CDATA[Scenario: You have to design and implement a distributed application where a lot of clients call...]]></description>
      <content:encoded><![CDATA[<P>Scenario: You have to design and implement a distributed application where a lot of clients call different operations in parallel. In certain situations, in order to make the system behave better, you need to delay some operations. Some examples where this can be useful:</P>
<P>- The distributed system encounters a problem and you have a retry logic in place (eg. the network goes down and you need to retry until it comes up again). In order to avoid hammering the system with the retry logic, you decide to add a small delay between consecutive retries.</P>
<P>- You know a critical operation is taking place and you want to wait for it to finish, either because the resources are shared or it has a higher priority etc (eg. Updates are installed every night at 2 PM or trace data is collected every 4 hours, and your client operations can wait until that is done).</P>
<P>To implement the delay, all the threads of the application need to sleep for a period of time (that can be determined at runtime, eg. choose a random delay in order to avoid all requests to execute at the same time). </P>
<P>Consider an app that starts a number of parallel operations that need to sleep. You can implement this in a sync or async fashion.</P>
<P>1. Sync sleep – Create all the threads and set the work to include sleeping</P><PRE class=code><SPAN style="COLOR: #2b91af">Thread</SPAN>[] clients = <SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">Thread</SPAN>[<SPAN style="COLOR: blue">this</SPAN>.ParallelOperations];
<SPAN style="COLOR: blue">for </SPAN>(<SPAN style="COLOR: blue">int </SPAN>i = 0; i &lt; <SPAN style="COLOR: blue">this</SPAN>.ParallelOperations; i++)
{
    clients[i] = <SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">Thread</SPAN>(<SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">ThreadStart</SPAN>(
        <SPAN style="COLOR: green">// We need a method void () target; 
        // for simplicity, inline it here
        </SPAN>() =&gt;
        {
            <SPAN style="COLOR: green">// ... Previous operations 
            </SPAN><SPAN style="COLOR: #2b91af">Stopwatch </SPAN>watch = <SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">Stopwatch</SPAN>();
            watch.Start();
            <SPAN style="COLOR: #2b91af">Thread</SPAN>.Sleep(SleepTime);
            watch.Stop();
            <SPAN style="COLOR: #2b91af">Console</SPAN>.WriteLine(<SPAN style="COLOR: #a31515">"Elapsed time: {0} msec"</SPAN>, 
                watch.ElapsedMilliseconds);
            <SPAN style="COLOR: green">// ... Subsequent operations 
        </SPAN>}));
}</PRE><PRE class=code><SPAN style="COLOR: green">// Start all clients
</SPAN><SPAN style="COLOR: blue">for </SPAN>(<SPAN style="COLOR: blue">int </SPAN>i = 0; i &lt; <SPAN style="COLOR: blue">this</SPAN>.ParallelOperations; i++)
{
    clients[i].Start();
}

<SPAN style="COLOR: green">// Wait for all clients to finish
</SPAN><SPAN style="COLOR: blue">for </SPAN>(<SPAN style="COLOR: blue">int </SPAN>i = 0; i &lt; <SPAN style="COLOR: blue">this</SPAN>.ParallelOperations; i++)
{
    clients[i].Join();
}</PRE>
<P>This implementation manually creates as many threads as the number of operations that should be ran and calls Sleep (if you need to sleep on a thread that has <A href="http://msdn.microsoft.com/en-us/library/system.stathreadattribute.aspx" mce_href="http://msdn.microsoft.com/en-us/library/system.stathreadattribute.aspx">STAThreadAttribute</A>, but you want to perform standard COM and SendMessage pumping, consider using one of the overloads of the <A href="http://msdn.microsoft.com/en-us/library/system.threading.thread.join.aspx" mce_href="http://msdn.microsoft.com/en-us/library/system.threading.thread.join.aspx">Join</A> method that specifies a timeout interval - <SPAN style="COLOR: #2b91af">Thread</SPAN>.CurrentThread.Join). </P>
<P>Another option is to use the CLR threadpool instead. To wait for the threads, we can use an event that we signal when all operations are done.</P><PRE class=code><SPAN style="COLOR: blue">int </SPAN>clientsDone = 0;
<SPAN style="COLOR: #2b91af">ManualResetEvent </SPAN>waitEvent = <SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">ManualResetEvent</SPAN>(<SPAN style="COLOR: blue">false</SPAN>);

<SPAN style="COLOR: blue">for </SPAN>(<SPAN style="COLOR: blue">int </SPAN>i = 0; i &lt; <SPAN style="COLOR: blue">this</SPAN>.ParallelOperations; i++)
{
    <SPAN style="COLOR: #2b91af">ThreadPool</SPAN>.QueueUserWorkItem(<SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">WaitCallback</SPAN>(o =&gt;
    {
        <SPAN style="COLOR: #2b91af">Stopwatch </SPAN>watch = <SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">Stopwatch</SPAN>();
        watch.Start();
        <SPAN style="COLOR: #2b91af">Thread</SPAN>.Sleep(SleepTime);
        watch.Stop();
        <SPAN style="COLOR: #2b91af">Console</SPAN>.WriteLine(<SPAN style="COLOR: #a31515">"Elapsed time: {0} msec"</SPAN>, watch.ElapsedMilliseconds);
        <SPAN style="COLOR: blue">if </SPAN>(<SPAN style="COLOR: #2b91af">Interlocked</SPAN>.Increment(<SPAN style="COLOR: blue">ref </SPAN>clientsDone) &gt;= <SPAN style="COLOR: blue">this</SPAN>.ParallelOperations)
        {
            waitEvent.Set();
        }
    }));
}

waitEvent.WaitOne(<SPAN style="COLOR: #2b91af">TimeSpan</SPAN>.FromSeconds(WaitTime));</PRE><PRE class=code><SPAN style="COLOR: green">// dispose of the timer and async event</SPAN></PRE>
<P>The sync version has one huge problem: it doesn’t scale. If you look on <A href="http://msdn.microsoft.com/en-us/library/d00bd51t.aspx" mce_href="http://msdn.microsoft.com/en-us/library/d00bd51t.aspx">msdn</A>, it is clearly stated that “the thread will not be scheduled for execution by the operating system for the amount of time specified”. With another words, we are sitting on the current thread without doing any useful work. If the system has many clients, it’s a high possibility that we will eventually run out of threads because operations come in faster than the rate at which we finish them.</P>
<P>2. Async sleep – The alternative is for the operation to start the Sleep and leave the thread to do other, useful work; when the wait is done, the app will be notified and another thread will continue the execution.</P>
<P>To implement the sleep async, we use a Timer – when the callback is triggered, the sleep is done.</P><PRE class=code><SPAN style="COLOR: blue">int </SPAN>clientsDone = 0;
<SPAN style="COLOR: #2b91af">ManualResetEvent </SPAN>waitEvent = <SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">ManualResetEvent</SPAN>(<SPAN style="COLOR: blue">false</SPAN>);

<SPAN style="COLOR: #2b91af">Timer </SPAN>t;
<SPAN style="COLOR: #2b91af">Stopwatch </SPAN>watch;
<SPAN style="COLOR: #2b91af">TimerCallback </SPAN>callback;
<SPAN style="COLOR: blue">for </SPAN>(<SPAN style="COLOR: blue">int </SPAN>i = 0; i &lt; ParallelOperations; i++)
{
    callback = <SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">TimerCallback</SPAN>(
        o =&gt;
        {
            <SPAN style="COLOR: #2b91af">Stopwatch </SPAN>passedWatch = (<SPAN style="COLOR: #2b91af">Stopwatch</SPAN>)o;
            passedWatch.Stop();
            <SPAN style="COLOR: #2b91af">Console</SPAN>.WriteLine(<SPAN style="COLOR: #a31515">"Elapsed time: {0} msec"</SPAN>, 
                passedWatch.ElapsedMilliseconds);
            <SPAN style="COLOR: blue">if </SPAN>(<SPAN style="COLOR: #2b91af">Interlocked</SPAN>.Increment(<SPAN style="COLOR: blue">ref </SPAN>clientsDone) &gt;= <SPAN style="COLOR: blue">this</SPAN>.ParallelOperations)
            {
                waitEvent.Set();
            }
        });

    watch = <SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">Stopwatch</SPAN>();
    watch.Start();
    t = <SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">Timer</SPAN>(callback, watch, SleepTime, <SPAN style="COLOR: #2b91af">TimeSpan</SPAN>.FromMilliseconds(-1));
}

waitEvent.WaitOne(<SPAN style="COLOR: #2b91af">TimeSpan</SPAN>.FromSeconds(50));
<SPAN style="COLOR: green">// dispose of the timer and async event</SPAN></PRE><A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"></A><A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"></A>
<P>Running this code with 10 operations and a sleep of 10 sec leads to this output:</P>
<P>Elapsed time: 10010 msec <BR>Elapsed time: 10009 msec <BR>Elapsed time: 10010 msec <BR>Elapsed time: 10009 msec <BR>Elapsed time: 10011 msec <BR>Elapsed time: 10011 msec <BR>Elapsed time: 10011 msec <BR>Elapsed time: 10011 msec <BR>Elapsed time: 10011 msec <BR>Elapsed time: 10011 msec</P>
<P>(notice how the actual time is not 10 sec, but it differs slightly. If the system is in an overloaded state, the difference will be much higher. The same is true for the sync case).</P>
<P>This works, but let’s rewrite to be more in sync with the .NET FX <A href="http://msdn.microsoft.com/en-us/library/ms228963.aspx" mce_href="http://msdn.microsoft.com/en-us/library/ms228963.aspx">Asynchronous Programming</A> model. From msdn:</P>
<BLOCKQUOTE>
<P>An asynchronous operation that uses the <A href="http://msdn.microsoft.com/en-us/library/system.iasyncresult.aspx" mce_href="http://msdn.microsoft.com/en-us/library/system.iasyncresult.aspx">IAsyncResult</A> design pattern is implemented as two methods named BeginOperationName and EndOperationName that begin and end the asynchronous operation OperationName respectively. For example, the <A href="http://msdn.microsoft.com/en-us/library/system.io.filestream.aspx" mce_href="http://msdn.microsoft.com/en-us/library/system.io.filestream.aspx">FileStream</A> class provides the <A href="http://msdn.microsoft.com/en-us/library/system.io.filestream.beginread.aspx" mce_href="http://msdn.microsoft.com/en-us/library/system.io.filestream.beginread.aspx">BeginRead</A> and <A href="http://msdn.microsoft.com/en-us/library/system.io.filestream.endread.aspx" mce_href="http://msdn.microsoft.com/en-us/library/system.io.filestream.endread.aspx">EndRead</A> methods to asynchronously read bytes from a file. These methods implement the asynchronous version of the <A href="http://msdn.microsoft.com/en-us/library/system.io.filestream.read.aspx" mce_href="http://msdn.microsoft.com/en-us/library/system.io.filestream.read.aspx">Read</A> method.</P>
<P>After calling BeginOperationName, an application can continue executing instructions on the calling thread while the asynchronous operation takes place on a different thread. For each call to BeginOperationName, the application should also call EndOperationName to get the results of the operation.</P></BLOCKQUOTE>
<P>We can change our code to implement this pattern by defining an async result. To make my job easier, I took the abstract class AsyncResult.cs from one of the <A href="http://msdn.microsoft.com/en-us/library/ms751450.aspx" mce_href="http://msdn.microsoft.com/en-us/library/ms751450.aspx">WCF MSDN Samples</A> (download the samples, then go to the directory you saved them and look for WCFWFCardSpace\WCF\Basic\Contract\Service\Asynchronous\CS\library). This class implements the <A href="http://msdn.microsoft.com/en-us/library/system.iasyncresult.aspx" mce_href="http://msdn.microsoft.com/en-us/library/system.iasyncresult.aspx">IAsyncResult</A> interface.</P>
<P>Using this base class, I defined SleepAsyncResult to start the timer and complete the operation in callback (for simplicity, I always set completedAsync flag to true, this should be set accordingly in practice).</P><PRE class=code><SPAN style="COLOR: blue">class </SPAN><SPAN style="COLOR: #2b91af">SleepAsyncResult </SPAN>: <SPAN style="COLOR: #2b91af">AsyncResult
</SPAN>{
    <SPAN style="COLOR: #2b91af">Timer </SPAN>t;
    <SPAN style="COLOR: blue">readonly </SPAN><SPAN style="COLOR: #2b91af">TimeSpan </SPAN>sleepTime;

    <SPAN style="COLOR: blue">public </SPAN>SleepAsyncResult(<SPAN style="COLOR: #2b91af">TimeSpan </SPAN>sleepTime, <SPAN style="COLOR: #2b91af">AsyncCallback </SPAN>callback, <SPAN style="COLOR: blue">object </SPAN>state)
        : <SPAN style="COLOR: blue">base</SPAN>(callback, state)
    {
        <SPAN style="COLOR: blue">this</SPAN>.sleepTime = sleepTime;
        <SPAN style="COLOR: blue">this</SPAN>.Start();
    }

    <SPAN style="COLOR: blue">public void </SPAN>Start()
    {
        <SPAN style="COLOR: #2b91af">Stopwatch </SPAN>watch = <SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">Stopwatch</SPAN>();
        <SPAN style="COLOR: #2b91af">TimerCallback </SPAN>cb = <SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">TimerCallback</SPAN>(
           o =&gt;
           {
               watch.Stop();
               <SPAN style="COLOR: #2b91af">Console</SPAN>.WriteLine(<SPAN style="COLOR: #a31515">"Elapsed time: {0} msec"</SPAN>,
                   watch.ElapsedMilliseconds);
               <SPAN style="COLOR: blue">this</SPAN>.Complete(<SPAN style="COLOR: blue">false</SPAN>);
               t.Dispose();
           });

        watch.Start();
        t = <SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">Timer</SPAN>(cb, <SPAN style="COLOR: blue">null</SPAN>, <SPAN style="COLOR: blue">this</SPAN>.sleepTime, <SPAN style="COLOR: #2b91af">TimeSpan</SPAN>.FromMilliseconds(-1));
    }

    <SPAN style="COLOR: blue">public static void </SPAN>End(<SPAN style="COLOR: #2b91af">IAsyncResult </SPAN>result)
    {
        <SPAN style="COLOR: #2b91af">AsyncResult</SPAN>.End&lt;<SPAN style="COLOR: #2b91af">SleepAsyncResult</SPAN>&gt;(result);
    }
}</PRE>
<P>Then we write the Begin/End methods using this async result:</P><PRE class=code><SPAN style="COLOR: blue">int </SPAN>clientsDone = 0;
<SPAN style="COLOR: #2b91af">ManualResetEvent </SPAN>waitEvent = <SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">ManualResetEvent</SPAN>(<SPAN style="COLOR: blue">false</SPAN>);

<SPAN style="COLOR: #2b91af">IAsyncResult </SPAN>BeginSleep()
{
    <STRONG><SPAN style="COLOR: blue">return new </SPAN><SPAN style="COLOR: #2b91af">SleepAsyncResult</SPAN>(SleepTime, EndSleep, <SPAN style="COLOR: blue">null</SPAN>);</STRONG> 
}

<SPAN style="COLOR: blue">void </SPAN>EndSleep(<SPAN style="COLOR: #2b91af">IAsyncResult </SPAN>result)
{
<STRONG>    <SPAN style="COLOR: #2b91af">SleepAsyncResult</SPAN>.End(result);</STRONG>
    <SPAN style="COLOR: blue">if </SPAN>(<SPAN style="COLOR: #2b91af">Interlocked</SPAN>.Increment(<SPAN style="COLOR: blue">ref this</SPAN>.clientsDone) &gt;= <SPAN style="COLOR: blue">this</SPAN>.ParallelOperations)
    {
        <SPAN style="COLOR: blue">this</SPAN>.waitEvent.Set();
    }
}</PRE><A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"></A>
<P>Implementing the Sleep becomes dead simple. </P><PRE class=code><SPAN style="COLOR: blue">for </SPAN>(<SPAN style="COLOR: blue">int </SPAN>i = 0; i &lt; ParallelOperations; i++)
{
    <SPAN style="COLOR: blue">this</SPAN>.BeginSleep();
}

waitEvent.WaitOne(<SPAN style="COLOR: #2b91af">TimeSpan</SPAN>.FromSeconds(50));</PRE>
<P>Et voila! We are now sleeping asynchronously!</P>
<P>Note:</P>
<P>The code presented is just for demo purposes and I don’t recommend using it in production. Distributed code should be very careful with exception handling, multithreading issues, sharing resources, leaking resources etc. </P>]]></content:encoded>
    </item>
    <item>
      <title>Explorer crash when installing Windows Live – How do you bring it back?</title>
      <link>https://docs.microsoft.com/archive/blogs/oanapl/explorer-crash-when-installing-windows-live-how-do-you-bring-it-back</link>
      <pubDate>Mon, 01 Feb 2010 16:04:00 GMT</pubDate>
      <dc:creator><![CDATA[OanaPlaton]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/oanapl/2010/02/01/explorer-crash-when-installing-windows-live-how-do-you-bring-it-back/</guid>
      <description><![CDATA[For quite a while I’ve been using Live Writer to edit and publish blogs and I am quite satisfied...]]></description>
      <content:encoded><![CDATA[<P>For quite a while I’ve been using Live Writer to edit and publish blogs and I am quite satisfied with it (there are some quirks, no doubt about it, but it mostly works).</P>
<P>I recently tried to install Live Writer on my newest Win7 box and I had a most unpleasant experience. </P>
<P>First, the installer told me there are a couple of programs that should be closed in order for the installation to proceed. It also offered me the option to ignore them – which I gladly chose. After trying really hard for a couple of minutes, it went belly up with the error code 0x80070643 (very helpful!)</P>
<P mce_keep="true"><IMG title="Windows Live installation error" style="WIDTH: 647px; HEIGHT: 548px" height=548 alt="Windows Live installation error" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Components.PostAttachments/00/09/95/66/94/LiveWriter-Error.jpg" original-url="http://blogs.msdn.com/photos/oanapl/images/9956694/original.aspx" width=647 mce_src="http://blogs.msdn.com/photos/oanapl/images/9956694/original.aspx"></P>
<P>So I try again. This time I ignore the “ignore” option. The other option: the installer gracefully offers to close some programs that are in the way for me. Cool, says I, go right ahead (I hate when installers give you a list of programs and it’s your business to go through it and kill them – what a waste of time!). So the installer starts bringing down programs – there goes my music, there goes this, there goes that, and … surprise, surprise … there goes Explorer. Which means no Start button, no task bar no nothing. Now, looking back, I must admit that I didn’t pay any attention to the list of programs the installer “needed” to close, but at a backward glance it was huge (check the picture). As my excuse, I usually go very fast through these installation steps – aka I don’t read them. </P>
<P><IMG title="Windows Live - close programs" style="WIDTH: 647px; HEIGHT: 548px" height=548 alt="Windows Live - close programs" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Components.PostAttachments/00/09/95/66/92/LiveWriter.jpg" original-url="http://blogs.msdn.com/photos/oanapl/images/9956692/original.aspx" width=647 mce_src="http://blogs.msdn.com/photos/oanapl/images/9956692/original.aspx"></P>
<P>So here I am, no Explorer in sight (Explorer is a Windows process that starts at startup and remains up). How do I bring it back? With a command prompt open, piece of cake: go though the open programs using Alt+Tab until I land on the Command Prompt and then start explorer with the command “explorer.exe”. </P>
<P>As it was, I didn’t have a command prompt open. Next option: task manager. To open task manager, use the shortcut Ctrl+Shift+Escape (I prefer it to Alt+Ctrl+Delete –&gt; open Task Manger). In task manager go to File –&gt;&nbsp; New Task and create a new task for Explorer.exe. Et voila! The task bar, the start button are all back. This method is useful any time when Explorer crashes (as an alternative for reboot).</P>
<P><IMG title="Task manager" style="WIDTH: 438px; HEIGHT: 276px" height=276 alt="Task manager" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Components.PostAttachments/00/09/95/66/95/TaskManager-StartTask.jpg" original-url="http://blogs.msdn.com/photos/oanapl/images/9956695/original.aspx" width=438 mce_src="http://blogs.msdn.com/photos/oanapl/images/9956695/original.aspx"></P>
<P>So what about my Live Writer installation? I hate to admit, but I gave up for now. I’ll try again tomorrow, maybe the Live gods are on my side. All in all,&nbsp;bad mark for the Windows Live user experience.</P>]]></content:encoded>
    </item>
    <item>
      <title>WCF Communication Objects states Cheat Sheet</title>
      <link>https://docs.microsoft.com/archive/blogs/oanapl/wcf-communication-objects-states-cheat-sheet</link>
      <pubDate>Fri, 30 Oct 2009 15:16:46 GMT</pubDate>
      <dc:creator><![CDATA[OanaPlaton]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/oanapl/2009/10/30/wcf-communication-objects-states-cheat-sheet/</guid>
      <description><![CDATA[WCF is all about communication objects – channels, listeners, factories, all implement the...]]></description>
      <content:encoded><![CDATA[<p>WCF is all about communication objects – channels, listeners, factories, all implement the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.icommunicationobject.aspx">ICommunicationObject</a> interface (some through the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.communicationobject.aspx">CommunicationObject</a> class). This provides a base implementation for the basic state machine states and transitions common to all communication-oriented object.</p>  <p>At any given point in time, the communication objects find themselves in a <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.communicationstate.aspx">CommunicationState</a>. Here is a diagram with the states and the transitions:</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/oanapl/WindowsLiveWriter/WCFCommunicationObjectsstatesandtransiti_A1F7/image_2.png" original-url="http://blogs.msdn.com/blogfiles/oanapl/WindowsLiveWriter/WCFCommunicationObjectsstatesandtransiti_A1F7/image_2.png"><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="482" alt="image" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/oanapl/WindowsLiveWriter/WCFCommunicationObjectsstatesandtransiti_A1F7/image_thumb.png" original-url="http://blogs.msdn.com/blogfiles/oanapl/WindowsLiveWriter/WCFCommunicationObjectsstatesandtransiti_A1F7/image_thumb.png" width="422" border="0" /></a></p>  <p>When we look at a communication object in a debugger, we see something like this (some columns and internal objects removed for brevity reasons):</p>  <p>Name: System.ServiceModel.Channels.ServiceChannel</p>  <p>Fields:</p>  <table cellspacing="0" cellpadding="0" border="0"><tbody>     <tr>       <td width="142">Type</td>        <td width="64">VT</td>        <td width="118">Value</td>        <td width="208">Name</td>     </tr>      <tr>       <td>System.Boolean</td>        <td>1</td>        <td>0</td>        <td>aborted</td>     </tr>      <tr>       <td>System.Boolean</td>        <td>1</td>        <td>0</td>        <td>closeCalled</td>     </tr>      <tr>       <td>System.Boolean</td>        <td>1</td>        <td>0</td>        <td>onClosingCalled</td>     </tr>      <tr>       <td>System.Boolean</td>        <td>1</td>        <td>0</td>        <td>onClosedCalled</td>     </tr>      <tr>       <td>System.Boolean</td>        <td>1</td>        <td>1</td>        <td>onOpeningCalled</td>     </tr>      <tr>       <td>System.Boolean</td>        <td>1</td>        <td>1</td>        <td>onOpenedCalled</td>     </tr>      <tr>       <td>System.Boolean</td>        <td>1</td>        <td>0</td>        <td>raisedClosed</td>     </tr>      <tr>       <td>System.Boolean</td>        <td>1</td>        <td>0</td>        <td>raisedClosing</td>     </tr>      <tr>       <td>System.Boolean</td>        <td>1</td>        <td>0</td>        <td>raisedFaulted</td>     </tr>      <tr>       <td>System.Boolean</td>        <td>1</td>        <td>0</td>        <td>traceOpenAndClose</td>     </tr>      <tr>       <td>System.Object</td>        <td>0</td>        <td>000000000131d8e0</td>        <td>eventSender</td>     </tr>      <tr>       <td><font color="#004000"><strong>System.Int32</strong></font></td>        <td><font color="#004000"><strong>1</strong></font></td>        <td><font color="#004000"><strong>2</strong></font></td>        <td><font color="#004000"><strong>state</strong></font></td>     </tr>      <tr>       <td>System.EventHandler</td>        <td>0</td>        <td>0</td>        <td>Closed</td>     </tr>      <tr>       <td>System.EventHandler</td>        <td>0</td>        <td>0</td>        <td>Closing</td>     </tr>      <tr>       <td>System.EventHandler</td>        <td>0</td>        <td>0</td>        <td>Faulted</td>     </tr>      <tr>       <td>System.EventHandler</td>        <td>0</td>        <td>0</td>        <td>Opened</td>     </tr>      <tr>       <td>System.EventHandler</td>        <td>0</td>        <td>0</td>        <td>Opening</td>     </tr>   </tbody></table> <font size="2">   <p>     <br /></p> In our example, the communication object is in state 2. How does that translate to the actual states? To tell you the truth, I always take some time to map the number to the state, so I started using this cheat sheet:</font>   <p><span style="color: blue">public enum </span><span style="color: #2b91af">CommunicationState      <br /></span>{     <br />&#160;&#160;&#160; Created = 0,     <br />&#160;&#160;&#160; Opening = 1,     <br />&#160;&#160;&#160; Opened = 2,     <br />&#160;&#160;&#160; Closing = 3,     <br />&#160;&#160;&#160; Closed = 4,     <br />&#160;&#160;&#160; Faulted = 5     <br />}</p>  <p>So in our case, the ServiceChannel is Opened. We could identify the state by looking at the other variable – if close called or aborted was called, we can only by in state 4 or 5 and so on. But the cheat sheet makes it simple. </p>  <p>Hope you find it useful!</p>]]></content:encoded>
    </item>
    <item>
      <title>Microsoft Women’s Leadership and Development Conference</title>
      <link>https://docs.microsoft.com/archive/blogs/oanapl/microsoft-womens-leadership-and-development-conference</link>
      <pubDate>Thu, 29 Oct 2009 09:04:00 GMT</pubDate>
      <dc:creator><![CDATA[OanaPlaton]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/oanapl/2009/10/29/microsoft-womens-leadership-and-development-conference/</guid>
      <description><![CDATA[Every other year, Microsoft organizes a conference for women. Why? Because it recognizes that women...]]></description>
      <content:encoded><![CDATA[<P>Every other year, Microsoft organizes a conference for women. Why? Because it recognizes that women more than men feel the need to get inspired by listening to some sessions oriented towards the emotional space and, more to the point, women feel the need to talk to other women, find out what issues those women have and feel that they are not alone. Well, this is more why women participate at the conference. But the conference benefits Microsoft as well, because inspired women are more creative, work harder and more efficiently. </P>
<P>This year's theme was “Opportunity In Change”. The planning team was formed by volunteers that did a great job – the organization was really well planned, the sessions and the speakers well chosen and from registration to food and networking events everything went flawlessly. </P>
<P>And I want to share with you some of the things I learned. The conference took 2 days and a half. In the 2 full days, there were a couple of sessions going in parallel. Of course, I chose the sessions that seemed more interesting to me. But I learned that the content and the speaker are not enough to make it a good presentation; in order to inspire you, the information and the delivery must match some internal struggle you are dealing with. There were sessions contained the right info, where the speaker did all the right things to attract and connect to the audience, but that didn’t honestly impress me. And sessions that I found heart reaching did nothing for other women.</P>
<P>The session I liked most was one by <A href="http://www.nancydsolomon.com/" mce_href="http://www.nancydsolomon.com/"><FONT color=#0000cc>Nancy D. Solomon</FONT></A>, talking about impact. As a writer, speaker, facilitator and executive coach, Nancy has built her career around one simple question: “What did you come here to do, and are you getting it done?” In this session, she gave us the definition of impact -&nbsp; impact is the fingerprint, not the finger that left the print. Put it simply, it's the consequence of what you do/say/think that matters and not the action/word/thought per se. This was a good point for me, as I have the tendency to look at actions instead of the impact of those actions.</P>
<P>Another good point: people usually don't know what they want, because nobody asked them and, more importantly, they never asked themselves. This is quite applicable inside Microsoft. I know people that do things because they think that that is what they should be doing: I'll take this job because I'll be better positioned for the next , I'll do this because it will increase my visibility, etc. Very few ask: <B>what do I really want</B>? She told us about a study that looks at how engaged the employees are. I believe I found <A href="http://www.nbrii.com/blog/EngagedOrDisengagedThatIsTheQuestion.aspx" mce_href="http://www.nbrii.com/blog/EngagedOrDisengagedThatIsTheQuestion.aspx"><FONT color=#0000cc>the study</FONT></A>, and it says:</P>
<BLOCKQUOTE>
<P>The <A href="http://gmj.gallup.com/" mce_href="http://gmj.gallup.com/"><FONT color=#0000cc>Gallup Management Journal</FONT></A> publishes a semi-annual Employee Engagement Index. Recent results for the U.S. indicated that: </P>
<P>•&nbsp;&nbsp;&nbsp; Only 29% of employees are actively engaged in their jobs and feel a passion for their work and a connection to their company. <BR>•&nbsp;&nbsp;&nbsp; Over half of employees (54%) are not engaged in their work and have essentially “checked out.” They are going through the motions; putting in their time and keeping busy but not working with passion. <BR>•&nbsp;&nbsp;&nbsp; The remaining employees, 17%, are actively disengaged. Such employees act on their unhappiness and undermine the work their engaged co-workers are trying to accomplish. </P></BLOCKQUOTE>
<P>When it comes to career progress, Nancy sais a lot of people think that personal satisfaction and achievement are on the same axis, and therefore in order to get one, the other will be neglected, Instead, she argues that people move an 2 axes, so it's possible to move to accomplish both if you do what you like.</P>
<P><A href="file:///C:/Users/oanapl/AppData/Local/Temp/1/WindowsLiveWriter1286139640/supfiles127BBA89/image[2].png" mce_href="file:///C:/Users/oanapl/AppData/Local/Temp/1/WindowsLiveWriter1286139640/supfiles127BBA89/image[2].png"></A><IMG title="Personal satisfaction / achievement graph" style="WIDTH: 288px; HEIGHT: 288px" height=288 alt="Personal satisfaction / achievement graph" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Components.PostAttachments/00/09/91/47/92/CareerTrack.jpg" original-url="http://blogs.msdn.com/photos/oanapl/images/9914792/original.aspx" width=288 mce_src="http://blogs.msdn.com/photos/oanapl/images/9914792/original.aspx">&nbsp;</P>
<P>Another session I liked was <A href="http://bonniestjohn.com/" mce_href="http://bonniestjohn.com/"><FONT color=#0000cc>Bonnie St John</FONT></A>’s one, about achieving peak performance in spite of the fact that life is sometimes tough. This was a very inspiring story: Bonnie had a most interesting life:</P>
<BLOCKQUOTE>
<P>Due to a condition called pre-femoral focal disorder, Bonnie had her right leg amputated above the knee when she was only 5 years old. Despite this challenge, she went on to excel as an athlete, a scholar, a mother, and a businesswoman. After graduating <A href="http://en.wikipedia.org/wiki/Magna_Cum_Laude" mce_href="http://en.wikipedia.org/wiki/Magna_Cum_Laude"><FONT color=#0000cc>Magna Cum Laude</FONT></A> from <A href="http://en.wikipedia.org/wiki/Harvard_University" mce_href="http://en.wikipedia.org/wiki/Harvard_University"><FONT color=#0000cc>Harvard University</FONT></A> in 1986, Bonnie won a <A href="http://en.wikipedia.org/wiki/Rhodes_Scholarship" mce_href="http://en.wikipedia.org/wiki/Rhodes_Scholarship"><FONT color=#0000cc>Rhodes Scholarship</FONT></A> to <A href="http://en.wikipedia.org/wiki/Oxford_University" mce_href="http://en.wikipedia.org/wiki/Oxford_University"><FONT color=#0000cc>Oxford University</FONT></A> where she earned her M.Litt. Degree in Economics in 1990. She worked in the White House during the <A href="http://en.wikipedia.org/wiki/Clinton_administration" mce_href="http://en.wikipedia.org/wiki/Clinton_administration"><FONT color=#0000cc>Clinton administration</FONT></A> as a Director for the <A href="http://en.wikipedia.org/wiki/National_Economic_Council" mce_href="http://en.wikipedia.org/wiki/National_Economic_Council"><FONT color=#0000cc>National Economic Council</FONT></A>, and is currently CEO of Courageous Spirit, Inc. Bonnie provides inspirational and motivational keynote speeches to dozens of business organizations annually, touching literally tens of thousands of lives each year with her messages of strength and courage.</P></BLOCKQUOTE>
<P>The most important take away from her presentation was that if people often compare life with sports, nowadays, companies are better compared with disabilities sports (due to the economic situation that’s not quite pink – in case you haven’t noticed). Companies need to thrive despite their disabilities; same for people. About the people she competed with at Paralympics, she said: "what they don't have doesn't matter". What matters is to do the best with what you have. </P>
<P>Instead of playing it safe to stay up all the time, it's more important to learn how to get up fast after you fall. </P>
<P>Now, most of the sessions touched upon some common themes:</P>
<UL>
<LI>Be yourself, and be the best you can be. 
<LI>Take risks, get out of your comfort zone. 
<LI>Enjoy the small moments of life, take time regularly to feel joy and delight. 
<LI>Find and follow your purpose in life to be more efficient. 
<LI>Soft skills impact business performance. A study shows that people give in average 85% off what they could be giving on the job; they put in more depending on the direct manager’s soft skills and the soft skills of people around them. </LI></UL>
<P>I also loved the quote <A href="http://www.dynamicinteractions.com/about/president" mce_href="http://www.dynamicinteractions.com/about/president"><FONT color=#0000cc>Mitch Shepard</FONT></A> shared with us at her session about Emotional Intelligence: <STRONG>The cure for exertion is not rest, it’s living wholeheartedly</STRONG>. I believe I’ll make this my motto.</P>
<P>Hope this gives you an idea of what happened at the Microsoft conference. Like <A href="http://www.microsoft.com/presspass/exec/brummel/default.aspx" mce_href="http://www.microsoft.com/presspass/exec/brummel/default.aspx"><FONT color=#0000cc>Lisa Brummel</FONT></A>, Microsoft’s senior VP for HR said at the conference, there are a lot of opportunities for personal development and learning activities in Microsoft; if people don’t know about them, it’s management’s fault; if they know and don’t take advantage of them, it’s their own fault. The women’s conference is an opportunity for women to network and connect with other women, learn and get inspired by different opinions, opportunities, and a variety of experiences. If your company organizes something similar, I highly recommend going.</P>]]></content:encoded>
    </item>
    <item>
      <title>ETW (Event Tracing For Windows) – what it is and useful tools</title>
      <link>https://docs.microsoft.com/archive/blogs/oanapl/etw-event-tracing-for-windows-what-it-is-and-useful-tools</link>
      <pubDate>Tue, 04 Aug 2009 19:55:00 GMT</pubDate>
      <dc:creator><![CDATA[OanaPlaton]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/oanapl/2009/08/04/etw-event-tracing-for-windows-what-it-is-and-useful-tools/</guid>
      <description><![CDATA[Event Tracing for Windows is the standard way to trace used by all features of Windows. Like the...]]></description>
      <content:encoded><![CDATA[<P>Event Tracing for Windows is the standard way to trace used by all features of Windows. Like the article <A href="http://msdn.microsoft.com/en-us/magazine/cc163437.aspx" mce_href="http://msdn.microsoft.com/en-us/magazine/cc163437.aspx"><FONT color=#0000cc>Improve Debugging And Performance Tuning With ETW</FONT></A> explains, ETW is </P>
<BLOCKQUOTE>
<P>“a general-purpose, high-speed tracing facility provided by the operating system. Using a buffering and logging mechanism implemented in the kernel, ETW provides a tracing mechanism for events raised by both user-mode applications and kernel-mode device drivers. Additionally, ETW gives you the ability to enable and disable logging dynamically, making it easy to perform detailed tracing in production environments without requiring reboots or application restarts. The logging mechanism uses per-processor buffers that are written to disk by an asynchronous writer thread. This allows large-scale server applications to write events with minimum disturbance.”</P></BLOCKQUOTE>
<P>The article above explains the ETW architecture (that suffered great improvements since Windows Vista), explaining events and sessions, event providers and event consumers. As a quick overview: an <STRONG>event provider </STRONG>writes events to ETW sessions (it can be any user-mode application, managed application, driver etc). When events are written, ETW adds more info about the time it took place, process and thread ID that generated it, processor number, and CPU usage data of the logging thread. This info is used by the <STRONG>event consumers </STRONG>- application that reads log files or listens to a session for real time events and processes them. More about providers at <A href="http://blogs.msdn.com/sudeepg/archive/2009/03/01/etw-trace-providers-when-to-use-what.aspx" mce_href="http://blogs.msdn.com/sudeepg/archive/2009/03/01/etw-trace-providers-when-to-use-what.aspx"><FONT color=#0000cc>ETW Trace Providers - When to use what</FONT></A>.</P>
<P>Since Windows Vista, the event provider APIs are simpler to use and offer richer functionality (like same way to use trace and event logs). To register as an ETW provider, software components need to provide a GUID as a unique identifier and a callback that will be invoked when notifications are enabled. When enabling a provider, a controller can specify </P>
<P>- a level (1-byte integer) – used to show the severity or verbosity of events (eg. verbose, info, error, critical)</P>
<P>- keywords (8-byte bit masks) – indicate subcomponents in a provider, so subcomponents can be enabled separately.</P>
<P>.Net Framework offers a managed ETW provider API (see <A href="http://msdn.microsoft.com/en-us/library/system.diagnostics.eventing.aspx" mce_href="http://msdn.microsoft.com/en-us/library/system.diagnostics.eventing.aspx"><FONT color=#0000cc>System.Diagnostics.Eventing Namespace</FONT></A>).</P>
<P>Once a provider is installed, users can collect events from the provider using the <A href="http://technet.microsoft.com/en-us/library/cc753820(WS.10).aspx" mce_href="http://technet.microsoft.com/en-us/library/cc753820(WS.10).aspx"><FONT color=#0000cc>logman tool</FONT></A> or <A href="http://technet.microsoft.com/en-us/library/cc722173(WS.10).aspx" mce_href="http://technet.microsoft.com/en-us/library/cc722173(WS.10).aspx"><FONT color=#0000cc>Reliability and Performance Monitor</FONT></A> (Perfmon in Vista and above). The Event Viewer offers another means for collecting and viewing events. Logman is a controller that offers the following options:</P>
<BLOCKQUOTE>
<P><A href="http://technet.microsoft.com/en-us/library/cc788102(WS.10).aspx" mce_href="http://technet.microsoft.com/en-us/library/cc788102(WS.10).aspx"><FONT color=#0000cc>logman create</FONT></A> - Create a counter, trace, configuration data collector, or API.</P>
<P><A href="http://technet.microsoft.com/en-us/library/cc788030(WS.10).aspx" mce_href="http://technet.microsoft.com/en-us/library/cc788030(WS.10).aspx"><FONT color=#0000cc>logman query</FONT></A> - Query data collector properties.</P>
<P><A href="http://technet.microsoft.com/en-us/library/cc788121(WS.10).aspx" mce_href="http://technet.microsoft.com/en-us/library/cc788121(WS.10).aspx"><FONT color=#0000cc>logman start | stop</FONT></A> - Start or stop data collection.</P>
<P><A href="http://technet.microsoft.com/en-us/library/cc788120(WS.10).aspx" mce_href="http://technet.microsoft.com/en-us/library/cc788120(WS.10).aspx"><FONT color=#0000cc>logman delete</FONT></A> - Delete an existing data collector.</P>
<P><A href="http://technet.microsoft.com/en-us/library/cc785463(WS.10).aspx" mce_href="http://technet.microsoft.com/en-us/library/cc785463(WS.10).aspx"><FONT color=#0000cc>logman update</FONT></A> - Update the properties of an existing data collector.</P>
<P><A href="http://technet.microsoft.com/en-us/library/cc785450(WS.10).aspx" mce_href="http://technet.microsoft.com/en-us/library/cc785450(WS.10).aspx"><FONT color=#0000cc>logman import | export</FONT></A> - Import a data collector set from an XML file or export a data collector set to an XML file.</P></BLOCKQUOTE>
<P>To read more about logman, try <A href="http://blogs.technet.com/askperf/archive/2008/05/13/two-minute-drill-logman-exe.aspx" mce_href="http://blogs.technet.com/askperf/archive/2008/05/13/two-minute-drill-logman-exe.aspx"><FONT color=#0000cc>Two Minute Drill: LOGMAN.EXE</FONT></A>.</P>
<P><A href="http://technet.microsoft.com/en-us/library/bb490959.aspx" mce_href="http://technet.microsoft.com/en-us/library/bb490959.aspx"><FONT color=#0000cc>Tracerpt</FONT></A> can be used to process event trace logs or real-time data from instrumented event trace providers. It generates trace analysis reports and <STRONG>CSV</STRONG> (comma-delimited) files for the events generated. <A href="http://www.microsoft.com/downloads/details.aspx?displaylang=en&amp;FamilyID=890cd06b-abf8-4c25-91b2-f8d975cf8c07" mce_href="http://www.microsoft.com/downloads/details.aspx?displaylang=en&amp;FamilyID=890cd06b-abf8-4c25-91b2-f8d975cf8c07"><FONT color=#0000cc>LogParser 2.2</FONT></A> also knows to parse ETW events. </P>
<P>There are other tools that can help with event logging information, like <A href="http://msdn.microsoft.com/en-us/library/aa969767.aspx#event_trace" mce_href="http://msdn.microsoft.com/en-us/library/aa969767.aspx#event_trace"><FONT color=#0000cc>Event trace</FONT></A>&nbsp;and <A href="http://msdn.microsoft.com/en-us/library/aa969767.aspx#event_trace" mce_href="http://msdn.microsoft.com/en-us/library/aa969767.aspx#event_trace"><FONT color=#0000cc>ETW Trace Viewer</FONT></A>.</P>
<P>To see an example of how to use ETW, read <A href="http://blogs.msdn.com/sudeepg/archive/2009/02/25/capturing-and-analyzing-an-etw-trace-event-tracing-for-windows.aspx" mce_href="http://blogs.msdn.com/sudeepg/archive/2009/02/25/capturing-and-analyzing-an-etw-trace-event-tracing-for-windows.aspx"><FONT color=#0000cc>Capturing and analyzing an ETW Trace</FONT></A>&nbsp;article.</P>
<P>The tools I mentioned so far are useful to&nbsp;get and analyze the traces. From a developer point of view, if you want to&nbsp;generate traces for your software application, you can create a trace source and then write events to it. Using an ETW listener offers huge performance improvements over other trace listeners. For a managed application that uses the existing trace listeners or other custom listeners, the only change is to switch to the EventProviderTraceListener (a configuration change).&nbsp;For a provider with GUID 4a632b62-b345-42d4-56dc-g1sac9hfjr14 (generated and installed&nbsp;by you), the config file can look like this:</P><PRE class=code><SPAN style="COLOR: blue">&lt;?</SPAN><SPAN style="COLOR: #a31515">xml </SPAN><SPAN style="COLOR: red">version</SPAN><SPAN style="COLOR: blue">=</SPAN>"<SPAN style="COLOR: blue">1.0</SPAN>" <SPAN style="COLOR: red">encoding</SPAN><SPAN style="COLOR: blue">=</SPAN>"<SPAN style="COLOR: blue">utf-8</SPAN>" <SPAN style="COLOR: blue">?&gt;
&lt;</SPAN><SPAN style="COLOR: #a31515">configuration</SPAN><SPAN style="COLOR: blue">&gt;
  &lt;</SPAN><SPAN style="COLOR: #a31515">system.diagnostics</SPAN><SPAN style="COLOR: blue">&gt;
    &lt;</SPAN><SPAN style="COLOR: #a31515">sources</SPAN><SPAN style="COLOR: blue">&gt;
      &lt;</SPAN><SPAN style="COLOR: #a31515">source </SPAN><SPAN style="COLOR: red">name</SPAN><SPAN style="COLOR: blue">=</SPAN>"<SPAN style="COLOR: blue">MySourceName</SPAN>" <SPAN style="COLOR: red">switchName</SPAN><SPAN style="COLOR: blue">=</SPAN>"<SPAN style="COLOR: blue">mySwitch</SPAN>" 
              <SPAN style="COLOR: red">switchType</SPAN><SPAN style="COLOR: blue">=</SPAN>"<SPAN style="COLOR: blue">System.Diagnostics.SourceSwitch</SPAN>"<SPAN style="COLOR: blue">&gt;
        &lt;</SPAN><SPAN style="COLOR: #a31515">listeners</SPAN><SPAN style="COLOR: blue">&gt;
          &lt;</SPAN><SPAN style="COLOR: #a31515">remove </SPAN><SPAN style="COLOR: red">name</SPAN><SPAN style="COLOR: blue">=</SPAN>"<SPAN style="COLOR: blue">Default</SPAN>" <SPAN style="COLOR: blue">/&gt;
          &lt;</SPAN><SPAN style="COLOR: #a31515">add </SPAN><SPAN style="COLOR: red">name</SPAN><SPAN style="COLOR: blue">=</SPAN>"<SPAN style="COLOR: blue">MyEventProviderTraceListener</SPAN>"
               <SPAN style="COLOR: red">type</SPAN><SPAN style="COLOR: blue">=</SPAN>"<SPAN style="COLOR: blue">System.Diagnostics.Eventing.EventProviderTraceListener, 
               System.Core, Version=3.5.0.0, Culture=neutral, 
               PublicKeyToken=b77a5c561934e089</SPAN>"
               <SPAN style="COLOR: red">initializeData</SPAN><SPAN style="COLOR: blue">=</SPAN>"<SPAN style="COLOR: blue">4a632b62-b345-42d4-56dc-g1sac9hfjr14</SPAN>" <SPAN style="COLOR: blue">/&gt;
        &lt;/</SPAN><SPAN style="COLOR: #a31515">listeners</SPAN><SPAN style="COLOR: blue">&gt;
      &lt;/</SPAN><SPAN style="COLOR: #a31515">source</SPAN><SPAN style="COLOR: blue">&gt;
    &lt;/</SPAN><SPAN style="COLOR: #a31515">sources</SPAN><SPAN style="COLOR: blue">&gt;
    </SPAN><SPAN style="COLOR: blue">&lt;</SPAN><SPAN style="COLOR: #a31515">trace </SPAN><SPAN style="COLOR: red">autoflush</SPAN><SPAN style="COLOR: blue">=</SPAN>"<SPAN style="COLOR: blue">true</SPAN>" <SPAN style="COLOR: red">indentsize</SPAN><SPAN style="COLOR: blue">=</SPAN>"<SPAN style="COLOR: blue">4</SPAN>"<SPAN style="COLOR: blue">/&gt;
  &lt;/</SPAN><SPAN style="COLOR: #a31515">system.diagnostics</SPAN><SPAN style="COLOR: blue">&gt;
&lt;/</SPAN><SPAN style="COLOR: #a31515">configuration</SPAN><SPAN style="COLOR: blue">&gt;</SPAN></PRE><A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"></A>
<P>But more about this in a future post. Stay tuned!</P>]]></content:encoded>
    </item>
    <item>
      <title>Design patterns: How do you notify components about events that happen in different components?</title>
      <link>https://docs.microsoft.com/archive/blogs/oanapl/design-patterns-how-do-you-notify-components-about-events-that-happen-in-different-components</link>
      <pubDate>Thu, 02 Jul 2009 20:57:00 GMT</pubDate>
      <dc:creator><![CDATA[OanaPlaton]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/oanapl/2009/07/02/design-patterns-how-do-you-notify-components-about-events-that-happen-in-different-components/</guid>
      <description><![CDATA[I recently had to solve these kind of requirements: some components execute actions and at some...]]></description>
      <content:encoded><![CDATA[<P>I recently had to solve these kind of requirements: some components execute actions and at some point in time need to notify other components that certain events happened, so the other components can execute code related to these events. For example, class A executes method ChangeStateOfObjectX, and needs to notify class B when X is changed; then B does a certain action (for example, increments a perf counter that illustrates the number of inner objects in X, or writes an event entry or plays a song) when it’s notified. Let’s call class A the Events Generator (because it generates events :)) and B the Events Consumer (because it takes actions in response to the events generated by A). </P>
<P>Let’s take a concrete example: the class ProjectProgressTracker keeps track of a project progress – this is the Events Generator; when a task is added, completed or blocked (all internal states that the user doesn’t have access to), it needs to let a monitor system know – the Events Consumer. </P><PRE class=code><SPAN style="COLOR: green">// generates events when a task is added, completed, blocked etc
</SPAN><SPAN style="COLOR: blue">class </SPAN><SPAN style="COLOR: #2b91af">ProjectProgressTracker </SPAN>{
    <SPAN style="COLOR: blue">static </SPAN><SPAN style="COLOR: #2b91af">Random </SPAN>r = <SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">Random</SPAN>((<SPAN style="COLOR: blue">int</SPAN>)<SPAN style="COLOR: #2b91af">DateTime</SPAN>.Now.Ticks);
    <SPAN style="COLOR: #2b91af">List</SPAN>&lt;<SPAN style="COLOR: #2b91af">Task</SPAN>&gt; tasks;

    <SPAN style="COLOR: blue">public </SPAN>ProjectProgressTracker(<SPAN style="COLOR: blue">string</SPAN>[] initialTasks) {
        <SPAN style="COLOR: blue">this</SPAN>.tasks = <SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">List</SPAN>&lt;<SPAN style="COLOR: #2b91af">Task</SPAN>&gt;();
        <SPAN style="COLOR: blue">if </SPAN>(initialTasks != <SPAN style="COLOR: blue">null</SPAN>)
            <SPAN style="COLOR: blue">foreach </SPAN>(<SPAN style="COLOR: blue">string </SPAN>s <SPAN style="COLOR: blue">in </SPAN>initialTasks)
                <SPAN style="COLOR: blue">this</SPAN>.tasks.Add(<SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">Task</SPAN>(s));
    }

    <SPAN style="COLOR: blue">public void </SPAN>NextAction() {
        <SPAN style="COLOR: blue">int </SPAN>randomNumber = r.Next(10);
        <SPAN style="COLOR: blue">if </SPAN>(randomNumber &lt; 3)
            <SPAN style="COLOR: green">// a new task was added
        </SPAN><SPAN style="COLOR: blue">else if </SPAN>(randomNumber &gt; 6)
            <SPAN style="COLOR: green">// a task is blocked
        </SPAN><SPAN style="COLOR: blue">else
</SPAN>            <SPAN style="COLOR: green">// the task is done
</SPAN>    }

    <SPAN style="COLOR: blue">class </SPAN><SPAN style="COLOR: #2b91af">Task </SPAN>{
        <SPAN style="COLOR: blue">string </SPAN>name;
        <SPAN style="COLOR: blue">public </SPAN>Task(<SPAN style="COLOR: blue">string </SPAN>name)
            <SPAN style="COLOR: blue">this</SPAN>.name = name;
        <SPAN style="COLOR: green">// other properties &amp; methods
    </SPAN>}
}</PRE><A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"></A>
<P>This monitor system – StatusUpdatePublisher, sends mails and updates calendars. </P><PRE class=code><SPAN style="COLOR: green">// the class that reacts to events generated by ProjectProgressTracker
</SPAN><SPAN style="COLOR: blue">class </SPAN><SPAN style="COLOR: #2b91af">StatusUpdatePublisher </SPAN>{
    <SPAN style="COLOR: blue">public void </SPAN>OnTaskAdded(<SPAN style="COLOR: blue">string </SPAN>taskName) {
        <SPAN style="COLOR: blue">this</SPAN>.UpdateCalendar(<SPAN style="COLOR: blue">true</SPAN>);
        <SPAN style="COLOR: blue">this</SPAN>.SendMail(taskName, <SPAN style="COLOR: #a31515">"added"</SPAN>);
    }
    <SPAN style="COLOR: blue">public void </SPAN>OnTaskBlocked(<SPAN style="COLOR: blue">string </SPAN>taskName) {
        <SPAN style="COLOR: blue">this</SPAN>.SendMail(taskName, <SPAN style="COLOR: #a31515">"blocked"</SPAN>);
    }
    <SPAN style="COLOR: blue">public void </SPAN>OnTaskCompleted(<SPAN style="COLOR: blue">string </SPAN>taskName) {
        <SPAN style="COLOR: blue">this</SPAN>.UpdateCalendar(<SPAN style="COLOR: blue">false</SPAN>);
        <SPAN style="COLOR: blue">this</SPAN>.SendMail(taskName, <SPAN style="COLOR: #a31515">"completed"</SPAN>);
    }

    <SPAN style="COLOR: blue">void </SPAN>SendMail(<SPAN style="COLOR: blue">string </SPAN>taskName, <SPAN style="COLOR: blue">string </SPAN>action) {
        <SPAN style="COLOR: #2b91af">Console</SPAN>.WriteLine(<SPAN style="COLOR: #a31515">"Task {0} was {1}"</SPAN>, taskName, action);
    }
    <SPAN style="COLOR: blue">void </SPAN>UpdateCalendar(<SPAN style="COLOR: blue">bool </SPAN>taskAdded) {
        <SPAN style="COLOR: #2b91af">Console</SPAN>.WriteLine(<SPAN style="COLOR: #a31515">"Task was {0}"</SPAN>, taskAdded ? <SPAN style="COLOR: #a31515">"added" </SPAN>: <SPAN style="COLOR: #a31515">"removed"</SPAN>);
    }
}</PRE><A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"></A>
<P>The 2 functionalities (generator / consumer) are completely separate. </P>
<P>1. One way to implement this is to pass an Events Consumer object when constructing the Events Generator; then the generator class simply uses the consumer instance to call the desired methods. </P><PRE class=code><SPAN style="COLOR: blue">class </SPAN><SPAN style="COLOR: #2b91af">ProjectProgressTracker </SPAN>{
    <SPAN style="COLOR: blue">static </SPAN><SPAN style="COLOR: #2b91af">Random </SPAN>r = <SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">Random</SPAN>((<SPAN style="COLOR: blue">int</SPAN>)<SPAN style="COLOR: #2b91af">DateTime</SPAN>.Now.Ticks);
    <SPAN style="COLOR: #2b91af">List</SPAN>&lt;<SPAN style="COLOR: #2b91af">Task</SPAN>&gt; tasks;
    <SPAN style="COLOR: blue">readonly </SPAN><SPAN style="COLOR: #2b91af">StatusUpdatePublisher </SPAN>publisher;

    <SPAN style="COLOR: blue">public </SPAN>ProjectProgressTracker(
        <SPAN style="COLOR: blue">string</SPAN>[] initialTasks, <SPAN style="COLOR: #2b91af">StatusUpdatePublisher </SPAN>publisher) {
        <SPAN style="COLOR: blue">this</SPAN>.publisher = publisher;
        <SPAN style="COLOR: green">// other functionality, see above
    </SPAN>}

    <SPAN style="COLOR: blue">public void </SPAN>NextAction() {
        <SPAN style="COLOR: green">// This should be replaced with the actual logic
        </SPAN><SPAN style="COLOR: blue">int </SPAN>randomNumber = r.Next(10);
        <SPAN style="COLOR: blue">if </SPAN>(randomNumber &lt; 3)
            publisher.OnTaskAdded(randomNumber.ToString());
        <SPAN style="COLOR: blue">else if </SPAN>(randomNumber &gt; 6)
            publisher.OnTaskBlocked(randomNumber.ToString());
        <SPAN style="COLOR: blue">else
            </SPAN>publisher.OnTaskCompleted(randomNumber.ToString());
    }

    <SPAN style="COLOR: green">// other methods &amp; classes
</SPAN>}</PRE><A href="http://11011.net/software/vspaste"></A><A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"></A>
<P>This works, but makes the events generator class <STRONG>tightly coupled</STRONG> with the events consumer. Consider now that we want to add another monitor system that generates documentation tasks. If we follow the style above, we should pass it too inside the events generator class so it can call the correct methods. Of course, this model doesn’t scale very well. </P>
<P>2. Another option is to raise some events at the correct time. </P><PRE class=code><SPAN style="COLOR: blue">class </SPAN><SPAN style="COLOR: #2b91af">TaskEventArgs </SPAN>: <SPAN style="COLOR: #2b91af">EventArgs </SPAN>{
    <SPAN style="COLOR: blue">public </SPAN>TaskEventArgs(<SPAN style="COLOR: blue">string </SPAN>taskName) {
        <SPAN style="COLOR: blue">this</SPAN>.TaskName = taskName;
    }
    <SPAN style="COLOR: blue">public string </SPAN>TaskName { <SPAN style="COLOR: blue">get</SPAN>; <SPAN style="COLOR: blue">private set</SPAN>; }
}

<SPAN style="COLOR: blue">delegate void </SPAN><SPAN style="COLOR: #2b91af">TaskEventHandler</SPAN>(<SPAN style="COLOR: blue">object </SPAN>sender, <SPAN style="COLOR: #2b91af">TaskEventArgs </SPAN>e);</PRE><A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"></A>
<P>The events generator class has 3 events – for tasks added, completed and blocked. </P><PRE class=code><SPAN style="COLOR: blue">class </SPAN><SPAN style="COLOR: #2b91af">ProjectProgressTracker </SPAN>{
    <SPAN style="COLOR: blue">public event </SPAN><SPAN style="COLOR: #2b91af">TaskEventHandler </SPAN>OnTaskAdded;
    <SPAN style="COLOR: blue">public event </SPAN><SPAN style="COLOR: #2b91af">TaskEventHandler </SPAN>OnTaskCompleted;
    <SPAN style="COLOR: blue">public event </SPAN><SPAN style="COLOR: #2b91af">TaskEventHandler </SPAN>OnTaskBlocked;

    <SPAN style="COLOR: blue">public void </SPAN>NextAction() {
        <SPAN style="COLOR: green">// This should be replaced with the actual logic
        </SPAN><SPAN style="COLOR: blue">int </SPAN>randomNumber = r.Next(10);
        <SPAN style="COLOR: #2b91af">TaskEventArgs </SPAN>eventArgs = <SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">TaskEventArgs</SPAN>(
            randomNumber.ToString());
        <SPAN style="COLOR: blue">if </SPAN>(randomNumber &lt; 3)
            <SPAN style="COLOR: blue">this</SPAN>.OnTaskAdded(<SPAN style="COLOR: blue">this</SPAN>, eventArgs);
        <SPAN style="COLOR: blue">else if </SPAN>(randomNumber &gt; 6)
            <SPAN style="COLOR: blue">this</SPAN>.OnTaskBlocked(<SPAN style="COLOR: blue">this</SPAN>, eventArgs);
        <SPAN style="COLOR: blue">else
            this</SPAN>.OnTaskCompleted(<SPAN style="COLOR: blue">this</SPAN>, eventArgs);
    }

    <SPAN style="COLOR: green">// other methods &amp; classes
</SPAN>}</PRE><A href="http://11011.net/software/vspaste"></A><A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"></A>
<P>Then the user of the class needs to hook up the events to the correct methods in the consumer class.</P><PRE class=code>ProjectProgressTracker tracker = <SPAN style="COLOR: blue">new </SPAN>ProjectProgressTracker(
    <SPAN style="COLOR: blue">new string</SPAN>[] {<SPAN style="COLOR: #a31515">"Gather requirements"</SPAN>, <SPAN style="COLOR: #a31515">"Prototype"</SPAN>});
tracker.OnTaskAdded += 
    (<SPAN style="COLOR: blue">object </SPAN>o, TaskEventArgs e) =&gt; publisher.OnTaskAdded(e.TaskName);
tracker.OnTaskCompleted += 
    (<SPAN style="COLOR: blue">object </SPAN>o, TaskEventArgs e) =&gt; publisher.OnTaskCompleted(e.TaskName);
tracker.OnTaskBlocked += 
    (<SPAN style="COLOR: blue">object </SPAN>o, TaskEventArgs e) =&gt; publisher.OnTaskBlocked(e.TaskName); 
</PRE><A href="http://11011.net/software/vspaste"></A><A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"></A><A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"></A><A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"></A>
<P>The benefit of this approach is that the generator class is not modified, no matter how many consumer classes we want to add to it. The disadvantage is that the user class needs to hook up all events to the correct implementation in consumers.</P>
<P>3. Another solution is to use the Observable/Observer pattern. <A href="http://www.exciton.cs.rice.edu/JavaResources/DesignPatterns/ObserverObservable.htm" mce_href="http://www.exciton.cs.rice.edu/JavaResources/DesignPatterns/ObserverObservable.htm">The Observer-Observable design pattern</A> is a a very useful pattern for maintaining one-way communication between one object and a set of other objects. The observers receive communications from the Observable. Observers do not have a reference back to the Observable, so the communication is strictly from the Observable to the Observers. The observable is the object the Observers are "watching". The Observable maintains some sort of&nbsp; list of references to Observers. That way, the Observable can send a message to all the Observers by calling each of their update methods. </P>
<P>This is a known pattern, but since it’s not implemented in .Net Framework 3.5, I am just going to define some interfaces that suit my needs.</P>
<P>Here, the class that generates events is the IObservable&lt;T&gt; and the class that consumes events in IObserver&lt;T&gt;:</P><PRE class=code><SPAN style="COLOR: blue">interface </SPAN><SPAN style="COLOR: #2b91af">IObservable</SPAN>&lt;T&gt; {
    <SPAN style="COLOR: blue">void </SPAN>Subscribe(<SPAN style="COLOR: #2b91af">IObserver</SPAN>&lt;T&gt; observer);
    <SPAN style="COLOR: blue">bool </SPAN>Unsubscribe(<SPAN style="COLOR: #2b91af">IObserver</SPAN>&lt;T&gt; observer);
}

<SPAN style="COLOR: blue">interface </SPAN><SPAN style="COLOR: #2b91af">IObserver</SPAN>&lt;T&gt; {
    <SPAN style="COLOR: blue">void </SPAN>OnNext(T value);
}</PRE><A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"></A>
<P><A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"></A>In our case, T is a class that contains the state of the task – the name of the task and the action that was taken:</P><PRE class=code><SPAN style="COLOR: blue">enum </SPAN><SPAN style="COLOR: #2b91af">TaskAction </SPAN>{ Added, Completed, Blocked }
<SPAN style="COLOR: blue">class </SPAN><SPAN style="COLOR: #2b91af">TaskState </SPAN>{
    <SPAN style="COLOR: blue">public </SPAN>TaskState(<SPAN style="COLOR: blue">string </SPAN>taskName, <SPAN style="COLOR: #2b91af">TaskAction </SPAN>taskAction) {
        <SPAN style="COLOR: blue">this</SPAN>.TaskAction = taskAction;
        <SPAN style="COLOR: blue">this</SPAN>.TaskName = taskName;
    }
    <SPAN style="COLOR: blue">public string </SPAN>TaskName { <SPAN style="COLOR: blue">get</SPAN>; <SPAN style="COLOR: blue">private set</SPAN>; }
    <SPAN style="COLOR: blue">public </SPAN><SPAN style="COLOR: #2b91af">TaskAction </SPAN>TaskAction { <SPAN style="COLOR: blue">get</SPAN>; <SPAN style="COLOR: blue">private set</SPAN>; }
}</PRE>
<P><A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"></A>So our classes change accordingly: the ProjectProgressTracker implements the IObservable interface, and the status update class implements the IObserver interface.</P><PRE class=code><SPAN style="COLOR: blue">class </SPAN><SPAN style="COLOR: #2b91af">ProjectProgressTracker </SPAN>: <SPAN style="COLOR: #2b91af">IObservable</SPAN>&lt;<SPAN style="COLOR: #2b91af">TaskState</SPAN>&gt; {
    <SPAN style="COLOR: #2b91af">List</SPAN>&lt;<SPAN style="COLOR: #2b91af">IObserver</SPAN>&lt;<SPAN style="COLOR: #2b91af">TaskState</SPAN>&gt;&gt; observers = 
        <SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">List</SPAN>&lt;<SPAN style="COLOR: #2b91af">IObserver</SPAN>&lt;<SPAN style="COLOR: #2b91af">TaskState</SPAN>&gt;&gt;();

    <SPAN style="COLOR: blue">public void </SPAN>Subscribe(<SPAN style="COLOR: #2b91af">IObserver</SPAN>&lt;<SPAN style="COLOR: #2b91af">TaskState</SPAN>&gt; observer) {
        <SPAN style="COLOR: blue">this</SPAN>.observers.Add(observer);
    }
    <SPAN style="COLOR: blue">public bool </SPAN>Unsubscribe(<SPAN style="COLOR: #2b91af">IObserver</SPAN>&lt;<SPAN style="COLOR: #2b91af">TaskState</SPAN>&gt; observer) {
        <SPAN style="COLOR: blue">return this</SPAN>.observers.Remove(observer);
    }

    <SPAN style="COLOR: blue">public void </SPAN>NextAction() {
        <SPAN style="COLOR: green">// This should be replaced with the actual logic
        </SPAN><SPAN style="COLOR: blue">int </SPAN>randomNumber = r.Next(10);
        <SPAN style="COLOR: #2b91af">TaskEventArgs </SPAN>eventArgs = <SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">TaskEventArgs</SPAN>(
            randomNumber.ToString());
        <SPAN style="COLOR: blue">if </SPAN>(randomNumber &lt; 3)
            <SPAN style="COLOR: blue">foreach </SPAN>(<SPAN style="COLOR: #2b91af">IObserver</SPAN>&lt;<SPAN style="COLOR: #2b91af">TaskState</SPAN>&gt; observer <SPAN style="COLOR: blue">in this</SPAN>.observers)
                observer.OnNext(
                    <SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">TaskState</SPAN>(randomNumber.ToString(), <SPAN style="COLOR: #2b91af">TaskAction</SPAN>.Added));
        <SPAN style="COLOR: blue">else if </SPAN>(randomNumber &gt; 6)
            <SPAN style="COLOR: blue">foreach </SPAN>(<SPAN style="COLOR: #2b91af">IObserver</SPAN>&lt;<SPAN style="COLOR: #2b91af">TaskState</SPAN>&gt; observer <SPAN style="COLOR: blue">in this</SPAN>.observers)
                observer.OnNext(
                    <SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">TaskState</SPAN>(randomNumber.ToString(), <SPAN style="COLOR: #2b91af">TaskAction</SPAN>.Blocked));
        <SPAN style="COLOR: blue">else
            foreach </SPAN>(<SPAN style="COLOR: #2b91af">IObserver</SPAN>&lt;<SPAN style="COLOR: #2b91af">TaskState</SPAN>&gt; observer <SPAN style="COLOR: blue">in this</SPAN>.observers)
                observer.OnNext(
                    <SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">TaskState</SPAN>(randomNumber.ToString(), <SPAN style="COLOR: #2b91af">TaskAction</SPAN>.Completed));
    }

    <SPAN style="COLOR: green">// other methods &amp; classes
</SPAN>}

<SPAN style="COLOR: blue">class </SPAN><SPAN style="COLOR: #2b91af">StatusUpdatePublisher </SPAN>: <SPAN style="COLOR: #2b91af">IObserver</SPAN>&lt;<SPAN style="COLOR: #2b91af">TaskState</SPAN>&gt; {
    <SPAN style="COLOR: blue">public void </SPAN>OnNext(<SPAN style="COLOR: #2b91af">TaskState </SPAN>state) {
        <SPAN style="COLOR: blue">switch </SPAN>(state.TaskAction) {
            <SPAN style="COLOR: blue">case </SPAN><SPAN style="COLOR: #2b91af">TaskAction</SPAN>.Added:
                <SPAN style="COLOR: blue">this</SPAN>.OnTaskAdded(state.TaskName); <SPAN style="COLOR: blue">break</SPAN>;
            <SPAN style="COLOR: blue">case </SPAN><SPAN style="COLOR: #2b91af">TaskAction</SPAN>.Blocked:
                <SPAN style="COLOR: blue">this</SPAN>.OnTaskBlocked(state.TaskName); <SPAN style="COLOR: blue">break</SPAN>;
            <SPAN style="COLOR: blue">case </SPAN><SPAN style="COLOR: #2b91af">TaskAction</SPAN>.Completed:
                <SPAN style="COLOR: blue">this</SPAN>.OnTaskCompleted(state.TaskName); <SPAN style="COLOR: blue">break</SPAN>;
        }
    }

    <SPAN style="COLOR: green">// the other methods
</SPAN>}</PRE><A href="http://11011.net/software/vspaste"></A><PRE class=code></PRE>
<P>Now the user just constructs the classes and registers the desired consumers:</P><PRE class=code>StatusUpdatePublisher publisher = <SPAN style="COLOR: blue">new </SPAN>StatusUpdatePublisher();
ProjectProgressTracker tracker = <SPAN style="COLOR: blue">new </SPAN>ProjectProgressTracker(
    <SPAN style="COLOR: blue">new string</SPAN>[] {<SPAN style="COLOR: #a31515">"Gather requirements"</SPAN>, <SPAN style="COLOR: #a31515">"Prototype"</SPAN>});
tracker.Subscribe(publisher);
</PRE><A href="http://11011.net/software/vspaste"></A><A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"></A>
<P>This pattern has a couple of advantages: </P>
<UL>
<LI>Multiple consumers can be added easily 
<LI>The events generator doesn’t need to know anything about the consumers; no change in the generator is needed when one or more of the consumers is changed.</LI></UL>
<P>But we pay the penalty of wrapping the state in a class and then analyzing it in the Observer to see what concrete method to implement. </P>
<P>4. Another possible implementation is the IRegistrar pattern (Disclaimer: I’m not aware of a pattern with this name described. The name is something I came up with). This is somewhat similar with the IObservable pattern, but instead of a class that wraps the state when the event occurs, we specify an interface for the type of events. </P><PRE class=code><SPAN style="COLOR: blue">interface </SPAN><SPAN style="COLOR: #2b91af">IProjectEvents </SPAN>{
    <SPAN style="COLOR: blue">void </SPAN>OnTaskAdded(<SPAN style="COLOR: blue">string </SPAN>taskName);
    <SPAN style="COLOR: blue">void </SPAN>OnTaskBlocked(<SPAN style="COLOR: blue">string </SPAN>taskName);
    <SPAN style="COLOR: blue">void </SPAN>OnTaskCompleted(<SPAN style="COLOR: blue">string </SPAN>taskName);
}

<SPAN style="COLOR: blue">interface </SPAN><SPAN style="COLOR: #2b91af">IRegistrar</SPAN>&lt;T&gt; {
    <SPAN style="COLOR: blue">void </SPAN>Subscribe(T consumer);
    <SPAN style="COLOR: blue">bool </SPAN>Unsubscribe(T consumer);
}</PRE><A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"></A>
<P>The events consumers implement this interface:</P><PRE class=code><SPAN style="COLOR: blue">class </SPAN><SPAN style="COLOR: #2b91af">StatusUpdatePublisher </SPAN>: IProjectEvents {
    <SPAN style="COLOR: green">// the original methods
</SPAN>}</PRE><A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"></A>
<P>The generator class can register consumers that know to consume events of type T (IProjectEvents in our case).</P><PRE class=code><SPAN style="COLOR: blue">class </SPAN><SPAN style="COLOR: #2b91af">ProjectProgressTracker </SPAN>: <SPAN style="COLOR: #2b91af">IRegistrar</SPAN>&lt;<SPAN style="COLOR: #2b91af">IProjectEvents</SPAN>&gt; {
    <SPAN style="COLOR: #2b91af">List</SPAN>&lt;<SPAN style="COLOR: #2b91af">IProjectEvents</SPAN>&gt; consumers = <SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">List</SPAN>&lt;<SPAN style="COLOR: #2b91af">IProjectEvents</SPAN>&gt;();

    <SPAN style="COLOR: blue">public void </SPAN>Subscribe(<SPAN style="COLOR: #2b91af">IProjectEvents </SPAN>consumer) {
        <SPAN style="COLOR: blue">this</SPAN>.consumers.Add(consumer);
    }
    <SPAN style="COLOR: blue">public bool </SPAN>Unsubscribe(<SPAN style="COLOR: #2b91af">IProjectEvents </SPAN>consumer) {
        <SPAN style="COLOR: blue">return this</SPAN>.consumers.Remove(consumer);
    }

    <SPAN style="COLOR: blue">public void </SPAN>NextAction() {
        <SPAN style="COLOR: green">// This should be replaced with the actual logic
        </SPAN><SPAN style="COLOR: blue">int </SPAN>randomNumber = r.Next(10);
        <SPAN style="COLOR: #2b91af">TaskEventArgs </SPAN>eventArgs = <SPAN style="COLOR: blue">new </SPAN><SPAN style="COLOR: #2b91af">TaskEventArgs</SPAN>(
            randomNumber.ToString());
        <SPAN style="COLOR: blue">if </SPAN>(randomNumber &lt; 3)
            <SPAN style="COLOR: blue">foreach </SPAN>(<SPAN style="COLOR: #2b91af">IProjectEvents </SPAN>consumer <SPAN style="COLOR: blue">in this</SPAN>.consumers)
                consumer.OnTaskAdded(randomNumber.ToString());
        <SPAN style="COLOR: blue">else if </SPAN>(randomNumber &gt; 6)
            <SPAN style="COLOR: blue">foreach </SPAN>(<SPAN style="COLOR: #2b91af">IProjectEvents </SPAN>consumer <SPAN style="COLOR: blue">in this</SPAN>.consumers)
                consumer.OnTaskBlocked(randomNumber.ToString());
        <SPAN style="COLOR: blue">else
            foreach </SPAN>(<SPAN style="COLOR: #2b91af">IProjectEvents </SPAN>consumer <SPAN style="COLOR: blue">in this</SPAN>.consumers)
                consumer.OnTaskCompleted(randomNumber.ToString());
    }

    <SPAN style="COLOR: green">// other methods &amp; classes
</SPAN>}</PRE><A href="http://11011.net/software/vspaste"></A><A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"></A>
<P>The usage is just as the one for the IObservable pattern. </P>
<P>In our case, it seems that this pattern works the best, because we get all the previous advantages plus strongly typing when calling consumer methods. </P>
<P>Depending on your project requirements, you may choose one of these solutions or look for a better one. Some requirements may be:</P>
<UL>
<LI>Loosely coupling between the events generator and the consumers 
<UL>
<LI>Changing the consumer doesn’t affect the generator</LI></UL>
<LI>One or more consumers can be added 
<LI>Producers can have inner producers and the consumers must be propagated 
<LI>Etc… who knows?</LI></UL>]]></content:encoded>
    </item>
    <item>
      <title>.NET Framework 4.0 implements WS-Discovery</title>
      <link>https://docs.microsoft.com/archive/blogs/oanapl/net-framework-4-0-implements-ws-discovery</link>
      <pubDate>Thu, 11 Jun 2009 17:52:50 GMT</pubDate>
      <dc:creator><![CDATA[OanaPlaton]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/oanapl/2009/06/11/net-framework-4-0-implements-ws-discovery/</guid>
      <description><![CDATA[The .NET Framework 4.0 and Visual Studio 2010 Beta 1 are live. If you haven’t tried the bits, do so...]]></description>
      <content:encoded><![CDATA[<p>The <a href="http://www.microsoft.com/visualstudio/en-us/products/2010/default.mspx">.NET Framework 4.0 and Visual Studio 2010 Beta 1</a> are live. If you haven’t tried the bits, do so and give the team <a href="http://go.microsoft.com/fwlink/?LinkID=151484">feedback</a>. There are some very cool features added – just take a look at the <a href="http://msdn.microsoft.com/en-us/library/dd409230(VS.100).aspx">highlights</a>. </p>  <p>On the Communications front, Windows Communication Foundation has 3 major new features: support for WS-Discovery, standard endpoints (pre-defined endpoints with some of the properties fixed) and workflow services (messaging activities make the implementation of workflows very easy). </p>  <p>I am really excited with the support for the <a href="http://docs.oasis-open.org/ws-dd/discovery/1.1/cs-01/wsdd-discovery-1.1-spec-cs-01.pdf">WS-Discovery protocol</a>. From the msdn documentation:</p>  <blockquote>   <p>“The Service Discovery feature enables client applications to dynamically discover service addresses at run time in an interoperable way using WS-Discovery. The WS-Discovery specification outlines the message-exchange patterns (MEPs) required for performing lightweight discovery of services, both by multicast (ad hoc) and unicast (using a network resource).”</p> </blockquote>  <p>To learn more about Discovery, take a at the <a href="http://msdn.microsoft.com/en-us/library/dd483326%28VS.100%29.aspx">Discovery MSDN SDK samples</a>. Plus, the Discovery team is blogging, so go to the <a href="http://blogs.msdn.com/discovery/">Discovery team’s blog</a>. Or start with the <a href="https://channel9.msdn.com/shows/Endpoint/endpointtv-Service-Discovery-with-WCF/">Channel9 Discovery video</a>:</p>  <p><a title="Service Discovery with WCF" href="https://channel9.msdn.com/shows/Endpoint/endpointtv-Service-Discovery-with-WCF/"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/oanapl/WindowsLiveWriter/NETFramework4.0implementsWSDiscovery_D13F/image_3.png" original-url="http://blogs.msdn.com/blogfiles/oanapl/WindowsLiveWriter/NETFramework4.0implementsWSDiscovery_D13F/image_3.png" width="244" height="214" /></a></p>]]></content:encoded>
    </item>
  </channel>
</rss>