<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>Lost in Details</title>
        <link>https://lostindetails.com/articles</link>
        <description>Lost in Details Blog</description>
        <lastBuildDate>Mon, 13 Apr 2026 09:01:17 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>Feed for Node.js + Martin</generator>
        <atom:link href="https://lostindetails.com/articles/rss" rel="self" type="application/rss+xml"/>
        <item>
            <title><![CDATA[Self-hosting a web font]]></title>
            <link>https://lostindetails.com/articles/Self-hosting-a-web-font</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/Self-hosting-a-web-font</guid>
            <pubDate>Mon, 06 Apr 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[What I did to reduce the size of a font file to use it in a website without resorting to external cdns.]]></description>
            <content:encoded><![CDATA[<h1 id="self-hosting-a-web-font">Self-hosting a web font</h1>
<h2 id="tldr">TLDR;</h2>
<p>Using the woff2 format and font subsetting (eg. via <a href="https://github.com/zachleat/glyphhanger">glyphhanger</a>) you can get small font files for hosting web fonts yourself.</p>
<h2 id="motivation">Motivation</h2>
<p>Lately I’ve found a beautiful mono-spaced font called <a href="https://github.com/be5invis/Iosevka">Iosevka</a> (I like the etoile variant best). For coding I still prefer <a href="https://github.com/microsoft/cascadia-code">Cascadia Code</a> but for normal reading I do refer it over cascadia code.</p>
<p>If you actually download the font, you’ll find that the release zip file is ~120MB (or in the ballpark, depending on version), a single ttf file is around ~10MB and even the woff2 version (which is a format already compressed and optimized for usage on the web) is ~2MB in size.</p>
<p>As a custom font is hardly a necessary feature of any webpage and at best a nice-to-have, 2MB is waaay to big for a vanity download.</p>
<p>Considering that in my use case I would probably only need ~60+ chars (10 digits + 26 letters + 26 more in uppercase and a couple of special characters) I wanted a smaller file that only contains the characters that I am using.</p>
<h2 id="font-subsetting">Font Subsetting</h2>
<p>Turns out that the process of creating a smaller font from a subset of codepoints is called font subsetting (duh!) and there are a couple of nice tools like <a href="https://github.com/zachleat/glyphhanger">glyphhanger</a>, which can do that for you if you give them a website to crawl or a list of the characters required.</p>
<h2 id="putting-it-together">Putting it together</h2>
<p>So I threw together a short Dockerfile that sets up glyphhanger with woff2 export support and a script to instruct it to generate a woff2 subset with the whitelisted characters <a href="https://github.com/8/glyphhanger-docker">here</a>.</p>
<h3 id="dockerfile">Dockerfile</h3>
<p>The docker file installs glyphhanger via bun and the prerequisites for the enabling the woff2 export:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>FROM oven/bun:alpine</span></span>
<span class="line"><span>RUN apk add python3 py3-pip py3-fonttools py3-brotli py3-zopfli</span></span>
<span class="line"><span>RUN bun i -g glyphhanger</span></span>
<span class="line"><span>ENTRYPOINT [ "glyphhanger" ]</span></span></code></pre>
<h3 id="script">Script</h3>
<p>The following script volume maps the current directory (which should contain the input ttf files) into the container and instructrs glyphhanger to create a font subset in woff2 format:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="bash"><code><span class="line"><span style="color:#B392F0">docker</span><span style="color:#9ECBFF"> run</span><span style="color:#79B8FF"> -v</span><span style="color:#E1E4E8"> $(</span><span style="color:#79B8FF">pwd</span><span style="color:#E1E4E8">)</span><span style="color:#9ECBFF">:/home/bun/app</span><span style="color:#9ECBFF"> glyphhanger</span><span style="color:#79B8FF"> --whitelist=</span><span style="color:#9ECBFF">"/.- 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"</span><span style="color:#79B8FF"> --subset=</span><span style="color:#F97583">*</span><span style="color:#79B8FF">.ttf</span><span style="color:#79B8FF"> --formats=woff2</span></span></code></pre>
<p>Running that with my favourite font files, I get the following output files that are ~69KB in size:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>-rw-r--r--   1  9.6M Iosevka-Regular.ttf</span></span>
<span class="line"><span>-rw-r--r--   1   68K Iosevka-Regular-subset.woff2</span></span>
<span class="line"><span>-rw-r--r--   1  9.6M IosevkaEtoile-Regular.ttf</span></span>
<span class="line"><span>-rw-r--r--   1   69K IosevkaEtoile-Regular-subset.woff2</span></span></code></pre>
<p>Which I find adequate in size for some eye candy.</p>
<h3 id="references">References</h3>
<ul>
<li><a href="https://github.com/zachleat/glyphhanger">Glyphhanger (https://github.com/zachleat/glyphhanger)</a></li>
<li><a href="https://github.com/be5invis/Iosevka">Iosevka (https://github.com/be5invis/Iosevka)</a></li>
<li><a href="https://github.com/8/glyphhanger-docker">My Glyphhanger Dockerfile and Example script (https://github.com/8/glyphhanger-docker)</a></li>
</ul>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TailwindCSS color palette for Inkscape Update]]></title>
            <link>https://lostindetails.com/articles/TailwindCSS-color-palette-for-Inkscape-Update</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/TailwindCSS-color-palette-for-Inkscape-Update</guid>
            <pubDate>Tue, 22 Oct 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[An update for getting a current tailwindcss palette file for inkscape.]]></description>
            <content:encoded><![CDATA[<h2 id="tailwindcss-color-palette-for-inkscape---updated">TailwindCSS color palette for Inkscape - Updated</h2>
<h3 id="tldr">TLDR;</h3>
<p>I’ve updated the <a href="/colorpalette/tailwindcss-3-4-5.gpl">inkscape palette file for tailwindcss 3.4.5</a>.</p>
<h3 id="background">Background</h3>
<p>Some years ago, I’ve created a custom palette file that can be used with inkscape (and gimp) and wrote a <a href="/articles/TailwindCSS-color-palette-for-Inkscape">short article</a> about it.</p>
<p>Since writing that article, tailwindcss has evolved and changed their default color palette and so I wanted to update the palette to use the new colors in inkscape.</p>
<p>But meanwhile tailwindcss also changed how they generate the colors, which broke the code I wrote back then to generate the palette.</p>
<p>Today I rewrote that script that generates the palette.</p>
<h3 id="the-script">The Script</h3>
<p>This time the script is just a single fsharp file.</p>
<ol>
<li>It will grab the latest version of tailwindcss (3.4.5 at the time of writing) from the cdn</li>
<li>and try to parse the colors and</li>
<li>create a file named <code>tailwindcss.gpl</code></li>
</ol>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="fs"><code><span class="line"><span style="color:#F97583">module</span><span style="color:#B392F0"> Tailwind </span><span style="color:#F97583">=</span></span>
<span class="line"><span style="color:#F97583">  open</span><span style="color:#B392F0"> System</span></span>
<span class="line"><span style="color:#F97583">  open</span><span style="color:#B392F0"> System.Net.Http</span></span>
<span class="line"><span style="color:#F97583">  open</span><span style="color:#B392F0"> System.Text.RegularExpressions</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">  let</span><span style="color:#FFAB70"> getJs </span><span style="color:#F97583">()</span><span style="color:#F97583"> =</span></span>
<span class="line"><span style="color:#F97583">    let</span><span style="color:#FFAB70"> url</span><span style="color:#F97583"> =</span><span style="color:#9ECBFF"> "https://cdn.tailwindcss.com"</span></span>
<span class="line"><span style="color:#F97583">    let</span><span style="color:#FFAB70"> client</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#E1E4E8"> HttpClient</span><span style="color:#F97583">()</span></span>
<span class="line"><span style="color:#E1E4E8">    client.GetStringAsync</span><span style="color:#F97583">(</span><span style="color:#E1E4E8">url</span><span style="color:#F97583">)</span><span style="color:#E1E4E8">.Result</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">  type</span><span style="color:#B392F0"> Rgb</span><span style="color:#F97583"> =</span><span style="color:#F97583"> {</span></span>
<span class="line"><span style="color:#E1E4E8">    R</span><span style="color:#F97583">:</span><span style="color:#B392F0"> byte</span></span>
<span class="line"><span style="color:#E1E4E8">    G</span><span style="color:#F97583">:</span><span style="color:#B392F0"> byte</span></span>
<span class="line"><span style="color:#E1E4E8">    B</span><span style="color:#F97583">:</span><span style="color:#B392F0"> byte</span></span>
<span class="line"><span style="color:#F97583">  }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">  type</span><span style="color:#B392F0"> ColorValue</span><span style="color:#F97583"> =</span><span style="color:#F97583"> {</span></span>
<span class="line"><span style="color:#E1E4E8">    Value</span><span style="color:#F97583">:</span><span style="color:#B392F0"> int</span></span>
<span class="line"><span style="color:#E1E4E8">    Rgb</span><span style="color:#F97583">:</span><span style="color:#B392F0"> Rgb</span></span>
<span class="line"><span style="color:#F97583">  }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">  type</span><span style="color:#B392F0"> ColorGroup</span><span style="color:#F97583"> =</span><span style="color:#F97583"> {</span></span>
<span class="line"><span style="color:#E1E4E8">    Name</span><span style="color:#F97583">:</span><span style="color:#B392F0"> string</span></span>
<span class="line"><span style="color:#E1E4E8">    Values</span><span style="color:#F97583">:</span><span style="color:#B392F0"> ColorValue array</span></span>
<span class="line"><span style="color:#F97583">  }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">  let</span><span style="color:#FFAB70"> getColorGroups js </span><span style="color:#F97583">=</span></span>
<span class="line"><span style="color:#F97583">    let</span><span style="color:#FFAB70"> r</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> Regex </span><span style="color:#9ECBFF">"""(?&#x3C;name>\w+):{((?&#x3C;weight>[0-9]+):\"#(?&#x3C;value>[0-9a-f]+)\",?)+?}"""</span></span>
<span class="line"><span style="color:#E1E4E8">    </span></span>
<span class="line"><span style="color:#F97583">    let</span><span style="color:#FFAB70"> getColor </span><span style="color:#F97583">(</span><span style="color:#FFAB70">m</span><span style="color:#F97583">:</span><span style="color:#B392F0"> Match</span><span style="color:#F97583">)</span><span style="color:#F97583"> =</span></span>
<span class="line"><span style="color:#F97583">      {</span></span>
<span class="line"><span style="color:#E1E4E8">        Name </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> m.Groups</span><span style="color:#F97583">[</span><span style="color:#9ECBFF">"name"</span><span style="color:#F97583">].</span><span style="color:#E1E4E8">Value</span></span>
<span class="line"><span style="color:#E1E4E8">        Values </span><span style="color:#F97583">=</span></span>
<span class="line"><span style="color:#E1E4E8">          m.Groups</span><span style="color:#F97583">[</span><span style="color:#9ECBFF">"weight"</span><span style="color:#F97583">].</span><span style="color:#E1E4E8">Captures</span></span>
<span class="line"><span style="color:#F97583">          |></span><span style="color:#E1E4E8"> Seq.mapi </span><span style="color:#F97583">(fun</span><span style="color:#FFAB70"> i c </span><span style="color:#F97583">-></span></span>
<span class="line"><span style="color:#F97583">            let</span><span style="color:#FFAB70"> rgb</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> m.Groups</span><span style="color:#F97583">[</span><span style="color:#9ECBFF">"value"</span><span style="color:#F97583">].</span><span style="color:#E1E4E8">Captures</span><span style="color:#F97583">[</span><span style="color:#E1E4E8">i</span><span style="color:#F97583">].</span><span style="color:#E1E4E8">Value </span></span>
<span class="line"><span style="color:#F97583">            {</span></span>
<span class="line"><span style="color:#E1E4E8">              Value </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> c.Value </span><span style="color:#F97583">|></span><span style="color:#E1E4E8"> int</span></span>
<span class="line"><span style="color:#E1E4E8">              Rgb </span><span style="color:#F97583">=</span><span style="color:#F97583"> {</span></span>
<span class="line"><span style="color:#E1E4E8">                R </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> rgb</span><span style="color:#F97583">[</span><span style="color:#79B8FF">0</span><span style="color:#F97583">..</span><span style="color:#79B8FF">1</span><span style="color:#F97583">]</span><span style="color:#F97583"> |></span><span style="color:#E1E4E8"> Convert.FromHexString </span><span style="color:#F97583">|></span><span style="color:#E1E4E8"> Seq.head</span></span>
<span class="line"><span style="color:#E1E4E8">                G </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> rgb</span><span style="color:#F97583">[</span><span style="color:#79B8FF">2</span><span style="color:#F97583">..</span><span style="color:#79B8FF">3</span><span style="color:#F97583">]</span><span style="color:#F97583"> |></span><span style="color:#E1E4E8"> Convert.FromHexString </span><span style="color:#F97583">|></span><span style="color:#E1E4E8"> Seq.head</span></span>
<span class="line"><span style="color:#E1E4E8">                B </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> rgb</span><span style="color:#F97583">[</span><span style="color:#79B8FF">4</span><span style="color:#F97583">..</span><span style="color:#79B8FF">5</span><span style="color:#F97583">]</span><span style="color:#F97583"> |></span><span style="color:#E1E4E8"> Convert.FromHexString </span><span style="color:#F97583">|></span><span style="color:#E1E4E8"> Seq.head</span></span>
<span class="line"><span style="color:#F97583">            }</span></span>
<span class="line"><span style="color:#F97583">          })</span></span>
<span class="line"><span style="color:#F97583">          |></span><span style="color:#E1E4E8"> Seq.toArray</span></span>
<span class="line"><span style="color:#F97583">      }</span></span>
<span class="line"><span style="color:#E1E4E8">    </span></span>
<span class="line"><span style="color:#E1E4E8">    js</span></span>
<span class="line"><span style="color:#F97583">    |></span><span style="color:#E1E4E8"> r.Matches</span></span>
<span class="line"><span style="color:#F97583">    |></span><span style="color:#E1E4E8"> Seq.map getColor</span></span>
<span class="line"><span style="color:#F97583">    |></span><span style="color:#E1E4E8"> Seq.toArray</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">module</span><span style="color:#B392F0"> Gimp </span><span style="color:#F97583">=</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">  open</span><span style="color:#B392F0"> System.IO</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">  type</span><span style="color:#B392F0"> RgbColor</span><span style="color:#F97583"> =</span><span style="color:#F97583"> {</span></span>
<span class="line"><span style="color:#E1E4E8">    Name</span><span style="color:#F97583">:</span><span style="color:#B392F0"> string</span></span>
<span class="line"><span style="color:#E1E4E8">    R</span><span style="color:#F97583">:</span><span style="color:#B392F0"> byte</span></span>
<span class="line"><span style="color:#E1E4E8">    G</span><span style="color:#F97583">:</span><span style="color:#B392F0"> byte</span></span>
<span class="line"><span style="color:#E1E4E8">    B</span><span style="color:#F97583">:</span><span style="color:#B392F0"> byte</span></span>
<span class="line"><span style="color:#F97583">  }</span></span>
<span class="line"><span style="color:#F97583">  module</span><span style="color:#B392F0"> RgbColor </span><span style="color:#F97583">=</span></span>
<span class="line"><span style="color:#F97583">    let</span><span style="color:#FFAB70"> from name </span><span style="color:#F97583">(</span><span style="color:#FFAB70">r</span><span style="color:#F97583">,</span><span style="color:#FFAB70"> g</span><span style="color:#F97583">,</span><span style="color:#FFAB70"> b</span><span style="color:#F97583">)</span><span style="color:#F97583"> =</span></span>
<span class="line"><span style="color:#F97583">      {</span></span>
<span class="line"><span style="color:#E1E4E8">        Name </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> name</span></span>
<span class="line"><span style="color:#E1E4E8">        R </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> r</span></span>
<span class="line"><span style="color:#E1E4E8">        G </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> g</span></span>
<span class="line"><span style="color:#E1E4E8">        B </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> b</span></span>
<span class="line"><span style="color:#F97583">      }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">  type</span><span style="color:#B392F0"> Palette</span><span style="color:#F97583"> =</span><span style="color:#F97583"> {</span></span>
<span class="line"><span style="color:#E1E4E8">    Name</span><span style="color:#F97583">:</span><span style="color:#B392F0"> string</span></span>
<span class="line"><span style="color:#E1E4E8">    Colors</span><span style="color:#F97583">:</span><span style="color:#B392F0"> RgbColor array</span></span>
<span class="line"><span style="color:#F97583">  }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">  module</span><span style="color:#B392F0"> Palette </span><span style="color:#F97583">=</span></span>
<span class="line"><span style="color:#F97583">    let</span><span style="color:#FFAB70"> create name colors </span><span style="color:#F97583">=</span></span>
<span class="line"><span style="color:#F97583">      {</span></span>
<span class="line"><span style="color:#E1E4E8">        Colors </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> colors</span></span>
<span class="line"><span style="color:#E1E4E8">        Name </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> name</span></span>
<span class="line"><span style="color:#F97583">      }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">    let</span><span style="color:#FFAB70"> write </span><span style="color:#F97583">(</span><span style="color:#FFAB70">stream </span><span style="color:#F97583">:</span><span style="color:#B392F0"> Stream</span><span style="color:#F97583">)</span><span style="color:#F97583"> (</span><span style="color:#FFAB70">palette </span><span style="color:#F97583">:</span><span style="color:#B392F0"> Palette</span><span style="color:#F97583">)</span><span style="color:#F97583"> =</span></span>
<span class="line"><span style="color:#E1E4E8">      </span></span>
<span class="line"><span style="color:#F97583">      let</span><span style="color:#FFAB70"> formatColor </span><span style="color:#F97583">(</span><span style="color:#FFAB70">color </span><span style="color:#F97583">:</span><span style="color:#B392F0"> RgbColor</span><span style="color:#F97583">):</span><span style="color:#B392F0"> string </span><span style="color:#F97583">=</span></span>
<span class="line"><span style="color:#F97583">        let</span><span style="color:#FFAB70"> formatPart p </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> p.ToString</span><span style="color:#F97583">()</span><span style="color:#E1E4E8">.PadLeft</span><span style="color:#F97583">(</span><span style="color:#79B8FF">3</span><span style="color:#F97583">)</span></span>
<span class="line"><span style="color:#E1E4E8">        $</span><span style="color:#9ECBFF">"{formatPart color.R} {formatPart color.G} {formatPart color.B} {color.Name}"</span></span>
<span class="line"><span style="color:#E1E4E8">      </span></span>
<span class="line"><span style="color:#F97583">      use</span><span style="color:#E1E4E8"> sw </span><span style="color:#F97583">=</span><span style="color:#F97583"> new</span><span style="color:#E1E4E8"> StreamWriter</span><span style="color:#F97583">(</span><span style="color:#E1E4E8">stream</span><span style="color:#F97583">,</span><span style="color:#E1E4E8"> NewLine </span><span style="color:#F97583">=</span><span style="color:#9ECBFF"> "</span><span style="color:#79B8FF">\n</span><span style="color:#9ECBFF">"</span><span style="color:#F97583">)</span></span>
<span class="line"><span style="color:#E1E4E8">      sw.WriteLine </span><span style="color:#9ECBFF">"GIMP Palette"</span></span>
<span class="line"><span style="color:#E1E4E8">      sw.WriteLine $</span><span style="color:#9ECBFF">"Name: {palette.Name}"</span></span>
<span class="line"><span style="color:#E1E4E8">      sw.WriteLine </span><span style="color:#9ECBFF">"#"</span></span>
<span class="line"><span style="color:#F97583">      for</span><span style="color:#E1E4E8"> color </span><span style="color:#F97583">in</span><span style="color:#E1E4E8"> palette.Colors </span><span style="color:#F97583">do</span></span>
<span class="line"><span style="color:#E1E4E8">        formatColor color </span><span style="color:#F97583">|></span><span style="color:#E1E4E8"> sw.WriteLine</span></span>
<span class="line"><span style="color:#F97583">      ()</span></span>
<span class="line"><span style="color:#E1E4E8">      sw.WriteLine </span><span style="color:#9ECBFF">""</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">    let</span><span style="color:#FFAB70"> writeToFile file palette </span><span style="color:#F97583">=</span></span>
<span class="line"><span style="color:#F97583">      use</span><span style="color:#E1E4E8"> fs </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> File.OpenWrite file</span></span>
<span class="line"><span style="color:#E1E4E8">      write fs palette</span></span>
<span class="line"></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">let</span><span style="color:#FFAB70"> tailwindColorGroups</span><span style="color:#F97583"> =</span></span>
<span class="line"><span style="color:#E1E4E8">  Tailwind.getJs</span><span style="color:#F97583">()</span></span>
<span class="line"><span style="color:#F97583">  |></span><span style="color:#E1E4E8"> Tailwind.getColorGroups</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">let</span><span style="color:#FFAB70"> gimpColors</span><span style="color:#F97583"> =</span></span>
<span class="line"><span style="color:#E1E4E8">  tailwindColorGroups</span></span>
<span class="line"><span style="color:#F97583">  |></span><span style="color:#E1E4E8"> Array.collect </span><span style="color:#F97583">(fun</span><span style="color:#FFAB70"> colorGroup </span><span style="color:#F97583">-></span></span>
<span class="line"><span style="color:#E1E4E8">    colorGroup.Values</span></span>
<span class="line"><span style="color:#F97583">    |></span><span style="color:#E1E4E8"> Array.map</span><span style="color:#F97583">(fun</span><span style="color:#FFAB70"> colorValue </span><span style="color:#F97583">-></span></span>
<span class="line"><span style="color:#E1E4E8">        Gimp.RgbColor.from $</span><span style="color:#9ECBFF">"{colorGroup.Name}-{colorValue.Value}"</span><span style="color:#F97583"> (</span><span style="color:#E1E4E8">colorValue.Rgb.R</span><span style="color:#F97583">,</span><span style="color:#E1E4E8"> colorValue.Rgb.G</span><span style="color:#F97583">,</span><span style="color:#E1E4E8"> colorValue.Rgb.B</span><span style="color:#F97583">)</span></span>
<span class="line"><span style="color:#F97583">      )</span></span>
<span class="line"><span style="color:#F97583">    )</span></span>
<span class="line"><span style="color:#F97583">  |></span><span style="color:#E1E4E8"> Array.append </span><span style="color:#F97583">[|</span></span>
<span class="line"><span style="color:#E1E4E8">    Gimp.RgbColor.from </span><span style="color:#9ECBFF">"black"</span><span style="color:#F97583"> (</span><span style="color:#E1E4E8">byte </span><span style="color:#79B8FF">0</span><span style="color:#F97583">,</span><span style="color:#E1E4E8"> byte </span><span style="color:#79B8FF">0</span><span style="color:#F97583">,</span><span style="color:#E1E4E8"> byte </span><span style="color:#79B8FF">0</span><span style="color:#F97583">)</span></span>
<span class="line"><span style="color:#E1E4E8">    Gimp.RgbColor.from </span><span style="color:#9ECBFF">"white"</span><span style="color:#F97583"> (</span><span style="color:#E1E4E8">byte </span><span style="color:#79B8FF">255</span><span style="color:#F97583">,</span><span style="color:#E1E4E8"> byte </span><span style="color:#79B8FF">255</span><span style="color:#F97583">,</span><span style="color:#E1E4E8"> byte </span><span style="color:#79B8FF">255</span><span style="color:#F97583">)</span></span>
<span class="line"><span style="color:#F97583">  |]</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">let</span><span style="color:#FFAB70"> palette</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> Gimp.Palette.create </span><span style="color:#9ECBFF">"Tailwind CSS 3.4.5"</span><span style="color:#E1E4E8"> gimpColors</span></span>
<span class="line"></span>
<span class="line"><span style="color:#E1E4E8">Gimp.Palette.writeToFile </span><span style="color:#9ECBFF">"tailwindcss.gpl"</span><span style="color:#E1E4E8"> palette</span></span></code></pre>
<h3 id="how-to-use-it">How to use it</h3>
<ol>
<li>To run it you can copy/paste the script down below  into a file name <code>tailwindcss2palette.fsx</code> and then run:</li>
</ol>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>dotnet fsi tailwindcss2palette.fsx</span></span></code></pre>
<p>You need dotnet installed for this to work.</p>
<p>This which will generate the <code>tailwindcss.gpl</code> file for you.</p>
<p>Alternatively you can simply download <a href="/colorpalette/tailwindcss-3-4-5.gpl">tailwindcss-3-4-5.gpl</a> from here.</p>
<ol start="2">
<li>Put it in your inkscape palette folder.</li>
</ol>
<p>In my <a href="/articles/TailwindCSS-color-palette-for-Inkscape">previous article</a> I explain that step in more detail.</p>
<p>Also you might want to take a look at the <a href="https://inkscape-manuals.readthedocs.io/en/latest/palette.html">inkscape manual</a>.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Do not use todo lists to drive your work]]></title>
            <link>https://lostindetails.com/articles/Do-not-use-todo-lists-to-drive-your-work</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/Do-not-use-todo-lists-to-drive-your-work</guid>
            <pubDate>Wed, 26 Jul 2023 00:00:00 GMT</pubDate>
            <description><![CDATA[What problems can occur if you use To-do lists as the main driver of your work and what you should do instead.]]></description>
            <content:encoded><![CDATA[<h2 id="dont-use-to-do-lists-to-drive-your-work">Don’t use to-do lists to drive your work</h2>
<h3 id="tldr">TLDR;</h3>
<p>To-do lists are a simple, efficient tool for tracking open tasks. However, (mis-)using them as the sole driver of daily work can lead to several problems, which can be mitigated by using an additional time-management technique like timeboxing.</p>
<h3 id="the-problem-with-to-do-lists">The problem with to-do lists</h3>
<p>To-do lists are everywhere - and with good reason; they are a very simple and effective way of keep keeping track of things. Yet, they are often used as the <i>primary way to drive work</i> - which is something entirely different!</p>
<p>If your only strategy to get work done is opening up your to-do list, staring at it and then trying to complete the items one-by-one, you may find yourself struggling with the following problems:</p>
<ul>
<li>Everything needs to be a task</li>
<li>Struggling with tasks of varying size</li>
<li>Procrastination</li>
<li>Anxiety &#x26; Stress</li>
<li>Staying motivated</li>
</ul>
<p>Let’s look at each of these problems in detail and explore their origins.</p>
<h4 id="everything-needs-to-be-a-task">Everything needs to be a task</h4>
<p>Let’s start with the obvious one: If you’re only working from your to-do list, you are kind of required to create a task for what you are working on. But there are different kinds of work that don’t fit well with this approach.</p>
<p>For example, open-ended tasks that lack specific completion criteria fall outside the traditional to-do list framework. Activities such as brainstorming, research, optimization, marketing, editing and design or styling improvements are examples of tasks where the more effort you invest, the more you can achieve.</p>
<p>When dealing with this kind of work, it becomes challenging to determine when to consider it complete and move on.</p>
<p>Another example is tasks which require some amount of research before you can begin. Let’s say your task is to obtain X. First you have to figure out where you can find X and its cost. Alternatively, you may discover that X requires Y and you need to obtain Y first. Maybe it would be more cost-effective to built X yourself?</p>
<p>It may require an investigation task, such as “Find out how to get X”, that is put first and it’s output are the follow-up tasks. But it could also turn out that getting X is straightforward and could be completed during the investigation itself. In either case, a to-do list is not necessarily the best fit for managing these types of tasks.</p>
<h4 id="struggling-with-tasks-of-varying-size">Struggling with Tasks of varying size</h4>
<p>Other problematic categories are lots of small tasks. Creating a task for each chat or e-Mail message might seem overkill - until you have to answer that 20 question e-Mail that requires careful thought.</p>
<p>Do you create eight tasks for each message where seven are trivial and creating the to-do item takes more time than answering them directly, while the last one turns out to be a biggie? Or do you create one task “reply to e-mails” and then get stuck on the last e-Mail making it impossible to complete the task at all? Alternatively, do you go back and dynamically split them up then in someway?</p>
<p>It’s not that there a no viable solutions to these kinds of problems, it’s just that those solutions are only geared towards pleasing the to-do list process. Unfortunately they don’t bring any benefit on their own and you end up multitasking between the task at hand and updating the to-do list.</p>
<h4 id="procrastination">Procrastination</h4>
<p>Some tasks are more fun than others, but some are a real bother. Maybe because the task is unclear or it’s really difficult and it’s chance of success is very low. It could be that the task is gargantuan and even looking at it seems daunting. The exact reason doesn’t really matter.</p>
<p>If you are driving your work solely with a todo list, there will be tasks on that list that produce more internal friction and require more effort to even get started. If the effort required to start a task exceeds the available energy, the task will be procrastinated on.</p>
<h4 id="anxiety--stress">Anxiety &#x26; Stress</h4>
<p>To-do lists have a tendency to grow fast, as adding an item is far quicker than completing one. Working off a to-do list for hours on end and see it only grow can induce stress or feel overwhelming.</p>
<p>Continuously looking at the to-do list and thinking about future tasks while working on the current one can lead to unproductive task switching and further increases anxiety.</p>
<h4 id="staying-motivated">Staying motivated</h4>
<p>Staying motivated (or managing your dopamine levels) is very important to continuously produce good work without a crash in motivation. Motivation is highest right before receiving a reward and lowest if the next reward is far in the future.</p>
<p>With a to-do list, the reward is often crossing out the item, marking it done, dragging it into the “completed” column. An additional reward could be a small break, like getting a cup of coffee or tea or a quick walk.</p>
<p>The issue here is, that the reward is handed out by the completion of a task. This makes the size of the task, which is to a certain degree arbitrary, really important. Too small of a task and we get to many rewards and breaks, which may also lessen the impact of them and make them feel unimportant.</p>
<p>But a task that takes too long to complete is also a problem. Because the reward is far in the future, motivation is low and we without rewards, missing the breaks needed to prevent exhaustion and maintain performance. One could grind a full day or more before marking completing a single task.</p>
<h3 id="using-timeboxing-to-tame-the-to-do-list">Using Timeboxing to Tame the To-Do list</h3>
<p>One effective way of addressing the shortcomings of the to-do list based workflow is to switch to a timeboxing approach. Instead of committing to solving specific tasks, we dedicate pre-allocated periods of time to work on them. This results in a shift from focusing on outputs to efforts.</p>
<p>A focus on efforts - not outputs - has some major benefits, the biggest being that our effort is fully under our control, while completion of a task is not. That’s why focusing on efforts is the core skill needed for a growth mindset.</p>
<p>Additionally it comes with a couple of benefits that help alleviate the to-do list based problems mentioned earlier, because it:</p>
<ul>
<li>Provides the freedom to ignore the to-do list when it’s not a good fit.</li>
<li>Sets time limits on open-ended tasks.</li>
<li>Remains indifferent to tasks of varying sizes, eliminating the need to micro-managing the to-do list.</li>
<li>Reduces procrastination by committing only to a reasonable effort, regardless of the difficulty of a specific task.</li>
<li>Alleviates anxiety and stress by prioritizing effort and incorporating breaks at regular intervals.</li>
<li>Keeps motivation high by rewarding you for your effort rather than random task sizes.</li>
</ul>
<h3 id="summary">Summary</h3>
<p>By using a to-do list as a daily driver of work, we are putting it in charge of our anxiety and stress, our feelings of achievement and our motivation.</p>
<p>If we do that, we are forced to obsess over the number and size of each task, carefully adjusting it to keep it’s effect on our psyche in check.</p>
<p>A better approach is to use the to-do list for what it was meant to be - a simple way to track open tasks and use a different technique to drive our daily work - like timeboxing - which does a much better job at that.</p>
<h3 id="references">References</h3>
<ul>
<li><a href="https://en.wikipedia.org/wiki/Timeboxing">Wikipedia - Timeboxing</a></li>
<li><a href="https://en.wikipedia.org/wiki/Pomodoro_Technique">Wikipedia - Pomodoro Technique (https://en.wikipedia.org/wiki/Pomodoro_Technique)</a></li>
<li><a href="">Wikipedia - Growth Mindset</a></li>
<li><a href="https://www.youtube.com/watch?v=aQDOU3hPci0">Youtube - Hubermanlabs - Episode about Growth Mindset</a></li>
</ul>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Global HotKeys for Windows Applications]]></title>
            <link>https://lostindetails.com/articles/Global-HotKeys-for-Windows-Applications</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/Global-HotKeys-for-Windows-Applications</guid>
            <pubDate>Mon, 08 Mar 2021 00:00:00 GMT</pubDate>
            <description><![CDATA[How to get global HotKeys working in your .NET Windows Application, including some a Message Loop detour.]]></description>
            <content:encoded><![CDATA[<h2 id="how-to-use-global-hotkeys-on-windows">How to use Global HotKeys on Windows</h2>
<h3 id="tldr">TLDR;</h3>
<p>To receive global HotKeys in Windows, your application needs to process Window Messages and therefore will need a message loop. To do that, I’ve written a very small library that you can use or take a look at <a href="https://github.com/8/GlobalHotKeys">here</a>. Works for applicationTypes incl. <a href="https://avaloniaui.net">AvaloniaUI</a>, Console, WinForms and Wpf.</p>
<h3 id="who-needs-global-hotkeys">Who needs Global HotKeys?</h3>
<p>In my last <a href="./Desktop-Apps-with-AvaloniaUI-and-FSharp">blog post</a> I started writing a small Example Application named <a href="https://github.com/8/timeboxing">‘Timeboxing’</a>. I wanted to extend it now with a couple of features, one of which is starting and stopping the timer with a HotKey.</p>
<p>Handling keyboard input is easy in any application, but only if the application has focus. If it has not, you usually need to give it focus first.</p>
<p>Getting Focus is usually not handled by the application itself, but by the Window Manager of the platform, so if we want to add that feature, we will need to make use of some platform specific APIs. As my knowledge about other Desktop APIs except Windows is limited at best, I will only touch on windows.</p>
<p>If we take getting focus into account for starting an action, the following options come to mind:</p>
<ul>
<li><span class="hotkey" data-v-f00908f2><!--[-->ALT+TAB<!--]--></span> + Keyboard Input</li>
<li><span class="hotkey" data-v-f00908f2><!--[-->Win+[0-9]<!--]--></span> + Keyboard Input</li>
<li>Create an AutoHotKey script</li>
<li>Use an existing HotKey library</li>
<li>Start a second application instance that notifies the first and then exits</li>
<li>Use the Windows API to register a HotKey the proper way</li>
</ul>
<p>Given those options, you can probably already guess what I have opted for, but let’s try to keep the facade where I first list perfectly good options, before I find somewhat contrived reasons that help me rationalize my decision to <s>write some code</s> use the best approach.</p>
<h3 id="alt-tab">ALT-TAB</h3>
<p>The most prominent UX concept of Windows for switching between applications is of course ALT-Tabbing between applications. It allows you to quickly switch between the most recent applications. It works well, if you are continuously switching between two or so applications.</p>
<p>So the idea is, you are working on a thing, you hit <span class="hotkey" data-v-f00908f2><!--[-->ALT+TAB<!--]--></span>, you hit an application wide HotKey to say, start the timer and then you hit <span class="hotkey" data-v-f00908f2><!--[-->ALT+TAB<!--]--></span> again and continue working.</p>
<p>The thing is, Timeboxing is not an application that you have in the foreground, you probably don’t even have it as a recent application. That’s because it’s basically a countdown timer that you start and forget about for almost half an hour before you come back to it.</p>
<p>So it’s unlikely to be your most recent application, it’s just somewhere in that deep stack of IDEs, text editors, console windows and the many, many separate instances of browser windows that for whatever reason must not be allowed to mingle.</p>
<p>And with that what the user actually needs to do is:</p>
<ol>
<li>Press <span class="hotkey" data-v-f00908f2><!--[-->ALT+TAB,TAB,TAB,TAB,TAB,Shift+Tab<!--]--></span></li>
<li>Press the application-wide HotKey</li>
<li><span class="hotkey" data-v-f00908f2><!--[-->ALT+TAB<!--]--></span> to continue working</li>
</ol>
<h3 id="win-key--number">Win Key + Number</h3>
<p>Another option is that the user pins the application to the taskbar and then uses Windows Key and the 1-based index of the taskbar icon to start the application - or - brings it to the front in case the application is already started.</p>
<p>In comparison to the ALT-TAB approach, this one has the advantage that the HotKey is not context dependant, that is, it does not change depending on what app was active before. The disadvantage is, that it only works for <span class="hotkey" data-v-f00908f2><!--[-->Win+[0-9]<!--]--></span> so there are only 10 HotKeys and it vies with other applications for a spot.</p>
<p>An additional issue that it shares with the <span class="hotkey" data-v-f00908f2><!--[-->ALT-TAB<!--]--></span> approach is, that you can only activate the window - you cannot transport any additional information with it. It’s not a general HotKey, it’s just a “Focus it” Action and you need to tell the application what you want it do it in an additional step.</p>
<p>That’s fine, if it’s your IDE, but if it’s just a single action that you want to start, let’s say a Timer that you want to start, what could have been a single HotKey is now a sequence of:</p>
<ol>
<li>Press <span class="hotkey" data-v-f00908f2><!--[-->Win+Number<!--]--></span></li>
<li>Press the application-wide HotKey</li>
<li>Press <span class="hotkey" data-v-f00908f2><!--[-->ALT+TAB<!--]--></span> to continue working</li>
</ol>
<h3 id="shortcut--single-instance">Shortcut + Single Instance</h3>
<p>Another option is some combination of Shortcut Link with arguments, parsing said arguments a single instance check and some inter-process communication.</p>
<p>An example of what we would need to do could be:</p>
<ul>
<li>Parse the command-line arguments at startup of the application</li>
<li>Check if another instance of the app is already running
<ul>
<li>If not, start normally and execute the actions specified in he arguments</li>
<li>If there is another instance, use some form of IPC to tell the other instance what to do, then exit.</li>
</ul>
</li>
<li>Setup a shortcut that starts the app with the arguments.</li>
<li>Make the shortcut executable via a hotkey, for example pinning it to the taskbar or create the Shortcut on the Desktop and set it’s Shortcut key in the property page, which is basically a <span class="hotkey" data-v-f00908f2><!--[-->CTRL+ALT+[a-z0-9]<!--]--></span> Key combination.</li>
</ul>
<p>This approach is more flexible than just activating your application - you can get specific information to the application and act on it. One downside is the dependency on external links and the limited number of usable HotKeys.</p>
<h3 id="autohotkey">AutoHotKey</h3>
<p>For applications that I often use, I’d like to create a <a href="https://www.autohotkey.com/">AutoHotKey</a> script that focuses them when I press a custom HotKey, e.g.:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8;overflow-x:auto" tabindex="0" data-language="plaintext"><code><span class="line"><span>; active windows terminal on ctrl-;</span></span>
<span class="line"><span>Ctrl &amp; `;::</span></span>
<span class="line"><span>  WinActivate, ahk_class CASCADIA_HOSTING_WINDOW_CLASS</span></span></code></pre>
<p>Once you have it active, you can extend the script to click the buttons that you want and then switch back to the original application that had the focus earlier.</p>
<p>That’s a nice solution! You can cut down the sequence you need to do to a single HotKey combination. It works great for third party applications that you use yourself. I would like to provide a similar experience for my little pet application, but preferable without actually bundling it with an AutoHotKey script.</p>
<h3 id="looking-at-hotkey-libraries">Looking at HotKey Libraries</h3>
<p>To integrate that functionality in your app, you need to receive a global HotKey event somehow and after a quick web search, I found two libraries which promised to do what I wanted.</p>
<p>But upon closer inspection I found that they didn’t work for my scenario: one library depended on Wpf (and had a restrictive license) and the other one was dependent on either WinForms or Wpf.</p>
<p>That means that if you don’t want either of those dependencies - say because you are using an <a href="https://avaloniaui.net/">alternative UI Framework</a> or a Console App, you are out of luck.</p>
<h3 id="why-winforms-or-wpf">Why WinForms or Wpf?</h3>
<p>The question then becomes: Why do those libraries depend on WinForms or Wpf?</p>
<p>The answer lies in the API for handling HotKeys on Windows - which consists of two Win32 functions, one for registering and one for “unregistering” a hotkey (<a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-registerhotkey">RegisterHotKey</a> / <a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-unregisterhotkey">UnregisterHotKey</a>).</p>
<p>After calling <code>RegisterHotKey()</code> and supplying the function with a Window Handle and the HotKey in question, the system sends a <a href="https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-hotkey">WM_HOTKEY</a> Windows Message to the Window specified by the Handle every time the HotKey is pressed until <code>UnregisterHotKey()</code> is called.</p>
<h3 id="how-do-you-create-a-window">How do you create a Window?</h3>
<p>So to actually receive the notification Message, you need a Window that handles the incoming HotKey Window messages.</p>
<p>To create a Window, you need to call either <a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowa"><code>CreateWindow()</code></a> or <a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw"><code>CreateWindowEx()</code></a> and supply it with a couple of arguments, the most important being the Class of the Window that should be created.</p>
<p>The followup-question then becomes how do you create a Window Class?</p>
<h3 id="how-do-you-register-a-window-class">How do you register a Window Class?</h3>
<p>By calling either <a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-registerclassw"><code>RegisterClass()</code></a> or the <a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-registerclassexw"><code>RegisterClassEx()</code></a> function and supplying it with a reference to an instance of the <a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-wndclassw">WNDCLASSW</a> or the <a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-wndclassexw">WNDCLASSEX</a> struct respectively.</p>
<p>As one of it’s most important fields, the struct holds the Windows Procedure that gets called when a Window Messages is dispatched to a window of that class.</p>
<p>So before we can fill the struct, we need to implement the Windows Procedure in question, which is a delegate of type WNDPROC.</p>
<h3 id="how-do-you-write-a-windows-procedure">How do you write a Windows Procedure?</h3>
<p>Even though a Window Procedure needs to handle a lot of different messages - not only the <code>WM_HOTKEY</code> one that we are interested in - the implementation is quite easy, because we can delegate (hehe) most the work to a default implementation called <a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-defwindowprocw">DefWindowProc</a>.</p>
<p>So our implementation of the Windows Procedure will only handle <code>WM_HOTKEY</code> messages and fire a <code>HotKeyPressed</code> event if that is the case and forward any other kind of Window Message to <code>DefWindowProc</code>.</p>
<p>Phew, that’s almost all we need. There is one more thing that we need to do - we need to have message loop that reads messages from the message queue and dispatches it to the windows procedure.</p>
<h3 id="how-do-you-implement-a-message-loop">How do you implement a Message Loop?</h3>
<p>Luckily the process is <a href="https://docs.microsoft.com/en-us/windows/win32/winmsg/using-messages-and-message-queues">very well documented</a> - the message Loop itself is very simple, it basically consists of an while loop that reads messages from the message queue by calling <a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getmessage"><code>GetMessage()</code></a> and dispatches them to the Window Procedure by using <a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-dispatchmessage"><code>DispatchMessage()</code></a>.</p>
<p>But that complicates matters somewhat - a message loop needs to handle Window messages continuously and combined with the fact that <code>GetMessage()</code> blocks as long no messages are available and that it can only retrieve messages that are associated with the same thread, we will need a dedicated thread.</p>
<p>So to summarize, what we need is the following:</p>
<ul>
<li>a Message Loop</li>
<li>a Window Procedure</li>
<li>call RegisterClass</li>
<li>call CreateWindow</li>
<li>register HotKeys</li>
<li>unregister HotKeys</li>
<li>raise an event on pressed HotKey</li>
</ul>
<p>…and most of that needs to happen on the same, dedicated thread.</p>
<p>I think that kind of answers our previous question why the libraries take a dependency on Wpf or WinForms - they want to reuse the creation of Windows and the MessageLoop implementation.</p>
<h3 id="how-can-we-put-it-together">How can we put it together?</h3>
<p>Now that we finally have all the parts, we can assemble them into the separate operations that we need to handle, I came up with the following operations:</p>
<ul>
<li>Initialization</li>
<li>Register a HotKey</li>
<li>Unregister a HotKey</li>
<li>Receiving a HotKey</li>
<li>Cleanup</li>
</ul>
<h4 id="what-do-those-operations-do">What do those Operations do?</h4>
<p>Initialization consists of spawning a dedicated thread, creating a Window Procedure, registering a class, create a window and enter the message loop.</p>
<p>Registering the HotKey is basically just calling <code>RegisterHotKey()</code>. The only complication is, that it must happen on the thread that created the window.</p>
<p>Unregistering the HotKey means calling <code>UnregisterHotKey()</code> with the same caveat that it must be done by the thread that created the window.</p>
<p>Receiving the HotKey means reacting to the <code>WM_HOTKEY</code> message and raising an event.</p>
<p>Cleanup means Unregistering all Registered HotKey, destroying the Window and unregistering the class.</p>
<h4 id="how-does-the-implementation-look-like">How does the Implementation look like?</h4>
<h5 id="initialization">Initialization</h5>
<p>As for the API, I chose to write a class named <code>HotKeyManager</code>, which in it’s constructor handles the initialization as shown in the following diagram:</p>
<div class="h-2"></div>
<img src="/img/global-hotkeys/start-message-loop.png"/>
<div class="h-2"></div>
<h5 id="hotkey-registration">HotKey Registration</h5>
<p>Registering the HotKey is exposed by a member called <code>Register()</code>. To satisfy the requirement that only the thread that created the window can call <code>RegisterHotKey()</code>, the <code>Register()</code> member does not call <code>RegisterHotKey()</code> directly, instead it sends a custom Windows Message containing the details of the HotKey (VirtualKeyCode and Modifiers). Calling the <code>RegisterHotKey()</code> function is then done by the Window Procedure running on the Message Loop Thread.</p>
<h5 id="hotkey-unregistration">HotKey Unregistration</h5>
<p>Unregistering the HotKey also happens by sending a custom Windows Message. But instead of a corresponding <code>Unregister()</code> member on the HotKeyManager class, I chose to return an <code>IDisposable</code> instance as the return value of the <code>Register()</code> member, which simplifies the API and the implementation.</p>
<h5 id="hotkeypressed-event">HotKeyPressed event</h5>
<p>In addition to the aforementioned custom Window Messages, the Window Procedure also handles the <code>WM_HOTKEY</code> message, that the <code>HotKeyManager</code> exposes over the <code>HotKeyPressed</code> event.</p>
<h5 id="visualizing-the-message-loop">Visualizing the Message Loop</h5>
<p>I’ve tried to visualize the general behavior of the message loop in the following image:</p>
<div class="h-2"></div>
<img src="/img/global-hotkeys/message-loop.png"/>
<div class="h-2"></div>
<h3 id="where-is-the-code">Where is the code?</h3>
<p>Glad you asked! I’ve uploaded the code of the mini-library to github <a href="https://github.com/8/GlobalHotKeys">here</a>. The library code is mostly a single F# file - only the definitions used for interfacing with the Win32 API are living in separate files.</p>
<h4 id="how-can-we-use-the-code">How can we use the code?</h4>
<p>The following is the code for a simple C# Console Application that registers 2 hotkeys and prints a message to the Console whenever a HotKey is pressed:</p>
<h5 id="example-programcs">Example Program.cs</h5>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8;overflow-x:auto" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">using</span><span style="color:#B392F0"> System</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">using</span><span style="color:#B392F0"> GlobalHotKeys</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">using</span><span style="color:#B392F0"> GlobalHotKeys</span><span style="color:#E1E4E8">.</span><span style="color:#B392F0">Native</span><span style="color:#E1E4E8">.</span><span style="color:#B392F0">Types</span><span style="color:#E1E4E8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">void</span><span style="color:#B392F0"> HotKeyPressed</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">HotKey</span><span style="color:#B392F0"> hotKey</span><span style="color:#E1E4E8">) </span><span style="color:#F97583">=&gt;</span></span>
<span class="line"><span style="color:#E1E4E8">  Console.</span><span style="color:#B392F0">WriteLine</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">$&quot;HotKey Pressed: Id = </span><span style="color:#9ECBFF">{</span><span style="color:#E1E4E8">hotKey</span><span style="color:#9ECBFF">.</span><span style="color:#E1E4E8">Id</span><span style="color:#9ECBFF">}</span><span style="color:#9ECBFF">, Key = </span><span style="color:#9ECBFF">{</span><span style="color:#E1E4E8">hotKey</span><span style="color:#9ECBFF">.</span><span style="color:#E1E4E8">Key</span><span style="color:#9ECBFF">}</span><span style="color:#9ECBFF">, Modifiers = </span><span style="color:#9ECBFF">{</span><span style="color:#E1E4E8">hotKey</span><span style="color:#9ECBFF">.</span><span style="color:#E1E4E8">Modifiers</span><span style="color:#9ECBFF">}</span><span style="color:#9ECBFF">&quot;</span><span style="color:#E1E4E8">);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">using</span><span style="color:#F97583"> var</span><span style="color:#B392F0"> hotKeyManager</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> HotKeyManager</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#F97583">using</span><span style="color:#F97583"> var</span><span style="color:#B392F0"> subscription</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> hotKeyManager.HotKeyPressed.</span><span style="color:#B392F0">Subscribe</span><span style="color:#E1E4E8">(HotKeyPressed);</span></span>
<span class="line"><span style="color:#F97583">using</span><span style="color:#F97583"> var</span><span style="color:#B392F0"> shift1</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> hotKeyManager.</span><span style="color:#B392F0">Register</span><span style="color:#E1E4E8">(VirtualKeyCode.KEY_1, Modifiers.Shift);</span></span>
<span class="line"><span style="color:#F97583">using</span><span style="color:#F97583"> var</span><span style="color:#B392F0"> ctrl1</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> hotKeyManager.</span><span style="color:#B392F0">Register</span><span style="color:#E1E4E8">(VirtualKeyCode.KEY_1, Modifiers.Control);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#E1E4E8">Console.</span><span style="color:#B392F0">WriteLine</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">&quot;Listening for HotKeys...&quot;</span><span style="color:#E1E4E8">);</span></span>
<span class="line"><span style="color:#E1E4E8">Console.</span><span style="color:#B392F0">ReadLine</span><span style="color:#E1E4E8">();</span></span></code></pre>
<div class="h-2"></div>
<h5 id="example-applications">Example Applications</h5>
<p>There are also some <a href="https://github.com/8/GlobalHotKeys/tree/master/src/Examples">example applications</a> that show off the HotKey registration:</p>
<ul>
<li>
<a href="https://github.com/8/GlobalHotKeys/tree/master/src/Examples/Avalonia">Avalonia</a>
</li>
<li>
<a href="https://github.com/8/GlobalHotKeys/tree/master/src/Examples/Console">Console</a>
</li>
<li>
<a href="https://github.com/8/GlobalHotKeys/tree/master/src/Examples/WinForms">WinForms</a>
</li>
<li>
<a href="https://github.com/8/GlobalHotKeys/tree/master/src/Examples/Wpf">Wpf</a>
</li>
</ul>
<h3 id="references">References</h3>
<ul><li><a href="https://github.com/8/GlobalHotKeys">GlobalHotKey (<a href="https://github.com/8/GlobalHotKeys">https://github.com/8/GlobalHotKeys</a>)</a></li><li><a href="https://www.autohotkey.com/">AutoHotKey (<a href="https://www.autohotkey.com/">https://www.autohotkey.com/</a>)</a></li><li><a href="https://avaloniaui.net">AvaloniaUI (<a href="https://avaloniaui.net">https://avaloniaui.net</a>)</a></li><li><a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-registerhotkey">RegisterHotKey (<a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-registerhotkey">https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-registerhotkey</a>)</a></li><li><a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-unregisterhotkey">UnregisterHotKey (<a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-unregisterhotkey">https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-unregisterhotkey</a>)</a></li><li><a href="./Desktop-Apps-with-AvaloniaUI-and-FSharp">Blog Post “Desktop Apps with AvaloniaUI and FSharp” (./Desktop-Apps-with-AvaloniaUI-and-FSharp)</a></li><li><a href="https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-hotkey">WM_HOTKEY (<a href="https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-hotkey">https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-hotkey</a>)</a></li><li><a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowa">CreateWindow (<a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowa">https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowa</a>)</a></li><li><a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw">CreateWindowEx
(<a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw">https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw</a>)</a></li><li><a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-registerclassw">RegisterClass (<a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-registerclassw">https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-registerclassw</a>)</a></li><li><a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-registerclassexw">RegisterClassEx (<a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-registerclassexw">https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-registerclassexw</a>)</a></li><li><a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-wndclassw">WNDCLASSW (<a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-wndclassw">https://docs.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-wndclassw</a>)</a></li><li><a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-wndclassexw">WNDCLASSEX (<a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-wndclassexw">https://docs.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-wndclassexw</a>)</a></li><li><a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-defwindowprocw">DefWindowProc (<a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-defwindowprocw">https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-defwindowprocw</a>)</a></li><li><a href="https://docs.microsoft.com/en-us/windows/win32/winmsg/using-messages-and-message-queues">Message Loop (<a href="https://docs.microsoft.com/en-us/windows/win32/winmsg/using-messages-and-message-queues">https://docs.microsoft.com/en-us/windows/win32/winmsg/using-messages-and-message-queues</a>)</a></li><li><a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getmessage">GetMessage() (<a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getmessage">https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getmessage</a>)</a></li><li><a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-dispatchmessage">DispatchMessage() (<a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-dispatchmessage">https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-dispatchmessage</a>)</a></li></ul>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Desktop Apps with AvaloniaUI and FSharp]]></title>
            <link>https://lostindetails.com/articles/Desktop-Apps-with-AvaloniaUI-and-FSharp</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/Desktop-Apps-with-AvaloniaUI-and-FSharp</guid>
            <pubDate>Thu, 11 Feb 2021 00:00:00 GMT</pubDate>
            <description><![CDATA[Why you should consider switching from WPF and C# to AvaloniaUI and F# when developing desktop applications.]]></description>
            <content:encoded><![CDATA[<h2 id="desktop-apps-with-avalonia-ui-and-f">Desktop Apps with Avalonia UI and F#</h2>
<h3 id="tldr">TLDR;</h3>
<p>You can write cross platform desktop applications using AvaloniaUI, F# and Reactive Extensions instead of WPF and C#. You can take a look at an example Application called Timeboxing <a href="https://github.com/8/timeboxing">here</a>.</p>
<img src="/img/timeboxing/screenshot-action.png">
<h3 id="revisiting-desktop-apps">Revisiting Desktop Apps</h3>
<p>Lately I’ve been revisiting how to best write desktop applications using dotnet. In the past, I’ve mostly used WPF and while it got the job done, there were a lot things that could have been improved upon.</p>
<p>I chose to focus on the two problems that I found to be the most annoying:</p>
<ul>
<li>Windows only</li>
<li>Xaml</li>
</ul>
<h4 id="windows-only">Windows only</h4>
<p>In my eyes a big disadvantage of using WPF is that it only runs on Windows.</p>
<p>Nowadays, with dotnet core running great on Linux and Mac and WPF being available to a dotnet core application you would assume WPF to run on those platforms as well - but sadly you’d be wrong, because WPF still does not run on anything else except for Windows.</p>
<h4 id="xaml--meh">Xaml = Meh</h4>
<p>Using Mvvm and Bindings made at least the ViewModel code testable and restricted the ugly parts to the views, which I found to be the most troublesome part of the development experience.</p>
<p>The reason for this is, that Views are usually declared in Xaml and by writing Xaml you have to leave your trusty programming language behind. By doing that that, you lose all your existing tools that your programming language provides and trade it in for… some xml?!</p>
<p>This in turn renders even trivial tasks like negating booleans or converting data into painful endeavours of figuring out how every basic thing that you have been taking for granted can be done in this new environment.</p>
<p>But it’s not like a speed bump, that just slows you down one time when getting started, like learning a new API or writing some glue code. It’s stays a continuous problem, because you need to consume it in a way that’s both verbose and irreducible, so it does not get better much better over time.</p>
<p>Take for example negating a boolean. In C# you would just prepend <code>!</code> and be done with it. But in Xaml, you would need to implement an <code>IValueConverter</code> in a separate file, reference it in the xaml and use it in the binding.</p>
<p>There are of course <a href="https://stackoverflow.com/questions/1039636/how-to-bind-inverse-boolean-properties-in-wpf">several other solutions to that problem</a>, all with different tradeoffs, but the mere fact that a trivial problems does not have an equally trivial solution is exemplary for Xaml.</p>
<h3 id="can-we-do-better">Can we do better?</h3>
<p>So the question then becomes, how can we do better? I started to look at the crossplatform issue first, which is more fundamental as it is dictated by the UI-Framework that you are using.</p>
<h4 id="wpf---avaloniaui">WPF -> AvaloniaUI</h4>
<p>There are a couple of cross platform GUI Frameworks out there and doing a detailed comparison between even two such frameworks would be huge undertaking on moving targets - so I am not going to do that.</p>
<p>Also I don’t want do any of those projects a disservice by adding what little experience I have of using them and will therefore not even mention those that I looked at and didn’t pick, instead I just want to heave praise on the one I did.</p>
<p>So I’ve tried a couple of frameworks and the best solution for me was <a href="https://github.com/AvaloniaUI/Avalonia">AvaloniaUI</a>.</p>
<p>If you are looking for a cross-platform UI Framework for .NET, I highly recommend checking out AvaloniaUI, especially if you are coming from a WPF background. AvaloniaUI has all the best parts of WPF and in my opinion improves on a couple of them as well, e.g. styling and binding.</p>
<p>For example, AvaloniaUI solves the previously mentioned problem of negating a boolean value in a Binding by supporting the <a href="https://avaloniaui.net/docs/binding/converting-binding-values#negating-values">“Bang” (!) operator</a> directly in the Xaml Binding Syntax.</p>
<p>They also ship their own Designer Extension for Visual Studio and if you are using Jetbrains Rider you’ll find that they have recently also started shipping support for editing AvaloniaUI xaml and added a control preview.</p>
<p>The feature set is great, the code is great - for me, AvaloniaUI is what WPF should have been.</p>
<h4 id="xml---code">Xml -> Code</h4>
<p>Additionally, as I’ve mentioned earlier, I had a hunch that using normal code instead of xaml could result in a superior experience developing applications - at least for me.</p>
<p>To try out my theory, I’ve decided to built a small sample application using that approach to figure out what works and what doesn’t.</p>
<h4 id="from-view-classes">From View classes…</h4>
<p>The best practice when working with xaml is to create a class for each view. So the most straighforward way to transition from xaml to code is to do just that.</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="cs"><code><span class="line"><span style="color:#F97583">public</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> MainView</span><span style="color:#E1E4E8"> : </span><span style="color:#B392F0">UserControl</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  public</span><span style="color:#B392F0"> MainView</span><span style="color:#E1E4E8">()</span></span>
<span class="line"><span style="color:#E1E4E8">  {</span></span>
<span class="line"><span style="color:#79B8FF">    this</span><span style="color:#E1E4E8">.Content </span><span style="color:#F97583">=</span><span style="color:#F97583"> ..</span><span style="color:#E1E4E8">.</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<h4 id="to-view-methods">…To View methods…</h4>
<p>But I’ll found that creating them as classes is just the default - it doesn’t add anything. Why not instatiate a UserControl and set it’s Content property directly?</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="cs"><code><span class="line"><span style="color:#F97583">public</span><span style="color:#B392F0"> UserControl</span><span style="color:#B392F0"> GetMainView</span><span style="color:#E1E4E8">()</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  var</span><span style="color:#B392F0"> mainView</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> UserControl</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#F97583">  ..</span><span style="color:#E1E4E8">.</span></span>
<span class="line"><span style="color:#F97583">  return</span><span style="color:#E1E4E8"> mainView;</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>That’s much better as methods are way less rigid and better composable than classes.</p>
<h4 id="with-object-initializers">…With Object Initializers</h4>
<p>Also you’d want to use a declaration like approach to create the controls, not an imperative one. So e.g. instead of writing:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="cs"><code><span class="line"><span style="color:#F97583">var</span><span style="color:#B392F0"> mainView</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> UserControl</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#F97583">var</span><span style="color:#B392F0"> border</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Border</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">mainView.Content </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> border;</span></span>
<span class="line"><span style="color:#F97583">var</span><span style="color:#B392F0"> grid</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Grid</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">border.Child </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> grid;</span></span>
<span class="line"><span style="color:#F97583">..</span><span style="color:#E1E4E8">.</span></span></code></pre>
<p>Which obfuscates the hierachy of the controls and is just generally really hard to read and write, you’d probably want some variant of the following:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="cs"><code><span class="line"><span style="color:#F97583">new</span><span style="color:#E1E4E8"> UserControl {</span></span>
<span class="line"><span style="color:#E1E4E8">  Content </span><span style="color:#F97583">=</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Border</span><span style="color:#E1E4E8"> {</span></span>
<span class="line"><span style="color:#E1E4E8">    Child </span><span style="color:#F97583">=</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Grid</span><span style="color:#E1E4E8"> {</span></span>
<span class="line"><span style="color:#F97583">      ..</span><span style="color:#E1E4E8">.</span></span>
<span class="line"><span style="color:#E1E4E8">    }</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<h4 id="improvements">Improvements</h4>
<p>From a coding perspective this is tons better than Xaml, but sometimes you run into problems, because not all parts of the API is designed with an approach like that in mind. E.g. Collection properties that only have getters but no setters or creating and assigning styles and so one.</p>
<p>To work around those issues and get a better declaration-like approach, I wrote a couple of extension methods that I could invoke to keep this declaration style going without falling back to intermediate variables, which improved the code legibility a lot.</p>
<p>The result was a somewhat fluent API that takes in an object, mutates it and returns it again and allows you to keep going with the declaration based approach. It would probably be best to use the Builder pattern for the same approach, but that’s waaay more wrapper code than I was willing to write. So the downside was that it was rather inconsistent - there was a mix of pre-existing properties and some extension methods that you would need to chain.</p>
<h4 id="c---f">C# -> F#</h4>
<p>Then I switched to F#, which I found better suited to that approach. For example, it allows extending types with properties that can then be invoked in the constructor, which allowed me to further simplify the code. It also cuts down on some uses of brackets and commas, but far less than the marketing material would make you want to believe.</p>
<p>For example you can define extension properties for common operations like setting the grid row and column like so:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="fs"><code><span class="line"><span style="color:#6A737D">// extend all controls with the grid row / column properties</span></span>
<span class="line"><span style="color:#F97583">type</span><span style="color:#B392F0"> Control</span><span style="color:#F97583"> with</span></span>
<span class="line"><span style="color:#F97583">  member</span><span style="color:#FFAB70"> this.Row</span></span>
<span class="line"><span style="color:#F97583">    with</span><span style="color:#E1E4E8"> get </span><span style="color:#F97583">()</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> Grid.GetRow </span><span style="color:#F97583">(</span><span style="color:#E1E4E8">this</span><span style="color:#F97583">)</span></span>
<span class="line"><span style="color:#F97583">    and</span><span style="color:#FFAB70"> set row </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> Grid.SetRow </span><span style="color:#F97583">(</span><span style="color:#E1E4E8">this</span><span style="color:#F97583">,</span><span style="color:#E1E4E8"> row</span><span style="color:#F97583">)</span></span>
<span class="line"><span style="color:#F97583">  member</span><span style="color:#FFAB70"> this.Column</span></span>
<span class="line"><span style="color:#F97583">    with</span><span style="color:#E1E4E8"> get </span><span style="color:#F97583">()</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> Grid.GetColumn </span><span style="color:#F97583">(</span><span style="color:#E1E4E8">this</span><span style="color:#F97583">)</span></span>
<span class="line"><span style="color:#F97583">    and</span><span style="color:#FFAB70"> set column </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> Grid.SetColumn </span><span style="color:#F97583">(</span><span style="color:#E1E4E8">this</span><span style="color:#F97583">,</span><span style="color:#E1E4E8"> column</span><span style="color:#F97583">)</span></span>
<span class="line"><span style="color:#F97583">  member</span><span style="color:#FFAB70"> this.ColumnSpan</span></span>
<span class="line"><span style="color:#F97583">    with</span><span style="color:#E1E4E8"> get </span><span style="color:#F97583">()</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> Grid.GetColumnSpan </span><span style="color:#F97583">(</span><span style="color:#E1E4E8">this</span><span style="color:#F97583">)</span></span>
<span class="line"><span style="color:#F97583">    and</span><span style="color:#FFAB70"> set columnSpan </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> Grid.SetColumnSpan </span><span style="color:#F97583">(</span><span style="color:#E1E4E8">this</span><span style="color:#F97583">,</span><span style="color:#E1E4E8"> columnSpan</span><span style="color:#F97583">)</span></span>
<span class="line"><span style="color:#F97583">  member</span><span style="color:#FFAB70"> this.RowSpan</span></span>
<span class="line"><span style="color:#F97583">    with</span><span style="color:#E1E4E8"> get </span><span style="color:#F97583">()</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> Grid.GetRowSpan </span><span style="color:#F97583">(</span><span style="color:#E1E4E8">this</span><span style="color:#F97583">)</span></span>
<span class="line"><span style="color:#F97583">    and</span><span style="color:#FFAB70"> set rowSpan </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> Grid.SetRowSpan </span><span style="color:#F97583">(</span><span style="color:#E1E4E8">this</span><span style="color:#F97583">,</span><span style="color:#E1E4E8"> rowSpan</span><span style="color:#F97583">)</span></span></code></pre>
<p>Then you can just set the rows and columns properties directly when declaring the control:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="fs"><code><span class="line"><span style="color:#E1E4E8">Border </span><span style="color:#F97583">(</span></span>
<span class="line"><span style="color:#E1E4E8">  Child </span><span style="color:#F97583">=</span></span>
<span class="line"><span style="color:#E1E4E8">    Grid </span><span style="color:#F97583">(</span></span>
<span class="line"><span style="color:#E1E4E8">      ColumnDefinitions </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> ColumnDefinitions </span><span style="color:#9ECBFF">"*, Auto"</span><span style="color:#F97583">,</span></span>
<span class="line"><span style="color:#E1E4E8">      Children </span><span style="color:#F97583">=</span><span style="color:#F97583"> [</span></span>
<span class="line"><span style="color:#E1E4E8">        Button </span><span style="color:#F97583">(</span><span style="color:#E1E4E8">Column </span><span style="color:#F97583">=</span><span style="color:#79B8FF"> 1</span><span style="color:#F97583">,</span><span style="color:#F97583"> ...)</span></span>
<span class="line"><span style="color:#F97583">      ]</span></span>
<span class="line"><span style="color:#F97583">    )</span></span>
<span class="line"><span style="color:#F97583">)</span></span></code></pre>
<h4 id="viewmodels---state">ViewModels -> State</h4>
<p>To connect the views with the actual data, you can just write a ViewModel, like usually, by deriving from ReactiveUI’s ReactiveObject class and implementing observable properties that can be bound by assigning a Binding in the View’s declaration and that works as you would expect.</p>
<p>But I found that declaring the ViewModel classes required a lot of boilerplate code and was also actually one of the few things that I found harder to do in F# that in C#. Also binding them in the view using a string kind of doesn’t make sense if the View is written in Code anyway, because you could have verified those bindings at compile time instead of looking for the binding errors at runtime.</p>
<h4 id="reactive-extensions">Reactive Extensions</h4>
<p>While reactive extensions do have a learning curve, I do prefer them to easier approaches like <code>INotifyPropertyChanged</code> or Redux. While the latter approaches are easy to get started with, I find that there a certain scenarios for which they are just a bad fit.</p>
<p>So in the end I stuck with using Observables directly, which makes the binding code strongly typed but I got rid of all the ViewModels boilerplate code, looking at you <code>ReactiveObject</code>, <code>SetAndRaiseIfChanged</code>, <code>PropertyChangedHelper</code> and all of your many friends.</p>
<h4 id="appbuilder-extensions">AppBuilder Extensions</h4>
<p>After getting rid of the UserControl, Window on ViewModel classes, I’ve added a <a href="https://github.com/8/Timeboxing/blob/master/src/Timeboxing/AppBuilderExtensions.fs">couple of extension methods</a> for the fluent AppBuilder to get rid of writing a custom Application class just to select the theme or the mainwindow, which further cuts down on the boilerplate code and you are left with:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="fs"><code><span class="line"><span style="color:#E1E4E8">AppBuilder.Configure</span><span style="color:#F97583">&#x3C;</span><span style="color:#E1E4E8">Application</span><span style="color:#F97583">>()</span></span>
<span class="line"><span style="color:#E1E4E8">  .AddStyleFluentDark</span><span style="color:#F97583">()</span></span>
<span class="line"><span style="color:#E1E4E8">  .UsePlatformDetect</span><span style="color:#F97583">()</span></span>
<span class="line"><span style="color:#E1E4E8">  .UseMainWindowFactory</span><span style="color:#F97583">(</span><span style="color:#E1E4E8">mainWindowFactory</span><span style="color:#F97583">)</span></span></code></pre>
<h4 id="missing-preview--designer">Missing Preview / Designer</h4>
<p>Now there was one major issue left: no designer preview!</p>
<p>The reason is that the designer preview only works for .xaml files and classes and I’ve burned that bridge. One workaround is of course embedding the view in another control class based control and opening that one in the designer, but that’s back to boilerplate central.</p>
<p>While I’ve never used the designer in WPF for actual editing, I was definitely missing the preview, because spinning up the application continuously while you are working on the UI just doesn’t cut it.</p>
<p>In WPF, you could have built a primitive previewer yourself, by instantiating the control, calling <a href="https://docs.microsoft.com/en-us/dotnet/desktop/WPF/advanced/layout?view=netframeworkdesktop-4.8#LayoutSystem_Measure_Arrange">Measure() and Arrange()</a> on it and using <a href="https://docs.microsoft.com/en-us/dotnet/api/system.windows.media.imaging.rendertargetbitmap?view=net-5.0">RenderTargetBitmap</a> to render it to an png… and this is where the similarities between AvaloniaUI and WPF were really useful, because the <a href="https://github.com/8/Timeboxing/blob/master/src/Timeboxing.Test/Render.fs">same approach</a> works perfectly for Avalonia as well!</p>
<h4 id="preview-images">Preview Images</h4>
<p>I ended up writing simple integration tests that can render a control to a png.</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="fs"><code><span class="line"><span style="color:#79B8FF">[&#x3C;Fact>]</span></span>
<span class="line"><span style="color:#F97583">let</span><span style="color:#FFAB70"> mainViewTest </span><span style="color:#F97583">()</span><span style="color:#F97583"> =</span></span>
<span class="line"><span style="color:#E1E4E8">  renderSizeAuto </span><span style="color:#9ECBFF">"mainView"</span><span style="color:#F97583"> (</span><span style="color:#E1E4E8">State.init </span><span style="color:#F97583">>></span><span style="color:#E1E4E8"> mainView</span><span style="color:#F97583">)</span></span></code></pre>
<p>So when I am working on the controls I just mark those tests to be continually executed on a code change.</p>
<p>This works great in Visual Studio with <a href="https://www.ncrunch.net/">nCrunch</a>. In <a href="https://www.jetbrains.com/rider/">Rider</a> I am using the continuous testing mode to achieve a similar effect and I guess you can do it using <a href="https://docs.microsoft.com/en-us/aspnet/core/tutorials/dotnet-watch?view=aspnetcore-5.0">dotnet watch</a> as well if your are working in vscode or something else. Then you just need to open the files you are interested in a tool that reloads them on changes, e.g. vscode.</p>
<p>Suprisingly I found this approach to work better in some cases than using an integrated designer. While it’s slower, it’s also way more flexible because you can have multiple views of a control with different states visible at the same time. E.g. a progress bar that is empty, half-filled and full.</p>
<img src="/img/timeboxing/vscode-preview.png">
<div class="h-2"></div>
<p>This fits nicely with the fluent <code>ApplicationBuilder</code> approach to configure the themes, which allow you to generate previews of the controls using different themes as well.</p>
<p>You can an also try out how the control scales to different sizes.</p>
<h4 id="free-screenshots">Free screenshots</h4>
<p>As an added bonus, you automatically get screenshots of your application that you can use in a blog post or your documentation and that you can review for visual regressions without running your application yourself or using UI Automation.</p>
<div class="flex gap-2">
  <img src="/img/timeboxing/screenshot-startwork.png">
  <img src="/img/timeboxing/screenshot-startbreak.png">
</div>
<div class="h-2"></div>
<p>Helping out QA and contributing to the documentation of the project never felt so effortless!</p>
<h4 id="example-app-timeboxing">Example App: Timeboxing</h4>
<p>I’ve thrown together a sample application that demonstrates that approach. It’s called <a href="https://github.com/8/timeboxing">Timeboxing and available on github</a> and it’s basically a glorified countdown timer. If you are interested about it’s usecase, you can take a look at the <a href="https://en.wikipedia.org/wiki/Timeboxing">wikipedia article about timeboxing</a> or <a href="Using-Timeboxing-to-achieve-Workplace-Happiness">why I find it useful</a>.</p>
<p>The UI is pretty self-explanatory and looks like that:</p>
<img src="/img/timeboxing/screenshot-action.png">
<h3 id="summary">Summary</h3>
<p>When developing desktop applications I’ve switched out the following things:</p>
<ul>
<li>WPF -> AvaloniaUI</li>
<li>C# -> F#</li>
<li>Xaml -> Code</li>
<li>Views / UserControls -> Functions</li>
<li>ViewModels + Bindings -> Functions + Oberservables</li>
<li>Designer -> Preview Images</li>
</ul>
<p>I’ve found developing an application with that stack way more enjoyable, while improving the output as well.</p>
<p>So far so good, but this was only a small, single application and the question remains: What if the size of the application increases? Will this approach scale? I don’t know yet, but the simple architecture makes me rather optimistic and I am looking forward to find out.</p>
<h3 id="references">References</h3>
<ul>
<li><a href="https://github.com/AvaloniaUI/Avalonia">AvaloniaUI (</a><a href="https://github.com/AvaloniaUI/Avalonia">https://github.com/AvaloniaUI/Avalonia</a>)</li>
<li><a href="https://fsharp.org/">F# (</a><a href="https://fsharp.org">https://fsharp.org</a>)</li>
<li><a href="https://dotnetfoundation.org/projects/reactive-extensions">Reactive Extensions (</a><a href="https://dotnetfoundation.org/projects/reactive-extensions">https://dotnetfoundation.org/projects/reactive-extensions</a>)</li>
<li><a href="https://github.com/8/timeboxing">Timeboxing Github Page (</a><a href="https://github.com/8/timeboxing">https://github.com/8/timeboxing</a>)</li>
<li><a href="https://stackoverflow.com/questions/1039636/how-to-bind-inverse-boolean-properties-in-wpf">Inverting a property (Stackoverflow)</a></li>
<li><a href="https://en.wikipedia.org/wiki/Timeboxing">Wikipedia article about timeboxing (</a><a href="https://en.wikipedia.org/wiki/Timeboxing">https://en.wikipedia.org/wiki/Timeboxing</a>)</li>
</ul>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TailwindCSS color palette for Inkscape]]></title>
            <link>https://lostindetails.com/articles/TailwindCSS-color-palette-for-Inkscape</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/TailwindCSS-color-palette-for-Inkscape</guid>
            <pubDate>Sun, 20 Dec 2020 00:00:00 GMT</pubDate>
            <description><![CDATA[If you are in love with TailwindCSS and you want to use it's color palette in your inkscape designs.]]></description>
            <content:encoded><![CDATA[<h2 id="tailwindcss-color-palette-for-inkscape">TailwindCSS color palette for Inkscape</h2>
<h3 id="tldr">TLDR;</h3>
<p>I’ve converted the default <a href="https://tailwindcss.com/docs/customizing-colors#color-palette-reference">tailwind color palette</a> from <a href="https://github.com/tailwindlabs/tailwindcss/blob/master/colors.js">javascript</a> to an inkscape palette that you can download from <a href="/colorpalette/tailwindcss.gpl">here</a> and copy to your palette folder.</p>
<img class="cutout" src="/img/color-palette/color-palette.png" title="The color palette of TailwindCSS in Inkscape">
<h3 id="background">Background</h3>
<p><a href="https://tailwindcss.com">Tailwind CSS</a> is my favourite CSS Framework. Although Tailwind is highly customizable, it comes with great defaults, for example a <a href="https://tailwindcss.com/docs/customizing-colors#color-palette-reference">gorgeous color palette</a>.</p>
<p><a href="https://inkscape.org/">Inkscape</a> is a great, free vector graphics design tool that supports custom color palettes in GIMP’s palette format (.gpl). To be able to use the tailwind’s color palette in inkscape, I’ve created a custom color palette for inkscape that you can download and use.</p>
<h3 id="why-can-this-be-useful">Why can this be useful</h3>
<p>This can come in handy, if one of the following is true:</p>
<ul>
<li>You prefer to start your designs in inkscape before coding them</li>
<li>You want to create a svg graphic for your webpage</li>
<li>You just prefer the tailwindcss color palette to the one provided by default in inkscape.</li>
</ul>
<h3 id="how-to-use-tailwindcss-color-palette-with-inkscape">How to use tailwindcss color palette with inkscape</h3>
<ol>
<li>Download the <a href="/colorpalette/tailwindcss.gpl">palette</a>.</li>
<li>Copy it to your palette folder.<br>
You can find your palette folder, by opening the <code>Preferences</code> window by pressing <code>CTRL+Shift+p</code> in Inkscape and select <code>System</code> in the menu on the left. The palette folder is shown under <code>User palettes</code>. Click the button on the right to open it in the file explorer.<br>
(On Windows the default folder is <code>%APPDATA%\inkscape\palettes</code>)</li>
<li>Restart Inkscape so that the application picks up the new palette</li>
<li>Activate the palette, by clicking on the left-arrow icon on the bottom right and selecting <code>Tailwind CSS</code> from the popup as shown in the screenshot below.</li>
</ol>
<img src="/img/color-palette/select-palette-in-inkscape.png">
<br>
<p>To get the get a colors tailwindCSS name, you can hover over the color with the mouse.</p>
<img src="/img/color-palette/inkscape-hover-color.png">
<br>
<ol start="5">
<li>(Optionally) You can also use it in the <code>Swatches</code> window by pressing <code>Ctrl+Shift+w</code> and clicking on the <code>Left-Arrow</code> icon and selecting <code>Tailwind CSS</code> from the list of palettes.</li>
</ol>
<img src="/img/color-palette/select-palette-in-swatch-window.png">
<p>…and you are done!</p>
<h3 id="how-to-use-tailwindcss-color-palette-with-gimp">How to use tailwindcss color palette with Gimp</h3>
<p>As the file format is a Gimp palette, it can also be used as in gimp and the approach is similar.</p>
<ol>
<li>Start by downloading the <a href="/colorpalette/tailwindcss.gpl">palette</a>.</li>
<li>Copy <code>tailwindcss.gpl</code> to gimp’s palette folder, e.g. <code>%APPDATA%\GIMP\2.10\palettes</code> on windows.</li>
<li>Restart gimp</li>
<li>Open the <code>Palettes</code> window by clicking <code>Windows</code> -> <code>Dockable Dialogs</code> -> <code>Palettes</code></li>
</ol>
<img src="/img/color-palette/gimp-palettes.png">
<br>
<ol start="5">
<li>Now in the Palettes window open the palette in the <code>Palette Editor</code> by double-clicking the icon <code>Tailwind CSS</code></li>
</ol>
<img src="/img/color-palette/gimp-palette-editor.png">
<h3 id="source">Source</h3>
<p>I’ve written a small F# tool that did the conversion for me, it’s hosted on <a href="https://github.com/8/tailwind2palette">github</a>.</p>
<h3 id="references">References</h3>
<ul class="overflow-x-auto">
  <li>
    <a href="https://tailwindcss.com">
      Tailwind CSS (https://tailwindcss.com)
    </a>
  </li>
  <li>
    <a href="https://inkscape.org">
      Inkscape (https://inkscape.org)
    </a>
  </li>
  <li>
    <a href="https://tailwindcss.com/docs/customizing-colors#color-palette-reference">Tailwind CSS Color Palette Reference (https://tailwindcss.com/docs/customizing-colors#color-palette-reference)</a>
  </li>
  <li>
    <a href="https://github.com/8/tailwind2palette">Source Code (https://github.com/8/tailwind2palette)</a>
  </li>
</ul>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to get a Block Caret in Visual Studio]]></title>
            <link>https://lostindetails.com/articles/How-to-get-a-Block-Caret-in-Visual-Studio</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/How-to-get-a-Block-Caret-in-Visual-Studio</guid>
            <pubDate>Wed, 07 Oct 2020 00:00:00 GMT</pubDate>
            <description><![CDATA[Getting a Block Caret in vscode and Rider is trivial - in Visual Studio you can do it with an extension.]]></description>
            <content:encoded><![CDATA[<h2 id="how-to-get-a-block-caret-in-visual-studio">How to get a Block Caret in Visual Studio</h2>
<h3 id="tldr">TLDR;</h3>
<p>While Visual Studio does not support a Block Caret for normal mode, you can write an extension for Visual Studio to get a Block Caret, which I did and published <a href="https://marketplace.visualstudio.com/items?itemName=MartinKramer.BlockCaret">here</a>.</p>
<h3 id="philosophy">Philosophy</h3>
<p>So I am big fan of continuous small improvements that add up over time, which includes any investment into the developer inner loop. But the pursuit of tiny gains holds a danger of it’s own - it can lead the unwary traveller astray and into rabbit holes that one may not reappear from quickly - should they be deep enough.</p>
<p>In case I may be biased, hence the name of the domain, I let you dear reader, be the judge if this story falls into the former camp or the latter.</p>
<h3 id="whats-with-the-block-caret">What’s with the Block Caret?</h3>
<p>Maybe it’s because I am getting older or maybe it’s because I’ve recently upgraded to a 32” 4K Monitor, I found the visibility of the default Visual Studio caret lacking, as shown in the the following screenshot:</p>
<img src="/img/caret-visibility.png"/>
<p>While it’s certainly not impossible to find the caret that sits right after the second <code>logger</code>, it’s certainly not obvious and takes some mental effort.</p>
<p>I noticed that I’ve grown very fond of the block cursor type combined with a color that has a high contrast to your used color scheme - an approach that I’ve used in vscode to great success.</p>
<p>For me, this approach improves upon the easy discoveryability of a blinking cursor by ridding it of the blinkrate’s time-delay and replacing it’s distracting nagging with the serenity I’ve grown accustomed to by the line cursor.</p>
<p>You can take a look at some cursor types that are available in vscode and try the out by hovering over their names on the right.</p>
<h4 id="cursor-on-a-word">Cursor on a Word</h4>
<div style="display:grid;grid-auto-flow:column;grid-template-columns:400px;column-gap:10px;row-gap:10px;" class="overflow-x-auto"><img class="cutout" src="/img/caret/pos1/l.png"><div style="display:grid;grid-auto-flow:row;grid-auto-rows:min-content;row-gap:10px;column-gap:10px;" class="py-2"><!--[--><div class="px-2 py-1 cursor-pointer text-center border-2 bg-blue-700 border-blue-800 text-white hover:border-blue-900 hover:bg-blue-600">line (default)</div><div class="px-2 py-1 cursor-pointer text-center border-2 bg-blue-700 border-blue-800 text-white hover:border-blue-900 hover:bg-blue-600">line-thin</div><div class="px-2 py-1 cursor-pointer text-center border-2 bg-blue-700 border-blue-800 text-white hover:border-blue-900 hover:bg-blue-600">underscore</div><div class="px-2 py-1 cursor-pointer text-center border-2 bg-blue-700 border-blue-800 text-white hover:border-blue-900 hover:bg-blue-600">box</div><div class="px-2 py-1 cursor-pointer text-center border-2 bg-blue-700 border-blue-800 text-white hover:border-blue-900 hover:bg-blue-600">box-outline</div><!--]--></div></div>
<p>I found the visibility of a specific cursor type depends on the character it sits on.
For example, the visibility of most cursor types decrease dramatically if the caret sits ontop of a bracket, the only saving grace is the aggressive color of the caret.</p>
<h4 id="cursor-on-a-bracket">Cursor on a Bracket</h4>
<div style="display:grid;grid-auto-flow:column;grid-template-columns:400px;column-gap:10px;row-gap:10px;" class="overflow-x-auto"><img class="cutout" src="/img/caret/bracket2/l.png"><div style="display:grid;grid-auto-flow:row;grid-auto-rows:min-content;row-gap:10px;column-gap:10px;" class="py-2"><!--[--><div class="px-2 py-1 cursor-pointer text-center border-2 bg-blue-700 border-blue-800 text-white hover:border-blue-900 hover:bg-blue-600">line (default)</div><div class="px-2 py-1 cursor-pointer text-center border-2 bg-blue-700 border-blue-800 text-white hover:border-blue-900 hover:bg-blue-600">line-thin</div><div class="px-2 py-1 cursor-pointer text-center border-2 bg-blue-700 border-blue-800 text-white hover:border-blue-900 hover:bg-blue-600">underscore</div><div class="px-2 py-1 cursor-pointer text-center border-2 bg-blue-700 border-blue-800 text-white hover:border-blue-900 hover:bg-blue-600">box</div><div class="px-2 py-1 cursor-pointer text-center border-2 bg-blue-700 border-blue-800 text-white hover:border-blue-900 hover:bg-blue-600">box-outline</div><!--]--></div></div>
<p>The specifics will of course depend on a lot of factors, including the programming language and font used and so on, but in general the bigger the highlighted area and the higher the contrast the more visible it will be.</p>
<h3 id="the-search-begins">The search begins</h3>
<p>To my dismay, I found no such feature in Visual Studio, well with the exception of the override mode, which looks the part, but is useless to me due to the behavior change it introduces. The override mode is IMHO a mostly useless remnant of that IDE’s barbaric past, just like the tailbone in humans - and about as useful, YMMV of course.</p>
<p>So I looked into several other options:</p>
<ul>
<li>Cursor Thickness</li>
<li>Text Cursor indicator</li>
<li>Visual Studio Extensions</li>
</ul>
<h4 id="cursor-thickness">Cursor Thickness</h4>
<p>Then there is a system-wide setting for Windows that controls the thickness of the cursor that Visual Studio also respects:</p>
<img class="my-2" src="/img/change-cursor-thickness.png"/>
<p>The problem with that setting is that the color of the cursor is based on the “Plain Text” color and drawn with 100% opacity and so it obscures the character it currently sits on, which is… an interesting choice of implementation and the result is accordingly disappointing:</p>
<img class="cutout" src="/img/visualstudio-cursor-thickness.png"/>
<h4 id="text-cursor-indicator">Text cursor indicator</h4>
<p>In a recent windows build, a new Feature named <a href="https://docs.microsoft.com/en-us/windows-insider/archive/new-in-20H1#text-cursor-indicator">Text cursor indicator</a> was introduced, which sets out to solve exactly the “problem of the lost cursor”.</p>
<img class="mt-2 mb-4" src="/img/text-cursor-indicator.png"/>
<p>When turned on, it looks like it’s working and the indicators appear as shown in the following screenshot:</p>
<img class="cutout mt-2 mb-4" src="/img/text-cursor-indicator-yay.png"/>
<p>The problem is, that it stops working as soon as you scroll (using the mousewheel or a keyboard shortcut) or use <code>Go To Definition</code> - what a bummer!</p>
<img class="cutout my-2" src="/img/text-cursor-indicator-nay.png"/>
<p>If it would actually work and could be restricted to apply only to certain applications, it could be a viable solution.</p>
<h4 id="visual-studio-extensions">Visual Studio Extensions</h4>
<p>While I didn’t find any extension that solved the problem out of the box, it bears mention that there is a very popular Visual Studio Extension that adds Vim support to Visual Studio called <a href="https://github.com/VsVim/VsVim">VsVim</a>. As part of it’s Vim implementation it also implements a Block Caret for normal mode, as is custom for Vim. While I do think that Vim is a great solution for text editing and I use it actively, I find I am more productive with a different setup when writing code.</p>
<p>Thanks to Jared Parsons (<a href="https://twitter.com/jaredpar">@jaredpar</a>), the author of VsVim, who graciously OpenSourced the extension, I was able to gather enough information to figure out how he does that. The logic of rendering and updating the caret is rather straightforward and what you would expect, basically you hide the original caret and add your own vanilla WPF Controls (e.g. Canvas, Rectangle, TextBlock) to an AdornmentLayer and move them around as soon as something changes. But interfacing with Visual Studio was the tricky part and I am sure having the code available saved me lot of time (there is an especially arcane part for accessing the AdornmentLayer).</p>
<h3 id="visual-studio-extension-blockcaret">Visual Studio Extension: BlockCaret</h3>
<p>Armed with that knowledge I finally could write a very simple extension from scratch that implements a Block Caret with the result below:</p>
<img class="cutout" src="/img/block-caret-visibility.png"/>
<p>I’ve published the extension, so if you are interested you can try and download it from <a href="https://marketplace.visualstudio.com/items?itemName=MartinKramer.BlockCaret">here</a> or search for ‘BlockCaret’ in Visual Studio Extensions.</p>
<h3 id="references">References</h3>
<ul class="overflow-x-auto"><li><a href="https://docs.microsoft.com/en-us/windows-insider/archive/new-in-20H1#text-cursor-indicator"><p>Text Cursor Indicator (<a href="https://docs.microsoft.com/en-us/windows-insider/archive/new-in-20H1#text-cursor-indicator">https://docs.microsoft.com/en-us/windows-insider/archive/new-in-20H1#text-cursor-indicator</a>)</p></a></li><li><a href="https://marketplace.visualstudio.com/items?itemName=MartinKramer.BlockCaret"><p>Block Caret (<a href="https://marketplace.visualstudio.com/items?itemName=MartinKramer.BlockCaret">https://marketplace.visualstudio.com/items?itemName=MartinKramer.BlockCaret</a>)</p></a></li><li><a href="https://github.com/VsVim/VsVim">VsVim Github Page (<a href="https://github.com/VsVim/VsVim">https://github.com/VsVim/VsVim</a>)</a></li><li><a href="https://marketplace.visualstudio.com/items?itemName=JaredParMSFT.VsVim"><p>VsVim (<a href="https://marketplace.visualstudio.com/items?itemName=JaredParMSFT.VsVim">https://marketplace.visualstudio.com/items?itemName=JaredParMSFT.VsVim</a>)</p></a></li><li><a href="https://docs.microsoft.com/en-us/windows-insider/archive/new-in-20H1#text-cursor-indicator"><p>Text Cursor Indicators (<a href="https://docs.microsoft.com/en-us/windows-insider/archive/new-in-20H1#text-cursor-indicator">https://docs.microsoft.com/en-us/windows-insider/archive/new-in-20H1#text-cursor-indicator</a>)</p></a></li></ul>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Native Bindings in CSharp]]></title>
            <link>https://lostindetails.com/articles/Native-Bindings-in-CSharp</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/Native-Bindings-in-CSharp</guid>
            <pubDate>Sun, 19 Apr 2020 00:00:00 GMT</pubDate>
            <description><![CDATA[Native Bindings in C# and how to invoke native libraries when you don't know the library name at compile time.]]></description>
            <content:encoded><![CDATA[<h2 id="native-bindings-in-c">Native Bindings in C#</h2>
<h3 id="tldr">TLDR;</h3>
<p>When using <code>[DllImport]</code> you can only specify a constant string as the library name. If you are running dotnet core 3.0 or newer and you need more flexibilty, you can use the class <code>NativeLibrary</code> from the <code>System.Runtime.InteropServices</code> namespace.</p>
<p>If you need to change the name of the native library, a combination of <code>NativeLibrary.SetDllImportResolver()</code> and <code>NativeLibrary.TryLoad()</code> is all you need and you can find a <a href="#solution">code sample</a> further down the article.</p>
<h3 id="calling-native-libraries-from-c">Calling Native Libraries from C#</h3>
<p>The .NET way of calling native Libraries is <a href="https://docs.microsoft.com/en-us/dotnet/standard/native-interop/pinvoke">P/Invoke (Platform Invoke)</a>.</p>
<p>A major part of Platform Invoke is the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.dllimportattribute?view=netcore-3.1"><code>DllImportAttribute</code></a>, which is used to declare where - that is, in which native library - the implementation of the extern static methods can be found.</p>
<p>The following example shows a perfect use case:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">internal</span><span style="color:#F97583"> static</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> NativeApi</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#E1E4E8">  [</span><span style="color:#B392F0">DllImport</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">"user32.dll"</span><span style="color:#E1E4E8">)]</span></span>
<span class="line"><span style="color:#F97583">  public</span><span style="color:#F97583"> static</span><span style="color:#F97583"> extern</span><span style="color:#B392F0"> IntPtr</span><span style="color:#B392F0"> GetForegroundWindow</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>It’s a perfect use case, because the exact name of the library is known in advance and the library is also part of the operating system - only a single version exists and it’s name will never change.</p>
<h3 id="cross-platform-support">Cross-Platform support</h3>
<p>When Platform Invoke was designed, .NET only ran on windows but with Mono and later dotnetcore cross-platform support was added to Platform Invoke.</p>
<p>To make <code>[DllImport]</code> work cross-platform the runtime adds some additional logic when trying to determine the name of the native library. In particular, you can skip the file extension when using the <code>DllImport</code> attribute - the extension is selected automatically depending on the OS it runs on.</p>
<p>For example, when I want to create a C# wrapper that is able to call the method <code>TessBaseAPICreate()</code> from the <a href="https://github.com/tesseract-ocr/tesseract">tesseract library</a>, I can declare it like this:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">internal</span><span style="color:#F97583"> static</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> NativeTesseractApi</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#E1E4E8">  [</span><span style="color:#B392F0">DllImport</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">"libtesseract-4"</span><span style="color:#E1E4E8">)]</span></span>
<span class="line"><span style="color:#F97583">  public</span><span style="color:#F97583"> static</span><span style="color:#F97583"> extern</span><span style="color:#B392F0"> IntPtr</span><span style="color:#B392F0"> TessBaseAPICreate</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">  ...</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>Where the name of the library is supplied in the constructor of the DllImportAttribute.</p>
<p>This approach can enable cross-platform bindings, because the file extension is selected based on the executing operating system. On Windows it’s looking for a <code>.dll</code>, on linux it’s a <code>.so</code> file and on OS X it’s a <code>.dylib</code>.</p>
<p>Additionally, it’s custom to prefix the library name on linux with “lib” so that when a method is declared using <code>[DllImport("Library")]</code> the runtime will look for a file named <code>Library.dll</code> on Windows and on linux it look also for <code>liblibrary.so</code>.</p>
<h3 id="naming-is-hard">Naming is hard</h3>
<p>The problem is, that altough this pattern applies to many libraries, it’s not a strict rule - it may or may not apply to your favorite library as the authors are free to name them in any way they want.</p>
<p>An additional naming pattern for linux libraries is that the version number comes after the file extension. On windows on the other hand, there is usually no indication of the version directly in the file name.</p>
<p>So if you use <code>[DllImport("Library")]</code> this could lead to <code>liblibrary.so.3</code> being found and loaded.</p>
<p>In the aforementioned example with the tesseract library, the platform dependent library name resolution doesn’t work unfortunately, because it doesn’t follow that pattern: eg. the Windows binary is prefixed with <code>lib</code> and the version number comes after the filename, separated with a dash (<code>libtesseract-4.dll</code>).</p>
<p>Customizing the library name is unfortunately only possible at compile time, as the information is stored in an Attribute, which only allows compile time constants.</p>
<h3 id="conditional-compilation">Conditional Compilation</h3>
<p>This in turn, often leads to the use of conditional compilation with preprocessor directives like <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-if">#if</a> eg:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">internal</span><span style="color:#F97583"> static</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> NativeTesseractApi</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  static</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> Constants</span></span>
<span class="line"><span style="color:#E1E4E8">  {</span></span>
<span class="line"><span style="color:#F97583">    public</span><span style="color:#F97583"> const</span><span style="color:#F97583"> string</span><span style="color:#B392F0"> LibraryName</span><span style="color:#F97583"> =</span></span>
<span class="line"><span style="color:#E1E4E8">#</span><span style="color:#F97583">if</span><span style="color:#B392F0"> WIN</span></span>
<span class="line"><span style="color:#9ECBFF">      "libtesseract-4"</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#E1E4E8">#</span><span style="color:#F97583">else</span></span>
<span class="line"><span style="color:#E1E4E8">      "libtesseract.so.4";</span></span>
<span class="line"><span style="color:#E1E4E8">#</span><span style="color:#F97583">endif</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#E1E4E8">  [</span><span style="color:#B392F0">DllImport</span><span style="color:#E1E4E8">(Constants.LibraryName)]</span></span>
<span class="line"><span style="color:#F97583">  public</span><span style="color:#F97583"> static</span><span style="color:#F97583"> extern</span><span style="color:#B392F0"> IntPtr</span><span style="color:#B392F0"> TessBaseAPICreate</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">  ...</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>The downside of this approach is platform dependent il-code that needs to be rebuild for all platforms, despite all the code being the same except for this single constant.</p>
<p>There are a plethora of additional information that is sometimes used when coming up with assembly names, eg. debug vs release builds, x86 vs. x64, single vs multithreaded, etc. Although this can be solved by using additional build flags, rebuilding all combinations and storing the resulting artifacts can get unwieldy fast and leads to artifact bloat.</p>
<h3 id="static-classes">Static classes</h3>
<p>On the flip side it’s possible to write different bindings for each native assembly and then switch them at runtime to use the correct one. The problem with this approach is that this leads to code duplication, as you will need to write almost identical declarations for all methods for each native assembly, eg.:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">internal</span><span style="color:#F97583"> static</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> NativeTesseractLinuxApi</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  public</span><span style="color:#F97583"> const</span><span style="color:#F97583"> string</span><span style="color:#B392F0"> LibraryName</span><span style="color:#F97583"> =</span><span style="color:#9ECBFF"> "libtesseract.so.4"</span><span style="color:#E1E4E8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#E1E4E8">  [</span><span style="color:#B392F0">DllImport</span><span style="color:#E1E4E8">(Constants.LibraryName)]</span></span>
<span class="line"><span style="color:#F97583">  public</span><span style="color:#F97583"> static</span><span style="color:#F97583"> extern</span><span style="color:#B392F0"> IntPtr</span><span style="color:#B392F0"> TessBaseAPICreate</span><span style="color:#E1E4E8">();</span></span>
<span class="line"></span>
<span class="line"><span style="color:#E1E4E8">  [</span><span style="color:#B392F0">DllImport</span><span style="color:#E1E4E8">(Constants.PlaceHolderLibraryName)]</span></span>
<span class="line"><span style="color:#F97583">  public</span><span style="color:#F97583"> static</span><span style="color:#F97583"> extern</span><span style="color:#F97583"> void</span><span style="color:#B392F0"> TessBaseAPIDelete</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">IntPtr</span><span style="color:#B392F0"> handle</span><span style="color:#E1E4E8">);</span></span>
<span class="line"><span style="color:#E1E4E8">  ...</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">internal</span><span style="color:#F97583"> static</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> NativeTesseractWindowsApi</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  public</span><span style="color:#F97583"> const</span><span style="color:#F97583"> string</span><span style="color:#B392F0"> LibraryName</span><span style="color:#F97583"> =</span><span style="color:#9ECBFF"> "libtesseract-4"</span><span style="color:#E1E4E8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#E1E4E8">  [</span><span style="color:#B392F0">DllImport</span><span style="color:#E1E4E8">(Constants.LibraryName)]</span></span>
<span class="line"><span style="color:#F97583">  public</span><span style="color:#F97583"> static</span><span style="color:#F97583"> extern</span><span style="color:#B392F0"> IntPtr</span><span style="color:#B392F0"> TessBaseAPICreate</span><span style="color:#E1E4E8">();</span></span>
<span class="line"></span>
<span class="line"><span style="color:#E1E4E8">  [</span><span style="color:#B392F0">DllImport</span><span style="color:#E1E4E8">(Constants.PlaceHolderLibraryName)]</span></span>
<span class="line"><span style="color:#F97583">  public</span><span style="color:#F97583"> static</span><span style="color:#F97583"> extern</span><span style="color:#F97583"> void</span><span style="color:#B392F0"> TessBaseAPIDelete</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">IntPtr</span><span style="color:#B392F0"> handle</span><span style="color:#E1E4E8">);</span></span>
<span class="line"><span style="color:#E1E4E8">  ...</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>Additionally you will need some kind of runtime logic to switch between those classes, eg:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">internal</span><span style="color:#F97583"> static</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> NativeTesseract</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  static</span><span style="color:#F97583"> bool</span><span style="color:#B392F0"> IsWindows</span><span style="color:#E1E4E8">()</span></span>
<span class="line"><span style="color:#F97583">    =></span><span style="color:#E1E4E8"> Environment.OSVersion.Platform </span><span style="color:#F97583">==</span><span style="color:#E1E4E8"> PlatformID.Win32NT;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">  public</span><span style="color:#F97583"> static</span><span style="color:#B392F0"> IntPtr</span><span style="color:#B392F0"> TessBaseAPICreate</span><span style="color:#E1E4E8">()</span></span>
<span class="line"><span style="color:#F97583">      =></span><span style="color:#B392F0"> IsWindows</span><span style="color:#E1E4E8">()</span></span>
<span class="line"><span style="color:#F97583">        ?</span><span style="color:#E1E4E8"> NativeTesseractWindowsApi.</span><span style="color:#B392F0">TessBaseAPICreate</span><span style="color:#E1E4E8">()</span></span>
<span class="line"><span style="color:#F97583">        :</span><span style="color:#E1E4E8"> NativeTesseractLinuxApi.</span><span style="color:#B392F0">TessBaseAPICreate</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">  ...</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>To add insult to injury, even the glue code to switch between the different static classes is repetitive and cannot be abstracted succinctly without resorting to reflection (and giving up compile time checks) in C# as static classes cannot implement interfaces which in turn leads to code bloat.</p>
<h3 id="enter-the-nativelibrary-class">Enter the NativeLibrary class</h3>
<p>If you are approaching this from a native application, you would have probably used <a href="https://docs.microsoft.com/en-us/windows/win32/dlls/run-time-dynamic-linking">Run-Time Dynamic Linking</a> to solve that issue, using functions like <a href="https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibrarya?redirectedfrom=MSDN">LoadLibrary()</a> to load the dll and <a href="https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddress?redirectedfrom=MSDN">GetProcAddress()</a> to get the address of the function or the linux equivalent <a href="https://linux.die.net/man/3/dlopen">dlopen()</a> and <a href="https://linux.die.net/man/3/dlsym">dlsym()</a>, respectively.</p>
<p>With dotnet core 3.0, we have that option in managed code as well, thanks to the new class <a href="https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.nativelibrary?view=netcore-3.1"><code>NativeLibrary</code></a>.</p>
<p>So the managed counterpart for <code>LoadLibrary()</code>/<code>dlopen()</code> is <code>TryLoad()</code> and <code>GetProcAddress()</code>/<code>dlsym()</code> is handled by <code>TryGetExport()</code>, which is shown in the following table:</p>
<table class="table-fixed mt-2 mb-4">
<thead>
<tr>
  <th></th>
  <th>Linux</th>
  <th>Windows</th>
  <th>.NET (NativeLibrary)</th>
</tr>
</thead>
<tbody>
  <tr>
    <th>Load a Library</th>
    <td>LoadLibrary()</td>
    <td>dlopen()</td>
    <td>Load() / TryLoad()</td>
  </tr>
  <tr>
    <th>Get a Symbol</th>
    <td>GetProcAddress()</td>
    <td>dlsym()</td>
    <td>GetExport() / TryGetExport()</td>
  </tr>
</tbody>
</table>
<p>In addition to that, NativeLibrary also supports registering a callback that can be used to resolve dll import request, using the <code>SetDllImportResolver()</code> method.
With this, it’s really easy to select the library name at runtime and I came up with the following solution:</p>
<p><a name="solution"></a></p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">internal</span><span style="color:#F97583"> static</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> NativeTesseractApi</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  static</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> Constants</span></span>
<span class="line"><span style="color:#E1E4E8">  {</span></span>
<span class="line"><span style="color:#F97583">    public</span><span style="color:#F97583"> const</span><span style="color:#F97583"> string</span><span style="color:#B392F0"> PlaceHolderLibraryName</span><span style="color:#F97583"> =</span><span style="color:#9ECBFF"> "NativeTesseractLib"</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">    public</span><span style="color:#F97583"> const</span><span style="color:#F97583"> string</span><span style="color:#B392F0"> WindowsAssemblyName</span><span style="color:#F97583"> =</span><span style="color:#9ECBFF"> "libtesseract-4"</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">    public</span><span style="color:#F97583"> const</span><span style="color:#F97583"> string</span><span style="color:#B392F0"> LinuxAssemblyName</span><span style="color:#F97583"> =</span><span style="color:#9ECBFF"> "libtesseract.so.4"</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">  static</span><span style="color:#B392F0"> NativeTesseractApi</span><span style="color:#E1E4E8">()</span></span>
<span class="line"><span style="color:#F97583">    =></span><span style="color:#E1E4E8"> NativeLibrary.</span><span style="color:#B392F0">SetDllImportResolver</span><span style="color:#E1E4E8">(Assembly.</span><span style="color:#B392F0">GetExecutingAssembly</span><span style="color:#E1E4E8">(), DllImportResolver);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">  static</span><span style="color:#F97583"> string</span><span style="color:#B392F0"> GetLibraryName</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">string</span><span style="color:#B392F0"> libraryName</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#F97583">    =></span><span style="color:#E1E4E8"> libraryName </span><span style="color:#F97583">switch</span></span>
<span class="line"><span style="color:#E1E4E8">    {</span></span>
<span class="line"><span style="color:#B392F0">      Constants</span><span style="color:#E1E4E8">.</span><span style="color:#B392F0">PlaceHolderLibraryName</span><span style="color:#F97583"> =></span><span style="color:#E1E4E8"> Environment.OSVersion.Platform </span><span style="color:#F97583">switch</span></span>
<span class="line"><span style="color:#E1E4E8">      {</span></span>
<span class="line"><span style="color:#B392F0">        PlatformID</span><span style="color:#E1E4E8">.</span><span style="color:#B392F0">Win32NT</span><span style="color:#F97583"> =></span><span style="color:#E1E4E8"> Constants.WindowsAssemblyName,</span></span>
<span class="line"><span style="color:#79B8FF">        _</span><span style="color:#F97583"> =></span><span style="color:#E1E4E8"> Constants.LinuxAssemblyName,</span></span>
<span class="line"><span style="color:#E1E4E8">      },</span></span>
<span class="line"><span style="color:#79B8FF">      _</span><span style="color:#F97583"> =></span><span style="color:#E1E4E8"> libraryName,</span></span>
<span class="line"><span style="color:#E1E4E8">    };</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">  static</span><span style="color:#B392F0"> IntPtr</span><span style="color:#B392F0"> DllImportResolver</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">string</span><span style="color:#B392F0"> libraryName</span><span style="color:#E1E4E8">, </span><span style="color:#B392F0">Assembly</span><span style="color:#B392F0"> assembly</span><span style="color:#E1E4E8">, </span><span style="color:#B392F0">DllImportSearchPath</span><span style="color:#E1E4E8">? </span><span style="color:#B392F0">searchPath</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">  {</span></span>
<span class="line"><span style="color:#F97583">    var</span><span style="color:#B392F0"> platformDependentName</span><span style="color:#F97583"> =</span><span style="color:#B392F0"> GetLibraryName</span><span style="color:#E1E4E8">(libraryName);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#B392F0">    IntPtr</span><span style="color:#B392F0"> handle</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#E1E4E8">    NativeLibrary.</span><span style="color:#B392F0">TryLoad</span><span style="color:#E1E4E8">(platformDependentName, assembly, searchPath, </span><span style="color:#F97583">out</span><span style="color:#E1E4E8"> handle);</span></span>
<span class="line"><span style="color:#F97583">    return</span><span style="color:#E1E4E8"> handle;</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#E1E4E8">  [</span><span style="color:#B392F0">DllImport</span><span style="color:#E1E4E8">(Constants.PlaceHolderLibraryName)]</span></span>
<span class="line"><span style="color:#F97583">  public</span><span style="color:#F97583"> static</span><span style="color:#F97583"> extern</span><span style="color:#B392F0"> IntPtr</span><span style="color:#B392F0"> TessBaseAPICreate</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">  ...</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>Which basically consists for 4 steps:</p>
<ol>
<li>Keep a single static class and keep the declarative approach of using the <code>[DllImport]</code> attribute and use a well known string as the library name.</li>
</ol>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">internal</span><span style="color:#F97583"> static</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> NativeTesseractApi</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  static</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> Constants</span></span>
<span class="line"><span style="color:#E1E4E8">  {</span></span>
<span class="line"><span style="color:#F97583">    public</span><span style="color:#F97583"> const</span><span style="color:#F97583"> string</span><span style="color:#B392F0"> PlaceHolderLibraryName</span><span style="color:#F97583"> =</span><span style="color:#9ECBFF"> "NativeTesseractLib"</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#E1E4E8">    ...</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#E1E4E8">  [</span><span style="color:#B392F0">DllImport</span><span style="color:#E1E4E8">(Constants.PlaceHolderLibraryName)]</span></span>
<span class="line"><span style="color:#F97583">  public</span><span style="color:#F97583"> static</span><span style="color:#F97583"> extern</span><span style="color:#B392F0"> IntPtr</span><span style="color:#B392F0"> TessBaseAPICreate</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">  ...</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<ol start="2">
<li>Use <code>NativeLibrary.SetDllImportResolver()</code> to register a callback function that handles the importing.</li>
</ol>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">internal</span><span style="color:#F97583"> static</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> NativeTesseractApi</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  static</span><span style="color:#B392F0"> NativeTesseractApi</span><span style="color:#E1E4E8">()</span></span>
<span class="line"><span style="color:#F97583">    =></span><span style="color:#E1E4E8"> NativeLibrary.</span><span style="color:#B392F0">SetDllImportResolver</span><span style="color:#E1E4E8">(Assembly.</span><span style="color:#B392F0">GetExecutingAssembly</span><span style="color:#E1E4E8">(), DllImportResolver);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">  static</span><span style="color:#B392F0"> IntPtr</span><span style="color:#B392F0"> DllImportResolver</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">string</span><span style="color:#B392F0"> libraryName</span><span style="color:#E1E4E8">, </span><span style="color:#B392F0">Assembly</span><span style="color:#B392F0"> assembly</span><span style="color:#E1E4E8">, </span><span style="color:#B392F0">DllImportSearchPath</span><span style="color:#E1E4E8">? </span><span style="color:#B392F0">searchPath</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">  {</span></span>
<span class="line"><span style="color:#F97583">    ..</span><span style="color:#E1E4E8">.</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"><span style="color:#E1E4E8">  ...</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<ol start="3">
<li>Implement the library name resolution, based on it’s current environment.</li>
</ol>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">internal</span><span style="color:#F97583"> static</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> NativeTesseractApi</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  static</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> Constants</span></span>
<span class="line"><span style="color:#E1E4E8">  {</span></span>
<span class="line"><span style="color:#F97583">    public</span><span style="color:#F97583"> const</span><span style="color:#F97583"> string</span><span style="color:#B392F0"> PlaceHolderLibraryName</span><span style="color:#F97583"> =</span><span style="color:#9ECBFF"> "NativeTesseractLib"</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">    public</span><span style="color:#F97583"> const</span><span style="color:#F97583"> string</span><span style="color:#B392F0"> WindowsAssemblyName</span><span style="color:#F97583"> =</span><span style="color:#9ECBFF"> "libtesseract-4"</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">    public</span><span style="color:#F97583"> const</span><span style="color:#F97583"> string</span><span style="color:#B392F0"> LinuxAssemblyName</span><span style="color:#F97583"> =</span><span style="color:#9ECBFF"> "libtesseract.so.4"</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">  static</span><span style="color:#F97583"> string</span><span style="color:#B392F0"> GetLibraryName</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">string</span><span style="color:#B392F0"> libraryName</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#F97583">    =></span><span style="color:#E1E4E8"> libraryName </span><span style="color:#F97583">switch</span></span>
<span class="line"><span style="color:#E1E4E8">    {</span></span>
<span class="line"><span style="color:#B392F0">      Constants</span><span style="color:#E1E4E8">.</span><span style="color:#B392F0">PlaceHolderLibraryName</span><span style="color:#F97583"> =></span><span style="color:#E1E4E8"> Environment.OSVersion.Platform </span><span style="color:#F97583">switch</span></span>
<span class="line"><span style="color:#E1E4E8">      {</span></span>
<span class="line"><span style="color:#B392F0">        PlatformID</span><span style="color:#E1E4E8">.</span><span style="color:#B392F0">Win32NT</span><span style="color:#F97583"> =></span><span style="color:#E1E4E8"> Constants.WindowsAssemblyName,</span></span>
<span class="line"><span style="color:#79B8FF">        _</span><span style="color:#F97583"> =></span><span style="color:#E1E4E8"> Constants.LinuxAssemblyName,</span></span>
<span class="line"><span style="color:#E1E4E8">      },</span></span>
<span class="line"><span style="color:#79B8FF">      _</span><span style="color:#F97583"> =></span><span style="color:#E1E4E8"> libraryName,</span></span>
<span class="line"><span style="color:#E1E4E8">    };</span></span>
<span class="line"><span style="color:#E1E4E8">  ...</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<ol start="4">
<li>And then implement the resolver by using the resolved library name and calling <code>NativeLibrary.TryLoad()</code> to load it.</li>
</ol>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">internal</span><span style="color:#F97583"> static</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> NativeTesseractApi</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  static</span><span style="color:#B392F0"> IntPtr</span><span style="color:#B392F0"> DllImportResolver</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">string</span><span style="color:#B392F0"> libraryName</span><span style="color:#E1E4E8">, </span><span style="color:#B392F0">Assembly</span><span style="color:#B392F0"> assembly</span><span style="color:#E1E4E8">, </span><span style="color:#B392F0">DllImportSearchPath</span><span style="color:#E1E4E8">? </span><span style="color:#B392F0">searchPath</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">  {</span></span>
<span class="line"><span style="color:#F97583">    var</span><span style="color:#B392F0"> platformDependentName</span><span style="color:#F97583"> =</span><span style="color:#B392F0"> GetLibraryName</span><span style="color:#E1E4E8">(libraryName);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#B392F0">    IntPtr</span><span style="color:#B392F0"> handle</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#E1E4E8">    NativeLibrary.</span><span style="color:#B392F0">TryLoad</span><span style="color:#E1E4E8">(platformDependentName, assembly, searchPath, </span><span style="color:#F97583">out</span><span style="color:#E1E4E8"> handle);</span></span>
<span class="line"><span style="color:#F97583">    return</span><span style="color:#E1E4E8"> handle;</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"><span style="color:#E1E4E8">  ...</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>In a case like this, the approach of using the <code>NativeLibrary</code> class feels far superior to both the conditional compilation and multiple static classes approach and it saved us from either a lot of builds and their different binaries or a lot copy/pasted code.</p>
<h3 id="summary">Summary</h3>
<p><code>DllImport</code> combined with naming conventions can often make calling native binaries trivial, but in more complex cases, you can use conditional compilation, multiple static classes and now the new <code>NativeLibrary</code> class.</p>
<p>From those approaches, <code>NativeLibrary</code> provides the greatest flexibility to solve issues directly in code.</p>
<h3 id="references">References</h3>
<ul>
<li>
<p><a href="https://docs.microsoft.com/en-us/dotnet/standard/native-interop/pinvoke">P/Invoke (https://docs.microsoft.com/en-us/dotnet/standard/native-interop/pinvoke”)</a></p>
</li>
<li>
<p><a href="https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.dllimportattribute?view=netcore-3.1">DllImport Attribute (https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.dllimportattribute?view=netcore-3.1)</a></p>
</li>
<li>
<p><a href="https://github.com/tesseract-ocr/tesseract">Tesseract OCR (https://github.com/tesseract-ocr/tesseract)</a></p>
</li>
<li>
<p><a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-if">Conditional Compilation with #if (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-if)</a></p>
</li>
<li>
<p><a href="https://docs.microsoft.com/en-us/windows/win32/dlls/run-time-dynamic-linking">Run-time Dynamic Linking(https://docs.microsoft.com/en-us/windows/win32/dlls/run-time-dynamic-linking)</a></p>
</li>
<li>
<p><a href="https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibrarya">LoadLibrary() (https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibrarya)</a></p>
</li>
<li>
<p><a href="https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddress">GetProcAddress() (https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddress)</a></p>
</li>
<li>
<p><a href="https://linux.die.net/man/3/dlopen">dlopen() (https://linux.die.net/man/3/dlopen)</a></p>
</li>
<li>
<p><a href="https://linux.die.net/man/3/dlsym">dlsym() (https://linux.die.net/man/3/dlsym)</a></p>
</li>
<li>
<p><a href="https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.nativelibrary?view=netcore-3.1">NativeLibrary class (https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.nativelibrary?view=netcore-3.1)</a></p>
</li>
</ul>
<style lang="postcss" scoped>
  .table-fixed th, td {
    @apply px-4
  }
</style>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to run cron inside Docker]]></title>
            <link>https://lostindetails.com/articles/How-to-run-cron-inside-Docker</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/How-to-run-cron-inside-Docker</guid>
            <pubDate>Sun, 13 Oct 2019 00:00:00 GMT</pubDate>
            <description><![CDATA[What you need to do know to be able to run cronjobs inside a docker container, complete with an example Dockerfile.]]></description>
            <content:encoded><![CDATA[<h2 id="how-to-run-cron-jobs-inside-docker">How to run cron jobs inside docker</h2>
<h3 id="tldr">TLDR;</h3>
<p>When running cron as your ENTRYPOINT in a container, make sure you start cron in foreground mode (<code>cron -f</code>) and consider redirecting your job’s stdout and stderr to crons (eg. <code>*/1 * * * * root /app1/test.sh > /proc/1/fd/1 2>/proc/1/fd/2</code>). You can find an complete <code>Dockerfile</code> <a href="#dockerfile">here</a>.</p>
<h3 id="dockers-entrypoint">Dockers Entrypoint</h3>
<p>Docker is build for running one process per container. That doesn’t mean that you can’t run more than one process per container, it’s just that docker only cares about the first process of an image. This process is what you specify using the <a href="https://docs.docker.com/engine/reference/builder#entrypoint"><code>ENTRYPOINT</code></a> in your <code>Dockerfile</code> and it’s the process that docker starts when you run an image.</p>
<p>Should that process terminate, docker will stop the container and if that process writes to stdout or stderr, docker will make that information available via <code>docker logs [container]</code> and if you run the image attached your keyboard input will be forwarded to your <code>ENTRYPOINT</code>s stdin.</p>
<p>If you want to run multiple processes, you can start additional ones from your <code>ENTRYPOINT</code>. Docker doesn’t care about those child processes. Should one of them terminate, your container will continue to run - if they die, they die. And if they write stuff to stdout or stderr, docker doesn’t know and doesn’t care.</p>
<h3 id="cron-is-a-daemon">cron is a daemon</h3>
<p><code>cron</code> is usually run as a daemon so on startup cron <a href="https://linux.die.net/man/3/fork">forks</a>, which means it creates a running copy of itself and then terminates the original process.</p>
<p>Which is normally what you want, but when running inside a container docker will stop your container when your main process exits.</p>
<h3 id="running-cron-inside-a-docker-image">Running Cron inside a Docker image</h3>
<p>The way solve that problem is to instruct cron to start in foreground mode, so that it doesn’t fork by using:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="bash"><code><span class="line"><span style="color:#B392F0">cron</span><span style="color:#79B8FF"> -f</span></span></code></pre>
<p>By running cron in foreground mode you can use it as an <code>ENTRYPOINT</code> in your <code>Dockerfile</code> and it will execute the jobs you’ve specified in your crontab file.</p>
<h3 id="logging-of-cron-jobs">Logging of cron jobs</h3>
<p>There is one problem left, which is that the output of those jobs don’t show up in the docker logs, because docker only tracks the stdout/stderr of the first process.</p>
<p>A simple solution for this problem is just redirecting the stdout/stderr of the child processes to the main process (which will always have PID 1), e.g.:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>*/1 * * * * root /app1/test.sh > /proc/1/fd/1 2>/proc/1/fd/2</span></span></code></pre>
<h3 id="an-complete-example-">An complete example <a name="dockerfile"></a></h3><a name="dockerfile">
<p>Now to put it all together here is a complete <code>Dockerfile</code> as an example:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>FROM ubuntu</span></span>
<span class="line"><span></span></span>
<span class="line"><span># install cron</span></span>
<span class="line"><span>RUN apt-get update &#x26;&#x26; apt-get install cron -y -qq</span></span>
<span class="line"><span></span></span>
<span class="line"><span># create two test applications that we will launch using cron</span></span>
<span class="line"><span>RUN mkdir /app1 &#x26;&#x26; echo 'echo `date +"%H:%M:%S"` - This is sample application 1!' > /app1/test.sh &#x26;&#x26; chmod +x /app1/test.sh</span></span>
<span class="line"><span>RUN mkdir /app2 &#x26;&#x26; echo 'echo `date +"%H:%M:%S"` - This is sample application 2!' > /app2/test.sh &#x26;&#x26; chmod +x /app2/test.sh</span></span>
<span class="line"><span></span></span>
<span class="line"><span># register cron jobs to start the applications and redirects their stdout/stderr</span></span>
<span class="line"><span># to the stdout/stderr of the entry process by adding lines to /etc/crontab</span></span>
<span class="line"><span>RUN echo "*/1 * * * * root /app1/test.sh > /proc/1/fd/1 2>/proc/1/fd/2" >> /etc/crontab</span></span>
<span class="line"><span>RUN echo "*/2 * * * * root /app2/test.sh > /proc/1/fd/1 2>/proc/1/fd/2" >> /etc/crontab</span></span>
<span class="line"><span></span></span>
<span class="line"><span># start cron in foreground (don't fork)</span></span>
<span class="line"><span>ENTRYPOINT [ "cron", "-f" ]</span></span></code></pre>
<p>If you build and run it:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="bash"><code><span class="line"><span style="color:#B392F0">docker</span><span style="color:#9ECBFF"> build</span><span style="color:#9ECBFF"> .</span><span style="color:#79B8FF"> -t</span><span style="color:#9ECBFF"> cron</span></span>
<span class="line"><span style="color:#B392F0">docker</span><span style="color:#9ECBFF"> run</span><span style="color:#9ECBFF"> cron</span></span></code></pre>
<p>And wait for a couple of minutes and you should see the something similiar following output:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>17:03:01 - This is sample application 1!</span></span>
<span class="line"><span>17:04:01 - This is sample application 1!</span></span>
<span class="line"><span>17:04:01 - This is sample application 2!</span></span>
<span class="line"><span>17:05:01 - This is sample application 1!</span></span>
<span class="line"><span>17:06:01 - This is sample application 1!</span></span>
<span class="line"><span>17:06:01 - This is sample application 2!</span></span>
<span class="line"><span>17:07:01 - This is sample application 1!</span></span>
<span class="line"><span>17:08:01 - This is sample application 1!</span></span>
<span class="line"><span>17:08:01 - This is sample application 2!</span></span>
<span class="line"><span>17:09:01 - This is sample application 1!</span></span>
<span class="line"><span>17:10:01 - This is sample application 1!</span></span>
<span class="line"><span>17:10:01 - This is sample application 2!</span></span>
<span class="line"><span>17:11:01 - This is sample application 1!</span></span>
<span class="line"><span>17:12:01 - This is sample application 1!</span></span>
<span class="line"><span>17:12:01 - This is sample application 2!</span></span></code></pre>
<h3 id="references">References</h3>
</a><ul><a name="dockerfile">
</a><li><a name="dockerfile">
  </a><a href="https://docs.docker.com/engine/reference/builder#entrypoint">Dockerfile ENTRYPOINT (https://docs.docker.com/engine/reference/builder#entrypoint)</a>
</li>
<li>
  <a href="https://linux.die.net/man/3/fork">fork (https://linux.die.net/man/3/fork)</a>
</li>
</ul>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Artifact removal in CSharp]]></title>
            <link>https://lostindetails.com/articles/Image-Artifact-removal-in-CSharp</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/Image-Artifact-removal-in-CSharp</guid>
            <pubDate>Mon, 19 Aug 2019 00:00:00 GMT</pubDate>
            <description><![CDATA[Using C# and OpenCV, image artifacts are algorithmically detected and removed.]]></description>
            <content:encoded><![CDATA[<h2 id="artifact-removal-in-c-with-opencv">Artifact Removal in C# with OpenCV</h2>
<p>Recently I solved a computer-vision problem that came up in a project which I found interesting and wanted to share. More specifically it boiled down to a problem of artifact removal and it goes like this:</p>
<h3 id="the-problem">The Problem</h3>
<p>Given the following image which is a cutout of a scan of a sheet of paper:</p>
<img class="cutout" src="/img/artifact-removal/input.png" title="Image with artifacts">
<p>There are one or more lines of text that are interested in and we want to use an OCR (<a href="https://en.wikipedia.org/wiki/Optical_character_recognition">Optical Character Recognition</a>) Engine on it to retrieve the text.</p>
<p>Now the problem is, that there are some artifacts in addition to the text that we are interested in. If we feed the whole cutout into the OCR engine we get back the text we are looking for, but we also get the results of running the OCR on the artifacts as well.</p>
<p>So the process currently looks like that:
<img class="graph" src="/img/artifact-removal/pipeline.dot.svg"></p>
<p>Of course it’s possible to process the text after having run the OCR and that even makes perfect sense incase the structure of the text that you are looking for is well known, like e.g. a telephone number in a specific format. In that case you can simply post process the output of the OCR with a regex or parse the text yourself.</p>
<p>In that case you can extend your pipeline to look like that:
<img class="graph" src="/img/artifact-removal/text-parsing.dot.svg"></p>
<p>But that’s not always the case. It could be that the information upon which you can decide what is an artifact and what is the content is in the relative positions they take up in the image.</p>
<p>If that’s the case you need to remove the artifacts before the OCR step, else you lose the information on which you would base this decision.</p>
<p>So the process will look like:
<img class="graph" src="/img/artifact-removal/artifact-removal.dot.svg"></p>
<p>But enough with the abstract, let’s take another look at the example:</p>
<img class="cutout" src="/img/artifact-removal/input.png" title="Image with artifacts">
<p>Here we are interested in the middle line, the one reading “This is the example text that we want to detect.”.</p>
<p>Notice the additional lines of text at the top and the bottom, which we don’t want. Additionally the scan itself is often rotated a few degrees, as shown in the example.</p>
<p>So the question is: How do we get only the relevant portions from the image?</p>
<p><em>Note:</em>
<em>As you might have guessed, this specific example is made up by me, because the original images contain confidential information that I am not allowed to share.</em></p>
<h3 id="a-false-start">A False Start</h3>
<p>My first attempt to solve the problem was thwarted by the rotation of the image. I tried to find a Region of interest (a rectangle that is smaller than the image and contains only the relevant text) but this approach failed when it came to rotated images:</p>
<img class="cutout" src="/img/artifact-removal/roi.png" title="My Failed Region of Interest approach">
<p>As you can see, I’ve got the option to either cut off the top of “This is…” or I still had some artifacts from the end of the top line remaining.</p>
<h3 id="a-better-solution">A better Solution</h3>
<p>On my next attempt, I looked at the image and tried to distill the rules by which to decide if something is an artifact or not.</p>
<p>In this project, the artifacts where more or less continous artifacts that either touched the top or bottom of the image.</p>
<p>The strategy that I came up with is as follows:</p>
<ol start="0">
<li>Load the image</li>
<li>Get the positions of all objects</li>
<li>Find all objects that are near the top or bottom border</li>
<li>Find the sentences by recursively finding all objects that are next to previously found objects</li>
<li>Remove all artifacts from the image</li>
</ol>
<h4 id="0-load-the-image">0. Load the image</h4>
<p>Before we can start manipulating the image, we need to load it and make sure it’s a grayscale image.</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">var</span><span style="color:#B392F0"> input</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> File.</span><span style="color:#B392F0">ReadAllBytes</span><span style="color:#E1E4E8">(file);</span></span>
<span class="line"><span style="color:#F97583">using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> mat</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> Mat.</span><span style="color:#B392F0">FromImageData</span><span style="color:#E1E4E8">(input))</span></span>
<span class="line"><span style="color:#F97583">using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> grey</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> mat.</span><span style="color:#B392F0">CvtColor</span><span style="color:#E1E4E8">(ColorConversionCodes.BGR2GRAY))</span></span></code></pre>
<h4 id="1-get-the-positions-of-all-objects">1. Get the positions of all objects</h4>
<p>Finding the positions of the objects is really easy with OpenCV. All you need to do is call <a href="https://docs.opencv.org/3.3.1/d3/dc0/group__imgproc__shape.html#ga17ed9f5d79ae97bd4c7cf18403e1689a"><code>FindContours()</code></a>.</p>
<p>Well almost. The thing is that <code>FindContours()</code> works on binary images (which is a fancy word for black and white images), where everything that is not a zero (perfect black), is treated like an object. That means before you can call <code>Cv2.FindContours()</code> you first need to do a black/white conversion and invert the result.</p>
<p>The process of generating a binary image is called <a href="https://en.wikipedia.org/wiki/Thresholding_(image_processing)">thresholding</a>, because pixels are tested against a specified threshold and then (usually) either changed to black or white. OpenCV supports thresholding with a couple of different methods, for example <a href="https://docs.opencv.org/3.3.1/d7/d1b/group__imgproc__misc.html#gae8a4a146d1ca78c626a53577199e9c57"><code>Cv2.Threshold</code></a>.</p>
<p><em>Note:</em>
<em>For noisy real word data (scanned images!) you might want to use the fancier <a href="https://docs.opencv.org/3.3.1/d7/d1b/group__imgproc__misc.html#ga72b913f352e4a1b1b397736707afcde3"><code>Cv2.AdaptiveThreshold</code></a> for better results like so:</em></p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> thresholded</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Mat</span><span style="color:#E1E4E8">())</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#E1E4E8">  Cv2.</span><span style="color:#B392F0">AdaptiveThreshold</span><span style="color:#E1E4E8">(grey, thresholded, </span><span style="color:#79B8FF">255</span><span style="color:#E1E4E8">, AdaptiveThresholdTypes.GaussianC, ThresholdTypes.BinaryInv, </span><span style="color:#79B8FF">15</span><span style="color:#E1E4E8">, </span><span style="color:#79B8FF">7</span><span style="color:#E1E4E8">);</span></span>
<span class="line"><span style="color:#F97583">  ..</span><span style="color:#E1E4E8">.</span></span></code></pre>
<p>Given the input image, thresholding with inversion produces the following result:
<img class="cutout" src="/img/artifact-removal/thresholded.png"></p>
<h4 id="2-find-all-objects-near-the-borders">2. Find all objects near the borders</h4>
<p><code>Cv2.FindContours()</code> allows us to retrieve the bounding boxes of all contours in the image. This makes identifying the objects near the top and bottom border trivially easy.</p>
<p>Now that we can find all letters that are near the border, the question is: How can we find the letters next to those at the border? And the ones close to them and so on? Or to put it in another way: How can we find all sentences that are close to border.</p>
<h4 id="3-find-the-sentences">3. Find the sentences</h4>
<p>Turns out, that’s not an easy problem to solve! The first thing that came to my mind was naively computing the distance between all points of the bounding boxes of the objects. But this has a couple of problems, for example you need multiple passes because you need to repeat the proximity test for all contours after a new contour is found to be in close proximity. But what’s even worse is, that it’s wrong for contours when an edge is closer to another contour than a point of it’s bounding box.</p>
<p>After noticing that this problem is way more complicated than I previously thought, I backtracked a little and found a nice solution by visually joining the objects before calling <code>Cv2.FindContours()</code>.</p>
<p>This operation is called <a href="https://en.wikipedia.org/wiki/Dilation_(morphology)">dilation</a> and I am using the <a href="https://docs.opencv.org/3.0-beta/modules/imgproc/doc/filtering.html?highlight=morphologyex#void%20cvMorphologyEx(const%20CvArr*%20src,%20CvArr*%20dst,%20CvArr*%20temp,%20IplConvKernel*%20element,%20int%20operation,%20int%20iterations)"><code>Cv2.MorphologyEx</code></a> method for that. One of the parameters of that method is a structuring element. The structuring element is a fancy name for the width and height of a rectangle that is used to extend the existing objects.</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">int</span><span style="color:#B392F0"> dilateX</span><span style="color:#F97583"> =</span><span style="color:#79B8FF"> 15</span><span style="color:#E1E4E8">, </span><span style="color:#B392F0">dilateY</span><span style="color:#F97583"> =</span><span style="color:#79B8FF"> 3</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> dilateKernel</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> Cv2.</span><span style="color:#B392F0">GetStructuringElement</span><span style="color:#E1E4E8">(MorphShapes.Ellipse, </span><span style="color:#F97583">new</span><span style="color:#B392F0"> Size</span><span style="color:#E1E4E8">(dilateX, dilateY)))</span></span>
<span class="line"><span style="color:#F97583">using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> morphed</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Mat</span><span style="color:#E1E4E8">())</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#E1E4E8">  Cv2.</span><span style="color:#B392F0">MorphologyEx</span><span style="color:#E1E4E8">(thresholded, morphed, MorphTypes.Dilate, dilateKernel);</span></span>
<span class="line"><span style="color:#F97583">  ..</span><span style="color:#E1E4E8">.</span></span></code></pre>
<p>The following image shows the result of the dilation:
<img class="cutout" src="/img/artifact-removal/morphed.png"></p>
<p>When we now call <code>Cv2.FindContours()</code> instead of getting a contour for each letter, we only get 3 contours - one for each sentence - which can be done with the following C# Code:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#B392F0">Mat</span><span style="color:#E1E4E8">[] </span><span style="color:#B392F0">contours</span><span style="color:#E1E4E8">; </span><span style="color:#F97583">var</span><span style="color:#B392F0"> hierarchy</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Mat</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">Cv2.</span><span style="color:#B392F0">FindContours</span><span style="color:#E1E4E8">(morphed, </span><span style="color:#F97583">out</span><span style="color:#E1E4E8"> contours, hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple);</span></span></code></pre>
<p><em>Note:</em>
<em>Here I am passing RetrievalModes.External so that only the outermost contours are returned.</em></p>
<p>The following image visualizes the contours drawn over the input image:
<img class="cutout" src="/img/artifact-removal/contour.png"></p>
<p>Now we can easily find all contours whose bounding box touches the top or bottom border.</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">var</span><span style="color:#B392F0"> imageHeight</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> mat.Height;</span></span>
<span class="line"><span style="color:#F97583">var</span><span style="color:#B392F0"> yThreshold</span><span style="color:#F97583"> =</span><span style="color:#79B8FF"> 2</span><span style="color:#E1E4E8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">var</span><span style="color:#B392F0"> items</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> contours</span></span>
<span class="line"><span style="color:#E1E4E8">  .</span><span style="color:#B392F0">Select</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">c</span><span style="color:#F97583"> =></span><span style="color:#F97583"> new</span><span style="color:#E1E4E8"> { Contour </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> c, BoundingBox </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> c.</span><span style="color:#B392F0">BoundingRect</span><span style="color:#E1E4E8">() })</span></span>
<span class="line"><span style="color:#E1E4E8">  .</span><span style="color:#B392F0">ToArray</span><span style="color:#E1E4E8">();</span></span>
<span class="line"></span>
<span class="line"><span style="color:#6A737D">/* filter all contours that are near the top border or bottom border */</span></span>
<span class="line"><span style="color:#F97583">var</span><span style="color:#B392F0"> filteredTopBottom</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> items</span></span>
<span class="line"><span style="color:#E1E4E8">  .</span><span style="color:#B392F0">Where</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">i</span><span style="color:#F97583"> =></span><span style="color:#E1E4E8"> i.BoundingBox.Top </span><span style="color:#F97583">&#x3C;=</span><span style="color:#E1E4E8"> yThreshold </span><span style="color:#F97583">||</span></span>
<span class="line"><span style="color:#E1E4E8">             (imageHeight </span><span style="color:#F97583">-</span><span style="color:#E1E4E8"> i.BoundingBox.Bottom) </span><span style="color:#F97583">&#x3C;=</span><span style="color:#E1E4E8"> yThreshold)</span></span>
<span class="line"><span style="color:#E1E4E8">  .</span><span style="color:#B392F0">ToArray</span><span style="color:#E1E4E8">();</span></span></code></pre>
<h4 id="4-remove-all-artifacts">4. Remove all artifacts</h4>
<p>To remove the artifacts we simply draw over their contours and by doing so remove them from the image.</p>
<p>This can be done with the <code>Cv2.DrawContours()</code> method:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#E1E4E8">Cv2.</span><span style="color:#B392F0">DrawContours</span><span style="color:#E1E4E8">(fixedImage, filteredContours, </span><span style="color:#F97583">-</span><span style="color:#79B8FF">1</span><span style="color:#E1E4E8">, </span><span style="color:#F97583">new</span><span style="color:#B392F0"> Scalar</span><span style="color:#E1E4E8">(</span><span style="color:#79B8FF">255</span><span style="color:#E1E4E8">, </span><span style="color:#79B8FF">255</span><span style="color:#E1E4E8">, </span><span style="color:#79B8FF">255</span><span style="color:#E1E4E8">), Cv2.FILLED);</span></span></code></pre>
<p>And finally we are left with the clean, final image that we can pass on to the OCR engine:
<img class="cutout" src="/img/artifact-removal/final.png"></p>
<h3 id="summary">Summary</h3>
<p>In this article I tried to show how OpenCV can be used from C# to solve real-world computer vision problems.</p>
<p>Because the difficult part was figuring out <em>how</em> to tackle the problem at hand (and not necessarily the code itself), I tried to document my thought process including the dead ends.</p>
<p>If you want, you can find the <a href="https://github.com/8/ArtifactRemoval">complete example code here</a>.</p>
<h3 id="references">References</h3>
<div class="overflow-x-auto">
<ul>
<li>
<p><a href="https://github.com/8/ArtifactRemoval">Artifact Removal Github Repo (https://github.com/8/ArtifactRemoval)</a></p>
</li>
<li>
<p><a href="https://docs.opencv.org/3.0-beta/modules/refman.html">OpenCV Documentation (https://docs.opencv.org/3.0-beta/modules/refman.html)</a></p>
</li>
<li>
<p><a href="https://github.com/shimat/opencvsharp">OpenCvSharp4 (https://github.com/shimat/opencvsharp)</a></p>
</li>
<li>
<p><a href="https://en.wikipedia.org/wiki/Optical_character_recognition">Optical Character Recognition (https://en.wikipedia.org/wiki/Optical_character_recognition)</a></p>
</li>
<li>
<p><a href="https://docs.opencv.org/3.3.1/d3/dc0/group__imgproc__shape.html#ga17ed9f5d79ae97bd4c7cf18403e1689a">Cv2.FindContours() (https://docs.opencv.org/3.3.1/d3/dc0/group__imgproc__shape.html#ga17ed9f5d79ae97bd4c7cf18403e1689a)</a></p>
</li>
<li>
<p><a href="https://en.wikipedia.org/wiki/Thresholding_(image_processing)">Thresholding (https://en.wikipedia.org/wiki/Thresholding_(image_processing))</a></p>
</li>
<li>
<p><a href="https://docs.opencv.org/3.3.1/d7/d1b/group__imgproc__misc.html#gae8a4a146d1ca78c626a53577199e9c57">Cv2.Threshold (https://docs.opencv.org/3.3.1/d7/d1b/group__imgproc__misc.html#gae8a4a146d1ca78c626a53577199e9c57)</a></p>
</li>
<li>
<p><a href="https://docs.opencv.org/3.3.1/d7/d1b/group__imgproc__misc.html#ga72b913f352e4a1b1b397736707afcde3">Cv2.AdaptiveThreshold (https://docs.opencv.org/3.3.1/d7/d1b/group__imgproc__misc.html#ga72b913f352e4a1b1b397736707afcde3)</a></p>
</li>
<li>
<p><a href="https://en.wikipedia.org/wiki/Dilation_(morphology)">Dilation (https://en.wikipedia.org/wiki/Dilation_(morphology)</a></p>
</li>
<li>
<p><a href="https://docs.opencv.org/3.0-beta/modules/imgproc/doc/filtering.html?highlight=morphologyex#void%20cvMorphologyEx(const%20CvArr*%20src,%20CvArr*%20dst,%20CvArr*%20temp,%20IplConvKernel*%20element,%20int%20operation,%20int%20iterations)">Cv2.MorphologyEx (https://docs.opencv.org/3.0-beta/modules/imgproc/doc/filtering.html?highlight=morphologyex#void%20cvMorphologyEx(const%20CvArr*%20src,%20CvArr*%20dst,%20CvArr*%20temp,%20IplConvKernel*%20element,%20int%20operation,%20int%20iterations))</a></p>
</li>
</ul>
</div>
<style scoped>
@screen sm {
  .cutout {
    @apply w-auto;
  }
}

.cutout {
  @apply my-2 rounded shadow-md border-dashed border-2 border-gray-400 w-full;
}
</style>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use OpenCV with CSharp]]></title>
            <link>https://lostindetails.com/articles/How-to-use-OpenCV-with-CSharp</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/How-to-use-OpenCV-with-CSharp</guid>
            <pubDate>Mon, 29 Jul 2019 00:00:00 GMT</pubDate>
            <description><![CDATA[Learn how to get started with developing OpenCV Applications in C#, e.g. for image detection and conversion.]]></description>
            <content:encoded><![CDATA[<h2 id="how-to-use-opencv-with-c">How to use OpenCV with C#</h2>
<p>This article will explain how you can get started programming OpenCV with .NET in C#.</p>
<p>The problem is, that OpenCV is built with C/C++ and while comes with python bindings out of the box, it doesn’t have any official .NET bindings. That’s why there are lots of articles on how to get started using python but not a lot about dotnet.</p>
<h3 id="tldr">TLDR;</h3>
<p>Install the nugets <code>OpenCvSharp4</code> and either <code>OpenCvSharp4.runtime.win</code> or <code>OpenCvSharp4.runtime.ubuntu.18.04-x64</code>, depending on your platform or download the example solution <a href="/examples/opencvtest.zip">here</a>.</p>
<h3 id="getting-started">Getting started</h3>
<p>First you need to setup a new solution and project with the OpenCV Libraries. To access the native OpenCV libraries, you need a managed wrapper. I am using <a href="https://github.com/shimat/opencvsharp"><code>OpenCvSharp4</code></a>, which you can use with dotnet core and works on both windows and ubuntu and is licensed under the BSD, just like OpenCV itself.</p>
<ol>
<li>Create a new solution named <code>OpenCvTest</code> and move to that directory.
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="batch"><code><span class="line"><span style="color:#E1E4E8">dotnet new sln -o OpenCvTest</span></span>
<span class="line"><span style="color:#F97583">cd</span><span style="color:#E1E4E8"> OpenCvTest</span></span></code></pre>
</li>
<li>Create a new console project also named <code>OpenCvTest</code> and add it to the solution.
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="bat"><code><span class="line"><span style="color:#E1E4E8">dotnet new console -o OpenCvTest</span></span>
<span class="line"><span style="color:#E1E4E8">dotnet sln add OpenCvTest</span></span></code></pre>
</li>
<li>Add the nuget <code>OpenCvSharp4</code> to the project.
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="bat"><code><span class="line"><span style="color:#E1E4E8">dotnet add OpenCvTest package OpenCvSharp4</span></span></code></pre>
</li>
<li>Add the native runtime depending on your platform (either for windows or for ubuntu 18.04)
Either <code>OpenCvSharp4.runtime.win</code> for windows
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="bat"><code><span class="line"><span style="color:#E1E4E8">dotnet add OpenCvTest package OpenCvSharp4.runtime.win</span></span></code></pre>
or <code>OpenCvSharp4.runtime.ubuntu.18.04-x64</code> for Ubuntu 18.04.
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="bat"><code><span class="line"><span style="color:#E1E4E8">dotnet add OpenCvTest package OpenCvSharp4.runtime.ubuntu.18.04-x64</span></span></code></pre>
or both.</li>
</ol>
<p><em>Note:</em><br>
<em>There are alternative .NET wrappers for OpenCV, but a word of caution: While OpenCV is licensed under the BSD, which makes it useable for closed source commercial applications, some wrapper libraries are using a different license. For example EmguCV uses the <strong>GPL</strong> by default, making it useless for any commercial closed source software.</em></p>
<p><em>This creates the inane situation that the library that does all the heavy lifting is free to use, but the wrapper library that only forwards the calls can cost quite a fortune - without any of the original authors even getting any compensation.<br>
So make sure you check the license of the library before you start using it in a project!</em></p>
<h3 id="using-opencv-in-c">Using OpenCV in C#</h3>
<p>Now it’s time we actually use OpenCV!</p>
<ol>
<li>
<p>We will test the library by creating a really simple application that grayscales images with the following code:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">using</span><span style="color:#B392F0"> System</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">using</span><span style="color:#B392F0"> System</span><span style="color:#E1E4E8">.</span><span style="color:#B392F0">IO</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">using</span><span style="color:#B392F0"> OpenCvSharp</span><span style="color:#E1E4E8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">namespace</span><span style="color:#B392F0"> OpenCvTest</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  class</span><span style="color:#B392F0"> Program</span></span>
<span class="line"><span style="color:#E1E4E8">  {</span></span>
<span class="line"><span style="color:#F97583">    static</span><span style="color:#F97583"> void</span><span style="color:#B392F0"> Main</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">string</span><span style="color:#E1E4E8">[] </span><span style="color:#B392F0">args</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">    {</span></span>
<span class="line"><span style="color:#F97583">      if</span><span style="color:#E1E4E8"> (args.Length </span><span style="color:#F97583">&#x3C;</span><span style="color:#79B8FF"> 1</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">        Console.</span><span style="color:#B392F0">WriteLine</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">"Please specify a filename"</span><span style="color:#E1E4E8">);</span></span>
<span class="line"><span style="color:#F97583">      else</span></span>
<span class="line"><span style="color:#E1E4E8">      {</span></span>
<span class="line"><span style="color:#F97583">        string</span><span style="color:#B392F0"> inputFileName</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> args[</span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">];</span></span>
<span class="line"><span style="color:#F97583">        string</span><span style="color:#B392F0"> outputFileName</span><span style="color:#F97583"> =</span><span style="color:#9ECBFF"> $"</span><span style="color:#9ECBFF">{</span><span style="color:#E1E4E8">Path</span><span style="color:#9ECBFF">.</span><span style="color:#B392F0">GetFileNameWithoutExtension</span><span style="color:#9ECBFF">(</span><span style="color:#E1E4E8">inputFileName</span><span style="color:#9ECBFF">)}</span><span style="color:#9ECBFF">-gray.jpg"</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">        using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> image</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Mat</span><span style="color:#E1E4E8">(inputFileName))</span></span>
<span class="line"><span style="color:#F97583">          using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> gray</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> image.</span><span style="color:#B392F0">CvtColor</span><span style="color:#E1E4E8">(ColorConversionCodes.BGR2GRAY))</span></span>
<span class="line"><span style="color:#E1E4E8">            gray.</span><span style="color:#B392F0">SaveImage</span><span style="color:#E1E4E8">(outputFileName);</span></span>
<span class="line"><span style="color:#E1E4E8">      }</span></span>
<span class="line"><span style="color:#E1E4E8">    }</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>Let’s take a closer look at the important parts:</p>
<p>First, we import the namespace of the library:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">using</span><span style="color:#B392F0"> OpenCvSharp</span><span style="color:#E1E4E8">;</span></span></code></pre>
<p>Secondly, we load the image from a file into a matrix:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> image</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Mat</span><span style="color:#E1E4E8">(fileName))</span></span></code></pre>
<p>Thirdly, we convert the image to grayscale:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> gray</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> image.</span><span style="color:#B392F0">CvtColor</span><span style="color:#E1E4E8">(ColorConversionCodes.BGR2GRAY))</span></span></code></pre>
<p>Finally, we save the grayscaled image back to disk:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#E1E4E8">gray.</span><span style="color:#B392F0">SaveImage</span><span style="color:#E1E4E8">(outputFileName);</span></span></code></pre>
</li>
<li>
<p>Now we put an <code>example.jpg</code> in our solution directory, for example:
<img src="/img/opencv-example.jpg" alt="example.jpg" title="Photo by Max Bender on Unsplash"></p>
</li>
<li>
<p>After we run the application like so:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>dotnet run --project OpenCvTest\OpenCvTest.csproj example.jpg</span></span></code></pre>
</li>
<li>
<p>…we can find the resulting <code>example-gray.jpg</code> in the same folder:
<img src="/img/opencv-example-gray.jpg" alt="example-gray" title="Grayscaled Image"></p>
</li>
</ol>
<h3 id="download-the-example-solution">Download the Example Solution</h3>
<p>You can download a Zip-File with the complete solution <a href="/examples/opencvtest.zip">here</a>.</p>
<h3 id="summary">Summary</h3>
<p>Getting started with OpenCV in C# is easy, thanks to the nice wrapper library <a href="https://github.com/shimat/opencvsharp">OpenCvSharp4</a>.</p>
<h3 id="references">References</h3>
<ul>
<li>
<p><a href="https://docs.opencv.org/3.0-beta/modules/refman.html">OpenCV Documentation (https://docs.opencv.org/3.0-beta/modules/refman.html)</a></p>
</li>
<li>
<p><a href="https://github.com/shimat/opencvsharp">OpenCvSharp4 (https://github.com/shimat/opencvsharp)</a></p>
</li>
<li>
<p><a href="/examples/opencvtest.zip">Example Applikation (opencvtest.zip)</a></p>
</li>
</ul>
<style scoped>
img {
  @apply rounded-lg;
}
</style>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dotnet Cheatsheet]]></title>
            <link>https://lostindetails.com/articles/Dotnet-Cheatsheet</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/Dotnet-Cheatsheet</guid>
            <pubDate>Fri, 28 Jun 2019 00:00:00 GMT</pubDate>
            <description><![CDATA[I've created a cheat sheet for the dotnet cli in different colors. It's available as a pdf file that you can download.]]></description>
            <content:encoded><![CDATA[<h2 id="dotnet-cli-cheatsheet">Dotnet CLI Cheatsheet</h2>
<h3 id="tldr">TLDR;</h3>
<p>I’ve created a cheat sheet for the <code>dotnet</code> cli in different colors. It’s available as a pdf file that you can download at the <a href="#dotnet-cheat-sheets"> bottom of the page</a>.</p>
<h3 id="dotnet-commandline-interface">Dotnet Commandline Interface</h3>
<p>Being a fan of Visual Studio, I’ve neglected learning the dotnet commandline interface in the beginning when dotnet core came out. But now, after having setup the CI for a couple of projects, I was forced to leave my familiar and cushy Visual Studio and venture into commandline land.</p>
<p>Now that I’ve returned from this mouse-less land, I wanted to write down the commands that I needed more often in case someone else - like future me - may find it useful.</p>
<p>Because I’ve previously created a cheat sheet for the <a href="/articles/Docker-Cheatsheet">docker cli</a> I already had all the resources to more or less quickly generate a new cheat sheet at my disposal, so without further ado: Here is my take take on a <code>dotnet</code> cheatsheet.</p>
<div>
  <cheatsheetlist :items="items">
</cheatsheetlist></div>

<script lang="ts">
import { Component, Prop, Vue } from “vue-property-decorator”;
import VueRouter from “vue-router”;
import CheatSheetList, { CheatSheet } from ”../../components/CheatSheetList.vue”;</script>
<p>@Component({
components: { CheatSheetList }
})
export default class DotnetCheatSheet extends Vue {
items: CheatSheet[] = this.getCheatSheets();</p>
<p>getCheatSheets() {
const names = [“dotnet_blue_dark”,“dotnet_blue_light”,“dotnet_blue_light0”,“dotnet_blue_light1”,“dotnet_blue1_dark”,“dotnet_blue1_light”,“dotnet_blue1_light0”,“dotnet_blue1_light1”,“dotnet_blue2_dark”,“dotnet_blue2_light”,“dotnet_blue2_light0”,“dotnet_blue2_light1”,“dotnet_darkblue_dark”,“dotnet_darkblue_light”,“dotnet_darkblue_light0”,“dotnet_darkblue_light1”,“dotnet_darkgray_dark”,“dotnet_darkgray_light”,“dotnet_darkgray_light0”,“dotnet_darkgray_light1”,“dotnet_green_dark”,“dotnet_green_light”,“dotnet_green_light0”,“dotnet_green_light1”,“dotnet_iceblue_dark”,“dotnet_iceblue_light”,“dotnet_iceblue_light0”,“dotnet_iceblue_light1”,“dotnet_indigo_dark”,“dotnet_indigo_light”,“dotnet_indigo_light0”,“dotnet_indigo_light1”,“dotnet_lightgray_dark”,“dotnet_lightgray_light”,“dotnet_lightgray_light0”,“dotnet_lightgray_light1”,“dotnet_red_dark”,“dotnet_red_light”,“dotnet_red_light0”,“dotnet_red_light1”,]
return names.map(n => { return {
image: <code>/cheatsheet/dotnet/${n}.png</code>,
pdf: <code>/cheatsheet/dotnet/${n}.pdf</code>
} as CheatSheet });
}
}</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You should be using using in CSharp]]></title>
            <link>https://lostindetails.com/articles/You-should-be-using-using-in-CSharp</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/You-should-be-using-using-in-CSharp</guid>
            <pubDate>Tue, 11 Jun 2019 00:00:00 GMT</pubDate>
            <description><![CDATA[Find out why the using keyword is so useful in C#. Hint: It protects against three different ways how an instance can escape it's Dispose() call.]]></description>
            <content:encoded><![CDATA[<h2 id="you-should-be-using-using-in-csharp">You should be using <code>using</code> in CSharp</h2>
<h3 id="tldr">TLDR;</h3>
<ul>
<li>Use <code>using</code> instead of calling <code>Dispose()</code> manually whenever you can to keep instances from escaping their dispose call.</li>
<li>Refactor to reduce the need for curly braces and indentation.</li>
<li>Don’t keep Database Connections around longer than needed</li>
</ul>
<p>For extra points:</p>
<ul>
<li>Implement <code>IDisposable</code> yourself when you see <code>try</code> and <code>finally</code> being repeated in a pattern.</li>
<li>…but don’t use the old Dispose pattern</li>
</ul>
<h3 id="why-use-using">Why use <code>using</code>?</h3>
<p>A using statement in the C# looks like this:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">using</span><span style="color:#E1E4E8"> (</span><span style="color:#B392F0">Resource</span><span style="color:#B392F0"> resource</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> expression)</span></span>
<span class="line"><span style="color:#F97583">..</span><span style="color:#E1E4E8">.</span></span></code></pre>
<p>It is used for disposing Resources, which implement the <code>IDisposable</code> interface as soon as they leave the scope and without manually calling it’s <code>Dispose()</code> method.</p>
<p>The reason why this is useful is because there a ways that a disposable resource can escape the call of it’s <code>Dispose()</code> method.</p>
<p>Let’s start with an example and assume that the code in question calls <code>Dispose()</code> manually and starts simple:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">var</span><span style="color:#B392F0"> resource</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Resource</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">resource.</span><span style="color:#B392F0">Dispose</span><span style="color:#E1E4E8">();</span></span></code></pre>
<p>Now, that code is simple to read because it doesn’t do to much - the Resource is created and immediately disposed again.</p>
<p>A more reasonable snippet of code would look like:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">var</span><span style="color:#B392F0"> resource</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Resource</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#6A737D">// Insert a block of arbitrary statements.</span></span>
<span class="line"><span style="color:#E1E4E8">resource.</span><span style="color:#B392F0">Dispose</span><span style="color:#E1E4E8">();</span></span></code></pre>
<p>What could possible go wrong in this ominous block of arbitrary statements?</p>
<h4 id="1-protection-against-exceptions">1. Protection against exceptions</h4>
<p>Probably the most common way that resources escape their <code>Dispose()</code> call are exceptions.</p>
<p>Let’s take another look at the manual <code>Dispose()</code> call:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">var</span><span style="color:#B392F0"> resource</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Resource</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#6A737D">// Insert a block of arbitrary statements.</span></span>
<span class="line"><span style="color:#E1E4E8">resource.</span><span style="color:#B392F0">Dispose</span><span style="color:#E1E4E8">();</span></span></code></pre>
<p>If anything inside of the arbitrary statements block throws an <code>Exception</code> the execution stops before the <code>resource.Dispose()</code> call can be made.</p>
<p>If nothing at all catches the exception, then it’s sometimes no problem, because usually the process is terminated anyway and the OS cleans up after the process by freeing it’s resources like memory, files and sockets.</p>
<p>It’s usually if some <code>catch</code> statement earlier in the call stack handles the Exception and tries to keep on running like nothing happened that the real problems start to emerge.</p>
<p>Luckily the <code>using</code> statement protects against exceptions by wrapping the statement following it into a try block and the <code>Dispose()</code> method in it’s corresponding <code>finally</code> block.</p>
<p>So basically the following code:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> resource</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Resource</span><span style="color:#E1E4E8">())</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#6A737D">  // Insert a block of arbitrary statements.</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>Is converted to something like the following:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  var</span><span style="color:#B392F0"> resource</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Resource</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#F97583">  try</span></span>
<span class="line"><span style="color:#E1E4E8">  {</span></span>
<span class="line"><span style="color:#6A737D">    // Insert a block of arbitrary statements.</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"><span style="color:#F97583">  finally</span></span>
<span class="line"><span style="color:#E1E4E8">  {</span></span>
<span class="line"><span style="color:#B392F0">    IDisposable</span><span style="color:#B392F0"> d</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> (</span><span style="color:#B392F0">IDisposable</span><span style="color:#E1E4E8">)resource;</span></span>
<span class="line"><span style="color:#F97583">    if</span><span style="color:#E1E4E8"> (d </span><span style="color:#F97583">!=</span><span style="color:#79B8FF"> null</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">    {</span></span>
<span class="line"><span style="color:#E1E4E8">      d.</span><span style="color:#B392F0">Dispose</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">    }</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>Thereby preventing the escape via thrown Exceptions.</p>
<p>I am pretty sure you already knew that, but wait, there’s more!</p>
<h4 id="2-protects-against-reassignment">2. Protects against Reassignment</h4>
<p>Another way for an instance to escape could be a wrong reassignment. Let’s assume that <code>resource</code> actually has some resource of finite length, for example a Buffer. An unknowing developer could swoop in and reassign a new value to the variable like so:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">var</span><span style="color:#B392F0"> resource</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Resource</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#6A737D">// A block of arbitrary statements</span></span>
<span class="line"><span style="color:#F97583">if</span><span style="color:#E1E4E8"> (resource.Length </span><span style="color:#F97583">&#x3C;</span><span style="color:#E1E4E8"> requiredLength)</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#E1E4E8">  resource </span><span style="color:#F97583">=</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Resource</span><span style="color:#E1E4E8">(requiredLength);</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span>
<span class="line"><span style="color:#6A737D">// A block of arbitrary statements</span></span>
<span class="line"><span style="color:#E1E4E8">resource.</span><span style="color:#B392F0">Dispose</span><span style="color:#E1E4E8">();</span></span></code></pre>
<p>Now we have a bug - even though the <code>resource.Dispose()</code> call disposed an instance of the resource, it disposes only the second instance that was assigned inside the <code>if</code> statement - the first instance escapes.</p>
<p>By using the <code>using</code> statement (hehe) that potential error can’t happen, because the code:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> resource</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Resource</span><span style="color:#E1E4E8">())</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#6A737D">  // A block of arbitrary statements</span></span>
<span class="line"><span style="color:#F97583">  if</span><span style="color:#E1E4E8"> (resource.Length </span><span style="color:#F97583">&#x3C;</span><span style="color:#E1E4E8"> requiredLength)</span></span>
<span class="line"><span style="color:#E1E4E8">  {</span></span>
<span class="line"><span style="color:#E1E4E8">    resource </span><span style="color:#F97583">=</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Resource</span><span style="color:#E1E4E8">(requiredLength);</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"><span style="color:#6A737D">  // A block of arbitrary statements</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>Results in the following compile-time error:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>Cannot assign to 'resource' because it is a 'using variable' (CS1656)</span></span></code></pre>
<p>There is one more advantage, that’s kind of an extension of the reassignment protection.</p>
<h4 id="3-protects-against-ref-shenanigans-and-out-misuse">3. Protects against <code>ref</code> shenanigans and <code>out</code> misuse</h4>
<p>Additionally, the <code>using</code> statement prevents passing the parameter by <code>ref</code>, which would allow a reassignment of the variable from another method.</p>
<p>So the following code:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> resource</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Resource</span><span style="color:#E1E4E8">())</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#6A737D">  // A block of arbitrary statements</span></span>
<span class="line"><span style="color:#B392F0">  DoSomething</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">ref</span><span style="color:#E1E4E8"> resource);</span></span>
<span class="line"><span style="color:#6A737D">  // A block of arbitrary statements</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span>
<span class="line"><span style="color:#F97583">..</span><span style="color:#E1E4E8">.</span></span>
<span class="line"><span style="color:#F97583">void</span><span style="color:#B392F0"> DoSomething</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">ref</span><span style="color:#B392F0"> Resource</span><span style="color:#B392F0"> resource</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#E1E4E8">  resource </span><span style="color:#F97583">=</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Resource</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>…also doesn’t work and the following compile-time error is triggered:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>Cannot use 'resource' as a ref or out value because it is a 'using variable'</span></span></code></pre>
<p>As the error message hints, the same compile-time error is also shown if the variable is passed as an <code>out</code> parameter.</p>
<p>Which is fine by me, because it doesn’t make much sense for a method to produce already disposed objects, which commonly throw <a href="https://docs.microsoft.com/en-us/dotnet/api/system.objectdisposedexception?view=netframework-4.8"><code>ObjectDisposedException</code></a>s when any member is accessed after they got disposed.</p>
<p>With advantages like that, you would assume that everybody is using the <code>using</code> statement whenever they can, wouldn’t you?</p>
<p>I found out that’s not always the case. The reasons for that are often myths about <code>using</code> and <code>IDisposable</code> that pop up as objections from time to time. That’s why I decided to tackle them here as well.</p>
<h3 id="myths-that-developers-believe-about-using">Myths that developers believe about <code>using</code></h3>
<p>So without further ado I present to you the top 4 myths why developers don’t use <code>using</code> / <code>IDisposable</code>:</p>
<ol>
<li>Multiple <code>using</code> statements introduce too many indentations / curly braces / nested code blocks!</li>
<li>I can’t dispose the Database Connection, I will need it later again!</li>
<li>I’ve got nothing to dispose!</li>
<li>I need to implement the dispose pattern!</li>
</ol>
<p>Let’s look at each objection separately and see what we can do.</p>
<h4 id="1-too-much-indentation">1. Too much Indentation</h4>
<p>From time to time I hear developers complaining about the additional levels of indentation and curly braces that can be introduced by using a lot of <code>using</code> statements.</p>
<p>Let’s take a look at a simple example that accesses <a href="https://insights.stackoverflow.com/survey/2019#technology-_-databases">our 3rd most popular Database</a> and loads an entry with the matching id from a table.</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">namespace</span><span style="color:#B392F0"> UsingExample</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">    public</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> CustomerRepository</span><span style="color:#E1E4E8"> : </span><span style="color:#B392F0">ICustomerRepository</span></span>
<span class="line"><span style="color:#E1E4E8">    {</span></span>
<span class="line"><span style="color:#F97583">        string</span><span style="color:#B392F0"> GetConnectionString</span><span style="color:#E1E4E8">()</span></span>
<span class="line"><span style="color:#F97583">            =></span><span style="color:#9ECBFF"> "..."</span><span style="color:#E1E4E8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">        public</span><span style="color:#B392F0"> CustomerModel</span><span style="color:#B392F0"> GetCustomerById</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">int</span><span style="color:#B392F0"> id</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">        {</span></span>
<span class="line"><span style="color:#B392F0">            CustomerModel</span><span style="color:#B392F0"> customer</span><span style="color:#E1E4E8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">            using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> tran</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> TransactionScope</span><span style="color:#E1E4E8">())</span></span>
<span class="line"><span style="color:#E1E4E8">            {</span></span>
<span class="line"><span style="color:#F97583">                using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> conn</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> SqlConnection</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">GetConnectionString</span><span style="color:#E1E4E8">()))</span></span>
<span class="line"><span style="color:#E1E4E8">                {</span></span>
<span class="line"><span style="color:#E1E4E8">                    conn.</span><span style="color:#B392F0">Open</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#F97583">                    using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> cmd</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> SqlCommand</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">"select * from Customer where Id = @Id"</span><span style="color:#E1E4E8">, conn))</span></span>
<span class="line"><span style="color:#E1E4E8">                    {</span></span>
<span class="line"><span style="color:#E1E4E8">                        cmd.Parameters.</span><span style="color:#B392F0">AddWithValue</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">"Id"</span><span style="color:#E1E4E8">, id);</span></span>
<span class="line"><span style="color:#F97583">                        using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> dr</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> cmd.</span><span style="color:#B392F0">ExecuteReader</span><span style="color:#E1E4E8">())</span></span>
<span class="line"><span style="color:#E1E4E8">                        {</span></span>
<span class="line"><span style="color:#F97583">                            if</span><span style="color:#E1E4E8"> (dr.</span><span style="color:#B392F0">Read</span><span style="color:#E1E4E8">())</span></span>
<span class="line"><span style="color:#E1E4E8">                            {</span></span>
<span class="line"><span style="color:#E1E4E8">                                customer </span><span style="color:#F97583">=</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> CustomerModel</span></span>
<span class="line"><span style="color:#E1E4E8">                                {</span></span>
<span class="line"><span style="color:#E1E4E8">                                    Id        </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">int</span><span style="color:#E1E4E8">)   dr[</span><span style="color:#9ECBFF">"Id"</span><span style="color:#E1E4E8">],</span></span>
<span class="line"><span style="color:#E1E4E8">                                    Firstname </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">string</span><span style="color:#E1E4E8">)dr[</span><span style="color:#9ECBFF">"Firstname"</span><span style="color:#E1E4E8">],</span></span>
<span class="line"><span style="color:#E1E4E8">                                    Lastname  </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">string</span><span style="color:#E1E4E8">)dr[</span><span style="color:#9ECBFF">"Lastname"</span><span style="color:#E1E4E8">],</span></span>
<span class="line"><span style="color:#E1E4E8">                                };</span></span>
<span class="line"><span style="color:#E1E4E8">                            }</span></span>
<span class="line"><span style="color:#F97583">                            else</span></span>
<span class="line"><span style="color:#E1E4E8">                                customer </span><span style="color:#F97583">=</span><span style="color:#79B8FF"> null</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#E1E4E8">                        }</span></span>
<span class="line"><span style="color:#E1E4E8">                    }</span></span>
<span class="line"><span style="color:#E1E4E8">                }</span></span>
<span class="line"><span style="color:#E1E4E8">            }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">            return</span><span style="color:#E1E4E8"> customer;</span></span>
<span class="line"><span style="color:#E1E4E8">        }</span></span>
<span class="line"><span style="color:#E1E4E8">    }</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p><em>Note:</em>
<em>The TransactionScope is not really needed here, it only enforces that the command is really unable to modify anything, as it is automatically  rolled back when it leaves the scope.</em></p>
<p>Now you can argue that those indentation levels are problematic - and honestly - I would agree, because IMHO even though the code is not doing a lot, it is already pretty hard to read.</p>
<p>But that’s not an issue with using <code>using</code>! Heck, you’ve got the same problems if you nest your <code>if</code>s deeply. So the solution is not using fewer <code>using</code>s, but refactoring your code!</p>
<p>The similarity to <code>if</code> doesn’t end here, because <code>using</code> statements can skip the curly brackets, just like with an <code>if</code> statement. When you skip the curly braces <code>{}</code> after an <code>if</code> statement, you’ll want to indent the next statement, so that it’s clear that it is being affected by the <code>if</code>. But the thing is, you are not required to.</p>
<p>While we don’t want to take advantage of that freedom with an <code>if</code> statement, we maybe want to do that in the case of the <code>using</code> statement.</p>
<p>So instead of:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> tran</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> TransactionScope</span><span style="color:#E1E4E8">())</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">    using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> conn</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> SqlConnection</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">GetConnectionString</span><span style="color:#E1E4E8">()))</span></span>
<span class="line"><span style="color:#E1E4E8">    {</span></span>
<span class="line"><span style="color:#F97583">      ..</span><span style="color:#E1E4E8">.</span></span>
<span class="line"><span style="color:#E1E4E8">    }</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>we can just write:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> tran</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> TransactionScope</span><span style="color:#E1E4E8">())</span></span>
<span class="line"><span style="color:#F97583">using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> conn</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> SqlConnection</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">GetConnectionString</span><span style="color:#E1E4E8">()))</span></span></code></pre>
<p>Okay, but that trick alone does not get rid of all identations! Let’s take a look at how we use the <code>SqlConnection</code>:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> conn</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> SqlConnection</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">GetConnectionString</span><span style="color:#E1E4E8">()))</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#E1E4E8">    conn.</span><span style="color:#B392F0">Open</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#F97583">    using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> cmd</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> SqlCommand</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">"select * from Customer where Id = @Id"</span><span style="color:#E1E4E8">, conn))</span></span>
<span class="line"><span style="color:#E1E4E8">    {</span></span>
<span class="line"><span style="color:#F97583">      ..</span><span style="color:#E1E4E8">.</span></span>
<span class="line"><span style="color:#E1E4E8">    }</span></span>
<span class="line"><span style="color:#F97583">    ..</span><span style="color:#E1E4E8">.</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>If it weren’t this pesky <code>conn.Open()</code> call!
It keeps us from just skipping the curly braces on the <code>using</code> statement with the <code>new SqlConnection()</code>.</p>
<p>The reason is, that if you skip the curly braces <code>{}</code> the <code>using</code> variable will only be available for the following statement - in this case the <code>conn.Open()</code> call, but not for any statements after it, like the line were we actually use it in the <code>SqlCommand</code> constructor.</p>
<p>So what do we do in that case? The same thing that we do with too deeply nested <code>if</code> statements: we refactor them!</p>
<p>In this case, I am going to create a method for setting up the <code>SqlConnection</code>, including the <code>conn.Open()</code> call:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#B392F0">SqlConnection</span><span style="color:#B392F0"> GetOpenConnection</span><span style="color:#E1E4E8">()</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">    var</span><span style="color:#B392F0"> conn</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> SqlConnection</span><span style="color:#E1E4E8">(</span><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">.</span><span style="color:#B392F0">GetConnectionString</span><span style="color:#E1E4E8">());</span></span>
<span class="line"><span style="color:#E1E4E8">    conn.</span><span style="color:#B392F0">Open</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#F97583">    return</span><span style="color:#E1E4E8"> conn;</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>…and because I am on a roll, I am going to do the same thing for the <code>SqlCommand</code> and it’s <code>Parameters.AddWithValue()</code> call:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#B392F0">SqlCommand</span><span style="color:#B392F0"> GetSelectCustomerByIdCmd</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">int</span><span style="color:#B392F0"> id</span><span style="color:#E1E4E8">, </span><span style="color:#B392F0">SqlConnection</span><span style="color:#B392F0"> conn</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">    var</span><span style="color:#B392F0"> cmd</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> SqlCommand</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">"select * from Customer where Id = @Id"</span><span style="color:#E1E4E8">, conn);</span></span>
<span class="line"><span style="color:#E1E4E8">    cmd.Parameters.</span><span style="color:#B392F0">AddWithValue</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">"Id"</span><span style="color:#E1E4E8">, id);</span></span>
<span class="line"><span style="color:#F97583">    return</span><span style="color:#E1E4E8"> cmd;</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>While we are at it, we can also refactor the reading of the <code>CustomerModel</code> into it’s own method:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#B392F0">CustomerModel</span><span style="color:#B392F0"> ReadCustomer</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">IDataReader</span><span style="color:#B392F0"> dr</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#B392F0">    CustomerModel</span><span style="color:#B392F0"> customer</span><span style="color:#E1E4E8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">    if</span><span style="color:#E1E4E8"> (dr.</span><span style="color:#B392F0">Read</span><span style="color:#E1E4E8">())</span></span>
<span class="line"><span style="color:#E1E4E8">    {</span></span>
<span class="line"><span style="color:#E1E4E8">        customer </span><span style="color:#F97583">=</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> CustomerModel</span></span>
<span class="line"><span style="color:#E1E4E8">        {</span></span>
<span class="line"><span style="color:#E1E4E8">            Id        </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">int</span><span style="color:#E1E4E8">)   dr[</span><span style="color:#9ECBFF">"Id"</span><span style="color:#E1E4E8">],</span></span>
<span class="line"><span style="color:#E1E4E8">            Firstname </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">string</span><span style="color:#E1E4E8">)dr[</span><span style="color:#9ECBFF">"Firstname"</span><span style="color:#E1E4E8">],</span></span>
<span class="line"><span style="color:#E1E4E8">            Lastname  </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">string</span><span style="color:#E1E4E8">)dr[</span><span style="color:#9ECBFF">"Lastname"</span><span style="color:#E1E4E8">],</span></span>
<span class="line"><span style="color:#E1E4E8">        };</span></span>
<span class="line"><span style="color:#E1E4E8">    }</span></span>
<span class="line"><span style="color:#F97583">    else</span></span>
<span class="line"><span style="color:#E1E4E8">        customer </span><span style="color:#F97583">=</span><span style="color:#79B8FF"> null</span><span style="color:#E1E4E8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">    return</span><span style="color:#E1E4E8"> customer;</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>Now we can use them in the final refactored <code>GetCustomerById()</code> method:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">public</span><span style="color:#B392F0"> CustomerModel</span><span style="color:#B392F0"> GetCustomerById</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">int</span><span style="color:#B392F0"> id</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">    using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> tran</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> TransactionScope</span><span style="color:#E1E4E8">())</span></span>
<span class="line"><span style="color:#F97583">    using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> conn</span><span style="color:#F97583"> =</span><span style="color:#B392F0"> GetOpenConnection</span><span style="color:#E1E4E8">())</span></span>
<span class="line"><span style="color:#F97583">    using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> cmd</span><span style="color:#F97583"> =</span><span style="color:#B392F0"> GetSelectCustomerByIdCmd</span><span style="color:#E1E4E8">(id, conn))</span></span>
<span class="line"><span style="color:#F97583">    using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> dr</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> cmd.</span><span style="color:#B392F0">ExecuteReader</span><span style="color:#E1E4E8">())</span></span>
<span class="line"><span style="color:#F97583">        return</span><span style="color:#B392F0"> ReadCustomer</span><span style="color:#E1E4E8">(dr);</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>I would argue that this is much better than what we had in the beginning:</p>
<ul>
<li>We’ve got rid of the identation and the curlies and even if we want to keep the indentation, it’s now really easy to read.</li>
<li>We’ve got smaller methods that do less each and they only have one single concern instead of a big method that does all the things.</li>
<li>…but wait, there’s even more! Now the code is also easy to extend!</li>
</ul>
<p>As an example imagine that we now want to retrieve Customers in a slightly different way, for example retrieve all Customers at once. The only thing we need to do is implement two teeny-weeny methods that follow the same pattern as before:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#B392F0">SqlCommand</span><span style="color:#B392F0"> GetSelectAllCustomersCmd</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">SqlConnection</span><span style="color:#B392F0"> conn</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#F97583">    =></span><span style="color:#F97583"> new</span><span style="color:#B392F0"> SqlCommand</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">"select * from Customer"</span><span style="color:#E1E4E8">, conn);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">public</span><span style="color:#B392F0"> CustomerModel</span><span style="color:#E1E4E8">[] </span><span style="color:#B392F0">GetAllCustomers</span><span style="color:#E1E4E8">()</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">    var</span><span style="color:#B392F0"> customers</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> List</span><span style="color:#E1E4E8">&#x3C;</span><span style="color:#B392F0">CustomerModel</span><span style="color:#E1E4E8">>();</span></span>
<span class="line"><span style="color:#B392F0">    CustomerModel</span><span style="color:#B392F0"> customer</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">    using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> tran</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> TransactionScope</span><span style="color:#E1E4E8">())</span></span>
<span class="line"><span style="color:#F97583">    using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> conn</span><span style="color:#F97583"> =</span><span style="color:#B392F0"> GetOpenConnection</span><span style="color:#E1E4E8">())</span></span>
<span class="line"><span style="color:#F97583">    using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> cmd</span><span style="color:#F97583"> =</span><span style="color:#B392F0"> GetSelectAllCustomersCmd</span><span style="color:#E1E4E8">(conn))</span></span>
<span class="line"><span style="color:#F97583">    using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> dr</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> cmd.</span><span style="color:#B392F0">ExecuteReader</span><span style="color:#E1E4E8">())</span></span>
<span class="line"><span style="color:#F97583">        while</span><span style="color:#E1E4E8"> ((customer </span><span style="color:#F97583">=</span><span style="color:#B392F0"> ReadCustomer</span><span style="color:#E1E4E8">(dr)) </span><span style="color:#F97583">!=</span><span style="color:#79B8FF"> null</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">            customers.</span><span style="color:#B392F0">Add</span><span style="color:#E1E4E8">(customer);</span></span>
<span class="line"><span style="color:#F97583">    return</span><span style="color:#E1E4E8"> customers.</span><span style="color:#B392F0">ToArray</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>…and we are done!</p>
<h4 id="2-i-cant-dispose-the-database-connection-i-will-need-it-later-again">2. I can’t dispose the Database Connection, I will need it later again</h4>
<p>This one is not about the <code>IDisposable</code> interface, but about specific implementations - Database Connection - e.g. <code>SqlConnection</code>.</p>
<p>So on one hand opening a Database Connections is an expensive operation.</p>
<p>On the other hand, you should always hold onto disposable resources for the least amount of time possible.</p>
<p>Okay, but who wins in that case? Luckily we don’t have to decide, because ADO.NET implements <a href="https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/connection-pooling">ConnectionPooling</a>.</p>
<p>This means that a so-called pooler inside of the Framework holds onto the physical connection, even after we’ve called it’s <code>Dispose()</code> method.</p>
<p>As a result opening the Connection the first time is just as slow as always, but the second and all consecutive times when we open the connection we don’t pay that performance overhead - as long as the underlying physical connection is available and can be reused, of course.</p>
<p>This gives us the benefits of both worlds - a simple resource management strategy where we can just ask for a new Connection when we need it and dispose it immediately afterwards, but also great performance, because the underlying physical connection is being kept alive and reused, if possible.</p>
<p>So for Database Connections that means you should dispose them as soon as you are done with your operation, as you can see in the methods <code>GetAllCustomers()</code> and <code>GetCustomerById()</code> above.</p>
<h4 id="3-ive-got-nothing-to-dispose">3. I’ve got nothing to dispose</h4>
<p>Okay, that’s a valid reason - how could you possibly call <code>Dispose()</code> if you don’t have a class that implements the <code>IDisposable</code> interface?</p>
<p>Well, sometimes it makes sense to implement <code>IDisposable</code> even if you don’t have unmanaged resources to free.</p>
<p>So what I’ve found is that the <code>using</code> statement is also useful to wrap logic that you normally would want to encapsulate in a <code>try/finally</code> block - with the additional advantages of reassignment protection as explained above.</p>
<p>For just a one-time use, this doesn’t make sense of course, but if you happen to see this as a pattern repeating in your code than wrapping the <code>try/finally</code> in an <code>IDisposable</code> makes sense.</p>
<p>As an example, image you want to control the number of concurrent requests to a contested resource in a multithreaded application e.g. like your webserver.</p>
<p>You’ve setup your contested resource and an instance of <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.semaphoreslim?view=netframework-4.8"><code>SemaphoreSlim</code></a> to the maximum number of concurrent requests that you are comfortable with, like so:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">.contestedResource </span><span style="color:#F97583">=</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> ContestedResource</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">.semaphoreSlim </span><span style="color:#F97583">=</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> SemaphoreSlim</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">initialCount</span><span style="color:#E1E4E8">: </span><span style="color:#79B8FF">1</span><span style="color:#E1E4E8">, </span><span style="color:#B392F0">maxCount</span><span style="color:#E1E4E8">: </span><span style="color:#79B8FF">1</span><span style="color:#E1E4E8">);</span></span></code></pre>
<p>And you now implement the async wrapper that wraps the calls to the contested Resource (without blocking the calling thread, thanks to <code>SemaphoreSlim</code>s <code>WaitAsync()</code> method).</p>
<p>To not mess up the system with deadlocks if an exception is thrown when calling the contested resource, you make sure to wrap the call in a <code>try</code> block and release the semaphore in the <code>finally</code> block, like so:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">public</span><span style="color:#F97583"> async</span><span style="color:#B392F0"> Task</span><span style="color:#E1E4E8">&#x3C;</span><span style="color:#B392F0">Result</span><span style="color:#E1E4E8">> </span><span style="color:#B392F0">GetFoo</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">CancellationToken</span><span style="color:#B392F0"> ct</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  await</span><span style="color:#79B8FF"> this</span><span style="color:#E1E4E8">.semaphoreSlim.</span><span style="color:#B392F0">WaitAsync</span><span style="color:#E1E4E8">(ct);</span></span>
<span class="line"><span style="color:#F97583">  try</span><span style="color:#E1E4E8"> { </span><span style="color:#F97583">return</span><span style="color:#79B8FF"> this</span><span style="color:#E1E4E8">.contestedResource.</span><span style="color:#B392F0">GetFoo</span><span style="color:#E1E4E8">(); }</span></span>
<span class="line"><span style="color:#F97583">  finally</span><span style="color:#E1E4E8"> { </span><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">.semaphoreSlim.</span><span style="color:#B392F0">Release</span><span style="color:#E1E4E8">(); }</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">public</span><span style="color:#F97583"> async</span><span style="color:#B392F0"> Task</span><span style="color:#E1E4E8">&#x3C;</span><span style="color:#B392F0">Result</span><span style="color:#E1E4E8">> </span><span style="color:#B392F0">GetBar</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">CancellationToken</span><span style="color:#B392F0"> ct</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  await</span><span style="color:#79B8FF"> this</span><span style="color:#E1E4E8">.semaphoreSlim.</span><span style="color:#B392F0">WaitAsync</span><span style="color:#E1E4E8">(ct);</span></span>
<span class="line"><span style="color:#F97583">  try</span><span style="color:#E1E4E8"> { </span><span style="color:#F97583">return</span><span style="color:#79B8FF"> this</span><span style="color:#E1E4E8">.contestedResource.</span><span style="color:#B392F0">GetBar</span><span style="color:#E1E4E8">(); }</span></span>
<span class="line"><span style="color:#F97583">  finally</span><span style="color:#E1E4E8"> { </span><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">.semaphoreSlim.</span><span style="color:#B392F0">Release</span><span style="color:#E1E4E8">(); }</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">public</span><span style="color:#F97583"> async</span><span style="color:#B392F0"> Task</span><span style="color:#E1E4E8">&#x3C;</span><span style="color:#B392F0">Result</span><span style="color:#E1E4E8">> </span><span style="color:#B392F0">GetBaz</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">CancellationToken</span><span style="color:#B392F0"> ct</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  await</span><span style="color:#79B8FF"> this</span><span style="color:#E1E4E8">.semaphoreSlim.</span><span style="color:#B392F0">WaitAsync</span><span style="color:#E1E4E8">(ct);</span></span>
<span class="line"><span style="color:#F97583">  try</span><span style="color:#E1E4E8"> { </span><span style="color:#F97583">return</span><span style="color:#79B8FF"> this</span><span style="color:#E1E4E8">.contestedResource.</span><span style="color:#B392F0">GetBaz</span><span style="color:#E1E4E8">(); }</span></span>
<span class="line"><span style="color:#F97583">  finally</span><span style="color:#E1E4E8"> { </span><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">.semaphoreSlim.</span><span style="color:#B392F0">Release</span><span style="color:#E1E4E8">(); }</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">..</span><span style="color:#E1E4E8">.</span></span></code></pre>
<p>When you look at that code, you can see that a specific pattern repeats itself:</p>
<ol>
<li>It starts with the resource acquisition, which is always the same call: <code>await this.semaphoreSlim.WaitAsync(ct)</code></li>
<li>Then custom code inside a <code>try</code> block is executed</li>
<li>Then the resource is released inside a <code>finally</code> statement: <code>finally { this.semaphoreSlim.Release(); }</code></li>
</ol>
<p>Isn’t that exactly what <code>using</code> provides?
So let’s create code that wraps the semaphore usage in an <code>IDisposable</code> interface so that we can apply <code>using</code>:</p>
<p>The implementation will be split in two parts, the first one being the class that keeps track of the <code>SemaphoreSlim</code> instance and is able to hand out disposable tokens. The second class is the disposable token.</p>
<p>First I’ll start with the class that generates the tokens, I’ve called it <code>AsyncLock</code>:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">public</span><span style="color:#F97583"> sealed</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> AsyncLock</span><span style="color:#E1E4E8"> : </span><span style="color:#B392F0">IDisposable</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">    private</span><span style="color:#F97583"> readonly</span><span style="color:#B392F0"> SemaphoreSlim</span><span style="color:#B392F0"> semaphoreSlim</span><span style="color:#E1E4E8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">    public</span><span style="color:#B392F0"> AsyncLock</span><span style="color:#E1E4E8">()</span></span>
<span class="line"><span style="color:#F97583">        =></span><span style="color:#79B8FF"> this</span><span style="color:#E1E4E8">.semaphoreSlim </span><span style="color:#F97583">=</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> SemaphoreSlim</span><span style="color:#E1E4E8">(</span><span style="color:#79B8FF">1</span><span style="color:#E1E4E8">, </span><span style="color:#79B8FF">1</span><span style="color:#E1E4E8">);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">    public</span><span style="color:#F97583"> async</span><span style="color:#B392F0"> Task</span><span style="color:#E1E4E8">&#x3C;</span><span style="color:#B392F0">IDisposable</span><span style="color:#E1E4E8">> </span><span style="color:#B392F0">WaitAsync</span><span style="color:#E1E4E8">()</span></span>
<span class="line"><span style="color:#F97583">        =></span><span style="color:#F97583"> await</span><span style="color:#E1E4E8"> LockToken.</span><span style="color:#B392F0">WaitAsync</span><span style="color:#E1E4E8">(</span><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">.semaphoreSlim);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">    public</span><span style="color:#F97583"> void</span><span style="color:#B392F0"> Dispose</span><span style="color:#E1E4E8">()</span></span>
<span class="line"><span style="color:#F97583">        =></span><span style="color:#79B8FF"> this</span><span style="color:#E1E4E8">.semaphoreSlim.</span><span style="color:#B392F0">Dispose</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>AsyncLock is able to do 3 things:</p>
<ol>
<li>Initialize the <code>SemaphoreSlim</code> in the constructor.</li>
<li>Return an <code>IDisposable</code> instance by creating a new <code>LockToken</code> instance.</li>
<li>Propagate the <code>Dispose</code> to it’s <code>SemaphoreSlim</code> instance.</li>
</ol>
<p>Next comes the class that is returned from a call to <code>AsyncLock.WaitAsync()</code>, which I’ve called <code>LockToken</code>:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">sealed</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> LockToken</span><span style="color:#E1E4E8"> : </span><span style="color:#B392F0">IDisposable</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">    private</span><span style="color:#F97583"> readonly</span><span style="color:#B392F0"> SemaphoreSlim</span><span style="color:#B392F0"> semaphoreSlim</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">    private</span><span style="color:#F97583"> bool</span><span style="color:#B392F0"> isDisposed</span><span style="color:#F97583"> =</span><span style="color:#79B8FF"> false</span><span style="color:#E1E4E8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">    private</span><span style="color:#B392F0"> LockToken</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">SemaphoreSlim</span><span style="color:#B392F0"> semaphoreSlim</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#F97583">      =></span><span style="color:#79B8FF"> this</span><span style="color:#E1E4E8">.semaphoreSlim </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> semaphoreSlim;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">    public</span><span style="color:#F97583"> static</span><span style="color:#F97583"> async</span><span style="color:#B392F0"> Task</span><span style="color:#E1E4E8">&#x3C;</span><span style="color:#B392F0">LockToken</span><span style="color:#E1E4E8">> </span><span style="color:#B392F0">WaitAsync</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">SemaphoreSlim</span><span style="color:#B392F0"> semaphoreSlim</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">    {</span></span>
<span class="line"><span style="color:#F97583">        await</span><span style="color:#E1E4E8"> semaphoreSlim.</span><span style="color:#B392F0">WaitAsync</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#F97583">        return</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> LockToken</span><span style="color:#E1E4E8">(semaphoreSlim);</span></span>
<span class="line"><span style="color:#E1E4E8">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">    public</span><span style="color:#F97583"> void</span><span style="color:#B392F0"> Dispose</span><span style="color:#E1E4E8">()</span></span>
<span class="line"><span style="color:#E1E4E8">    {</span></span>
<span class="line"><span style="color:#F97583">        if</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">!</span><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">.isDisposed)</span></span>
<span class="line"><span style="color:#E1E4E8">        {</span></span>
<span class="line"><span style="color:#79B8FF">            this</span><span style="color:#E1E4E8">.semaphoreSlim.</span><span style="color:#B392F0">Release</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#79B8FF">            this</span><span style="color:#E1E4E8">.isDisposed </span><span style="color:#F97583">=</span><span style="color:#79B8FF"> true</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#E1E4E8">        }</span></span>
<span class="line"><span style="color:#E1E4E8">    }</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>This class is basically a fancy wrapper for calling <code>this.semaphoreSlim.Release()</code> that is called with <code>using</code>.</p>
<p><em>Note:</em>
<em>The <code>LockToken</code> class guards against calling <code>this.semaphoreSlim.Release()</code> multiple times, by keeping track if it was already disposed.</em></p>
<p>Now we can rewrite our wrapper like that:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">public</span><span style="color:#F97583"> async</span><span style="color:#B392F0"> Task</span><span style="color:#E1E4E8">&#x3C;</span><span style="color:#B392F0">Result</span><span style="color:#E1E4E8">> </span><span style="color:#B392F0">GetFoo</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">CancellationToken</span><span style="color:#B392F0"> ct</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> _</span><span style="color:#F97583"> =</span><span style="color:#F97583"> await</span><span style="color:#79B8FF"> this</span><span style="color:#E1E4E8">.asyncLock.</span><span style="color:#B392F0">WaitAsync</span><span style="color:#E1E4E8">())</span></span>
<span class="line"><span style="color:#F97583">      return</span><span style="color:#79B8FF"> this</span><span style="color:#E1E4E8">.contestedResource.</span><span style="color:#B392F0">GetFoo</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">public</span><span style="color:#F97583"> async</span><span style="color:#B392F0"> Task</span><span style="color:#E1E4E8">&#x3C;</span><span style="color:#B392F0">Result</span><span style="color:#E1E4E8">> </span><span style="color:#B392F0">GetBar</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">CancellationToken</span><span style="color:#B392F0"> ct</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> _</span><span style="color:#F97583"> =</span><span style="color:#F97583"> await</span><span style="color:#79B8FF"> this</span><span style="color:#E1E4E8">.asyncLock.</span><span style="color:#B392F0">WaitAsync</span><span style="color:#E1E4E8">())</span></span>
<span class="line"><span style="color:#F97583">      return</span><span style="color:#79B8FF"> this</span><span style="color:#E1E4E8">.contestedResource.</span><span style="color:#B392F0">GetBar</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">public</span><span style="color:#F97583"> async</span><span style="color:#B392F0"> Task</span><span style="color:#E1E4E8">&#x3C;</span><span style="color:#B392F0">Result</span><span style="color:#E1E4E8">> </span><span style="color:#B392F0">GetBaz</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">CancellationToken</span><span style="color:#B392F0"> ct</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> _</span><span style="color:#F97583"> =</span><span style="color:#F97583"> await</span><span style="color:#79B8FF"> this</span><span style="color:#E1E4E8">.asyncLock.</span><span style="color:#B392F0">WaitAsync</span><span style="color:#E1E4E8">())</span></span>
<span class="line"><span style="color:#F97583">      return</span><span style="color:#79B8FF"> this</span><span style="color:#E1E4E8">.contestedResource.</span><span style="color:#B392F0">GetBaz</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>And in addition we get this nice utility class that we can use for async locking.</p>
<h4 id="4-i-need-to-implement-the-dispose-pattern">4. I need to implement the dispose pattern</h4>
<p>First of all, what is the dispose pattern?
Basically, it’s a pattern of how to implement the <code>IDispose</code> interface.</p>
<p>But instead of just implementing the single method of this interface, namely <code>void Dispose()</code>, it also consists of an additional overload, usually <code>protected virtual void Dispose(bool disposing)</code> and a finalizer implementation, which in C# is Done via the <code>~Classname()</code>.</p>
<p>Now, in the past, this pattern was the recommended directly by Microsoft, but they changed that recently and now the recommendation is, that you wrap unmanaged resources in an <code>SafeHandle</code> instance and don’t implement the finalizer at all.</p>
<p>They still recommend to keep the <code>protected virtual Dispose(bool disposing)</code> overload so that derived classes can also get rid of their resources.</p>
<p>Okay, so we got rid of the Finalizer and if we don’t have unmanaged resources to track we need zero <code>SafeHandle</code>s!</p>
<p>What about the <code>protected virtual Dispose(bool disposing)</code> overload? Luckily there is a very simple solution to that: stick <code>sealed</code> on the class to deny any inheritance and you’re done!</p>
<p>So in a situation, were you have only Managed Resources that implement <code>IDisposable</code> themselves your implementation can be done in two steps:</p>
<ol>
<li>Implement <code>IDisposable</code> and dispose managed resources in your <code>Dispose()</code> method.</li>
<li>Make the class sealed.</li>
</ol>
<p>The lengthy and slightly confusing documentation for implementing <code>IDispose</code> can be found <a href="https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose">here</a> and if you made it through this document, be sure to check out the discussions in the associated issues, like <a href="https://github.com/dotnet/docs/issues/8463">this one</a>.</p>
<h3 id="summary">Summary</h3>
<p>The <code>using</code> statement in C# prevents an instance escaping it’s <code>Dispose()</code> call by protecting against exceptions and reassignment (either directly or by forwarding by <code>ref</code>).</p>
<p>Objections against <code>using/IDisposable</code> are common but most are easily solved:</p>
<p>Indentation and deeply nested code blocks can be solved via refactoring, Database Connection can be freely disposed, because <a href="https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/connection-pooling">Connection Pooling</a> speeds up their recreation and the recommended <a href="https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose">dispose pattern</a> has changed and can be shortcutted in most cases.</p>
<p>Additionally, <code>using/IDisposable</code> gives access to a nice abstraction over <code>try/finally</code> that we can use ourselves whenever we see that pattern repeating.</p>
<p>So please keep on using <code>using</code>!</p>
<h3 id="references">References</h3>
<ul>
<li>
<p><a href="https://www.ecma-international.org/publications/files/ECMA-ST/ECMA-334.pdf">C# Language Specification, page 265 (https://www.ecma-international.org/publications/files/ECMA-ST/ECMA-334.pdf)</a></p>
</li>
<li>
<p><a href="https://docs.microsoft.com/en-us/dotnet/api/system.objectdisposedexception?view=netframework-4.8">ObjectDisposedException (https://docs.microsoft.com/en-us/dotnet/api/system.objectdisposedexception?view=netframework-4.8)</a></p>
</li>
<li>
<p><a href="https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/connection-pooling">Connection Pooling (https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/connection-pooling)</a></p>
</li>
<li>
<p><a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.semaphoreslim?view=netframework-4.8">SemaphoreSlim (https://docs.microsoft.com/en-us/dotnet/api/system.threading.semaphoreslim?view=netframework-4.8)</a></p>
</li>
<li>
<p><a href="https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose">Implementing Dispose (https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose)</a></p>
</li>
<li>
<p><a href="https://github.com/dotnet/docs/issues/8463">Github Issue about “Implementing Dispose” (https://github.com/dotnet/docs/issues/8463)</a></p>
</li>
</ul>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Timeboxing to achieve Workplace Happiness]]></title>
            <link>https://lostindetails.com/articles/Using-Timeboxing-to-achieve-Workplace-Happiness</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/Using-Timeboxing-to-achieve-Workplace-Happiness</guid>
            <pubDate>Sun, 21 Oct 2018 00:00:00 GMT</pubDate>
            <description><![CDATA[Timeboxing is a time management strategy that can be used to improve autonomy, which is a key factor in achieving workplace happiness.]]></description>
            <content:encoded><![CDATA[<h2 id="using-timeboxing-to-achieve-workplace-happiness">Using Timeboxing to achieve Workplace Happiness</h2>
<h3 id="tldr">TLDR</h3>
<p>Take a look at the <a href="#summary">summary</a>.</p>
<h3 id="workplace-happiness-through-autonomy">Workplace Happiness through Autonomy</h3>
<p>Being able to choose what, when and how to do things at work - working autonomously - is one of <a href="https://en.wikipedia.org/wiki/Happiness_at_work">the most important aspects in experiencing happiness at work</a>.</p>
<p>To achieve that kind of independence one must be willing to shoulder additional responsibilities, like choosing worthwile goals, making plans, defining and completing those tasks, measuring progress, managing time spent and re-evaluating those goals.</p>
<p>No matter if you are an employee or self-employed - failure to meet those requirements will results in stress, anxiety and could finally end in you losing that autonomy.</p>
<h3 id="common-problems">Common Problems</h3>
<p>So what could possibly go wrong? The most common problems that might arise and endanger autonomy are:</p>
<ul>
<li>Procrastination</li>
<li>Anxiety</li>
<li>Distractions</li>
<li>Getting lost in details</li>
</ul>
<p>Not everyone suffers from all of those problems, but I consider them to be intrinsic dangers that can come and go and so it makes sense to be aware of them and the effects that they have.</p>
<h4 id="procrastination">Procrastination</h4>
<p>Procrastination is one of the most common problems and it means avoiding a task that needs to be accomplished. The reasons for avoidance are plentiful and may differ not only from person to person but from task to task.</p>
<p>For me personally it is often a task that requires a skill that I am not good with (accounting!) or a task that needs a big context switch that I am unwilling to do (accounting again!) or something I find just plain distasteful (okay, you guessed it, I am really not too fond of accounting).</p>
<p>The risk of procrastination is that high value tasks get postponed or not done at all. In my case that would be not reaching out to a potential customer, but instead implementing yet another feature that noone really asked for or scrambling to file my taxes at the last possible time.</p>
<h4 id="anxiety">Anxiety</h4>
<p>Anxiety is often connected to subconsciously knowing or thinking that something is wrong - for example it could be triggered by a task that you know is important, but are still procrastinating on.</p>
<p>It can also be triggered by exhaustion - working long periods of time without taking any breaks or without any measure of progress can also lead to anxiety.</p>
<p>While being a possible effect of procrastination, Anxiety can also be a cause of further procrastination. If a task is dreaded then it is more likely to be put off for a more opportune moment when our batteries are fully charged and we are in the right mood - a moment that might as well never come.</p>
<p>In addition to that being anxious just doesn’t feel good.</p>
<h4 id="distractions">Distractions</h4>
<p>When people think about distractions most of the time they think about social media and pings that they get from facebook, whatsapp or twitter (or diaspora, signal and mastodon, depending on your crowd). But they don’t really count - those are beginner level distractions! Why? Because they are so easy to ignore or turn off. The reason is that the source of the distraction is external and the distraction does not feel urgent and so we don’t have to take immediate action.</p>
<p>But what about work e-Mails from a customer or your colleage that has a question or two? Those are grade A distractions! You cannot just ignore them - it’s kind of your job to answer them even if they force a complete context switch.</p>
<p>The result is that those distractions keep us from making progress - especially in those parts of our work that requires deep thought and concentration.</p>
<h4 id="getting-lost-in-details">Getting Lost in Details</h4>
<p>While distractions keep us from focusing on deep work, there is also the opposite danger: getting lost in the details and not seeing the forest for the trees.</p>
<p>This can happen if no planning is done at all, but in my experience it happens more often when a previously defined goal changes or new facts appear and an existing plan is not adjusted accordingly. An example would be trying to find a way to solve a technical problem in a way that’s not applicable to the situation at hand - something that works in theory but just not in this particular case.</p>
<p>The outcome is often that a wrong path is followed for too long without recognizing it’s actually a dead end. What really should have happened would have been a re-evaluation of the existing plan.</p>
<h3 id="what-is-timeboxing">What is Timeboxing?</h3>
<p>Timeboxing in a nutshell is a time management technique that pre-allocates time periods for specific tasks.</p>
<p>At the beginning of the timebox, work on the task is started and work on the tasks stops not only when the task itself is completed, but also when the duration of the timebox elapses - whichever comes first.</p>
<p>So timeboxing at it’s core is a very simple time management strategy, it but still provides a couple of advantages over not having any time management strategy at all.</p>
<p>So the core rules are something like that:</p>
<ul>
<li>When a timebox begins, work on a task is started.</li>
<li>Work on a task is stopped when either the task is completed or the duration of the timebox elapses.</li>
</ul>
<p>Also one can add additional rules to (hopefully) improve it further.</p>
<p>For example I’ve found the following rules useful:</p>
<ul>
<li>Timeboxes are always the same length, they are the unit of measurement for all work durations. E.g. a Timebox is 25 Minutes. This task took 2 Timeboxes.</li>
<li>After a timebox, there is (usually) a break for a couple of minutes. Sometimes when I am feeling in the zone and know what needs to be done, I skip a break and start the next timebox right after the first.</li>
<li>No distractions are allowed in a Work Timebox. If the distraction can be averted in a couple of seconds and flow is not lost, it’s not counted as a distraction. If you give in to the distraction, the current work timebox is cancelled and must be started from the beginning.</li>
</ul>
<p>For an example of a timeboxing technique you can take a look at the <a href="https://en.wikipedia.org/wiki/Pomodoro_Technique">pomodoro technique</a>, on which most of those rules are loosely based.</p>
<p>No self-directed, autonomous being likes to follow arbitrary rules - especially from a random guy on the internet. That’s why in the following sections I will show how they can help with the aforementioned problems.</p>
<h3 id="tackling-procrastination">Tackling Procrastination</h3>
<p>Speaking from personal experience, tackling procrastination is all about starting the dreaded task. It could be something that you haven’t done before and you’ve got no idea how to even start it. Or it’s something you have done in the past and remember it being a real slog.</p>
<p>And that’s where the basic timeboxing rules come in handy because they don’t expect you to solve this unclear, exhausting or impossible seeming task. They only want you to try for a fixed amount of time. That’s quite doable! After that you are free to go, you get a break and you can then try again for another no-strings-attached timebox.</p>
<p>By demanding effort, not results timeboxing frees you to try and give it your best shot. And once you are in the middle of it, you realize that it’s not that bad as you have imagined, so you often keep at it once you have your momentum going.</p>
<h3 id="alleviating-anxiety">Alleviating Anxiety</h3>
<p>Alleviating anxiety depends on the source of the anxiety, there is no single thing that works in every case, so the question is: what is causing the anxiety?</p>
<p>One source of anxiety could procrastination, so tackling procrastination can instantly relieve some anxiety that has been built up by tasks that were previously put off.</p>
<h4 id="taking-breaks">Taking Breaks</h4>
<p>Another cause for anxiety are long working hours without breaks. That’s where timeboxing’s rule to stop working after the timebox elapsed is put to good use. When I worked non-stop (except for lunch break) I was often feeling stressed out and anxious at the end of the day. Being continuously reminded to take breaks - even just for a couple of minutes to take a quick walk, take some deep breaths and get some water greatly reduced my stress levels and got rid of my feelings of anxiety.</p>
<h4 id="tracking-efforts-not-results">Tracking Efforts, not Results</h4>
<p>In addition to taking breaks, timeboxing’s focus on efforts rather than results helps with anxiety that is connected with feelings of inadequacy like imposter syndrome. So for example instead of being stressed out because you couldn’t finish this single task that you set out to do for the day, you are reminded that you were able to complete 6 timeboxes all the way staying focused.</p>
<p>This subtly changes the thing you worry about from an external factor that you have no control over (the task at hand) to something that you can actually control (your time commitment and effort).</p>
<p>This is btw one of the oldest tricks of stoicism - logic dictates that if you want to be consistently happy than you need to derive pleasure from things that are in your control and not external factors.</p>
<h4 id="reducing-distractions">Reducing Distractions</h4>
<p>Distractions are a common stressor that result in anxiety. So reducing them will in turn reduce that part of anxiety that is being fed by stressful distractions.</p>
<h3 id="handling-distractions">Handling Distractions</h3>
<p>After you’ve gotten rid of all notifications by switching your mobile to do-not-disturb and closing all social media apps you are only left with the most difficult kinds of distractions: e-Mails and Co-Workers.</p>
<p>Timeboxing offers two great tools that work together to combat the most negative effects of distractions by suspending and batching them.</p>
<h4 id="suspending-distractions">Suspending Distractions</h4>
<p>The first part is suspending distractions by allocating the timebox and then defending the work that is done inside the timebox against intrusions.</p>
<p>Defending the work in the timebox can be as simple as only checking your e-Mails when the allotted timebox for e-Mail based work starts. Or you could check your e-Mails in every break. If something important comes up, then you can dedicate the next timebox to answer that e-Mail or solve that problem.</p>
<p>As the timeboxes are as long as you see reasonable, for example 25 minutes, the longest an e-Mail has to wait is 24 minutes and 59 seconds. IMHO every e-Mail can wait that long to be answered. If not, then I would argue it shouldn’t have been an e-Mail in the first place. If you insist that in your case it’s totally different, that’s fine too - in that case I would suggest you use the power of modern e-Mail Clients and create a ruleset that only notifies you in very specific cases.</p>
<p>With co-workers and colleagues that can question you at any moments notice, it’s a little more difficult. The best way that I’ve found to handle those situations is to clearly communicate that you are in the middle of something and that you will get back to them in X Minutes. Once again, there may be situations where that is not an option, for example if something is actually on fire and you need to run for the exit. In all of those case feel free to stop what you are doing and give in to the distraction.</p>
<h4 id="getting-back-to-the-distractions">Getting back to the distractions</h4>
<p>After you’ve suspended most distractions the next important thing is actually getting back to them when you can (and try not to procrastinate about it!).</p>
<p>By waiting for the allocated timebox (or the next break) before tackling the problem you benefit from two things:</p>
<p>The first is that people often solve their “urgent” problem themselves or at least add vital information to the problem at hand that was missing in their first inquiry. If you had dropped everything at once, you would have gotten stressed out and lost your progress thanks to the disruption.</p>
<p>The second advantage is that you are able to solve problems in a batch. What if a colleague asks you for info and you wait for your break to answer him and a second colleague needed something as well 5 minutes later? Now instead of being interrupted twice you are able to respond to them in one go.</p>
<h3 id="getting-lost-and-finding-your-way">Getting Lost and Finding your Way</h3>
<p>When it comes to removing your blinders and figuring out an alternative, superior approach to the one your currently following, nothing is as effective as taking a break. Taking a break puts your mind into diffuse mode and allows you to connect the dots that your deep work previously created.</p>
<p>Let me point out that that’s just another very good reason to incorporate breaks in your routine, even if you up to this point felt like “yeah, yeah, sure - for those who need them”.</p>
<p>So it’s often when we take a break that we will recombine the new information we previously gathered in the focused work with the old. That’s when we notice that we need to re-evaluate our approach to solving a problem or that we missed a more elegant way to achieve our goal.</p>
<h3 id="summary">Summary</h3>
<p>Happiness at work is greatly influenced by autonomy, which makes attaining and keeping autonomy highly desirable. Autonomy itself requires a minimum amount of self-management to maintain and if unaddressed leads to a couple of common problems:</p>
<ul>
<li>Procrastination</li>
<li>Anxiety</li>
<li>Distractions</li>
<li>Getting lost in details</li>
</ul>
<p>Timeboxing is a time-management strategy that can solve or soften most of those problems with just a couple of simple rules:</p>
<ul>
<li>Timeboxes have a fixed duration of e.g. 25 minutes</li>
<li>Working on a task is only done inside a timebox</li>
<li>When a timebox stops, work on the task stops as well</li>
<li>No distractions are allowed inside a timebox</li>
<li>A break follows a completed timebox</li>
</ul>
<h3 id="references">References</h3>
<ul>
<li><a href="https://en.wikipedia.org/wiki/Happiness_at_work">Wikipedia Happiness at work (https://en.wikipedia.org/wiki/Happiness_at_work)</a></li>
<li><a href="https://en.wikipedia.org/wiki/Procrastination">Wikipedia Procrastination (https://en.wikipedia.org/wiki/Procrastination)</a></li>
<li><a href="https://en.wikipedia.org/wiki/Pomodoro_Technique">Wikipedia Pomodoro Technique (https://en.wikipedia.org/wiki/Pomodoro_Technique)</a></li>
</ul>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create Svg Badges with CSharp]]></title>
            <link>https://lostindetails.com/articles/Create-Svg-Badges-with-CSharp</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/Create-Svg-Badges-with-CSharp</guid>
            <pubDate>Fri, 24 Aug 2018 00:00:00 GMT</pubDate>
            <description><![CDATA[I've written a small commandline tool that uses SkiaSharp to generate svg files in C#.]]></description>
            <content:encoded><![CDATA[<h2 id="creating-svg-badges-with-c">Creating Svg Badges with C#</h2>
<h3 id="tldr">TLDR;</h3>
<p>I wrote a small C# dotnetcore commandline tool for windows to generate svg badges like:</p>
<p><img src="/img/result-success.svg" alt="result-success.svg">
<img src="/img/result-error.svg" alt="result-success.svg"></p>
<p>That you can install over chocolatey:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="batch"><code><span class="line"><span style="color:#E1E4E8">choco install badger</span></span>
<span class="line"><span style="color:#E1E4E8">badger.exe -o result-success.svg -l </span><span style="color:#9ECBFF">"Testresults"</span><span style="color:#E1E4E8"> -r </span><span style="color:#9ECBFF">"100/100"</span><span style="color:#E1E4E8"> --lc #444444ff --rc #00ff00ff</span></span></code></pre>
<h3 id="background">Background</h3>
<p>I wanted my CI build results to contain nice svg badges like the ones above and I didn’t want to use some internet service, because the build itself shouldn’t depend on internet access and external services.</p>
<p>An option would be to design the svg using a vector design tool like inkscape and export an svg and then use a script to replace the corresponding colors and text.</p>
<p>But that has it’s own drawbacks - it’s very difficult to modify later on and positioning the items before you know the text is tricky - you might need to make your script smart enough to adjust the size of items as well.</p>
<p>Why not go all the way then and write a small commandline application that can create svgs from scratch? So that’s what I did.</p>
<h3 id="creating-svgs-with-skiasharp">Creating Svgs with SkiaSharp</h3>
<p>For generating the svg files, I chose the excellent <a href="https://github.com/mono/SkiaSharp">SkiaSharp</a> library (about which I’ve written already <a href="http://lostindetails.com/blog/post/SkiaSharp-with-Wpf">here</a>), which has a built-in Svg Backend. Thanks to SkiaSharp, creating a small commandline app that can create an Svg File consists basically of parsing the input and calling the right drawing methods.</p>
<p>I’ve called the tool <a href="https://github.com/8/badger">badger and uploaded it to github</a>.</p>
<p>If you are interested in the code, check out <a href="https://github.com/8/badger/blob/master/Badger/Service/SvgService.cs">SvgService.cs</a> which handles the Svg-File export and calls <a href="https://github.com/8/badger/blob/master/Badger/Service/BadgeService.cs">BadgeService.cs</a> in turn, which handles the actual drawing.</p>
<p>You can download the source code from github and build it yourself:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="batch"><code><span class="line"><span style="color:#E1E4E8">git clone https://github.com/8/badger</span></span>
<span class="line"><span style="color:#F97583">cd</span><span style="color:#E1E4E8"> badger</span></span>
<span class="line"><span style="color:#E1E4E8">build</span></span></code></pre>
<h3 id="installation-with-chocolatey">Installation with Chocolatey</h3>
<p>Now the only thing that’s missing is a nice way to install it.
I wasn’t in the mood of writing an WiX or an nsis installer, because their overkill for a simple commandline app that you can basically xcopy deploy.</p>
<p>On the other hand that doesn’t solve the question of where to upload the installer and how to find the link when you later on need it.</p>
<p>For installing applications and upgrading them on my windows machines, I am a fan of chocolatey, which is package manager for windows, that’s based on nuget. Chocolatey puts the installed executable automatically on your PATH, which is really useful for all commandline tools.</p>
<p>For Windows, I’ve created a package of the compiled executable and pushed it to chocolatey. You can install it using:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="batch"><code><span class="line"><span style="color:#E1E4E8">choco install badger</span></span></code></pre>
<p>It’s based on the .NET 4.7 Framework, so you need to make sure that it’s installed.</p>
<h3 id="using-the-tool">Using the tool</h3>
<p>After you’ve build the tool or installed it with chocolatey you can invoke it like that:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="batch"><code><span class="line"><span style="color:#E1E4E8">badger.exe -o result-success.svg -l </span><span style="color:#9ECBFF">"Testresults"</span><span style="color:#E1E4E8"> -r </span><span style="color:#9ECBFF">"100/100"</span><span style="color:#E1E4E8"> --lc #444444ff --rc #00ff00ff</span></span></code></pre>
<p>Which will create the following svg file:
<img src="/img/result-success.svg" alt="result-success.svg"></p>
<h3 id="resources">Resources</h3>
<ul>
<li><a href="https://github.com/8/badger">badger (https://github.com/8/badger)</a></li>
<li><a href="https://github.com/mono/SkiaSharp">SkiaSharp (https://github.com/mono/SkiaSharp)</a></li>
<li><a href="https://chocolatey.org">chocolatey (https://chocolatey.org)</a></li>
</ul>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Cheatsheet]]></title>
            <link>https://lostindetails.com/articles/Docker-Cheatsheet</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/Docker-Cheatsheet</guid>
            <pubDate>Wed, 15 Aug 2018 00:00:00 GMT</pubDate>
            <description><![CDATA[I've created a docker cli cheatsheet in different colors that you can download as a pdf.]]></description>
            <content:encoded><![CDATA[<h2 id="docker-cheatsheet">Docker Cheatsheet</h2>
<h3 id="tldr">TLDR;</h3>
<p>I’ve created a docker cli cheatsheet in different colors. If you want to download the pdf scroll to the bottom.</p>
<h3 id="background--goals">Background &#x26; Goals</h3>
<p>I’ve been working with docker extensively for the last few months and while I find the technology really useful, I’ve noticed that newcomers are often overwhelmed by the slew of commands and options available and I am only talking about running some containers - not to mention orchestrating them or building images.</p>
<p>As more and more people have been asking me what they can do with docker and what’s the command for that, I’ve thought about writing up the commands that I found most useful.</p>
<h3 id="the-solution">The solution</h3>
<p>This week, I finally had enough time and created a 1-page docker cli cheatsheet that you can download as a pdf and print.</p>
<p>If you happen to spot a mistake or I am missing your favourite docker command/option, please feel free to message me or comment, maybe I can squeeze it in.</p>
<p>Because I am not a designer, I’ve generated the docker cheatsheet in a couple of different color themes in hope that you might find a color that you’ll like.
<cheatsheetlist :items="items">
</cheatsheetlist></p>
<script lang="ts">
import { Component, Prop, Vue } from "vue-property-decorator";
import CheatSheetList, {
  CheatSheet
} from "../../components/CheatSheetList.vue";

@Component({
  components: { CheatSheetList }
})
export default class DockerCheatSheet extends Vue {
  items = this.getCheatSheets();
  getCheatSheets() {
    const names = [
      "docker_blue_dark",
      "docker_blue_light",
      "docker_blue_light0",
      "docker_blue_light1",
      "docker_blue1_dark",
      "docker_blue1_light",
      "docker_blue1_light0",
      "docker_blue1_light1",
      "docker_blue2_dark",
      "docker_blue2_light",
      "docker_blue2_light0",
      "docker_blue2_light1",
      "docker_darkblue_dark",
      "docker_darkblue_light",
      "docker_darkblue_light0",
      "docker_darkblue_light1",
      "docker_darkgray_dark",
      "docker_darkgray_light",
      "docker_darkgray_light0",
      "docker_darkgray_light1",
      "docker_green_dark",
      "docker_green_light",
      "docker_green_light0",
      "docker_green_light1",
      "docker_iceblue_dark",
      "docker_iceblue_light",
      "docker_iceblue_light0",
      "docker_iceblue_light1",
      "docker_indigo_dark",
      "docker_indigo_light",
      "docker_indigo_light0",
      "docker_indigo_light1",
      "docker_lightgray_dark",
      "docker_lightgray_light",
      "docker_lightgray_light0",
      "docker_lightgray_light1",
      "docker_red_dark",
      "docker_red_light",
      "docker_red_light0",
      "docker_red_light1"
    ];
    return names.map(n => {
      return {
        image: `/cheatsheet/docker/${n}.png`,
        pdf: `/cheatsheet/docker/${n}.pdf`
      } as CheatSheet;
    });
  }
}</script>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A look at OAuth 2.0]]></title>
            <link>https://lostindetails.com/articles/A-look-at-OAuth-2.0</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/A-look-at-OAuth-2.0</guid>
            <pubDate>Tue, 31 Oct 2017 00:00:00 GMT</pubDate>
            <description><![CDATA[I've read through the OAuth 2.0 rfc and summarised my findings in this article.]]></description>
            <content:encoded><![CDATA[<h2 id="a-quick-look-at-oauth2">A Quick Look at OAuth2</h2>
<h3 id="tldr">TLDR;</h3>
<p>If you need to access OAuth 2.0 protected resources, than go ahead and use the official SDK from your OAuth 2.0 provider, if available.</p>
<p>If you want to implement the server-side you might want to reconsider, as OAuth2 is both complicated and doesn’t do what you need on it’s own.</p>
<h3 id="background--goals">Background &#x26; Goals</h3>
<p>Recently I’ve taken a look at OAuth2, to find out if it’s a good fit for projects I am working on. To be specific, I was wondering if I should implement it as my means of Authentication.</p>
<p>I was looking for a framework that:</p>
<ol>
<li>should be simple to understand / straightforward to implement</li>
<li>should allow my app to receive basic information about the user</li>
<li>should allow my server to deliver content based on the users identity</li>
</ol>
<p>In this article I present why I don’t think that OAuth 2.0 meets those requirements. Should your requirements look like mine, then I suggest you rethink if you really want to use OAuth 2.0.</p>
<p><em>Disclaimer:
Every use case is different - so if you find that it still makes sense to deploy OAuth 2.0 in your system then don’t feel discouraged to do so!</em></p>
<p><em>Note:
If you are only interested in accessing OAuth 2.0 protected content from another service provider - that is if you are only implementing the client, then you have no choice anyway and can go ahead!</em></p>
<p>First let’s take a look and what OAuth 2.0 is and who is using it.</p>
<p>So let’s get started!</p>
<h3 id="what-is-oauth-20">What is OAuth 2.0?</h3>
<p>The short version:<br>
OAuth 2.0 is a delegated authorization framework for the enterprise.</p>
<p>For the long version, you can read all about OAuth 2.0 in it’s <a href="https://tools.ietf.org/html/rfc6749">70+ pages rfc 6749</a>.<br>
It also has a dedicated homepage at <a href="https://oauth.net/2">https://oauth.net/2</a> and a <a href="https://en.wikipedia.org/wiki/OAuth">wikipedia page</a>.</p>
<p>When talking about resources to read about OAuth 2.0, I think it’s worth mentioning that the lead author <a href="https://hueniverse.com/@eranhammer">Eran Hammer</a> was unhappy about the path that it has taken and <a href="https://hueniverse.com/oauth-2-0-and-the-road-to-hell-8eec45921529">resigned</a> and had his name removed from the project. You can read up on his reasons for doing so on his <a href="https://hueniverse.com/oauth-2-0-and-the-road-to-hell-8eec45921529">blog</a>.</p>
<p>Also we will find out that there are 2 additional RFCs that you may need to get familiar with,</p>
<h3 id="who-is-using-it">Who is using it?</h3>
<p>If you are going to use a technology, it doesn’t hurt to take a look at who is also using it. In this case, it’s the big players:</p>
<ul>
<li>Amazon</li>
<li>Facebook</li>
<li>Google</li>
<li>Microsoft</li>
<li>Twitter</li>
</ul>
<p>If you want to take a look yourself, <a href="https://en.m.wikipedia.org/wiki/List_of_OAuth_providers">here is a wikipedia page</a> that lists a number of known OAuth service providers. But not all of them implement 2.0 - many are still using 1.0 and 1.0a.</p>
<p>On one hand this looks rather promising, as a lot of big companies have embraced OAuth 2.0. On the other hand quite a few decided to not upgrade from an older implementation like 1.0 to the newer 2.0 version, even though Version 2.0 was published in October 2012.</p>
<h3 id="how-does-it-work">How does it work?</h3>
<p>At it’s heart, OAuth 2.0 specifies a flow that defines:</p>
<ul>
<li>which party is calling which party</li>
<li>in what order those calls are made</li>
<li>and what is the data that is being exchanged</li>
</ul>
<p>To understand it, you need to learn it’s terminology and learn about the specific flows it supports. The flows take advantange of the terminology, so you need to understand the terminology first - that’s why I’ll start with those.</p>
<h4 id="oauth-20-terminology">OAuth 2.0 Terminology</h4>
<p>To make sense of it, you’ll need to learn it’s terminology.</p>
<h5 id="involved-parties">Involved Parties</h5>
<p>First you need to know about the involved parties:</p>
<p>Client
: A client application, e.g. your web-, mobile- or desktop-app.</p>
<p>Resource Owner
: The user of your app who also happens to have access to some content on an OAuth 2.0 protected server.</p>
<p>Resource Server
: An OAuth 2.0 protected server that serves some content if you hand it a valid <code>Access Token</code>.</p>
<p>Authorization Server
: A server that the <code>Resource Server</code> trusts. It hosts a login page, that the user logs into. After the user logs in successfully and confirms the request, it will issue an <code>Authorization Grant</code>. It will also exchange an <code>Authorization Grant</code> for an <code>Access Token</code> for the client.</p>
<h5 id="exchanged-objects">Exchanged Objects</h5>
<p>Then you need to know about the objects being being exchanged between those parties:</p>
<p>Resource
: A <code>Resource</code> is some user content protected by OAuth 2.0 and provided by a <code>Resource Server</code>.</p>
<p>Authorization Request
: The <code>Authorization Request</code> is what happens when your App requests access to a <code>Resource</code> of the User.</p>
<p>Authorization Grant
: The <code>Authorizaton Grant</code> is returned as a response on a Client’s successful <code>Authorization Request</code>. It can be exchanged for an <code>Access Token</code>.</p>
<p>Access Token
: A token that is used to retrieve content from a <code>Resource Server</code> instead of user credentials. It is issued by the <code>Authorization Server</code>.</p>
<p>Refresh Token
: An optional token that can be returned by the <code>Authorization Server</code> in addition to the <code>Access Token</code>. It can be used to retrieve additional <code>Access Token</code> if for example the original <code>Access Token</code> expires.</p>
<h5 id="authorization-grant-types">Authorization Grant Types</h5>
<p>Then there are different Authorization Grant Types and the choice of the Grant Type influences how the <code>Access Token</code> can be obtained.
There are four base Authorization Grant Types specified in OAuth 2.0:</p>
<ol>
<li>Authorization Code</li>
<li>Implicit</li>
<li>Resource Owner Password Credentials</li>
<li>Client Credentials</li>
</ol>
<p>The specifics are not terribly important at the moment - you may want to skim them, as I will call out the differences between them later on. The first one, <code>Authorizaton Code</code>, is the most important one as we will see.</p>
<h6 id="authorization-code">Authorization Code</h6>
<p>This is the classic OAuth flow.</p>
<ol>
<li>The <code>Client</code> redirects the <code>Resource Owner</code> to the <code>Authentication Server</code>.</li>
<li>The <code>Client</code> logs in, confirms the requested access rights.</li>
<li>The <code>Authentication Server</code> redirects back to the <code>Client</code>.</li>
<li>The <code>Client</code> exchanges the <code>Authorization Code</code> to the <code>Access Token</code> by calling the <code>Authentication Server</code>.</li>
</ol>
<p><em>Note: This is the preferred Authorization Grant Type.</em></p>
<h6 id="implicit">Implicit</h6>
<ol>
<li>The <code>Client</code> redirects the <code>Resource Owner</code> to the <code>Authentication Server</code>.</li>
<li>The <code>Client</code> logs in, confirms the requested access rights.</li>
<li>The <code>Authentication Server</code> responds directly with the <code>Access Token</code>.</li>
</ol>
<h6 id="resource-owner-password-credentials">Resource Owner Password Credentials</h6>
<ol>
<li>The <code>Client</code> asks the user for username and password.</li>
<li>The <code>Client</code> sends the username and password to the <code>Authentication Server</code>.</li>
<li>The <code>Authorization Server</code> responds with the <code>Access Token</code>.</li>
</ol>
<h6 id="client-credentials">Client Credentials</h6>
<ol>
<li>The <code>Client</code> sends his own username and password to the <code>Authentication Server</code>.</li>
<li>The <code>Authorization Server</code> responds with the <code>Access Token</code>.</li>
</ol>
<h4 id="oauth-20-flow">OAuth 2.0 Flow</h4>
<p>An OAuth flow lists the number and order of steps that are executed between the involved parties. The specific steps depend on the authorization grant type being used.</p>
<p>Let’s start with a simple case, as shown in the abstract protocol flow that is also sketched out in the RFC. It can be visualized in a sequence diagram like this:</p>
<p><img src="/img/protocol-flow.svg" alt="OAuth2 Protocol Flow"></p>
<p>This flow would be used if the Authorization Grant Type <code>Resource Owner Password Credentials</code> is used - that’s why the <code>Client</code> would ask the <code>Resource Owner</code> directly.</p>
<p>This flow, although simple, is not the recommended approach.
In this flow the <code>Authorization Request</code> is sent directly to the <code>Resource Owner</code>, but in the recommended approach the <code>Client</code> should send it to the <code>Authorization Server</code> as an intermediary for enhanced security of the user credentials.</p>
<p>The preferred flow uses the Authorization Grant Type <code>Authorization Code</code> and looks like that:</p>
<p><img src="/img/protocol-flow-preferred.svg" alt="OAuth2 Preferred Protocol Flow"></p>
<p>But wait, that’s not all - the previous sequence diagramm was still missing the flow for using <code>Refresh Token</code>s. So here we go with <code>Refresh Token</code>s added to the mix:</p>
<p><img src="/img/refresh-token-flow.svg" alt="OAuth 2 Refresh Token Flow"></p>
<p>Now we know a little about how the flow looks like, let’s take a closer look at one of the objects that is central to the flow, namely the <code>Access Token</code>.</p>
<h4 id="what-are-access-tokens-made-of">What are Access Tokens made of?</h4>
<p>If you expect that the spec defines how the Access Token should look like, you will be disappointed, because the <code>Access Token</code> is defined only very vaguely as a string.</p>
<p>The RFC does not get any more specific than that - quite the opposite, it states that Access Tokens can have different formats and that those are outside the scope of this RFC but it links to another RFC for further reading.</p>
<h5 id="bearer-tokens">Bearer Tokens</h5>
<p>To get to know more about them you need to read the <a href="https://tools.ietf.org/html/rfc6750">RFC6750 (The OAuth 2.0 Authorization Framework: Bearer Token Usage)</a> which specifies how the Tokens should be used to access the <code>Resource Server</code>.</p>
<p>Even though RFC6750 specifies how Bearer Tokens are to be used, it does not tell us how a reasonable Access Token should be implemented.</p>
<h5 id="jwt---json--web-token">JWT - JSON  Web Token</h5>
<p>This is were JSON Web Tokens come in!</p>
<p>In yet another <a href="https://tools.ietf.org/html/rfc7519">RFC7519</a> we learn about an implementation of an <code>Access Token</code> that can be used in OAuth 2.0, called JWT (JSON  Web Token).</p>
<p>JWTs are a topic on their own and discussing them in detail is out of scope of this article.</p>
<p>Their main characteristics are:</p>
<ul>
<li>they hold certain predefined parameters</li>
<li>they are extensible with custom parameters</li>
<li>they can be signed and/or encrypted</li>
<li>they can be serialized to a string</li>
</ul>
<p>Those properties make them a perfect fit for Access Tokens. In addition to that, those properties allow them to be self-contained. That means they can contain all necessary information for the <code>Resource Server</code> to verify if the Resource Request of the <code>Client</code> is valid and should be served - the <code>Resource Server</code> doesn’t need to call the <code>Authentication Server</code> or look up additional information.</p>
<p>Now we know enough about what OAuth 2.0 is and how it can be implemented.</p>
<h4 id="is-oauth-20-simple-to-understand">Is OAuth 2.0 simple to understand?</h4>
<p>To come back to the first question I posed at the beginning: Is it simple to understand and simple to implement?</p>
<p>Well, when I started reading up on OAuth 2.0 I didn’t find a nice succinct writeup on the internet for how it works and what it does.</p>
<p>Now after having read through a few resources, I feel like I know why - because it’s complicated.</p>
<p>Basically, you would have to read, understand and implement at least those three RFCs.</p>
<p>So I would answer that question with: No, I don’t think so.</p>
<p>But that’s not all, IMHO it’s also missing some basic features…</p>
<h3 id="oauth-20-is-missing-authentication">OAuth 2.0 is missing Authentication</h3>
<p>When you start reading about OAuth 2.0 you soon will find out that the “Auth” part of it’s name stands for Authorization (and not Authentication) as made clear by both the homepage’s first sentence:</p>
<blockquote>
<p>“OAuth 2.0 is the industry-standard protocol for authorization.”</p>
</blockquote>
<p>I don’t know if I agree with the first part of the sentence, but the “for authorization” part is spot on.</p>
<p>And the rfc’s header:</p>
<blockquote>
<p>“The OAuth 2.0 Authorization Framework”</p>
</blockquote>
<h4 id="authorization-vs-authentication">Authorization vs. Authentication</h4>
<p>But why the hair splitting, what’s the difference between Authentication and Authorization?</p>
<p>According to <a href="https://stackoverflow.com/questions/6556522/authentication-versus-authorization#6556548">Stackoverflow</a>:</p>
<blockquote>
<p><strong>Authentication</strong> is the process of ascertaining that somebody really is who he claims to be.<br>
<strong>Authorization</strong> refers to rules that determine who is allowed to do what. E.g. Adam may be authorized to create and delete databases, while Usama is only authorised to read.</p>
</blockquote>
<p>or:</p>
<blockquote>
<p><strong>Authentication</strong> = login + password (who you are)
<strong>Authorization</strong> = permissions (what you are allowed to do)</p>
</blockquote>
<p>OAuth 2.0 doesn’t solve the problem of Authentication, only the problem of Authorization.</p>
<p>That’s too bad, because getting some base info about a user is almost always a requirement for an application. At least you want to show the user as signed in and you want to have some basic info that you can display, like a username, so that the user knows under which account he is signed in.</p>
<p>When I started looking at OAuth 2.0, I was under the assumption that it would provide a solution for this very common problem.</p>
<p>But with a vanilla OAuth 2.0 implementation you are out of luck if you expect that it provides a standard way of handling user profile information.</p>
<p>Because those misconceptions are a widely held belief, there is a <a href="https://oauth.net/articles/authentication/">nice article</a> on the official site that explains common pitfalls.</p>
<blockquote>
<p>In OAuth, the token is designed to be opaque to the client, but in the context of a user authentication, the client needs to be able to derive some information from the token.</p>
</blockquote>
<p>This torpedoes my goal that I want my app to receive basic information about the user.</p>
<p>On the other hand, the server that is serving the protected content has the same problem as the provided Access Token is not inherently linked to a specific user. Therefore the Resource Server has no idea which user has originated the request.</p>
<p>Or to quote the <a href="https://oauth.net/articles/authentication/">article</a> once more:</p>
<blockquote>
<p>The protected resource is not generally going to be in a position to tell if the user is still present by the token alone, since by the very nature and design of the OAuth protocol the user will not be available on the connection between the client and protected resource.</p>
</blockquote>
<p>Which means that my last goal - that the server should be able to provide info based on the users identity - also doesn’t work out of the box.</p>
<h4 id="solving-the-user-information-problem">Solving the User Information Problem</h4>
<p>We can of course solve the problem and add the support for the missing features. One option that comes to mind is:</p>
<ul>
<li>Add a User Info Token</li>
<li>Host a User Info Endpoint</li>
</ul>
<h5 id="adding-a-user-info-token">Adding a User Info Token</h5>
<p>One workaround to provide that information, would be extending the Access Token Response.</p>
<p>If you take a look at the example of a complete Access Token Response as specified in th RFC:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>HTTP/1.1 200 OK</span></span>
<span class="line"><span>Content-Type: application/json;charset=UTF-8</span></span>
<span class="line"><span>Cache-Control: no-store</span></span>
<span class="line"><span>Pragma: no-cache</span></span>
<span class="line"><span></span></span>
<span class="line"><span>{</span></span>
<span class="line"><span>  "access_token":"2YotnFZFEjr1zCsicMWpAA",</span></span>
<span class="line"><span>  "token_type":"example",</span></span>
<span class="line"><span>  "expires_in":3600,</span></span>
<span class="line"><span>  "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",</span></span>
<span class="line"><span>  "example_parameter":"example_value"</span></span>
<span class="line"><span>}</span></span></code></pre>
<p>You can see that additional parameters, like <code>example_parameter</code> can be part of the response. This is specifically supported by the spec by requiring that clients must ignore unrecognized response parameters.</p>
<p>So we are free to add an additional parameter. For example we could add a parameter and set it’s value to another serialized JWT that holds the users profile information. Let’s call this additional token User Profile Token.</p>
<p>The response could then look like this:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>HTTP/1.1 200 OK</span></span>
<span class="line"><span>Content-Type: application/json;charset=UTF-8</span></span>
<span class="line"><span>Cache-Control: no-store</span></span>
<span class="line"><span>Pragma: no-cache</span></span>
<span class="line"><span></span></span>
<span class="line"><span>{</span></span>
<span class="line"><span>  "access_token":"2YotnFZFEjr1zCsicMWpAA",</span></span>
<span class="line"><span>  "token_type":"example",</span></span>
<span class="line"><span>  "expires_in":3600,</span></span>
<span class="line"><span>  "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",</span></span>
<span class="line"><span>  "user_profile_token":"..."</span></span>
<span class="line"><span>}</span></span></code></pre>
<p>Now a Client Application is handed profile information of the user in addition to an <code>Access Token</code> and can mirror that information back to the user of the app.</p>
<h5 id="host-a-user-info-endpoint">Host a User Info Endpoint</h5>
<p>Additionally we could implement a <code>Resource Server</code> that answers a request containing a valid <code>Access Token</code> with our new User Profile Token.</p>
<p>That way, should the User Info returned when retrieving an Access Token have gone stale and is not up to date anymore, a new info can be retrieved.</p>
<h4 id="open-id-connect">Open ID Connect</h4>
<p>But if that’s such a common use case, wouldn’t it be great if the approach of using a second token and additionally supplying a <code>Resource Server</code> that works as a User Info Endpoint would also be part of a standard?!</p>
<p>That’s why a similiar approach is already standardized in <a href="http://openid.net/specs/openid-connect-core-1_0.html">yet another spec called Open ID Connect</a>. Therefore Open ID Connect is basically an authentication layer on top of OAuth 2.0.</p>
<p>So before going down the custom route, it may make more sense to implement Open ID Connect instead - but either way, it’s not part of OAuth 2.0.</p>
<p>In the end having no support for Authentication out of the box is a solvable, although annoying problem.</p>
<h3 id="use-cases">Use Cases</h3>
<p>Now we know what OAuth 2.0 can’t do, what about actual use cases? Let’s go through some usage scenarios based on different application types.</p>
<p>Previously, I’ve talked about the different Authorization Grant Types and looked at abstract flows. Now I want to map them to typical application types that I often implement:</p>
<ol>
<li>Web App</li>
<li>Mobile App</li>
<li>Desktop App</li>
<li>Console App</li>
<li>Privileged Service</li>
</ol>
<h4 id="web-app">Web App</h4>
<p>Consider building a Web App that wants to access a Resource on an Http Server that is protected via OAuth 2.0.</p>
<p>That’s the flow for which OAuth 2.0 was made!</p>
<p><img src="/img/authorization-code-flow.svg" alt="Authorization Code Flow"></p>
<p>In this diagram I’ve modelled the authorization code flow including the browser, because there are two important things going on:</p>
<ol>
<li>
<p>The Web App initiates the loading of the <code>Authentication Server</code>’s login page and cannot get a hold of the credentials of the user. It only receives the <code>Authorization Code</code>.<br>
That’s especially nice in case of third party apps as you wouldn’t trust them with your users login and password.</p>
</li>
<li>
<p>The Web App’s Backend server exchanges the <code>Authorization Code</code> against the <code>Access Token</code>. Therefore the Browser (and also the User) does not get a hold of the <code>Access Token</code>.</p>
</li>
</ol>
<p>That’s also nice, because the token is not exposed in an internet cafe or on an unlocked laptop.</p>
<h4 id="mobile-app">Mobile App</h4>
<p>Consider building a mobile app that wants to access a Resource on a Http Server that is protected via OAuth 2.0.</p>
<p>There are basically two options:</p>
<ol>
<li>Either use a WebView to load the login page of the <code>Authentication Server</code> inside of the app and therefore follow the <code>Implicit Code Flow</code>.</li>
</ol>
<p><img src="/img/implicit-flow.svg" alt="Implicit Flow"></p>
<ol start="2">
<li>Or ask the User directly for his username and password and follow the  <code>Resource Owner Password Credentials</code> flow.</li>
</ol>
<p><img src="/img/resource-owner-password-credentials-flow.svg" alt="Resource Owner Password Credentials Flow"></p>
<p>Both of these approaches are problematic. In the second case, it’s clear that the user credentials are exposed to the app, but even the first case is also dangerous, because:</p>
<ol>
<li>
<p>Instead of using a WebView the app could simply spoof the login page, as the user can’t be sure that he is inside a sandboxed browser.</p>
</li>
<li>
<p>Even if the Application is trustworthy and uses a WebView and really loads your login page, you are training your users to put trust in your login ui even if they cannot validate the origin. Which in turn increases the likelyhood of them falling for phishing attacks later on.</p>
</li>
</ol>
<h4 id="desktop-app">Desktop App</h4>
<p>As far as accessing OAuth 2.0 protected resources, building a desktop app is very similiar to a mobile app.</p>
<p>You can either use the <code>Implicit Flow</code> or the <code>Resource Owner Password Credential Flow</code>.</p>
<p>The main difference is that WebViews are usually more cumbersome to implement, so it’s way easier to go for the <code>Resource Owner Password Credential Flow</code>.</p>
<h4 id="console-app">Console App</h4>
<p>If you are building a console app you will be unable to redirect to the <code>Authentication Server</code>’s login page, therefore you will need ask the user for his or her username and password and follow the <code>Resource Owner Password Credentials</code> flow.</p>
<h4 id="privileged-service">Privileged Service</h4>
<p>When you are developing a privileged service that runs without user interaction you would implement the <code>Client Credentials</code> flow.</p>
<p>For example you could create a <code>Resource Owner</code> for the Service and provide the credentials in a configuration file.</p>
<h4 id="summary">Summary</h4>
<p>In all but the third party Web App scenario OAuth still depends trusting the Application to do the right thing. Either to not spoof the login screen or to handle the user credentials carefully.</p>
<h3 id="implementations">Implementations</h3>
<p>I am not going to go into much detail about specific implementations as there are many different options and they depend on usage scenario and language preferences. Instead I’ll give only some general recommendations for picking a client library based on what I’ve found.</p>
<p>Because there a lot of different flavours of OAuth, you probably can’t reuse the same client library for all providers.</p>
<p>So if you need to integrate with a specific OAuth Provider, probably the best option is to first check if there is an official client library or SDK for your favourite programming language available that already wraps the OAuth calls.</p>
<p>An additional advantage of that approach is that you get all the other capabilities of their API wrapped as well.</p>
<p>For example Facebook provides an official <a href="https://developers.facebook.com/docs/reference/php/">PHP based SDK</a>.</p>
<h4 id="using-unofficial-client-sdks">Using Unofficial Client SDKs</h4>
<p>If there is no SDK available for your favourite programming language, the next best thing is probably an unofficial opensource SDK for a specific OAuth Provider.</p>
<h4 id="using-oauth-client-libraries">Using OAuth Client Libraries</h4>
<p>In case you want to integrate with multiple OAuth Providers, you could also take a look at client libraries that support multiple OAuth Providers. As they are focused on the multiple providers, they usually handle only the OAuth part, so you still have to handle the provider specific resource requests yourself.</p>
<p>An example is the <a href="https://github.com/titarenko/OAuth2">OAuth2 client library for C#</a>. You can see that to support all those different providers a <a href="https://github.com/titarenko/OAuth2/tree/master/OAuth2/Client/Impl">custom implementation</a> is used for each.</p>
<p>As an alternative you can write the OAuth calls yourself, but you are probably saving time by not reinventing the wheel.</p>
<h4 id="server-libraries">Server Libraries</h4>
<p>First of, there is no “default” or “goto” implementation of OAuth 2.0. The reason being that the different companies that are part of the OAuth 2.0 working group wouldn’t agree on one. Everyone wants their language and implementation to be the “correct” one.</p>
<p>If you are looking for general purpose client or server OAuth libraries, a good place to start is the official OAuth 2.0 Website’s <a href="https://oauth.net/code/">list of libraries</a>.</p>
<h3 id="conclusion">Conclusion</h3>
<p>If you are developing a Client Web Application that wants to access Resources that are protected by a third party OAuth 2.0 provider you will have to implement the client side of OAuth, but with a matching SDK that’s rather straightforward.</p>
<p>Things look different on the server-side, as there are a couple of problems with OAuth 2.0 - for me the following are the most pressing:</p>
<ul>
<li>Too complicated for what it does, you need to implement at least three RFCs</li>
<li>Missing basic functionality for common scenarios like Authentication</li>
<li>Limited usefulness outside of specific scenarios like third party Web Apps</li>
<li>Extensibility and vagueness cause differences in implementation</li>
</ul>
<p>All of the above make me wary of implementing OAuth 2.0 server-side and my advise is to stay away unless you have very specific reasons not to.</p>
<p>What might those reasons be?</p>
<ul>
<li>You are working in an enterprise environment</li>
<li>You expect lots of custom built apps</li>
<li>Many of them are WebApp</li>
<li>You plan to implement Open ID Connect</li>
<li>You are willing to spent more time and money than is strictly necessary to solve the problem</li>
</ul>
<p>If that’s not you, than you are probably better off skipping OAuth 2.0.</p>
<h3 id="references">References</h3>
<ul>
<li><a href="https://tools.ietf.org/html/rfc6749">OAuth 2.0. RFC (https://tools.ietf.org/html/rfc6749)</a></li>
<li><a href="https://oauth.net/2">OAuth 2.0 Homepage (https://oauth.net/2)</a></li>
<li><a href="https://en.wikipedia.org/wiki/OAuth">OAuth Wikipedia Page (https://en.wikipedia.org/wiki/OAuth)</a></li>
<li><a href="http://openid.net/connect/">OpenID Connect (http://openid.net/connect/)</a></li>
<li><a href="https://hueniverse.com/oauth-2-0-and-the-road-to-hell-8eec45921529">OAuth 2.0 Lead Author resigns Blogpost(https://hueniverse.com/oauth-2-0-and-the-road-to-hell-8eec45921529)</a></li>
<li><a href="https://oauth.net/articles/authentication">OAuth 2.0 Common Authentication Pitfalls (https://oauth.net/articles/authentication)</a></li>
<li><a href="https://tools.ietf.org/html/rfc6750">OAuth 2.0 Authorization Framework: Bearer Token Usage RFC 6750 (https://tools.ietf.org/html/rfc6750)</a></li>
<li><a href="https://oauth.net/code/">OAuth 2.0 Client and Server Libraries (https://oauth.net/code/)</a></li>
<li>[ (<a href="https://github.com/titarenko/OAuth2">https://github.com/titarenko/OAuth2</a>)]</li>
</ul>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get Contributor stats from git]]></title>
            <link>https://lostindetails.com/articles/Get-Contributor-stats-from-git</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/Get-Contributor-stats-from-git</guid>
            <pubDate>Tue, 15 Aug 2017 00:00:00 GMT</pubDate>
            <description><![CDATA[This article shows how to retrieve stats like commits and lines changed per contributor from git using the commandline.]]></description>
            <content:encoded><![CDATA[<h2 id="get-contributor-stats-from-git">Get Contributor stats from git</h2>
<h3 id="tldr">TLDR;</h3>
<p>Abstract: This article is about getting contributor stats from a git repository.</p>
<p>Solution:</p>
<ol>
<li>To get the number of commits for each user execute <code>git shortlog -sn --all</code></li>
<li>To get the number of lines added and delete by a specific user <a href="http://harelba.github.io/q/install.html">install q</a> and then execute: <code>git log --author=&quot;authorsname&quot; --format=tformat: --numstat | q -t &quot;select sum(c1), sum(c2) from -&quot;</code></li>
</ol>
<p>Conclusion:</p>
<ol>
<li>q is cool, put it in your toolbelt.</li>
<li>Don’t use those stats as a base for calculating salaries.</li>
</ol>
<h3 id="overview">Overview</h3>
<p>Last week I wanted to retrieve simple stats about contributors from a git repository.</p>
<p>I came up with the following two stats:</p>
<ol>
<li>Commits per Contributor</li>
<li>Lines changed per Contributor</li>
</ol>
<h3 id="stats-from-git">Stats from git</h3>
<h4 id="commits-per-contributor">Commits per Contributor</h4>
<p>Getting the number of commits for each contributor is easy with git, just execute:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8;overflow-x:auto" tabindex="0" data-language="plaintext"><code><span class="line"><span>git shortlog -sn --all</span></span></code></pre>
<p>and you will get an output like this:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8;overflow-x:auto" tabindex="0" data-language="plaintext"><code><span class="line"><span>  3  author</span></span></code></pre>
<p>Which will show you the number of commits for each user.</p>
<p>The command is broken up as follows:</p>
<ul>
<li><code>git shortlog</code> summarizes <code>git log</code></li>
<li><code>-s</code> suppresses the description of the commits and shows only the commit count</li>
<li><code>-n</code> sorts the output by most commits descending</li>
<li><code>--all</code> show it for all branches</li>
</ul>
<h4 id="lines-changed-per-contributor">Lines changed per Contributor</h4>
<p>The second thing I was interested in, was the number of lines changed.</p>
<p>Git is able to tell you the number of lines changed per file for each commit. When we now restrict the shown commits only to a specific author, we will be able to get a list of all changes he or she did for all files.</p>
<p>This can be accomplished with the following git command: <code>git log --author=&quot;authorsname&quot; --format=tformat: --numstat</code></p>
<p>The command can be broken down like so:</p>
<ul>
<li><code>git log</code> shows info about commits</li>
<li><code>--author=&quot;name&quot;</code> shows only info about a specific author. You could also use <code>--committer=&quot;name&quot;</code> if your author and committer are always the same.</li>
<li><code>--format=tformat:</code> is a nice one, it uses an empty <code>tformat</code> string to basically get rid of every information, so this outputs an empty string for each commit.</li>
<li><code>--numstat</code> adds the number of lines added and delete for each file of the commit.</li>
</ul>
<p>This leaves us with one remaining problem:
How to sum up all those single lines in case we don’t care about the name of those files? Well, we will need to use another tool to do it, the question is, which one?</p>
<p>I had the following ideas:</p>
<ol>
<li>Write a custom shell script by glueing together different commandline tools</li>
<li>Write a custom commandline tool</li>
<li>Use Excel</li>
</ol>
<p>So I looked at all of them:</p>
<ol>
<li>A shell script would need to use additional tools and would probably be pretty brittle - it would break on different versions of the tools used, depend on a specific shell and have very slim chances of working cross platform. If I am forced to write something, new I’d rather write a small commandline tool then.</li>
<li>Nah, on second thought, I don’t want to do that either, I was looking for something more out of the box for such a generic task.</li>
<li>Are you kidding me, we are at the commandline here?!</li>
</ol>
<p>Then it dawned on me: What I wanted to do was calculate aggregates over columns - and there is already a great way to express that: <strong>SQL</strong>!</p>
<p>The question is, how can I run a sql statement against that output without the overhead of pushing it to relational database first?</p>
<p>This is were the great little command tool <a href="https://github.com/harelba/q">q (https://github.com/harelba/q)</a> comes in!</p>
<p>It can run a sql query against data coming from csv and STDIN.
The command that I used (including the sql query that calculates the sums of all added and deleted files) for q is <code>q -t &quot;select sum(c1), sum(c2) from -&quot;</code>.</p>
<p>The query can broken down as follows:</p>
<ul>
<li><code>-t</code> use tab as the separator between columns</li>
<li><code>sum(c1)</code> the sum of the first column</li>
<li><code>sum(c2)</code> the sum of the second column</li>
<li><code>from -</code> from STDIN</li>
</ul>
<p>Now we only need to pipe the output of the git command into our call of <code>q</code>.</p>
<p>Therefore to get the number of lines changed per contributor you need to:</p>
<ol>
<li>Install <a href="https://github.com/harelba/q">q</a> as explained <a href="http://harelba.github.io/q/install.html">here</a>.</li>
<li>Execute</li>
</ol>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8;overflow-x:auto" tabindex="0" data-language="plaintext"><code><span class="line"><span>git log --author=&quot;authorsname&quot; --format=tformat: --numstat | q -t &quot;select sum(c1), sum(c2) from -&quot;</span></span></code></pre>
<ol start="3">
<li>And you will get an output like this:</li>
</ol>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8;overflow-x:auto" tabindex="0" data-language="plaintext"><code><span class="line"><span>4       1</span></span></code></pre>
<p>which is the number of added and deleted rows.</p>
<h4 id="svn">Svn</h4>
<p>If you are working with svn, you could try the git svn bridge and clone a repo from svn first, like so: <code>git svn clone url_to_your_repository</code></p>
<h3 id="conclusion">Conclusion</h3>
<p>While getting stats like commits per contributor and lines changed is rather easy using git, those stats may not be as useful as you think for measuring developer contribution:</p>
<ol>
<li>
<p>They are not comparable in and off themselves.
Comparing the number of added F# lines with added lines to a XML Config file is maybe not the best idea.</p>
</li>
<li>
<p>They can easily be gamed. For example by adding and removing additional lines, and splitting changes over multiple commits and multiple lines - you will get what you measure.</p>
</li>
<li>
<p>Last but not least: They measure almost always the wrong thing. Nobody cares about lines and commits - imho far more important are code coverage, issues solved, good communication, on boarding new team members and so on.</p>
</li>
</ol>
<p>So take stats like this with a grain of salt, or better a spoon and don’t base any important decisions upon them!</p>
<p>On one hand, maybe those stats aren’t so great after all, on their own, they seem more like vanity metrics instead of actionable data.
But on the other hand, I’ve put a new and flexible tool into my toolbelt today :)</p>
<div> <!-- GitStatsLink Test --> </div>
<h3 id="references">References</h3>
<ul>
<li><a href="https://git-scm.com/docs/git-shortlog">git shortlog (https://git-scm.com/docs/git-shortlog)</a></li>
<li><a href="https://git-scm.com/docs/git-log">git log (https://git-scm.com/docs/git-log)</a></li>
<li><a href="https://github.com/harelba/q">q (https://github.com/harelba/q)</a></li>
<li><a href="http://harelba.github.io/q/install.html">install q (http://harelba.github.io/q/install.html)</a></li>
</ul>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use a XBox Controller to control your Angular2 app]]></title>
            <link>https://lostindetails.com/articles/Use-a-XBox-Controller-to-control-your-Angular2-app</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/Use-a-XBox-Controller-to-control-your-Angular2-app</guid>
            <pubDate>Sun, 07 May 2017 00:00:00 GMT</pubDate>
            <description><![CDATA[By using XInput and calling native Windows APIs you can use an XBox Controller to control any application.]]></description>
            <content:encoded><![CDATA[<h2 id="use-a-xbox-controller-to-control-your-angular2-app">Use a XBox Controller to control your Angular2 App</h2>
<h3 id="tldr">TLDR;</h3>
<ol>
<li>For repeated multiple choice data entry you might want to consider alternative forms of input, like e.g. a gamepad.</li>
<li>Gamepad support is provided by <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ee417014(v=vs.85).aspx">XInput</a> on Windows.</li>
<li><a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms646310(v=vs.85).aspx"><code>SendInput()</code></a> allows sending of Keyboard events to foreground applications</li>
<li>Combine both in a <a href="https://github.com/8/XInput2Key">simple application</a></li>
<li><a href="http://lostindetails.com/blog/post/Hotkeys-in-Angular2">Add Hotkey support</a> to your Angular2 app</li>
<li>Now you are able to control your app with an XBox Controller</li>
</ol>
<h3 id="who-would-want-that">Who would want that?</h3>
<p>A customer had an interesting idea - he asked if there were alternative user input devices available that could be used for data entry for an Angular2 Intranet Application that I was working on.</p>
<p>His reasoning was that the WebApp was used for data entry - and lots of it! After login, the application basically consists of a main loop that would present it’s user with visual and textual information and would ask the user to take a decision based on it. As the possible input is limited and speed for data entry is paramount, hotkeys support was introduced. I’ve wrote my take on hotkey support <a href="http://lostindetails.com/blog/post/Hotkeys-in-Angular2">here</a>. But additionally the customer was worried about the amount of stress that an employee could suffer from repeated usage.</p>
<p>The customer asked for ergonomic input devices that could be used in addition to a keyboard. The idea was to allow the users to freely switch between different devices if he felt uncomfortable using one.</p>
<h3 id="why-the-xbox-controller">Why the XBox Controller?</h3>
<p>An ergonomic input device in widespread use that is also within budget are Gamepads. They are basically made for varying methods of input and allow extended usage with minimum strain.</p>
<p>Additionally I knew that the WebApp was used as an intranet application and the customer was using Windows Machines, which do have native support for XBox Controllers and on which additional software could be installed.</p>
<p>Support for gamepads and joysticks on Windows is provided via <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ee417014(v=vs.85).aspx">XInput or the now deprecated DirectInput API</a> - both of them are a part of DirectX.</p>
<p>The XBox Controller works with XInput and DirectInput and most of the third party Gamepads provide a hardware switch for changing between XInput and DirectInput. This comes in handy if your game or app supports only one API, but not the other.</p>
<h3 id="getting-access-to-the-xbox-controller">Getting access to the XBox Controller</h3>
<p>So the first obstacle was to get access to the XBox Controller, as you cannot get access to DirectX (and specifically XInput) from an Angular Application directly. For this, a native Windows Application was necessary.</p>
<p>I opted for a C# Wpf Application and chose <a href="http://sharpdx.org">SharpDX (http://sharpdx.org)</a>, which is a thin wrapper for the C++ DirectX Api.</p>
<h4 id="polling-the-controller">Polling the Controller</h4>
<p>XInput comes with a poll based API, which is perfect for it’s natural audience, that is games. They usually poll the state of the controllers inside of their main loop and do immediate mode rendering - it all fits together.</p>
<p>Example of polling the Keystroke:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">var</span><span style="color:#B392F0"> controller</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Controller</span><span style="color:#E1E4E8">(UserIndex.One);</span></span>
<span class="line"><span style="color:#B392F0">Keystroke</span><span style="color:#B392F0"> keystroke</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">var</span><span style="color:#B392F0"> result</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> controller.</span><span style="color:#B392F0">GetKeystroke</span><span style="color:#E1E4E8">(DeviceQueryType.Gamepad, </span><span style="color:#F97583">out</span><span style="color:#E1E4E8"> keystroke);</span></span>
<span class="line"><span style="color:#F97583">if</span><span style="color:#E1E4E8"> (result.Success)</span></span>
<span class="line"><span style="color:#F97583">    ..</span><span style="color:#E1E4E8">.</span></span></code></pre>
<p>or the more concise :</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">var</span><span style="color:#B392F0"> controller</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Controller</span><span style="color:#E1E4E8">(UserIndex.One);</span></span>
<span class="line"><span style="color:#F97583">if</span><span style="color:#E1E4E8"> (controller.</span><span style="color:#B392F0">GetKeystroke</span><span style="color:#E1E4E8">(DeviceQueryType.Gamepad, </span><span style="color:#F97583">out</span><span style="color:#B392F0"> Keystroke</span><span style="color:#B392F0"> keystroke</span><span style="color:#E1E4E8">).Success)</span></span>
<span class="line"><span style="color:#F97583">    ..</span><span style="color:#E1E4E8">.</span></span></code></pre>
<h4 id="from-polling-to-pushing">From Polling to Pushing</h4>
<p>In this case however, I am creating a normal Windows Desktop Application using retained mode drawing and I would prefer a push based interface for the gamepad events. That’s why I’ve chosen to wrap the poll based API inside of my application with push based events.</p>
<p>For exposing the push events to the rest of the application, you can use c# events or plain callbacks using delegates, but I’ve chosen <a href="http://reactivex.io/">Reactive Extensions</a> as I greatly prefer the interface.</p>
<p>So my interface looks like this:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">public</span><span style="color:#F97583"> interface</span><span style="color:#B392F0"> IXInputService</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">    bool</span><span style="color:#B392F0"> IsListening</span><span style="color:#E1E4E8"> { </span><span style="color:#F97583">get</span><span style="color:#E1E4E8">; </span><span style="color:#F97583">set</span><span style="color:#E1E4E8">; }</span></span>
<span class="line"><span style="color:#B392F0">    IObservable</span><span style="color:#E1E4E8">&#x3C;</span><span style="color:#B392F0">Keystroke</span><span style="color:#E1E4E8">> </span><span style="color:#B392F0">Keystrokes</span><span style="color:#E1E4E8"> { </span><span style="color:#F97583">get</span><span style="color:#E1E4E8">; }</span></span>
<span class="line"><span style="color:#B392F0">    IObservable</span><span style="color:#E1E4E8">&#x3C;</span><span style="color:#B392F0">ControllerConnected</span><span style="color:#E1E4E8">> </span><span style="color:#B392F0">Connected</span><span style="color:#E1E4E8"> { </span><span style="color:#F97583">get</span><span style="color:#E1E4E8">; }</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>For implementing the continuous polling there are also a couple of options, for example a timer, a delayed task, a thread pool thread or the Application Idle event.</p>
<p>I’ve chosen to spin up a dedicated Thread, as the thread is both long running and the timing between each Poll request is fixed.</p>
<p>To test it out, I created a small Wpf prototype app (XInput2Key), that is able to read out the state of the gamepad’s buttons and shows if they are currently pressed.</p>
<p><img src="/img/XInput2Key.png" alt="XInput2Key"></p>
<h3 id="interfacing-with-angular2">Interfacing with Angular2</h3>
<p>Now I was able to read out the gamepad input and the only thing that remains is to interface with the angular2 application. As I mentioned previously, the application already had hotkey support, so the obvious choice was to just send keyboard input to the angular application.</p>
<p>This has the additional advantage that the applications are very loosely coupled and you can use one without the other. This allows using the XInput application to work with any other application as well, as long as the target app has somekind of hotkey support.</p>
<p>As I already took a dependency on the host operating system being windows (for the DirectX support), I took a quick look at the native Windows Api and chose the <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms646310(v=vs.85).aspx"><code>SendInput()</code></a> function. This function allows sending of keystrokes and mouse events to the foreground application, which in my case would be a browser with the loaded angular2 application.</p>
<p>To access the native C WinApi Method, I needed <code>[DllImport]</code> declarations for <code>SendInput()</code> which I luckily found on <a href="http://www.pinvoke.net/default.aspx/user32.SendInput">PInvoke.net</a>.</p>
<p>Thanks to both SharpDX and PInvoke.Net I was quickly able to throw together a prototype application that:</p>
<ol>
<li>reads in a config file for mapping the gamepad buttons -> keyboard keys</li>
<li>listens for gamepad button presses using XInput</li>
<li>maps them to keystrokes</li>
<li>sends the keystrokes to the foreground application using <code>SendInput()</code></li>
</ol>
<h3 id="sample-app">Sample App</h3>
<p>I’ve pushed the resulting app to github (<a href="https://github.com/8/XInput2Key">https://github.com/8/XInput2Key</a>) incase you want to try it yourself.</p>
<p>If you check the Checkbox ‘Is Emulating Keys’, then the mapped keyboard input is sent to the foreground window. If you open up an instance of your favourite text editor, you can try it out.</p>
<p><img src="/img/XInput2Key.gif" alt="XInput2Key"></p>
<p>The only caveat is that due to security constraints of <code>SendInput()</code> it cannot send input to applications running with administrator rights, if the app isn’t started with administrator rights itself.</p>
<h3 id="setting-up-angular2-to-deal-with-hotkeys">Setting up Angular2 to deal with Hotkeys</h3>
<p>For hotkey support in angular I am basically using the javascript library <a href="https://craig.is/killing/mice">mousetrap</a> with an angular2 wrapper. If you’re interested in how I’ve done that, you can check out my blog post about using <a href="http://lostindetails.com/blog/post/Hotkeys-in-Angular2">Hotkeys in Angular2</a>.</p>
<h3 id="references">References</h3>
<ul>
<li><a href="http://sharpdx.org">SharpDX (http://sharpdx.org)</a></li>
<li><a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ee417014(v=vs.85).aspx">XInput and DirectInput</a></li>
<li><a href="http://pinvoke.net">PInvoke.net (http://pinvoke.net)</a></li>
<li><a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms646310(v=vs.85).aspx">SendInput() function (https://msdn.microsoft.com/en-us/library/windows/desktop/ms646310(v=vs.85).aspx)</a></li>
<li><a href="https://craig.is/killing/mice">Mousetrap Javascript Library (https://craig.is/killing/mice)</a></li>
<li><a href="https://github.com/8/XInput2Key">XInput2Key Sample App (https://github.com/8/XInput2Key)</a></li>
<li><a href="http://lostindetails.com/blog/post/Hotkeys-in-Angular2">Blog Post: Hotkeys in Angular2 (http://lostindetails.com/blog/post/Hotkeys-in-Angular2)</a></li>
</ul>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hotkeys in Angular2]]></title>
            <link>https://lostindetails.com/articles/Hotkeys-in-Angular2</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/Hotkeys-in-Angular2</guid>
            <pubDate>Sat, 29 Apr 2017 00:00:00 GMT</pubDate>
            <description><![CDATA[Thanks to the mousetrap javascript library you can easily create a reusable HotkeysService including configuration.]]></description>
            <content:encoded><![CDATA[<h2 id="hotkeys-in-angular2">Hotkeys in Angular2</h2>
<h3 id="background">Background</h3>
<p>For the app that I was building for a customer, I needed hotkey support for Angular2. For a plain old javascript web app, I’ve used the excellent javascript library <a href="https://craig.is/killing/mice">mousetrap (https://craig.is/killing/mice)</a> to great success and I wanted to use it in angular2 app as well.</p>
<h3 id="mousetrap-for-angular--angular2-hotkeys">Mousetrap for angular => angular2-hotkeys</h3>
<p>As it turns out, somebody already created an nice angular2 wrapper for mousetrap called <a href="https://github.com/brtnshrdr/angular2-hotkeys">angular2-hotkeys (https://github.com/brtnshrdr/angular2-hotkeys)</a> that wraps mousetrap and allows you to import a <code>HotkeysService</code> and register keys for it.</p>
<p>To install it, simply follow the instructions in the <a href="https://github.com/brtnshrdr/angular2-hotkeys/blob/master/README.MD">README</a>.</p>
<p>Now a component can just request the <code>HotkeysService</code> in it’s constructor and register a hotkey for itself by invoking the <code>HotkeysService.add()</code> method.</p>
<p>Additionally, the component should also remove the hotkey once it gets destroyed. To do this, we store the returned value of the <code>HotkeysService.add()</code> method and supply it as an argument to the <code>HotkeysService.remove()</code> method when the component is destroyed.</p>
<p>In Angular, this can be done by implementing <code>OnDestroy</code> and it’s <code>ngOnDestroy</code> method. When the component gets destroyed, angular invokes the method and and the previously registered hotkey is removed.</p>
<p>A complete example could look like this:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="typescript"><code><span class="line"><span style="color:#F97583">import</span><span style="color:#E1E4E8"> { Component, OnDestroy } </span><span style="color:#F97583">from</span><span style="color:#9ECBFF"> '@angular/core'</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">import</span><span style="color:#E1E4E8"> { HotkeysService, Hotkey } </span><span style="color:#F97583">from</span><span style="color:#9ECBFF"> 'angular2-hotkeys'</span><span style="color:#E1E4E8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#E1E4E8">@</span><span style="color:#B392F0">Component</span><span style="color:#E1E4E8">({</span></span>
<span class="line"><span style="color:#E1E4E8">  selector: </span><span style="color:#9ECBFF">'app-root'</span><span style="color:#E1E4E8">,</span></span>
<span class="line"><span style="color:#E1E4E8">  templateUrl: </span><span style="color:#9ECBFF">'./app.component.html'</span><span style="color:#E1E4E8">,</span></span>
<span class="line"><span style="color:#E1E4E8">  styleUrls: [</span><span style="color:#9ECBFF">'./app.component.css'</span><span style="color:#E1E4E8">]</span></span>
<span class="line"><span style="color:#E1E4E8">})</span></span>
<span class="line"><span style="color:#F97583">export</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> AppComponent</span><span style="color:#F97583"> implements</span><span style="color:#B392F0"> OnDestroy</span><span style="color:#E1E4E8"> {</span></span>
<span class="line"><span style="color:#FFAB70">  title</span><span style="color:#F97583"> =</span><span style="color:#9ECBFF"> 'app works!'</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#FFAB70">  hotkeyCtrlLeft</span><span style="color:#F97583">:</span><span style="color:#B392F0"> Hotkey</span><span style="color:#F97583"> |</span><span style="color:#B392F0"> Hotkey</span><span style="color:#E1E4E8">[];</span></span>
<span class="line"><span style="color:#FFAB70">  hotkeyCtrlRight</span><span style="color:#F97583">:</span><span style="color:#B392F0"> Hotkey</span><span style="color:#F97583"> |</span><span style="color:#B392F0"> Hotkey</span><span style="color:#E1E4E8">[];</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">  constructor</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">private</span><span style="color:#FFAB70"> hotkeysService</span><span style="color:#F97583">:</span><span style="color:#B392F0"> HotkeysService</span><span style="color:#E1E4E8">) {</span></span>
<span class="line"><span style="color:#79B8FF">    this</span><span style="color:#E1E4E8">.hotkeyCtrlLeft </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> hotkeysService.</span><span style="color:#B392F0">add</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">new</span><span style="color:#B392F0"> Hotkey</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">'ctrl+left'</span><span style="color:#E1E4E8">, </span><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">.ctrlLeftPressed));</span></span>
<span class="line"><span style="color:#79B8FF">    this</span><span style="color:#E1E4E8">.hotkeyCtrlRight </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> hotkeysService.</span><span style="color:#B392F0">add</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">new</span><span style="color:#B392F0"> Hotkey</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">'ctrl+right'</span><span style="color:#E1E4E8">, </span><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">.ctrlRightPressed));</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#B392F0">  ctrlLeftPressed</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> (</span><span style="color:#FFAB70">event</span><span style="color:#F97583">:</span><span style="color:#B392F0"> KeyboardEvent</span><span style="color:#E1E4E8">, </span><span style="color:#FFAB70">combo</span><span style="color:#F97583">:</span><span style="color:#79B8FF"> string</span><span style="color:#E1E4E8">)</span><span style="color:#F97583">:</span><span style="color:#79B8FF"> boolean</span><span style="color:#F97583"> =></span><span style="color:#E1E4E8"> {</span></span>
<span class="line"><span style="color:#79B8FF">    this</span><span style="color:#E1E4E8">.title </span><span style="color:#F97583">=</span><span style="color:#9ECBFF"> 'ctrl+left pressed'</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">    return</span><span style="color:#79B8FF"> true</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#B392F0">  ctrlRightPressed</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> (</span><span style="color:#FFAB70">event</span><span style="color:#F97583">:</span><span style="color:#B392F0"> KeyboardEvent</span><span style="color:#E1E4E8">, </span><span style="color:#FFAB70">combo</span><span style="color:#F97583">:</span><span style="color:#79B8FF"> string</span><span style="color:#E1E4E8">)</span><span style="color:#F97583">:</span><span style="color:#79B8FF"> boolean</span><span style="color:#F97583"> =></span><span style="color:#E1E4E8"> {</span></span>
<span class="line"><span style="color:#79B8FF">    this</span><span style="color:#E1E4E8">.title </span><span style="color:#F97583">=</span><span style="color:#9ECBFF"> 'ctrl+right pressed'</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">    return</span><span style="color:#79B8FF"> true</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#B392F0">  ngOnDestroy</span><span style="color:#E1E4E8">() {</span></span>
<span class="line"><span style="color:#79B8FF">    this</span><span style="color:#E1E4E8">.hotkeysService.</span><span style="color:#B392F0">remove</span><span style="color:#E1E4E8">(</span><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">.hotkeyCtrlLeft);</span></span>
<span class="line"><span style="color:#79B8FF">    this</span><span style="color:#E1E4E8">.hotkeysService.</span><span style="color:#B392F0">remove</span><span style="color:#E1E4E8">(</span><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">.hotkeyCtrlRight);</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<h3 id="beyond-hello-world">Beyond “Hello World!”</h3>
<p>Now this works fine for a simple app, but there are a couple of problems:</p>
<ul>
<li>If one component registers a hotkey and a second component also registered the same hotkey, the previous subscription would be overriden.</li>
<li>Additionally the subscription / unsubscription logic leakes into each and every component that wants to register a hotkey.</li>
<li>The Hotkey events are not the flexible <code>Observable&#x3C;T></code> as we have come to expect in angular.</li>
<li>Keys are hardcoded inside of each component and therefore difficult to change</li>
</ul>
<h3 id="wrapping-hotkeys-in-a-commandservice">Wrapping Hotkeys in a CommandService</h3>
<p>To solve that problem, I’ve introduced a <code>CommandService</code>. It’s basically an EventAggregator, that upon initialization reads in a config.json that specifies which keys should be mapped to which commands. It exposes an Observable and registers all the hotkeys specified in the <code>config.json</code>.</p>
<p>Everytime one of those keys are pressed, it triggers the corresponding commands. Instead of importing the <code>HotkeysService</code> itself, all components import the <code>CommandService</code> and subscribe to it’s observable. If the user presses a registered hotkey, a Command is triggered and the components check if they are interested in the comand and if so, take action.</p>
<p>Besides allowing easy updating of the hotkeys by editing the <code>config.json</code>, this moves the hotkey registration code to one place, which makes switching the hotkeys library a breeze (in case that should be necessary in the future). This approach also captures the essence of what the hotkeys are doing - they are issuing a command to components. It also allows reusing the <code>CommandService</code> to explicitedly raise those commands from other components.</p>
<p>An implementation of the <code>CommandService</code> looks like that:</p>
<h4 id="commandservicets">CommandService.ts</h4>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="typescript"><code><span class="line"><span style="color:#F97583">import</span><span style="color:#E1E4E8"> { Injectable } </span><span style="color:#F97583">from</span><span style="color:#9ECBFF"> '@angular/core'</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">import</span><span style="color:#E1E4E8"> { Http } </span><span style="color:#F97583">from</span><span style="color:#9ECBFF"> '@angular/http'</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">import</span><span style="color:#E1E4E8"> { HotkeysService, Hotkey } </span><span style="color:#F97583">from</span><span style="color:#9ECBFF"> 'angular2-hotkeys'</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">import</span><span style="color:#E1E4E8"> { Subject } </span><span style="color:#F97583">from</span><span style="color:#9ECBFF"> 'rxjs/Subject'</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">import</span><span style="color:#E1E4E8"> { Observable } </span><span style="color:#F97583">from</span><span style="color:#9ECBFF"> 'rxjs/Observable'</span><span style="color:#E1E4E8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">class</span><span style="color:#B392F0"> HotkeyConfig</span><span style="color:#E1E4E8"> {</span></span>
<span class="line"><span style="color:#E1E4E8">  [</span><span style="color:#FFAB70">key</span><span style="color:#F97583">:</span><span style="color:#79B8FF"> string</span><span style="color:#E1E4E8">]</span><span style="color:#F97583">:</span><span style="color:#79B8FF"> string</span><span style="color:#E1E4E8">[];</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">class</span><span style="color:#B392F0"> ConfigModel</span><span style="color:#E1E4E8"> {</span></span>
<span class="line"><span style="color:#FFAB70">  hotkeys</span><span style="color:#F97583">:</span><span style="color:#B392F0"> HotkeyConfig</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">export</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> Command</span><span style="color:#E1E4E8"> {</span></span>
<span class="line"><span style="color:#FFAB70">  name</span><span style="color:#F97583">:</span><span style="color:#79B8FF"> string</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#FFAB70">  combo</span><span style="color:#F97583">:</span><span style="color:#79B8FF"> string</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#FFAB70">  ev</span><span style="color:#F97583">:</span><span style="color:#B392F0"> KeyboardEvent</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#E1E4E8">@</span><span style="color:#B392F0">Injectable</span><span style="color:#E1E4E8">()</span></span>
<span class="line"><span style="color:#F97583">export</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> CommandService</span><span style="color:#E1E4E8"> {</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">  private</span><span style="color:#FFAB70"> subject</span><span style="color:#F97583">:</span><span style="color:#B392F0"> Subject</span><span style="color:#E1E4E8">&#x3C;</span><span style="color:#B392F0">Command</span><span style="color:#E1E4E8">>;</span></span>
<span class="line"><span style="color:#FFAB70">  commands</span><span style="color:#F97583">:</span><span style="color:#B392F0"> Observable</span><span style="color:#E1E4E8">&#x3C;</span><span style="color:#B392F0">Command</span><span style="color:#E1E4E8">>;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">  constructor</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">private</span><span style="color:#FFAB70"> hotkeysService</span><span style="color:#F97583">:</span><span style="color:#B392F0"> HotkeysService</span><span style="color:#E1E4E8">,</span></span>
<span class="line"><span style="color:#F97583">              private</span><span style="color:#FFAB70"> http</span><span style="color:#F97583">:</span><span style="color:#B392F0"> Http</span><span style="color:#E1E4E8">) {</span></span>
<span class="line"><span style="color:#79B8FF">    this</span><span style="color:#E1E4E8">.subject </span><span style="color:#F97583">=</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Subject</span><span style="color:#E1E4E8">&#x3C;</span><span style="color:#B392F0">Command</span><span style="color:#E1E4E8">>();</span></span>
<span class="line"><span style="color:#79B8FF">    this</span><span style="color:#E1E4E8">.commands </span><span style="color:#F97583">=</span><span style="color:#79B8FF"> this</span><span style="color:#E1E4E8">.subject.</span><span style="color:#B392F0">asObservable</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#79B8FF">    this</span><span style="color:#E1E4E8">.http.</span><span style="color:#B392F0">get</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">'assets/config.json'</span><span style="color:#E1E4E8">).</span><span style="color:#B392F0">toPromise</span><span style="color:#E1E4E8">()</span></span>
<span class="line"><span style="color:#E1E4E8">      .</span><span style="color:#B392F0">then</span><span style="color:#E1E4E8">(</span><span style="color:#FFAB70">r</span><span style="color:#F97583"> =></span><span style="color:#E1E4E8"> r.</span><span style="color:#B392F0">json</span><span style="color:#E1E4E8">() </span><span style="color:#F97583">as</span><span style="color:#B392F0"> ConfigModel</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">      .</span><span style="color:#B392F0">then</span><span style="color:#E1E4E8">(</span><span style="color:#FFAB70">c</span><span style="color:#F97583"> =></span><span style="color:#E1E4E8"> {</span></span>
<span class="line"><span style="color:#F97583">        for</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">const</span><span style="color:#79B8FF"> key</span><span style="color:#F97583"> in</span><span style="color:#E1E4E8"> c.hotkeys) {</span></span>
<span class="line"><span style="color:#F97583">          const</span><span style="color:#79B8FF"> commands</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> c.hotkeys[key];</span></span>
<span class="line"><span style="color:#E1E4E8">          hotkeysService.</span><span style="color:#B392F0">add</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">new</span><span style="color:#B392F0"> Hotkey</span><span style="color:#E1E4E8">(key, (</span><span style="color:#FFAB70">ev</span><span style="color:#E1E4E8">, </span><span style="color:#FFAB70">combo</span><span style="color:#E1E4E8">) </span><span style="color:#F97583">=></span><span style="color:#79B8FF"> this</span><span style="color:#E1E4E8">.</span><span style="color:#B392F0">hotkey</span><span style="color:#E1E4E8">(ev, combo, commands)));</span></span>
<span class="line"><span style="color:#E1E4E8">        }</span></span>
<span class="line"><span style="color:#E1E4E8">      });</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#B392F0">  hotkey</span><span style="color:#E1E4E8">(</span><span style="color:#FFAB70">ev</span><span style="color:#F97583">:</span><span style="color:#B392F0"> KeyboardEvent</span><span style="color:#E1E4E8">, </span><span style="color:#FFAB70">combo</span><span style="color:#F97583">:</span><span style="color:#79B8FF"> string</span><span style="color:#E1E4E8">, </span><span style="color:#FFAB70">commands</span><span style="color:#F97583">:</span><span style="color:#79B8FF"> string</span><span style="color:#E1E4E8">[])</span><span style="color:#F97583">:</span><span style="color:#79B8FF"> boolean</span><span style="color:#E1E4E8"> {</span></span>
<span class="line"><span style="color:#E1E4E8">    commands.</span><span style="color:#B392F0">forEach</span><span style="color:#E1E4E8">(</span><span style="color:#FFAB70">c</span><span style="color:#F97583"> =></span><span style="color:#E1E4E8"> {</span></span>
<span class="line"><span style="color:#F97583">      const</span><span style="color:#79B8FF"> command</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> {</span></span>
<span class="line"><span style="color:#E1E4E8">        name: c,</span></span>
<span class="line"><span style="color:#E1E4E8">        ev: ev,</span></span>
<span class="line"><span style="color:#E1E4E8">        combo: combo</span></span>
<span class="line"><span style="color:#E1E4E8">      } </span><span style="color:#F97583">as</span><span style="color:#B392F0"> Command</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#79B8FF">      this</span><span style="color:#E1E4E8">.subject.</span><span style="color:#B392F0">next</span><span style="color:#E1E4E8">(command);</span></span>
<span class="line"><span style="color:#E1E4E8">    });</span></span>
<span class="line"><span style="color:#F97583">    return</span><span style="color:#79B8FF"> true</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<h4 id="an-configjson-example">An config.json example:</h4>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="json"><code><span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#79B8FF">  "hotkeys"</span><span style="color:#E1E4E8">: {</span></span>
<span class="line"><span style="color:#79B8FF">    "left"</span><span style="color:#E1E4E8">: [ </span><span style="color:#9ECBFF">"MainComponent.MoveLeft"</span><span style="color:#E1E4E8"> ],</span></span>
<span class="line"><span style="color:#79B8FF">    "right"</span><span style="color:#E1E4E8">: [ </span><span style="color:#9ECBFF">"MainComponent.MoveRight"</span><span style="color:#E1E4E8"> ],</span></span>
<span class="line"><span style="color:#79B8FF">    "ctrl+left"</span><span style="color:#E1E4E8">: [ </span><span style="color:#9ECBFF">"AppComponent.Back"</span><span style="color:#E1E4E8">, </span><span style="color:#9ECBFF">"MainComponent.MoveLeft"</span><span style="color:#E1E4E8"> ],</span></span>
<span class="line"><span style="color:#79B8FF">    "ctrl+right"</span><span style="color:#E1E4E8">: [ </span><span style="color:#9ECBFF">"AppComponent.Forward"</span><span style="color:#E1E4E8">, </span><span style="color:#9ECBFF">"MainComponent.MoveRight"</span><span style="color:#E1E4E8"> ]</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>A consuming Component would look like that:</p>
<h4 id="maincomponentts">MainComponent.ts</h4>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="typescript"><code><span class="line"><span style="color:#F97583">import</span><span style="color:#E1E4E8"> { Component, OnDestroy } </span><span style="color:#F97583">from</span><span style="color:#9ECBFF"> '@angular/core'</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">import</span><span style="color:#E1E4E8"> { Command, CommandService } </span><span style="color:#F97583">from</span><span style="color:#9ECBFF"> './command.service'</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">import</span><span style="color:#E1E4E8"> { Subscription } </span><span style="color:#F97583">from</span><span style="color:#9ECBFF"> 'rxjs/Subscription'</span><span style="color:#E1E4E8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#E1E4E8">@</span><span style="color:#B392F0">Component</span><span style="color:#E1E4E8">({</span></span>
<span class="line"><span style="color:#E1E4E8">  moduleId: </span><span style="color:#79B8FF">module</span><span style="color:#E1E4E8">.</span><span style="color:#79B8FF">id</span><span style="color:#E1E4E8">,</span></span>
<span class="line"><span style="color:#E1E4E8">  selector: </span><span style="color:#9ECBFF">'main'</span><span style="color:#E1E4E8">,</span></span>
<span class="line"><span style="color:#E1E4E8">  templateUrl: </span><span style="color:#9ECBFF">'main.component.html'</span></span>
<span class="line"><span style="color:#E1E4E8">})</span></span>
<span class="line"><span style="color:#F97583">export</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> MainComponent</span><span style="color:#F97583"> implements</span><span style="color:#B392F0"> OnDestroy</span><span style="color:#E1E4E8"> {</span></span>
<span class="line"><span style="color:#FFAB70">  command</span><span style="color:#F97583">:</span><span style="color:#79B8FF"> string</span><span style="color:#F97583"> =</span><span style="color:#9ECBFF"> 'None'</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#FFAB70">  subscription</span><span style="color:#F97583">:</span><span style="color:#B392F0"> Subscription</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">  constructor</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">private</span><span style="color:#FFAB70"> commandService</span><span style="color:#F97583">:</span><span style="color:#B392F0"> CommandService</span><span style="color:#E1E4E8">) {</span></span>
<span class="line"><span style="color:#79B8FF">    this</span><span style="color:#E1E4E8">.subscription </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> commandService.commands.</span><span style="color:#B392F0">subscribe</span><span style="color:#E1E4E8">(</span><span style="color:#FFAB70">c</span><span style="color:#F97583"> =></span><span style="color:#79B8FF"> this</span><span style="color:#E1E4E8">.</span><span style="color:#B392F0">handleCommand</span><span style="color:#E1E4E8">(c));</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"><span style="color:#B392F0">  handleCommand</span><span style="color:#E1E4E8">(</span><span style="color:#FFAB70">command</span><span style="color:#F97583">:</span><span style="color:#B392F0"> Command</span><span style="color:#E1E4E8">) {</span></span>
<span class="line"><span style="color:#F97583">    switch</span><span style="color:#E1E4E8"> (command.name) {</span></span>
<span class="line"><span style="color:#F97583">      case</span><span style="color:#9ECBFF"> 'MainComponent.MoveLeft'</span><span style="color:#E1E4E8">: </span><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">.command </span><span style="color:#F97583">=</span><span style="color:#9ECBFF"> 'left!'</span><span style="color:#E1E4E8">; </span><span style="color:#F97583">break</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">      case</span><span style="color:#9ECBFF"> 'MainComponent.MoveRight'</span><span style="color:#E1E4E8">: </span><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">.command </span><span style="color:#F97583">=</span><span style="color:#9ECBFF"> 'right!'</span><span style="color:#E1E4E8">; </span><span style="color:#F97583">break</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#E1E4E8">    }</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"><span style="color:#B392F0">  ngOnDestroy</span><span style="color:#E1E4E8">() {</span></span>
<span class="line"><span style="color:#79B8FF">    this</span><span style="color:#E1E4E8">.subscription.</span><span style="color:#B392F0">unsubscribe</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<h3 id="sample-app">Sample App</h3>
<p>I’ve pushed a simple sample app that uses the CommandService to <a href="https://github.com/8/hotkey-sample">github (https://github.com/8/hotkey-sample)</a>.</p>
<h3 id="references">References</h3>
<ul>
<li><a href="https://craig.is/killing/mice">Mousetrap (https://craig.is/killing/mice)</a></li>
<li><a href="https://github.com/brtnshrdr/angular2-hotkeys">angular2-hotkeys (https://github.com/brtnshrdr/angular2-hotkeys)</a></li>
<li><a href="https://github.com/8/hotkey-sample">My Sample App with the CommandService (https://github.com/8/hotkey-sample)</a></li>
</ul>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Windows Built in OCR from CSharp]]></title>
            <link>https://lostindetails.com/articles/Using-Windows-Built-in-OCR-from-CSharp</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/Using-Windows-Built-in-OCR-from-CSharp</guid>
            <pubDate>Wed, 12 Apr 2017 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<h2 id="using-win10-built-in-ocr">Using Win10 Built-in OCR</h2>
<h3 id="tldr">TLDR;</h3>
<p>To get OCR in C# Console- Wpf- or WinForms-App:</p>
<ol start="0">
<li>run on a modern Windows Version (e.g.: Win10)</li>
<li>add nuget <code>UwpDesktop</code></li>
<li>add the following code:</li>
</ol>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>var engine = OcrEngine.TryCreateFromLanguage(new Windows.Globalization.Language("en-US"));</span></span>
<span class="line"><span>string filePath = TestData.GetFilePath("testimage.png");</span></span>
<span class="line"><span>var file = await Windows.Storage.StorageFile.GetFileFromPathAsync(filePath);</span></span>
<span class="line"><span>var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);</span></span>
<span class="line"><span>var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);</span></span>
<span class="line"><span>var softwareBitmap = await decoder.GetSoftwareBitmapAsync();</span></span>
<span class="line"><span>var ocrResult = await engine.RecognizeAsync(softwareBitmap);</span></span>
<span class="line"><span>Console.WriteLine(ocrResult.Text);</span></span></code></pre>
<h3 id="ocr-troubles">OCR Troubles</h3>
<p>When UWP (=Universal Windows Platform) Apps were introduced, I was interested in what new APIs came with them. Soon the <a href="https://docs.microsoft.com/en-us/uwp/api/windows.media.ocr.ocrengine"><code>OcrEngine</code> (https://docs.microsoft.com/en-us/uwp/api/windows.media.ocr.ocrengine)</a> peaked my interest, because it promised a simple and quick way to retrieve text from images.</p>
<p>A simple OcrEngine was something that I was looking for as the alternatives are big and cumbersome to use (I am looking at you Tesseract), discontinued (MODI; was included with Office), in the cloud and/or expensive.</p>
<p>Back then the problem was that you needed to create a UWP Application to access the UWP APIs, but at the same time an UWP Application was completely sandboxed! You couldn’t even use any cross process communication (with the exception of using the cloud and a very basic file based approach).</p>
<p>That meant I couldn’t use the <code>OcrEngine</code> in a WindowsService or WebService or even over a commandline!</p>
<p>So with that being the case, I put together a quick solution using Tesseract, but I never got around to tuning it and it never performed well.</p>
<h3 id="uwpdesktop">UwpDesktop</h3>
<p>Time went by and then the great <a href="https://blogs.msdn.microsoft.com/lucian">Lucian Wischik (https://blogs.msdn.microsoft.com/lucian)</a> published the library <a href="https://github.com/ljw1004/uwp-desktop">uwp-desktop (https://github.com/ljw1004/uwp-desktop)</a> as a nuget package called <code>UwpDesktop</code>.</p>
<p>This package made UWP APIs available to Applications based on the normal .NET Framework. When I read the announcement, I was instantly reminded of my previous failure to make use of the <code>OcrEngine</code> and finally today I took it out for a spin and it worked great!</p>
<h3 id="example-code">Example Code</h3>
<p>The following code reads in the supplied file and prints out the detected text:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>var engine = OcrEngine.TryCreateFromLanguage(new Windows.Globalization.Language("en-US"));</span></span>
<span class="line"><span>string filePath = TestData.GetFilePath("testimage.png");</span></span>
<span class="line"><span>var file = await Windows.Storage.StorageFile.GetFileFromPathAsync(filePath);</span></span>
<span class="line"><span>var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);</span></span>
<span class="line"><span>var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);</span></span>
<span class="line"><span>var softwareBitmap = await decoder.GetSoftwareBitmapAsync();</span></span>
<span class="line"><span>var ocrResult = await engine.RecognizeAsync(softwareBitmap);</span></span>
<span class="line"><span>Console.WriteLine(ocrResult.Text);</span></span></code></pre>
<h3 id="example-application">Example Application</h3>
<p>I’ve put together a very <a href="https://github.com/8/ConsoleUwpOcr">simple example app and pushed it to github (https://github.com/8/ConsoleUwpOcr)</a> that makes use of the OcrEngine.</p>
<h4 id="example-output">Example Output:</h4>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>ocr.exe ..\..\..\ConsoleUwpOcr.Test\TestData\testimage.png</span></span>
<span class="line"><span>Welcome to Thunderbird Donate to Thunderbird Thunderbird IS the leading open source, cross- platform email and calendaring client, free for business and personal use. We want it to stay secure and become even better. If you like Thunderbird, please consider a donation! By donating, you Will help us to continue delivering an ad-free top-notch email client. Make a donation » Other ways to contribute to Thunderbird Now IS a great time for you to get involved: writing code, testing, support, localization and more. Join a global community! Share your skills and Pick up a few new ones along the way. Volunteer as much as you like. Or as little. It's totally up to you. Learn more » Why we need donations You might already know that Thunderbird improvements are no longer paid for by Mozilla. Fortunately there IS an active community keeping it running and developing it further. But to survive long term, the project needs funding. Thunderbird IS currently transitioning to an independent organization. Being independent, we can shape our own fate, but there IS significant infrastructure that must be majntajned to deliver the application to our tens of millions of users. For Thunderbird to survive and continue to evolve, we need your support and ask for your donation today. All the money donated Will go directly to funding Thunderbird development and infrastructure.</span></span></code></pre>
<h3 id="references">References</h3>
<ul>
<li><a href="https://docs.microsoft.com/en-us/uwp/api/windows.media.ocr.ocrengine"><code>OcrEngine</code> (https://docs.microsoft.com/en-us/uwp/api/windows.media.ocr.ocrengine)</a></li>
<li><a href="https://blogs.msdn.microsoft.com/lucian">Lucian Wischik (https://blogs.msdn.microsoft.com/lucian)</a></li>
<li><a href="https://github.com/ljw1004/uwp-desktop">UwpDesktop (https://github.com/ljw1004/uwp-desktop)</a></li>
<li><a href="https://github.com/8/ConsoleUwpOcr">OCR Example App (https://github.com/8/ConsoleUwpOcr)</a></li>
</ul>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fixing ORA 06502 in CSharp]]></title>
            <link>https://lostindetails.com/articles/Fixing-ORA-06502-in-CSharp</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/Fixing-ORA-06502-in-CSharp</guid>
            <pubDate>Fri, 16 Sep 2016 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<h2 id="fixing-ora-06502-in-c">Fixing ORA-06502 in C#</h2>
<h3 id="a-bug-appears">A bug appears</h3>
<p>A few days ago a friend asked me to help him figure out a bug that was reported. Thanks to the error report he was already able to trace the bug to a specific code fragment, but he was wondering why it failed - the code looked perfectly fine.</p>
<h3 id="the-cause">The cause</h3>
<p>The code was interfacing with an oracle database and was calling a stored procedure. As a stored procedures can’t return a value by itself, the usual way to retrieve data is to use an output parameter. The C# code sets the parameter up by declaring it’s type, size and direction and the stored procedure is then able to access and update it. After the control returns back to the caller, you can access the parameter and use it’s filled value.</p>
<p>The error message was: <code>ORA-06502: PL/SQL: numeric or value error: character string buffer too small exception</code></p>
<p>In this case the calling code was:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>cmd.Parameters.Add("param1", OracleDbType.Varchar2, 512, Direction.Output);</span></span></code></pre>
<p>When we took a look at signature of the offending method, we quickly spotted the bug:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>public OracleParameter Add(string name, OracleDbType dbType, object val, ParameterDirection dir)</span></span></code></pre>
<p>The problem was with the third parameter - the caller thought he was initializing the size of the output parameter, but instead he was supplying the initial value - which isn’t used for an output parameter anyway.</p>
<p>Fixing the code was easy by setting the size of the parameter explicitedly and we could have called it a day, but I’ve seen a bug just like this before and so I wondered how this mistake could have happened and I took a second look.</p>
<h3 id="the-root-cause">The root cause</h3>
<p>Digging deeper, I found the following overload:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>public OracleParameter Add(string name, OracleDbType dbType, int size)</span></span></code></pre>
<p>And then it dawned on me! Can you see what happened?</p>
<p>When the caller of the method started typing, he saw the overload where the third parameter is the size of type <code>int</code> and the correct overload is chosen.</p>
<p>It looked something like this:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>cmd.Parameters.Add("param1", OracleDbType.Varchar2, 512</span></span></code></pre>
<p>But he didn’t stop here, he continued on, because he wanted to supply the <code>ParameterDirection</code> as well and the moment he did so, the other overload was chosen, where the third parameter is now the value and not the size!</p>
<p>The caller didn’t notice, as an <code>int</code> converts nicely to an <code>object</code> and the signatures match up.</p>
<h3 id="bad-api-design">Bad API design</h3>
<p>The culprit in this scenario was bad design on oracles behalf when they added overloads that change the semantics of a parameter at a certain position.</p>
<p>If the types of the parameters would have differed sufficently it would only be a nuisance for the developer, as the compiler would have caught the error, but to make matters worse the types used were implicetly convertable from one to the other and therefore the compiler was of no help.</p>
<p>General <a href="https://msdn.microsoft.com/en-us/library/ms229029(v=vs.110).aspx">guidelines for Member Overloading</a> are documented nicely on the msdn and while you may freely ignore those design principles in your own applications (even if they make sense) in a professional public facing API you really should follow them, your customers will thank you for it.</p>
<h3 id="references">References</h3>
<p><a href="https://msdn.microsoft.com/en-us/library/ms229029(v=vs.110).aspx">Member Overloading on msdn (https://msdn.microsoft.com/en-us/library/ms229029(v=vs.110).aspx)</a></p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Binding your View to your ViewModel in Wpf]]></title>
            <link>https://lostindetails.com/articles/Binding-your-View-to-your-ViewModel-in-Wpf</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/Binding-your-View-to-your-ViewModel-in-Wpf</guid>
            <pubDate>Sun, 28 Aug 2016 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<h2 id="binding-your-view-to-your-viewmodel-in-wpf">Binding your View to your ViewModel in Wpf</h2>
<h3 id="overview">Overview</h3>
<p>When you are using <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel">Mvvm</a> you need a way to bind your view to the ViewModel.</p>
<p>While this is always done by binding the DataContext Property of a View to an instance of the specific ViewModel class, there are generally two different scenarios:</p>
<ol>
<li>The ViewModel can be retrieved using the current DataContext.</li>
<li>The ViewModel needs to be retrieved from a global source or created on demand.</li>
</ol>
<p>While the first first scenario is straightforward, the second is a little more a tricky and in this article I’ll show a simple pattern that you can use in your applications to simplify the binding process.</p>
<h3 id="different-scenarios">Different Scenarios</h3>
<p>If the ViewModel can be retrieved using the current DataContext of a View, then I’ll call this scenario “Hierarchical ViewModels” and if this is not the case, then I’ll call them “Independent ViewModels”.</p>
<h4 id="hierarchical-viewmodels">Hierarchical ViewModels</h4>
<h5 id="background">Background</h5>
<p>In the first scenario, you are already within a view that is bound to a ViewModel and you want to bind a child view to a ViewModel that is different than the one in the current DataContext, but one that it holds a reference to.</p>
<p>Often the parent is created by a DependencyInjection container that supplies the child ViewModel to the parent inside it’s constructor on instantiation.</p>
<p>The parent than exposes the child ViewModel via a public property.</p>
<p>In the parent view, you can just create a binding that sets the DataContext of the child to this property.</p>
<h5 id="example">Example</h5>
<p>In the following section, I’ve included an example for a hierarchical setup.</p>
<p>Consider this example consisting of two Views:</p>
<ul>
<li>MasterView</li>
<li>DetailView</li>
</ul>
<p>that are bound to these two ViewModels:</p>
<ul>
<li>MasterViewModel</li>
<li>DetailViewModel</li>
</ul>
<p><strong>MasterViewModel.cs</strong></p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">public</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> MasterViewModel</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  public</span><span style="color:#B392F0"> DetailViewModel</span><span style="color:#B392F0"> Detail</span><span style="color:#E1E4E8"> { </span><span style="color:#F97583">get</span><span style="color:#E1E4E8">; </span><span style="color:#F97583">set</span><span style="color:#E1E4E8">; }</span></span>
<span class="line"><span style="color:#E1E4E8">  ...</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p><strong>DetailViewModel.cs</strong></p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">public</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> DetailViewModel</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#E1E4E8">  ...</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>Then the following code can be used to bind the <code>DetailView</code> inside of the <code>MasterView</code> to the <code>DetailViewModel</code> contained inside the <code>MasterViewModel</code>s Detail property:</p>
<p><strong>MasterView.xaml</strong></p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="xml"><code><span class="line"><span style="color:#E1E4E8">&#x3C;</span><span style="color:#85E89D">v:DetailView</span><span style="color:#B392F0"> DataContext</span><span style="color:#E1E4E8">={Binding Detail} /></span></span></code></pre>
<p><em>Note:</em>
<em>As the Source of the Binding defaults to the current DataContext, the Source property of the Binding does not need to be set explicitly and the  the Binding needs only to contain the path to the ViewModel.</em></p>
<h4 id="independent-viewmodels">Independent ViewModels</h4>
<h5 id="background-1">Background</h5>
<p>Then there there are Independent ViewModels, which don’t know of each other. This is the case for all base ViewModels, who are the “entry points” for all hierarchical setups.</p>
<p>Some examples:</p>
<ul>
<li>The first ViewModel that is bound to a view, eg. <code>MainViewModel</code>, when there is no existing DataContext</li>
<li>Independent ViewModels for cross cutting concerns like
<ul>
<li>navigation eg. the Menu</li>
<li>information eg. the Statusbar and Notifications</li>
</ul>
</li>
</ul>
<p>In those cases, there current DataContext of the View does not contain a property that we can use, so we need to access some kind of central Locator or Factory, which is probably backed by an IoC Container that knows how to retrieve or create the requested ViewModel.</p>
<h5 id="example-1">Example</h5>
<p>Now setting up independent ViewModels or the first ViewModel when no DataContext is yet available, requires a little more work.</p>
<p>I’ve come with this simple pattern to make the ViewModels available for binding inside each view.</p>
<ol>
<li>
<p>Create a Locator that exposes the ViewModels that your views require via properties.</p>
</li>
<li>
<p>Add an instance of the locator as a static resource to your Application.
This should be done on Application Startup, for example by:</p>
<ul>
<li>Creating an Instance declaritively in your app.xaml file</li>
<li>Subscribing to your applications Startup event and setting it using the <code>Resources</code> property.</li>
</ul>
</li>
<li>
<p>Bind the View to the ViewModel by using the Locator as a Source using the StaticResource Binding.</p>
</li>
</ol>
<h6 id="locator">Locator</h6>
<p>As the first step, we need to create a locator that exposes the ViewModels that will be requested by from within a view.</p>
<p>The Locator exposes the ViewModels as properties, that makes binding against them easy using the normal binding syntax.</p>
<p>You can take the manual approach, where you implement each new ViewModel as a new property of the Locator yourself or you can use a dynamic approach where the ViewModels are lookup by your dependency injection container.</p>
<p>An example for the manual approach would look like something like this:</p>
<p><strong>Locator.cs (manual)</strong></p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">public</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> Locator</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">    public</span><span style="color:#E1E4E8"> MainViewModel { get { return </span><span style="color:#F97583">new</span><span style="color:#B392F0"> MainViewModel</span><span style="color:#E1E4E8">(); }}</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>As the manual approach gets tedious really fast, I’ve opted for the dynamic approach.</p>
<p>My implementation is based on DynamicObject that allows me to forward the property accessor to a dependency resolver for fulfillment.</p>
<p><strong>Locator.cs (dynamic)</strong></p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#6A737D">/// &#x3C;</span><span style="color:#85E89D">summary</span><span style="color:#6A737D">>Locator that forwards property access to the Dependency Resolver&#x3C;/</span><span style="color:#85E89D">summary</span><span style="color:#6A737D">></span></span>
<span class="line"><span style="color:#F97583">public</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> Locator</span><span style="color:#E1E4E8"> : </span><span style="color:#B392F0">DynamicObject</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#6A737D">  /// &#x3C;</span><span style="color:#85E89D">summary</span><span style="color:#6A737D">>Gets or sets the resolver that is used to map a property access to an instance&#x3C;/</span><span style="color:#85E89D">summary</span><span style="color:#6A737D">></span></span>
<span class="line"><span style="color:#F97583">  public</span><span style="color:#B392F0"> Func</span><span style="color:#E1E4E8">&#x3C;</span><span style="color:#F97583">string</span><span style="color:#E1E4E8">, </span><span style="color:#F97583">object</span><span style="color:#E1E4E8">> </span><span style="color:#B392F0">Resolver</span><span style="color:#E1E4E8"> { </span><span style="color:#F97583">get</span><span style="color:#E1E4E8">; </span><span style="color:#F97583">private</span><span style="color:#F97583"> set</span><span style="color:#E1E4E8">; }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">  public</span><span style="color:#B392F0"> Locator</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">Func</span><span style="color:#E1E4E8">&#x3C;</span><span style="color:#F97583">string</span><span style="color:#E1E4E8">, </span><span style="color:#F97583">object</span><span style="color:#E1E4E8">> </span><span style="color:#B392F0">resolver</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">  {</span></span>
<span class="line"><span style="color:#79B8FF">    this</span><span style="color:#E1E4E8">.Resolver </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> resolver;</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">  public</span><span style="color:#F97583"> override</span><span style="color:#F97583"> bool</span><span style="color:#B392F0"> TryGetMember</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">GetMemberBinder</span><span style="color:#B392F0"> binder</span><span style="color:#E1E4E8">, </span><span style="color:#F97583">out</span><span style="color:#F97583"> object</span><span style="color:#B392F0"> result</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">  {</span></span>
<span class="line"><span style="color:#F97583">    bool</span><span style="color:#B392F0"> successful</span><span style="color:#E1E4E8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">    string</span><span style="color:#B392F0"> property</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> binder.Name;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">    var</span><span style="color:#B392F0"> resolver</span><span style="color:#F97583"> =</span><span style="color:#79B8FF"> this</span><span style="color:#E1E4E8">.Resolver;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">    if</span><span style="color:#E1E4E8"> (resolver </span><span style="color:#F97583">!=</span><span style="color:#79B8FF"> null</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">    {</span></span>
<span class="line"><span style="color:#F97583">      try</span></span>
<span class="line"><span style="color:#E1E4E8">      {</span></span>
<span class="line"><span style="color:#E1E4E8">        result </span><span style="color:#F97583">=</span><span style="color:#B392F0"> resolver</span><span style="color:#E1E4E8">(property);</span></span>
<span class="line"><span style="color:#E1E4E8">        successful </span><span style="color:#F97583">=</span><span style="color:#79B8FF"> true</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#E1E4E8">      }</span></span>
<span class="line"><span style="color:#F97583">      catch</span><span style="color:#E1E4E8"> { result </span><span style="color:#F97583">=</span><span style="color:#79B8FF"> null</span><span style="color:#E1E4E8">; successful </span><span style="color:#F97583">=</span><span style="color:#79B8FF"> false</span><span style="color:#E1E4E8">; }</span></span>
<span class="line"><span style="color:#E1E4E8">    }</span></span>
<span class="line"><span style="color:#F97583">    else</span></span>
<span class="line"><span style="color:#E1E4E8">    {</span></span>
<span class="line"><span style="color:#E1E4E8">      result </span><span style="color:#F97583">=</span><span style="color:#79B8FF"> null</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#E1E4E8">      successful </span><span style="color:#F97583">=</span><span style="color:#79B8FF"> false</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#E1E4E8">    }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">    return</span><span style="color:#E1E4E8"> successful;</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>The locator is supplied with a Func in it’s constructor that resolves the request for the ViewModel based on the requested property name.</p>
<p>For example, let’s say you are using Autofac as a dependency resolver and you’ve configured Autofac to resolve your ViewModels by looking them up from your <code>ViewModel</code> namespace using a simple convention like this:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#B392F0">ContainerBuilder</span><span style="color:#B392F0"> builder</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Autofac</span><span style="color:#E1E4E8">.</span><span style="color:#B392F0">ContainerBuilder</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">builder.</span><span style="color:#B392F0">RegisterAssemblyTypes</span><span style="color:#E1E4E8">(Assembly.</span><span style="color:#B392F0">GetExecutingAssembly</span><span style="color:#E1E4E8">())</span></span>
<span class="line"><span style="color:#E1E4E8">  .</span><span style="color:#B392F0">InNamespace</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">"WpfMvvmExample.ViewModel"</span><span style="color:#E1E4E8">);</span></span>
<span class="line"><span style="color:#F97583">var</span><span style="color:#B392F0"> container</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> builder.</span><span style="color:#B392F0">Build</span><span style="color:#E1E4E8">();</span></span></code></pre>
<p>Now you can create an instance of the Locator like this:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">var</span><span style="color:#B392F0"> locator</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Locator</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">property</span><span style="color:#F97583"> =></span><span style="color:#E1E4E8"> container.</span><span style="color:#B392F0">Resolve</span><span style="color:#E1E4E8">(Type.</span><span style="color:#B392F0">GetType</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">$"WpfMvvmExample.ViewModel.</span><span style="color:#9ECBFF">{</span><span style="color:#E1E4E8">property</span><span style="color:#9ECBFF">}</span><span style="color:#9ECBFF">"</span><span style="color:#E1E4E8">)));</span></span></code></pre>
<p><em>Note:</em>
<em>As the binding path used inside a view is just a string and evaluated at runtime and not strongly typed, using a dynamic object fits nicely, as we don’t lose any type information.</em></p>
<h6 id="add-the-initialized-locator">Add the initialized Locator</h6>
<p>Now it’s time to add the Locator to someplace where your views can access it. The <code>Application_Startup</code> method inside the <code>App</code> class is a good place for that.</p>
<p><strong>App.xaml.cs</strong></p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#B392F0">ContainerBuilder</span><span style="color:#B392F0"> builder</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Autofac</span><span style="color:#E1E4E8">.</span><span style="color:#B392F0">ContainerBuilder</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">builder.</span><span style="color:#B392F0">RegisterAssemblyTypes</span><span style="color:#E1E4E8">(Assembly.</span><span style="color:#B392F0">GetExecutingAssembly</span><span style="color:#E1E4E8">())</span></span>
<span class="line"><span style="color:#E1E4E8">  .</span><span style="color:#B392F0">InNamespace</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">"WpfMvvmExample.ViewModel"</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">  .</span><span style="color:#B392F0">SingleInstance</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">        </span></span>
<span class="line"><span style="color:#F97583">var</span><span style="color:#B392F0"> container</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> builder.</span><span style="color:#B392F0">Build</span><span style="color:#E1E4E8">();</span></span>
<span class="line"></span>
<span class="line"><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">.Resources[</span><span style="color:#9ECBFF">"Locator"</span><span style="color:#E1E4E8">] </span><span style="color:#F97583">=</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Locator</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">property</span><span style="color:#F97583"> =></span><span style="color:#E1E4E8"> container.</span><span style="color:#B392F0">Resolve</span><span style="color:#E1E4E8">(Type.</span><span style="color:#B392F0">GetType</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">$"WpfMvvmExample.ViewModel.</span><span style="color:#9ECBFF">{</span><span style="color:#E1E4E8">property</span><span style="color:#9ECBFF">}</span><span style="color:#9ECBFF">"</span><span style="color:#E1E4E8">)));</span></span></code></pre>
<h6 id="bind-the-view-to-the-viewmodel">Bind the View to the ViewModel</h6>
<p>Finally we can use the Locator inside of a view to use it to bind to a ViewModel. We reference the Locator as the bindings Source property and point the path property to the required ViewModel type.</p>
<p><strong>MainWindow.xaml</strong></p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="xml"><code><span class="line"><span style="color:#E1E4E8">&#x3C;</span><span style="color:#85E89D">v:MainView</span><span style="color:#B392F0"> DataContext</span><span style="color:#E1E4E8">=</span><span style="color:#9ECBFF">"{Binding MainViewModel, Source={StaticResource Locator}}"</span><span style="color:#E1E4E8"> /></span></span></code></pre>
<h5 id="example-code-on-github">Example Code on github</h5>
<p>I’ve uploaded an small example application to <a href="https://github.com/8/WpfMvvmExample">github</a> that contains the Locator and the setup in case it is useful for anybody else.</p>
<p>If you have any comments please feel free to drop me a line in the comments below, thanks!</p>
<p>Take care,<br>
-Martin</p>
<h3 id="references">References</h3>
<ul>
<li><a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel">Mvvm (en.wikipedia.org/wiki/Model–view–viewmodel)</a></li>
<li><a href="https://github.com/8/WpfMvvmExample">Example Application Github Source Code (https://
github.com/8/WpfMvvmExample)</a></li>
<li><a href="https://github.com/autofac/Autofac">Autofac (https://github.com/autofac/Autofac)</a></li>
</ul>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SkiaSharp with Wpf]]></title>
            <link>https://lostindetails.com/articles/SkiaSharp-with-Wpf</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/SkiaSharp-with-Wpf</guid>
            <pubDate>Fri, 01 Apr 2016 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<h2 id="skiasharp-with-wpf-example">SkiaSharp with Wpf Example</h2>
<h3 id="background">Background</h3>
<p>After
<a href="https://developer.xamarin.com/guides/cross-platform/drawing/">SkiaSharp</a>
was announced by Miguel de Icaza on <a href="https://blog.xamarin.com/cross-platform-2d-graphics-with-skiasharp/">his
blog</a>,
I downloaded the nuget and took it for a spin and used it for some image
manipulation.</p>
<p>While the sample code got me started, it was written for
<a href="https://msdn.microsoft.com/en-us/library/system.drawing%28v=vs.110%29.aspx">System.Drawing/GDI+</a>
and when I later wanted to use it in a Wpf app, I didn’t find any
sample code for that. So I wrote some code and this blog post, in case
someone else might find that useful.</p>
<h3 id="drawing-a-bitmap-in-wpf">Drawing a Bitmap in Wpf</h3>
<h4 id="imagesource-and-writeablebitmap">ImageSource and WriteableBitmap</h4>
<p>Basically, when you’re using Wpf you most often want to use an
<a href="https://msdn.microsoft.com/en-us/library/system.windows.media.imagesource%28v=vs.110%29.aspx">ImageSource</a>,
for example to display it within an Image control. When creating an
ImageSource yourself, the
<a href="https://msdn.microsoft.com/en-us/library/system.windows.media.imaging.writeablebitmap%28v=vs.110%29.aspx">WriteableBitmap</a>
comes in handy. It is not only a subclass of ImageSource, it’s also
double buffered, which allows a smooth udpate process.</p>
<h4 id="sourcecode">Sourcecode</h4>
<p>I’ve written the following code to do that:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">public</span><span style="color:#B392F0"> WriteableBitmap</span><span style="color:#B392F0"> CreateImage</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">int</span><span style="color:#B392F0"> width</span><span style="color:#E1E4E8">, </span><span style="color:#F97583">int</span><span style="color:#B392F0"> height</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  return</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> WriteableBitmap</span><span style="color:#E1E4E8">(width, height, </span><span style="color:#79B8FF">96</span><span style="color:#E1E4E8">, </span><span style="color:#79B8FF">96</span><span style="color:#E1E4E8">, PixelFormats.Bgra32, BitmapPalettes.Halftone256Transparent);</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span>
<span class="line"><span style="color:#F97583">public</span><span style="color:#F97583"> void</span><span style="color:#B392F0"> UpdateImage</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">WriteableBitmap</span><span style="color:#B392F0"> writeableBitmap</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  int</span><span style="color:#B392F0"> width</span><span style="color:#F97583">  =</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">int</span><span style="color:#E1E4E8">)writeableBitmap.Width,</span></span>
<span class="line"><span style="color:#B392F0">      height</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">int</span><span style="color:#E1E4E8">)writeableBitmap.Height;</span></span>
<span class="line"><span style="color:#E1E4E8">  writeableBitmap.</span><span style="color:#B392F0">Lock</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#F97583">  using</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">var</span><span style="color:#B392F0"> surface</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> SKSurface.</span><span style="color:#B392F0">Create</span><span style="color:#E1E4E8">(</span></span>
<span class="line"><span style="color:#B392F0">    width</span><span style="color:#E1E4E8">: width,</span></span>
<span class="line"><span style="color:#B392F0">    height</span><span style="color:#E1E4E8">: height,</span></span>
<span class="line"><span style="color:#B392F0">    colorType</span><span style="color:#E1E4E8">: SKColorType.Bgra_8888,</span></span>
<span class="line"><span style="color:#B392F0">    alphaType</span><span style="color:#E1E4E8">: SKAlphaType.Premul,</span></span>
<span class="line"><span style="color:#B392F0">    pixels</span><span style="color:#E1E4E8">: writeableBitmap.BackBuffer,</span></span>
<span class="line"><span style="color:#B392F0">    rowBytes</span><span style="color:#E1E4E8">: width </span><span style="color:#F97583">*</span><span style="color:#79B8FF"> 4</span><span style="color:#E1E4E8">))</span></span>
<span class="line"><span style="color:#E1E4E8">  {</span></span>
<span class="line"><span style="color:#B392F0">    SKCanvas</span><span style="color:#B392F0"> canvas</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> surface.Canvas;</span></span>
<span class="line"><span style="color:#E1E4E8">    canvas.</span><span style="color:#B392F0">Clear</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">new</span><span style="color:#B392F0"> SKColor</span><span style="color:#E1E4E8">(</span><span style="color:#79B8FF">130</span><span style="color:#E1E4E8">, </span><span style="color:#79B8FF">130</span><span style="color:#E1E4E8">, </span><span style="color:#79B8FF">130</span><span style="color:#E1E4E8">));</span></span>
<span class="line"><span style="color:#E1E4E8">    canvas.</span><span style="color:#B392F0">DrawText</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">"SkiaSharp on Wpf!"</span><span style="color:#E1E4E8">, </span><span style="color:#79B8FF">50</span><span style="color:#E1E4E8">, </span><span style="color:#79B8FF">200</span><span style="color:#E1E4E8">, </span><span style="color:#F97583">new</span><span style="color:#B392F0"> SKPaint</span><span style="color:#E1E4E8">() { Color </span><span style="color:#F97583">=</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> SKColor</span><span style="color:#E1E4E8">(</span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">, </span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">, </span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">), TextSize </span><span style="color:#F97583">=</span><span style="color:#79B8FF"> 100</span><span style="color:#E1E4E8"> });</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"><span style="color:#E1E4E8">  writeableBitmap.</span><span style="color:#B392F0">AddDirtyRect</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">new</span><span style="color:#B392F0"> Int32Rect</span><span style="color:#E1E4E8">(</span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">, </span><span style="color:#79B8FF">0</span><span style="color:#E1E4E8">, width, height));</span></span>
<span class="line"><span style="color:#E1E4E8">  writeableBitmap.</span><span style="color:#B392F0">Unlock</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>Basically, what we want to do is:</p>
<ul>
<li>Create a WriteableBitmap of the appropriate size</li>
<li>Update the WriteableBitmap with Skia
<ol>
<li>Lock the Backing Buffer</li>
<li>Use Skia with the matching pixelformat to draw into the backing
buffer</li>
<li>Mark the Bitmap as dirty</li>
<li>Unlock the Bitmaps Backing Buffer again</li>
</ol>
</li>
</ul>
<p><em>Note:</em>
<em>Don’t forget to mark the updated region of the bitmap as dirty, else nothing is going to happen!</em></p>
<h3 id="example-wpf-app">Example Wpf App</h3>
<p>Now that I was able to render an Wpf image with Skia and the
WriteableBitmap class supports double buffering, I wanted to create a
quick app that updates the Image once per frame.</p>
<p>For that, I’ve subscribed the <code>CompositionTarget.Rendering</code> event and
updated the render method to draw the number of elapsed frames. You can
see the output on the screenshot below:</p>
<h4 id="screenshot">Screenshot</h4>
<p><img src="/img/SkiaSharpExample.png" alt="Screenshot of SkiaSharp Wpf Example
Application" title="SkiaSharp Wpf Example Application"></p>
<h4 id="sourcecode-on-github">Sourcecode on Github</h4>
<p>If you’re interested in the example app, I’ve uploaded the source of
the <strong>SkiaSharp Wpf Example Application to github</strong> at
<a href="https://github.com/8/SkiaSharp-Wpf-Example">https://github.com/8/SkiaSharp-Wpf-Example</a></p>
<p>If you find any of that useful or I am missing something, please feel
free to drop me a comment below, thanks!</p>
<p>Take care,<br>
Martin</p>
<h3 id="references">References</h3>
<ul>
<li><a href="https://msdn.microsoft.com/en-us/library/system.drawing%28v=vs.110%29.aspx">System.Drawing/GDI+
(https://msdn.microsoft.com/en-us/library/system.drawing%28v=vs.110%29.aspx)</a></li>
<li><a href="https://msdn.microsoft.com/en-us/library/system.windows.media.imagesource%28v=vs.110%29.aspx">ImageSource on msdn
(https://msdn.microsoft.com/en-us/library/system.windows.media.imagesource%28v=vs.110%29.aspx)</a></li>
<li><a href="https://msdn.microsoft.com/en-us/library/system.windows.media.imaging.writeablebitmap%28v=vs.110%29.aspx">WriteableBitmap on msdn
(https://msdn.microsoft.com/en-us/library/system.windows.media.imaging.writeablebitmap%28v=vs.110%29.aspx)</a></li>
<li><a href="https://developer.xamarin.com/guides/cross-platform/drawing/">SkiaSharp
(https://developer.xamarin.com/guides/cross-platform/drawing/)</a></li>
<li><a href="https://blog.xamarin.com/cross-platform-2d-graphics-with-skiasharp/">Cross-Platform 2D Graphics with SkiaSharp
(https://blog.xamarin.com/cross-platform-2d-graphics-with-skiasharp/)</a></li>
<li><a href="https://github.com/8/SkiaSharp-Wpf-Example">SkiaSharp Wpf Example App on github
(https://github.com/8/SkiaSharp-Wpf-Example)</a></li>
</ul>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Knockout Bindings]]></title>
            <link>https://lostindetails.com/articles/Custom-Knockout-Bindings</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/Custom-Knockout-Bindings</guid>
            <pubDate>Thu, 24 Mar 2016 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<h2 id="creating-custom-knockout-bindings">Creating Custom Knockout Bindings</h2>
<h3 id="background">Background</h3>
<p>I’ve been using and enjoying <a href="http://knockoutjs.com">knockout.js</a> for
some time now.</p>
<p>It’s a great library that allows you to use MVVM in web applications
and keeps you from writing spaghetti code to manipulate the DOM without
requiring a switch to a monolithic framework and the associated
downsides like lock-in and too many abstractions from plain html.</p>
<p>Using knockoutjs, you are still free to use DOM manipulation yourself if
and when you need it. The great thing is, it’s also easily extendable.</p>
<h3 id="extending-knockout">Extending Knockout</h3>
<p>Why is being extendable a big plus and why would you want to extend
knockout? Is something essential missing from knockout?</p>
<p>Nope, I don’t think so.</p>
<p>Instead of growing to a monolithic framework, it just solves a
particular problem, namely factoring out the UI glue code into reusable
bindings. It comes with almost all bindings you could think of by
default, but it doesn’t try to be everything for everyone - and thats
where custom bindings come in.</p>
<p>Using custom binding handlers, it offers you the chance to stick to DRY
and to use declarations instead of repeating javascript snippets over
and over again.</p>
<p>That often comes in handy, when you need to reuse some javascript code
in multiple places and the code is tied to an element defined in html.</p>
<p>In the next few paragraphs, I am showing some small, exemplary binding
handlers that have proven useful to me, nothing fancy.</p>
<h3 id="example-bindinghandlers">Example BindingHandlers</h3>
<p>I’ve been using some small knockout bindings that uses jquery’s
<a href="https://api.jquery.com/fadeIn/">fadeIn()</a> /
<a href="https://api.jquery.com/fadeOut/">fadeOut()</a> methods and
<a href="https://api.jquery.com/slideDown/">slideDown()</a> /
<a href="https://api.jquery.com/fadeIn/">slideUp()</a> to achieve simple animations
on an element.</p>
<h4 id="fadevisible">FadeVisible</h4>
<p>The binding is defined in the following few lines:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="js"><code><span class="line"><span style="color:#E1E4E8">ko.bindingHandlers.fadeVisible </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> {</span></span>
<span class="line"><span style="color:#B392F0">  init</span><span style="color:#E1E4E8">: </span><span style="color:#F97583">function</span><span style="color:#E1E4E8"> (</span><span style="color:#FFAB70">element</span><span style="color:#E1E4E8">, </span><span style="color:#FFAB70">valueAccessor</span><span style="color:#E1E4E8">) {</span></span>
<span class="line"><span style="color:#F97583">    var</span><span style="color:#E1E4E8"> value </span><span style="color:#F97583">=</span><span style="color:#B392F0"> valueAccessor</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#B392F0">    $</span><span style="color:#E1E4E8">(element).</span><span style="color:#B392F0">toggle</span><span style="color:#E1E4E8">(ko.</span><span style="color:#B392F0">unwrap</span><span style="color:#E1E4E8">(value));</span></span>
<span class="line"><span style="color:#E1E4E8">  },</span></span>
<span class="line"><span style="color:#B392F0">  update</span><span style="color:#E1E4E8">: </span><span style="color:#F97583">function</span><span style="color:#E1E4E8"> (</span><span style="color:#FFAB70">element</span><span style="color:#E1E4E8">, </span><span style="color:#FFAB70">valueAccessor</span><span style="color:#E1E4E8">) {</span></span>
<span class="line"><span style="color:#F97583">    var</span><span style="color:#E1E4E8"> value </span><span style="color:#F97583">=</span><span style="color:#B392F0"> valueAccessor</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">    ko.</span><span style="color:#B392F0">unwrap</span><span style="color:#E1E4E8">(value) </span><span style="color:#F97583">?</span><span style="color:#B392F0"> $</span><span style="color:#E1E4E8">(element).</span><span style="color:#B392F0">fadeIn</span><span style="color:#E1E4E8">() </span><span style="color:#F97583">:</span><span style="color:#B392F0"> $</span><span style="color:#E1E4E8">(element).</span><span style="color:#B392F0">fadeOut</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"><span style="color:#E1E4E8">};</span></span></code></pre>
<h4 id="slidedownvisible">SlideDownVisible</h4>
<p>The definition for the slideDown binding looks almost identical:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="js"><code><span class="line"><span style="color:#E1E4E8">ko.bindingHandlers.slideDownVisible </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> {</span></span>
<span class="line"><span style="color:#B392F0">  init</span><span style="color:#E1E4E8">: </span><span style="color:#F97583">function</span><span style="color:#E1E4E8"> (</span><span style="color:#FFAB70">element</span><span style="color:#E1E4E8">, </span><span style="color:#FFAB70">valueAccessor</span><span style="color:#E1E4E8">) {</span></span>
<span class="line"><span style="color:#F97583">    var</span><span style="color:#E1E4E8"> value </span><span style="color:#F97583">=</span><span style="color:#B392F0"> valueAccessor</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#B392F0">    $</span><span style="color:#E1E4E8">(element).</span><span style="color:#B392F0">toggle</span><span style="color:#E1E4E8">(ko.</span><span style="color:#B392F0">unwrap</span><span style="color:#E1E4E8">(value));</span></span>
<span class="line"><span style="color:#E1E4E8">  },</span></span>
<span class="line"><span style="color:#B392F0">  update</span><span style="color:#E1E4E8">: </span><span style="color:#F97583">function</span><span style="color:#E1E4E8"> (</span><span style="color:#FFAB70">element</span><span style="color:#E1E4E8">, </span><span style="color:#FFAB70">valueAccessor</span><span style="color:#E1E4E8">) {</span></span>
<span class="line"><span style="color:#F97583">    var</span><span style="color:#E1E4E8"> value </span><span style="color:#F97583">=</span><span style="color:#B392F0"> valueAccessor</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">    ko.</span><span style="color:#B392F0">unwrap</span><span style="color:#E1E4E8">(value) </span><span style="color:#F97583">?</span><span style="color:#B392F0"> $</span><span style="color:#E1E4E8">(element).</span><span style="color:#B392F0">slideDown</span><span style="color:#E1E4E8">() </span><span style="color:#F97583">:</span><span style="color:#B392F0"> $</span><span style="color:#E1E4E8">(element).</span><span style="color:#B392F0">slideUp</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"><span style="color:#E1E4E8">};</span></span></code></pre>
<p>In turn, they both are very similar to the example knockout binding in
knockouts <a href="http://knockoutjs.com/documentation/custom-bindings.html">custom-binding
documentation</a>
which also provides a binding that uses slideDown() and slideUp().</p>
<h4 id="usage">Usage</h4>
<p>As for usage, you’d replace the default <a href="http://knockoutjs.com/documentation/visible-binding.html">‘visible’
binding</a> with
‘fadeVisible’ or ‘slideDownVisible’ respectively.</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="html"><code><span class="line"><span style="color:#E1E4E8">    &#x3C;</span><span style="color:#85E89D">div</span><span style="color:#B392F0"> data-bind</span><span style="color:#E1E4E8">=</span><span style="color:#9ECBFF">"fadeVisible: isVisible"</span><span style="color:#E1E4E8">></span></span>
<span class="line"><span style="color:#E1E4E8">    ...</span></span></code></pre>
<h4 id="nuget-package">Nuget package</h4>
<p>I’ve used the slideDownVisible binding already in a couple of projects
and I’ve finally gotten sick of copy/pasting them, so I’ve packaged
them as nuget packages named
<a href="https://www.nuget.org/packages/knockout-fadeVisible/">‘knockout-fadeVisible’</a>
and
<a href="https://www.nuget.org/packages/knockout-slideDownVisible/">‘knockout-slideDownVisible’</a>
and uploaded them to nuget.org so that I can add it faster the next time
I might need it. The (very short) source is on
<a href="https://github.com/8/ko-bindings/blob/master/ko-bindings/Scripts/knockout-fadeVisible.js">github</a>
as well.</p>
<h4 id="bootstrap-modal">Bootstrap Modal</h4>
<p>Another example of transforming javascript glue code to a declarative
knockout binding would be the following modalVisible binding:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="js"><code><span class="line"><span style="color:#E1E4E8">ko.bindingHandlers.modalVisible </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> {</span></span>
<span class="line"><span style="color:#B392F0">  init</span><span style="color:#E1E4E8">: </span><span style="color:#F97583">function</span><span style="color:#E1E4E8"> (</span><span style="color:#FFAB70">element</span><span style="color:#E1E4E8">, </span><span style="color:#FFAB70">valueAccessor</span><span style="color:#E1E4E8">) {</span></span>
<span class="line"><span style="color:#F97583">    var</span><span style="color:#E1E4E8"> value </span><span style="color:#F97583">=</span><span style="color:#B392F0"> valueAccessor</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#6A737D">    /* init the modal */</span></span>
<span class="line"><span style="color:#B392F0">    $</span><span style="color:#E1E4E8">(element).</span><span style="color:#B392F0">modal</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#6A737D">    /* subscribe to the 'hidden' event and update the observable, if the modal gets hidden */</span></span>
<span class="line"><span style="color:#B392F0">    $</span><span style="color:#E1E4E8">(element).</span><span style="color:#B392F0">on</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">'hidden.bs.modal'</span><span style="color:#E1E4E8">, </span><span style="color:#F97583">function</span><span style="color:#E1E4E8"> (</span><span style="color:#FFAB70">e</span><span style="color:#E1E4E8">) {</span></span>
<span class="line"><span style="color:#F97583">      if</span><span style="color:#E1E4E8"> (ko.</span><span style="color:#B392F0">isObservable</span><span style="color:#E1E4E8">(value)) { </span><span style="color:#B392F0">value</span><span style="color:#E1E4E8">(</span><span style="color:#79B8FF">false</span><span style="color:#E1E4E8">); }</span></span>
<span class="line"><span style="color:#E1E4E8">    });</span></span>
<span class="line"><span style="color:#E1E4E8">  },</span></span>
<span class="line"><span style="color:#B392F0">  update</span><span style="color:#E1E4E8">: </span><span style="color:#F97583">function</span><span style="color:#E1E4E8"> (</span><span style="color:#FFAB70">element</span><span style="color:#E1E4E8">, </span><span style="color:#FFAB70">valueAccessor</span><span style="color:#E1E4E8">) {</span></span>
<span class="line"><span style="color:#F97583">    var</span><span style="color:#E1E4E8"> value </span><span style="color:#F97583">=</span><span style="color:#B392F0"> valueAccessor</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">    ko.</span><span style="color:#B392F0">unwrap</span><span style="color:#E1E4E8">(value) </span><span style="color:#F97583">?</span><span style="color:#B392F0"> $</span><span style="color:#E1E4E8">(element).</span><span style="color:#B392F0">modal</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">'show'</span><span style="color:#E1E4E8">) </span><span style="color:#F97583">:</span><span style="color:#B392F0"> $</span><span style="color:#E1E4E8">(element).</span><span style="color:#B392F0">modal</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">'hide'</span><span style="color:#E1E4E8">);</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>It wraps bootstrap javascript code in a tidy, nice to use knockout
binding after using the binding like:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="html"><code><span class="line"><span style="color:#E1E4E8">&#x3C;</span><span style="color:#85E89D">div</span><span style="color:#B392F0"> class</span><span style="color:#E1E4E8">=</span><span style="color:#9ECBFF">"modal fade"</span><span style="color:#B392F0"> data-bind</span><span style="color:#E1E4E8">=</span><span style="color:#9ECBFF">"modalVisible: isVisible"</span><span style="color:#B392F0">...</span></span></code></pre>
<p>This takes care of initializing the modal and allows controlling it’s
visibility using an observable. It handles hiding and showing of the
modal and therefore removes the need to manipulate the DOM from my
ViewModels javascript code.</p>
<h3 id="conclusion">Conclusion</h3>
<p>Knockoutjs is nice and flexible library that is not only easy to get
started with, but also easy to extend.</p>
<p>Creating custom binding handlers may save you from writing repetitive
and error prone code and allows you to stick view specific code
declaratively right on the target html element, which makes reasoning
about your view easier.</p>
<p>Decoupling jQuery and other DOM manipulation code from your normal code
also makes that code simpler to test.</p>
<p>Take care,<br>
Martin</p>
<h3 id="references">References</h3>
<ul>
<li><a href="http://knockoutjs.com">Knockout.js (http://knockoutjs.com)</a></li>
<li><a href="http://knockoutjs.com/documentation/custom-bindings.html">Creating a custom binding for Knockout
(http://knockoutjs.com/documentation/custom-bindings.html)</a></li>
<li><a href="http://knockoutjs.com/documentation/visible-binding.html">Knockout’s ‘visible’ binding
(http://knockoutjs.com/documentation/visible-binding.html)</a></li>
<li><a href="https://api.jquery.com/slideDown/">jQuery slideDown()
(https://api.jquery.com/slideDown/)</a></li>
<li><a href="https://api.jquery.com/slideUp/">jQuery slideUp()
(https://api.jquery.com/slideUp/)</a></li>
<li><a href="https://api.jquery.com/fadeIn/">jQuery fadeIn()
(https://api.jquery.com/fadeIn/)</a></li>
<li><a href="https://api.jquery.com/fadeOut/">jQuery fadeOut()
(https://api.jquery.com/fadeOut/)</a></li>
<li><a href="https://github.com/8/ko-bindings/blob/master/ko-bindings/Scripts/knockout-fadeVisible.js">fadeVisible binding
(https://github.com/8/ko-bindings/blob/master/ko-bindings/Scripts/knockout-fadeVisible.js)</a></li>
<li><a href="https://github.com/8/ko-bindings/blob/master/ko-bindings/Scripts/knockout-slideDownVisible.js">slideDownVisible knockout binding
(https://github.com/8/ko-bindings/blob/master/ko-bindings/Scripts/knockout-slideDownVisible.js)</a></li>
<li><a href="http://getbootstrap.com/javascript/#modals">Bootstrap Modal Javascript
(http://getbootstrap.com/javascript/#modals)</a></li>
</ul>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript debugging in VisualStudio with Chrome]]></title>
            <link>https://lostindetails.com/articles/JavaScript-debugging-in-VisualStudio-with-Chrome</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/JavaScript-debugging-in-VisualStudio-with-Chrome</guid>
            <pubDate>Thu, 28 Jan 2016 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<h2 id="debugging-javascript-in-visual-studio">Debugging JavaScript in Visual Studio</h2>
<h3 id="tldr">TL;DR</h3>
<ol>
<li>Start chrome in remote debug mode:
<code>chrome.exe --remote-debugging-port=9222</code></li>
<li>Attach Visual Studio: “Debug” -> “Attach to Process…” ->
select the chrome instance</li>
<li>Done.</li>
</ol>
<h3 id="justifying-a-use-case">Justifying a use case</h3>
<p>So you are still reading? Fine, than I can do some rambling. I was
developing a JavaScript WebApp with some complicated client code - it’s
built like a game loop using requestAnimationFrame and canvas to render
multiple videos onscreen and playing synced audio - like most software
it worked, but sometimes it would glitch and I was trying to figure out
what caused it.</p>
<p>Now what I wanted was to debug the code, preferably from the comfort of
my IDE, which happens to be Visual Studio, but while Visual Studio
supports debugging JavaScript via Internet Explorer out of the box, it
does not support any other browser.</p>
<p>More often than not, that’s not a big problem, you just fire up IE,
wonder why you never changed the startup page to something reasonable
and use it just once for debugging.</p>
<p>But not in this case as I was making use of
<a href="https://developer.mozilla.org/en-US/docs/Web/API/AudioContext">AudioContext</a>
and other shiny new WebApi stuff that are available in Chrome and
Firefox already but - you guessed it - not in IE.</p>
<p>You could of course do what everyone else would do and use the built-in
chrome developer tools, which are great imho, but that would incur the
cost of mental task switchs for using a different IDE that does not
share the same syntax highlighting, hotkeys and general workflow you
have come to be so productive with. So for the sake of this article I
count switching to a different tooling as giving up.</p>
<h3 id="wondering-if-its-possible">Wondering if it’s possible…?</h3>
<p>So I started wondering, if the big V is able to debug javascript running
in chrome.</p>
<p>The first hint, that the consensus is that it won’t work, was for me
that out of the box selecting chrome as your browser in visual studio
and starting your debug session does not work, while it does for IE.</p>
<blockquote>
<p>Quick Robin, to the googlemobile!</p>
<p>Almost every IT-SuperHero</p>
</blockquote>
<p>But the googlemobile failed hard this time,
<a href="https://developer.chrome.com/native-client/devguide/devcycle/vs-addin">top</a>
search results was talking about a Native Client and C++ code and a
<a href="http://forums.asp.net/t/2034995.aspx?JavaScript+debugging+in+visual+studio+with+chrome+or+Firefox+Non+IE+brower+">thread</a>
from last year said that it’s not possible and Visual Studio’s
integrated Extension search turned up nothing.</p>
<p>But on the other hand, I’ve already tried Visual Studio’s <a href="https://www.visualstudio.com/en-us/features/node-js-vs.aspx">Node.js
Tools</a> and
I remember vividly being amazed that debugging just worked. Okay, so
because Node.js and chrome both use V8 as their JavaScript engine,
Visual Studio must already be able to debug it.</p>
<h3 id="fiddlin-around">Fiddlin’ around</h3>
<p>So I ignored that Visual Studio does not start debugging if you are
using chrome and I simply tried to attach it to chrome using DEBUG ->
Attach to Process… and while that did not work, I noticed something
interesting:</p>
<p>In the “Code Type” selection I found a listing for Webkit!</p>
<p><img src="/img/webkitdebugging.png" alt=""></p>
<p>Now I knew that Visual Studio could do it and even expects me to use
Debug and Attach and so it’s probably chrome that doesn’t cooperate,
which makes sense as a sane default.</p>
<h3 id="solution">Solution</h3>
<p>So when I returned to google again I knew what to look for and a search
for chrome remote debugging brought me to <a href="https://developer.chrome.com/devtools/docs/debugger-protocol">this
page</a>
where my the missing part for my answer was waiting:</p>
<ol>
<li>Start chrome in remote debug mode:
<code>chrome.exe --remote-debugging-port=9222</code></li>
<li>Attach Visual Studio: “Debug” -> “Attach to Process…” ->
select the chrome instance</li>
<li>Done.</li>
</ol>
<h3 id="references">References</h3>
<ul>
<li><a href="https://www.visualstudio.com/en-us/features/node-js-vs.aspx">Visual Studio Node.js Tools
(https://www.visualstudio.com/en-us/features/node-js-vs.aspx)</a></li>
<li><a href="https://developer.chrome.com/devtools/docs/debugger-protocol">Chrome Debugger Protocol
(https://developer.chrome.com/devtools/docs/debugger-protocol)</a></li>
</ul>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[M-Files mass file export]]></title>
            <link>https://lostindetails.com/articles/M-Files-mass-file-export</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/M-Files-mass-file-export</guid>
            <pubDate>Fri, 15 Jan 2016 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<h2 id="exporting-a-lot-of-files-at-once-from-m-files">Exporting a lot of files at once from M-Files</h2>
<h3 id="background">Background</h3>
<p>I’ve written about how to do a mass file import into M-Files
<a href="M-Files-mass-file-import-Part-I">here</a> and
<a href="M-Files-mass-file-import-Part-II">here</a> before, but recently I was
contacted by a client who had quite the opposite problem - he wanted to
export a lot of files out of M-Files.</p>
<h3 id="getting-info">Getting Info</h3>
<p>After a quick skype call to get to know the client and the details of
the project, the following facts were available:</p>
<ul>
<li>The data resides in a single M-Files Vault</li>
<li>It’s backed by a whopping 230+ GB SQL Server Database</li>
<li>Other ways to export, direct access to the SQL Server and manual
exporting had failed</li>
<li>An export of all document files (.docx, .pdf, …) is needed</li>
<li>All properties of the files should be exported to a CSV file</li>
<li>Time was of the essence (when is it not?)</li>
</ul>
<h3 id="what-didnt-work">What didn’t work</h3>
<p>It seems that the client tried to export the data directly from the SQL
Server, but I heard that this approach failed as they couldn’t make out
what goes where. From a software engineering perspective, this is fair,
as the data storage is an implementation detail that can be changed
anytime (for example by using another database backend).</p>
<p>Next they tried to export the files manually. That’s not only slow, but
also an awfully error prone process and when you’re interested in the
metadata as well, then you really really shouldn’t go down this route,
even with a few documents, but in this case we had a few hundred
thousand.</p>
<p>So what’s the alternative?</p>
<p>You probably know what’s the right approach: a small custom application
that uses the M-Files API to access all documents programmatically.</p>
<h3 id="solution">Solution</h3>
<p>Armed with this knowledge we can formulate the characteristics of the
solution:</p>
<ul>
<li>Create the files</li>
<li>Create metadata</li>
<li>Reliable</li>
<li>Fast</li>
<li>Inexpensive</li>
</ul>
<p>Considering the fact, that the tool needed to be done quickly and keep
the development cost low, I decided on writing a Commandline
Application. Another reason was, that it did not need to look fancy and
would be operated by skilled IT personal who preferred a simple
commandline interface anyway. I would have been happy to create a Wpf
Application like <a href="/chronographer">Chronographer</a> but that would have
been overkill.</p>
<h4 id="exporting-the-files">Exporting the files</h4>
<p>As I had prior experience with the M-Files API, it didn’t take me long
get the file export running. In the screenshot below you see the results
if run against the Sample Vault.</p>
<p><img src="/img/MFilesExporterFiles.png" alt/></p>
<h4 id="exporting-the-data-to-csv">Exporting the Data to CSV</h4>
<p>A little more interesting but still straight forward was the csv export,
as you need to know all properties to create the csv header and put them
in the right column. To do this, I enumerate all classes in the Vault
and collect their properties and then they are written in the header
row.</p>
<p>A feature of M-Files is, that all M-Files documents can contain 0 or
more files, which meant for me that a found document could result in
zero exported files (if it didn’t hold any) or more than 1 file, in
which case the csv export also needed to repeat the properties
accordingly.</p>
<p>I settled on creating 4 fixed csv columns followed by the properties of
all classes. The 4 columns are:</p>
<ol>
<li>FilePath<br/>
Allows mapping to the exported files</li>
<li>FileId<br/>
The id of the document in the M-Files Vault</li>
<li>SourceFileId<br/>
The id of the binary file document (.docx, .pdf, …)</li>
<li>ClassName<br/>
The name of the class that the exported file belongs to</li>
</ol>
<p>Below you’ll find a screenshot of the result when run against the
Sample Vault.</p>
<p><img src="/img/MFilesExporterCsv.png" alt title="Screenshot of CSV Export"/></p>
<h4 id="enumerating-the-files">Enumerating the files</h4>
<p>An interesting problem was enumerating all the files to export. I
settled on creating a search for the documents that skips deleted
objects. As the maximum number of search results is capped at 100.000
items, you are not able to fetch all documents with a single search. I
solved that by adding an additional search condition, namely searching
for ids with a specified segment, where segment 0 for example means
items 0-9999 and segment 1 returns 10000-19999. By repeatedly searching
for files in this way and incrementing the segment, I was able to
traverse the whole vault.</p>
<h3 id="complications">Complications</h3>
<p>As always, nothing works perfectly on the first try and while the CSV
Export completed successfully, when we were exporting the files for a
few hours M-Files threw an Exception with the error message “An SQL
update statement yielded a probable lock conflict. Lock request time out
period exceeded.” which seemed like a M-Files glitch to me.</p>
<p>Anyway, as we needed to try again we were loath to start the export from
the beginning, so I added another commandline argument that allowed us
to specify a starting segment so that we could continue our export
instead of starting it from the beginning.</p>
<p>So that the final commandline interface looked like this:</p>
<p><img src="/img/MFilesExporter.png" alt/></p>
<p>Additional parameters like the Vault Name and the Credentials are stored
in a config file in the same folder and read by the application at
startup.</p>
<p>On the second run, we didn’t encounter any errors and we had exported
over 200K files and produced a nice 120MB CSV file. In the end, we had a
nice, repeatable process that was able to save the client a lot of time,
money and headaches.</p>
<div><div class="bg-primary-200 border-l-4 px-2 py-2 border-primary-800 flex"><div class="px-2"><h3 class="font-semibold text-lg pt-2 pb-1">Vault Exporter</h3><p>I&#39;ve started working on a commercial Software for exporting Documents from M-Files at: <br><a href="http://vault-exporter.com">https://vault-exporter.com</a></p><p class="text-sm text-primary-800 italic"><span class="font-bold">Note</span>: Not all features are fixed yet, so if you want to join the discussion or you just want to be notified when it launches, please head over and join the <a href="https://m-files-exporter.com">mailing list</a> to receive an update when it launches.</p></div></div></div>
<h3 id="references">References</h3>
<ul>
<li><a href="M-Files-mass-file-import-Part-I">Blog post: M-Files mass file import Part I
(http://lostindetails.com/blog/post/“M-Files-mass-file-import-Part-I)</a></li>
<li><a href="M-Files-mass-file-import-Part-II">Blog post: M-Files mass file import Part II
(http://lostindetails.com/blog/post/“M-Files-mass-file-import-Part-II)</a></li>
<li><a href="/chronographer">Chronographer, a Wpf Application I wrote
(http://lostindetails.com/chronographer)</a></li>
</ul>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[M-Files Backend Databases]]></title>
            <link>https://lostindetails.com/articles/M-Files-Backend-Databases</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/M-Files-Backend-Databases</guid>
            <pubDate>Tue, 05 Jan 2016 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<h2 id="about-m-files-databases">About M-Files Databases</h2>
<h3 id="background">Background</h3>
<p>M-Files always stores it’s data in a Sql Database. As of this writing
two Database vendors are supported:</p>
<ul>
<li>
<p>Firebird (default)</p>
<p>Firebird is an open source Sql Server, you can find out more about
it on <a href="http://firebirdsql.org/">http://firebirdsql.org</a>. As it is
free, it’s the default option when you install M-Files.</p>
</li>
<li>
<p>MS-SQL Server</p>
<p><a href="http://www.microsoft.com/sqlserver/">Microsoft’s Sql Server</a> is
the second option. Because it’s rather expensive, it’s not the
default option and the M-Files customer has to buy and install it
themselves.</p>
</li>
</ul>
<h3 id="database-engines-in-the-wild">Database Engines in the wild</h3>
<p>Both Firebird and MS-Sql should be able to handle M-Files Vaults of
considerable size, but in practice Firebird gets used more often in
smaller businesses and MS-Sql Server gets used more often in bigger
firms.</p>
<p>While the price tag certainly does matter, more often than not it
depends on whetever there is a preexisting investment into MS-Sql Server
or not. If the company already has a MS-SQL Server on premise, it’s a
no brainer to tack on an additional Database. Even if they don’t have a
DBA who already has experience with administrating the server, a lot of
companies already depend on the MS-Sql Server if they run on the
Microsoft Stack at all for different reasons, maybe they already have a
CMS or Website that depends on it.</p>
<h3 id="ms-sql-server-express">MS Sql Server Express</h3>
<p>Although a free version of Microsofts Sql Server called “Sql Server
Express” is <a href="https://www.microsoft.com/en-us/server-cloud/products/sql-server-editions/sql-server-express.aspx">available for
download</a>
(it even comes with reporting Services and an ok GUI for Administration
if you pick up the SQL Server Express with Advanced Services) it’s
often a poor choice for M-Files, because of the 10 GB limit on database.</p>
<p>Don’t get me wrong - 10 GB is not a small amount of data, but in this
case remember that M-Files does not only store your customers and
invoices as numbers and strings, but it also stores all binary files in
the database as well - that means all word documents, powerpoints and
pdfs with their high resolution cat pictures. If you throw in revisions
of the same file and multiply that by a couple of users you get to a lot
of data very quickly.</p>
<p>If you think that that’s not an issue in your case, you should be able
to use the express version as mentioned in <a href="https://community.m-files.com/index.php?topic=280.0">this
thread</a> on the
M-Files Forum.</p>
<h3 id="backing-up-and-restoring-a-m-files-vault">Backing up and Restoring a M-Files Vault</h3>
<p>Backing up and Restoring an M-Files Vault depends on your backend
Database.</p>
<p>If you’re using the default firebird sql server, than the backup is
done using the M-Files Admin tool.</p>
<p>But if you are using the Microft Sql Server as the backend, then you’ll
need to a tool like the Sql Server Management Studio to create a backup
of your vault and restore it back again, which is rather simple to do
for anyone that has used the tool once before.</p>
<h3 id="a-problem-when-restoring-a-ms-sql-based-vault">A problem when restoring a MS-SQL based Vault</h3>
<p>What prompted this quick writeup is that yesterday a client had a
problem restoring an M-Files Vault on the SQL Server.</p>
<p>Restoring the Database using the Management Tools worked fine, but the
target system had a newer version of M-Files running and was trying an
upgrade but failed with the following error message:</p>
<p>Upgrading the document vault ‘Vaultname’ failed.
ALTER ASSEMBLY for assembly ‘MFMSSQLCLRObjs’ failed because assembly ‘MFMSSQLCLRObjs’ is not authorized for PERMISSION_SET = UNSAFE. The assembly is authorized when either of the following is true: the database owner (DBO) has UNSAFE ASSEMBLY permission and the database has the TRUSTWORTHY database property on; or the assembly is signed with a certificate or an assymmetric key that has a corresponding login with UNSAFE ASSEMBLY permission. (ERROR: 10327, SQLSTATE: 42000)</p>
<p>After checking that the dbo had the correct permissions, I found that
the problem was that the restored database did not have the TRUSTWORTHY
property set.</p>
<p>I fixed that by excecuting the following command in the Sql Management
Studio as explained in <a href="https://msdn.microsoft.com/en-us/library/ms187861.aspx">this Microsoft
Article</a>:</p>
<p>ALTER DATABASE Vaultname SET TRUSTWORTHY ON;</p>
<p>After that I was able to attach the document vault without problems.</p>
<div><div class="bg-primary-200 border-l-4 px-2 py-2 border-primary-800 flex"><div class="px-2"><h3 class="font-semibold text-lg pt-2 pb-1">Vault Exporter</h3><p>I&#39;ve started working on a commercial Software for exporting Documents from M-Files at: <br><a href="http://vault-exporter.com">https://vault-exporter.com</a></p><p class="text-sm text-primary-800 italic"><span class="font-bold">Note</span>: Not all features are fixed yet, so if you want to join the discussion or you just want to be notified when it launches, please head over and join the <a href="https://m-files-exporter.com">mailing list</a> to receive an update when it launches.</p></div></div></div>
<h3 id="references">References</h3>
<ul>
<li><a href="http://firebirdsql.org/">Firebird Sql (http://firebirdsql.org/)</a></li>
<li><a href="http://www.microsoft.com/sqlserver/">MS-SQL Server
(http://www.microsoft.com/sqlserver/)</a></li>
<li><a href="https://www.microsoft.com/en-us/server-cloud/products/sql-server-editions/sql-server-express.aspx">SQL Server Express Edition
(https://www.microsoft.com/en-us/server-cloud/products/sql-server-editions/sql-server-express.aspx)</a></li>
<li><a href="https://community.m-files.com/index.php?topic=280.0">Thread about SQL Server Express Support in M-Files 9.0 RC
(https://community.m-files.com/index.php?topic=280.0)</a></li>
<li><a href="https://msdn.microsoft.com/en-us/library/ms187861.aspx">TRUSTWORTHY Database Property
(https://msdn.microsoft.com/en-us/library/ms187861.aspx)</a></li>
</ul>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fixing Razor Intellisense]]></title>
            <link>https://lostindetails.com/articles/Fixing-Razor-Intellisense</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/Fixing-Razor-Intellisense</guid>
            <pubDate>Tue, 24 Nov 2015 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<h4 id="tldr">TL;DR</h4>
<p>If razor intellisense stops working suddenly, try deleting your
<code>C:\Users\username\AppData\Local\Microsoft\VisualStudio\14.0\ComponentModelCache</code>
folder.</p>
<h4 id="the-problem">The Problem</h4>
<p>When I was opening Visual Studio the other day, I was greeted with the
following error message:</p>
<p><img src="/img/vs_exception.png" alt=""></p>
<p>Closing and reopening Visual Studio didn’t fix the error - it occurred
every time I opened a razor view (.cshtml) page. While Visual Studio
itself did not crash, highlightning and intellisense was broken inside
the view. E.g. razor comments “</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>@* this is a comment! *@</span></span></code></pre>
<p>were not highlighted correctly (just as in this post) and my favourite
spellchecker (intellisense) had stopped working as well.</p>
<h4 id="looking-at-the-error">Looking at the error</h4>
<p>I did as I was told and took a look at the ActivityLog as the error
message suggested and opened:
<code>C:\Users\username\AppData\Roaming\Microsoft\VisualStudio\14.0\ActivityLog.xml</code>
Which in turn revealed the following stack trace: <code>     </code></p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentException: Item has already been added. Key in dictionary: 'RazorSupportedRuntimeVersion' Key being added: 'RazorSupportedRuntimeVersion' at System.Collections.Hashtable.Insert(Object key, Object nvalue, Boolean add) at System.Collections.Hashtable.Add(Object key, Object value) at System.Collections.Specialized.HybridDictionary.Add(Object key, Object value) at Microsoft.VisualStudio.Utilities.PropertyCollection.AddProperty(Object key, Object property) at Microsoft.VisualStudio.Html.Package.Razor.RazorVersionDetector.Microsoft.Html.Editor.ContainedLanguage.Razor.Def.IRazorVersionDetector.GetVersion(ITextBuffer textBuffer) at Microsoft.Html.Editor.ContainedLanguage.Razor.RazorUtility.TryGetRazorVersion(ITextBuffer textBuffer, Version&#x26; razorVersion) at Microsoft.Html.Editor.ContainedLanguage.Razor.RazorErrorTagger..ctor(ITextBuffer textBuffer) --- End of inner exception stack trace --- at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark&#x26; stackMark) at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) at System.Activator.CreateInstance(Type type, Object[] args) at Microsoft.Html.Editor.ContainedLanguage.Common.ContainedCodeErrorTaggerProvider`1.CreateTagger[T](ITextBuffer textBuffer) at Microsoft.VisualStudio.Text.Tagging.Implementation.TagAggregator`1.GatherTaggers(ITextBuffer textBuffer)</span></span></code></pre>
<p>Looking at the stacktrace confirmed my suspicion that on a big picture
view something razor specific was messed up (I am looking at you
‘RazorSupportedRuntimeVersion’), I also got the info that an exception
was being thrown, because a duplicate hashtable entry was being
inserted.</p>
<h4 id="google-to-the-rescue">Google to the rescue</h4>
<p>The best part was of course, that an error message gave me something to
google for and so I did and finally came to a <a href="https://connect.microsoft.com/VisualStudio/feedback/details/1572978/no-intellisense-in-razor-views-argumentexception-razorsupportedruntimeversion-already-added-to-dictionary">Visual Studio Feedback
Item</a>
with the same error message.</p>
<p>The issue is of course marked as closed, but that’s neither here nor
there.</p>
<h4 id="a-first-workaround-appears">A first workaround appears</h4>
<p>Under workarounds I found out, that resetting your user data seems to
fix the issue. To do that you execute <code>devenv /resetuserdata</code> and sure
enough it did! Intellisense and Highlightning started to work again in
the razor view!</p>
<p>But the workaround also has some drawbacks, it well, resets your user
data (who would have thought?!), which means it removes all your
extensions as well.</p>
<p>Well, whatever. But then it happened to me again a few days later. :|</p>
<h4 id="improving-the-workaround">Improving the workaround</h4>
<p>Okay, so I thought, I could probably do better and not reset everything
but only the part that causes the problem. So I took another look at the
StackTrace and judging from the StackTrace
RazorVersionDetector.GetVersion() seems like the culprit. According to
the StackTrace RazorVersionDetector sits in
Microsoft.VisualStudio.Html.Package.Razor and luckily I found a dll with
the same name under:
<code>C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Web Tools\Editors\Microsoft.VisualStudio.Html.Package.dll</code>.</p>
<p>So I fired up trusty <a href="http://ilspy.net/">ILSpy</a> and looked at the
<del>strange looking</del> interesting interpretation of the C# code of the
RazorVersionDetector that ILSpy showed me. There I noticed that it’s
private methods were called GetCachedVersion() and SetCachedVersion()
which was why it worked at first, but broke later on and why resetting
the user data worked - it cleared the cache.</p>
<p>Armed with the knowledge I looked for cache folder and luckily I found
it:
<code>C:\Users\username\AppData\Local\Microsoft\VisualStudio\14.0\ComponentModelCache</code></p>
<p>Removing or renaming this folder forces Visual Studio to recreate it and
Razor intellisense starts working again and you get to keep your
extensions and stuff.</p>
<h4 id="references">References</h4>
<ul>
<li><a href="https://connect.microsoft.com/VisualStudio/feedback/details/1572978/no-intellisense-in-razor-views-argumentexception-razorsupportedruntimeversion-already-added-to-dictionary">Visual Studio Connect Item
(https://connect.microsoft.com/VisualStudio/feedback/details/1572978/no-intellisense-in-razor-views-argumentexception-razorsupportedruntimeversion-already-added-to-dictionary)</a></li>
<li><a href="http://ilspy.net">ILSpy (http://ilspy.net)</a></li>
</ul>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keep an open mind when choosing a software solution]]></title>
            <link>https://lostindetails.com/articles/Keep-an-open-mind-when-choosing-a-software-solution</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/Keep-an-open-mind-when-choosing-a-software-solution</guid>
            <pubDate>Thu, 29 Oct 2015 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<h2 id="choosing-between-different-solutions-webapp-mobileapp-desktopapp-console-or-service">Choosing between different solutions (WebApp, MobileApp, DesktopApp, Console or Service)</h2>
<h3 id="abstract">Abstract</h3>
<p>In this article I’ll encourage you to keep an open mind about your
options when building a software solution.</p>
<h3 id="motivation">Motivation</h3>
<p>Why write or read about how to choose between different solutions?
Shouldn’t it be obvious? I think it’s well worth our time to dwell on
that, especially considering two reasons:</p>
<ol>
<li>Choosing the wrong solution is one of the most expensive mistakes to
make. E.g. adding an unplanned feature to an application may seem
expensive, but it pales in comparison with the realization that your
mobile app should have been website or the other way round.</li>
<li>Often a decision about a platform or solution is not made
deliberately, because we are simply not aware of all our options.
E.g. consider if Kahneman’s WYSIATI (What You See Is All There Is)
theory comes into play here or the “If all you have is a hammer,
everything looks like a nail” quote rings true.</li>
</ol>
<h3 id="why-dont-we-evaluate-our-options-more-carefully">Why don’t we evaluate our options more carefully?</h3>
<p>There are a couple of obstacles that keep us from taking a closer look.</p>
<ul>
<li><strong>Missing Expertise</strong> It often requires in-depth knowledge and
experience of different technologies, which is hard to come by. E.g.
if you’re only skilled in developing Web Pages for customers you
won’t necessarily see that a Windows Service or a commandline tool
on a <a href="http://www.parallella.org/">Parallela Board</a> fits the
requirements better.</li>
<li><strong>Emotional Bias</strong> We’re often biased towards some technology not
based upon it’s merits and flaws for our specific use case, but
rather on our feelings and emotions based on a past project. Not
only was it a different project and the technology should be
reevaluated in the context of the new one, but also our emotions
were influenced by other factors like a too short deadline,
mismanagement, unrealistic expectations or difficulties with the
involved parties.</li>
<li><strong>Lots of Options</strong> Evaluating a lot of options is difficult and
straining, consider for example the book <a href="http://www.ted.com/talks/barry_schwartz_on_the_paradox_of_choice">The paradox of
choice</a>
or the <a href="http://www.ted.com/talks/barry_schwartz_on_the_paradox_of_choice">TED
Talk</a>
given by Barry Schwartz.</li>
</ul>
<h3 id="removing-the-obstacles">Removing the Obstacles</h3>
<p>But how can you remove those obstacles?</p>
<p><strong>Missing Expertise</strong></p>
<p>Missing Expertise can be battled in the following ways:</p>
<ol>
<li><strong>Learn about it</strong> The most obvious, although hardest solution is to
learn about the qualities of certain technologies. This does not
mean that one needs to become an expert in every new technology that
pops up, but knowing if it’s a good match for a certain use case is
important.</li>
<li><strong>Get Help</strong> If you’re a consultant or developer and the technology
that is most appropriate or required for the task does not match
your expertise, you should acknowledge the fact and inform your
client or boss. If you have a colleague or acquaintance that
specializes in that technology or field you should refer to them.</li>
</ol>
<p><strong>Emotional Bias</strong></p>
<ol>
<li><strong>Stressfree Environment</strong> A good way to combat emotional bias is to
get to know a technology in a stressfree environment. This may mean,
that you take a look at it in your spare time, without the clock
ticking.</li>
<li><strong>Tiny steps</strong> Start step by step and don’t try get everything done
at once. Sometimes you’ll feel tempted to try something big at once
that you are able to do in another language or with another
framework that you’ve already mastered - but don’t give in. Small
incremental successes keep your motiviation going for a longer time.</li>
<li><strong>Ask a friend</strong> If you really dislike a certain technology, you
should talk with a friend or someone you respect that is fond of it.
As he or she is your friend, you are unlikely to completely dismiss
them and get a glance why someone would want to use that and
advantages it has.</li>
</ol>
<p><strong>Lots of Options</strong></p>
<p>And finally, to get a quick overview I’ve compiled the following list
that can be used to get the juices flowing on what parts could make up
the ideal solution. My hope is that by spelling them out, they’ll be on
the radar the next time when a problem needs solving. Many solutions do
not fall strictly within one category and more often than not consist of
more than one part.</p>
<p><em>Disclaimer</em></p>
<p>This list is neither exhaustive nor can it be, it’s just a reminder of
what’s out there and should be seen as an inspiration to get you to
explore your options.</p>
<ul>
<li>Web Solutions
<ul>
<li>Static Web Pages (consider online/offline help, manuals)</li>
<li>Content Management Systems (CMS)
<ul>
<li>Wordpress (php)</li>
<li>Umbraco (asp.net)</li>
</ul>
</li>
<li>Mobile first</li>
<li>Server Side Frameworks
<ul>
<li>Asp.Net
<ul>
<li>NancyFx</li>
<li>Asp.Net MVC</li>
<li>Asp.Net WebApi</li>
</ul>
</li>
<li>Ruby
<ul>
<li>Ruby on Rails</li>
<li>Sinatra</li>
</ul>
</li>
<li>Php
<ul>
<li>phpcake</li>
<li>Symfony</li>
</ul>
</li>
<li>Node.js</li>
</ul>
</li>
<li>Forums
<ul>
<li>phpBB (php)</li>
<li>MVCForum (asp.net mvc)</li>
</ul>
</li>
<li>SPA</li>
<li>Web API</li>
<li>Front End Frameworks
<ul>
<li>Bootstrap</li>
<li>jqueryUI</li>
<li>Skeleton</li>
</ul>
</li>
<li>javascript frameworks
<ul>
<li>angular</li>
<li>aurelia</li>
<li>knockout</li>
<li>react</li>
</ul>
</li>
<li>visualization
<ul>
<li>d3</li>
<li>Raphaël</li>
<li>processing</li>
</ul>
</li>
<li>CSS Languages
<ul>
<li>Less</li>
<li>Sass</li>
</ul>
</li>
</ul>
</li>
<li>Mobile Applications
<ul>
<li>Platform specific
<ul>
<li>Android</li>
<li>iOS</li>
<li>Windows Phone</li>
<li>Blackberry</li>
</ul>
</li>
<li>Cross platform
<ul>
<li>Apache Cordova</li>
<li>Xamarin</li>
<li>RemObjects</li>
<li>Unity</li>
</ul>
</li>
</ul>
</li>
<li>Desktop Applications
<ul>
<li>Wpf (windows only)</li>
<li>WinForms (cross platform using mono)</li>
<li>GTK and it’s wrappers like GTK#</li>
<li>DirextX and it’s wrappers like SlimDX or SharpDX</li>
<li>OpenGL and it’s wrappers like OpenTK</li>
<li>Unity</li>
</ul>
</li>
<li>Console Applications</li>
<li>Windows Services
<ul>
<li>topshelf</li>
</ul>
</li>
<li>Linux Daemons</li>
<li>Datastorage
<ul>
<li>FileSystem</li>
<li>SQL Databases
<ul>
<li>MS-Sql</li>
<li>MySql</li>
<li>Postgresql</li>
<li>Oracle</li>
<li>SQLite</li>
</ul>
</li>
<li>No SQL Databases
<ul>
<li>RethinkDB</li>
<li>MongoDB</li>
<li>LMDB</li>
</ul>
</li>
</ul>
</li>
<li>WebServers
<ul>
<li>Apache</li>
<li>nginx</li>
</ul>
</li>
<li>Media Processing
<ul>
<li>imagemagick for images</li>
<li>sox for audios</li>
<li>ffmpeg for videos</li>
</ul>
</li>
<li>Virtualization
<ul>
<li>Virtual Box</li>
<li>Hyper-V</li>
<li>Virtual Machine</li>
<li>Xen</li>
</ul>
</li>
<li>Operating Systems
<ul>
<li>Linux</li>
<li>Windows</li>
<li>BSD</li>
</ul>
</li>
<li>Hardware platforms
<ul>
<li>Raspberry Pi</li>
<li>Beagle Bone</li>
<li>Parallela</li>
</ul>
</li>
<li>Cloud platforms
<ul>
<li>Amazon</li>
<li>Azure</li>
<li>Digital Ocean</li>
<li>Linode</li>
</ul>
</li>
<li>Payment Providers
<ul>
<li>stripe</li>
<li>braintree</li>
<li>paypal</li>
</ul>
</li>
</ul>
<p>As always feel free to leave a comment, especially if you want to remind
me of an important option that I completely missed when I typed up the
list, as I most certainly did.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing an Update Check for an Application]]></title>
            <link>https://lostindetails.com/articles/Implementing-an-Update-Check-for-an-Application</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/Implementing-an-Update-Check-for-an-Application</guid>
            <pubDate>Fri, 25 Sep 2015 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<h2 id="check-for-updates-for-an-application">“Check for Updates” for an Application</h2>
<h3 id="background">Background</h3>
<p>In this article I explore a simple mechanism to check if an update is
available by querying a server. My use case was that I’ve been writing
a C# Application and I wanted to include a quick “Check for Updates”
functionality that would inform the user if an update is available.</p>
<p>Additionally, I wanted a simple upgrade process, so that I can upload a
new setup file and it’s picked up by the webserver automatically, so
the requirements were quickly formulated:</p>
<h3 id="requirements">Requirements</h3>
<ul>
<li>The client application should be able to detect if a new version is
available</li>
<li>Publishing a new update should be painless</li>
</ul>
<h3 id="formulating-a-plan">Formulating a plan</h3>
<ol>
<li>The Client App reads it’s version number</li>
<li>Client App sends the version number to the Webserver</li>
<li>Webserver compares the version number with the latest available
version and returns the result</li>
<li>Client displays the result and asks the user to upgrade</li>
</ol>
<h3 id="step-0---versioning-the-application">Step 0 - Versioning the Application</h3>
<p>As it turns out, there is a Step 0 associated with this process and that
is versioning the application in the first place.</p>
<p>The simplest way to version your app is probably using the
<code>System.Reflect.AssemblyVersionAttribute</code> as used in the auto-generated
AssemblyInfo.cs file in your application.</p>
<p>I personally prefer to let the build process increment the build and
revision parts of the version, so I’ve changed the use of the
AssemblyVersion attribute in AssemblyInfo.cs to:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#E1E4E8">[</span><span style="color:#F97583">assembly</span><span style="color:#E1E4E8">: </span><span style="color:#B392F0">AssemblyVersion</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">"0.7.*"</span><span style="color:#E1E4E8">)]</span></span></code></pre>
<p>That way, even if I forget to manually increment the version number, the
versions differ between each build which adds an additional safety net
when diagnosing problems.</p>
<p>On top of that I removed the
<code>[assembly: AssemblyFileVersion("1.0.0.0")]</code> declaration, as I prefer to
keep them in sync.</p>
<p>After rebuilding the application I checked the generated version by
right-clicking the file and selecting “Properties” -> “Details”, as
you can see in the screenshot.</p>
<p><img src="/img/propertiesdialog.png" alt=""></p>
<h3 id="step-1---reading-the-application-version">Step 1 - Reading the Application Version</h3>
<p>Reading the version of the Application is a one-liner:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">var</span><span style="color:#B392F0"> version</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> Assembly.</span><span style="color:#B392F0">GetExecutingAssembly</span><span style="color:#E1E4E8">().</span><span style="color:#B392F0">GetName</span><span style="color:#E1E4E8">().Version;</span></span></code></pre>
<h3 id="step-2---sending-the-version-to-the-webserver">Step 2 - Sending the Version to the Webserver</h3>
<p>Sending the version to the webserver and retrieving the result is done
using a simple WebRequest:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">var</span><span style="color:#B392F0"> baseUrl</span><span style="color:#F97583"> =</span><span style="color:#9ECBFF"> "http://yourdomain.com/yourapp"</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">var</span><span style="color:#B392F0"> url</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> Path.</span><span style="color:#B392F0">Combine</span><span style="color:#E1E4E8">(baseUrl, </span><span style="color:#F97583">string</span><span style="color:#E1E4E8">.</span><span style="color:#B392F0">Format</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">"isupdateavailable?v={0}"</span><span style="color:#E1E4E8">, version));</span></span>
<span class="line"><span style="color:#F97583">var</span><span style="color:#B392F0"> request</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> (</span><span style="color:#B392F0">HttpWebRequest</span><span style="color:#E1E4E8">)WebRequest.</span><span style="color:#B392F0">Create</span><span style="color:#E1E4E8">(url);</span></span>
<span class="line"><span style="color:#F97583">if</span><span style="color:#E1E4E8"> (((</span><span style="color:#B392F0">HttpWebResponse</span><span style="color:#E1E4E8">)request.</span><span style="color:#B392F0">GetResponse</span><span style="color:#E1E4E8">()).StatusCode </span><span style="color:#F97583">==</span><span style="color:#E1E4E8"> HttpStatusCode.OK)</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#6A737D">  /* update is available... */</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>The above code snippet assumes that you have a webserver that returns OK
when an update is available. We’ll see about that in the next step. In
a production ready case you might want to use GetResponseAsync and
return an Task.</p>
<h3 id="step-3---the-webserver-compares-versions">Step 3 - The Webserver compares versions</h3>
<p>The webserver retrieves the version from the parameter, creates a
Version object and compares the Version object with that of the current
file.</p>
<p>In my case, I chose to encode the version in the setup file name like
so: ‘setup_0.8.5742.26637.exe’ and read it back in using a regular
expression. My reasons for not using the same process as on the client
were the following:</p>
<ul>
<li>You can upload multiple setup files, which is handy if you want to
be able to keep older versions</li>
<li>As the generated setup file is native code (I am using
<a href="http://nsis.sourceforge.net/Main_Page">NSIS</a> to create the
installer), not a managed assembly, reading the product version
breaks down on a linux server (which I happen to use). The reason
is, that the Product Version is encoded in the PE-Header of the file
and while mono allows reading the version from a .NET assembly it
does not work with a native file as it would on windows.</li>
</ul>
<p>So the code to retrieve the current version looks something like this:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">private</span><span style="color:#F97583"> static</span><span style="color:#B392F0"> Regex</span><span style="color:#B392F0"> SetupFileRegex</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Regex</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">"Setup_(?.*?)</span><span style="color:#79B8FF">\\</span><span style="color:#9ECBFF">.exe"</span><span style="color:#E1E4E8">);</span></span>
<span class="line"><span style="color:#F97583">private</span><span style="color:#B392F0"> Version</span><span style="color:#B392F0"> GetVersionFromFileName</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">string</span><span style="color:#B392F0"> fileName</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  var</span><span style="color:#B392F0"> m</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> SetupFileRegex.</span><span style="color:#B392F0">Match</span><span style="color:#E1E4E8">(fileName);</span></span>
<span class="line"><span style="color:#F97583">  return</span><span style="color:#E1E4E8"> m.Success </span><span style="color:#F97583">?</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Version</span><span style="color:#E1E4E8">(m.Groups[</span><span style="color:#9ECBFF">"Version"</span><span style="color:#E1E4E8">].Value) </span><span style="color:#F97583">:</span><span style="color:#79B8FF"> null</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span>
<span class="line"><span style="color:#F97583">private</span><span style="color:#B392F0"> Version</span><span style="color:#B392F0"> GetLatestVersion</span><span style="color:#E1E4E8">()</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  string</span><span style="color:#E1E4E8">[] </span><span style="color:#B392F0">files</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> Directory.</span><span style="color:#B392F0">GetFiles</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">GetSetupFolder</span><span style="color:#E1E4E8">(), </span><span style="color:#9ECBFF">"Setup_*.exe"</span><span style="color:#E1E4E8">);</span></span>
<span class="line"><span style="color:#F97583">  return</span><span style="color:#E1E4E8"> files.</span><span style="color:#B392F0">Select</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">f</span><span style="color:#F97583"> =></span><span style="color:#F97583"> new</span><span style="color:#E1E4E8"> {</span></span>
<span class="line"><span style="color:#E1E4E8">    File </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> f,</span></span>
<span class="line"><span style="color:#E1E4E8">    Version </span><span style="color:#F97583">=</span><span style="color:#B392F0"> GetVersionFromFileName</span><span style="color:#E1E4E8">(Path.</span><span style="color:#B392F0">GetFileName</span><span style="color:#E1E4E8">(f))</span></span>
<span class="line"><span style="color:#E1E4E8">  })</span></span>
<span class="line"><span style="color:#E1E4E8">  .</span><span style="color:#B392F0">Where</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">f</span><span style="color:#F97583"> =></span><span style="color:#E1E4E8"> f.Version </span><span style="color:#F97583">!=</span><span style="color:#79B8FF"> null</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">  .</span><span style="color:#B392F0">OrderByDescending</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">f</span><span style="color:#F97583"> =></span><span style="color:#E1E4E8"> f.Version)</span></span>
<span class="line"><span style="color:#E1E4E8">  .</span><span style="color:#B392F0">First</span><span style="color:#E1E4E8">()</span></span>
<span class="line"><span style="color:#E1E4E8">  .Version;</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>Returning the correct status code becomes easy then, simply compare the
versions. For example like:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">var</span><span style="color:#B392F0"> clientVersion</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> Version</span><span style="color:#E1E4E8">(</span><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">.Request.Query[</span><span style="color:#9ECBFF">"v"</span><span style="color:#E1E4E8">]);</span></span>
<span class="line"><span style="color:#F97583">  var</span><span style="color:#B392F0"> latestVersion</span><span style="color:#F97583"> =</span><span style="color:#B392F0"> GetLatestVersion</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#F97583">  return</span><span style="color:#E1E4E8"> clientVersion </span><span style="color:#F97583">&#x3C;</span><span style="color:#E1E4E8"> latestVersion </span><span style="color:#F97583">?</span><span style="color:#E1E4E8"> HttpStatusCode.OK </span><span style="color:#F97583">:</span><span style="color:#E1E4E8"> HttpStatusCode.NotFound;</span></span></code></pre>
<p>In a solid web framework, returning the status code should be as easy as
that. I personally use <a href="http://nancyfx.org/">NancyFx</a> for all Serverside
coding and warmly recommend it, the
<a href="https://github.com/NancyFx/Nancy/wiki/Introduction#the-super-duper-happy-path">SDHP</a>
is true, it’s really a pleasure to work with.</p>
<h3 id="step-4---display-update-available">Step 4 - Display “Update available”</h3>
<p>In my use case, I chose to simply display an “update available” button
in my application that takes the user to the download page, which I find
is the most flexible solution, as I can keep the updating process itself
and change and release notes separate from the application.</p>
<p>Take care,<br>
Martin</p>
<h3 id="references">References</h3>
<ul>
<li>NSIS (null soft scriptable install system)
<a href="http://nsis.sourceforge.net/Main_Page">http://nsis.sourceforge.net/Main_Page</a></li>
<li>NancyFx <a href="http://nancyfx.org/">http://nancyfx.org/</a></li>
<li>SDHP (super duper happy path)
<a href="https://github.com/NancyFx/Nancy/wiki/Introduction#the-super-duper-happy-path">https://github.com/NancyFx/Nancy/wiki/Introduction#the-super-duper-happy-path</a></li>
</ul>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AvalonDock 2.0 with MVVM]]></title>
            <link>https://lostindetails.com/articles/AvalonDock-2.0-with-MVVM</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/AvalonDock-2.0-with-MVVM</guid>
            <pubDate>Mon, 07 Sep 2015 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<h2 id="avalondock-20-and-mvvm">AvalonDock 2.0 and MVVM</h2>
<h3 id="background">Background</h3>
<p>When I was writing an application, I came to the conclusion that a
flexible GUI Layout that enables the user to rearrange the windows to
fit their needs would be the best option. I wanted an interface that is
as flexible as Visual Studio itself when it comes to window positioning.</p>
<h3 id="docking-libraries">Docking Libraries</h3>
<p>Back in the days, I’ve already used a commercial solution, but that was
years ago and I didn’t have a license for a current version. That’s
why I took a look at our all <a href="http://stackoverflow.com/questions/344205/recommendations-on-a-wpf-docking-library">favourite
site</a>
and so came to find AvalonDock.</p>
<h3 id="avalondock">AvalonDock</h3>
<p>AvalonDock is a Wpf Docking Library that provides your windows app with
docking windows just like Visual Studio. The library has a lot going for
it: it’s available as a nuget package, totally free and it comes with
MVVM support (which I deeply care about), at least the <a href="https://avalondock.codeplex.com/">codeplex
page</a> claims it does.</p>
<h3 id="getting-avalondock">Getting AvalonDock</h3>
<p>There a two options to get AvalonDock, either grab it from the codeplex
site under downloads or get it via nuget. While I prefer nuget, this
time you need to take care to select the correct package, as there is
also a pay-only version available as well as an older, out of date
version. It’s simply named ‘AvalonDock’, take a look at the
screenshot below:</p>
<p><img src="/img/AvalonDock_nuget_package.png" alt=""></p>
<p>While the library does what I want, I found it’s documentation quite
lacking - the tutorials, except for one, are hopelessly outdated - they
refer to the version 1.3 while the current version (as of this writing)
is 2.0. As almost none of the classes, properties or methods are the
same, they are more misleading than do any good.</p>
<p>Considering that the last comment that asks for an update of the
documentation was written in 2012 and has gone unanswered, I wouldn’t
hold my breath for an update anytime soon.</p>
<p>So heading back to our favorite site, search reveals promising
<a href="http://stackoverflow.com/questions/28457026/how-to-use-mvvm-in-avalondock-2-0">questions</a>
but lacking answers: consisting of a ‘let me google that for you’
link, followed by a link to an article about the version 1.3 or <a href="http://stackoverflow.com/questions/23406451/sample-code-to-show-how-to-use-avalondock-in-an-mvvm-application">another
one</a>
with answers that link to the same outdated tutorial and one that links
to the codeplex documentation page, which got us started hunting for
information in the first place, all apparently posted by someone
point-hungry that skipped reading the whole question.</p>
<h3 id="finding-an-example-app">Finding an example app</h3>
<p>After some looking around I found an example app back on the CodePlex
site - it’s not under downloads, there you’ll only find the library
and some themes - but under <a href="https://avalondock.codeplex.com/SourceControl/latest#">source
code</a> and you can
get it when clicking the Download Button.</p>
<p>Now we’re off to a good start - we can see some of the properties in
use, even in a somewhat MVVMish use.</p>
<h3 id="putting-it-to-use">Putting it to use</h3>
<p>After studying the MVVM example, I knew how to bind the DocumentManager
against a Document Collection, and wanted it to use it in a way that
allows me to just update the properties of our viewmodels and have the
view reflect those changes and vice-versa. That would come in handy for
opening and closing windows and updating the title and so on.</p>
<p>First of all, I wanted to use the IsChecked property of the menu item to
open and close the DockWindow and so on, as shown in the screenshot
below.</p>
<p><img src="/img/AvalonDock_mvvm_example.png" alt="AvalonDock using Mvvm Bindings to close and open
windows"></p>
<p>The following xaml code snippet shows how I wired up the View to
ViewModel binding with a style:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="html"><code><span class="line"><span style="color:#E1E4E8">&#x3C;</span><span style="color:#FDAEB7;font-style:italic">Window</span><span style="color:#B392F0"> ...</span></span>
<span class="line"><span style="color:#B392F0">  xmlns:dock</span><span style="color:#E1E4E8">=</span><span style="color:#9ECBFF">"http://schemas.xceed.com/wpf/xaml/avalondock"</span></span>
<span class="line"><span style="color:#B392F0">  xmlns:dockctrl</span><span style="color:#E1E4E8">=</span><span style="color:#9ECBFF">"clr-namespace:Xceed.Wpf.AvalonDock.Controls;assembly=Xceed.Wpf.AvalonDock"</span></span>
<span class="line"><span style="color:#E1E4E8">  ></span></span>
<span class="line"><span style="color:#E1E4E8">  ...</span></span>
<span class="line"><span style="color:#E1E4E8">  &#x3C;</span><span style="color:#FDAEB7;font-style:italic">dock:DockingManager</span><span style="color:#B392F0"> Grid.Row</span><span style="color:#E1E4E8">=</span><span style="color:#9ECBFF">"1"</span></span>
<span class="line"><span style="color:#B392F0">                        DataContext</span><span style="color:#E1E4E8">=</span><span style="color:#9ECBFF">"{Binding DockManagerViewModel}"</span></span>
<span class="line"><span style="color:#B392F0">                        DocumentsSource</span><span style="color:#E1E4E8">=</span><span style="color:#9ECBFF">"{Binding Documents}"</span><span style="color:#E1E4E8"> ></span></span>
<span class="line"></span>
<span class="line"><span style="color:#E1E4E8">    &#x3C;</span><span style="color:#FDAEB7;font-style:italic">dock:DockingManager.LayoutItemContainerStyle</span><span style="color:#E1E4E8">></span></span>
<span class="line"><span style="color:#6A737D">      &#x3C;!-- you can add additional bindings from the layoutitem to the DockWindowViewModel --></span></span>
<span class="line"><span style="color:#E1E4E8">      &#x26;ltStyle TargetType="{x:Type dockctrl:LayoutItem}"></span></span>
<span class="line"><span style="color:#E1E4E8">        &#x3C;</span><span style="color:#FDAEB7;font-style:italic">Setter</span><span style="color:#B392F0"> Property</span><span style="color:#E1E4E8">=</span><span style="color:#9ECBFF">"Title"</span><span style="color:#B392F0"> Value</span><span style="color:#E1E4E8">=</span><span style="color:#9ECBFF">"{Binding Model.Title}"</span><span style="color:#E1E4E8"> /></span></span>
<span class="line"><span style="color:#E1E4E8">        &#x3C;</span><span style="color:#FDAEB7;font-style:italic">Setter</span><span style="color:#B392F0"> Property</span><span style="color:#E1E4E8">=</span><span style="color:#9ECBFF">"CloseCommand"</span><span style="color:#B392F0"> Value</span><span style="color:#E1E4E8">=</span><span style="color:#9ECBFF">"{Binding Model.CloseCommand}"</span><span style="color:#E1E4E8"> /></span></span>
<span class="line"><span style="color:#E1E4E8">        &#x3C;</span><span style="color:#FDAEB7;font-style:italic">Setter</span><span style="color:#B392F0"> Property</span><span style="color:#E1E4E8">=</span><span style="color:#9ECBFF">"CanClose"</span><span style="color:#B392F0"> Value</span><span style="color:#E1E4E8">=</span><span style="color:#9ECBFF">"{Binding Model.CanClose}"</span><span style="color:#E1E4E8"> /></span></span>
<span class="line"><span style="color:#E1E4E8">      &#x3C;/</span><span style="color:#FDAEB7;font-style:italic">Style</span><span style="color:#E1E4E8">></span></span>
<span class="line"><span style="color:#E1E4E8">    &#x3C;/</span><span style="color:#FDAEB7;font-style:italic">dock:DockingManager.LayoutItemContainerStyle</span><span style="color:#E1E4E8">></span></span>
<span class="line"></span>
<span class="line"><span style="color:#E1E4E8">  &#x3C;/</span><span style="color:#FDAEB7;font-style:italic">dock:DockingManager</span><span style="color:#E1E4E8">></span></span>
<span class="line"><span style="color:#E1E4E8">&#x3C;/</span><span style="color:#FDAEB7;font-style:italic">Window</span><span style="color:#E1E4E8">></span></span></code></pre>
<p>As figuring out how to use the MVVM support was harder than expected and
in case anyone else needs to do that, I’ve uploaded a complete example
app to <a href="https://github.com/8/AvalonDockMVVM">github</a> that should get you
started.</p>
<p>Take care,<br>
Martin</p>
<h3 id="references">References</h3>
<ul>
<li>My Avalon Dock Mvvm Example on Github
<a href="https://github.com/8/AvalonDockMVVM">https://github.com/8/AvalonDockMVVM</a></li>
<li>AvalonDock CodePlex <a href="https://avalondock.codeplex.com/">https://avalondock.codeplex.com/</a></li>
<li>Stackoverflow Docking Libraries
<a href="http://stackoverflow.com/questions/344205/recommendations-on-a-wpf-docking-library">http://stackoverflow.com/questions/344205/recommendations-on-a-wpf-docking-library</a></li>
</ul>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[M-Files mass file deletion]]></title>
            <link>https://lostindetails.com/articles/M-Files-mass-file-deletion</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/M-Files-mass-file-deletion</guid>
            <pubDate>Sun, 19 Jul 2015 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<h2 id="deleting-thousands-of-files-from-m-files">Deleting thousands of files from M-Files</h2>
<h3 id="summary">Summary</h3>
<p>In this article I am discussing mass file deletion from M-Files and why
this is sometimes useful and conclude with a C# implementation that is
able to delete files based on their object type or class.</p>
<h3 id="use-cases">Use Cases</h3>
<p>When you are inserting a lot of files you probably need to delete a lot
of files as well. In my case, as I’ve been writing the importer I am
using unit tests to test if the insertion works and if it does, I end up
with a lot of new files in my M-Files vault. So to make the process of
insertion repeatable, I needed a way to reset the vault back to it’s
former state.</p>
<p>If you’d be working with a database, you’d usually wrap the insertion
into a transaction that gets rolled back automatically when you’re
finished with the test, but sadly M-Files lacks support for this
concept.</p>
<p>One option to achieve this is to restore a backup of the vault that was
taken before the insertion process. Another way is deletion of the
inserted files. Both having different trade-offs. In this installment I
am going to visit deleting objects from M-Files.</p>
<p>Another use case comes up if you are creating a new vault by copying all
data, but you want to keep only a subset of it and get rid of the rest.</p>
<p>Or you’ve just done a mass import of files and noticed that you’ve
missed specifying a property or some other error and the quickest way to
solve the problem is to repeat the insertion process, but first you need
to get rid of the files you just imported.</p>
<h3 id="deletion-is-not-what-you-think">Deletion is not what you think</h3>
<p>Ususally deletion means removal of the files, but M-Files treats
deletion differently, it just marks the files in question as deleted.
They are still held in the M-Files Vault and can still be retrieved and
therefore still take away resources like memory and disk space.</p>
<p>Instead of deleting files, the complete removal of files is achieved by
destroying files.</p>
<h3 id="destroying-objects">Destroying Objects</h3>
<p>Destroying objects in M-Files is independent from deletion - you do not
need to delete an object before you destroy it, you can just go ahead
and destroy it and be done with it.</p>
<h3 id="steps-involved-in-destroying-an-object">Steps involved in destroying an object</h3>
<ol>
<li>Login to the vault</li>
<li>Retrieve the <code>ObjID</code> of the object you want to destroy</li>
<li>call <code>Vault.ObjectOperations.DestroyObject()</code> and supply the ObjID</li>
</ol>
<h4 id="login-to-the-vault">Login to the vault</h4>
<p>The login sequence is straightforward:</p>
<ol>
<li>Create an <code>MFilesServerApplication</code> instance</li>
<li>Call it’s <code>Connect()</code> method and supply your credentials</li>
<li>Iterate through it’s vaults and login to your target vault by
calling it’s <code>LogIn()</code> method.</li>
</ol>
<h4 id="retrieve-the-objid">Retrieve the ObjID</h4>
<p>There are plenty of options to retrieve the ObjID of the object or
objects you want to destroy.</p>
<ul>
<li>Maybe you already know the Id of the object. That would be the case
if you inserted the object before and stored the Id of the newly
created object somewhere.</li>
<li>You may want to execute a view and delete the objects it returns.</li>
<li>Or you may want to search for objects based on some common criteria,
like their object type or class.</li>
</ul>
<h4 id="searching-for-objects">Searching for Objects</h4>
<p>Searching for Objects in M-Files can be achieved by using the
<code>SearchCondition</code> class. The following examples demonstrate the use of
the <code>SearchCondition</code> class to look for objects that correspond to a
specific object type or class.</p>
<h5 id="search-by-objecttype">Search by ObjectType</h5>
<p>The following code snippet creates a <code>SearchCondition</code> instance that
looks for all objects that are of the specified objectType.</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8;overflow-x:auto" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#6A737D">/* find all files with the specified object type */</span></span>
<span class="line"><span style="color:#F97583">var</span><span style="color:#B392F0"> searchCondition</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> SearchCondition</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">searchCondition.ConditionType </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> MFConditionType.MFConditionTypeEqual;</span></span>
<span class="line"><span style="color:#E1E4E8">searchCondition.Expression.DataStatusValueType </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> MFStatusType.MFStatusTypeObjectTypeID;</span></span>
<span class="line"><span style="color:#E1E4E8">searchCondition.TypedValue.</span><span style="color:#B392F0">SetValue</span><span style="color:#E1E4E8">(MFDataType.MFDatatypeLookup, objectTypeId);</span></span></code></pre>
<h5 id="search-by-class">Search by class</h5>
<p>In the following code snippet a <code>SearchCondition</code> instance is created
that allows searching for objects that belong to the specified class.</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8;overflow-x:auto" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#6A737D">/* find all files with the specified class */</span></span>
<span class="line"><span style="color:#F97583">var</span><span style="color:#B392F0"> searchCondition</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> SearchCondition</span><span style="color:#E1E4E8">();</span></span>
<span class="line"><span style="color:#E1E4E8">searchCondition.ConditionType </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> MFConditionType.MFConditionTypeEqual;</span></span>
<span class="line"><span style="color:#E1E4E8">searchCondition.Expression.DataPropertyValuePropertyDef </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> (</span><span style="color:#F97583">int</span><span style="color:#E1E4E8">)MFBuiltInPropertyDef.MFBuiltInPropertyDefClass;</span></span>
<span class="line"><span style="color:#E1E4E8">searchCondition.TypedValue.</span><span style="color:#B392F0">SetValue</span><span style="color:#E1E4E8">(MFDataType.MFDatatypeLookup, classId);</span></span></code></pre>
<h5 id="getting-results">Getting results</h5>
<p>After creating a SearchCondition that looks for the objects, we need to
execute the search to retrieve the results.</p>
<p>This is done by calling
<code>Vault.ObjectSearchOperations.SearchForObjectsByConditionsEx()</code> and
supplying the <code>SearchConditions</code>.</p>
<p>The <code>SearchForObjectsByConditionsEx()</code> method returns an instance of the
<code>ObjectSearchResults</code> class.</p>
<p>Enumerating the ObjectSearchResults we find <code>ObjectVersion</code> instances
and it’s <code>ObjVer.ObjID</code> property that we can use as a parameter to the
aforementioned <code>DestroyObject()</code> method.</p>
<p><em>Hint</em></p>
<p>One Advantage of calling the Ex version is that you can specify
additional search parameters, like <code>MaxResultCount</code> and
<code>SearchTimeoutInSeconds</code> which is pretty important if you are dealing
with a lot of files. Otherwise you might end up with an incomplete query
and may overlook files that exceeded the maximum result count.</p>
<h3 id="putting-it-all-together">Putting it all together</h3>
<p>I’ve put together a small C# Console Application that implements the
whole process and <a href="http://github.com/8/MFilesDeleter">uploaded it to
github</a>.</p>
<h4 id="screenshots">Screenshots</h4>
<p><img src="/img/MFilesDeleter_listing_objects.png" alt="Screenshot of MFilesDeleter listing objects by class
name" title="Listing objects by class name"/>
<img src="/img/MFilesDeleter_destroying_objects.png" alt="Screenshot of MFilesDeleter destroying objects by class
name" title="Destroying objects by class name"/></p>
<h3 id="references">References</h3>
<ul>
<li><a href="http://github.com/8/MFilesDeleter">M-Files Deleter on github
(http://github.com/8/MFilesDeleter)</a></li>
</ul>
<p>If you have any questions or comments, feel free to leave a comment
below or e-Mail me and thank you for reading!</p>
<p>Take care,<br/>
Martin</p>
<div><div class="bg-primary-200 border-l-4 px-2 py-2 border-primary-800 flex"><div class="px-2"><h3 class="font-semibold text-lg pt-2 pb-1">Vault Exporter</h3><p>I&#39;ve started working on a commercial Software for exporting Documents from M-Files at: <br><a href="http://vault-exporter.com">https://vault-exporter.com</a></p><p class="text-sm text-primary-800 italic"><span class="font-bold">Note</span>: Not all features are fixed yet, so if you want to join the discussion or you just want to be notified when it launches, please head over and join the <a href="https://m-files-exporter.com">mailing list</a> to receive an update when it launches.</p></div></div></div>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[M-Files mass file import Part II]]></title>
            <link>https://lostindetails.com/articles/M-Files-mass-file-import-Part-II</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/M-Files-mass-file-import-Part-II</guid>
            <pubDate>Thu, 09 Jul 2015 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<h2 id="importing-files-using-the-native-api">Importing files using the native API</h2>
<h3 id="background">Background</h3>
<p>The native API of M-Files is pretty powerful - everything you can
achieve by using the admin client or the client tools you can do
programmatically using the API.</p>
<p>It’s not available as a separate download, but is installed when you
install M-Files.</p>
<h3 id="requirements">Requirements</h3>
<h4 id="creating-a-new-object">Creating a new object</h4>
<p>Inserting data into an existing M-Files Vault is pretty straightforward.
To Create a new object instance, you need 4 things that can easily be
done using the API:</p>
<ol>
<li>The Id of the ObjectType you want to insert</li>
<li>A list of all properties that are required</li>
<li>A working connection to a vault</li>
<li>Optional: Source Files (= ordinary files from the filesystem) that
will be attached</li>
</ol>
<p>1. and 2. are dependent on the metadata of the vault, whereas 3. and 4.
work the same for every object or vault.</p>
<h4 id="an-intimate-knowledge-of-the-metadata-structure">An intimate knowledge of the metadata structure</h4>
<p>As mentioned above, inserting a new object requires knowledge about the
structure of the metadata. For example, if you want to create a document
instance and the class you are trying to create has a required Date
property, then you need to add a property named Date of type Date so
that those requirements are fulfilled when you create a new document
instance.</p>
<p>This tightly couples creating instances with your metadata structure -
if for example you decided to rename a property of your document, you
need to update your code to mirror that change.</p>
<p>In my case, which I argue is probably the default, classes and
properties are not set it stone and will evolve in the engagement, so I
thought about coming up with a better solution.</p>
<h4 id="making-it-flexible">Making it flexible</h4>
<p>Now the thing is, the API supports accessing the metadata as well - this
means that you can enumerate object types, classes and their properties
and you can find out what DataType backs a specific property and you can
also enumerate value lists.</p>
<p>With this in mind, it’s possible to decouple the insertion process from
the specifics of the structure, as the structure can be reflected upon
at insertion time.</p>
<p>This not only generalizes the code doing the insertion, it also
decouples it from knowing anything about the metadata in advance and
therefore makes reuse possible.</p>
<h4 id="making-it-transparent">Making it transparent</h4>
<p>When you’re inserting a ton of files, you’ll need reporting - you need
to know which files were tried to import and which of those succeeded
and which of those did not.</p>
<p>Further, for those files who failed to import, you’d want an error
message, that tells you want went wrong so that you can go back and fix
it.</p>
<h4 id="iterative-approach">Iterative approach</h4>
<p>As the next thing, you’d want to fix those errors quickly and retry the
process, skipping those files that did already import successful (so to
not create duplicates), but retry those that failed before and update
their status again.</p>
<p>Fixing those errors should be made easy, as well as repeating the
process, so that you are able to make progress quickly.</p>
<h3 id="the-solution">The Solution</h3>
<h4 id="putting-it-all-together">Putting it all together</h4>
<p>For those reasons I chose to write a Csv Importer that is able to insert
new object instances by reading in a Comma separated file.</p>
<p>The first row holds the column headers. The column headers consist of
the object type, class name and all property names. Each following row
represents an item that will be inserted.</p>
<p>The insertion process adds two additional columns - the first holding
the Id of a successfully imported item, the second holds the import
status, that can either be success or an error message. A backup of the
input file is saved before insertion takes place, so that those files
can be compared for a granular analysis.</p>
<p>The importer itself is implemented as a console application, which makes
automating and repeating the process very easy. For example hitting the
up arrow key and pressing Enter.</p>
<p>With this solution we achieve the following goals:</p>
<ul>
<li>
<p><strong>Flexible</strong></p>
<div>
<p>The importer can be reused across vaults and you can use any kind of
tool to create the csv file.</p>
</div>
</li>
<li>
<p><strong>Transparent</strong></p>
<div>
<p>The csv file is updated with the results - you can clearly see what
worked and what did not.</p>
</div>
</li>
<li>
<p><strong>Iterative</strong></p>
<div>
<p>You can easily update the data with excel / calc and start the
import again.</p>
</div>
</li>
<li>
<p><strong>Automatable</strong></p>
<div>
<p>The commandline application lends itself to automation without any
user interaction.</p>
</div>
</li>
</ul>
<p><img src="/img/MFilesImporterScreenshot.png" alt="Screenshot of the M-Files Commandline Csv
Importer" title="Screenshot of the M-Files Commandline Csv Importer"></p>
<h4 id="editing-the-csv-file">Editing the Csv File</h4>
<p>Viewing and editing the Csv is easy as there are a couple of editors out
there.</p>
<p>For example Microsoft Excel or the free LibreOffice Calc are well known
tools that make navigating and updating the Csv easy as you can filter
for Error or Success and bulk edit similiar rows.</p>
<h4 id="additional-note-about-performance">Additional Note about performance</h4>
<p>Generalized and flexible code is usually not as performant as code that
can take advantage of special cases. In the software development
process, performance is often the stepchild - first comes correctness
and that’s that. In this case performance was an important factor,
considering the sheer amount of files that are being inserted. If you
use too much precious time inserting each file, then those seconds
really do add up!</p>
<p>Luckily, most of the time lost in the insertion process proofed to be
lookups - lookups of text strings to find their corresponding object in
the vault and use it’s Id as a property value. By caching those values
significant performance improvements could be reached. The drawback
being that changes in the metadata won’t be picked up mid-insertion.</p>
<h4 id="update-official-m-files-csv-import-tool">Update: Official M-Files Csv Import Tool</h4>
<p>In the meantime M-Files has published an Csv-Importer themselves, who
according to their readme acts in a similiar way, except that it’s an
GUI application, which comes with different tradeoffs and they don’t
seem to update the csv, they just create an error output and a license
that does not allow redistribution of the tool.</p>
<h4 id="update-ii-sourcecode-for-mfilesimporter-available">Update II: Sourcecode for MFilesImporter available</h4>
<p>I finally had the time to push some code to github! If you’re brave,
head over to the <a href="https://github.com/8/MFilesImporter">github repo</a> and
take a look.</p>
<h3 id="references">References</h3>
<ul>
<li><a href="https://en.wikipedia.org/wiki/Comma-separated_values">Commma Separated Values
(https://en.wikipedia.org/wiki/Comma-separated_values)</a></li>
<li><a href="https://www.libreoffice.org/discover/calc/">Libre Office Calc
(https://www.libreoffice.org/discover/calc/)</a></li>
<li><a href="https://github.com/8/MFilesImporter">Github Repo
(https://github.com/8/MFilesImporter)</a></li>
</ul>
<p>If you have a question feel free to email me or write a comment and
thank you for reading!</p>
<p>Take care,<br>
Martin</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[M-Files Class Exporter]]></title>
            <link>https://lostindetails.com/articles/M-Files-Class-Exporter</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/M-Files-Class-Exporter</guid>
            <pubDate>Fri, 26 Jun 2015 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<h2 id="an-alternative-class-csv-export">An alternative Class CSV Export</h2>
<h3 id="overview">Overview</h3>
<p>In this article I’ll show an alternative way to take a look at the
class hierarchy in M-Files by exporting all classes and their properties
into a single CSV-file (Comma Separated Value) so that they can be
reviewed in Excel.</p>
<h3 id="intro">Intro</h3>
<p>Usually when you start to work on a project, you’ll want to get an
overview first. In a M-File project with a lot of custom metadata, you
probably want to know about the classes and their properties.</p>
<h3 id="m-files-admin">M-Files Admin</h3>
<p>The first and most common way is certainly firing up the M-Files Admin
and taking a look at all classes and properties.</p>
<p>While the admin interface works great for interactively exploring and
editing the classes, there are also some drawbacks to this method.</p>
<ul>
<li>You need to be an admin</li>
<li>There is no central view that allows viewing all classes and their
properties at a glance</li>
<li>Interactive nature is not a good fit for presentations or working
with clients or offline review</li>
</ul>
<h3 id="export-to-text-format">Export to Text Format</h3>
<p>One logical approach would be to export the metadata into a text format.
That way you can get the following benefits:</p>
<ul>
<li>you can use it offline, by printing it out or e-Mailing it to
multiple persons</li>
<li>you don’t need admin access to the server, you don’t even need a
M-Files installation to view it</li>
<li>you can annotate it easily</li>
</ul>
<p>An export to a Comma Separated Value File seems like a good choice, as
it supports structured data and there are a lot of client tools to view
and edit it.</p>
<h3 id="the-built-in-solution">The built-in solution</h3>
<p>Luckily M-Files comes with an Export List function that does exactly
that, it allows the creation of a csv file with all classes as shown in
the screenshot below.</p>
<p>The Admin interface allows exporting a list of all classes, by using the
context-menu and clicking ‘Export List…’</p>
<p><img src="/img/MFilesAdmin-ExportList.png" alt="M-Files Screenshot of the Admin Interface 'Export as
List...'"/></p>
<p>The export creates a file whose content mirrors the columns that are
shown on the right.</p>
<p>So for the hierarchical view, you only get a list of the object types
and in the Flat View you’ll get at least a list of classes if you
right-click ‘classes’ and choose ‘Export as List…’ - but that’s
not what I wanted.</p>
<h3 id="what-i-needed">What I needed</h3>
<p>What I needed was a list of all classes and all their properties, like
the following:</p>
<p>Class</p>
<p>Property</p>
<p>Type</p>
<p>Required</p>
<p>Agenda</p>
<p>Name or title</p>
<p>Text</p>
<p>True</p>
<p>Agenda</p>
<p>Event date</p>
<p>Date</p>
<p>False</p>
<p>…</p>
<p>Assignment</p>
<p>Name or title</p>
<p>Text</p>
<p>True</p>
<p>Assignment</p>
<p>Assignment description</p>
<p>Multiline Text</p>
<p>False</p>
<p>…</p>
<p>With a list like that, I can sit down with a client and really get to
work and answer the important questions like:</p>
<ul>
<li>What properties are missing?</li>
<li>Which are of the wrong type?</li>
<li>Should this property be required or not?</li>
<li>How can we fill this specific property from existing data?</li>
</ul>
<p>while taking notes and making annotations.</p>
<h3 id="the-solution">The solution</h3>
<p>To solve that problem I wrote a short commandline tool that exports the
classes and their properties to a csv file.</p>
<h4 id="where-to-get-it">Where to get it</h4>
<p>You can download it here:
<a href="/mfiles/MFilesExporter.zip" title="MFilesExporter.zip">MFilesExporter.zip</a></p>
<h4 id="how-to-use-it">How to use it</h4>
<ul>
<li>
<p>unpack the files into a folder</p>
</li>
<li>
<p>open the cmd prompt by pressing Win+R, type ‘cmd’ and hit enter.</p>
</li>
<li>
<p>change to the directory where you unpacked the files, eg. if you
unpacked the files into the folder c:\users\test\documents type</p>
<p>cd c:\users\test\documents</p>
</li>
<li>
<p>Start it from the commandline:</p>
<p>MFilesExporter.exe -v “My Vault” -e</p>
</li>
</ul>
<p><img src="/img/MFilesExporterScreenshot.png" alt title="MFilesExporter Screenshot"/></p>
<h4 id="example-output">Example Output</h4>
<p>When you run it over ‘My Vault’ it produces <a href="/mfiles/MFilesClassExportMyVault.csv">this CSV
File</a></p>
<p>The following screenshot shows the first few rows of the generated file:</p>
<p><img src="/img/MFilesExportCsvScreenshot.png" alt title="MFilesExporter Csv Screenshot"/></p>
<p>If you find this tool useful or if you found a problem or have a feature
suggestion, please feel free to leave a comment. Thank you!</p>
<div><div class="bg-primary-200 border-l-4 px-2 py-2 border-primary-800 flex"><div class="px-2"><h3 class="font-semibold text-lg pt-2 pb-1">Vault Exporter</h3><p>I&#39;ve started working on a commercial Software for exporting Documents from M-Files at: <br><a href="http://vault-exporter.com">https://vault-exporter.com</a></p><p class="text-sm text-primary-800 italic"><span class="font-bold">Note</span>: Not all features are fixed yet, so if you want to join the discussion or you just want to be notified when it launches, please head over and join the <a href="https://m-files-exporter.com">mailing list</a> to receive an update when it launches.</p></div></div></div>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[M-Files mass file import Part I]]></title>
            <link>https://lostindetails.com/articles/M-Files-mass-file-import-Part-I</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/M-Files-mass-file-import-Part-I</guid>
            <pubDate>Thu, 18 Jun 2015 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<h2 id="importing-tens-of-thousand-of-files-in-m-files">Importing tens of thousand of files in M-Files</h2>
<h3 id="overview">Overview</h3>
<p>This is the first part of blog series where I talk about a recent
project working with M-Files. I will publish the next parts on my blog
as well.</p>
<h3 id="prelude">Prelude</h3>
<p>In a recent project, I was helping a client importing tens of thousand
of files into M-Files. <a href="http://m-files.com">M-Files</a> is an information
management solution for documents and other information.</p>
<h4 id="m-files-in-a-nutshell">M-Files in a nutshell</h4>
<p>M-Files allows you to create, edit and search for objects, which are
instances of classes with certain properties. Usually an administrator
manages the classes and users manage instances of those classes.</p>
<p>A class instance may have files attached, but they can also consist of
only metadata, depending on the properties of it’s class.</p>
<p>M-Files runs on Windows, comes with a server component and client
components (eg. an explorer extension), a web interface, APIs and
documentation.</p>
<h3 id="the-requirement">The Requirement</h3>
<p>As the schema was already finished, that is, all classes were already
defined, the client needed a way to import tens of thousands of files
from their NAS into M-Files and attach the correct metadata. As the
number of files was really big, manually importing and tagging the files
was no option, so that’s why they contacted me.</p>
<h3 id="setting-up-a-development-environment">Setting up a development environment</h3>
<p>So first things first, I started by setting up a new test environment,
where I could develop the solution without effecting the production
system. As you can download a fully functional trial version of all
components from their website, the only thing I was missing was getting
the schemas and the files from the client.</p>
<p>Early on we decided, that the best option to tag the files were based on
their full file path, as the customer used a naming scheme for their
files and folder structure. This was fortunate, as I could skip a
content analysis of the files, their full path would hold all relevant
information. This meant, that I didn’t need a full copy of all files -
just the filepath was sufficient.</p>
<p>This solved two problems at once:</p>
<ul>
<li>Getting full access to sensitive client data</li>
<li>Copying terabytes of data or manipulating the production environment</li>
</ul>
<p>As the NAS was running on a linux box, I wrote a short script that
dumped all the names of the files that they wanted to import into a text
file.</p>
<p>I then wrote a commandline tool that used that list to recreate the
files on the virtual machine, with the difference being, that each file
has no content, it’s size is 0 bytes.</p>
<p>Now the development environment was setup - even the files that I wanted
to import would look like they did to a client in the production
environment.</p>
<p>So setting up my development environment looked like this:</p>
<ul>
<li>Download M-Files</li>
<li>Spin up a new windows-based virtual machine</li>
<li>Install M-Files on the virtual machine</li>
<li>Create a backup of the customers vault</li>
<li>Restore the backup of the vault on my virtual machine</li>
<li>Create a list of files that the client wanted to import</li>
<li>Recreate those files on development environment</li>
</ul>
<h3 id="getting-to-work">Getting to work</h3>
<p>With the setup out of the way, I could now get to work on the solution.</p>
<p>M-Files supports a few APIs, including:</p>
<ul>
<li>Native API</li>
<li>Web API</li>
<li>UI Extensibility Framework</li>
</ul>
<p>In this case, the natural choice was the more mature native API, which
is ActiveX powered, as there is no requirement for a GUI integration and
the superior speed advantage alone disqualifies the Web API. The M-Files
native API comes with a .NET wrapper that makes interacting with M-Files
both fast and takes away the pain of interoperating with COM objects,
thereby reducing the cost of iteration. The native api is well
documented - the documentation is included in the installation, in case
you didn’t find it online.</p>
<h3 id="stay-tuned-for-part-ii">Stay tuned for Part II</h3>
<p>In the next part I will post about how I used the M-Files API and how
the solution I came up with looked like…</p>
<p>If you have any questions, please feel free to leave a comment here and
thank you for reading!</p>
<p>Take care,<br/>
Martin</p>
<div><div class="bg-primary-200 border-l-4 px-2 py-2 border-primary-800 flex"><div class="px-2"><h3 class="font-semibold text-lg pt-2 pb-1">Vault Exporter</h3><p>I&#39;ve started working on a commercial Software for exporting Documents from M-Files at: <br><a href="http://vault-exporter.com">https://vault-exporter.com</a></p><p class="text-sm text-primary-800 italic"><span class="font-bold">Note</span>: Not all features are fixed yet, so if you want to join the discussion or you just want to be notified when it launches, please head over and join the <a href="https://m-files-exporter.com">mailing list</a> to receive an update when it launches.</p></div></div></div>
<h3 id="resources">Resources</h3>
<ul>
<li><a href="http://m-files.com">M-Files (http://m-files.com)</a></li>
<li><a href="http://www.m-files.com/en/api">M-Files APis
(http://www.m-files.com/en/api)</a></li>
<li><a href="http://virtualbox.org">Virtual Box (http://virtualbox.org)</a></li>
</ul>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing INotifyPropertyChanged]]></title>
            <link>https://lostindetails.com/articles/Implementing-INotifyPropertyChanged</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/Implementing-INotifyPropertyChanged</guid>
            <pubDate>Fri, 12 Jun 2015 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<h2 id="an-everyday-task">An everyday task</h2>
<p>If you’ve written some MVVM Wpf Application, chances are you’ve
probably implemented the interface INotifyPropertyChanged a couple of
times. In this post, I am going to talk about different options for
implementing this simple interface.</p>
<p>The interface looks like this:</p>
<p>INotifyPropertyChanged</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">interface</span><span style="color:#B392F0"> INotifyPropertyChanged</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  event</span><span style="color:#B392F0"> PropertyChangedEventHandler</span><span style="color:#B392F0"> PropertyChanged</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<h2 id="the-requirement">The Requirement</h2>
<p>Now consider implementing a class that has a simple property that raises
the PropertyChanged event when it changes. Let’s specify the
capabilities of the class using the following interface:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">interface</span><span style="color:#B392F0"> IChangeNotifier</span><span style="color:#E1E4E8"> : </span><span style="color:#B392F0">INotifyPropertyChanged</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  int</span><span style="color:#B392F0"> Value</span><span style="color:#E1E4E8"> { </span><span style="color:#F97583">get</span><span style="color:#E1E4E8">; </span><span style="color:#F97583">set</span><span style="color:#E1E4E8">; }</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<h2 id="a-straightforward-implementation">A straightforward implementation</h2>
<p>Let’s take a stab at it with a straightforward implementation:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">class</span><span style="color:#B392F0"> ChangeNotifier</span><span style="color:#E1E4E8"> : </span><span style="color:#B392F0">IChangeNotifier</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  private</span><span style="color:#F97583"> int</span><span style="color:#B392F0"> _Value</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">  public</span><span style="color:#F97583"> int</span><span style="color:#B392F0"> Value</span></span>
<span class="line"><span style="color:#E1E4E8">  {</span></span>
<span class="line"><span style="color:#F97583">    get</span><span style="color:#E1E4E8"> { </span><span style="color:#F97583">return</span><span style="color:#E1E4E8"> _Value; }</span></span>
<span class="line"><span style="color:#F97583">    set</span></span>
<span class="line"><span style="color:#E1E4E8">    {</span></span>
<span class="line"><span style="color:#E1E4E8">      _Value </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> value;</span></span>
<span class="line"><span style="color:#B392F0">      OnPropertyChanged</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">new</span><span style="color:#B392F0"> PropertyChangedEventArgs</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">"Value"</span><span style="color:#E1E4E8">));</span></span>
<span class="line"><span style="color:#E1E4E8">    }</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"><span style="color:#F97583">  public</span><span style="color:#F97583"> event</span><span style="color:#B392F0"> PropertyChangedEventHandler</span><span style="color:#B392F0"> PropertyChanged</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">  protected</span><span style="color:#F97583"> virtual</span><span style="color:#F97583"> void</span><span style="color:#B392F0"> OnPropertyChanged</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">PropertyChangedEventArgs</span><span style="color:#B392F0"> e</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">  {</span></span>
<span class="line"><span style="color:#F97583">    if</span><span style="color:#E1E4E8"> (PropertyChanged </span><span style="color:#F97583">!=</span><span style="color:#79B8FF"> null</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#B392F0">      PropertyChanged</span><span style="color:#E1E4E8">(</span><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">, e);</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>While this implementation satisfies the requirements of raising the
event when the value changes, it brings with it a list of rather
suboptimal consequences.</p>
<ul>
<li>
<p>Setting the property fires the event everytime, even if the supplied
value has not changed.</p>
<ol>
<li>Besides being a possible performance problem, as the event is
invoked multiple times,</li>
<li>when used with event handlers that update properties themselves
a deadlock can be triggered. eg. consider two input fields that
display a number in two different formats. If the first number
is updated by the user, the second number is adjusted by the
event handler and vice-versa. If the events keep triggering
themselves the application will deadlock.</li>
</ol>
</li>
<li>
<p>The code is not exception safe if the unsubscriber and the firing of
the event happen on different threads.</p>
<div>
<p>Consider the race condition that could occur when the thread that
fires the event checks ‘if (PropertyChanged != null)’ and then a
different thread unsubscribes in just that moment and the first
thread tries to raise the event and triggers a
NullReferenceException instead.</p>
</div>
</li>
<li>
<p>The code is not refactoring safe for the author.</p>
<div>
<p>If (better: when) the author of the class renames the property he
has to remember to rename the hardcoded string as well. Consider
refactoring the interface - a rename of the interface property in
Visual Studio will rename the property names of all implementing
classes, but not the string used in with firing the
PropertyChangedEventHandler.</p>
</div>
</li>
<li>
<p>The code is not typo safe for the consumer.</p>
<div>
<p>Consider the consumer of the event, who is probably trying to
discern in his eventhandler which property raised the event. If he
makes a typo, the compiler will be unable to catch the error.</p>
</div>
</li>
</ul>
<h2 id="an-improved-version">An improved version</h2>
<p>First, we’ll modify the property setter to fire only when the value of
the property changes.</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">private</span><span style="color:#F97583"> int</span><span style="color:#B392F0"> _Value</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">public</span><span style="color:#F97583"> int</span><span style="color:#E1E4E8"> Value</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#E1E4E8">  get { </span><span style="color:#F97583">return</span><span style="color:#E1E4E8"> _Value; }</span></span>
<span class="line"><span style="color:#E1E4E8">  set</span></span>
<span class="line"><span style="color:#E1E4E8">  {</span></span>
<span class="line"><span style="color:#F97583">    if</span><span style="color:#E1E4E8"> (_Value </span><span style="color:#F97583">!=</span><span style="color:#E1E4E8"> value)</span></span>
<span class="line"><span style="color:#E1E4E8">    {</span></span>
<span class="line"><span style="color:#E1E4E8">      _Value </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> value;</span></span>
<span class="line"><span style="color:#B392F0">      OnPropertyChanged</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">new</span><span style="color:#B392F0"> PropertyChangedEventArgs</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">"Value"</span><span style="color:#E1E4E8">));</span></span>
<span class="line"><span style="color:#E1E4E8">    }</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>That solves the first of our concerns - the event handler is now only
fired if a change of the value really happens.</p>
<p>Now let’s redo the event implementation to fix the race condition:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">public</span><span style="color:#E1E4E8"> event </span><span style="color:#B392F0">PropertyChangedEventHandler</span><span style="color:#B392F0"> PropertyChanged</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">protected</span><span style="color:#F97583"> virtual</span><span style="color:#F97583"> void</span><span style="color:#B392F0"> OnPropertyChanged</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">PropertyChangedEventArgs</span><span style="color:#B392F0"> e</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  var</span><span style="color:#B392F0"> propertyChanged</span><span style="color:#F97583"> =</span><span style="color:#79B8FF"> this</span><span style="color:#E1E4E8">.PropertyChanged;</span></span>
<span class="line"><span style="color:#F97583">  if</span><span style="color:#E1E4E8"> (propertyChanged </span><span style="color:#F97583">!=</span><span style="color:#79B8FF"> null</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#B392F0">    propertyChanged</span><span style="color:#E1E4E8">(</span><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">, e);</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>By storing a local copy of the event handler, we make sure to test and
execute the same instance, hence solving the possible
NullReferenceException. We’re able to cross our second concern off the
list.</p>
<h2 id="further-options">Further Options</h2>
<p>We still have the problem of refactoring for the author and consumer of
the class. Let’s try to tacke those.</p>
<h3 id="using-a-const-field">Using a const field</h3>
<p>Then there is the option of using a const field to hold the string:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">public</span><span style="color:#F97583"> const</span><span style="color:#F97583"> string</span><span style="color:#B392F0"> ValuePropertyName</span><span style="color:#F97583"> =</span><span style="color:#9ECBFF"> "Value"</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">private</span><span style="color:#F97583"> int</span><span style="color:#B392F0"> _Value</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">public</span><span style="color:#F97583"> int</span><span style="color:#E1E4E8"> Value</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#E1E4E8">  get { </span><span style="color:#F97583">return</span><span style="color:#E1E4E8"> _Value; }</span></span>
<span class="line"><span style="color:#E1E4E8">  set</span></span>
<span class="line"><span style="color:#E1E4E8">  {</span></span>
<span class="line"><span style="color:#F97583">    if</span><span style="color:#E1E4E8"> (_Value </span><span style="color:#F97583">!=</span><span style="color:#E1E4E8"> value)</span></span>
<span class="line"><span style="color:#E1E4E8">    {</span></span>
<span class="line"><span style="color:#E1E4E8">      _Value </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> value;</span></span>
<span class="line"><span style="color:#B392F0">      OnPropertyChanged</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">new</span><span style="color:#B392F0"> PropertyChangedEventArgs</span><span style="color:#E1E4E8">(ValuePropertyName));</span></span>
<span class="line"><span style="color:#E1E4E8">    }</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>This does not solve your refactoring problem, but the author of the
class and the event consumer at least use the same field and therefore
the consumer can’t make a typo.</p>
<p>The drawback here being, that</p>
<ol>
<li>the consumer of the event must write his code against the actual
implementation of the class to access the ValuePropertyName field
and</li>
<li>each implementor of the interface gets to pick a (possibly wrong)
name.</li>
</ol>
<p>So ideally the constant string would be part of the interface, which is
not possible. This brings as to our next attempt:</p>
<h2 id="using-an-extension-method">Using an extension Method</h2>
<p>Putting it into an extension class for the interface works kind of, the
trouble being that extension properties are not supported and neither
const nor static, so your only option is a instance method.</p>
<p>Consider the extension method defined in:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">public</span><span style="color:#F97583"> static</span><span style="color:#F97583"> class</span><span style="color:#B392F0"> ChangeNotifierExtensions</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  public</span><span style="color:#F97583"> static</span><span style="color:#F97583"> string</span><span style="color:#B392F0"> GetValuePropertyName</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">this</span><span style="color:#B392F0"> IChangeNotifier</span><span style="color:#B392F0"> changeNotifier</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">  {</span></span>
<span class="line"><span style="color:#F97583">    return</span><span style="color:#9ECBFF"> "Value"</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>Now you can imagine every implementor of the IChangeNotifier interface
as well as the event consumer accessing the same string - if they follow
our convention.</p>
<h3 id="using-linqs-memberexpression">Using Linq’s MemberExpression</h3>
<p>It’s possible to substitute the hard coded string using a strongly
typed property reference using the Linq’s MemberExpression. Take a look
at the following code:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">private</span><span style="color:#F97583"> int</span><span style="color:#B392F0"> _Value</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">public</span><span style="color:#F97583"> int</span><span style="color:#E1E4E8"> Value</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#E1E4E8">  get { </span><span style="color:#F97583">return</span><span style="color:#E1E4E8"> _Value; }</span></span>
<span class="line"><span style="color:#E1E4E8">  set</span></span>
<span class="line"><span style="color:#E1E4E8">  {</span></span>
<span class="line"><span style="color:#F97583">    if</span><span style="color:#E1E4E8"> (_Value </span><span style="color:#F97583">!=</span><span style="color:#E1E4E8"> value)</span></span>
<span class="line"><span style="color:#E1E4E8">    {</span></span>
<span class="line"><span style="color:#E1E4E8">      _Value </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> value;</span></span>
<span class="line"><span style="color:#B392F0">      OnPropertyChanged</span><span style="color:#E1E4E8">(() </span><span style="color:#F97583">=></span><span style="color:#79B8FF"> this</span><span style="color:#E1E4E8">.Value);</span></span>
<span class="line"><span style="color:#E1E4E8">    }</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span>
<span class="line"><span style="color:#F97583">protected</span><span style="color:#F97583"> virtual</span><span style="color:#F97583"> void</span><span style="color:#B392F0"> OnPropertyChanged</span><span style="color:#E1E4E8">(Expression> property)</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  string</span><span style="color:#B392F0"> propertyName</span><span style="color:#F97583"> =</span><span style="color:#E1E4E8"> (property.Body </span><span style="color:#F97583">as</span><span style="color:#B392F0"> MemberExpression</span><span style="color:#E1E4E8">).Member.Name;</span></span>
<span class="line"><span style="color:#B392F0">  OnPropertyChanged</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">new</span><span style="color:#B392F0"> PropertyChangedEventArgs</span><span style="color:#E1E4E8">(propertyName));</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#F97583">public</span><span style="color:#E1E4E8"> event </span><span style="color:#B392F0">PropertyChangedEventHandler</span><span style="color:#B392F0"> PropertyChanged</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">protected</span><span style="color:#F97583"> virtual</span><span style="color:#F97583"> void</span><span style="color:#B392F0"> OnPropertyChanged</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">PropertyChangedEventArgs</span><span style="color:#B392F0"> e</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  var</span><span style="color:#B392F0"> propertyChanged</span><span style="color:#F97583"> =</span><span style="color:#79B8FF"> this</span><span style="color:#E1E4E8">.PropertyChanged;</span></span>
<span class="line"><span style="color:#F97583">  if</span><span style="color:#E1E4E8"> (propertyChanged </span><span style="color:#F97583">!=</span><span style="color:#79B8FF"> null</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#B392F0">    propertyChanged</span><span style="color:#E1E4E8">(</span><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">, e);</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>This does what we want - we got rid of the string “Value” and we’re
refactoring save - if the name of the property get’s refactored the
string used to create the PropertyChangedEventArgs instance is updated
as well. The consumer of the event can even use a similiar method to
test for the properties name.</p>
<p>So we’re done, right?</p>
<p>Well, of course there is a catch here (despite depending on a newer
framework than the former option) and it’s performance related. Using
the approach with the MemberExpression class is significantly slower
than the hard coded string.</p>
<p>Does it matter? The answer is of course: it depends. If you’re only
firing a couple of events, the delay is negliable. But if your firing
hundred thousand it adds up. And there is one-time delay on the first
execution of the path. So don’t use it, if you’re implementing your
game loop and consider warming it up if you need fast first-time
performance.</p>
<h2 id="additional-performance-considerations">Additional performance considerations</h2>
<p>There is another possible perfomance cost payed in the usual
implementation and it’s memory related. Everytime we raise the event a
new PropertyChangedEventArgs instance is allocated. And it’s
unnecessary, as everytime we create it with the same string for the same
property.</p>
<p>Does this really matter? Again it depends - it did for me when I was
implementing a Xamarin Forms Android application and the opengl view
stuttered occasionally, which was caused by the garbage collector pauses
from creating a ton of PropertyChangedEvents.</p>
<p>Consider the following property implementation:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">private</span><span style="color:#F97583"> static</span><span style="color:#B392F0"> PropertyChangedEventArgs</span><span style="color:#B392F0"> ValuePropertyChangedEventArgs</span><span style="color:#F97583"> =</span><span style="color:#F97583"> new</span><span style="color:#B392F0"> PropertyChangedEventArgs</span><span style="color:#E1E4E8">(</span><span style="color:#9ECBFF">"Value"</span><span style="color:#E1E4E8">);</span></span>
<span class="line"><span style="color:#F97583">private</span><span style="color:#F97583"> int</span><span style="color:#B392F0"> _Value</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">public</span><span style="color:#F97583"> int</span><span style="color:#E1E4E8"> Value</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#E1E4E8">  get { </span><span style="color:#F97583">return</span><span style="color:#E1E4E8"> _Value; }</span></span>
<span class="line"><span style="color:#E1E4E8">  set</span></span>
<span class="line"><span style="color:#E1E4E8">  {</span></span>
<span class="line"><span style="color:#F97583">    if</span><span style="color:#E1E4E8"> (_Value </span><span style="color:#F97583">!=</span><span style="color:#E1E4E8"> value)</span></span>
<span class="line"><span style="color:#E1E4E8">    {</span></span>
<span class="line"><span style="color:#E1E4E8">      _Value </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> value;</span></span>
<span class="line"><span style="color:#B392F0">      OnPropertyChanged</span><span style="color:#E1E4E8">(ValuePropertyChangedEventArgs);</span></span>
<span class="line"><span style="color:#E1E4E8">    }</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>Which get’s rid of the unecessary allocations by reusing the same
static instance of the PropertyChangedEventArgs class.</p>
<p>So are we doomed with flawed implementations of a pretty simple
interface? No, to the rescue comes C# 6!</p>
<h3 id="new-features-in-c-6">New features in C# 6</h3>
<p>C# 6 comes with new features, of which one is the null-conditional
operator, which is a succinct way to solve our NullReference race
condition. Instead of:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">protected</span><span style="color:#F97583"> virtual</span><span style="color:#F97583"> void</span><span style="color:#B392F0"> OnPropertyChanged</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">PropertyChangedEventArgs</span><span style="color:#B392F0"> e</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#F97583">  var</span><span style="color:#B392F0"> propertyChanged</span><span style="color:#F97583"> =</span><span style="color:#79B8FF"> this</span><span style="color:#E1E4E8">.PropertyChanged;</span></span>
<span class="line"><span style="color:#F97583">  if</span><span style="color:#E1E4E8"> (propertyChanged </span><span style="color:#F97583">!=</span><span style="color:#79B8FF"> null</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#B392F0">    propertyChanged</span><span style="color:#E1E4E8">(</span><span style="color:#79B8FF">this</span><span style="color:#E1E4E8">, e);</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>We can write:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">protected</span><span style="color:#F97583"> virtual</span><span style="color:#F97583"> void</span><span style="color:#B392F0"> OnPropertyChanged</span><span style="color:#E1E4E8">(</span><span style="color:#B392F0">PropertyChangedEventArgs</span><span style="color:#B392F0"> e</span><span style="color:#E1E4E8">)</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#E1E4E8">  PropertyChanged</span><span style="color:#F97583">?</span><span style="color:#E1E4E8">.</span><span style="color:#B392F0">Invoke</span><span style="color:#E1E4E8">(e);</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<p>instead.</p>
<p>While the null conditional operator is just syntactic sugar, the nameof
operator will solve our problem of getting a string of the property name
and the property implementation will probably look like:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="csharp"><code><span class="line"><span style="color:#F97583">private</span><span style="color:#F97583"> int</span><span style="color:#B392F0"> _Value</span><span style="color:#E1E4E8">;</span></span>
<span class="line"><span style="color:#F97583">public</span><span style="color:#F97583"> int</span><span style="color:#E1E4E8"> Value</span></span>
<span class="line"><span style="color:#E1E4E8">{</span></span>
<span class="line"><span style="color:#E1E4E8">  get { </span><span style="color:#F97583">return</span><span style="color:#E1E4E8"> _Value; }</span></span>
<span class="line"><span style="color:#E1E4E8">  set</span></span>
<span class="line"><span style="color:#E1E4E8">  {</span></span>
<span class="line"><span style="color:#F97583">    if</span><span style="color:#E1E4E8"> (_Value </span><span style="color:#F97583">!=</span><span style="color:#E1E4E8"> value)</span></span>
<span class="line"><span style="color:#E1E4E8">    {</span></span>
<span class="line"><span style="color:#E1E4E8">      _Value </span><span style="color:#F97583">=</span><span style="color:#E1E4E8"> value;</span></span>
<span class="line"><span style="color:#B392F0">      OnPropertyChanged</span><span style="color:#E1E4E8">(</span><span style="color:#F97583">nameof</span><span style="color:#E1E4E8">(Value));</span></span>
<span class="line"><span style="color:#E1E4E8">    }</span></span>
<span class="line"><span style="color:#E1E4E8">  }</span></span>
<span class="line"><span style="color:#E1E4E8">}</span></span></code></pre>
<h2 id="conclusion">Conclusion</h2>
<ol>
<li>Implementing a simple interface brings with it a couple of
tradeoffs. Even if those tradeoffs are mostly minor, there are edge
cases one should be aware of that warrent choosing one
implementation over the other.</li>
<li>C# 6 will make everything better. :)</li>
</ol>
<p>Please leave a comment if something is unclear or you spot an error.
Thank you for reading!</p>
<p>Take care,<br>
Martin</p>
<h2 id="references">References</h2>
<ul>
<li>Null-conditional operator on msdn
(<a href="https://msdn.microsoft.com/en-us/library/dn986595%28v=vs.140%29.aspx">https://msdn.microsoft.com/en-us/library/dn986595%28v=vs.140%29.aspx</a>)</li>
<li>nameof operator on msdn
(<a href="https://msdn.microsoft.com/en-us/library/dn986596%28v=vs.140%29.aspx">https://msdn.microsoft.com/en-us/library/dn986596%28v=vs.140%29.aspx</a>)</li>
</ul>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compiling a kernel module for the raspberry pi 2]]></title>
            <link>https://lostindetails.com/articles/Compiling-a-kernel-module-for-the-raspberry-pi-2</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/Compiling-a-kernel-module-for-the-raspberry-pi-2</guid>
            <pubDate>Wed, 25 Feb 2015 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<h2 id="compiling-a-kernel-module-for-the-raspberry-pi-2">Compiling a kernel module for the raspberry pi 2</h2>
<p>Normally compiling a kernel module for a linux distribution is rather
straight forward, but on the raspberry pi however it’s a little more
involved. That’s why in this article I am going to show how I build
kernel modules for the raspbian wheezy distro.</p>
<p>There are a couple of infos on the web about how to do it, but piecing
them together for a working solution took some effort. That’s why I am
writing them down for future use. Following these steps I successfully
build kernel modules for raspberry pi 2 raspbian release 2015-02-16.</p>
<h3 id="background">Background</h3>
<p>Building your kernel module for the raspberry pi is a two step process.
The first step is to build the complete kernel for the raspberry pi on
the ubuntu machine. This will take a long time, but you’ll need to do
it only once. After the build is complete, you can build your kernel
module fast and easy and just copy the resulting binary to the raspberry
pi.</p>
<h3 id="requirements">Requirements</h3>
<ul>
<li>
<p>Raspberry Pi flashed with a raspbian wheezy distribution</p>
<p>Get the <a href="http://downloads.raspberrypi.org/raspbian_latest">latest raspbian
image</a> from the
raspberrypi foundations website.</p>
</li>
<li>
<p>Ubuntu for cross-compiling</p>
<p>Both time and space constrains make building the raspberry pi kernel
on the raspberry pi itself rather challenging. That’s why I went to
road of cross-compiling from ubuntu to raspberry pi.</p>
<p>If you don’t have a ubuntu machine, grab a ubuntu image from their
<a href="http://www.ubuntu.com/download/desktop">download page</a> and spin it
up in a virtual machine of your choice. Myself, I use
<a href="https://www.virtualbox.org/wiki/Downloads">virtualbox</a> on a windows
machine.</p>
</li>
<li>
<p>Patience</p>
</li>
</ul>
<h3 id="getting-the-correct-source">Getting the correct source</h3>
<h4 id="the-normal-way">The normal way</h4>
<p>Getting the correct source to build the kernel is trickier than one
would guess. As explained on
<a href="http://kernelnewbies.org/KernelHeaders">kernelnewbies.org</a> you need the
exact version of the headers from the kernel that the modules are built
for.</p>
<p>Normally you’d simply install the kernel header package for the
specific kernel version that you get when you execute <code>uname -r</code>, but
while raspbian provides header packages, the raspberry pi foundation,
who modifies them does not, as you’ll find out if you <a href="http://www.raspberrypi.org/forums/viewtopic.php?f=66&#x26;t=57401">read through
raspberry pi orgs
forums</a>.</p>
<h4 id="the-raspberry-way">The raspberry way</h4>
<p>What they do however, is keep the complete source in their github <a href="https://github.com/raspberrypi/linux">linux
repository</a>. When they build a
raspberry pi firmware, which is proprietery, closed source btw, those
binaries are checked-in in the <a href="https://github.com/raspberrypi/firmware">firmware
repository</a> including a
<a href="https://github.com/raspberrypi/firmware/blob/master/extra/git_hash">file</a>
that contains the git hash that points to the commit in the linux repo
that they used to build it.</p>
<p>So luckily for us there is a link that you can follow to get the exact
source code and the steps are as follows:</p>
<ol>
<li>Get the Firmware Hash from the raspberry pi</li>
<li>Get the Linux Kernel Hash from the ‘Firmware’ github repo</li>
<li>Get the Linux Kernel Source from the ‘Linux’ github repo</li>
</ol>
<p>Thanks to the raspberry pi forms user ‘Zeta’ who put a script together
and posted it in this
<a href="http://www.raspberrypi.org/forums/viewtopic.php?f=66&#x26;t=57401">thread</a>
to perform those steps:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span># Get the Firmware Hash from the Raspberry Pi</span></span>
<span class="line"><span>FIRMWARE_HASH=$(zgrep "* firmware as of" /usr/share/doc/raspberrypi-bootloader/changelog.Debian.gz | head -1 | awk '{ print $5 }')</span></span>
<span class="line"><span></span></span>
<span class="line"><span># Get the git hash for this kernel</span></span>
<span class="line"><span>KERNEL_HASH=$(wget https://raw.github.com/raspberrypi/firmware/$FIRMWARE_HASH/extra/git_hash -O -)</span></span>
<span class="line"><span></span></span>
<span class="line"><span># Checkout the files on ubuntu</span></span>
<span class="line"><span>git checkout $KERNEL_HASH</span></span></code></pre>
<h3 id="building-the-kernel">Building the kernel</h3>
<p>Armed with this knowledge we can now finally execute a step by step
plan:</p>
<ol>
<li>
<p>Start up ubuntu</p>
</li>
<li>
<p>Get the tools from <a href="https://github.com/raspberrypi/tools">https://github.com/raspberrypi/tools</a> e.g.:
<code>git clone https://github.com/raspberrypi/tools </code></p>
</li>
<li>
<p>Set the environment variable CCPREFIX to point to the master tools
like so:
<code>export CCPREFIX=/home/INSERT YOUR USER NAME HERE/tools-master/arm-bcm2708/arm-bcm2708-linux-gnueabi/bin/arm-bcm2708-linux-gnueabi-</code></p>
</li>
<li>
<p>Get the source from <a href="https://github.com/raspberrypi/linux">https://github.com/raspberrypi/linux</a> e.g.:
<code>git clone https://github.com/raspberrypi/linux </code></p>
</li>
<li>
<p>Set the environment variable KERNEL_SRC to point to the kernel
source: <code>export KERNEL_SRC=/home/INSERT YOUR USER NAME HERE/linux</code></p>
</li>
<li>
<p>on the raspberry pi execute
<code>FIRMWARE_HASH=$(zgrep "* firmware as of" /usr/share/doc/raspberrypi-bootloader/changelog.Debian.gz | head -1 | awk '{ print $5 }')</code>
to retrieve the firmware hash.</p>
</li>
<li>
<p>execute
<code>KERNEL_HASH=$(wget https://raw.github.com/raspberrypi/firmware/$FIRMWARE_HASH/extra/git_hash -O -)</code>
to retrieve the kernel hash.</p>
</li>
<li>
<p>back on ubuntu checkout the correct version of the kernel source
code inside the KERNEL_SRC directory using git:
<code>git checkout INSERT_KERNEL_HASH_HERE</code></p>
</li>
<li>
<p>execute <code>make mrproper</code> in the KERNEL_SRC directory.</p>
</li>
<li>
<p>copy /proc/config.gz from the raspberry pi to the KERNEL_SRC
directory.</p>
<p>e.g. <code>scp pi@ipaddress:/proc/config.gz ./</code> and unpack it:
<code>zcat config.gz > .config</code></p>
</li>
<li>
<p>execute <code>make ARCH=arm CROSS_COMPILE=${CCPREFIX} oldconfig</code></p>
</li>
<li>
<p>execute <code>make ARCH=arm CROSS_COMPILE=${CCPREFIX}</code></p>
</li>
<li>
<p>…and wait.</p>
<p><img src="/img/waiting.jpg" alt="" title="waiting..."></p>
</li>
<li>
<p>…keep waiting.</p>
</li>
</ol>
<p>If everything worked out ok, the kernel should be successfully rebuilt.
Now the source directory can be used to built kernel modules for your
raspberry pi.</p>
<h3 id="building-kernel-modules">Building Kernel modules</h3>
<p>Now that the kernel has been successfully built, a new MOdule.symvers
has been created. You can now use a make file that references the kernel
source directory to built the kernel module only. E.g. use a line like:</p>
<pre class="astro-code github-dark" style="background-color:#24292e;color:#e1e4e8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>PREFIX = /home/[USER]/tools-master/arm-bcm2708/arm-bcm2708-linux-gnueabi/bin/arm-bcm2708-linux-gnueabi-</span></span>
<span class="line"><span>    make ARCH=arm CROSS_COMPILE=$(PREFIX) -C /home/[USER]/linux M=$(SRC) modules</span></span></code></pre>
<p>As I need to continually build kernel modules for more than one kernel
version, I copy the source directory and rename it to match the kernel
version. If a new kernel version comes out, I just checkout the source
in a new folder. In the makefile I reference the different source
folders to build the kernel module for different kernel versions.For an
example of a makefile you can take a look
<a href="https://github.com/amescon/raspicomm-module/blob/master/Makefile">here</a>.</p>
<h3 id="references">References</h3>
<ul>
<li><a href="Latest%20Raspbian%20Image">http://downloads.raspberrypi.org/raspbian_latest</a></li>
<li><a href="Ubuntu%20Download%20Page">http://www.ubuntu.com/download/desktop</a></li>
<li><a href="http://elinux.org/Raspberry_Pi_Kernel_Compilation">http://elinux.org/Raspberry_Pi_Kernel_Compilation</a></li>
<li><a href="http://bchavez.bitarmory.com/archive/2013/01/16/compiling-kernel-modules-for-raspberry-pi.aspx">http://bchavez.bitarmory.com/archive/2013/01/16/compiling-kernel-modules-for-raspberry-pi.aspx</a></li>
<li><a href="http://www.raspberrypi.org/forums/viewtopic.php?f=66&#x26;t=57401">http://www.raspberrypi.org/forums/viewtopic.php?f=66&#x26;t=57401</a></li>
</ul>
<p>[Update 10/7/2015 - Fixed copy/paste error in git clone url.]</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why write a blog]]></title>
            <link>https://lostindetails.com/articles/Why-write-a-blog</link>
            <guid isPermaLink="false">https://lostindetails.com/articles/Why-write-a-blog</guid>
            <pubDate>Fri, 20 Feb 2015 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<h2 id="why-write-a-blog">Why write a blog?</h2>
<p>I’ve decided to start a blog. Why now? Aren’t there enough blogs out
there? Even good ones? So why start crappy one now? Well, I thought
about starting a blog for a while now and I’ve finally decided to do
something about it. I thought I’d start by listing a few reasons that
after years got me to start this blogging thing.</p>
<h3 id="my-reasons-to-write-a-blog">My reasons to write a blog</h3>
<h4 id="1-improve-your-writing">1. Improve your writing</h4>
<p>The best way to get better at something is experience. English is not my
native language and while my passive vocabulary is ok, I am not any good
at expressing myself, so being continually forced to write full
sentences does help.</p>
<h4 id="2-think-your-ideas-through">2. Think your ideas through</h4>
<p>“Writing is nature’s way to show us how sloppy our thinking is.” is a
nice quote that I heard from Leslie Lamport that fits well. To write an
article or a post you’ll need to think it all through, find and fill
gaps in your understanding and restructure it.</p>
<p>From a more meta perspective, as I was thinking about writing a blog, I
thought about reasons why I should invest the time to setup a blog and
write articles, but they were kind of diffuse, but as I actually set
down to write this ‘hello world’ post, I was forced revisit my
thoughts and order and prioritise them.</p>
<h4 id="3-fact-check-your-ideas">3. Fact check your ideas</h4>
<p>I think a blog is a good way to fact check your thinking. The observable
reader might spot errors and flaws in your writing. Everybody knows,
that nothing motivates people like pointing out that someone is wrong on
the internet. Even nonsensical grammar or typos are spotted and brought
to your attention. Kinda like peer review.</p>
<p><a href="https://xkcd.com/386/"><img src="http://imgs.xkcd.com/comics/duty_calls.png" alt="" title="xkcd&#x27;s Duty Calls"></a></p>
<h4 id="4-find-things-again">4. Find things again</h4>
<p>That reason is pretty important to me, I need a place where I can find
things again that I tend to forget. Similiar to onenote or evernote, but
were you put more effort in and allow public access. With a blog, I know
where I need to go to look it up again.</p>
<p>So, there you have it, my reasons to write a blog. If you can think up
other good reasons, then feel free to point them out.</p>
<p><em>Take care,<br>
Martin</em></p>]]></content:encoded>
        </item>
    </channel>
</rss>