<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>Naeem Khedarun</title>
  
  <link href="/blog/atom.xml" rel="self"/>
  
  <link href="http://naeem.khedarun.co.uk/blog/"/>
  <updated>2017-04-03T14:19:48.000Z</updated>
  <id>http://naeem.khedarun.co.uk/blog/</id>
  
  <author>
    <name>Naeem Khedarun</name>
    
  </author>
  
  <generator uri="http://hexo.io/">Hexo</generator>
  
  <entry>
    <title>NugetXray - Be proactive in keeping your packages up to date</title>
    <link href="http://naeem.khedarun.co.uk/blog/2017/04/03/nugetxray-be-proactive-in-keeping-your-packages-up-to-date-1491218032473/"/>
    <id>http://naeem.khedarun.co.uk/blog/2017/04/03/nugetxray-be-proactive-in-keeping-your-packages-up-to-date-1491218032473/</id>
    <published>2017-04-03T13:51:21.000Z</published>
    <updated>2017-04-03T14:19:48.000Z</updated>
    
    <content type="html"><![CDATA[<p>The package management features within Visual Studio are fantastic when working within a single solution. It lets you know when there are new packages available and you are referencing multiple versions of the same package. There are some scenarios which could be improved:</p>
<ul>
<li>It’s easy to forget to check whether there are new versions.</li>
<li>Solutions composed of packages output by different repositories.</li>
</ul>
<p>Some of our applications have code distributed across different repositories and packages. Since these are different solutions its difficult to use existing tools to detect when these packages are getting out of sync. <a href="https://github.com/naeemkhedarun/NugetXray" target="_blank" rel="external">NugetXray</a> has commands to do just that.</p>
<p>It’s available at <a href="https://www.nuget.org/packages/NugetXray/" target="_blank" rel="external">nuget.org</a>.</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">nuget install NugetXray</div></pre></td></tr></table></figure>
<p>There are currently two commands: one to find out of date packages and another to find package version mismatches.</p>
<h3 id="Find-packages-with-newer-versions"><a href="#Find-packages-with-newer-versions" class="headerlink" title="Find packages with newer versions"></a>Find packages with newer versions</h3><p>To generate a diff report:</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">.\NugetXray.exe diff -d C:\git\source\</div><div class="line"></div><div class="line">Scanning https://www.nuget.org/api/v2 for packages.configs.</div><div class="line">WindowsAzure.Storage.2.1.0.4                                | -5.0.0      | 3   configs</div><div class="line">Newtonsoft.Json.6.0.8                                             | -3.0.0      | 4   configs</div><div class="line">WindowsAzure.Storage.4.3.0                                   | -3.0.0      | 1   configs</div></pre></td></tr></table></figure>
<p>This shows us how many major, minor or patch versions we are behind by. You can generate a report across multiple repositories by setting the directory parameter to the root of both repositories.</p>
<p>You can also output either json or html if you want to build further tooling around it. The html report can included as a <a href="https://confluence.jetbrains.com/display/TCD8/Including+Third-Party+Reports+in+the+Build+Results" target="_blank" rel="external">third party teamcity report</a>.</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">.\NugetXray.exe diff -d C:\git\source\ -f html -o diff.html</div></pre></td></tr></table></figure>
<p><img src="/blog/images/nx-diff.png" alt=""> </p>
<h3 id="Find-packages-which-need-consolidating"><a href="#Find-packages-which-need-consolidating" class="headerlink" title="Find packages which need consolidating"></a>Find packages which need consolidating</h3><p>To find whether you have multiple versions of the same package, you can run the duplicate command.</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">.\NugetXray.exe duplicate -d C:\git\source\</div><div class="line"></div><div class="line">Scanning C:\git\ConveyorBelt\ for packages.configs.</div><div class="line">WindowsAzure.Storage                                                   | 2 versions</div><div class="line"></div><div class="line">Errors:   1</div></pre></td></tr></table></figure>
<p>As before you can include multiple solutions under a single root directory to find duplicates across solutions. It also supports both Json and Html output.</p>
<h3 id="Fail-the-build"><a href="#Fail-the-build" class="headerlink" title="Fail the build"></a>Fail the build</h3><p>If you want to integrate it with your build process, and fail when there are packages which need updating or consolidating, you can use the exit code. If calling from PowerShell you can get by calling <code>$LASTEXITCODE</code>. A negative exit code is returned to indicate there are results.</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">.\NugetXray.exe diff -d C:\git\source\</div><div class="line">$LASTEXITCODE</div><div class="line">-1</div></pre></td></tr></table></figure>
<h3 id="Verbose-flag"><a href="#Verbose-flag" class="headerlink" title="Verbose flag"></a>Verbose flag</h3><p>If you want more details output around the failures and which packages.config they refer to you can specify the <code>verbose</code> flag. </p>
<p>If you have any feedback or feature requests you can create an <a href="https://github.com/naeemkhedarun/NugetXray/issues" target="_blank" rel="external">issue</a> or reach me <a href="https://twitter.com/naeemkhedarun" target="_blank" rel="external">@naeemkhedarun</a>.</p>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;The package management features within Visual Studio are fantastic when working within a single solution. It lets you know when there are
    
    </summary>
    
      <category term="development" scheme="http://naeem.khedarun.co.uk/blog/categories/development/"/>
    
    
      <category term="C#" scheme="http://naeem.khedarun.co.uk/blog/tags/C/"/>
    
      <category term="powershell" scheme="http://naeem.khedarun.co.uk/blog/tags/powershell/"/>
    
      <category term="nuget" scheme="http://naeem.khedarun.co.uk/blog/tags/nuget/"/>
    
  </entry>
  
  <entry>
    <title>OctoSearch - Cache and search Octopus Deploy variable sets</title>
    <link href="http://naeem.khedarun.co.uk/blog/2017/01/11/octosearch-cache-and-search-octopus-deploy-variable-sets-1484135933380/"/>
    <id>http://naeem.khedarun.co.uk/blog/2017/01/11/octosearch-cache-and-search-octopus-deploy-variable-sets-1484135933380/</id>
    <published>2017-01-11T11:58:53.000Z</published>
    <updated>2017-01-11T12:28:57.000Z</updated>
    
    <content type="html"><![CDATA[<p>When putting together new deployments the <a href="https://octopus.com/" target="_blank" rel="external">octopus deploy</a> interface does a great job. Unfortunately, when you have hundreds of deployments and thousands of variables it can become difficult to find and navigate the variables without search and filter functions.</p>
<p>As a stop-gap to Octopus hopefully adding this feature I’ve created <a href="https://github.com/naeemkhedarun/OctoSearch" target="_blank" rel="external">OctoSearch</a>. This allows you to download and cache the variable sets with their variable collections locally as Text, Json or Html.</p>
<p>OctoSearch itself is a package available from nuget. It has been compiled down to a native executable so a dotnet core installation is not needed.</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">&gt; nuget install OctoSearch</div><div class="line">&gt; cd .\tools\OctoSearch*\tools</div><div class="line">&gt; .\OctoSearch.exe</div></pre></td></tr></table></figure>
<p>The first step is to login with the octopus server so we can create, download and cache an API token. This will be used for subsequent calls to octopus.</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">&gt; .\OctoSearch.exe login -l https://octopus/ -u username</div><div class="line">Please enter your password...</div><div class="line">*********</div><div class="line">Successfully logged in.</div></pre></td></tr></table></figure>
<p>Now that we’re authenticated we can download and cache the variable sets and their variable collections. This cache will be used for our searches to reduce the load on the Octopus server. Variables marked as sensitive won’t have their values downloaded or cached; their variable names will be searchable but not their values.</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">&gt; .\OctoSearch.exe cache</div><div class="line">Saved LibraryVariableSet1.</div><div class="line">Saved LibraryVariableSet2.</div><div class="line">...</div></pre></td></tr></table></figure>
<p>With the variables cached locally you can run fast searches and regenerate them into either Json or Html documents. To run a basic command line search you can use the search verb. It takes a regex so you can pass in basic text or more advanced text searches when you need to.</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">&gt; .\OctoSearch.exe search --regex connectionstring</div><div class="line">Database.ConnectionString            ConnectionStringOne</div><div class="line">ServiceBus.ConnectionString          ConnectionStringTwo</div></pre></td></tr></table></figure>
<p>To output the search results into a text file you can do:</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">&gt; .\OctoSearch.exe search --regex connectionstring --output-file results.txt</div></pre></td></tr></table></figure>
<p>To display all the variables in a html report we omit the regex to default to a greedy regex \w.. The html report has a client side search facility to filter variables for easier exploration.</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">&gt; .\OctoSearch.exe search --output-file results.html --output-format html</div></pre></td></tr></table></figure>
<p>This will give you a search UI that looks like:</p>
<p><img src="https://github.com/naeemkhedarun/OctoSearch/raw/master/wiki/images/html-report.png" alt="search report"></p>
<p>If you would prefer it in Json:</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">&gt; .\OctoSearch.exe search  --output-file results.json --output-format json</div></pre></td></tr></table></figure>
<p>Once we have it in Json we can load and analyse it within powershell. For example to get all the variables marked as <code>IsSensitive</code> we could do:</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">&gt; $variablesets = ConvertFrom-Json (gc -Raw .\results.json)</div><div class="line">&gt; ($variablesets | % &#123; $_.Variables &#125; | ? &#123; $_.IsSensitive &#125;).length</div><div class="line">300</div></pre></td></tr></table></figure>
<p>If you have any feedback or feature requests you can <a href="https://github.com/naeemkhedarun/OctoSearch/issues" target="_blank" rel="external">create an issue</a> or reach me <a href="https://twitter.com/NaeemKhedarun" target="_blank" rel="external">@naeemkhedarun</a>.</p>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;When putting together new deployments the &lt;a href=&quot;https://octopus.com/&quot; target=&quot;_blank&quot; rel=&quot;external&quot;&gt;octopus deploy&lt;/a&gt; interface does
    
    </summary>
    
      <category term="operations" scheme="http://naeem.khedarun.co.uk/blog/categories/operations/"/>
    
    
      <category term="powershell" scheme="http://naeem.khedarun.co.uk/blog/tags/powershell/"/>
    
      <category term="octopus" scheme="http://naeem.khedarun.co.uk/blog/tags/octopus/"/>
    
  </entry>
  
  <entry>
    <title>HttpClient DNS settings for Azure Cloud Services and Traffic Manager</title>
    <link href="http://naeem.khedarun.co.uk/blog/2016/11/30/httpclient-dns-settings-for-azure-cloud-services-and-traffic-manager-1480285049222/"/>
    <id>http://naeem.khedarun.co.uk/blog/2016/11/30/httpclient-dns-settings-for-azure-cloud-services-and-traffic-manager-1480285049222/</id>
    <published>2016-11-30T12:00:10.000Z</published>
    <updated>2016-11-30T12:37:32.000Z</updated>
    
    <content type="html"><![CDATA[<p>At my current workplace, some of our systems are approaching 1 Billion requests per day. At these volumes sub-optimal configuration between systems can cause significant issues and subtle performance degradation. To understand some of the issues we are facing I’m going back to basics. You can find the code for this post at <a href="https://github.com/naeemkhedarun/TestHttpClient" target="_blank" rel="external">https://github.com/naeemkhedarun/TestHttpClient</a>.</p>
<p>Thanks to <a href="http://byterot.blogspot.co.uk/2016/07/singleton-httpclient-dns.html" target="_blank" rel="external">Aliostad</a> for his analysis on the HttpClient and <a href="https://github.com/fschwiet/PSHostsFile" target="_blank" rel="external">fschwiet</a> for writing the .NET hosts library which I’ve now taken off my own to-do list.</p>
<p>There are two DNS level scenarios that I want to investigate:</p>
<ul>
<li>Connect to the production cloud service slot after a VIP swap. Clients connect to a cloud service using a <code>cloudapp.net</code> DNS name which points to the Azure Load Balancer distributing traffic over the nodes.</li>
<li>Resolve the latest Traffic Manager configuration. Traffic manager is a DNS level load balancer. Clients resolve a traffic manager address to an IP address and connect directly to the endpoint. So what happens when the IP changes? We’ll try the scenario with both a Transient and Singleton HttpClient. </li>
</ul>
<h4 id="Transient"><a href="#Transient" class="headerlink" title="Transient"></a>Transient</h4><figure class="highlight csharp"><table><tr><td class="code"><pre><div class="line">[Fact]</div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">async</span> Task <span class="title">TransientTimeoutTest</span>(<span class="params"></span>)</span></div><div class="line">&#123;</div><div class="line">    HostsFile.Set(_hostname, <span class="string">"127.0.0.1"</span>);</div><div class="line">    <span class="keyword">var</span> client = <span class="keyword">new</span> TransientHttpClient(<span class="keyword">new</span> Uri(<span class="string">$"http://<span class="subst">&#123;_hostname&#125;</span>:9200"</span>));</div><div class="line"></div><div class="line">    <span class="keyword">var</span> timer = Stopwatch.StartNew();</div><div class="line">    <span class="keyword">try</span></div><div class="line">    &#123;</div><div class="line">        <span class="keyword">await</span> <span class="keyword">new</span> LoopUntilFailure(client).ExecuteAsync(</div><div class="line">            () =&gt; Task.Run(() =&gt; HostsFile.Set(_hostname, <span class="string">"128.0.0.1"</span>)));</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">catch</span></div><div class="line">    &#123;</div><div class="line">        _logger.WriteLine(timer.ElapsedMilliseconds.ToString());</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>133721ms</p>
</blockquote>
<p>The transient client eventually behaves as expected despite taking 133 seconds to respect the change. The <a href="https://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.dnsrefreshtimeout.aspx" target="_blank" rel="external">ServicePointManager.DnsRefreshTimeout</a> defaults to 120 seconds. This still leaves 13 seconds unaccounted for which I suspect is the final socket connection timeout. </p>
<p>A test isolating the connection to the non-responsive endpoint yields: </p>
<blockquote>
<p>13086ms</p>
</blockquote>
<p>I wasn’t able to find any configuration for this timeout within .NET but I didn’t manage to trace the framework source to an enumeration <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms740668.aspx#WSAETIMEDOUT" target="_blank" rel="external">WSAETIMEDOUT</a>. The timeout is controlled by the OS documented <a href="https://technet.microsoft.com/en-us/library/cc938208.aspx" target="_blank" rel="external">here</a>.</p>
<blockquote>
<p>TCP/IP adjusts the frequency of retransmissions over time. The delay between the first and second retransmission is three seconds. This delay doubles after each attempt. After the final attempt, TCP/IP waits for an interval equal to double the last delay, and then it closes the connection request.</p>
</blockquote>
<p>You find the default values for your OS (<em>in my case Windows Server 2016</em>) by running:</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">#  netsh interface tcp show global</div><div class="line">Querying active state...</div><div class="line"></div><div class="line">TCP Global Parameters</div><div class="line">----------------------------------------------</div><div class="line">Initial RTO              : 3000</div><div class="line">Max SYN Retransmissions  : 2</div></pre></td></tr></table></figure>
<p>So the result should be <code>(1 * 3000) + (2 * 3000) = 12000ms</code> which explains the extra time. Now the result is understood, let’s re-run the test after dropping the DNS refresh timeout to 10 seconds.</p>
<figure class="highlight csharp"><table><tr><td class="code"><pre><div class="line">ServicePointManager.DnsRefreshTimeout = <span class="number">10000</span>;</div></pre></td></tr></table></figure>
<blockquote>
<p>25026ms</p>
</blockquote>
<p>So with a transient HttpClient a working way to stay up to date with traffic manager configuration is to tune the <code>DnsRefreshTimeout</code> property to a good value for your application.</p>
<h4 id="Singleton"><a href="#Singleton" class="headerlink" title="Singleton"></a>Singleton</h4><p>Using a singleton client will reuse the connection for many requests to reduce the overhead with starting new TCP connections. In this setup we still want the connection to be recreated occasionally so we get the latest DNS configuration.</p>
<figure class="highlight csharp"><table><tr><td class="code"><pre><div class="line">[Fact]</div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">async</span> Task <span class="title">SingletonDnsChangeTest</span>(<span class="params"></span>)</span></div><div class="line">&#123;</div><div class="line">    HostsFile.Set(_hostname, <span class="string">"127.0.0.1"</span>);</div><div class="line">    <span class="keyword">var</span> client = <span class="keyword">new</span> SingletonHttpClient(<span class="keyword">new</span> Uri(<span class="string">$"http://<span class="subst">&#123;_hostname&#125;</span>:9200"</span>));</div><div class="line"></div><div class="line">    <span class="keyword">var</span> timer = Stopwatch.StartNew();</div><div class="line">    <span class="keyword">try</span></div><div class="line">    &#123;</div><div class="line">        <span class="keyword">await</span> <span class="keyword">new</span> LoopUntilFailure(client).ExecuteAsync(</div><div class="line">            () =&gt; Task.Run(() =&gt; HostsFile.Set(_hostname, <span class="string">"128.0.0.1"</span>)));</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">catch</span></div><div class="line">    &#123;</div><div class="line">        _logger.WriteLine(</div><div class="line">            <span class="string">$"<span class="subst">&#123;<span class="keyword">typeof</span>(IHttpClient).Name&#125;</span> - <span class="subst">&#123;timer.ElapsedMilliseconds&#125;</span>"</span>);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>Cancelled after 180000</p>
</blockquote>
<p>With a singleton HttpClient the connection is kept alive by default. This can be undesirable in configuration changes or scale out scenarios where you want your clients to connect to and use the new resources. Let’s try the <code>DnsRefreshTimeout</code>.</p>
<figure class="highlight csharp"><table><tr><td class="code"><pre><div class="line">ServicePointManager.DnsRefreshTimeout = <span class="number">10000</span>;</div></pre></td></tr></table></figure>
<blockquote>
<p>Cancelled after 180000</p>
</blockquote>
<p>Since the connection is open and kept open, we need to find a way to close it. There is another setting which controls the length of time a connection is held open for called <a href="https://msdn.microsoft.com/en-us/library/system.net.servicepoint.connectionleasetimeout.aspx" target="_blank" rel="external">ServicePointManager.ConnectionLeaseTimeout</a>.</p>
<figure class="highlight csharp"><table><tr><td class="code"><pre><div class="line">ServicePointManager.FindServicePoint(<span class="keyword">new</span> Uri(<span class="string">"http://testdns:9200"</span>))</div><div class="line">    .ConnectionLeaseTimeout = <span class="number">10000</span>;</div></pre></td></tr></table></figure>
<blockquote>
<p>145558</p>
</blockquote>
<p>Unfortunately, having this setting alone isn’t enough based on our previous transient experiments; the DNS is still cached. Let’s combine the two settings.</p>
<blockquote>
<p>33223</p>
</blockquote>
<p>So now, despite using a singleton pattern within the code, our connections are being recreated and re-resolved up to every 20 seconds (both timeouts combined). </p>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;At my current workplace, some of our systems are approaching 1 Billion requests per day. At these volumes sub-optimal configuration betwe
    
    </summary>
    
      <category term="development" scheme="http://naeem.khedarun.co.uk/blog/categories/development/"/>
    
    
      <category term="azure" scheme="http://naeem.khedarun.co.uk/blog/tags/azure/"/>
    
      <category term=".NET" scheme="http://naeem.khedarun.co.uk/blog/tags/NET/"/>
    
      <category term="C#" scheme="http://naeem.khedarun.co.uk/blog/tags/C/"/>
    
  </entry>
  
  <entry>
    <title>Azure Networking Bandwidth: Public IP vs Peered Networking</title>
    <link href="http://naeem.khedarun.co.uk/blog/2016/10/16/Azure-Networking-Bandwidth-Public-IP-vs-Peered-Networking-1476657686312/"/>
    <id>http://naeem.khedarun.co.uk/blog/2016/10/16/Azure-Networking-Bandwidth-Public-IP-vs-Peered-Networking-1476657686312/</id>
    <published>2016-10-16T22:54:30.000Z</published>
    <updated>2016-10-17T00:11:59.000Z</updated>
    
    <content type="html"><![CDATA[<p>We have a application setup which might be familiar to you; A cloud service in a classic virtual network (v1) which communicates with a database in an ARM virtual network (v2). Ideally we would like both of these services in a single network, but are restricted from doing so due to the deployment models. We had a discussion which involved performance, security and ideal topologies, however this post will solely focus on performance.</p>
<blockquote>
<p>Is there a difference in latency and bandwidth when they are both hosted in the same region?</p>
</blockquote>
<h3 id="Test-setup"><a href="#Test-setup" class="headerlink" title="Test setup"></a>Test setup</h3><p>To reflect the setup we have for our application, two VMs were provisioned in North Europe.</p>
<p><strong>Source</strong></p>
<ul>
<li>A3 (Large) Windows Cloud service</li>
<li>Classic Virtual Network</li>
</ul>
<p><strong>Destination</strong></p>
<ul>
<li>DS13v2 Linux Virtual machine</li>
<li>ARM Virtual Network peered to the Classic VNet</li>
</ul>
<h3 id="Traceroute"><a href="#Traceroute" class="headerlink" title="Traceroute"></a>Traceroute</h3><p>I first wanted to test the latency and number of hops between the VMs. ICMP is not available for this test as we are hitting a public IP, however we can use TCP by using <a href="https://blogs.msdn.microsoft.com/gsamant/2015/02/16/ping-and-tracert-commands-on-azure-vm/" target="_blank" rel="external">nmap</a>.</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">PS C:\Users\user&gt; nmap -sS -Pn -p 80 --traceroute 13.xx.xx.xx</div><div class="line"></div><div class="line">HOP RTT     ADDRESS</div><div class="line">1   ... 7</div><div class="line">8   0.00 ms 13.xx.xx.xx</div></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">PS C:\Users\user&gt; nmap -sS -Pn -p 80 --traceroute 10.xx.xx.xx</div><div class="line"></div><div class="line">HOP RTT     ADDRESS</div><div class="line">1   0.00 ms 10.xx.xx.xx</div></pre></td></tr></table></figure>
<p>We can see that there are 8 hops over the public IP, and as we expect only a single hop over the peered network. Both routes are still extremely fast with negligible ping times. This confirms my collegues suspicions; despite connecting to a public address the traffic probably never leaves the datacenters perimeter network. </p>
<h3 id="Bandwidth-iperf3"><a href="#Bandwidth-iperf3" class="headerlink" title="Bandwidth (iperf3)"></a>Bandwidth (iperf3)</h3><p>To measure the bandwidth available between the VMs I’m using <a href="https://iperf.fr/iperf-download.php" target="_blank" rel="external">iperf3</a> which is cross platform. The test is run from the windows machine as a client and flows to the iperf server hosted on the linux box.</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><div class="line"><span class="comment"># Public IP test</span></div><div class="line">.\iperf3.exe -c 13.xx.xx.xx -i 1 -t 30</div><div class="line"></div><div class="line"><span class="comment"># Peered network test</span></div><div class="line">.\iperf3.exe -c 10.xx.xx.xx -i 1 -t 30</div></pre></td></tr></table></figure>
<chart type="LineChart" options="{'legend':{'position':'bottom'}, 'height':'300', 'vAxis': { 'minValue': 0, 'title':'Bandwidth (Mbit)'}, 'hAxis':{'title':'Time (s)'}}"><br>  <div></div><br></chart>

<table>
<thead>
<tr>
<th>Seconds</th>
<th>Public IP</th>
<th>Peered</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>985</td>
<td>996</td>
</tr>
<tr>
<td>2</td>
<td>951</td>
<td>947</td>
</tr>
<tr>
<td>3</td>
<td>975</td>
<td>976</td>
</tr>
<tr>
<td>4</td>
<td>936</td>
<td>956</td>
</tr>
<tr>
<td>5</td>
<td>989</td>
<td>962</td>
</tr>
<tr>
<td>6</td>
<td>958</td>
<td>965</td>
</tr>
<tr>
<td>7</td>
<td>967</td>
<td>962</td>
</tr>
<tr>
<td>8</td>
<td>959</td>
<td>926</td>
</tr>
<tr>
<td>9</td>
<td>964</td>
<td>985</td>
</tr>
<tr>
<td>10</td>
<td>961</td>
<td>948</td>
</tr>
<tr>
<td>11</td>
<td>968</td>
<td>953</td>
</tr>
<tr>
<td>12</td>
<td>960</td>
<td>980</td>
</tr>
<tr>
<td>13</td>
<td>949</td>
<td>957</td>
</tr>
<tr>
<td>14</td>
<td>976</td>
<td>966</td>
</tr>
<tr>
<td>15</td>
<td>960</td>
<td>949</td>
</tr>
<tr>
<td>16</td>
<td>966</td>
<td>972</td>
</tr>
<tr>
<td>17</td>
<td>959</td>
<td>954</td>
</tr>
<tr>
<td>18</td>
<td>966</td>
<td>975</td>
</tr>
<tr>
<td>19</td>
<td>961</td>
<td>969</td>
</tr>
<tr>
<td>20</td>
<td>964</td>
<td>963</td>
</tr>
<tr>
<td>21</td>
<td>965</td>
<td>962</td>
</tr>
<tr>
<td>22</td>
<td>962</td>
<td>933</td>
</tr>
<tr>
<td>23</td>
<td>962</td>
<td>993</td>
</tr>
<tr>
<td>24</td>
<td>958</td>
<td>961</td>
</tr>
<tr>
<td>25</td>
<td>967</td>
<td>958</td>
</tr>
<tr>
<td>26</td>
<td>963</td>
<td>958</td>
</tr>
<tr>
<td>27</td>
<td>961</td>
<td>956</td>
</tr>
<tr>
<td>28</td>
<td>963</td>
<td>970</td>
</tr>
<tr>
<td>29</td>
<td>965</td>
<td>962</td>
</tr>
<tr>
<td>30</td>
<td>962</td>
<td>963</td>
</tr>
</tbody>
</table>
<p>Surprisingly, both achieve the desired bandwith (1Gbps) for the selected VM sizes. </p>
<p>I was still curious if the performance profile was the same when upgrading both VMs to support 10Gbps networking. For this test both machines were upgraded to the DS14v2 VM size. To maximise the bandwidth I used iperfs <code>-P</code> switch to run concurrent workers. The buffer size was also increased to see the effect it has on the bandwidth.</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><div class="line"><span class="comment">#Public IP with 4 processes</span></div><div class="line">.\iperf3.exe -c 13.7xx.xx.xx -i 1 -t 30 -P 4</div><div class="line"><span class="comment">#Peered network with 4 processes</span></div><div class="line">.\iperf3.exe -c 10.xx.xx.xx -i 1 -t 30 -P 4</div><div class="line"><span class="comment">#Public IP with 4 processes and 32MB buffer</span></div><div class="line">.\iperf3.exe -c 13.xx.xx.xx -i 1 -t 30 -P 4 -w 32MB</div><div class="line"><span class="comment">#Peered network with 4 processes and 32MB buffer</span></div><div class="line">.\iperf3.exe -c 10.xx.xx.xx -i 1 -t 30 -P 4 -w 32MB</div></pre></td></tr></table></figure>
<chart type="BarChart" options="{'hAxis':{'baseline':0}, 'legend':{'position':'bottom'}, 'height':'300'}"><br>  <div></div><br></chart>

<table>
<thead>
<tr>
<th>Test</th>
<th>Bandwidth (Mbps)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Public IP</td>
<td>2480</td>
</tr>
<tr>
<td>Peered</td>
<td>2630</td>
</tr>
<tr>
<td>Public IP (32MB)</td>
<td>3230</td>
</tr>
<tr>
<td>Peered (32MB)</td>
<td>2710</td>
</tr>
</tbody>
</table>
<p>As expected, with the default values the peered network performed better although the difference was marginal. More surprisingly, the public network had a high thoroughput when the buffer size was increased and despite running the test multiple times I am unable to explain why.</p>
<p>For our workload and use case, I can say the performance difference between the two approaches is irrelevant. If you are evaluating whether you might gain network performance by switching to peered networking then I hope these numbers can help guide you. I would recommend running a similar test if you are choosing different VM sizes or workload.</p>
]]></content>
    
    <summary type="html">
    
      &lt;p&gt;We have a application setup which might be familiar to you; A cloud service in a classic virtual network (v1) which communicates with a d
    
    </summary>
    
      <category term="operations" scheme="http://naeem.khedarun.co.uk/blog/categories/operations/"/>
    
    
      <category term="azure" scheme="http://naeem.khedarun.co.uk/blog/tags/azure/"/>
    
  </entry>
  
  <entry>
    <title>Create a Chrome app for the Service Fabric Explorer</title>
    <link href="http://naeem.khedarun.co.uk/blog/2016/01/25/create-a-chrome-app-for-the-service-fabric-explorer-1453728596801/"/>
    <id>http://naeem.khedarun.co.uk/blog/2016/01/25/create-a-chrome-app-for-the-service-fabric-explorer-1453728596801/</id>
    <published>2016-01-25T13:29:56.000Z</published>
    <updated>2016-10-10T21:19:36.000Z</updated>
    
    <content type="html"><![CDATA[<p>The new web based fabric explorer has a much nicer interface than the old desktop application. However we’ve lost the ability to pin it to the taskbar for quick shortcuts <code>win+n</code> and having it as a chrome tab is less convenient than its own window.</p>
<p>Thankfully Chrome can help with that. Open the fabric explorer:</p>
<blockquote>
<p><a href="http://localhost:19080/explorer" target="_blank" rel="external">http://localhost:19080/explorer</a></p>
</blockquote>
<p>Create the desktop app:</p>
<p><img src="/blog/images/chrome-create-application.png" alt="More tools -&gt; Create application shortcuts"></p>
<p>Then you can pin it to the taskbar as you would normally. You’ll get a window with all the extra Chrome removed.</p>
<p><img src="/blog/images/servicefabric-dashboard.png" alt=""></p>
<p>Don’t forget to take advantage of the default windows taskbar keyboard shortcuts. I have it<br>pinned as the fourth taskbar item, so its quick to switch using <code>win+4</code>.</p>
]]></content>
    
    <summary type="html">
    
      The new web based fabric explorer has a much nicer interface than the old desktop application. However we&#39;ve lost the ability to pin it to the taskbar for quick shortcuts and having it as a chrome tab is less convenient than its own window.
    
    </summary>
    
      <category term="development" scheme="http://naeem.khedarun.co.uk/blog/categories/development/"/>
    
    
      <category term="servicefabric" scheme="http://naeem.khedarun.co.uk/blog/tags/servicefabric/"/>
    
  </entry>
  
  <entry>
    <title>Use Visual Studio Code as the default Git editor</title>
    <link href="http://naeem.khedarun.co.uk/blog/2016/01/21/use-visual-studio-code-as-the-default-git-editor-1453391604798/"/>
    <id>http://naeem.khedarun.co.uk/blog/2016/01/21/use-visual-studio-code-as-the-default-git-editor-1453391604798/</id>
    <published>2016-01-21T15:58:44.000Z</published>
    <updated>2016-10-10T21:19:36.000Z</updated>
    
    <content type="html"><![CDATA[<p>I am not familar with the default <a href="http://www.vim.org/" target="_blank" rel="external">Vim</a> editor that comes with <a href="https://git-scm.com/" target="_blank" rel="external">Git</a>, which makes interactive rebases difficult. It took me a while until I realised you can configure this. Thanks to <a href="http://stackoverflow.com/users/431072/f-boucheros" target="_blank" rel="external">F Boucheros</a> this is quite easy!</p>
<blockquote>
<p>git config –global core.editor “‘C:\Program Files (x86)\Microsoft VS Code\code.exe’ -w”  </p>
</blockquote>
<p>And now when you run your <code>git rebase -i</code> the todo log will open in vscode.</p>
<p><img src="/blog/images/vscode-rebase.png" alt=""></p>
]]></content>
    
    <summary type="html">
    
      I am not familar with the default Vim editor that comes with Git. It took me a while until I realised you can configure this.
    
    </summary>
    
      <category term="development" scheme="http://naeem.khedarun.co.uk/blog/categories/development/"/>
    
    
      <category term="git" scheme="http://naeem.khedarun.co.uk/blog/tags/git/"/>
    
  </entry>
  
  <entry>
    <title>Publish live reliable actor telemetry from service fabric</title>
    <link href="http://naeem.khedarun.co.uk/blog/2016/01/18/publish-live-reliable-actor-telemetry-from-service-fabric-1453119939817/"/>
    <id>http://naeem.khedarun.co.uk/blog/2016/01/18/publish-live-reliable-actor-telemetry-from-service-fabric-1453119939817/</id>
    <published>2016-01-18T12:25:39.000Z</published>
    <updated>2016-10-10T21:19:36.000Z</updated>
    
    <content type="html"><![CDATA[<p>After you’ve got your service fabric application live, you might see performance issues which you didn’t pick up in testing or simulated load tests. This could be for a number of reasons.</p>
<ul>
<li>Unexpected actor bottleneck, they are <a href="https://azure.microsoft.com/en-gb/documentation/articles/service-fabric-reliable-actors-introduction/#concurrency" target="_blank" rel="external">single threaded</a>.</li>
<li>Time spent waiting on a bottlenecked actor.</li>
<li>Large state affecting IO performance.</li>
</ul>
<p>Reliable actors do not yet have interception interfaces to add in this kind of detailed telemetry, but with careful code its possible to do this with a dynamic proxy. I chose to use <a href="http://www.lightinject.net/#interception" target="_blank" rel="external">LightInject</a> for this but most of the framework would do the same job. I use statsd and graphite as my telemetry platform and I’ve had good experiences with <a href="https://github.com/Pereingo/statsd-csharp-client" target="_blank" rel="external">this nuget package</a></p>
<p>We need to intercept object on both sides of the network boundary to cover these scenarios.</p>
<ul>
<li>Service fabrics initialisation to trace <em>OnLoadStateAsync</em>, <em>OnActivateAsync</em>, etc…</li>
<li>Fabric client initialisation to trace client interface calls <em>IActorInterface.YourDoWorkMethodAsync</em>.</li>
</ul>
<p>We can trace the former by using service fabrics dependency injection support to initialise the actors with a proxy inbetween. First we override fabrics initialisation to use our DI container which has dynamic proxy support.</p>
<figure class="highlight csharp"><table><tr><td class="code"><pre><div class="line">fabricRuntime.RegisterActorFactory(() =&gt; </div><div class="line">    ServiceLocator.Current.GetInstance&lt;YourActor&gt;());</div></pre></td></tr></table></figure>
<p>Next we tell our DI container to resolve these types with a proxy that includes our telemetry interceptor.</p>
<figure class="highlight csharp"><table><tr><td class="code"><pre><div class="line">serviceRegistry.Intercept(registration =&gt; </div><div class="line">    <span class="keyword">typeof</span>(IActor).IsAssignableFrom(registration.ServiceType),</div><div class="line">    (factory, definition) =&gt;</div><div class="line">    &#123;</div><div class="line">        definition.Implement(factory.GetInstance&lt;ActorInterceptor&gt;);</div><div class="line">    &#125;);</div></pre></td></tr></table></figure>
<p>This will catch the timings for any calls to actors made by the fabric system. Now we need to get the timings for all the calls we make, both <em>actor to actor</em> and <em>client to actor</em>.</p>
<figure class="highlight csharp"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">ActorFactory</span> : <span class="title">IActorFactory</span></div><div class="line">&#123;</div><div class="line">    <span class="keyword">readonly</span> ActorInterceptor _actorInterceptor;</div><div class="line">    <span class="keyword">readonly</span> ConcurrentDictionary&lt;Type, Type&gt; _proxies = </div><div class="line">        <span class="keyword">new</span> ConcurrentDictionary&lt;Type, Type&gt;();</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ActorFactory</span>(<span class="params">ActorInterceptor actorInterceptor</span>)</span></div><div class="line">    &#123;</div><div class="line">        _actorInterceptor = actorInterceptor;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="keyword">public</span> T Get&lt;T&gt;(ActorId actorId) <span class="keyword">where</span> T : IActor</div><div class="line">    &#123;</div><div class="line">        <span class="keyword">var</span> proxyType = _proxies.GetOrAdd(<span class="keyword">typeof</span>(T), type =&gt;</div><div class="line">            <span class="keyword">new</span> ProxyBuilder().GetProxyType(</div><div class="line">                <span class="keyword">new</span> ProxyDefinition(<span class="keyword">typeof</span>(T), <span class="literal">true</span>).Implement(</div><div class="line">                    () =&gt; _actorInterceptor)));</div><div class="line"></div><div class="line">        <span class="keyword">return</span> (T)Activator.CreateInstance(proxyType, </div><div class="line">            <span class="keyword">new</span> Lazy&lt;T&gt;(() =&gt; ActorProxy.Create&lt;T&gt;(actorId)));</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>Above we’ve created a factory class which should be used by clients and actors to create the proxied ActorProxies. We cache the generated proxy types in a thread safe dictionary as they are <a href="http://naeem.khedarun.co.uk/blog/2016/01/18/a-look-at-performance-on-dotnet-dynamic-proxies-1448894394346/">expensive to create</a>.</p>
<p>Lastly we need the intercetor itself. We need to be sympathetic towards:</p>
<ul>
<li>All actor calls return a Task.</li>
<li>Avoid blocking calls by calling <code>Result</code> or <code>Wait</code> on the task.</li>
</ul>
<p>We can use a task continuation to handle the writing of telemetry together with a closure to capture the timer. If there is a return value we should return it, and for whatever reason that value is not a Task then we won’t try to add the continuation.</p>
<figure class="highlight csharp"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">ActorInterceptor</span> : <span class="title">IInterceptor</span></div><div class="line">&#123;</div><div class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">Invoke</span>(<span class="params">IInvocationInfo invocationInfo</span>)</span></div><div class="line">    &#123;</div><div class="line">        <span class="keyword">var</span> name = <span class="keyword">string</span>.Format(<span class="string">"Actors.&#123;0&#125;.&#123;1&#125;"</span>,</div><div class="line">            invocationInfo.Proxy.Target.GetType().Name,</div><div class="line">            invocationInfo.Method.Name);</div><div class="line"></div><div class="line">        <span class="keyword">var</span> timer = Metrics.StartTimer(name);</div><div class="line"></div><div class="line">        <span class="keyword">var</span> returnValue = invocationInfo.Proceed();</div><div class="line"></div><div class="line">        (returnValue <span class="keyword">as</span> Task)?.ContinueWith(task =&gt;</div><div class="line">        &#123;</div><div class="line">           timer.Dispose();</div><div class="line">        &#125;);</div><div class="line"></div><div class="line">        <span class="keyword">return</span> returnValue;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>If you have your metrics library configured to push to a graphite backend you can use the following query to graph it:</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">stats.timers.actors.*.*.mean</div><div class="line">stats.timers.actors.*.*.count</div></pre></td></tr></table></figure>
<p><img src="/blog/images/actor-telemetry.png" alt="actor telemetry"></p>
]]></content>
    
    <summary type="html">
    
      After you&#39;ve got your service fabric application live, you might see performance issues which you didn&#39;t pick up in testing or simulated load tests.
    
    </summary>
    
      <category term="development" scheme="http://naeem.khedarun.co.uk/blog/categories/development/"/>
    
    
      <category term="azure" scheme="http://naeem.khedarun.co.uk/blog/tags/azure/"/>
    
      <category term=".NET" scheme="http://naeem.khedarun.co.uk/blog/tags/NET/"/>
    
      <category term="C#" scheme="http://naeem.khedarun.co.uk/blog/tags/C/"/>
    
      <category term="servicefabric" scheme="http://naeem.khedarun.co.uk/blog/tags/servicefabric/"/>
    
  </entry>
  
  <entry>
    <title>A look at performance on .NET dynamic proxies</title>
    <link href="http://naeem.khedarun.co.uk/blog/2016/01/18/a-look-at-performance-on-dotnet-dynamic-proxies-1448894394346/"/>
    <id>http://naeem.khedarun.co.uk/blog/2016/01/18/a-look-at-performance-on-dotnet-dynamic-proxies-1448894394346/</id>
    <published>2016-01-18T09:00:00.000Z</published>
    <updated>2016-10-10T21:19:36.000Z</updated>
    
    <content type="html"><![CDATA[<p>I currently use <a href="http://www.lightinject.net/" target="_blank" rel="external">LightInject</a> for dependency injection primarily for its good performance and well documented features. I needed to proxy our service fabric actors to trace call timings and I wanted to see if their <a href="http://www.lightinject.net/#interception" target="_blank" rel="external">interception</a> package was competitive with other open source offerings.</p>
<p>We’ll take a look at:</p>
<ul>
<li><a href="https://github.com/castleproject/Core" target="_blank" rel="external">Castle Dynamic Proxy</a> - This is likely the most popular dynamic proxy library for .NET.</li>
<li><a href="http://www.lightinject.net/#interception" target="_blank" rel="external">LightInject Interceptor</a> - I hadn’t heard of this one until I started using LightInject.</li>
<li><a href="https://github.com/mtamme/NProxy" target="_blank" rel="external">NProxy</a> - Also a new one to me, but I’ve added it since it is easy to use.</li>
</ul>
<h3 id="Creating-proxy-instances"><a href="#Creating-proxy-instances" class="headerlink" title="Creating proxy instances"></a>Creating proxy instances</h3><chart type="BarChart" options="{'legend':{'position':'bottom'}, 'height':'300'}"><br>  <div></div><br></chart>

<table>
<thead>
<tr>
<th>Library</th>
<th>Average Time (us)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Castle</td>
<td>2.5237 us</td>
</tr>
<tr>
<td>LightInject</td>
<td>1047.9463 us</td>
</tr>
<tr>
<td>NProxy</td>
<td>1.7470 us</td>
</tr>
</tbody>
</table>
<p>I was quite surprised to see such a difference between the frameworks. I guessed that both NProxy and Castle cache their proxy types internally, which LightInject expects you to handle your own caching. Something good to bear in mind! </p>
<p>After caching the proxy type things are a little more competitive:</p>
<chart type="BarChart" options="{'legend':{'position':'bottom'}, 'height':'300'}"><br>  <div></div><br></chart>

<table>
<thead>
<tr>
<th>Library</th>
<th>Average Time (ns)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Castle</td>
<td>2437.7655 ns</td>
</tr>
<tr>
<td>LightInject</td>
<td>100.6836 ns</td>
</tr>
<tr>
<td>NProxy</td>
<td>1670.7880 ns</td>
</tr>
</tbody>
</table>
<p>I still think the code can be more optimal in all cases, so I reduced everything as much as possible to a single call to activate the proxy type. I’ve included timings for <code>Activator.CreateInstance</code> and the standard constructor against the non-proxy type as a baseline.</p>
<chart type="BarChart" options="{'legend':{'position':'bottom'}, 'height':'300'}"><br>  <div></div><br></chart>

<table>
<thead>
<tr>
<th>Library</th>
<th>Average Time (ns)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Castle</td>
<td>109.5888 ns</td>
</tr>
<tr>
<td>LightInject</td>
<td>99.2248 ns</td>
</tr>
<tr>
<td>NProxy</td>
<td>1041.4311 ns</td>
</tr>
<tr>
<td>Activator</td>
<td>77.9584 ns</td>
</tr>
<tr>
<td>Constructor</td>
<td>6.7176 ns</td>
</tr>
</tbody>
</table>
<p>Things are much closer now! The difference between Castle and LightInject are negligible. There might be a way to optimise NProxy further but the API didn’t yield any obvious optimisations.</p>
<h3 id="Calling-proxied-methods"><a href="#Calling-proxied-methods" class="headerlink" title="Calling proxied methods"></a>Calling proxied methods</h3><p>Now let’s take a look at the runtime overhead of calling a proxied object. I’ve included an unproxied instance as a baseline.</p>
<chart type="BarChart" options="{'hAxis':{'baseline':0}, 'legend':{'position':'bottom'}, 'height':'300'}"><br>  <div></div><br></chart>

<table>
<thead>
<tr>
<th>Library</th>
<th>Average Time (ns)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Castle</td>
<td>2.9992 ns</td>
</tr>
<tr>
<td>LightInject</td>
<td>2.9826 ns</td>
</tr>
<tr>
<td>NProxy</td>
<td>2.9893 ns</td>
</tr>
<tr>
<td>No Proxy</td>
<td>3.0494 ns</td>
</tr>
</tbody>
</table>
<p>Surprisingly there is no overhead with any of the libraries with calling the proxied object. The graph looks skewed due to how close the results are and the timings are in nanoseconds. This is great news and we can use whichever library we want guilt-free. </p>
<p>You can review the code for the benchmarks on <a href="https://github.com/naeemkhedarun/Benchmarks/blob/master/Benchmarking/DynamicProxyBenchmark.cs" target="_blank" rel="external">github</a>.</p>
]]></content>
    
    <summary type="html">
    
      I needed to proxy our service fabric actors to trace call timings and I wanted to see if their interception package was competitive with other open source offerings.
    
    </summary>
    
      <category term="development" scheme="http://naeem.khedarun.co.uk/blog/categories/development/"/>
    
    
      <category term=".NET" scheme="http://naeem.khedarun.co.uk/blog/tags/NET/"/>
    
  </entry>
  
  <entry>
    <title>Getting the number of service fabric partitions</title>
    <link href="http://naeem.khedarun.co.uk/blog/2016/01/14/Getting-the-number-of-service-fabric-partitions-1452789246119/"/>
    <id>http://naeem.khedarun.co.uk/blog/2016/01/14/Getting-the-number-of-service-fabric-partitions-1452789246119/</id>
    <published>2016-01-14T16:34:19.000Z</published>
    <updated>2016-10-10T21:19:36.000Z</updated>
    
    <content type="html"><![CDATA[<p>You might need to programmatically lookup details about a service. The FabricClient class can be used to lookup various things from the cluster.</p>
<figure class="highlight csharp"><table><tr><td class="code"><pre><div class="line"><span class="keyword">var</span> fabricClient = <span class="keyword">new</span> FabricClient();</div><div class="line"><span class="keyword">var</span> partitions = <span class="keyword">await</span> fabricClient.QueryManager.GetPartitionListAsync(</div><div class="line">    <span class="keyword">new</span> Uri(<span class="string">$"fabric:/App/<span class="subst">&#123;serviceName&#125;</span>"</span>));</div><div class="line"></div><div class="line"><span class="keyword">var</span> partition = partitions[<span class="number">0</span>] <span class="comment">//Select the first partition;</span></div><div class="line"><span class="keyword">var</span> partitionLowKey = ((Int64RangePartitionInformation)partition.PartitionInformation).LowKey;</div></pre></td></tr></table></figure>
<p>The result of <code>GetPartitionListAsync</code> should never change for a service as you can’t change the partition information after a service has been created. It would be safe and give better performance to cache this. </p>
<p>The endpoint of the primary replica however can move between machines, so this does need to be resolved more frequently. You can also cache this if you have a retry strategy that will re-resolve after an <code>EndpointNotFoundException</code>.</p>
<figure class="highlight csharp"><table><tr><td class="code"><pre><div class="line"><span class="keyword">var</span> resolver = <span class="keyword">new</span> ServicePartitionResolver(() =&gt; fabricClient);</div><div class="line"><span class="keyword">var</span> resolvedPartition = <span class="keyword">await</span> resolver.ResolveAsync(<span class="keyword">new</span> Uri(<span class="string">$"fabric:/App/<span class="subst">&#123;serviceName&#125;</span>"</span>), partitionLowKey, CancellationToken.None);</div></pre></td></tr></table></figure>
]]></content>
    
    <summary type="html">
    
      You might need to programmatically lookup details about a service. The FabricClient class can be used to lookup various things from the cluster.
    
    </summary>
    
      <category term="development" scheme="http://naeem.khedarun.co.uk/blog/categories/development/"/>
    
    
      <category term="azure" scheme="http://naeem.khedarun.co.uk/blog/tags/azure/"/>
    
      <category term=".NET" scheme="http://naeem.khedarun.co.uk/blog/tags/NET/"/>
    
      <category term="C#" scheme="http://naeem.khedarun.co.uk/blog/tags/C/"/>
    
      <category term="servicefabric" scheme="http://naeem.khedarun.co.uk/blog/tags/servicefabric/"/>
    
  </entry>
  
  <entry>
    <title>Sharding data across service fabric partitions</title>
    <link href="http://naeem.khedarun.co.uk/blog/2016/01/14/sharding-data-across-service-fabric-partitions-1452597860697/"/>
    <id>http://naeem.khedarun.co.uk/blog/2016/01/14/sharding-data-across-service-fabric-partitions-1452597860697/</id>
    <published>2016-01-14T14:58:24.000Z</published>
    <updated>2016-10-10T21:19:36.000Z</updated>
    
    <content type="html"><![CDATA[<p>Service fabric gives you two mechanisms out of the box when resolving which partition you hit when calling a Reliable Service. We’ll ignore the singleton partitions as they won’t help us with sharding.</p>
<ul>
<li><strong>Named Partition</strong> - This is a fixed name for each partition configured at deploy time.</li>
<li><strong>Ranged Partition</strong> - This uses an <code>Int64</code> range to decide which partition a numbered key falls in.</li>
</ul>
<p>More information can be found <a href="https://azure.microsoft.com/en-gb/documentation/articles/service-fabric-concepts-partitioning/" target="_blank" rel="external">here</a>.</p>
<h3 id="Named-Partitioning"><a href="#Named-Partitioning" class="headerlink" title="Named Partitioning"></a>Named Partitioning</h3><p>A named partition allows you to specify explicitly which partition you want to access at runtime. A common example is to specify A-Z named partitions and use the first letter of your data as the key. This splits your data into 26 partitions. </p>
<figure class="highlight xml"><table><tr><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">Service</span> <span class="attr">Name</span>=<span class="string">"TestService"</span>&gt;</span></div><div class="line">  <span class="tag">&lt;<span class="name">StatefulService</span> <span class="attr">ServiceTypeName</span>=<span class="string">"TestServiceType"</span> </span></div><div class="line">                   <span class="attr">TargetReplicaSetSize</span>=<span class="string">"3"</span> </div><div class="line">                   <span class="attr">MinReplicaSetSize</span>=<span class="string">"2"</span>&gt;</div><div class="line">    <span class="tag">&lt;<span class="name">NamedPartition</span>&gt;</span></div><div class="line">      <span class="tag">&lt;<span class="name">Partition</span> <span class="attr">Name</span>=<span class="string">"a"</span>/&gt;</span></div><div class="line">      <span class="tag">&lt;<span class="name">Partition</span> <span class="attr">Name</span>=<span class="string">"b"</span>/&gt;</span></div><div class="line">      ...</div><div class="line">      <span class="tag">&lt;<span class="name">Partition</span> <span class="attr">Name</span>=<span class="string">"z"</span>/&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">NamedPartition</span>&gt;</span></div><div class="line">  <span class="tag">&lt;/<span class="name">StatefulService</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">Service</span>&gt;</span></div></pre></td></tr></table></figure>
<p>The advantages to this are that it is simple and you know which partition your data goes in without a lookup. Unfortunately as we will test later, you are unlikely to get a good distribution of your data across the partitions.</p>
<h3 id="Ranged-Partitioning"><a href="#Ranged-Partitioning" class="headerlink" title="Ranged Partitioning"></a>Ranged Partitioning</h3><p>With a ranged partition the fabric tooling by default uses the entire <code>Int64</code> range as keys to decide which partition. It will then convert these into ranges or buckets depending on the partition count.</p>
<figure class="highlight xml"><table><tr><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">Service</span> <span class="attr">Name</span>=<span class="string">"TestService"</span>&gt;</span></div><div class="line">  <span class="tag">&lt;<span class="name">StatefulService</span> <span class="attr">ServiceTypeName</span>=<span class="string">"TestServiceType"</span> </span></div><div class="line">                   <span class="attr">TargetReplicaSetSize</span>=<span class="string">"3"</span> </div><div class="line">                   <span class="attr">MinReplicaSetSize</span>=<span class="string">"2"</span>&gt;</div><div class="line">    <span class="tag">&lt;<span class="name">UniformInt64Partition</span> <span class="attr">PartitionCount</span>=<span class="string">"26"</span></span></div><div class="line">                           <span class="attr">LowKey</span>=<span class="string">"-9223372036854775808"</span> </div><div class="line">                           <span class="attr">HighKey</span>=<span class="string">"9223372036854775807"</span> /&gt;</div><div class="line">  <span class="tag">&lt;/<span class="name">StatefulService</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">Service</span>&gt;</span></div></pre></td></tr></table></figure>
<p>However to be able to lookup a partition we need a function which can reduce our data to an integer value. To use the configuration above we can convert our strings into an <code>Int64</code>. </p>
<figure class="highlight csharp"><table><tr><td class="code"><pre><div class="line"><span class="keyword">var</span> md5 = MD5.Create();</div><div class="line"><span class="keyword">var</span> <span class="keyword">value</span> = md5.ComputeHash(Encoding.ASCII.GetBytes(<span class="keyword">value</span>));</div><div class="line"><span class="keyword">var</span> key = BitConverter.ToInt64(<span class="keyword">value</span>, <span class="number">0</span>);</div><div class="line"></div><div class="line"><span class="keyword">var</span> client = ServiceProxy.Create&lt;ITestService&gt;(</div><div class="line">                    key, </div><div class="line">                    <span class="keyword">new</span> Uri(<span class="string">"fabric:/App/TestService"</span>))</div></pre></td></tr></table></figure>
<ol>
<li>Hash the value to a fixed length byte array.</li>
<li>Convert the array to an <code>Int64</code>.</li>
<li>Create the client with the calculated key to connect to the service on that partition.</li>
</ol>
<h3 id="Ranged-Partition-with-Consistent-Hashing"><a href="#Ranged-Partition-with-Consistent-Hashing" class="headerlink" title="Ranged Partition with Consistent Hashing"></a>Ranged Partition with Consistent Hashing</h3><p>Rather than use the ranges, you can fix your keys and plug in your own hash algorithm to resolve the partition.</p>
<figure class="highlight xml"><table><tr><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">Service</span> <span class="attr">Name</span>=<span class="string">"TestService"</span>&gt;</span></div><div class="line">  <span class="tag">&lt;<span class="name">StatefulService</span> <span class="attr">ServiceTypeName</span>=<span class="string">"TestServiceType"</span> </span></div><div class="line">                   <span class="attr">TargetReplicaSetSize</span>=<span class="string">"3"</span> </div><div class="line">                   <span class="attr">MinReplicaSetSize</span>=<span class="string">"2"</span>&gt;</div><div class="line">    <span class="tag">&lt;<span class="name">UniformInt64Partition</span> <span class="attr">PartitionCount</span>=<span class="string">"26"</span> </span></div><div class="line">                           <span class="attr">LowKey</span>=<span class="string">"0"</span> </div><div class="line">                           <span class="attr">HighKey</span>=<span class="string">"25"</span> /&gt;</div><div class="line">  <span class="tag">&lt;/<span class="name">StatefulService</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">Service</span>&gt;</span></div></pre></td></tr></table></figure>
<p>We now have a key range limited to 0-25 rather than the entire <code>Int64</code> range. We can resolve a client connected to this partition in the same way, however this time we need to compute a key that fits in this smaller range. I’m using the jump consistent hash implementation in <a href="https://github.com/turowicz/Hydra" target="_blank" rel="external">hydra</a>.</p>
<figure class="highlight csharp"><table><tr><td class="code"><pre><div class="line"><span class="keyword">var</span> shard = <span class="keyword">new</span> JumpSharding().GetShard(<span class="keyword">value</span>, <span class="number">26</span>);</div><div class="line"><span class="keyword">var</span> client = ServiceProxy.Create&lt;ITestService&gt;(</div><div class="line">                    shard, </div><div class="line">                    <span class="keyword">new</span> Uri(<span class="string">"fabric:/App/TestService"</span>))</div></pre></td></tr></table></figure>
<ol>
<li>Call get shard with the value and number of partitions to distribute across.</li>
<li>Create the client with the calculated key to connect to the service on that partition.</li>
</ol>
<h3 id="Distribution"><a href="#Distribution" class="headerlink" title="Distribution"></a>Distribution</h3><p>To benchmark the distribution we have a list of around 17000 real email addresses. This should give us an idea of how the sharding strategies will distribute the data across 26 partitions. Another advantage of using one of the <code>Int64</code> methods is that they can be used with any amount of partitions.</p>
<p>We are looking for an even number of accounts allocated to each partition.</p>
<chart type="BarChart" options="{'title':'Email accounts distribution comparison','vAxis':{'title':'Partitions'},'legend':{'position':'bottom'}, 'height':'750'}"><br>  <div></div><br></chart>

<table>
<thead>
<tr>
<th>Partition</th>
<th>Alphabet</th>
<th>Consistent Hash</th>
<th>Ranging</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>1569</td>
<td>684</td>
<td>650</td>
</tr>
<tr>
<td>1</td>
<td>912</td>
<td>682</td>
<td>730</td>
</tr>
<tr>
<td>2</td>
<td>1027</td>
<td>647</td>
<td>646</td>
</tr>
<tr>
<td>3</td>
<td>1175</td>
<td>662</td>
<td>701</td>
</tr>
<tr>
<td>4</td>
<td>513</td>
<td>687</td>
<td>700</td>
</tr>
<tr>
<td>5</td>
<td>415</td>
<td>665</td>
<td>658</td>
</tr>
<tr>
<td>6</td>
<td>581</td>
<td>653</td>
<td>684</td>
</tr>
<tr>
<td>7</td>
<td>466</td>
<td>693</td>
<td>637</td>
</tr>
<tr>
<td>8</td>
<td>405</td>
<td>657</td>
<td>690</td>
</tr>
<tr>
<td>9</td>
<td>1714</td>
<td>681</td>
<td>699</td>
</tr>
<tr>
<td>10</td>
<td>643</td>
<td>654</td>
<td>669</td>
</tr>
<tr>
<td>11</td>
<td>608</td>
<td>696</td>
<td>681</td>
</tr>
<tr>
<td>12</td>
<td>1800</td>
<td>734</td>
<td>665</td>
</tr>
<tr>
<td>13</td>
<td>526</td>
<td>717</td>
<td>647</td>
</tr>
<tr>
<td>14</td>
<td>213</td>
<td>693</td>
<td>613</td>
</tr>
<tr>
<td>15</td>
<td>793</td>
<td>693</td>
<td>676</td>
</tr>
<tr>
<td>16</td>
<td>31</td>
<td>654</td>
<td>683</td>
</tr>
<tr>
<td>17</td>
<td>1039</td>
<td>681</td>
<td>713</td>
</tr>
<tr>
<td>18</td>
<td>1562</td>
<td>661</td>
<td>665</td>
</tr>
<tr>
<td>19</td>
<td>803</td>
<td>708</td>
<td>747</td>
</tr>
<tr>
<td>20</td>
<td>46</td>
<td>653</td>
<td>709</td>
</tr>
<tr>
<td>21</td>
<td>268</td>
<td>693</td>
<td>666</td>
</tr>
<tr>
<td>22</td>
<td>301</td>
<td>678</td>
<td>679</td>
</tr>
<tr>
<td>23</td>
<td>55</td>
<td>702</td>
<td>675</td>
</tr>
<tr>
<td>24</td>
<td>134</td>
<td>670</td>
<td>708</td>
</tr>
<tr>
<td>25</td>
<td>136</td>
<td>737</td>
<td>744</td>
</tr>
</tbody>
</table>
<p>We can see from those results that sharding using the first character of an email produces wildly different partition sizes, not what we want! Both the jump hash and integer ranging methods produced very even parition sizes.</p>
<h3 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h3><p>Based on these results I would use the ranged partitioning method, it produces provides good balancing and is fast to compute. An additional advantage is you do not need to know the partition count in the code, just map your data to an <code>Int64</code> and service fabric will do the rest. </p>
]]></content>
    
    <summary type="html">
    
      Service fabric gives you two mechanisms out of the box when resolving which partition you hit when calling a Reliable Service.
    
    </summary>
    
      <category term="development" scheme="http://naeem.khedarun.co.uk/blog/categories/development/"/>
    
    
      <category term="azure" scheme="http://naeem.khedarun.co.uk/blog/tags/azure/"/>
    
      <category term=".NET" scheme="http://naeem.khedarun.co.uk/blog/tags/NET/"/>
    
      <category term="C#" scheme="http://naeem.khedarun.co.uk/blog/tags/C/"/>
    
      <category term="servicefabric" scheme="http://naeem.khedarun.co.uk/blog/tags/servicefabric/"/>
    
  </entry>
  
  <entry>
    <title>Logging all unhandled exceptions in .NET</title>
    <link href="http://naeem.khedarun.co.uk/blog/2016/01/05/logging-all-unhandled-exceptions-in-dotnet-1452008814097/"/>
    <id>http://naeem.khedarun.co.uk/blog/2016/01/05/logging-all-unhandled-exceptions-in-dotnet-1452008814097/</id>
    <published>2016-01-05T15:46:54.000Z</published>
    <updated>2016-10-10T21:19:36.000Z</updated>
    
    <content type="html"><![CDATA[<p>With most applications its easy to get started on logging.</p>
<ul>
<li>Install a logging framework like NLog or log4net.</li>
<li>Put try catches around your main program logic and include contextual information with the exception.</li>
<li>If its a web application use a logging middleware for your web framework.</li>
</ul>
<p>However this will not log unhandled exceptions from places you couldn’t forsee. So let’s log these just in case anything goes wrong.</p>
<p>Any exceptions which crash the application can be handled using the <code>UnhandledException</code> event.</p>
<figure class="highlight csharp"><table><tr><td class="code"><pre><div class="line">AppDomain.CurrentDomain.UnhandledException += (sender, args) =&gt;</div><div class="line">&#123;</div><div class="line">    Log.Exception((Exception)args.ExceptionObject);</div><div class="line">&#125;;</div></pre></td></tr></table></figure>
<p>This will help you diagnose fatal errors. Unfortunately not all exceptions are fatal, and if you have any timers, unawaited async or unhandled task pool exceptions these can cause your application to behave unexpectedly without you knowing about it.</p>
<p>You can use the UnobservedTaskException to catch some of those ones:</p>
<figure class="highlight csharp"><table><tr><td class="code"><pre><div class="line">TaskScheduler.UnobservedTaskException += (sender, args) =&gt;</div><div class="line">&#123;</div><div class="line">    <span class="keyword">if</span> (!args.Observed)</div><div class="line">    &#123;</div><div class="line">        Log.Exception(args.Exception);</div><div class="line">    &#125;</div><div class="line">&#125;;</div></pre></td></tr></table></figure>
<p>If you know any other events or ways to get more of these unexpected errors please let me know!</p>
]]></content>
    
    <summary type="html">
    
      With most applications its easy to get started on logging. However this will not log unhandled exceptions from places you couldn&#39;t forsee. So let&#39;s log these just in case anything goes wrong.
    
    </summary>
    
      <category term="development" scheme="http://naeem.khedarun.co.uk/blog/categories/development/"/>
    
    
      <category term=".NET" scheme="http://naeem.khedarun.co.uk/blog/tags/NET/"/>
    
      <category term="C#" scheme="http://naeem.khedarun.co.uk/blog/tags/C/"/>
    
  </entry>
  
  <entry>
    <title>Attaching and formatting drives with Azure ARM and PowerShell</title>
    <link href="http://naeem.khedarun.co.uk/blog/2015/12/03/attaching-and-formatting-drives-with-azure-arm-and-powershell/"/>
    <id>http://naeem.khedarun.co.uk/blog/2015/12/03/attaching-and-formatting-drives-with-azure-arm-and-powershell/</id>
    <published>2015-12-03T12:02:16.000Z</published>
    <updated>2016-10-10T21:19:36.000Z</updated>
    
    <content type="html"><![CDATA[<p>Setting up a virtual machine in Azure using ARM has been made straightforward, even with one-click deployments. If you have any services that need a bigger disk, there are a few more moving parts to get it working. This is based on the <a href="https://github.com/Azure/azure-quickstart-templates/tree/master/windows-vm-custom-script" target="_blank" rel="external">custom script quickstart template</a> and <a href="http://blogs.technet.com/b/heyscriptingguy/archive/2013/05/29/use-powershell-to-initialize-raw-disks-and-partition-and-format-volumes.aspx" target="_blank" rel="external">Ed Wilsons formatting script article</a></p>
<h3 id="Attach-a-disk"><a href="#Attach-a-disk" class="headerlink" title="Attach a disk"></a>Attach a disk</h3><p>To attach a data disk to the virtual machine you can use the following configuration just below the osDisk definition.</p>
<figure class="highlight json"><table><tr><td class="code"><pre><div class="line">&#123;</div><div class="line">      <span class="attr">"dataDisks"</span>:[&#123;</div><div class="line">            <span class="attr">"lun"</span>:<span class="number">0</span>,</div><div class="line">            <span class="attr">"name"</span>:<span class="string">"datadisk"</span>,</div><div class="line">            <span class="attr">"diskSizeGB"</span>:<span class="number">1000</span>,</div><div class="line">            <span class="attr">"createOption"</span>:<span class="string">"Empty"</span>,</div><div class="line">            <span class="attr">"vhd"</span>:&#123;</div><div class="line">                  <span class="attr">"Uri"</span>:<span class="string">"[variables('dataDiskUri')]"</span></div><div class="line">            &#125;</div><div class="line">      &#125;]</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<ul>
<li>lun (Logical Unit Number) should be unique for each attached disk and starts from zero.</li>
<li>diskSizeGB has a maximum of 1000 (1 TB) in Azure currently.</li>
<li>createOption should be “Empty” for a new disk.</li>
<li>vhd.Uri is the full path you want the blob created in.</li>
</ul>
<p>If we deployed the template with this now, we will get a raw unformatted disk with no drive label. You can view it in Disk Manager or by running the following PowerShell on the box.</p>
<figure class="highlight powershell"><table><tr><td class="code"><pre><div class="line">Get-Disk | Where partitionstyle <span class="nomarkup">-eq</span> <span class="string">'raw'</span></div></pre></td></tr></table></figure>
<p>We need one more resource to complete the deployment and give us a formatted disk. We can use the CustomScriptExtension to run a PowerShell script which will format any raw attached disks (in case you want to do multiple drives).</p>
<figure class="highlight json"><table><tr><td class="code"><pre><div class="line">&#123;</div><div class="line">   <span class="attr">"type"</span>:<span class="string">"Microsoft.Compute/virtualMachines/extensions"</span>,</div><div class="line">   <span class="attr">"name"</span>:<span class="string">"[concat(variables('vmName'),'/InitialiseDisks')]"</span>,</div><div class="line">   <span class="attr">"apiVersion"</span>:<span class="string">"2015-05-01-preview"</span>,</div><div class="line">   <span class="attr">"location"</span>:<span class="string">"[resourceGroup().location]"</span>,</div><div class="line">   <span class="attr">"dependsOn"</span>:[</div><div class="line">      <span class="string">"[concat('Microsoft.Compute/virtualMachines/', variables('vmName'))]"</span></div><div class="line">   ],</div><div class="line">   <span class="attr">"properties"</span>:&#123;</div><div class="line">      <span class="attr">"publisher"</span>:<span class="string">"Microsoft.Compute"</span>,</div><div class="line">      <span class="attr">"type"</span>:<span class="string">"CustomScriptExtension"</span>,</div><div class="line">      <span class="attr">"typeHandlerVersion"</span>:<span class="string">"1.2"</span>,</div><div class="line">      <span class="attr">"settings"</span>:&#123;</div><div class="line">         <span class="attr">"fileUris"</span>:[</div><div class="line">            <span class="string">"[variables('initialiseDisksScript')]"</span></div><div class="line">         ],</div><div class="line">         <span class="attr">"commandToExecute"</span>:<span class="string">"[concat('powershell -ExecutionPolicy Unrestricted -file ',parameters('scriptName'))]"</span></div><div class="line">      &#125;</div><div class="line">   &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<ul>
<li>dependsOn will need to be the resource path for our virtual machine to ensure this extension is run after its provisioned.</li>
<li>fileUris is an array of any files we want downloaded and made available to execute. <strong>This needs to be a path to an azure blob</strong>, unfortunately you cannot link to any other domains like github.</li>
<li>commandToExecute is a cmd.exe command, so we need to call out to powershell to invoke our script. The working directory will have your downloaded file already there, so you don’t need the full path to execute it, just the name.</li>
</ul>
<p>You will need to upload the following script to a blob:</p>
<figure class="highlight powershell"><table><tr><td class="code"><pre><div class="line">Get-Disk | ` </div><div class="line">Where partitionstyle <span class="nomarkup">-eq</span> <span class="string">'raw'</span> | ` </div><div class="line">Initialize-Disk -PartitionStyle MBR -PassThru | ` </div><div class="line">New-Partition -AssignDriveLetter -UseMaximumSize | ` </div><div class="line">Format-Volume -FileSystem NTFS -NewFileSystemLabel <span class="string">"datadisk"</span> -Confirm:<span class="literal">$false</span></div></pre></td></tr></table></figure>
]]></content>
    
    <summary type="html">
    
      Setting up a virtual machine in Azure using ARM has been made straightforward, even with one-click deployments. If you have any services that need a bigger disk, there are a few more moving parts to get it working.
    
    </summary>
    
      <category term="operations" scheme="http://naeem.khedarun.co.uk/blog/categories/operations/"/>
    
    
      <category term="azure" scheme="http://naeem.khedarun.co.uk/blog/tags/azure/"/>
    
      <category term="powershell" scheme="http://naeem.khedarun.co.uk/blog/tags/powershell/"/>
    
  </entry>
  
</feed>
