<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="https://www.w3.org/2005/Atom" xmlns:sy="https://purl.org/rss/1.0/modules/syndication/" xmlns:dc="https://purl.org/dc/elements/1.1/" xmlns:content="https://purl.org/rss/1.0/modules/content/" xmlns:wfw="https://wellformedweb.org/CommentAPI/" xmlns:slash="https://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>The Activity Designer</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/tilovell/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/tilovell/feed.xml</link>
    <description>Not actually a WF 4.0 blog any more :)</description>
    <lastBuildDate>Mon, 17 Oct 2016 22:17:11 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>Grokking ContextAwareResult (.Net internals)</title>
      <link>https://docs.microsoft.com/archive/blogs/tilovell/grokking-contextawareresult-net-internals</link>
      <pubDate>Mon, 17 Oct 2016 22:17:11 GMT</pubDate>
      <dc:creator><![CDATA[tilovell09]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/tilovell/?p=1725</guid>
      <description><![CDATA[(This is the sequel to grokking LazyAsyncResult, which could be considered a...]]></description>
      <content:encoded><![CDATA[(This is the sequel to <a href="https://blogs.msdn.microsoft.com/tilovell/2016/10/17/grokking-lazyasyncresult-net-internal/">grokking LazyAsyncResult</a>, which could be considered a prerequisite.)

You'll see if you look through Socket async API internals that they aren't just using the LazyAsyncResult class, they're actually calling this thing called <strong>ContextAwareResult</strong> (and so are a few of the other .Net network async APIs). What is this beast?

The class blurb is "This class will ensure that the correct context is restored on the thread before invoking a user callback."

If you've ever seen ContextAwareResult in action, what you normally eventually see is a call stack like this:

<a href="https://msdnshared.blob.core.windows.net/media/2016/10/ContextAwareResult_in_action.png"><img width="1103" height="53" alt="ContextAwareResult_in_action" src="https://msdnshared.blob.core.windows.net/media/2016/10/ContextAwareResult_in_action.png" /></a>

I.e. ContextAwareResult at some point in time captures an <strong>ExecutionContext</strong>, and some other point in time (when the async operation completes) uses that execution context for invoking the callback, via ExecutionContext.Run(). Still, after peeking at the code it took me some untangling and learning about LazyAsyncResult to properly understand the question "when is the execution context captured?"

Basically it is not such a long class and it boils down to handling what I think are the two mainline scenarios after you call the Begin*() API which is going to return you a ContextAwareResult:

Scenario a) the async result actually completes synchronously during the call to Begin*()! This is fabulous news, because the execution context now doesn't even need to be captured and restored at all, because the current execution context is already the right one!

Scenario b) the async result is discovered to need to complete asynchronously. This is slightly less than fabulous news, because now an execution context needs to be captured and stored on the AsyncResult. (Unless there is no AsyncCallback, which I will call out as being outside of Scenarios a and b, in fact let's call it Scenario c). The context must be captured during the implementation of Begin*(), and obviously <em>before</em> the user's callback is called. The call chain here is thus: *.Begin*() -&gt; ContextAwareResult.FinishPostingAsyncOp() -&gt; CaptureOrComplete(), which should *either* captures the context (if needed) or calls the user completion immediately - hence the name.

Of course since this is an internal framework class, there must to be some optimization tricks here right? :) Of course there is. Some performance testing probably led to a useful observation: any time you are newing up a lot of ContextAwareResults inside repeated calls to a particular Begin*() implementation, you may find the calls are actually getting called with the same exact AsyncCallback over and over again (but perhaps with different AsyncState). Therefore in the framework, a class like Socket implementing (e.g.) BeginReceive() can keep an set of cache fields like (e.g.) 'ReceiveClosure', and each time it needs to use a ContextAwareResult to return asynchronously it passes the cached callback into FinishPostingAsyncOp(). Which then flows it to CaptureOrComplete(). If CaptureOrComplete() detects that the AsyncCallback is the <em>same</em> delegate on the <em>same</em> context as before, it can just copy the cached ExecutionContext, instead of capturing it all over again, which I guess must be kind of costly.

Finally to complete the async operation, ContextAwareResult.Complete() overrides of LazyAsyncResult.Complete() in order to hook the callback of the user's AsyncCallback and actually run the callback with ExecutionContext.Run(). The upshot of this is that the user's callback where they will call End*() will be running <em>with the same execution context</em> as when they called Begin*().

Inquiring minds will now want to know about scenario d): what if there <em>is no execution context</em> when we call Begin*()? Simple: there's nothing to capture! And so ContextAwareResult.Complete() can just invoke the AsyncCallback directly without restoring any execution context! This is good to know, as sometimes you are don't actually need the ExecutionContext to be restored, so suppressing your ExecutionContext before calling Begin*() can be a way to get a performance boost.]]></content:encoded>
    </item>
    <item>
      <title>Grokking LazyAsyncResult (.Net internal)</title>
      <link>https://docs.microsoft.com/archive/blogs/tilovell/grokking-lazyasyncresult-net-internal</link>
      <pubDate>Mon, 17 Oct 2016 21:08:41 GMT</pubDate>
      <dc:creator><![CDATA[tilovell09]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/tilovell/?p=1715</guid>
      <description><![CDATA[(Background: sometimes as I try to understand our bugs, I have to learn about the .net internal...]]></description>
      <content:encoded><![CDATA[(Background: sometimes as I try to understand our bugs, I have to learn about the .net internal classes used for implementation of the public classes that we're consuming - my motivator today is SocketAsyncEventArgs.)

Today I'm going to try to understand the internal class <strong>LazyAsyncResult</strong>.

Now that .Net core is open source we can find its source code in the state I see it here:

https://github.com/dotnet/corefx/blob/bffef76f6af208e2042a2f27bc081ee908bb390b/src/Common/src/System/Net/LazyAsyncResult.cs

- but I like to use Reflector which helps me figure otu how the class is actually used too.

The class comment in source is pretty helpful: "LazyAsyncResult - Base class for all IAsyncResult classes that want to take advantage of lazily-allocated event handles".

In plainer language, imagine that you have to implement the IAsyncResult interface from scratch as part of a new API you're writing. (Yes, this is less and less likely as the world moves to async/await and Task based APIs, but humor me!)

The interface must provide the following properties(snippeting from MSDN with links and all):
<ol>
 	<li>object AsyncState</li>
 	<li>WaitHandle AsyncWaitHandle</li>
 	<li>bool CompletedSynchronously</li>
 	<li>bool IsCompleted</li>
</ol>
The member to pay attention to for understanding LazyAsyncReuslt is <strong>AsyncWaitHandle</strong>. Clearly, the goal of this class is that if no caller actually ever needs a WaitHandle to wait on, then we shouldn't need to allocate one - as after all, allocating WaitHandles is slightly expensive.

How expensive? Well, here is <a href="https://joeduffyblog.com/2006/05/30/implementing-a-highperf-iasyncresult-lockfree-lazy-allocation/">an interesting discussion related to the subject by Joe Duffy</a>, which basically explains the entire reason for having this LazyAsyncResult class. Aside from mentioning that allocating these handles is kinda expensive, he does some performance measurements, and then notes "In the case of high performance asynchronous IO, for example, where completion often involves simply marshaling some bytes between buffers, this can be a key step in the process of improving system throughput."

I think Joe was not being explicit in that sentence, but he probably meant that if async callbacks just to move some bytes between buffers, you <em>might never actually wait on the event at all. </em>Which is what makes it the best performance win. And also inferring, since he didn't include his test harness, I think his fibonnaci scenario is probably also not actually waiting on the event - otherwise we wouldn't expect to see an actual performance improvement for large fibonacci scenarios.

So is that the case that you won't be using any WaitHandles when you are using the async socket API?... Hopefully. :)

Anyway, now we understand most of the class design, but what about all these internal members the .net framework adds on top of the IAsyncResult interface? There are heaps of them! Here they are listed, with descriptions lifted from the source, broken into groups with commentary:

These properties are an obvious set to have in order to implement a 'Begin*/End* IAsyncResult pattern, which promises to callback some user-supplied callback method with a user-supplied async object parameter. Normally, also the 'End*' method returns the final result of the async operation.
<ol>
 	<li>protected AsyncCallback AsyncCallback - "Caller's callback method"</li>
 	<li>internal object AsyncObject - "Caller's async object"</li>
 	<li>internal object Result - "Final I/O result returned by the End* method"</li>
 	<li>internal int ErrorCode - "Win32 error code for Win32 IO async calls (that want to throw)."</li>
</ol>
Note that sometimes <strong>Result</strong> is actually set to hold an exception object, when the result of the async operation was a failure, and as a bonus, there is an int ErrorCode field for storing Win32 error codes such as socket errors, where applicable.

Some of these next properties are a little less clearly described:
<ol>
 	<li>internal bool EndCalled - "True if the user called the End*() method" [what? the user calls their own end method?]</li>
 	<li>internal bool InternalPeekCompleted - "Returns true if this call created the event." [what???]</li>
 	<li>internal void InvokeCallback()</li>
 	<li>internal void InvokeCallback(object result)</li>
 	<li>protected void ProtectedInvokeCallback(object result, IntPtr userToken) - "A method for completing the IO with a result and invoking the user's callback. Used by derived classes to pass context into an overridden Complete()." [note: ProtectedInvokeCallback calls into Complete() if the async result had not been completed yet.]
</li>

</ol>
I mean, come on, how could LazyAsyncResult possibly know that the user called their own end method without going through LazyAsyncResult at all? That can't really be what the comment means, so what is <strong>EndCalled</strong> actually for? Inspection shows that the purpose of EndCalled is to implement 'double-End-call' checking, i.e. inside an End*() method, the IAsyncResult will be cast as LazyAsyncResult and used to perform a sanity check, which becomes a nice debugging assistant:

<code>if (lazyAsyncResult.EndCalled) { throw new InvalidOperationException("You already called End* on this async result, calling it twice is an error"); }
lazyAsyncResult.EndCalled = true;</code>

And what about this <strong>InternalPeekCompleted</strong> boolean? Well, untangling its implementation, it relies on a field m_IntCompleted in the LazyAsyncResultobject. The field m_intCompleted stores two pieces of information: a) whether the async result completed synchronously yet, and b) how many times 'ProtectedInvokeCallback() or InvokeCallback() (which calls ProtectedInvokeCallback())' callback has been called, which is most useful for ensuring that if the async result finally does complete, the user callback gets called back exactly once. 

Anyway, <strong>InternalPeekCompleted</strong> is in short, designed to return true not excatly whenever the async result is completed but rather when the user's callback has been dispatched, or the user has otherwise observed the event to be completed. This gets used as a general book-keeping aid for various classes knowledgeable of LazyAsyncResult implementation, who want to e.g. keep track of their own internal state, without calling <strong>IsCompleted</strong>, which would have an undesirable side effect: 'IsCompleted' is rather special - it ensures that as soon as any external observer of the LazyAsyncResult starts seeing the 'IsCompleted' propertly as true (or false), <i>every thread</i> starts consistently seeing IsCompleted is true (or false) consistently, i.e. it 'locks in' a truth value for synchronous completion.

That leaves:
<ul>
 	<li>internal void InternalCleanup() - "A general interface that is called to release unmanaged resources associated with the class. It completes the result but doesn't do any of the notifications."</li>
 	<li>internal object InternalWaitForCompletion() - "If [AsyncWaitHandle] is used, the [manual reset event] cannot be disposed because it is under the control of the application.  Internal should use InternalWaitForCompletion instead - never AsyncWaitHandle"</li>
</ul>

The main learning I see here is that InternalWaitForCompletion comes with benefits that echo InternalPeekCompleted: when there's a framework-internal substitute for a public member that knows the difference between an 'external observer' viewing the completion state of the async result, and a 'piece of the framework' peeking at that completion state (or waiting upon it), this allows being more efficient about whether to create wait handles, whether to clean them up, and whether to bother trying to present a universally consistent story around whether the event completed synchronously nor not - the framework can be assumed to a) not do anything silly like wait on the wait handle after the event has actually completed, and b) be robust to the possibility that the user doesn't know yet whether the event is completing synchronously. (Presumably the framework code verifiably does it correctly - if only all user code were also easily verifiable to do the same!)

There's one really niec simplification in API the framework gives itself. In the framework internal world, LazyAsyncResult only has to implement 'wait for the event', and can implement that however it likes. In the public code scenario, LazyAsyncResult has a much more demanding spec: do it with a WaitHandle or bust! (D'oh.)

So TL;DR: LazyAsyncResult is just a reusable 'IAsyncResult' implementation for the framework to use, that comes with a bunch of commonly useful optimizations. Their benefit is partly from optimizing common user scenarios, and partly from the framework knowing that it can use more specialized APIs than IAsyncResult interface in its implementation (when the IAsyncResult way would result in suboptimalness).

]]></content:encoded>
    </item>
    <item>
      <title>Slimming down your build - don't copy the intellisense files!</title>
      <link>https://docs.microsoft.com/archive/blogs/tilovell/slimming-down-your-build-dont-copy-the-intellisense-files</link>
      <pubDate>Fri, 01 May 2015 11:18:43 GMT</pubDate>
      <dc:creator><![CDATA[tilovell09]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/tilovell/2015/05/01/slimming-down-your-build-dont-copy-the-intellisense-files/</guid>
      <description><![CDATA[So you know how a lot of nuget packages include intellisense XML files and they get copied to your...]]></description>
      <content:encoded><![CDATA[<p>So you know how a lot of nuget packages include intellisense XML files and they get copied to your output binaries folder during build?<br /><br />I did a quick web search but soon for how to fix this, but soon gave up and resorted to searching my msbuild .targets files instead. Finally I found it. The AllowedReferenceRelatedFileExtensions variable.</p>
<p><br />Just add this to your .csproj (or .props or .targets file depending on how you're structuring your build).<br /><br />&nbsp;&nbsp;&nbsp; &lt;!-- note: This controls what files *related to a DLL* are copied to the output directory with the dll.<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Setting custom AllowedReferenceRelatedFileExtensions to just .pdb and .pri - EXCLUDE .xml so that<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; all sorts of giant intellisense XML files are not copied to the bin directories!<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; You can override this per-project if you really want the .xml files for some reason --&gt;<br />&nbsp;&nbsp;&nbsp; &lt;AllowedReferenceRelatedFileExtensions&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; .pdb;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; .pri<br />&nbsp;&nbsp;&nbsp; &lt;/AllowedReferenceRelatedFileExtensions&gt;</p>
<p>Of course once I discovered the variable, it was *easy* to find many other people already knew about this. I was just failing to find it, sigh.</p>
<p>Example: <a href="https://stackoverflow.com/questions/2011434/preventing-referenced-assembly-pdb-and-xml-files-copied-to-output">https://stackoverflow.com/questions/2011434/preventing-referenced-assembly-pdb-and-xml-files-copied-to-output</a></p>]]></content:encoded>
    </item>
    <item>
      <title>Is Autofac magical - part II</title>
      <link>https://docs.microsoft.com/archive/blogs/tilovell/is-autofac-magical-part-ii</link>
      <pubDate>Mon, 06 Apr 2015 09:23:48 GMT</pubDate>
      <dc:creator><![CDATA[tilovell09]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/tilovell/2015/04/06/is-autofac-magical-part-ii/</guid>
      <description><![CDATA[Now that you've read part I perhaps you can answer this.
What does this code...]]></description>
      <content:encoded><![CDATA[<p>Now that you've <a href="https://blogs.msdn.com/b/tilovell/archive/2015/04/04/is-autofac-magical.aspx">read part I</a> perhaps you can answer this.</p>
<p>What does this code do?</p>
<p>&nbsp;&nbsp;&nbsp; class FO : IEnumerable<br />&nbsp;&nbsp;&nbsp; {</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public IEnumerator GetEnumerator()<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; throw new NotImplementedException();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; class Program<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; static void Main(string[] args)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var cb = new ContainerBuilder();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cb.Register(ctx =&gt; new FO()).As&lt;IEnumerable&gt;().InstancePerLifetimeScope();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cb.Register&lt;Func&lt;FO&gt;&gt;(ctx =&gt; { return () =&gt; new FO(); }).As&lt;Func&lt;IEnumerable&gt;&gt;();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var x = cb.Build();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; using (var s = x.BeginLifetimeScope())<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var f = s.Resolve&lt;Func&lt;IEnumerable&gt;&gt;();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var i1 = f();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var i2 = f();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var ie = x.Resolve&lt;IEnumerable&gt;();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp; }</p>
<p>In particular<br /><br />Are <strong>i1</strong>, <strong>i2</strong>, and <strong>ie</strong> distinct?<br /><br />What if you comment out the line cb.Register&lt;Func&lt;FO&gt;&gt;(ctx =&gt; { return () =&gt; new FO(); }).As&lt;Func&lt;IEnumerable&gt;&gt;();?</p>]]></content:encoded>
    </item>
    <item>
      <title>Is Autofac magical?</title>
      <link>https://docs.microsoft.com/archive/blogs/tilovell/is-autofac-magical</link>
      <pubDate>Fri, 03 Apr 2015 16:22:50 GMT</pubDate>
      <dc:creator><![CDATA[tilovell09]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/tilovell/2015/04/03/is-autofac-magical/</guid>
      <description><![CDATA[The answer is yes!
OK let me explain. I never registered anything as...]]></description>
      <content:encoded><![CDATA[<p>The answer is yes!</p>
<p>OK let me explain. I never registered anything as Func&lt;IObservable&lt;object&gt;&gt; and yet the below code still works. It turns out to be that not only does autofac understand Func&lt;Dependency&gt;(), it understands a whole bunch of things that you may or may not have intended to be dependency relationships. :)</p>
<p>The details [Copied straight from https://autofac.readthedocs.org/en/latest/resolve/relationships.html]</p>
<table class="docutils" border="1">
<tbody valign="top">
<tr class="row-even">
<td><tt class="docutils literal"><span class="pre">B</span></tt></td>
<td>Direct Dependency</td>
</tr>
<tr class="row-odd">
<td><em>A</em> needs <em>B</em> at some point in the future</td>
<td><tt class="docutils literal"><span class="pre">Lazy&lt;B&gt;</span></tt></td>
<td>Delayed Instantiation</td>
</tr>
<tr class="row-even">
<td><em>A</em> needs <em>B</em> until some point in the future</td>
<td><tt class="docutils literal"><span class="pre">Owned&lt;B&gt;</span></tt></td>
<td><a class="reference internal" href="https://autofac.readthedocs.org/en/latest/advanced/owned-instances.html"><em>Controlled Lifetime</em></a></td>
</tr>
<tr class="row-odd">
<td><em>A</em> needs to create instances of <em>B</em></td>
<td><tt class="docutils literal"><span class="pre">Func&lt;B&gt;</span></tt></td>
<td>Dynamic Instantiation</td>
</tr>
<tr class="row-even">
<td><em>A</em> provides parameters of types <em>X</em> and <em>Y</em> to <em>B</em></td>
<td><tt class="docutils literal"><span class="pre">Func&lt;X,Y,B&gt;</span></tt></td>
<td>Parameterized Instantiation</td>
</tr>
<tr class="row-odd">
<td><em>A</em> needs all the kinds of <em>B</em></td>
<td><tt class="docutils literal"><span class="pre">IEnumerable&lt;B&gt;</span></tt>, <tt class="docutils literal"><span class="pre">IList&lt;B&gt;</span></tt>, <tt class="docutils literal"><span class="pre">ICollection&lt;B&gt;</span></tt></td>
<td>Enumeration</td>
</tr>
<tr class="row-even">
<td><em>A</em> needs to know <em>X</em> about <em>B</em></td>
<td><tt class="docutils literal"><span class="pre">Meta&lt;B&gt;</span></tt> and <tt class="docutils literal"><span class="pre">Meta&lt;B,X&gt;</span></tt></td>
<td><a class="reference internal" href="https://autofac.readthedocs.org/en/latest/advanced/metadata.html"><em>Metadata Interrogation</em></a></td>
</tr>
<tr class="row-odd">
<td><em>A</em> needs to choose <em>B</em> based on <em>X</em></td>
<td><tt class="docutils literal"><span class="pre">IIndex&lt;X,B&gt;</span></tt></td>
</tr>
</tbody>
</table>
<p>So now I know!</p>
<p>using System;<br />using System.Collections.Generic;<br />using System.Linq;<br />using System.Text;<br />using System.Threading.Tasks;<br />using Autofac;</p>
<p>namespace IsAutoFacMagical<br />{<br />&nbsp;&nbsp;&nbsp; class CO : IObservable&lt;object&gt;<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public IDisposable Subscribe(IObserver&lt;object&gt; observer)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; throw new NotImplementedException();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; class DO<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public Func&lt;IObservable&lt;object&gt;&gt; Magic { get; set; }<br />&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;&nbsp;&nbsp; class Program<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; static void Main(string[] args)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var cb = new ContainerBuilder();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cb.RegisterType&lt;CO&gt;().As&lt;IObservable&lt;object&gt;&gt;();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cb.RegisterType&lt;DO&gt;().PropertiesAutowired();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var x = cb.Build();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var d = x.Resolve&lt;DO&gt;();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var m1 = d.Magic();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp; }<br />}<br /><br /></p>]]></content:encoded>
    </item>
    <item>
      <title>Distilling some ideas for keeping that data access code (and test code) tidy...</title>
      <link>https://docs.microsoft.com/archive/blogs/tilovell/distilling-some-ideas-for-keeping-that-data-access-code-and-test-code-tidy</link>
      <pubDate>Thu, 02 Apr 2015 15:04:52 GMT</pubDate>
      <dc:creator><![CDATA[tilovell09]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/tilovell/2015/04/02/distilling-some-ideas-for-keeping-that-data-access-code-and-test-code-tidy/</guid>
      <description><![CDATA[I just spent a while doing some refactoring. It turned out to be a very long while, probably much...]]></description>
      <content:encoded><![CDATA[<p>I just spent a while doing some refactoring. It turned out to be a very long while, probably much more than I would have originally estimated.&nbsp;(Part of the reason for that is builds and tests that take a long time...)&nbsp;The changes I made were somewhat haphazard at first, and I wasn't sure why I thought they were good ideas, but now I'm starting to feel like some of them are definitely good ideas, in fact, maybe there are patterns or lessons to distil from the changes.</p>
<p><span style="text-decoration: underline;">Principle #1 - Keep serialization knowledge where it belongs - in your data access layer!</span></p>
<p>Problem manifestation #1: we were using Entity Framework with string fields and effectively storing enumeration values as strings. What this tends to lead to is little bits of smelly code everywhere like the following:</p>
<p>deployment.Status = DeploymentStatus.Active.ToString();</p>
<p>if (String.Equals(deployment.Status, DeploymentStatus.Suspended.ToString());</p>
<p>DeploymentStatus status = (DeploymentStatus)Enum.Parse(typeof(DeploymentStatus), deployment.Status, true);<br />switch (status) {...}</p>
<p>Problem manifestation #2: we were also using Entity Framework to store json serialized dictionaries of settings....</p>
<p>Solution:</p>
<p>Fix the model. Make the code model really have&nbsp;an enum&nbsp;DeploymentStatus property, and a Dictionary&lt;string,string&gt; Settings property. Change the data abstraction layer to be what knows how to serialize that to and from a string in the database column, and then hurray! You can remove those ToStrings() and Parses() from code everywhere.</p>
<p><span style="text-decoration: underline;">Principle #2 - Query objects can be testability goodness!</span></p>
<p>Problem manifestation: (Basically we were half-way there, but realizing none of the benefits, leading to brittle mocking code.)</p>
<p>Again with the Entity Framework, we had a bunch of smell test code which would be (Test code before:)<br /><br />var resourceSpec = new ResourceSpecification(resourceName, otherQueryParameters);<br />var fakeStore = A.Fake&lt;DeploymentStore&gt;();<br />A.CallTo(() =&gt; fakeStore.GetDeployment(resourceSpec)).Returns(new Deployment { ... });</p>
<p>For all our methods which needed to do some action on an existing deployment, they would take either a ResourceSpecification or a bunch of string parameters, then look up the deployment, then do some stuff with it. Testing them was a PITA because you are constantly jumping through the hoop of 'how do I mock out the retrieval of the actual Deployment resource from the database'?<br /><br />Code before:</p>
<p>var deployment = _context.GetDeployment(resourceSpec);<br /><br />Code after:</p>
<p>var deployment = resourceSpec.GetDeployment(_context);</p>
<p>Test code after:</p>
<p>var resourceSpec = new MockResourceSpecification(new Deployment { });<br /><br /><span style="text-decoration: underline;">Principle #3 - Resolve Queries for objects up-front at the input validation layer, then the actual work can be done</span></p>
<p>This may remind you of the 'query command separation' principle...<br />Code pattern to avoid:</p>
<p>function DoSomethingWithDeployment(ResourceSpecification r, blah, blah, blah)<br />{<br />&nbsp;&nbsp;&nbsp;&nbsp;...<br />&nbsp;&nbsp;&nbsp; CallOtherFunction(r, blah, blah, blah)<br />&nbsp;&nbsp;&nbsp; ...<br />}</p>
<p>function CallOtherFunction(ResourceSpecification r, blah, blah, blah)<br />{<br />&nbsp;&nbsp;&nbsp; Deployment d = r.TryGetDeployment();<br />&nbsp;&nbsp;&nbsp; if (d == null) throw new DeploymentDoesn'tExistException();<br />}<br /><br />Code pattern to use:</p>
<p>function DoSomethingWithDeployment(ResourceSpecification r, blah, blah, blah)<br />{<br />&nbsp;&nbsp;&nbsp; Deployment d = r.GetDeploymentOrBust(); //throws an exception if deployment doesn't exist<br />&nbsp;&nbsp;&nbsp; ...<br />&nbsp;&nbsp;&nbsp; CallOtherFunction(d, blah, blah, blah);<br />&nbsp;&nbsp;&nbsp; ...<br />}</p>
<p>Why is the second code so much better than the first? Because it's now much easier reasoning about and testing the code path for deployment doesn't exist. <br />-validation code is all right there in the function taking <em>user input</em>, which is where you <em>expect</em> that you have to write validation oriented test cases.<br />-contract between your functions got clearer and simpler<br />-the code path it is now one less function deep, so now less test cases for the deeper function!</p>]]></content:encoded>
    </item>
    <item>
      <title>Request and connection throttling when self hosting with OwinHttpListener</title>
      <link>https://docs.microsoft.com/archive/blogs/tilovell/request-and-connection-throttling-when-self-hosting-with-owinhttplistener</link>
      <pubDate>Wed, 11 Mar 2015 12:51:16 GMT</pubDate>
      <dc:creator><![CDATA[tilovell09]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/tilovell/2015/03/11/request-and-connection-throttling-when-self-hosting-with-owinhttplistener/</guid>
      <description><![CDATA[[Disclaimer before we begin: I'm not really an expert on OWIN (henceforth 'owin') or HttpListener -...]]></description>
      <content:encoded><![CDATA[<p>[Disclaimer before we begin: I'm not really an expert on OWIN (henceforth 'owin') or HttpListener - I just researched this as best I could myself so I may get some stuff wrong. Question my authority!]</p>
<p><strong>Self-hosting </strong>a web server using owin instead of using IIS is an attractive option to me partly because of the limitations of my own experience: I am not an IIS expert, and console apps seem like they will be a way to complete control over things that matter without having to spend time learning IIS-isms.</p>
<p>However, while the sample code snippets show it is incredibly easy to get started hosting owin in just a few lines of code, and have it call you to implement your application logic through a very simple interface, it leaves a fundamental question - what if I need to understand and control things deeper in the software stack that I am running on? Which for me is currently OwinHttpListener etc.</p>
<p>For instance, recently we had a discussion around security of one such owin hosted HTTPS endpoint for diagnostics/management, and possible DOS attacks. While in our particular case we don't care that much if this particular endpoint goes down due to a DOS attack, we <em>do</em> care if this one little endpoint becomes an easy&nbsp;way to DOS the entire process or machine. How do you know if your self-hosted web application is robust enough to withstand slowloris attacks, or just traffic-based DOS attacks Answering this required me to do some research, and google just didn't seem to have the answers readily at hand, so I spent some time digging through reflector, MSDN, and reading about Windows/HTTP.SYS/IIS mitigations for DOS attacks. Let me now summarize some of the things&nbsp;I think&nbsp;I learned in my research.</p>
<p>1. There only seem to be a few basic strategies to choose from:</p>
<p><strong>Filtering out</strong> or blacklisting bad traffic:<br />-Examples: IP based filtering, request-header-based filtering. The idea here is that you can put a filter in your request pipeline that detects attacking requests/packets somehow by <em>what they look like</em>, and discarding them. Possibly you do this by manually configuring filtering <em>in reaction</em> to an identified&nbsp;DOS attack. In order to do this you must have logs which let you identify what the bad traffic looks like. Possibly you implement some kind of automatic filtering system, which might actually be more of a <em>throttling</em> system...<strong><br /><br />Throttling </strong>traffic:<br />-You can throttle the server overall and attempt to limit total incoming traffic on your server to what you know your server can handle. The point of this is to stop your application performance degrading by trying to handle too many requests at once...<br />-At application level, if you're in an authenticated app, you can throttle requests per-user, once you've authenticated their connection... <br />-You can throttle clients at lower levels again based on something about what the requests you are getting look like, and e.g. only accept a few concurrent TCP sessions per client IP address. You have to be careful with such IP based policies though. Sometimes due to NAT a single IP address can represent thousands of legitimate users...<br /><strong><br />Out-scaling </strong>traffic:<br />-Throw so much servers and bandwidth into action that you can actually handle all the load coming at you. This one may get expensive, so someone is going to have to weigh up the cost of this vs the cost of not doing this and just being DOSed...</p>
<p>2. In general, your best defense against DOS attacks is a multi-layered one.</p>
<p>At the application level, you can easily write a request handler that throttles the number of simultaneous requests your application instance will try to serve. For instance see answers to:</p>
<p><a href="https://stackoverflow.com/questions/33969/best-way-to-implement-request-throttling-in-asp-net-mvc">https://stackoverflow.com/questions/33969/best-way-to-implement-request-throttling-in-asp-net-mvc</a></p>
<p>But what happens if there are too many requests queued at&nbsp;the next&nbsp;layer below your application, or next piece of server infrastructure in front of your application (think load balancer) waiting to get into your application throttling mechanism, because your application throttling code, even though fast, just isn't handling them fast enough?</p>
<p>BTW. IIS is apparently not vulnerable experimentally to e.g. slowloris. So what about&nbsp;HttpListener?<br /><br />3. In the case of HttpListener, it is built upon HTTP.SYS and there are already some throttling mechanisms in place, for you to use, with reasonable defaults. But if you are not in IIS and are leveraging HTTP.SYS via the <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa364634(v=vs.85).aspx">Http Server API</a> you should be able to exercise control too</p>
<p>Here are <em>some</em> of the properties you can theoretically set, <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa364458(v=vs.85).aspx">once you find the right API</a>:</p>
<p><strong>(per <br />EntityBody - </strong>The time, in seconds, allowed for the request entity body to arrive.<br /><strong>DrainEntityBody - </strong>The time, in seconds, allowed for the HTTP Server API to drain the entity body on a Keep-Alive connection.<br /><strong>RequestQueue - </strong>The time, in seconds, allowed&nbsp; for the request to remain in the request queue before the application picks it up.<br /><strong>IdleConnection - </strong>The time, in seconds, allowed for an idle connection.<strong><br />HeaderWait - </strong>The time, in seconds, allowed for the HTTP Server API to&nbsp;parse the request header.<br /><strong>MinSendRate - </strong>The minimum send rate, in bytes-per-second, for the response. The default response send rate is 150 bytes-per-second.<br /><strong><br /></strong><strong>MaxConnections (per url group)- </strong>The number of connections allowed. Setting this value to HTTP_LIMIT_INFINITE allows an unlimited number of connections.</p>
<p><strong>HttpServerQueueLengthProperty (per request queue) - </strong>Modifies or sets the limit on the number of outstanding requests in the request queue.</p>
<p>Note the documented defaults are:</p>
<table>
<tbody>
<tr><th>Timer</th><th>HTTP Server API Default</th><th>HTTP Server API&nbsp; Wide Configuration</th><th>Application Specific Configuration</th></tr>
<tr>
<td>EntityBody</td>
<td>2 Minutes</td>
<td>No</td>
<td>Yes</td>
</tr>
<tr>
<td>DrainEntityBody</td>
<td>2 Minutes</td>
<td>No</td>
<td>Yes</td>
</tr>
<tr>
<td>RequestQueue</td>
<td>2 Minutes</td>
<td>No</td>
<td>Yes</td>
</tr>
<tr>
<td>IdleConnection</td>
<td>2 Minutes</td>
<td>Yes</td>
<td>Limited</td>
</tr>
<tr>
<td>HeaderWait</td>
<td>2 Minutes</td>
<td>Yes</td>
<td>Limited</td>
</tr>
<tr>
<td>MinSendRate</td>
<td>150 bytes/second</td>
<td>No</td>
<td>Yes</td>
</tr>
</tbody>
</table>
<p>&nbsp;</p>
<table>
<tbody>
<tr>
<td>HttpServerQueueLengthProperty</td>
<td>ULONG</td>
<td>1000</td>
</tr>
</tbody>
</table>
<p>Now <em>luckily,</em> if you are using HttpListener you don't have to go read the unmanaged code docs and figure out how to P/Invoke everything, because there is a <strong>TimeoutManager</strong> on HttpListener which lets you set all these properties via the <a href="https://msdn.microsoft.com/en-us/library/system.net.httplistenertimeoutmanager(v=vs.110).aspx">HttpListenerTimeoutManager</a> class - although they are not as thoroughly documented in the .NET api. But of course the even better news I just implied is just that these default limits exist is already going to&nbsp;be giving your application some sensible filtering and throttling goodness.</p>
<p><br />4. OwinHttpListener comes with some <em>additional </em>checks and balances you can use for throttling requests at its own entry gate (instead of your application's). The way to do this is</p>
<p>owinHttpListener.SetRequestProcessingLimits(int maxAccepts, int maxRequests);</p>
<p>also, for convenience, owinHttpListener <strong>also</strong> lets you do SetRequestQueueLimit(long length), which modifies the aforementioned RequestQueueLength property of the Http Server API which for some reason HttpListener does not expose.<br /><br /></p>]]></content:encoded>
    </item>
    <item>
      <title>Exploring F# (1)</title>
      <link>https://docs.microsoft.com/archive/blogs/tilovell/exploring-f-1</link>
      <pubDate>Tue, 17 Feb 2015 09:48:18 GMT</pubDate>
      <dc:creator><![CDATA[tilovell09]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/tilovell/2015/02/17/exploring-f-1/</guid>
      <description><![CDATA[C# and typescript are starting to feel too familiar and dull, so I went exploring. I fired up my...]]></description>
      <content:encoded><![CDATA[<p>C# and typescript are starting to feel too familiar and dull, so I went exploring. I fired up my first F# console app, and learned a few things. I'm taking a very lazy almost-but-not-quite-just-in-time approach to learning where I ask newbie stack overflow questions as I go along whenever I can't find the answer with a search engine. Here are the things I'm learning</p>
<p><a title="In F# there are many different collection-looking syntaxes that compile into something. What do they mean?" href="https://stackoverflow.com/questions/28567224/in-f-what-are-these-collection-looking-things">In F# there are many different collection-looking syntaxes that compile into something. What do they mean?</a><br /><br />{a, b, c, d}, [a, b, c, d], (a, b, c, d), [|a, b, c, d|]<br /><br />Which is really just another way of asking this: </p>
<div><a class="question-hyperlink" href="https://stackoverflow.com/questions/28552191/why-doesnt-seq-groupby-work-like-i-think-it-will-with-lists-f">Why doesn't Seq.groupBy work like I think it will with lists? (F#)</a></div>
<div><a class="question-hyperlink" href="https://stackoverflow.com/questions/28551721/what-is-difference-between-lists-arrays-and-tuples-in-f">What is difference between lists, arrays, and tuples in F#?</a></div>
<div>How do I filter a list in F#? Question and Answer: <a href="https://stackoverflow.com/questions/23597681/best-functional-way-to-filter-list-in-f">Best Functional Way To Filter List in F#</a></div>
<div><a title="What are the best ways to concatenate lists in F#?" href="https://stackoverflow.com/questions/28567483/what-are-the-best-ways-to-concatenate-lists-in-f">What are the best ways to concatenate lists in F#?</a><br />Why do I ask the question? Because I know the answer is going to be 'it depends...'</div>
<div><a title="Does F# have something like ternary ?: operator?<br />" href="https://stackoverflow.com/questions/28551938/does-f-have-the-ternary-operator">Does F# have a ternary ?: operator?</a><br />(The answer is basically yes... but the syntax is quite different)</div>
<div>If you particularly like/dislike this experimental blog post which is a collection of stack overflow links (looks like link spam doesn't it?) let me know in the comments by all means - your feedback is appreciated.</div>
<div>Was this an easier way of learning than other ways? Well... to be honest all that typing in stackoverflow and this blog takes a lot of extra time. But I love the warm happy feeling that I get when real people on the internet are answering my questions, intelligently, and fast! It is marvelous. Thank you&nbsp;stackoverflow!&nbsp;:)</div>]]></content:encoded>
    </item>
    <item>
      <title>Everything but the language design…?</title>
      <link>https://docs.microsoft.com/archive/blogs/tilovell/everything-but-the-language-design</link>
      <pubDate>Fri, 05 Dec 2014 15:50:44 GMT</pubDate>
      <dc:creator><![CDATA[tilovell09]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/tilovell/2014/12/05/everything-but-the-language-design/</guid>
      <description><![CDATA[So I’ve been reading some history of programming languages. And one question that came up a lot is...]]></description>
      <content:encoded><![CDATA[<p>So I’ve been reading some history of programming languages. And one question that came up a lot is ‘What made this language popular? Why did it live, where others have failed?’ There have been a bunch of different answers, for different languages, and they don’t really have much to do with language design. And it seems like it’s usually not just one thing that goes right being enough. So here is my own attempt to collect a list of things that helped.</p>  <p>1) Start small and with a goal. Then iterate a little. I draw this conclusion from hearing about LISP, SmallTalk, Forth, C, C++, Pascal that they didn’t come from really grandiose designs to take over the world. The projects started with some small goal to achieve, and were happy to achieve success for that goal with some very small level of proving a point, or being adopted by a small community. This will help you achieve point 2:</p>  <p>2) Don’t be vaporware - have a real implementation early and make it as available as possible.</p>  <p>3) Be easy to port the compiler and the language. Because otherwise you’re going to be running only on one system, or you’ll be generating code for one system, and systems tend to die off in popularity over time being replaced by new ones. There are a lot strategies that come up as answer to the ‘be easy to port’ criteria:</p>  <p>3a) use a frontend compiler architecture generating C (or other highly portable language) code</p>  <p>3b) generate code for a virtual machine [e.g. PL/0, Forth]</p>  <p>3c) be a very compact language to define, and therefore easy to implement a boostrapper interpreter (e.g. LISP, Smalltalk)</p>  <p>3d) be self-hosting (compiler written in its own language), so that if some small set of core-language features can be ported in a bootstrap compiler, it can then compile your main compiler can </p>  <p>4) Have some major commercial backing to attach to that will promote your language! Seriously, this has helped a lot of languages over time. :)</p>  <p>5) Once you have a few too many implementations, get standardized. Or at least have a draft standard. Or have a single authoritative reference implementation (maybe open source). Otherwise eventually people are going to say your language is too fragmented and they don’t know which flavor to adopt, and with choice overload they probably won’t choose your language at all.</p>  <p>6) Be lucky.</p>  <p>Having read a bunch of stories now, I think I have decided the programming language story I really like is Forth. Because it’s the story of how one stubborn guy can decide he is wasting too much time learning all these languages which won’t let him do exactly what he want with the underlying machine/OS, and decide he only wants to need to know one perfectly powerful and simple language for the rest of his life, and he figures out a way to do just that:</p>  <p>-he defines a simple abstract machine architecture   <br />-he defines a simple and powerful language which supports structured programming and code reuse, without all these other complex features everyone wants to put in their languages    <br />-he writes most of the compiler in self-hosting fashion    <br />-any time he has a programming project he just ports the compiler bootstrapper and virtual machine to whatever architecture, and he can reuse all his knowledge on a brand new system.    <br />-bliss…?</p>  <p>Even if his language never catches on with the mainstream he can still be quite a productive programmer in his language anyway, especially since he can keep tweaking the language to his own liking.</p>]]></content:encoded>
    </item>
    <item>
      <title>Reading performance counter data in .NET</title>
      <link>https://docs.microsoft.com/archive/blogs/tilovell/reading-performance-counter-data-in-net</link>
      <pubDate>Fri, 21 Nov 2014 15:55:40 GMT</pubDate>
      <dc:creator><![CDATA[tilovell09]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/tilovell/2014/11/21/reading-performance-counter-data-in-net/</guid>
      <description><![CDATA[Nothing you can’t easily write yourself, but while playing around, I wrote this one myself, and...]]></description>
      <content:encoded><![CDATA[<p>Nothing you can’t easily write yourself, but while playing around, I wrote this one myself, and learned one or two things.    <br /></p>  <p>Firsltry, it demonstrates the wrinkle that when reading % processor time you need to specify the instance name of the processor, or the special instance name “_Total”.</p>  <p>Secondly you’ll notice that the % CPU time is a performance counter of type Timer100NsInverse, which results in it showing weird large numbers. </p>  <p>MDSN says “Counters of this type calculate active time by measuring the time that the service was inactive and then subtracting the percentage of active time from 100 percent.” </p>  <p>In other words, it tells you your processor’s IDLE time, as a count of some units of 100Ns intervals, measured over some other arbitrarily sized interval which you presumably need to find out from the counter sample timestamps… complicated, sigh.</p>  <p>I used <a href="https://blogs.msdn.com/b/tilovell/archive/2014/01/31/sample-using-ultimatetimer-threadpooltimer.aspx">UltimateTimer</a> for the timer, of course...</p>  <p>using System;    <br />using System.Collections.Generic;     <br />using System.Diagnostics;     <br />using System.Linq;     <br />using System.Text;     <br />using System.Threading.Tasks;</p>  <p>namespace pcpusher    <br />{     <br />&#160;&#160;&#160; class Program     <br />&#160;&#160;&#160; {     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; static Dictionary&lt;string, string&gt; CountersToMetrics = new Dictionary&lt;string,string&gt;     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; {     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; { @&quot;\Processor(_Total)\% Processor Time&quot;, &quot;percentProcessorTime&quot; }     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; };</p>  <p>&#160;&#160;&#160;&#160;&#160;&#160;&#160; static Dictionary&lt;string, PerformanceCounter&gt; CountersToPC = new Dictionary&lt;string,PerformanceCounter&gt;();</p>  <p>&#160;&#160;&#160;&#160;&#160;&#160;&#160; static void Main(string[] args)    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; {     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; foreach (var k in CountersToMetrics.Keys)     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var parts = k.Split(new []{'\\'}, StringSplitOptions.RemoveEmptyEntries);     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; try     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var safePart = parts[0].Contains(&quot;(&quot;) ? parts[0].Substring(0, parts[0].IndexOf(&quot;(&quot;)) : parts[0];     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var pc = new PerformanceCounter(safePart, parts[1], readOnly: true);     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (parts[0].Contains(&quot;(_Total)&quot;))     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; pc.InstanceName = &quot;_Total&quot;;     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; CountersToPC.Add(k, pc);     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; catch (Exception e)     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Console.WriteLine(&quot;can't get PC: &quot; + k + &quot; &quot; + e.Message);     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>  <p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; using (var timer1 = UltimateTimer.ThreadPoolTimer.Create(onTimer1))    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; timer1.SetTimer(DateTime.Now, 1000, 10);     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Console.WriteLine(&quot;Press any key to end process&quot;);     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Console.ReadLine();     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; timer1.Close();     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>  <p>&#160;&#160;&#160;&#160;&#160;&#160;&#160; private static void onTimer1()    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; {     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; foreach (var k in CountersToMetrics.Keys)     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; try     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var sample1 = CountersToPC[k].NextSample();     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Console.WriteLine(k + &quot; @ &quot; + sample1.TimeStamp100nSec + &quot;(&quot; + sample1.CounterType + &quot;)&quot; + &quot; : &quot; + sample1.RawValue);     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; catch (Exception e)     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Console.WriteLine(k + &quot; couldn't read &quot; + e.Message);     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; }     <br />&#160;&#160;&#160; }     <br />}     </p>]]></content:encoded>
    </item>
  </channel>
</rss>