<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title>Thomas Freudenberg</title>
  <link href="https://thomasfreudenberg.com/atom.xml" rel="self"/>
  <link href="https://thomasfreudenberg.com/"/>
  <updated>2019-01-28T21:41:36.5419262+00:00</updated>
  <id></id>
  <author>
    <name>Thomas Freudenberg</name>
    
  </author>

  
  
  <entry>
    <title type="html"><![CDATA[Async/await in Desktop Applications]]></title>
    <link href="https://thomasfreudenberg.com/archive/2019/01/28/async-await-in-desktop-applications/"/>
    <updated>2019-01-28T00:00:00+00:00</updated>
    <id>/archive/2019/01/28/async-await-in-desktop-applications/</id>
    <content type="html"><![CDATA[<p><em>This is a transcript of a demonstration I gave in our company internally
about async/await &quot;challenges&quot; in UI programming. YOu can find the accompanying
repository in <a href="https://github.com/thoemmi/CrossThreadingTests">my repository on Github</a>.</em></p>
<div class="image-center"><p><img src="/files/archive/async-await-winforms-app.png" alt="Demo App" title="Demo App" /></p>
</div>
<p>The form contains three buttons which are intended to download the
the content from <a href="http://microsoft.com">http://microsoft.com</a> asynchronously and show it
in a TextBox.</p>
<h2 id="cross-thread-issue">Cross-Thread issue 😦</h2>
<pre><code class="language-csharp">private async void button1_Click(object sender, EventArgs e)
{
    // await a completed task =&gt; will continue synchronously
    await SomeFastAsyncOperation().ConfigureAwait(false);

    // await a slow task =&gt; will continue in another thread
    var t = await SomeSlowAsyncOperation().ConfigureAwait(false);

    // write text to text box
    textBox1.Text = t;
}
</code></pre>
<p>When clicking the first button, an <code>InvalidOperationException</code> will
be thrown with the message</p>
<blockquote>
<p>Cross-thread operation not valid: Control 'textBox1' accessed from a
thread other than the thread it was created on.</p>
</blockquote>
<p>That's because in Win32 UIs you must access controls from the same thread
that created them. Because the after awaiting <code>SomeSlowAsyncOperation</code>
the method continues not in the main thread but a nackground thread,
accessing <code>textBox1</code> is forbidden.</p>
<p>When you debug <code>button1_Click</code>, pay attention to the <em>Threads</em> tool window.</p>
<div class="image-center"><p><img src="/files/archive/async-await-debugger.png" alt="Debugger" title="Debugger Thread Toolwindow" /></p>
</div>
<ol>
<li>Entering the method, you'll be on thread #1, the main thread.</li>
<li>After calling <code>SomeFastAsyncOperation</code>, the code continues on thread #1.
That's because the method returns an already completed task, so the code
can continue synchronously.</li>
<li>In contrast, <code>SomeSlowAsyncOperation</code> returns a not-completed task,
therefore the succeeding code will continue not another one. (The UI thread
will be released here and continue pumping the Win32 message queue)</li>
<li>The property <code>textBox1.Text</code> will be set in said background thread and
fail, because Win32 controls mist be accessed from the same thread that
created them.</li>
</ol>
<h2 id="blocking">Blocking 😦</h2>
<pre><code class="language-csharp">private async void button2_Click(object sender, EventArgs e)
{
    // await a completed task =&gt; will continue synchronously
    await SomeFastAsyncOperation().ConfigureAwait(false);

    // await a slow task =&gt; will continue in another thread
    var t = SomeSlowAsyncOperation().ConfigureAwait(false).GetAwaiter().GetResult();

    // write text to text box
    textBox1.Text = t;
}
</code></pre>
<p>Clicking the second button will freeze the application. The
<code>GetAwaiter().GetResult()</code> invocation will try to re-enter the
the main thread, which is waiting for the task, so we'll run into a dead-lock.</p>
<h2 id="run-smoothly">Run smoothly 😃</h2>
<pre><code class="language-csharp">private async void button3_Click(object sender, EventArgs e)
{
    // force switch to threadpool thread
    await TaskScheduler.Default;

    // await a completed task =&gt; will continue synchronously
    await SomeFastAsyncOperation().ConfigureAwait(false);

    // await a slow task =&gt; will continue in another thread
    var t = await SomeSlowAsyncOperation().ConfigureAwait(false);

    // switch to main thread
    await _joinableTaskFactory.SwitchToMainThreadAsync();

    // write text to text box
    textBox1.Text = t;
}
</code></pre>
<p>Using the <code>JoinableTaskFactory</code> from <a href="https://github.com/Microsoft/vs-threading"><em>Microsoft.VisualStudio.Threading</em></a>
(NuGet package <a href="https://nuget.org/packages/Microsoft.VisualStudio.Threading">here</a>),
we are able to &quot;switch&quot; back to the UI thread.</p>
<p>As the namespace implies, <em>Microsoft.VisualStudio.Threading</em> originates from
the Visual Studio team. I stumbled over this library while reading the documentation
for Visual Studio extensibility. Visual Studio is quite a complex application, and
there are myriads of extensions available. To improve the start-up time, Microsoft
strongly recommends to make use of asynchronous programming (see
<a href="https://docs.microsoft.com/en-us/visualstudio/extensibility/managing-multiple-threads-in-managed-code?view=vs-2017"><em>How to: Manage multiple threads in managed code</em></a>
and <a href="https://docs.microsoft.com/en-us/visualstudio/extensibility/how-to-use-asyncpackage-to-load-vspackages-in-the-background?view=vs-2017"><em>How to: Use AsyncPackage to load VSPackages in the background</em></a>)</p>
<p>I won't go into details of how async/await works. Basically, the compiler generates
a state machine, which Dixin explains pretty good in his blog serie
<a href="https://weblogs.asp.net/dixin/understanding-c-sharp-async-await-1-compilation"><em>Understanding C# async / await (1) Compilation</em></a>
(<a href="https://weblogs.asp.net/dixin/understanding-c-sharp-async-await-2-awaitable-awaiter-pattern">Part 2</a>,
<a href="https://weblogs.asp.net/dixin/understanding-c-sharp-async-await-3-runtime-context">Part 3</a>).</p>
<p>In our case, two calls are interesting:</p>
<ol>
<li><code>await TaskScheduler.Default;</code> will continue the succeeding code in a threadpool thread<br>
<small>(actually, the library provides an extension method <code>GetAwaiter(this TaskScheduler this)</code>.
This works because the compiler uses a naming convention instead of requiring an interface implemenntation)</small></li>
<li><code>await _joinableTaskFactory.SwitchToMainThreadAsync();</code> will continue the succeeding code in the
main thread <br><small>(actually, in the thread with instantiated <code>_joinableTaskFactory</code>).</small></li>
</ol>
<p>As you could see, <em>Microsoft.VisualStudio.Threading</em> makes asynchronous programming
in desktop applications, both WinForms and WPF, much simpler.</p>
<p>BTW, I've learned a lot reading the <a href="https://github.com/Microsoft/vs-threading">code of that library</a>. It provides
much more async helpers like <code>AsyncEventHandlers</code>.</p>
<p>Here are some more links if you want to learn more about async programming:</p>
<ul>
<li><p><a href="https://www.slideshare.net/aarnott/the-3-vs-threading-rules"><em>The 3 VS Threading Rules</em></a> by Andrew Arnott</p>
</li>
<li><p><a href="https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html"><em>Don't Block on Async Code</em></a> by Stephen Cleary</p>
</li>
<li><p><a href="https://lesen.amazon.de/kp/embed?asin=B00KCY2CB4&amp;preview=newtab&amp;linkCode=kpe&amp;ref_=cm_sw_r_kb_dp_WWQtCbZETE973"><em>Concurrency in C# Cookbook: Asynchronous, Parallel, and Multithreaded Programming</em></a> by Stephen Cleary</p>
</li>
</ul>]]></content>
  </entry>
  
  
  
  <entry>
    <title type="html"><![CDATA[Generating workflow diagrams for TFS work items]]></title>
    <link href="https://thomasfreudenberg.com/archive/2018/01/16/generating-workflow-diagram-for-witd/"/>
    <updated>2018-01-16T00:00:00+00:00</updated>
    <id>/archive/2018/01/16/generating-workflow-diagram-for-witd/</id>
    <content type="html"><![CDATA[<p>In my current position as the Technical Lead of Product Development I have several
responsibilities. One of them is the definition and implementation of our development
processes. We're using Team Foundation Server, which supports rich customization
of the process configuration, especially the workflow of work items.</p>
<p>To document the workflow of our work items, I wanted to create perspicuous charts.
However, if you're a nerd like me, you don't want to use Powerpoint or Visio to
create high gloss charts. Instead I like to automate the creation of the charts.</p>
<p>Fortunately, the XML format of work item template definitions (WITD) is well-documented, see
<a href="https://docs.microsoft.com/en-us/vsts/work/customize/reference/all-workflow-xml-elements-reference?toc=/vsts/work/customize/toc.json&amp;bc=/vsts/work/customize/breadcrumb/toc.json">All WORKFLOW XML elements reference</a>.
To get the XML file of a WITD, you can use either the Visual Studio Add-in
<a href="https://marketplace.visualstudio.com/items?itemName=KarthikBalasubramanianMSFT.TFSProcessTemplateEditor">TFS Process Template Editor</a>
or use <a href="https://docs.microsoft.com/en-us/vsts/work/customize/reference/witadmin/witadmin-import-export-manage-wits"><code>witadmin</code></a>:</p>
<pre><code class="language-shell">witadmin exportwitd /collection:CollectionURL /p:Project /n:TypeName [/f:FileName]
</code></pre>
<p>On the other end, the <a href="http://www.graphviz.org/">Graphviz suite</a> includes a nice
small tool named <strong><code>dot</code></strong> to draw directed graphs as PNGs, reading the defintion
of the graph from a text file.</p>
<p>The challenge was now to convert the XML of the WITD to the <a href="https://graphviz.gitlab.io/_pages/doc/info/lang.html">DOT language</a>.
But that's quite easy to accomplish using Powershell. But before I show the script,
first a picture of the default workflow for bugs from the Scrum process template:</p>
<div class="image-center"><p><img src="/files/archive/witd.bug.default.png" alt="Pretzel and Azure" /></p>
</div>
<p>And here's the script:</p>
<script src="https://gist.github.com/a4e5566a53a4b4c72424c59fdbc4eba4.js?file=Create-WorkflowDiagramFromWitd.ps1"></script>Liquid error: One or more errors occurred.
<p>If you pay close attention, you may notice that if only certain users or groups
are permitted to change a work item to a specific state, the graph will show
this too. E.g. if only members of the QA are allowed to move a but from the
<em>Done</em> state, the graph will look like this:</p>
<div class="image-center"><p><img src="/files/archive/witd.bug.customized.png" alt="Pretzel and Azure" /></p>
</div>
<p>Nevertheless, the script was written in a short time, it does what it should
do without any error handling. However, it suits my needs. Maybe yours as well.</p>]]></content>
  </entry>
  
  
  
  <entry>
    <title type="html"><![CDATA[ResourceLib, PE Format, and WiX]]></title>
    <link href="https://thomasfreudenberg.com/archive/2017/12/11/resourcelib-pe-format-and-wix/"/>
    <updated>2017-12-11T00:00:00+00:00</updated>
    <id>/archive/2017/12/11/resourcelib-pe-format-and-wix/</id>
    <content type="html"><![CDATA[<p><em>Some time ago I reported a bug and provided a pull request to
<a href="https://github.com/resourcelib/resourcelib"><strong>resourcelib</strong></a>, a managed
library to read and write Win32 resources in executables or DLL's.
And unawarely, the next morning I was a maintainer of that library.</em></p>
<p><em>This blog post is about an issue we've received: someone tried to
patched the Win32 resources of a</em> setup.exe <em>, an executable installer
created with <a href="http://wixtoolset.org/">WiX</a>. However, after changing
the resources with resourdelib, the setup didn't work anymore.</em></p>
<p><em>I've spent some time investigating this issue using <a href="https://msdn.microsoft.com/de-de/library/756as972.aspx"><code>dumpbin</code></a>
and reading the <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms680547(v=vs.85).aspx#section_table__section_headers_">PE format specification</a>.
Because I don't know how good Google is at indexing Github issues, I'll
also post my analysis here in my blog for reference. The original
thread is <a href="https://github.com/resourcelib/resourcelib/issues/19#issuecomment-350891529">here</a>.</em></p>
<p><strong>TL;DR:</strong> to me it looks like WiX is doing it wrong.</p>
<p>According to the output of <code>dumpbin</code> there are 7 sections in the executable the issuer provided:</p>
<table>
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Range</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td><code>.text</code></td>
<td>0x00000400 to 0x00049FFF</td>
</tr>
<tr>
<td>2</td>
<td><code>.rdata</code></td>
<td>0x0004A000 to 0x00068DFF</td>
</tr>
<tr>
<td>3</td>
<td><code>.data</code></td>
<td>0x00068E00 to 0x000697FF</td>
</tr>
<tr>
<td>4</td>
<td><code>.wixburn</code></td>
<td>0x00069800 to 0x000699FF</td>
</tr>
<tr>
<td>5</td>
<td><code>.tls</code></td>
<td>0x00069A00 to 0x00069BFF</td>
</tr>
<tr>
<td>6</td>
<td><code>.rsrc</code></td>
<td>0x00069C00 to 0x0006D7FF</td>
</tr>
<tr>
<td>7</td>
<td><code>.reloc</code></td>
<td>0x0006D800 to 0x000715FF</td>
</tr>
</tbody>
</table>
<p>In a hex viewer you can see that after the last section, the file continues for another <strong>104205 bytes</strong>, starting with 0x4D 0x53 0x43 0x46 (<code>MSCF</code>, the magic number starting a <a href="https://de.wikipedia.org/wiki/CAB_(Dateiformat)">cab file</a>).</p>
<p>I patched the <code>StringFileInfo</code> resource using <strong>resourcelib</strong>, which changed the content of the <code>.rsrc</code> section only. Afterwards the file ended at 0x000715FF, i.e. the following <strong>104205 bytes</strong> were missing.</p>
<p>By the way, the <code>.wixburn</code> section contains following bytes:</p>
<pre><code>RAW DATA #4
  0046C000: 00 43 F1 00 02 00 00 00 04 12 28 81 2C 64 40 48  .C±.......(.,d@H
  0046C010: B2 B1 34 64 EC 08 65 64 00 16 07 00 00 00 00 00  ▓▒4d∞.ed........
  0046C020: 00 00 00 00 00 00 00 00 01 00 00 00 02 00 00 00  ................
  0046C030: 92 8E 01 00 7B 08 00 00                          ....{...
</code></pre>
<p>which means</p>
<table>
<thead>
<tr>
<th>Field</th>
<th style="text-align: right;">Bytes</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>magic number</td>
<td style="text-align: right;">0-3</td>
<td>0x00f14300</td>
</tr>
<tr>
<td>Version</td>
<td style="text-align: right;">4-7</td>
<td>0x00000002</td>
</tr>
<tr>
<td>Bundled GUID</td>
<td style="text-align: right;">8-23</td>
<td>{81281204-642c-4840-b2b1-3464ec086564}</td>
</tr>
<tr>
<td>Engine (stub) size</td>
<td style="text-align: right;">24-27</td>
<td>0x00071600</td>
</tr>
<tr>
<td>Original checksum</td>
<td style="text-align: right;">28-31</td>
<td>0x00000000</td>
</tr>
<tr>
<td>Original signature offset</td>
<td style="text-align: right;">32-35</td>
<td>0x00000000</td>
</tr>
<tr>
<td>Original signature size</td>
<td style="text-align: right;">36-39</td>
<td>0x00000000</td>
</tr>
<tr>
<td>Container Type (1 = CAB)</td>
<td style="text-align: right;">40-43</td>
<td>1</td>
</tr>
<tr>
<td>Container Count</td>
<td style="text-align: right;">44-47</td>
<td>2</td>
</tr>
<tr>
<td>Byte count of manifest + UX container</td>
<td style="text-align: right;">48-51</td>
<td>102,034</td>
</tr>
<tr>
<td>Byte count of attached container</td>
<td style="text-align: right;">52-55</td>
<td>2,171</td>
</tr>
</tbody>
</table>
<h3 id="intermediateresult">Intermediate result</h3>
<ul>
<li>the <code>.wixburn</code> section points to 104,205 bytes (102,034 + 2,171), starting at 0x00071600.</li>
<li>the last PE section ends at 0x000715ff.</li>
<li>after using the official Win32 API to edit resources, the file ends at 0x000715ff, and the following 104,205 byte are gone.</li>
</ul>
<p>So after editing the resources, the exact payload WiX is referring to is eliminated.</p>
<h3 id="therefore-my-conclusion-is-that-wix">Therefore my conclusion is that WiX</h3>
<ul>
<li>adds a (small) section <code>.wixburn</code> pointing beyond the last section, and</li>
<li>appends the payload (read: the cabinet file) at that location-</li>
</ul>
<p>As far as I understand the specification, this procedure is not compliant with the PE format. That might be the reason why <code>EndUpdateResource</code> cuts the file after the last section when writing the changed resources.</p>]]></content>
  </entry>
  
  
  
  <entry>
    <title type="html"><![CDATA[Cleaning NuGet's cache]]></title>
    <link href="https://thomasfreudenberg.com/archive/2017/04/21/cleaning-nugets-cache/"/>
    <updated>2017-04-21T00:00:00+00:00</updated>
    <id>/archive/2017/04/21/cleaning-nugets-cache/</id>
    <content type="html"><![CDATA[<p>From the beginning NuGet used a per-solution folder <code>packages</code> to store all packages for
the projects in a solution. (Does anyone else remember the numerous discussion whether
that folder belongs into the VCS or not?).</p>
<p><a href="http://blog.nuget.org/20151008/NuGet-3-What-and-Why.html">That changed</a> with NuGet 3 and
<code>project.json</code>-based projects:</p>
<blockquote>
<h3 id="global-packages-folder">Global Packages Folder</h3>
<p>With Project.JSON managed projects, there is now a packages folder that is shared for
all projects that you work with. Packages are downloaded and stored in the
<code>%userprofile%\.nuget\packages</code> folder. This means that if you are working on multiple
UWP projects on your workstation, you only have one copy of the EntityFramework package
and its dependencies on your machine. All .NET projects will acquire package references
from this global shared folder. This also means that when you need to configure a new
project, your project will not take time starting so that it can download a fresh copy
of <code>EntityFramework.nupkg</code> Instead, it will simply and quickly reference the files you
have already downloaded. ASP.NET 5 uses the <code>%userprofile%\.dnx\packages</code> folder and as
that framework nears completion it will use the <code>%userprofile%\.nuget\packages</code> folder
as well.</p>
</blockquote>
<p>Well, I didn't pay much attention to that change, until I ran out of disk space last
week and used <a href="https://windirstat.net/">WinDirTree</a> to find the culprit. Indeed, the size
of my packages folder was more than 6 GB.</p>
<p>Therefore I wrote a small PowerShell script which deletes all packages which haven't
been accessed for a configurable number of days (150 by default):</p>
<script src="https://gist.github.com/c76f1a5533fa86e631b2ed9bbc43c412.js?file=Clear-NuGetCache.ps1"></script>Liquid error: One or more errors occurred.
<p>Don't worry that you could delete a package which you would need later again. NuGet will
just download the missing package again.</p>
<p>The script support the <code>-WhatIf</code> parameter, so calling</p>
<pre><code class="language-powershell">.\Clear-NuGetCache.ps1 -CutOffDays 90 -WhatIf
</code></pre>
<p>wouldn't delete a single byte but log which folders the script would remove.</p>]]></content>
  </entry>
  
  
  
  <entry>
    <title type="html"><![CDATA[Pretzel and Kudu on Azure]]></title>
    <link href="https://thomasfreudenberg.com/archive/2017/03/21/pretzel-and-kudu-on-azure/"/>
    <updated>2017-03-21T00:00:00+00:00</updated>
    <id>/archive/2017/03/21/pretzel-and-kudu-on-azure/</id>
    <content type="html"><![CDATA[<p>I've published a couple of posts about that I'm using <a href="https://github.com/Code52/pretzel">Pretzel</a>
to generate the HTML pages of my blog. However, I didn't talk about the hosting.</p>
<p>Actually, it's quite simple: The source files for the site are hosted in a
<a href="https://github.com/thoemmi/thomasfreudenberg.com">git repository on GitHub</a>. The generated site is
hosted in Azure. Whenever I push changes to the git repository, the web site will be updated
automatically.</p>
<div class="image-center"><p><img src="/files/archive/pretzel-and-azure.png" alt="Pretzel and Azure" /></p>
</div>
<p>The setup is a two-stage process: first, you have to create a Azure App Service and connect it to
your git repository. The steps involved are documented very well in
<a href="https://docs.microsoft.com/en-us/azure/app-service-web/app-service-continuous-deployment">Continuous Deployment to Azure App Service</a>.</p>
<p>The second step is to execute Pretzel on the Azure side. Enter <strong>Kudu</strong>. Kudu is the engine
behind git deployments in Azure. It's well documented in the <a href="https://github.com/projectkudu/kudu/wiki">wiki at GitHub</a>.
<a href="https://github.com/projectkudu/kudu/wiki/Deployment">By default</a>, Kudu will locate the relevant
<code>csproj</code> file, compile it, and copy the artifacts to wwwroot. That's why many web sizes running on
Azure contain an empty &quot;shim project&quot;.</p>
<p>However, you can simplify the setup by <a href="https://github.com/projectkudu/kudu/wiki/Customizing-deployments">customizing Kudu's behavior</a>.
In my case I want Kudu to run <code>pretzel.exe</code> to generate the static HTML files from my sources:</p>
<ol>
<li><p>Add <code>pretzel.exe</code> (and all its dependencies) to your git repository (I've used a subfolder named
<code>_pretzel</code>)</p>
</li>
<li><p>Add a batch file <code>deploy.cmd</code> to execute <code>pretzel.exe</code>:</p>
<pre><code class="language-batch">@echo off
echo Running Pretzel...
_pretzel\pretzel.exe bake --destination=%DEPLOYMENT_TARGET%
</code></pre>
<p><code>bake</code> is the Pretzel's command to generate the files, and the destination folder is <code>%DEPLOYMENT_TARGET%</code>,
which is the wwwroot folder.</p>
</li>
<li><p>Instruct Kudu to execute that <code>deploy.cmd</code> by creating a file <code>.deployment</code> with following
content:</p>
<pre><code class="language-ini">[config]
command = deploy.cmd
</code></pre>
</li>
</ol>
<p>That's all. Whenever I push changes to the git repository, Kudu will get the current files,
execute Pretzel, and the updated web site is public. The whole process takes less than a minute.</p>
<p>Of course this can be adapted to any other static site generator too, e.g. Jekyll.</p>]]></content>
  </entry>
  
  
  
  <entry>
    <title type="html"><![CDATA[Encrypting values when serializing with JSON.NET]]></title>
    <link href="https://thomasfreudenberg.com/archive/2017/02/11/encrypting-values-when-serializing-with-json-net/"/>
    <updated>2017-02-11T00:00:00+00:00</updated>
    <id>/archive/2017/02/11/encrypting-values-when-serializing-with-json-net/</id>
    <content type="html"><![CDATA[<p>In a small inhouse app I wrote recently I store the settings in a json file, using the
popular <a href="http://www.newtonsoft.com/json">Json.NET</a> library. However, the settings
include a password, which should't appear as clear text in the json file.</p>
<p>I stumbled over <a href="http://stackoverflow.com/a/29240043/4747">this</a> answer at Stack Overflow
by Brian Rogers. This solution uses a custom
<a href="http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Serialization_IContractResolver.htm"><code>IContractResolver</code></a>
and a new marker attribute <code>JsonEncryptAttribute</code>. Adding the attribute is quite easy:</p>
<pre><code class="language-csharp">public class Settings {
    [JsonEncrypt]
    public string Password { get; set; }
}
</code></pre>
<p>But you have to remember to add the <code>ContractResolver</code> additionally:</p>
<pre><code class="language-csharp">JsonConvert.SerializeObject(book, Formatting.Indented, new JsonSerializerSettings {
    ContractResolver = new EncryptedStringPropertyResolver (&quot;#my*S3cr3t&quot;)
});
</code></pre>
<p>Though the solution is clever, I don't like the custom <code>IContractResolver</code>. Therefore
I read through Json.NET's documentation to find an easier way, i.e. by only applying
an attribute to the property to encrypt.</p>
<p>In fact, Json.NET supports custom converters by annotating properties with
<a href="http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonConverterAttribute.htm"><code>JsonConverterAttribute</code></a>.
That attribute even allows you to pass additional parameters to your custom converter,
like in this case the encryption key.</p>
<p>Therefore I took Brian's code and converted it into a <code>JsonConverter</code> (also published as a
<a href="https://gist.github.com/thoemmi/e118c15e7588750b1cc18dab00be31fd#file-encryptingjsonconverter-cs">Gist</a>):</p>
<script src="https://gist.github.com/e118c15e7588750b1cc18dab00be31fd.js?file=EncryptingJsonConverter.cs"></script>Liquid error: One or more errors occurred.
<p>And the usage is pretty simple:</p>
<pre><code class="language-csharp">public class Settings {
    [JsonConverter(typeof(EncryptingJsonConverter), &quot;#my*S3cr3t&quot;)]
    public string Password { get; set; }
}
</code></pre>
<p>There's no need for any additional code like a custom <code>ContractResolver</code>.
And you can even use different encryption keys for different properties.</p>
<p>My code works only for <code>string</code> properties though, but that's all I needed.</p>]]></content>
  </entry>
  
  
  
  <entry>
    <title type="html"><![CDATA[Presenting Byte Size Values in WPF]]></title>
    <link href="https://thomasfreudenberg.com/archive/2017/01/21/presenting-byte-size-values-in-wpf/"/>
    <updated>2017-01-21T00:00:00+00:00</updated>
    <id>/archive/2017/01/21/presenting-byte-size-values-in-wpf/</id>
    <content type="html"><![CDATA[<p>Though it's not my main job, I still enjoy writing WPF application. Small tools, making
my colleagues' and my own life easier.</p>
<p>Recently I had the requirement to display size values in bytes, kilobytes, etc in a well-rounded way.
You will find many examples for formatting such values in the internet. Most look like this:</p>
<pre><code class="language-c#">string result;
if (number &gt;= 1024 * 1024 * 1024) {
    result = (number / 1024.0 / 1024 / 1024).ToString(&quot;F1&quot;) + &quot; GB&quot;;
} else if (number &gt;= 1024 * 1024) {
    result = (number / 1024.0 / 1024).ToString(&quot;F1&quot;) + &quot; MB&quot;;
} else if (number &gt;= 1024) {
    result = (number / 1024.0).ToString(&quot;F1&quot;) + &quot; KB&quot;;
} else {
    result = number + &quot; Bytes&quot;;
}
</code></pre>
<p>or, in a smarter way</p>
<pre><code class="language-c#">string[] sizes = { &quot;B&quot;, &quot;KB&quot;, &quot;MB&quot;, &quot;GB&quot;, &quot;TB&quot; };
double len = number;
int order = 0;
while (len &gt;= 1024 &amp;&amp; order &lt; sizes.Length - 1) {
    order++;
    len = len / 1024;
}
string result = $&quot;{len:0.##} {sizes[order]}&quot;;
</code></pre>
<p>However, if you're on the Windows platform, there's a much easier option:
<strong><a href="https://msdn.microsoft.com/en-us/library/windows/desktop/bb759975(v=vs.85).aspx"><code>StrFormatByteSize</code></a></strong>.
That's the same method that Explorer is using to display file sizes. Its advantages are that
you don't have any localization issues, and it it has a fixed precision of 3 digits.</p>
<p>Because my application is using WPF, I wrote a <code>IValueConverter</code> to be used in bindings:</p>
<script src="https://gist.github.com/03b81c07586f63accb83521d783d6749.js?file=FormatKbSizeConverter.cs"></script>Liquid error: One or more errors occurred.
<p>Formatting binded values in XAML becomes quite easy with that converter
(see <a href="https://gist.github.com/thoemmi/03b81c07586f63accb83521d783d6749#file-mainwindow-xaml">full XAML</a>):</p>
<pre><code class="language-xml">&lt;DataGrid
  AutoGenerateColumns=&quot;False&quot;
  IsReadOnly=&quot;True&quot;
  ItemsSource=&quot;{StaticResource numbers}&quot;&gt;
  &lt;DataGrid.Resources&gt;
    &lt;!--  the actual converter  --&gt;
    &lt;local:FormatKbSizeConverter x:Key=&quot;FormatKbSizeConverter&quot; /&gt;
  &lt;/DataGrid.Resources&gt;
  &lt;DataGrid.Columns&gt;
    &lt;!--  First column shows the plain values  --&gt;
    &lt;DataGridTextColumn
      Binding=&quot;{Binding}&quot;
      ElementStyle=&quot;{StaticResource RightCell}&quot;
      Header=&quot;Plain&quot; /&gt;
    &lt;!--  Second column shows the formatted values  --&gt;
    &lt;DataGridTextColumn
      Binding=&quot;{Binding Converter={StaticResource FormatKbSizeConverter}}&quot;
      ElementStyle=&quot;{StaticResource RightCell}&quot;
      Header=&quot;Formatted&quot; /&gt;
  &lt;/DataGrid.Columns&gt;
&lt;/DataGrid&gt;
</code></pre>
<div class="image-center"><p><img src="/files/archive/FormatKbSizeConverter.png" alt="FormatKbSizeConverter" /></p>
</div>]]></content>
  </entry>
  
  
  
  <entry>
    <title type="html"><![CDATA[Pretzel Plugin: Redirect]]></title>
    <link href="https://thomasfreudenberg.com/archive/2017/01/08/pretzel-redirect-plugin/"/>
    <updated>2017-01-08T00:00:00+00:00</updated>
    <id>/archive/2017/01/08/pretzel-redirect-plugin/</id>
    <content type="html"><![CDATA[<p>A while back I wrote about the migration of my blog from Community Server over Jekyll to Pretzel.</p>
<p>One golden rule when restructuring a web site is to avoid dead links. The original web engine was
a classic ASP.NET application, where every URL ends in <code>.aspx</code> (at least if you don't configure
extensionless URLs). Tens years ago every URLs ended in an extension like <code>.html</code>, <code>.php</code>, whatever.
Now-a-days, you barely see any file extensions anymore. The web servers don't expose the underlying
technology, and the user just doesn't care. And so does Pretzel.</p>
<p>To use a new URL schema, but preserve the old links and redirect them to the new schema, I wrote
an plugin for Pretzel, <a href="https://github.com/thoemmi/Pretzel.RedirectFrom">Pretzel.RedirectFrom</a>.
I've used the <a href="https://github.com/jekyll/jekyll-redirect-from">jekyll-redirect-from</a> plugin as
a guide, so the syntax is the same. Just add alternative URLs in the page's YAML front-matter:</p>
<pre><code class="language-yaml">---
title: &quot;My First Post&quot;
redirect_from:
  - /pages/page1
---
</code></pre>
<p>This will generate a small html page at <code>\pages\page1\index.html</code>, which will redirect to the new
location:</p>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;meta charset=&quot;utf-8&quot; /&gt;
&lt;title&gt;Redirecting...&lt;/title&gt;
&lt;link rel=&quot;canonical&quot; href=&quot;/2016/10/31/myfirstpost.html&quot; /&gt;
&lt;meta http-equiv=&quot;refresh&quot; content=&quot;0; url=/2016/10/31/myfirstpost.html&quot; /&gt;
&lt;h1&gt;Redirecting...&lt;/h1&gt;
&lt;a href=&quot;/2016/10/31/myfirstpost.html&quot;&gt;Click here if you are not redirected.&lt;/a&gt;
&lt;script&gt;
    location=&quot;/2016/10/31/myfirstpost.html&quot;
&lt;/script&gt;
</code></pre>
<p>Pretzel is a static file generator, so the redirection must be performed at the client-side.</p>
<p>However, I prefer a &quot;real&quot; redirect, i.e. a response with the correct HTTP status <code>301 Moved Permanently</code>.
Therefore I've implemented an additional switch. If you're using IIS (or Azure, or any other web server
supporting ASP.NET), you can specify the switch <code>redirect_generate_aspx: true</code> in Pretzel's
<code>_config.yml</code>. In this case the generated page will look like this:</p>
<pre><code class="language-aspnet">&lt;%@ Page Language=&quot;C#&quot;%&gt;
&lt;script runat=&quot;server&quot;&gt;
private void Page_Load(object sender, System.EventArgs e)
{
    Response.StatusCode = 301;
    Response.Status = &quot;301 Moved Permanently&quot;;
    Response.AddHeader(&quot;Location&quot;,&quot;/2016/10/31/myfirstpost.html&quot;);
    Response.End();
}
&lt;/script&gt;
</code></pre>
<p>This ensures that the server returns the correct HTTP status.</p>
<p>Anyway, this plugin is a <a href="https://github.com/Code52/pretzel/wiki/create-plugins">simple ScriptCs file</a>,
so you only have to copy
<a href="https://github.com/thoemmi/Pretzel.RedirectFrom/blob/master/Pretzel.RedirectFrom.csx">Pretzel.RedirectFrom.csx</a>
to the <code>_plugin</code> folder of your Pretzel site, and you will be ready to use redirects.</p>]]></content>
  </entry>
  
  
  
  <entry>
    <title type="html"><![CDATA[Pretzel Plugin: Sitemap]]></title>
    <link href="https://thomasfreudenberg.com/archive/2016/12/29/pretzel-sitemap/"/>
    <updated>2016-12-29T00:00:00+00:00</updated>
    <id>/archive/2016/12/29/pretzel-sitemap/</id>
    <content type="html"><![CDATA[<p>A couple of month ago <a href="/archive/2016/05/16/from-jekyll-to-pretzel/">I wrote</a> that
I switched to <strong>Pretzel</strong> to drive my site.</p>
<p>What I really like about Pretzel (except that it's written in .NET) is that it is
so <a href="https://github.com/Code52/pretzel/wiki/create-plugins">easy to extend</a>. You can
write plugins either as a .NET assembly, or—even simpler—throw in an
<code>.csx</code> file, because Pretzel supports <a href="http://scriptcs.net/">ScriptCs</a>.</p>
<p>One of the first extensions I wrote was a <strong><a href="https://en.wikipedia.org/wiki/Site_map">site map</a></strong>
plugin. By default Pretzel already creates a site map, but only for static pages.
Unfortunately, this doesn't include paginated pages like the home page. Those pages
are generated dynamically at runtime of Pretzel, and the default <code>sitemap.xml</code> doesn't
take those dynamic pages into account.</p>
<p>Therefore I wrote this plugin which creates the <code>sitemap.xml</code> including all generated
pages, even the paginated ones. It uses the same technique as
<a href="https://github.com/Code52/pretzel/blob/master/src/Pretzel.Logic/Templating/JekyllEngineBase.cs#L89"><code>JekyllEngineBase.ProcessFile</code></a>:
for each post and page it adds an <code>url</code> entry to the sitemap. Additionally it checks
the page's front-matter if <code>paginate</code> is specified, and adds relevant URLs to the sitemap
too.</p>
<p>The plugin is <a href="https://github.com/thoemmi/Pretzel.Sitemap">hosted on Github</a> including
some basic tests, but in fact you only have to copy
<a href="https://github.com/thoemmi/Pretzel.Sitemap/blob/master/Pretzel.Sitemap.csx"><code>Pretzel.Sitemap.csx</code></a>
to the <code>_plugin</code> folder of your Pretzel site.</p>]]></content>
  </entry>
  
  
  
  <entry>
    <title type="html"><![CDATA[Naming Events in .NET]]></title>
    <link href="https://thomasfreudenberg.com/archive/2016/07/01/naming-events-in-dotnet/"/>
    <updated>2016-07-01T00:00:00+00:00</updated>
    <id>/archive/2016/07/01/naming-events-in-dotnet/</id>
    <content type="html"><![CDATA[<p><strong>Update 2016/12/29</strong>: I've complained about the <code>On</code> prefix in the <a href="https://docs.microsoft.com/en-us/dotnet/articles/csharp/events-overview#comments-container">comment section</a>
of the documentation (and <a href="http://blog.gauffin.org/">Jonas Gauffin</a> too). In fact the prefix was a mistake and
is <a href="https://github.com/dotnet/docs/pull/1012">fixed</a> by now.</p>
<hr>
<p>Things are changing in the .NET world. A couple of days ago Microsoft released
<a href="https://blogs.msdn.microsoft.com/dotnet/2016/06/27/announcing-net-core-1-0/">.NET Core 1.0</a>,
the new cross-platform, open source, and modular .NET platform.</p>
<p>Unfortunately, not only the managed framework's changing, but naming guidelines
too.</p>
<p>Lets start with the old .NET framework. Microsoft says in the
<a href="https://msdn.microsoft.com/en-us/library/ms229012.aspx#Anchor_2">Naming Guideline for Events</a>:</p>
<blockquote>
<p><strong>✓ DO</strong> name events with a verb or a verb phrase.</p>
<p>Examples include <code>Clicked</code>, <code>Painting</code>, <code>DroppedDown</code>, and so on.</p>
<p><strong>✓ DO</strong> give events names with a concept of before and after, using the present
and past tenses.</p>
<p>For example, a close event that is raised before a window is closed would be
called <code>Closing</code>, and one that is raised after the window is closed would be
called <code>Closed</code>.</p>
</blockquote>
<p>The (slightly outdated) <a href="https://msdn.microsoft.com/en-us/library/h0eyck3s(VS.71).aspx">Event Naming Guidelines for .NET Framework 1.1</a>
even says more explicitly:</p>
<blockquote>
<ul>
<li>Do not use a prefix or suffix on the event declaration on the type. For
example, use <code>Close</code> instead of <code>OnClose</code>.</li>
</ul>
</blockquote>
<p>That's what we've been taught for the last 15 years: Events are named without
a prefix.</p>
<p>Let's repeat: Events are named without a prefix.</p>
<h2 id="entry.net-core">Entry .NET Core!</h2>
<p><a href="https://github.com/MrRoundRobin">Robin Müller</a>, maintainer of the <a href="https://github.com/MrRoundRobin/telegram.bot">telegram.bot</a>
library, changed the names of all event from an unprefixed name to prefixed with <code>On</code>
in a <a href="https://github.com/MrRoundRobin/telegram.bot/commit/54860e7048c2a0b76a206739d1bc1a2795e31199">recent commit</a>.
I complained that this renaming would contradict the guidelines recommendations by Microsoft
and what we've learnt the last 15 years.</p>
<p>However, Robin pointed me to the <a href="https://docs.microsoft.com/en-us/dotnet/articles/csharp/events-overview#language-support-for-events">new guidelines</a>
(emphasis mine):</p>
<blockquote>
<p>There are a number of conventions that you should follow when declaring an event.
Typically, the event delegate type has a void return. <strong>Prefix event declarations
with 'On'.</strong> The remainder of the name is a verb.</p>
</blockquote>
<p>WTF? Do we have to forget the old habits and rename all events when moving from good ol'
.NET Framework to .NET Core?</p>
<p>The new guidelines include a comment section at the bottom where I asked for the rational
behind the changed guideline a few days ago, but I still got no answer. I'd really like to
now...</p>
<p><strong>Sidenote:</strong> Most of us are used to name the <strong>handler</strong> for an event
<code>On&lt;name of the event&gt;</code>, e.g.</p>
<pre><code class="language-c#">foo.SomethingHappened += OnSomethingHappened;
</code></pre>
<p>What should we call those event handlers now? <code>OnOnSomethingHappened</code>?</p>]]></content>
  </entry>
  
  
  
  <entry>
    <title type="html"><![CDATA[From Jekyll To Pretzel]]></title>
    <link href="https://thomasfreudenberg.com/archive/2016/05/16/from-jekyll-to-pretzel/"/>
    <updated>2016-05-16T00:00:00+00:00</updated>
    <id>/archive/2016/05/16/from-jekyll-to-pretzel/</id>
    <content type="html"><![CDATA[<p><a href="/archive/2015/12/31/first-stop-jekyll/">Some time ago</a> I told that I converted my blog
from CommunityServer to <strong>Jekyll</strong> on <strong>Github Pages</strong>. However, I was not satisfied with
that solution. Running a static site has one drawback: redirects for moved pages.</p>
<p>When you change the structure of a web site, you don't want old links to reference now
invalid URLs. That's would be called <a href="https://en.wikipedia.org/wiki/Link_rot"><strong>link rot</strong></a>.
Instead, you want that users following a link to an old location are redirected to the
new page automatically.</p>
<p>Actually, there are plugins for Jekyll for redirection, the most popular is
<a href="https://github.com/jekyll/jekyll-redirect-from">jekyll-redirect-from</a>. However, what
it does is creating an HTML page at the old location with a <code>HTTP-REFRESH</code> meta tag
pointing to the new URL.</p>
<p>I don't like this solution because the status code of the HTTP response is <strong>200</strong>,
indicating that the old URL is still valid. I <em>guess</em> that Google or other search engines
pay attention to the <code>HTTP-REFRESH</code> meta tag, but nevertheless it's a bad idea for SEO
reasons.</p>
<p>Instead, a correct implementation would return the status code <strong>302</strong>, indicating that the
page moved permanently. Unfortunately that's not possible generally for static web sites.</p>
<p>That was the main reason I ditched Github Pages. I didn't want to go back to self-hosting
on a virtual server, so I decided to move my site to <strong>Azure</strong>. Additionally I took the
chance and replaced the blog engine too.</p>
<p>Not being a Ruby guy, I searched for a similar blog system but written in .NET. There are
a few, but the most appearing to me was the <a href="https://github.com/Code52/pretzel"><strong>Pretzel</strong></a>.
Pretzel is an open source blog system, behaving more or less the same as Jekyll.
Additionally it supports several extension points, which I as a developer really like.</p>
<p>I'll write about running Pretzel on Azure and different Pretzel extensions I wrote in
some future posts.</p>
<p><strong>TL;DR:</strong> I wanted to have more control over my website, therefore I moved from Github
Pages to Azure, and from Jekyll to Pretzel.</p>]]></content>
  </entry>
  
  
  
  <entry>
    <title type="html"><![CDATA[Password support in 7Zip4Powershell]]></title>
    <link href="https://thomasfreudenberg.com/archive/2016/03/31/7zip4powershell-with-password-support/"/>
    <updated>2016-03-31T00:00:00+00:00</updated>
    <id>/archive/2016/03/31/7zip4powershell-with-password-support/</id>
    <content type="html"><![CDATA[<div class="image-right"><p><img src="/files/archive/7zip4powershell-logo.png" alt="PowerShell Gallery Logo" /></p>
</div>
<p>A few minutes ago I published the new version 1.3 of <a href="https://github.com/thoemmi/7Zip4Powershell">7Zip4PowerShell</a>.
<a href="http://blog.onyxhat.com/">Isaac Springer</a> <a href="https://github.com/thoemmi/7Zip4Powershell/issues/8">asked</a> for password support when creating or extracting archives, so I
added the optional parameter <code>-Password</code> to both <code>Compress-7Zip</code> and <code>Expand-7Zip</code>.</p>
<p>You can get the new version at <a href="https://www.nuget.org/packages/7Zip4Powershell/1.3.0">NuGet</a> as well as
<a href="https://www.powershellgallery.com/packages/7Zip4Powershell/1.3.0">PowerShell Gallery</a>.</p>]]></content>
  </entry>
  
  
  
  <entry>
    <title type="html"><![CDATA[7Zip4Powershell in PowerShell Gallery]]></title>
    <link href="https://thomasfreudenberg.com/archive/2016/02/28/7zip4powershell-in-powershell-gallery/"/>
    <updated>2016-02-28T00:00:00+00:00</updated>
    <id>/archive/2016/02/28/7zip4powershell-in-powershell-gallery/</id>
    <content type="html"><![CDATA[<div class="image-right"><p><img src="/files/archive/powershell-gallery.png" alt="PowerShell Gallery Logo" /></p>
</div>
<p>A few days ago the <em>Preview</em> suffix was removed from <strong>PowerShell
Gallery</strong>. This gallery is a central repository for PowerShell content
such as modules and scripts. You can read the <a href="https://blogs.msdn.microsoft.com/powershell/2016/02/25/the-powershell-gallery-is-public/">public
announcement</a>
in the Windows PowerShell Blog. You can find instruction how to take
advantage of the gallery on its
<a href="https://www.powershellgallery.com/">homepage</a>, and more details on the <a href="https://www.powershellgallery.com/GettingStarted?section=Get%20Started">Get Started page</a>.</p>
<p>Until now I published
<strong><a href="https://github.com/thoemmi/7Zip4Powershell">7Zip4PowerShell</a></strong>, my
PowerShell commands to compress and expand files with 7-Zip, as a plain
assembly. However, several users asked for a &quot;real&quot; PowerShell module. I took
the public release of the PowerShell gallery as an opportunity to
accommondate that demand. The 7Zip4PowerShell module is now <a href="https://www.powershellgallery.com/packages/7Zip4Powershell/1.2.0">available
in the
gallery</a>,
and installing it is as simple as invoking</p>
<pre><code class="language-powershell">Install-Module -Name 7Zip4Powershell
</code></pre>
<p>I'm very happy that the folks at Microsoft created that gallery, because it makes the discovery of interesting modules so much easier.</p>]]></content>
  </entry>
  
  
  
  <entry>
    <title type="html"><![CDATA[Saving bandwidth with Zopfli]]></title>
    <link href="https://thomasfreudenberg.com/archive/2016/01/02/zopflipng/"/>
    <updated>2016-01-02T00:00:00+00:00</updated>
    <id>/archive/2016/01/02/zopflipng/</id>
    <content type="html"><![CDATA[<p>Today Jeff Atwood published the article <a href="http://blog.codinghorror.com/zopfli-optimization-literally-free-bandwidth/">Zopfli Optimization: Literally Free Bandwidth</a>, praising the compression algorithm <strong>Zopfli</strong>. Zopfli was created by Google and <a href="http://googledevelopers.blogspot.de/2013/02/compress-data-more-densely-with-zopfli.html">published in 2013</a>:</p>
<blockquote>
<p>The <a href="https://code.google.com/p/zopfli/">Zopfli Compression Algorithm</a> is a new open sourced general purpose data compression library that got its name from a Swiss bread recipe. It is an implementation of the Deflate compression algorithm that creates a smaller output size compared to previous techniques. [...]</p>
<p>The output generated by Zopfli is typically <a href="https://zopfli.googlecode.com/files/Data_compression_using_Zopfli.pdf">3–8% smaller</a> compared to <a href="http://en.wikipedia.org/wiki/Zlib">zlib</a> at maximum compression, and we believe that Zopfli represents the state of the art in Deflate-compatible compression. Zopfli is written in C for portability. It is a compression-only library; existing software can decompress the data. Zopfli is bit-stream compatible with compression used in gzip, Zip, PNG, HTTP requests, and others.</p>
</blockquote>
<p>Jeff gave Zopfli a try and got <a href="http://blog.codinghorror.com/zopfli-optimization-literally-free-bandwidth/">impressive results</a>:</p>
<blockquote>
<p>In my testing, Zopfli reliably produces 3 to 8 percent smaller PNG images than even the mighty PNGout, which is an incredible feat.</p>
</blockquote>
<p>However, Zopfli has one drawback. Its awesome compression ratio comes with a speed penalty, it's <a href="http://www.lifehacker.com.au/2013/03/a-look-at-zopfli-googles-open-source-compression-algorithm/">more than <strong>80 times slower</strong> than gzip</a>.</p>
<p>Because of its slowness Zopfli is not the best choice for compression at runtime. But where it really shines is when it's used for pre-compressed data. A very good candidate are PNG encoded images. There's even a Zopfli encoder for that purpose, <strong>ZopfliPNG</strong>.</p>
<p>So because of the proclaimed reduction of the size of PNGs, I gave ZopfliPNG a try. First I measured the current size of all PNG images of my site with this PowerShell command:</p>
<pre><code class="language-powershell">PS&gt; gci *.png -Recurse | Measure-Object -Sum Length

Count    : 110
Average  :
Sum      : 4775284
Maximum  :
Minimum  :
Property : Length
</code></pre>
<p>That's about <strong>4.6 MiB</strong> of PNGs. Than I let ZopfliPNG re-compress all these files:</p>
<pre><code class="language-powershell">gci *.png -Recurse | %{ zopflipng.exe -y --lossy_transparent $_.FullName $_.FullName }
</code></pre>
<p>A few minutes and 110 files later the command has finished. 56 files have been changed, i.e. ZopfliPNG was able to produce a smaller size for more than half of all images.</p>
<p>The entire size of all PNGs is now this:</p>
<pre><code class="language-powershell">PS&gt; gci *.png -Recurse | Measure-Object -Sum Length

Count    : 110
Average  :
Sum      : 3616048
Maximum  :
Minimum  :
Property : Length
</code></pre>
<p>So from the former 4.6 MiB it went down to <strong>3.4 MiB</strong>, that's a reduction by <strong>26 percent</strong>. Quite impressive for just changing the compression algorithm.</p>]]></content>
  </entry>
  
  
  
  <entry>
    <title type="html"><![CDATA[My Journey to Pretzel: First Stop Jekyll]]></title>
    <link href="https://thomasfreudenberg.com/archive/2015/12/31/first-stop-jekyll/"/>
    <updated>2015-12-31T00:00:00+00:00</updated>
    <id>/archive/2015/12/31/first-stop-jekyll/</id>
    <content type="html"><![CDATA[<p>As described in my <a href="/archive/2015/12/30/journey_to_pretzel/">previous post</a>, I decided to replace my CommunityServer setup with a static site generator. Being a vivid GitHub user, the first choice was <a href="https://pages.github.com/">GitHub Pages</a>. GitHub Pages allows you to commit your site to a repository and let GitHub serve it using <a href="http://jekyllrb.com/">Jekyll</a>.</p>
<p>I won't go into detail how to setup Jekyll or GitHub Pages. You'll be able to find enough information in the internet. Phil Haack, a much better story teller than me, wrote an article about <a href="http://haacked.com/archive/2013/12/02/dr-jekyll-and-mr-haack/">his migration from SubText to Jekyll</a>. He also gave advice how to <a href="http://haacked.com/archive/2013/12/09/preserving-disqus-comments-with-jekyll/">preserve all comments with Disqus</a>.</p>
<p>So my first step was to get the data of my existing site out of CommunityServer and into a format that Jekyll understands. <a href="http://www.keyvan.tech/">Keyvan Nayyeri</a> wrote once <a href="http://blogml.codeplex.com/">an extension for CommunityServer</a> to download the content as a <a href="https://en.wikipedia.org/wiki/BlogML">BlogML</a> document (a standarized XML format for storing blog content).</p>
<p>Then I found <a href="https://github.com/pcibraro/BlogMLToMarkdown">BlogMLToMarkdown</a>, a command line tool transforming a BlogML document to markdown documents ready to be consumed by Jekyll.</p>
<p>However, I had to tweak that tool for my needs. Amongst others it</p>
<ul>
<li>downloads all images, attachments, and other files hosted on my old site and changes the referencing links,</li>
<li>fixes redirects, and</li>
<li>exports all (approved) comments to a <code>disqus.wxr</code>, ready to be imported into <a href="https://disqus.com/">Disqus</a>.</li>
</ul>
<p>If you're interested you can see my <a href="https://github.com/thoemmi/BlogMLToMarkdown">fork at Github</a>.</p>
<p>After I transformed my blog and tweaked the style (it's based on <a href="http://hyde.getpoole.com/">Hyde</a>), I committed it to a GitHub repository, where it was happily hosted.</p>
<p>However, this setup had some drawbacks, which I will discuss in another post.</p>]]></content>
  </entry>
  
  
  
  <entry>
    <title type="html"><![CDATA[My Journey to Pretzel: Preface]]></title>
    <link href="https://thomasfreudenberg.com/archive/2015/12/30/journey_to_pretzel/"/>
    <updated>2015-12-30T00:00:00+00:00</updated>
    <id>/archive/2015/12/30/journey_to_pretzel/</id>
    <content type="html"><![CDATA[<p>After running my site for more than 12 years, I decided it was time to replace the software behind it with something new.</p>
<p>I started this blog with <strong>.Text</strong> in August of 2002, which later was merged into <strong>CommunityServer</strong>. I wrote many extensions for CS, customized it in many ways, and was active in the community. <a href="http://telligent.com/">Telligent</a>, the company behind CommunityServer, even awarded me with a MVP status.</p>
<p>However, I lost interest in CS after a while. I started writing my own blog engine (as most developers do I guess). Well, not only once but countless times. Every few months I threw away the current code and started again from scratch. I took the opportunity to play around with the newest stuff, <a href="http://www.asp.net/mvc">ASP.NET MVC</a> and <a href="http://nancyfx.org/">Nancy</a>, <a href="http://www.asp.net/entity-framework">Entity Framework</a> or <a href="http://ravendb.net/">RavenDb</a>, n-tier architecture or <a href="http://codebetter.com/gregyoung/2010/02/16/cqrs-task-based-uis-event-sourcing-agh/">CQRS</a>.</p>
<p>Well, though I learnt a lot about the different technologies, libraries etc, I never got to the point where my software was ready to be published.</p>
<p>Finally I decided to overcome my developer ego and use some existing software. A few month ago I switched to <a href="http://jekyllrb.com/">Jekyll</a>, a static site generator written in Ruby. Some weeks later I switched again, this time to <a href="https://github.com/Code52/pretzel">Pretzel</a>, which is very similar to Jekyll but written in .NET.</p>
<p>After writing this introduction, I intend to publish a couple of posts about the different stations of my journey to Pretzel in the next few weeks. E.g. I wrote several extensions for Pretzel, and I configured Azure for auto-deployment whenever I push to the <a href="https://github.com/thoemmi/thomasfreudenberg.com">git repository of this site</a>.</p>]]></content>
  </entry>
  
  
  
  <entry>
    <title type="html"><![CDATA[NuGet package for 7Zip4Powershell]]></title>
    <link href="https://thomasfreudenberg.com/archive/2013/04/19/nuget-package-for-7zip4powershell/"/>
    <updated>2013-04-19T16:06:19+00:00</updated>
    <id>/archive/2013/04/19/nuget-package-for-7zip4powershell/</id>
    <content type="html"><![CDATA[<div class="image-right"><p><img src="/files/archive/nuget.png" alt="nuget" title="nuget" /></p>
</div>
<p>A few days ago I mentioned <a href="/archive/2013/04/07/7-zip-for-powershell/">7-Zip for Powershell</a>. I’ve now created a NuGet package and published it at <a href="https://nuget.org/packages/7Zip4Powershell/">NuGet.org</a>.</p>
<p>It took me a while to figure it out, but finally it’s a “tools only” package, i.e. it adds no references to your project.</p>
<p>To use the new commands just add the package to your solution and import it in your Powershell script:</p>
<pre><code class="language-powershell">$SolutionDir = split-path -parent $PSCommandPath
Import-Module (Join-Path $SolutionDir &quot;packages\7Zip4Powershell.1.0\tools\7Zip4Powershell.dll&quot;)
</code></pre>]]></content>
  </entry>
  
  
  
  <entry>
    <title type="html"><![CDATA[Fun with RavenDB and ASP.NET MVC&#58; part I]]></title>
    <link href="https://thomasfreudenberg.com/archive/2013/04/07/fun-with-ravendb-and-asp-net-mvc-part-i/"/>
    <updated>2013-04-07T20:09:55+00:00</updated>
    <id>/archive/2013/04/07/fun-with-ravendb-and-asp-net-mvc-part-i/</id>
    <content type="html"><![CDATA[<p>I’m working on a small pet project with ASP.NET MVC, where hierarchical structured documents are stored in <a href="http://ravendb.net/">RavenDB</a>. These documents can be retrieved by their unique URL, which is also stored in the document. Because there are different kinds of document class, they all derive from the common interface <code>IRoutable</code>. This interface defines a property <code>Path</code>, by which the document can be accessed.</p>
<pre><code class="language-csharp">public interface IRoutable {
    string Id { get; set; }
    string Path { get; set; }
}

public class Document : IRoutable {
    public string Id { get; set; }
    public string Path { get; set; }
}

using (var session = _store.OpenSession()) {
    session.Store(new Document { Path = &quot;a&quot; });
    session.Store(new Document { Path = &quot;a/b&quot; });
    session.Store(new Document { Path = &quot;a/b/c&quot; });
    session.Store(new Document { Path = &quot;a/d&quot; });
    session.Store(new Document { Path = &quot;a/d/e&quot; });
    session.Store(new Document { Path = &quot;a/f&quot; });
    session.SaveChanges();
}
</code></pre>
<p>Additionally there’s the requirement, that the incoming URL may consist of more parts than the document’s path, carrying some additional information about the request. Here are some examples of possible requests, and which document should match:</p>
<table>
<thead>
<tr>
<th>Request</th>
<th>Found document</th>
</tr>
</thead>
<tbody>
<tr>
<td>a/x</td>
<td>a</td>
</tr>
<tr>
<td>a/b/c/y/z</td>
<td>a/b/c</td>
</tr>
</tbody>
</table>
<p>So, given the path, how can you find the correct document?</p>
<p>The solution to this consists of three parts:</p>
<ol>
<li>Identify documents in the database which can be accessed via their path</li>
<li>Index those documents</li>
<li>Find the document which matches best a given URL</li>
</ol>
<h3 id="marking-routable-documents">Marking routable documents</h3>
<p>Because there’s not a single class for pages stored in the database, I mark all documents implementing <code>IRoutable</code> by adding a flag <code>IsRoutable</code> to the document’s metadata. This is done by implementing <a href="http://ravendb.net/docs/2.0/client-api/advanced/client-side-listeners"><code>IDocumentStoreListener</code></a>, so the code is called by RavenDB whenever a document is stored:</p>
<pre><code class="language-csharp">public class DocumentStoreListener : IDocumentStoreListener {
    public const string IS_ROUTABLE = &quot;IsRoutable&quot;;

    public bool BeforeStore(string key, object entityInstance, RavenJObject metadata, RavenJObject original) {
        var document = entityInstance as IRoutable;
        if (document == null) {
            return false;
        }
        if (metadata.ContainsKey(IS_ROUTABLE) &amp;&amp; metadata.Value&lt;bool&gt;(IS_ROUTABLE)) {
            return false;
        }
        metadata.Add(IS_ROUTABLE, true);
        return true;
    }

    public void AfterStore(string key, object entityInstance, RavenJObject metadata) {
    }
}
</code></pre>
<h3 id="indexing-routable-documents">Indexing routable documents</h3>
<p>The next step is to create an index for all documents with the proper flag in their metadata:</p>
<pre><code class="language-csharp">public class IRoutable_ByPath : AbstractIndexCreationTask {
    public override IndexDefinition CreateIndexDefinition() {
        return new IndexDefinition {
            Map = @&quot;from doc in docs where doc[&quot;&quot;@metadata&quot;&quot;][&quot;&quot;&quot; + DocumentStoreListener.IS_ROUTABLE + @&quot;&quot;&quot;].ToString() == &quot;&quot;True&quot;&quot; select new { doc.Path }&quot;
        };
    }
}
</code></pre>
<h3 id="searching-for-documents">Searching for documents</h3>
<p>Ok, so much for the preparation. The interesting part starts when a request comes in. Here RavenDB’s <a href="http://ravendb.net/docs/2.0/client-api/querying/static-indexes/searching#boosting">boosting</a> feature is quite handy. The more parts of the path match, the higher score the document will get. E.g. if the requested path is <code>a/b/c/d/e</code>, following RavenDB search will be queried:</p>
<table>
<thead>
<tr>
<th>search term</th>
<th>boost</th>
</tr>
</thead>
<tbody>
<tr>
<td>a/b/c/d/e</td>
<td>5</td>
</tr>
<tr>
<td>a/b/c/d</td>
<td>4</td>
</tr>
<tr>
<td>a/b/c</td>
<td>3</td>
</tr>
<tr>
<td>a/b</td>
<td>2</td>
</tr>
<tr>
<td>a</td>
<td>1</td>
</tr>
</tbody>
</table>
<p>The code to create such a query looks like this:</p>
<pre><code class="language-csharp">public IRoutable GetRoutable(string path) {
    var query = _documentSession
        .Query&lt;IRoutable, IRoutable_ByPath&gt;();

    if (!String.IsNullOrEmpty(path)) {
        var pathParts = path.Split('/');
        for (var i = 1; i &lt;= pathParts.Length; ++i) {
            var shortenedPath = String.Join(&quot;/&quot;, pathParts, startIndex: 0, count: i);
            query = query.Search(doc =&gt; doc.Path, shortenedPath, boost: i, options: SearchOptions.Or);
        }
    } else {
        query = query.Where(doc =&gt; doc.Path == String.Empty);
    }

    var document = query.Take(1).FirstOrDefault();
    return document;
}
</code></pre>
<p>This method will finally return the document with the longest matching path.</p>
<p>Based on the incoming request we have found a matching document. What we can do with the remaining part of the URL I’ll leave for the next installment.</p>
<p>I published the complete code with unit tests in this <a href="https://github.com/thoemmi/FunWithRavenDB">Github repository</a>.</p>]]></content>
  </entry>
  
  
  
  <entry>
    <title type="html"><![CDATA[7-Zip for Powershell]]></title>
    <link href="https://thomasfreudenberg.com/archive/2013/04/07/7-zip-for-powershell/"/>
    <updated>2013-04-07T14:27:56+00:00</updated>
    <id>/archive/2013/04/07/7-zip-for-powershell/</id>
    <content type="html"><![CDATA[<div class="image-right"><p><img src="/files/archive/powershell_logo.jpg" alt="powershell_logo" title="powershell_logo" /></p>
</div>
<p>At work we deal with different big databases, and by big I mean between 3.5 and 8 GB. Those databases are zipped with <a href="http://7-zip.org/">7-Zip</a> and stored on a server. Depending on the scenario we unzip one of these databases to a local folder and attach it to the SQL Server. To simplify these steps we have a couple of Powershell scripts, among other things invoking the command line version of 7-Zip.</p>
<p>However, extracting an archive of several gigabytes over the network might take some time, and we’d like to see the progress in the Powershell console. Powershell provides a standard way to report progress by calling <a href="http://msdn.microsoft.com/en-us/library/system.management.automation.cmdlet.writeprogress(v=vs.85).aspx"><code>Cmdlet.WriteProgress</code></a>, which then will be displayed by the current host (e.g. command line) appropriately.</p>
<p>Therefore with some support of a co-worker I’ve written two <strong>Cmdlet</strong>s for extracting and compressing archives. The syntax is simple as this:</p>
<pre><code>Expand-7Zip
    [-ArchiveFileName] &lt;string&gt;
    [-TargetPath] &lt;string&gt;
    [&lt;CommonParameters&gt;]

Compress-7Zip 
    [-ArchiveFileName] &lt;string&gt; 
    [-Path] &lt;string&gt;
    [[-Filter] &lt;string&gt;]
    [-Format &lt;OutArchiveFormat&gt; {SevenZip | Zip | GZip | BZip2 | Tar | XZ}]
    [-CompressionLevel &lt;CompressionLevel&gt; {None | Fast | Low | Normal | High | Ultra}]
    [-CompressionMethod &lt;CompressionMethod&gt; {Copy | Deflate | Deflate64 | BZip2 | Lzma | Lzma2 | Ppmd | Default}]
    [&lt;CommonParameters&gt;]
</code></pre>
<p>It works with both x86 and x64 and uses <a href="https://sevenzipsharp.codeplex.com/">SevenZipSharp</a> as a wrapper around 7zip’s API.</p>
<p><img src="/files/archive/7zip4powershell.png" alt="7zip4powershell" title="7zip4powershell" /></p>
<p>You can download the cmdlets with the required libraries <a href="/files/archive/7Zip4Powershell.zip">here</a> or grap the sources at <a href="https://github.com/thoemmi/7Zip4Powershell">Github</a>.</p>]]></content>
  </entry>
  
  
  
  <entry>
    <title type="html"><![CDATA[Don’t copy my referenced assemblies]]></title>
    <link href="https://thomasfreudenberg.com/archive/2012/11/21/dont-copy-my-referenced-assemblies/"/>
    <updated>2012-11-21T06:51:17+00:00</updated>
    <id>/archive/2012/11/21/dont-copy-my-referenced-assemblies/</id>
    <content type="html"><![CDATA[<p>There are cases where you don’t want referenced assemblies to be copied to your output folder.</p>
<p>E.g. you write a plugin for an existing application, which provides a library declaring its contracts. Since the application will load that contract assembly itself, there’s no need for a second copy of the assembly in your plugin folder.</p>
<p>“But you can configure Visual Studio not to copy a reference to the output folder,” you may say. Well, that’s right. In the properties of a referenced assembly you can simply set <strong>Copy Local</strong> to <strong>False</strong>.</p>
<p>But…</p>
<p>If you’re an avid user of NuGet like I am, every time you update a package, the old references are removed from your project and the new ones will be added, and <strong>Copy Local</strong> will be <strong>True</strong> again. Do you think you will always remember to change that property back to <strong>False</strong> whenever you update a package? I don’t know about you, but I won’t.</p>
<p>Therefore, here’s a little trick I use in such cases. I have a little MSBuild file which suppresses any referenced assembly to be copied to the output folder:</p>
<pre><code class="language-xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;Project ToolsVersion=&quot;4.0&quot; xmlns=&quot;http://schemas.microsoft.com/developer/msbuild/2003&quot;&gt;

  &lt;!-- make all references non-private, so they won't be copied to the output folder --&gt;
  &lt;Target Name=&quot;ClearReferenceCopyLocalPaths&quot; AfterTargets=&quot;ResolveAssemblyReferences&quot;&gt;
    &lt;ItemGroup&gt;
      &lt;ReferenceCopyLocalPaths Remove=&quot;@(ReferenceCopyLocalPaths)&quot; /&gt;
    &lt;/ItemGroup&gt;
  &lt;/Target&gt;

&lt;/Project&gt;
</code></pre>
<p>Save that snippet to a file i.e. <strong>PreBuild.targets</strong>, and include it in your project file like this:</p>
<pre><code class="language-xml">  &lt;Import Project=&quot;$(MSBuildToolsPath)\Microsoft.CSharp.targets&quot; /&gt;
  &lt;Import Project=&quot;$(SolutionDir)\.nuget\nuget.targets&quot; /&gt;
  &lt;Import Project=&quot;PreBuild.targets&quot; /&gt;
</code></pre>
<p>That’s it. From now on the output folder will only contain your assembly (along with other build artifacts such as the pdb file, of course)</p>]]></content>
  </entry>
  
  
</feed>