<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>The Blog of Colin Mackay</title>
	<atom:link href="https://colinmackay.scot/feed/" rel="self" type="application/rss+xml" />
	<link>https://colinmackay.scot</link>
	<description></description>
	<lastBuildDate>Sat, 10 Oct 2020 12:03:47 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>

<image>
	<url>https://colinangusmackay.files.wordpress.com/2019/02/gamer-avatar-256.png?w=32</url>
	<title>The Blog of Colin Mackay</title>
	<link>https://colinmackay.scot</link>
	<width>32</width>
	<height>32</height>
</image> 
<cloud domain='colinmackay.scot' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<atom:link rel="search" type="application/opensearchdescription+xml" href="https://colinmackay.scot/osd.xml" title="The Blog of Colin Mackay" />
	<atom:link rel='hub' href='https://colinmackay.scot/?pushpress=hub'/>
	<item>
		<title>ReSharper test runner still going after tests complete</title>
		<link>https://colinmackay.scot/2020/10/10/resharper-test-runner-still-going-after-tests-complete/</link>
					<comments>https://colinmackay.scot/2020/10/10/resharper-test-runner-still-going-after-tests-complete/#respond</comments>
		
		<dc:creator><![CDATA[Colin Mackay]]></dc:creator>
		<pubDate>Sat, 10 Oct 2020 12:00:01 +0000</pubDate>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[IDisposable]]></category>
		<category><![CDATA[IHost]]></category>
		<category><![CDATA[JetBrains Rider]]></category>
		<category><![CDATA[R#]]></category>
		<category><![CDATA[ReSharper]]></category>
		<category><![CDATA[Rider]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[unit testing]]></category>
		<category><![CDATA[WebApplicationFactory]]></category>
		<guid isPermaLink="false">http://colinmackay.scot/?p=13615</guid>

					<description><![CDATA[I&#8217;ve been writing some tests and I got this message: [RIDER LOGO] Unit Test Runner The process ReSharperTestRunner64:26252 has finished running tests assigned to it, but is still running. Possible reasons are incorrect asynchronous code or lengthy test resource disposal. If test cleanup is expected to be slow, please extend the wait timout in the [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>I&#8217;ve been writing some tests and I got this message:</p>



<figure class="wp-block-image size-large"><a href="https://colinangusmackay.files.wordpress.com/2020/10/image.png"><img data-attachment-id="13617" data-permalink="https://colinmackay.scot/image/" data-orig-file="https://colinangusmackay.files.wordpress.com/2020/10/image.png" data-orig-size="563,144" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image" data-image-description="" data-medium-file="https://colinangusmackay.files.wordpress.com/2020/10/image.png?w=300" data-large-file="https://colinangusmackay.files.wordpress.com/2020/10/image.png?w=563" src="https://colinangusmackay.files.wordpress.com/2020/10/image.png?w=563" alt="" class="wp-image-13617" srcset="https://colinangusmackay.files.wordpress.com/2020/10/image.png 563w, https://colinangusmackay.files.wordpress.com/2020/10/image.png?w=150 150w, https://colinangusmackay.files.wordpress.com/2020/10/image.png?w=300 300w" sizes="(max-width: 563px) 100vw, 563px" /></a></figure>



<blockquote class="wp-block-quote"><p><strong>[RIDER LOGO] Unit Test Runner</strong></p><p>The process ReSharperTestRunner64:26252 has finished running tests assigned to it, but is still running.</p><p>Possible reasons are incorrect asynchronous code or lengthy test resource disposal. If test cleanup is expected to be slow, please extend the wait timout in the Unit Testing options page.</p></blockquote>



<p>It turns out that because I was setting up an <code>IHost</code> as part of my test (via a <code>WebApplicationFactory</code>) that it was what was causing issues. Normally, it would hang around until the application is told to terminate, but nothing in the tests was telling it to terminate.</p>



<p>The culprit was this line of code:</p>



<pre class="wp-block-code"><code>var factory = new WebApplicationFactory&lt;Startup&gt;<strong>()</strong>.WithWebHostBuilder();</code></pre>



<p>The <code>factory</code> is disposable and I wasn&#8217;t calling <code>Dispose()</code> explicitly, or implicitly via a <code>using</code> statement.</p>



<p>The fix to this was simply to wrap the returned <code>WebApplicationFactory&lt;T&gt;</code> in a using block and the test running completed in a timely manner at the end of the tests.</p>



<pre id="block-ba0cf4d7-e91d-49ea-94a4-c9b0c3c3fb5f" class="wp-block-code"><code>using var factory = new WebApplicationFactory&lt;Startup&gt;<strong>()</strong><br>     .WithWebHostBuilder();</code></pre>



<p>or, if by preference, or using an older version of C#:</p>



<pre class="wp-block-code"><code>using (var factory = new WebApplicationFactory&lt;Startup&gt;<strong>()</strong>.WithWebHostBuilder())<br>{<br>    // do stuff with the factory<br>}</code></pre>



<p>Although this was running in JetBrains Rider, it uses ReSharper under the hood, so I&#8217;m assuming this issue happens with ReSharper running in Visual Studio too.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://colinmackay.scot/2020/10/10/resharper-test-runner-still-going-after-tests-complete/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:thumbnail url="https://colinangusmackay.files.wordpress.com/2020/10/image.png" />
		<media:content url="https://colinangusmackay.files.wordpress.com/2020/10/image.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="https://0.gravatar.com/avatar/976babfada7ad5877e400110cc30f777?s=96&#38;d=wavatar&#38;r=PG" medium="image">
			<media:title type="html">Colin Angus Mackay</media:title>
		</media:content>

		<media:content url="https://colinangusmackay.files.wordpress.com/2020/10/image.png?w=563" medium="image" />
	</item>
		<item>
		<title>How to: Tell if a PowerShell script is running as the Administrator</title>
		<link>https://colinmackay.scot/2019/08/10/how-to-tell-if-a-powershell-script-is-running-as-the-administrator/</link>
					<comments>https://colinmackay.scot/2019/08/10/how-to-tell-if-a-powershell-script-is-running-as-the-administrator/#respond</comments>
		
		<dc:creator><![CDATA[Colin Mackay]]></dc:creator>
		<pubDate>Sat, 10 Aug 2019 16:46:37 +0000</pubDate>
				<category><![CDATA[How To]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Tip of the Day]]></category>
		<category><![CDATA[authorisation]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Secuirty]]></category>
		<guid isPermaLink="false">http://colinmackay.scot/?p=13608</guid>

					<description><![CDATA[$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) if (-not ($currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))) { Write-Warning "This script needs to be running as the administrator." Exit 1 } Write-Host "You are running as the administrator." This script gets the current Windows Identity, then queries it to find out if it has the appropriate role.]]></description>
										<content:encoded><![CDATA[<pre>
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if (-not ($currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)))
{
    Write-Warning "This script needs to be running as the administrator."
    Exit 1
}

Write-Host "You are running as the administrator."
</pre>
<p>This script gets the current Windows Identity, then queries it to find out if it has the appropriate role.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://colinmackay.scot/2019/08/10/how-to-tell-if-a-powershell-script-is-running-as-the-administrator/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/976babfada7ad5877e400110cc30f777?s=96&#38;d=wavatar&#38;r=PG" medium="image">
			<media:title type="html">Colin Angus Mackay</media:title>
		</media:content>
	</item>
		<item>
		<title>Ensure Controller actions/classes have authorisation</title>
		<link>https://colinmackay.scot/2018/08/17/ensure-controller-actions-classes-have-authorisation/</link>
					<comments>https://colinmackay.scot/2018/08/17/ensure-controller-actions-classes-have-authorisation/#respond</comments>
		
		<dc:creator><![CDATA[Colin Mackay]]></dc:creator>
		<pubDate>Fri, 17 Aug 2018 09:28:59 +0000</pubDate>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[nunit]]></category>
		<category><![CDATA[Reflection]]></category>
		<category><![CDATA[shouldy]]></category>
		<category><![CDATA[unit testing]]></category>
		<guid isPermaLink="false">http://colinmackay.scot/?p=13597</guid>

					<description><![CDATA[A couple of years ago I wrote a unit test to ensure that all our controller actions (or Controller classes) had appropriate authorisation set up. This ensures we don&#8217;t go to production with a new controller or action that falls back to the default authorisation. We must think about this and explicitly apply it. I&#8217;ve [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>A couple of years ago I wrote a unit test to ensure that all our controller actions (or <code>Controller</code> classes) had appropriate authorisation set up. This ensures we don&#8217;t go to production with a new controller or action that falls back to the default authorisation. We must think about this and explicitly apply it.</p>
<p>I&#8217;ve not thought about that unit test much since then. But this week one of the developers on the team created some new controllers for some new functionality we have, and the unit test failed. Although he&#8217;d put an <code>[Authorize]</code> attribute on some of the controllers, he&#8217;d not done it for all. A common enough lapse. But thanks to this unit test, it was caught early.</p>
<p>Our build server reported it:</p>
<pre>
The provided expression
    should be
0
    but was
1

Additional Info:
    You need to specify [AllowAnonymous] or [Authorize] or a derivative on the following actions, or the class that contains them.
 * MVC.Controllers.CommunicationsPortalController.Index


   at Shouldly.ShouldlyCoreExtensions.AssertAwesomely[T](T actual, Func`2 specifiedConstraint, Object originalActual, Object originalExpected, Func`1 customMessage, String shouldlyMethod)
   at Shouldly.ShouldBeTestExtensions.ShouldBe[T](T actual, T expected, Func`1 customMessage)
   at Shouldly.ShouldBeTestExtensions.ShouldBe[T](T actual, T expected, String customMessage)
   at MVC.UnitTests.Controllers.ControllerAccessTests.All_Controller_Actions_Have_Authorisation() in G:\TeamCityData\TeamCityBuildAgent-3\work\7cc517fed469d618\src\MyApplication\MVC.UnitTests\Controllers\ControllerAccessTests.cs:line 52
</pre>
<p>The code for the unit test is in this GitHub Gist: <a href="https://gist.github.com/colinangusmackay/7c3d44775a61d98ee54fe179f3cd3f21" rel="nofollow">https://gist.github.com/colinangusmackay/7c3d44775a61d98ee54fe179f3cd3f21</a></p>
<p>If you want to use this yourself, you&#8217;ll have to edit line 24 (<code>Assembly mvcAssembly = typeof(HomeController).Assembly;</code>) and provide a controller class in your project. It has also been written for <a href="https://www.nuget.org/packages/NUnit/">NUnit</a>, and we&#8217;re using <a href="https://www.nuget.org/packages/Shouldly/">Shouldly</a> as the assertion library.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://colinmackay.scot/2018/08/17/ensure-controller-actions-classes-have-authorisation/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/976babfada7ad5877e400110cc30f777?s=96&#38;d=wavatar&#38;r=PG" medium="image">
			<media:title type="html">Colin Angus Mackay</media:title>
		</media:content>
	</item>
		<item>
		<title>Creating a Throttle with an ActionBlock &#8211; Addendum (Cancelling)</title>
		<link>https://colinmackay.scot/2018/07/17/creating-a-throttle-with-an-actionblock-addendum-cancelling/</link>
					<comments>https://colinmackay.scot/2018/07/17/creating-a-throttle-with-an-actionblock-addendum-cancelling/#comments</comments>
		
		<dc:creator><![CDATA[Colin Mackay]]></dc:creator>
		<pubDate>Tue, 17 Jul 2018 20:11:46 +0000</pubDate>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[ActionBlock]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C# 7]]></category>
		<category><![CDATA[Task Parallel Library]]></category>
		<category><![CDATA[TPL]]></category>
		<guid isPermaLink="false">http://colinmackay.scot/?p=13592</guid>

					<description><![CDATA[In my previous post I described how to create a throttle with an action block so you wouldn&#8217;t have too many tasks running simultaneously. But what if you want to cancel the tasks? In our use case, we have a hard-limit of 2 minutes to complete the work (or as much as possible). A typical [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><a href="https://colinmackay.scot/2018/07/16/creating-a-throttle-with-actionblock/" title="Creating a throttle with an ActionBlock">In my previous post</a> I described how to create a throttle with an action block so you wouldn&#8217;t have too many tasks running simultaneously. But what if you want to cancel the tasks? </p>
<p>In our use case, we have a hard-limit of 2 minutes to complete the work (or as much as possible). A typical run will take about 30-40 seconds. Sometimes due to network issues or database issues we can&#8217;t complete everything in that time, so we have to stop what we&#8217;re doing and come back later &#8211; and hopefully things will be better and we can complete our run.</p>
<p>So, we need to tell the <code>ActionBlock</code> to stop processing tasks. To do this we pass it a <code>CancellationToken</code>. When we&#8217;ve finished posting work items to the <code>ActionBlock</code> we tell the <code>CancellationTokenSource</code> to cancel after a set time. We also check the cancellation token from within our task for the cancelled state an exit at appropriately safe points.</p>
<pre>
// Before setting up the ActionBlock create a CancellationTokenSource
CancellationTokenSource cts = new CancellationTokenSource();

// Set up the ActionBlock with the CancellationToken passed in the options
ActionBlock&lt;int&gt; throttle = new ActionBlock&lt;int&gt;(
    action: i=&gt;DoStuff(i),
    dataflowBlockOptions: new ExecutionDataflowBlockOptions
    {
        MaxDegreeOfParallelism = 3,
        CancellationToken = cts.Token
    });

// ...Other code  to post work items to the action block...

// After posting the work items, set the timeout in ms.
cts.CancelAfter(2000);

// Wrap the await up to catch the cancellation
Task completionTask = throttle.Completion;
try
{
    await completionTask;
}
catch (TaskCanceledException e)
{
    Console.WriteLine(e);
}
</pre>
<p><small>The code is available on GitHub: <a href="https://github.com/colinangusmackay/ActionBlockThrottle/tree/master/src/04.CancellingTasksInTheActionBlock" rel="nofollow">https://github.com/colinangusmackay/ActionBlockThrottle/tree/master/src/04.CancellingTasksInTheActionBlock</a></small></p>
<h2>Things to watch for</h2>
<p>If you start your timer (When you set <code>cts.CancelAfter(...)</code>) before you&#8217;ve posted your work items, it is possible for the cancellation to trigger before you&#8217;ve posted all your work items, in which case you should check the cancellation token as you&#8217;re posting your work items, otherwise you will be wasting time posting work items that will never be processed.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://colinmackay.scot/2018/07/17/creating-a-throttle-with-an-actionblock-addendum-cancelling/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/976babfada7ad5877e400110cc30f777?s=96&#38;d=wavatar&#38;r=PG" medium="image">
			<media:title type="html">Colin Angus Mackay</media:title>
		</media:content>
	</item>
		<item>
		<title>Creating a Throttle with ActionBlock</title>
		<link>https://colinmackay.scot/2018/07/16/creating-a-throttle-with-actionblock/</link>
					<comments>https://colinmackay.scot/2018/07/16/creating-a-throttle-with-actionblock/#comments</comments>
		
		<dc:creator><![CDATA[Colin Mackay]]></dc:creator>
		<pubDate>Mon, 16 Jul 2018 19:19:17 +0000</pubDate>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[ActionBlock]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C# 7]]></category>
		<category><![CDATA[MaxDegreeOfParallelism]]></category>
		<category><![CDATA[Task Parallel Library]]></category>
		<category><![CDATA[TPL]]></category>
		<guid isPermaLink="false">http://colinmackay.scot/?p=13575</guid>

					<description><![CDATA[We have an application that needs to perform a repetitive task on many external services and record then aggregate the results. As the system has grown the number of external systems has increased which causes some issues as we originally just created a number of tasks and waited on them all completing. This overwhelmed various [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>We have an application that needs to perform a repetitive task on many external services and record then aggregate the results. As the system has grown the number of external systems has increased which causes some issues as we originally just created a number of tasks and waited on them all completing. This overwhelmed various things as all these tasks were launched near simultaneously. We needed a way to throttle each task, so we used an <code>ActionBlock</code>, part of the Task Parallel Library&#8217;s <a href="https://www.nuget.org/packages/System.Threading.Tasks.Dataflow/">System.Threading.Tasks.Dataflow</a> package.</p>
<h2>Basic setup</h2>
<p>I&#8217;ve created a little application that does some &#8220;work&#8221; (by sleeping for random periods of a few milliseconds). It looks like this:</p>
<pre>
class Program
{
    private static byte[] work = new byte[100];
    static void Main(string[] args)
    {
        new Random().NextBytes(work);
        for (int i = 0; i &lt; work.Length; i++)
        {
            DoStuff(i);
        }
        Console.WriteLine(&quot;All done!&quot;);
        Console.ReadLine();
    }

    static void DoStuff(int data)
    {
        int wait = work[data];
        Console.WriteLine($&quot;{data:D3} : Work will take {wait}ms&quot;);
        Thread.Sleep(wait);
    }
}
</pre>
<p><small>Also available on GitHub: <a href="https://github.com/colinangusmackay/ActionBlockThrottle/tree/master/src/00.BasicSerialImplementation" rel="nofollow">https://github.com/colinangusmackay/ActionBlockThrottle/tree/master/src/00.BasicSerialImplementation</a></small></p>
<p>This is the very basic application that I&#8217;ll be parallelising.</p>
<h2>A simple ActionBlock</h2>
<p>Here is the same program, but with the work wrapped in an <code>ActionBlock</code>. It is a bit more complex, and currently for little extra benefit as we&#8217;re not done anything to parallelise it yet.</p>
<pre>
class Program
{
    private static byte[] work = new byte[100];
    static async Task Main(string[] args)
    {
        new Random().NextBytes(work);

        // Define the throttle
        var throttle = new ActionBlock&lt;int&gt;(i=&gt;DoStuff(i));
        
        // Create the work set.
        for (int i = 0; i &lt; work.Length; i++)
        {
            throttle.Post(i);
        }

        // indicate that there is no more work 
        throttle.Complete();

        // Wait for the work to complete.
        await throttle.Completion;

        Console.WriteLine(&quot;All done!&quot;);
        Console.ReadLine();
    }

    static void DoStuff(int data)
    {
        int wait = work[data];
        Console.WriteLine($&quot;{data:D3} : Work will take {wait}ms&quot;);
        Thread.Sleep(wait);
    }
}
</pre>
<p><small>Also available on GitHub: <a href="https://github.com/colinangusmackay/ActionBlockThrottle/tree/master/src/01.SimpleActionBlock" rel="nofollow">https://github.com/colinangusmackay/ActionBlockThrottle/tree/master/src/01.SimpleActionBlock</a></small></p>
<p>This does the same as the first version, by default an <code>ActionBlock</code> does not parallelise any of the processing of the work. All the work is still processed sequentially.</p>
<h2>The producer and consumer run in parallel</h2>
<p>I said before this is for &#8220;little extra benefit&#8221;. So I should explain what I mean by that. There is now some parallelisation between the producer and the consumer portions. The <code>for</code> loop that contains the <code>throttle.Post(...)</code> (the producer) is running in parallel with the calls to <code>DoStuff()</code> (the consumer). You can see this if you slow down the producer and introduce some <code>Console.WriteLine(...)</code> statements to see things in action.</p>
<p>This is some example output from that version of the code.</p>
<pre>
000 : Posting Work Item 0.
000 : Work will take 32ms
001 : Posting Work Item 1.
001 : Work will take 179ms
002 : Posting Work Item 2.
003 : Posting Work Item 3.
004 : Posting Work Item 4.
002 : Work will take 28ms
005 : Posting Work Item 5.
003 : Work will take 9ms
004 : Work will take 100ms
006 : Posting Work Item 6.
007 : Posting Work Item 7.
005 : Work will take 109ms
008 : Posting Work Item 8.
009 : Posting Work Item 9.
</pre>
<p>I slowed the producer by introducing a wait of 50ms between posting items. As you can see in the time it took to post 10 items (it is zero based) it had only processed 6 items, but the producer and consumer are running simultaneously, so it is not waiting until the producer has completed before it starts processing the items.</p>
<p><small>Available on GitHub: <a href="https://github.com/colinangusmackay/ActionBlockThrottle/blob/master/src/02.SimpleActionBlockShowingProducerConsumer" rel="nofollow">https://github.com/colinangusmackay/ActionBlockThrottle/blob/master/src/02.SimpleActionBlockShowingProducerConsumer</a></small></p>
<h2>Setting the Throttle</h2>
<p>Finally, we get to the point that we can set some sort of throttle. In our use case we had a lot of work to do, most of which was actually waiting for external systems to respond, but if we threw everything in at once it would be overwhelmed. </p>
<p>Now we can set up some parallelism. The <code>ActionBlock</code> can take some options in the form of an <code>ExecutionDataflowBlockOptions</code> object. It has many options, but the one we&#8217;re interested in is <code>MaxDegreeOfParallelism</code>. The creation of the action block now looks like this:</p>
<pre>
ActionBlock&lt;int&gt; throttle = new ActionBlock&lt;int&gt;(
    action: i=&gt;DoStuff(i),
    dataflowBlockOptions: new ExecutionDataflowBlockOptions
    {
        MaxDegreeOfParallelism = 3
    });
</pre>
<p>In our example, we&#8217;re just going to set it to 3 for demonstration purposes, but you&#8217;ll likely want to experiment to see where you get the best results.</p>
<p>In the example application, I also added a small counter (<code>tasksInProgress</code>) to keep a count of the number of active tasks and added it to the <code>Console.WriteLine(...)</code> in the <code>DoStuff(...)</code> method. The output looks like this:</p>
<pre>
000 : Posting Work Item 0.
000 : [TIP:1] Work will take 34ms
001 : Posting Work Item 1.
001 : [TIP:2] Work will take 216ms
002 : Posting Work Item 2.
002 : [TIP:2] Work will take 177ms
003 : Posting Work Item 3.
003 : [TIP:3] Work will take 183ms
004 : Posting Work Item 4.
005 : Posting Work Item 5.
006 : Posting Work Item 6.
007 : Posting Work Item 7.
008 : Posting Work Item 8.
004 : [TIP:3] Work will take 15ms
009 : Posting Work Item 9.
005 : [TIP:3] Work will take 57ms
006 : [TIP:3] Work will take 85ms
010 : Posting Work Item 10.
... etc...
</pre>
<p>You can see at the start the number of simultaneously running tasks builds up to the <code>MaxDegreeOfParallelism</code> value that was set. So long as the producer part is producing work items faster than the consumer can consume them, the tasks in progress (TIP) will stay at or close to the <code>MaxDegreeOfParallelism</code>.</p>
<p><small>Code available on GitHub: <a href="https://github.com/colinangusmackay/ActionBlockThrottle/tree/master/src/03.MaxDegreesOfParallelismAsAThrottle" rel="nofollow">https://github.com/colinangusmackay/ActionBlockThrottle/tree/master/src/03.MaxDegreesOfParallelismAsAThrottle</a></small></p>
]]></content:encoded>
					
					<wfw:commentRss>https://colinmackay.scot/2018/07/16/creating-a-throttle-with-actionblock/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/976babfada7ad5877e400110cc30f777?s=96&#38;d=wavatar&#38;r=PG" medium="image">
			<media:title type="html">Colin Angus Mackay</media:title>
		</media:content>
	</item>
		<item>
		<title>Comparing logically adjacent rows in a database table</title>
		<link>https://colinmackay.scot/2018/07/13/comparing-logically-adjacent-rows-in-a-database-table/</link>
					<comments>https://colinmackay.scot/2018/07/13/comparing-logically-adjacent-rows-in-a-database-table/#respond</comments>
		
		<dc:creator><![CDATA[Colin Mackay]]></dc:creator>
		<pubDate>Fri, 13 Jul 2018 19:38:09 +0000</pubDate>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[SQL]]></category>
		<guid isPermaLink="false">http://colinmackay.scot/?p=13582</guid>

					<description><![CDATA[If you have database table that stores something such as when an action occurred, it might be useful to work out how far apart these events are. It is easy to join different tables together, or even if you have a self-referential join to join rows of the same table together if an existing relationship [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>If you have database table that stores something such as when an action occurred, it might be useful to work out how far apart these events are. It is easy to join different tables together, or even if you have a self-referential join to join rows of the same table together if an existing relationship exists. But what if you want to join on a logically adjacent row?</p>
<p>First of all, I&#8217;m saying &#8220;logically adjacent row&#8221; because relational databases are set based, there is no concept of sequence unless we specifically define it (e.g. an <code>ORDER BY</code> clause). So we have to define what adjacent row means in the context of what ever query we want. It could be based on date/time (as is the example I&#8217;m going to show you later), or some other sort order (alphabetical listing, distance from a point, etc.)</p>
<p>So, to start with we need a way of ordering the data that we have.</p>
<pre>
SELECT 
    RANK() OVER (ORDER BY ColumnThatDefinesSequence) as [Sequence], 
    PrimaryKeyIdColumn
FROM MyTable
</pre>
<p>What this will do is create a result set consisting of an uninterrupted sequence that increments by one each time which maps to the primary key of the table. You can add in filters such as a <code>WHERE</code> clause to remove any rows you are not interested in and the <code>RANK</code> function will always ensure that it results in a sequence that starts at one and increments by one, thus effectively closing the gaps in the source data&#8217;s key. `Sequence` will become our key later on.</p>
<p>Next, we need join each adjacent row together:</p>
<pre>
WITH Seq(Sequence, Id)
AS
(
    SELECT 
        RANK() OVER (ORDER BY ColumnThatDefinesSequence) as [Sequence], 
        PrimaryKeyIdColumn
    FROM MyTable
)
SELECT *
FROM Seq s1
INNER JOIN Seq s2 ON s1.[Sequence] = s2.[Sequence]-1
</pre>
<p>This now produces a result set that has each adjacent row joined with each other. Because we know that the <code>Sequence</code> will always increment by one compared to its logically adjacent neighbour we can join against the row with the <code>Sequence</code> number one lower than this row.</p>
<p>This can now use used with the source table to get the final data set.</p>
<pre>
WITH Seq(Sequence, Id)
AS
(
    SELECT 
        RANK() OVER (ORDER BY ColumnThatDefinesSequence) as [Sequence], 
        PrimaryKeyIdColumn
    FROM MyTable
)
SELECT mt1.*, mt2.*
FROM Seq s1
INNER JOIN Seq s2 ON s1.[Sequence] = s2.[Sequence]-1
INNER JOIN MyTable mt1 ON mt1.PrimaryKeyId = s1.Id
INNER JOIN MyTable mt2 ON mt2.PrimaryKeyId = s2.Id
</pre>
<p>The result set here is now just the source table rows joined to their logically adjacent row.</p>
<p>So, if your source table is a set of actions and it has a column of an action occurred (which we&#8217;ll call <code>ActionDate</code> in this example), you could find out how far apart the actions are with a query like this.</p>
<pre>
WITH Seq(Sequence, Id)
AS
(
    SELECT 
        RANK() OVER (ORDER BY ColumnThatDefinesSequence) as [Sequence], 
        PrimaryKeyIdColumn
    FROM MyTable
)
SELECT 
    mt1.PrimaryKeyId AS FirstActionId, 
    mt1.ActionDate AS FirstActionDate, 
    mt2.PrimaryKeyId AS SecondActionId, 
    mt2.ActionDate AS SecondActionDate 
    DATEDIFF(SECOND, mt1.ActionDate, mt2.ActionDate) AS TimeBetweenActions
FROM Seq s1
INNER JOIN Seq s2 ON s1.[Sequence] = s2.[Sequence]-1
INNER JOIN MyTable mt1 ON mt1.PrimaryKeyId = s1.Id
INNER JOIN MyTable mt2 ON mt2.PrimaryKeyId = s2.Id
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://colinmackay.scot/2018/07/13/comparing-logically-adjacent-rows-in-a-database-table/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/976babfada7ad5877e400110cc30f777?s=96&#38;d=wavatar&#38;r=PG" medium="image">
			<media:title type="html">Colin Angus Mackay</media:title>
		</media:content>
	</item>
		<item>
		<title>Paramore Brighter: The Russian Doll Model</title>
		<link>https://colinmackay.scot/2018/03/31/paramore-brighter-the-russian-doll-model/</link>
					<comments>https://colinmackay.scot/2018/03/31/paramore-brighter-the-russian-doll-model/#respond</comments>
		
		<dc:creator><![CDATA[Colin Mackay]]></dc:creator>
		<pubDate>Sat, 31 Mar 2018 16:29:42 +0000</pubDate>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[brighter]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[command processor]]></category>
		<category><![CDATA[Paramore.Brighter]]></category>
		<guid isPermaLink="false">http://colinmackay.scot/?p=13559</guid>

					<description><![CDATA[I&#8217;ve mentioned a bit about the attributing the handler and the step and timing parameters, but I&#8217;ve not explained them properly in previous posts (&#8220;Retrying commands&#8221; mentions steps, and &#8220;Don&#8217;t Repeat Yourself&#8221; also mentions timings). So, I&#8217;ve created a small project to demonstrate what they mean and how it all operates. The code for this [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>I&#8217;ve mentioned a bit about the attributing the handler and the <code>step</code> and <code>timing</code> parameters, but I&#8217;ve not explained them properly in previous posts (&#8220;<a href="https://colinmackay.scot/2018/03/02/paramore-brighter-with-quality-of-service-retrying-commands/">Retrying commands</a>&#8221; mentions steps, and &#8220;<a href="https://colinmackay.scot/2018/03/18/paramore-brighter-dry-with-custom-decorated-command-handlers/">Don&#8217;t Repeat Yourself</a>&#8221; also mentions timings). So, I&#8217;ve created a small project to demonstrate what they mean and how it all operates.</p>
<p>The <a href="https://github.com/colinangusmackay/BrighterRecipes/tree/master/src/steps-and-timing" rel="noopener" target="_blank">code for this post is available on GitHub</a>.</p>
<p>If you just have the target handler, that is the handler that is directly tied to the <code>Command</code> that got <code>Sent</code>, without any decorations, then we won&#8217;t have to worry about the Russian Doll Model. There is only one handler, and it goes directly there. However, as soon as you start decorating your handler with other handlers it comes in to effect.</p>
<h3>Timing</h3>
<p>As the name suggests this affects when the decorated handler will run. Either before or after the target handler. However, handlers set to run &#8220;before&#8221; also get an opportunity to do things afterwards as well due to the Russian Doll model, as we&#8217;ll see.</p>
<p>The <code>Before</code> handler wraps the target handler, and the target handler wraps the <code>After</code> handler. At the very centre is the inner most <code>After</code> handler. Like this:</p>
<p><figure data-shortcode="caption" id="attachment_13566" aria-describedby="caption-attachment-13566" style="width: 1000px" class="wp-caption aligncenter"><a href="https://colinangusmackay.files.wordpress.com/2018/03/russian-doll-model-before-and-after1.png"><img loading="lazy" data-attachment-id="13566" data-permalink="https://colinmackay.scot/2018/03/31/paramore-brighter-the-russian-doll-model/russian-doll-model-before-and-after-2/" data-orig-file="https://colinangusmackay.files.wordpress.com/2018/03/russian-doll-model-before-and-after1.png" data-orig-size="1920,1080" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Russian Doll Model: Before and After" data-image-description="&lt;p&gt;Russian Doll Model with Before and After handlers&lt;/p&gt;
" data-medium-file="https://colinangusmackay.files.wordpress.com/2018/03/russian-doll-model-before-and-after1.png?w=300" data-large-file="https://colinangusmackay.files.wordpress.com/2018/03/russian-doll-model-before-and-after1.png?w=640" src="https://colinangusmackay.files.wordpress.com/2018/03/russian-doll-model-before-and-after1.png" alt="Russian Doll Model with Before and After handlers" width="1000" height="563" class="size-full wp-image-13566" srcset="https://colinangusmackay.files.wordpress.com/2018/03/russian-doll-model-before-and-after1.png?w=1000&amp;h=563 1000w, https://colinangusmackay.files.wordpress.com/2018/03/russian-doll-model-before-and-after1.png?w=150&amp;h=84 150w, https://colinangusmackay.files.wordpress.com/2018/03/russian-doll-model-before-and-after1.png?w=300&amp;h=169 300w, https://colinangusmackay.files.wordpress.com/2018/03/russian-doll-model-before-and-after1.png?w=768&amp;h=432 768w, https://colinangusmackay.files.wordpress.com/2018/03/russian-doll-model-before-and-after1.png?w=1024&amp;h=576 1024w, https://colinangusmackay.files.wordpress.com/2018/03/russian-doll-model-before-and-after1.png 1920w" sizes="(max-width: 1000px) 100vw, 1000px" /></a><figcaption id="caption-attachment-13566" class="wp-caption-text">Russian Doll Model with Before and After handlers</figcaption></figure></p>
<p>The red arrows in the diagram show the flow of the code. So, for a handler with a before and after decoration, the code will execute in the following order:</p>
<ul>
<li>The &#8220;Before&#8221; timing <code>Handle</code> method</li>
<li>The Target <code>Handle</code> method</li>
<li>The &#8220;After&#8221; timing <code>Handle</code> method</li>
<li>The Target <code>Handle</code> method continued (after any call to the <code>base.Handle()</code>)</li>
<li>The &#8220;Before&#8221; timing <code>Handle</code> method continued (after any call to the <code>base.Handle()</code>)</li>
</ul>
<p>Obviously, you do not have to call the </code>base.Handler</code> from your handler, but if you do that you break the Russian Doll Model, subsequent steps will not be called. Throwing an exception also will not call subsequent steps. According to Ian Cooper, the originator of the Paramore Brighter framework, <a href="https://gitter.im/iancooper/Paramore?at=559d1e9821e1d6761f2a2f00" target="_blank">&#8220;An exception is the preferred mechanism to exit a pipeline&#8221;</a>.</p>
<h3>Steps</h3>
<p>If you have multiple decorators with the same <code>timing</code>, it may be important to let the framework know in which order to run them.</p>
<p>For <code>Before</code> handlers the steps ascend, so step 1, followed by step 2, followed by step 3, etc. For <code>After</code> handlers the steps descend, so step 3, followed by step 2, followed by step 1.</p>
<p><figure data-shortcode="caption" id="attachment_13569" aria-describedby="caption-attachment-13569" style="width: 1000px" class="wp-caption aligncenter"><a href="https://colinangusmackay.files.wordpress.com/2018/03/russian-doll-model-7-layer.png"><img loading="lazy" data-attachment-id="13569" data-permalink="https://colinmackay.scot/2018/03/31/paramore-brighter-the-russian-doll-model/russian-doll-model-7-layer/" data-orig-file="https://colinangusmackay.files.wordpress.com/2018/03/russian-doll-model-7-layer.png" data-orig-size="1026,806" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Russian Doll Model 7 Layers" data-image-description="" data-medium-file="https://colinangusmackay.files.wordpress.com/2018/03/russian-doll-model-7-layer.png?w=300" data-large-file="https://colinangusmackay.files.wordpress.com/2018/03/russian-doll-model-7-layer.png?w=640" src="https://colinangusmackay.files.wordpress.com/2018/03/russian-doll-model-7-layer.png" alt="Russian Doll Model 7 Layers" width="1000" height="786" class="size-full wp-image-13569" srcset="https://colinangusmackay.files.wordpress.com/2018/03/russian-doll-model-7-layer.png?w=1000&amp;h=786 1000w, https://colinangusmackay.files.wordpress.com/2018/03/russian-doll-model-7-layer.png?w=150&amp;h=118 150w, https://colinangusmackay.files.wordpress.com/2018/03/russian-doll-model-7-layer.png?w=300&amp;h=236 300w, https://colinangusmackay.files.wordpress.com/2018/03/russian-doll-model-7-layer.png?w=768&amp;h=603 768w, https://colinangusmackay.files.wordpress.com/2018/03/russian-doll-model-7-layer.png?w=1024&amp;h=804 1024w, https://colinangusmackay.files.wordpress.com/2018/03/russian-doll-model-7-layer.png 1026w" sizes="(max-width: 1000px) 100vw, 1000px" /></a><figcaption id="caption-attachment-13569" class="wp-caption-text">7 Layer Russian Doll Model (3 Before, Target, and 3 After)</figcaption></figure></p>
<p>The red arrows in the diagram show the flow of the code. So, for a handler with three before and after decorations, the code will execute in the following order:</p>
<ul>
<li>Step 1 for the &#8220;Before&#8221; timing <code>Handle</code> method</li>
<li>Step 2 for the &#8220;Before&#8221; timing <code>Handle</code> method</li>
<li>Step 3 for the &#8220;Before&#8221; timing <code>Handle</code> method</li>
<li>The Target <code>Handle</code> method</li>
<li>Step 3 for the &#8220;After&#8221; timing <code>Handle</code> method</li>
<li>Step 2 for the &#8220;After&#8221; timing <code>Handle</code> method</li>
<li>Step 1 for the &#8220;After&#8221; timing <code>Handle</code> method</li>
<li>Step 2 for the &#8220;After&#8221; timing <code>Handle</code> method continued (after any call to the <code>base.Handle()</code>)</li>
<li>Step 3 for the &#8220;After&#8221; timing <code>Handle</code> method continued (after any call to the <code>base.Handle()</code>)</li>
<li>The Target <code>Handle</code> method continued (after any call to the <code>base.Handle()</code>)</li>
<li>Step 3 for the &#8220;Before&#8221; timing <code>Handle</code> method continued (after any call to the <code>base.Handle()</code>)</li>
<li>Step 2 for the &#8220;Before&#8221; timing <code>Handle</code> method continued (after any call to the <code>base.Handle()</code>)</li>
<li>Step 1 for the &#8220;Before&#8221; timing <code>Handle</code> method continued (after any call to the <code>base.Handle()</code>)</li>
</ul>
<h3>Base Handler classes</h3>
<p>You can, of course, create a class between <code>RequestHandler</code> and your own target handler class and this adds its own complexity to the model.</p>
<p>Any handler attributes added to the base class will be added to the pipeline and those handlers will be run for the time, and step they specify. Also, remember that the base class has its own <code>Handle</code> method which can have code before and and after the call to the base class&#8217;s implementation.</p>
<p>This can be seen in the <a href="https://github.com/colinangusmackay/BrighterRecipes/tree/master/src/steps-and-timing" rel="noopener" target="_blank">sample project on GitHub</a>, which you can download and experiment with to see how the code is executed.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://colinmackay.scot/2018/03/31/paramore-brighter-the-russian-doll-model/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/976babfada7ad5877e400110cc30f777?s=96&#38;d=wavatar&#38;r=PG" medium="image">
			<media:title type="html">Colin Angus Mackay</media:title>
		</media:content>

		<media:content url="https://colinangusmackay.files.wordpress.com/2018/03/russian-doll-model-before-and-after1.png" medium="image">
			<media:title type="html">Russian Doll Model with Before and After handlers</media:title>
		</media:content>

		<media:content url="https://colinangusmackay.files.wordpress.com/2018/03/russian-doll-model-7-layer.png" medium="image">
			<media:title type="html">Russian Doll Model 7 Layers</media:title>
		</media:content>
	</item>
		<item>
		<title>Paramore Brighter: DRY with Custom Decorated Command Handlers</title>
		<link>https://colinmackay.scot/2018/03/18/paramore-brighter-dry-with-custom-decorated-command-handlers/</link>
					<comments>https://colinmackay.scot/2018/03/18/paramore-brighter-dry-with-custom-decorated-command-handlers/#comments</comments>
		
		<dc:creator><![CDATA[Colin Mackay]]></dc:creator>
		<pubDate>Sun, 18 Mar 2018 14:01:55 +0000</pubDate>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[command processor]]></category>
		<category><![CDATA[paramore]]></category>
		<category><![CDATA[Paramore.Brighter]]></category>
		<guid isPermaLink="false">http://colinmackay.scot/?p=13555</guid>

					<description><![CDATA[You may wish to add similar functionality to many (or all) command handlers. The typical example is logging. You can decorate a command handler in a similar way to the policies I showed in previous posts to add common functionality. I&#8217;ve used this technique to guard the handler from invalid command arguments/parameters (essentially a validator), [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>You may wish to add similar functionality to many (or all) command handlers. The typical example is logging. You can decorate a command handler in a similar way to the policies I showed in previous posts to add common functionality. I&#8217;ve used this technique to guard the handler from invalid command arguments/parameters (essentially a validator), and for ensuring that we ping our APM (Application Performance Management) tool when a command completes. I&#8217;ll use the latter to demonstrate creating a custom decorator and handler to initiate this common code.</p>
<p>Paramore Brighter Command Processor will look for any attributes derived from <code>RequestHandlerAttribute</code> that are added to the <code>Handle</code> method on your command handler class. It will then use them to build a pipeline for your command.</p>
<p>So, in the example here, our attribute class looks like this: </p>
<pre>
public class HeartbeatAttribute : RequestHandlerAttribute
{
    public HeartbeatAttribute(int step, HandlerTiming timing = HandlerTiming.After) : base(step, timing)
    {
    }

    public override Type GetHandlerType()
    {
        return typeof(HeartbeatHandler&lt;&gt;);
    }
}
</pre>
<p>We are deriving from <code>RequestHandlerAttribute</code>, and it has an abstract method that you need to implement. <code>GetHandlerType()</code> returns the type of handler that needs to be instantiated to handle the common task. </p>
<p>The <code>RequestHandlerAttribute</code> class also takes two arguments for its constructor that you either need to capture from users of your attribute or supply yourself. It takes a <code>step</code> and a <code>timing</code> parameter. Since we&#8217;ve already talked about <code>step</code> in a <a href="/2018/03/02/paramore-brighter-with-quality-of-service-retrying-commands/">previous post</a> we&#8217;ll move on to talking about <code>timing</code>.</p>
<p>The two options for <code>timing</code> are <code>Before</code> and <code>After</code>. In the previous examples the <code>timing</code> has been implicitly set to <code>Before</code> because the handler needed perform actions before your target handler (the one that you decorated). If you set the <code>timing</code> to <code>After</code> it only actions after your target handler.</p>
<p>In the example here, the timing is set <code>After</code> because we want to make sure that the the handler completed correctly before our handler runs. So, if it throws an exception then our heartbeat handler won&#8217;t run. If you need to perform an action <strong>before</strong> and <strong>after</strong>, then set the timing to <code>Before</code>, and perform actions before the call to <code>base.Handle()</code> and after the call.</p>
<p>Our heartbeat handler looks like this:</p>
<pre>
public class HeartbeatHandler&lt;TRequest&gt; : RequestHandler&lt;TRequest&gt; where TRequest : class, IRequest
{
    public override TRequest Handle(TRequest command)
    {
        // We would probably call a heartbeat service at this point.
        // But for demonstration we'll just write to the console.

        Console.WriteLine($"Heartbeat pulsed for {command.GetType().FullName}");
        string jsonString = JsonConvert.SerializeObject(command);
        Console.WriteLine(jsonString);

        return base.Handle(command);
    }
}
</pre>
<p>The important thing, as will all handlers, is to remember the call to the <code>base.Handle()</code> which ensures the pipeline is continued.</p>
<p>The target handler decoration looks like this:</p>
<pre>
[FallbackPolicy(step:1, backstop:true, circuitBreaker:false)]
[UsePolicy(policy: "GreetingRetryPolicy", step:2)]
[Heartbeat(step:3)]
public override SalutationCommand Handle(SalutationCommand command)
{
    // Stuff to handle the command.

    return base.Handle(command);
}
</pre>
<p>The first two decorators are from previous posts (<a href="https://colinmackay.scot/2018/03/02/paramore-brighter-with-quality-of-service-retrying-commands/">Retrying Commands</a> and <a href="https://colinmackay.scot/2018/02/16/paramore-brighter-implementing-a-fallback-exception-handler/">Implementing a fallback exception handler</a>) while the third is our new decorator.</p>
<p>When run, you can see that if the service fails completely (i.e. all the retries failed) then the Heartbeat does not get run. However, if the command succeeds then the heartbeat handler is run. Our APM knows the command succeeded and can display that.</p>
<h3>Remember</h3>
<p>Remember to wire up the handler, as with all handlers, to your dependency injection framework, so that it can be correctly instantiated:</p>
<pre>
serviceCollection.AddScoped(typeof(HeartbeatHandler&lt;&gt;));
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://colinmackay.scot/2018/03/18/paramore-brighter-dry-with-custom-decorated-command-handlers/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/976babfada7ad5877e400110cc30f777?s=96&#38;d=wavatar&#38;r=PG" medium="image">
			<media:title type="html">Colin Angus Mackay</media:title>
		</media:content>
	</item>
		<item>
		<title>Paramore Brighter with Quality of Service: Retrying Commands</title>
		<link>https://colinmackay.scot/2018/03/02/paramore-brighter-with-quality-of-service-retrying-commands/</link>
					<comments>https://colinmackay.scot/2018/03/02/paramore-brighter-with-quality-of-service-retrying-commands/#comments</comments>
		
		<dc:creator><![CDATA[Colin Mackay]]></dc:creator>
		<pubDate>Fri, 02 Mar 2018 14:07:28 +0000</pubDate>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[paramore]]></category>
		<category><![CDATA[Paramore.Brighter]]></category>
		<category><![CDATA[polly]]></category>
		<guid isPermaLink="false">http://colinmackay.scot/?p=13542</guid>

					<description><![CDATA[Paramore Brighter supports Policies to maintain quality of service. This is useful when your command makes calls to external services, whether they are databases, web services, or any other end point that exists out of the process of your application. You can set up retry policies, circuit-breaker policies, and timeout policies. For this post, we&#8217;ll [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Paramore Brighter supports Policies to maintain quality of service. This is useful when your command makes calls to external services, whether they are databases, web services, or any other end point that exists out of the process of your application. You can set up retry policies, circuit-breaker policies, and timeout policies. For this post, we&#8217;ll concentrate on setting up a retry policy.</p>
<p>The <a href="https://github.com/colinangusmackay/BrighterRecipes/tree/master/src/quality-of-service" rel="noopener" target="_blank">full code from this post is available on GitHub.com</a>.</p>
<p>The <code>SalutationHandler</code> that we&#8217;ve been using in previous posts now emulates an external failure by throwing an exception in some cases. The policy handler will catch the exception and act on it, retrying the command if necessary.</p>
<h3>Set up the policy</h3>
<p>First off let&#8217;s set up the policy. In this case I&#8217;m going for an exponential backoff (doubling the wait time on each attempt) and it will perform a maximum of 4 attempts.</p>
<pre>
private static IAmAPolicyRegistry GetPolicies()
{
    var policyRegistry = new PolicyRegistry();

    // These are the default policies that must exist. 
    // We're not using them, so we're setting them to No-op
    policyRegistry.Add(CommandProcessor.RETRYPOLICY, Policy.NoOp());
    policyRegistry.Add(CommandProcessor.RETRYPOLICYASYNC, Policy.NoOpAsync());
    policyRegistry.Add(CommandProcessor.CIRCUITBREAKER, Policy.NoOp());
    policyRegistry.Add(CommandProcessor.CIRCUITBREAKERASYNC, Policy.NoOpAsync());
    
    // Sets up the policy that we're going to use 
    // for the SaluationHandler
    var greetingRetryPolicy = Policy
        .Handle&lt;Exception&gt;()
        .WaitAndRetry(new[]
        {
            TimeSpan.FromSeconds(1),
            TimeSpan.FromSeconds(2), 
            TimeSpan.FromSeconds(4) 
        }, (exception, timeSpan) =&gt;
        {
            Console.WriteLine($" ** An error occurred: {exception.Message}");
            Console.WriteLine($" ** Waiting {timeSpan.Seconds} seconds until retry.");
        });

    policyRegistry.Add("GreetingRetryPolicy", greetingRetryPolicy);
    return policyRegistry;
}
</pre>
<p>The policies are defined using <a href="https://github.com/App-vNext/Polly/wiki" rel="noopener" target="_blank">Polly</a>, a .NET resilience and transient-fault-handling library.</p>
<p>The <code>.Handle&lt;Exception&gt;()</code> means the policy handles all exceptions. You might want it to be more specific for your use case. e.g. <code>SqlException</code> for database errors.</p>
<p>The <code>WaitAndRetry(...)</code> takes a set of timings (as <code>TimeSpan</code> objects) for how long to wait between attempts and an <code>Action</code> which is run between attempts. Although there are only 3 times here, it will make 4 attempts. Each time represents the amount of time <em>after</em> an attempt before retrying. The first attempt is performed immediately.</p>
<p>The <code>Action</code> allows you to set up what you want to do between attempts. In this case, I&#8217;ve only had it output to the console. You may wish to log the error, or take other actions that might help it work.</p>
<p>Finally, we add the policy to the registry and give it a name, so we can refer to it on our <code>Handle</code> method in our command handler class.</p>
<p>In order for Brighter to be able to use this policy, the Handler for it needs to be registered in the IoC container.</p>
<pre>
serviceCollection.AddScoped(typeof(ExceptionPolicyHandler&lt;&gt;));
</pre>
<p><H3>The Command Handler</H3></p>
<p>It should be noted that the regardless of the number retries that are made, they are all processed through the same instance of the command handler. This may be important if you store state to do with the progress of the command. It also might be important in case any services you rely on that are injected into the command handler get left in an undefined state if things go wrong.</p>
<pre>
[FallbackPolicy(step:1, backstop:true, circuitBreaker:false)]
[UsePolicy(policy: "GreetingRetryPolicy", step:2)]
public override SalutationCommand Handle(SalutationCommand command)
{
    ...
}
</pre>
<p>We still have our fallback that we set up in the <a href="https://colinmackay.scot/2018/02/16/paramore-brighter-implementing-a-fallback-exception-handler/">previous post on Paramore Brighter</a>, but we now have a <code>UsePolicy</code> attribute. And since we have two attributes the <code>Step</code> argument now becomes important.</p>
<p>The command processor sets up the policy and command handlers like a Russian doll, with the command handler right in the middle. The outer handler (doll) is step 1, then the one inside that is step 2, and so on until you get to the actual command handler. So, in this case at the very outside is the <code>FallbackPolicy</code> and it only does its thing if it gets an exception, the <code>UsePolicy</code> will act on exceptions before the fallback sees them most of the time.</p>
<p>The <code>UsePolicy</code> attribute takes the name of the policy that we set up earlier when we were creating the policy registry.</p>
<h3>Analysing the StackTrace</h3>
<p>So, when we ask to greet &#8220;Voldemort&#8221; it will always fail. We get a stack trace that shows off the Russian Doll quite well.</p>
<pre>
System.ApplicationException: A death-eater has appeared.
   at QualityOfService.SalutationHandler.ThrowOnTheDarkLord(SalutationCommand command) in C:\dev\BrighterRecipes\src\quality-of-service\quality-of-service\SalutationHandler.cs:line 46
   at QualityOfService.SalutationHandler.Handle(SalutationCommand command) in C:\dev\BrighterRecipes\src\quality-of-service\quality-of-service\SalutationHandler.cs:line 21
   at Paramore.Brighter.RequestHandler`1.Handle(TRequest command)
</pre>
<p>The above is our <code>SaulatationHandler</code>, starting from the top where the exception is thrown, until the point that our code is called by Paramore Brighter itself.</p>
<pre>
   at Paramore.Brighter.Policies.Handlers.ExceptionPolicyHandler`1.&lt;&gt;n__0(TRequest command)
   at Paramore.Brighter.Policies.Handlers.ExceptionPolicyHandler`1.&lt;&gt;c__DisplayClass2_0.b__0()
   at Polly.Policy.&lt;&gt;c__DisplayClass33_0`1.b__0(Context ctx, CancellationToken ct)
   at Polly.Policy.&lt;&gt;c__DisplayClass42_0`1.b__0(Context ctx, CancellationToken ct)
   at Polly.RetrySyntax.&lt;&gt;c__DisplayClass19_0.b__1(Context ctx, CancellationToken ct)
   at Polly.Retry.RetryEngine.Implementation[TResult](Func`3 action, Context context, CancellationToken cancellationToken, IEnumerable`1 shouldRetryExceptionPredicates, IEnumerable`1 shouldRetryResultPredicates, Func`1 policyStateFactory)
   at Polly.RetrySyntax.&lt;&gt;c__DisplayClass19_1.b__0(Action`2 action, Context context, CancellationToken cancellationToken)
   at Polly.Policy.Execute[TResult](Func`3 action, Context context, CancellationToken cancellationToken)
   at Polly.Policy.Execute[TResult](Func`1 action)
   at Paramore.Brighter.Policies.Handlers.ExceptionPolicyHandler`1.Handle(TRequest command)
   at Paramore.Brighter.RequestHandler`1.Handle(TRequest command)
</pre>
<p>The above section is all part of the retry handler, as defined by the policy we set up. Most of this code is in Polly, which is the quality of service package that Brighter uses.</p>
<pre>
   at Paramore.Brighter.Policies.Handlers.FallbackPolicyHandler`1.CatchAll(TRequest command)
// The rest of this isn't really part of the exception 
// stack trace, but I wanted to show you where it came from.
   at Paramore.Brighter.Policies.Handlers.FallbackPolicyHandler`1.Handle(TRequest command)
   at Paramore.Brighter.CommandProcessor.Send[T](T command)
   at QualityOfService.Program.Main(String[] args)
</pre>
<p>Finally, the most outer of the handlers (which you cannot normally see all of because it has caught the exception in <code>CatchAll</code>) before handing it off to our fallback handler.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://colinmackay.scot/2018/03/02/paramore-brighter-with-quality-of-service-retrying-commands/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/976babfada7ad5877e400110cc30f777?s=96&#38;d=wavatar&#38;r=PG" medium="image">
			<media:title type="html">Colin Angus Mackay</media:title>
		</media:content>
	</item>
		<item>
		<title>Setting file permissions on a remote machine with PowerShell</title>
		<link>https://colinmackay.scot/2018/02/28/setting-file-permissions-on-a-remote-machine-with-powershell/</link>
					<comments>https://colinmackay.scot/2018/02/28/setting-file-permissions-on-a-remote-machine-with-powershell/#respond</comments>
		
		<dc:creator><![CDATA[Colin Mackay]]></dc:creator>
		<pubDate>Wed, 28 Feb 2018 22:31:10 +0000</pubDate>
				<category><![CDATA[Misc]]></category>
		<category><![CDATA[ACL]]></category>
		<category><![CDATA[IIS]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Remote PowerShell]]></category>
		<category><![CDATA[security]]></category>
		<guid isPermaLink="false">http://colinmackay.scot/?p=13539</guid>

					<description><![CDATA[Recently I needed to set some file permissions on a remote machine. Previously I&#8217;d done this relatively easily through a share as the user account I was using also had administrator rights on the other side and I was dealing with domain accounts. However, this did not work for a user that was local to [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Recently I needed to set some file permissions on a remote machine. Previously I&#8217;d done this relatively easily through a share as the user account I was using also had administrator rights on the other side and I was dealing with domain accounts. However, this did not work for a user that was local to the remote machine.</p>
<p>So, I creates a small PowerShell function to remotely set the user to a local (or any domain) account. (This also works for virtual accounts like <code>IIS AppPool/</code> users)</p>
<pre>
function Add-RemoteAcl
(
    [string]$computerName,
    [string]$directory,
    [string]$user,
    [string]$permission
)
{
    $session = New-PSSession -ComputerName $computerName;
    Invoke-Command -Session $session -Args $directory, $user, $permission -ScriptBlock {
        param([string]$directory,[string]$user,[string]$permission)
        $acl = Get-Acl $directory;
        $accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($user, $permission, "ContainerInherit, ObjectInherit", "None", "Allow");
        if ($accessRule -eq $null){
            Throw "Unable to create the Access Rule giving $permission permission to $user on $directory";
        }
        $acl.AddAccessRule($accessRule)
        Set-Acl -aclobject $acl $directory
    };
    Remove-PSSession $session;
}</pre>
<p>To run the PowerShell remotely, first of all, I create a new PowerShell session on the remote machine with <a href="https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/new-pssession?view=powershell-6" target="_blank"><code>New-PSSession</code></a>, then I run a script in that session with <a href="https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/invoke-command?view=powershell-6"><code>Invoke-Command</code></a>, and finally I clean up with <a href="https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/remove-pssession?view=powershell-6"><code>Remove-PSSession</code></a> to end the remote session.</p>
<p>Bear in mind that you will need the appropriate permissions on the remote machine for whatever actions you want to take.</p>
<h3>Invoke-Command</h3>
<p>This is where all the work is done. You can pass a session to <code>Invoke-Command</code>, and you can also pass an <code>ArgumentList</code> to pass in to the command. This gives it some fantastic abilities.</p>
<p>Be aware that variables that exist outside the script block are not visible within the script block, you have to pass them as an <code>ArgumentList</code> (alias <code>Args</code>), and the script block has to pick them up. Hence the code above starts the script block with a <code>params</code> section in order to pick up the values passed as the <code>Args</code>.</p>
<h3>Setting the file permissions</h3>
<p>In order to add new rules to an ACL you have to <a href="https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.security/get-acl?view=powershell-6"><code>Get-Acl</code></a> to get the existing set of rules, create the new <a href="https://msdn.microsoft.com/en-us/library/system.security.accesscontrol.filesystemaccessrule(v=vs.110).aspx"><code>FileSystemAccessRule</code></a> for the permission you want to grant, then <a href="https://msdn.microsoft.com/en-us/library/d49cww7f(v=vs.110).aspx"><code>AddAccessRule</code></a> to the ACL you retrieved, and finally <a href="https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.security/set-acl?view=powershell-6"><code>Set-Acl</code></a> to persist the addition.</p>
<p>If you were just to create the new rule and set that, then all the existing rules would be replaced with the one rule that was just created.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://colinmackay.scot/2018/02/28/setting-file-permissions-on-a-remote-machine-with-powershell/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/976babfada7ad5877e400110cc30f777?s=96&#38;d=wavatar&#38;r=PG" medium="image">
			<media:title type="html">Colin Angus Mackay</media:title>
		</media:content>
	</item>
	</channel>
</rss>
