<?xml version="1.0" encoding="UTF-8"?><rss 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" version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Benjamin Proemmer]]></title><description><![CDATA[{ my life with dotnet }]]></description><link>https://proemmer.azurewebsites.net/</link><generator>Ghost 0.9</generator><lastBuildDate>Fri, 15 May 2026 08:41:59 GMT</lastBuildDate><atom:link href="https://proemmer.azurewebsites.net/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Configuration and the IOptions pattern]]></title><description><![CDATA[<p>(This article is based on .NET Core SDK 1.0.0-preview2.1-003155 and "Microsoft.Extensions.Options.ConfigurationExtensions": "1.1.0-*")</p>

<p>There are some improvements of the way we get access to our configuration files in ASP.NET Core. The time as we did assign the properties of our config classes</p>]]></description><link>https://proemmer.azurewebsites.net/2016/11/13/configuration-and-the-ioptions-pattern/</link><guid isPermaLink="false">c0c2c091-ec39-4f41-8777-73d6e19ee636</guid><dc:creator><![CDATA[Benjamin Prömmer]]></dc:creator><pubDate>Sun, 13 Nov 2016 21:16:13 GMT</pubDate><content:encoded><![CDATA[<p>(This article is based on .NET Core SDK 1.0.0-preview2.1-003155 and "Microsoft.Extensions.Options.ConfigurationExtensions": "1.1.0-*")</p>

<p>There are some improvements of the way we get access to our configuration files in ASP.NET Core. The time as we did assign the properties of our config classes by ourselves and we have to deal with config entry keys is gone. With <code>Microsoft.Extensions.Configuration</code> and the <code>Microsoft.Extensions.Options</code> package we now have the ability to map our configuration sections to <a href="https://en.wikipedia.org/wiki/Plain_Old_CLR_Object">POCO's</a> and inject them where we need it. </p>

<p>This is very helpful for a cleaner design not least since because the ASP.NET Core framework gives us the ability to store our configuration on different places. These places for example could be files (e.g. <code>appsettings.json</code>, <code>$"appsettings.{env.EnvironmentName}.json"</code>), environment variables, command line arguments an something else. So let us explore what paths we are now open to, and if you would try this by yourselves, you could find the sample code on GitHub in a <a href="https://github.com/proemmer/Configuration.Sample">SampleProject</a>. </p>

<h1 id="configurationbuilder">ConfigurationBuilder</h1>

<p>The entry point of our configuration system is the class <a href="https://github.com/aspnet/Configuration/blob/1376ae0d9230c3552b8c8e3f5303ec1e271e0de5/src/Microsoft.Extensions.Configuration.Abstractions/IConfigurationBuilder.cs"><code>ConfigurationBuilder</code></a>. This is the place where we can configure our configuration sources. After calling the <code>Build</code> method, we have full access to the configuration by using the <a href="https://github.com/aspnet/Configuration/blob/1376ae0d9230c3552b8c8e3f5303ec1e271e0de5/src/Microsoft.Extensions.Configuration.Abstractions/IConfigurationRoot.cs"><code>IConfigurationRoot</code></a> interface which also inherits the <a href="https://github.com/aspnet/Configuration/blob/1376ae0d9230c3552b8c8e3f5303ec1e271e0de5/src/Microsoft.Extensions.Configuration.Abstractions/IConfiguration.cs"><code>IConfiguration</code></a> interface.</p>

<pre><code class="language-c#">public IConfigurationRoot Configuration { get; }

public Startup(IHostingEnvironment env)  
{
    var builder = new ConfigurationBuilder()
        .AddCommandLine(Environment.GetCommandLineArgs())
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();
    Configuration = builder.Build();
}
</code></pre>

<p>To read now our configuration values we can use some of the interface methods like them shown below.</p>

<pre><code class="language-c#">//Gets or sets a configuration value.
string this[string key] { get; set; }

//Gets the immediate descendant configuration sub-sections.
IEnumerable&lt;IConfigurationSection&gt; GetChildren();

//Gets a configuration sub-section with the specified key.
IConfigurationSection GetSection(string key);  
</code></pre>

<h1 id="ioptionsandioptionsmonitor">IOptions and IOptionsMonitor</h1>

<p>And now let's take a look onto the new and recommended way to get access to the configuration values. This method named <code>Options pattern</code> is, as I think, a much better way doing this. </p>

<p>Firstly we have to create a <code>POCO</code>. The properties of this are representing our configuration settings/entries. For this class it is not necessary to inherit from any other class (for example there is no ConfigurationBase class or so).</p>

<pre><code class="language-c#">public class MySettings  
{
    public string MySettingsEnry1{get; set;}
    public List&lt;string&gt; MySettingsEnryList{get; set;}
    public int MySettingsNumber{get; set;}
}
</code></pre>

<p><code>Attention: IEnumerable instead of List would not work!</code></p>

<p>As you can see, you create it with with strongly typed properties, not only 'everything is a string' and map it to a corresponding <code>JSON</code> section of our settings file. As a sample of this, we can map the <code>JSON</code> configuration section below with the class above according you have configured the binding as described in the next section.</p>

<pre><code class="language-json">{
  "MySettings" :{
    "MySettingsEnry1":"Value",
    "MySettingsEnryList":[
       "A",
       "B"
    ],
    "MySettingsNumber": 10
  }
}
</code></pre>

<h1 id="startupconfiguretheoptionsbindings">Startup (configure the options bindings)</h1>

<p>To use the configuration <code>POCO's</code> with the <code>Options Pattern</code> we now have to do some minimal configuration effort. But this is not so much work, it can easily be done in the <code>ConfigureServices</code> method of the <code>Startup</code> class. </p>

<p>In this method we have to define the mapping of the <code>POCO's</code> and the <code>Section's</code> of the configuration file. There we have to call <code>services.Configure&lt;POCONAME&gt;(CONFIGSECTION)</code> for every single mapping. And after this we than have to register the needed services in the <a href="https://en.wikipedia.org/wiki/Inversion_of_control"><code>Ioc</code></a> of ASP.NET Core by calling  <code>services.AddOptions()</code>. These few steps are shown in the next code snipet.</p>

<pre><code class="language-c#">public class Startup  
{
    public IConfigurationRoot Configuration { get; }

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure&lt;MySettings&gt;(Configuration.GetSection("MySettings"));
        services.AddOptions();

        services.AddSingleton&lt;IMySampleService, MySampleService&gt;();
        ...
        services.AddMvc()
    }
}
</code></pre>

<h1 id="useyouroptions">Use your options</h1>

<p>So now after we have configured all our needs I will show how we can use it in action. At this point we have two choices. First we take a look at the <code>normal</code> way where we only get an instance of our configuration <code>POCO</code> to read (and also write) our settings. </p>

<p>(Notice: Writing the settings could only change the value in the memory, not in the file. 
If you use the <code>IOptions&lt;MySettings&gt;</code> in different services, there will be an instance per service, which means if you change a settings value in service A, the settings value in service B will not be affected.)</p>

<pre><code class="language-c#">public class MySampleService  
{
    private IOptions&lt;MySettings&gt; _settings;

    public MySampleService(IOptions&lt;MySettings&gt; settings)
    {
        _settings = settings; 
        //access options with _settings.Value.[PropertyName]
    }
}
</code></pre>

<p>Now the second and more cool way is to use <code>IOptionsMonitor</code> which gave us also access to the configuration. But, in this variant we always have access to the current value also even the values of the configurations will get changed.(This means, another service which also has an injected IOptionsMonitor<mysettings> changes the settings in memory and also when the configuration file was changed). If we want to be informed about the changes of our files, we additionally have to configure <code>reloadOnChange: true</code> in our <code>ConfigurationBuilder</code>. </mysettings></p>

<pre><code class="language-c#">public class MySampleService  
{
    private IOptionsMonitor&lt;MySettings&gt; _settings;
    private IDisposable _configWatcher;

    public MySettings Settings{ get{ return _settings.CurrentValue; }}

    public MySampleService(IOptionsMonitor&lt;MySettings&gt; settings)
    {
        _settings = settings;
        _configWatcher = _settings.OnChange(ConfigChanged); 
        //access options with _settings.CurrentValue.[PropertyName]
    }

    private void ConfigChanged(MySettings currentConfig)
    {
    }
}
</code></pre>

<p>As the sample above shows, we always have access to the current configuration data by using the <code>Settings</code> property, because this points always on the <code>CurrentValue</code> of the settings <code>POCO</code>. <br>
If you also need to get informed of a configuration change in your code, you could register the <code>OnChanged</code> Action of the <code>IOptionsMonitor</code>. </p>

<h1 id="onethingismissing">One thing is missing</h1>

<p>As cool as this stuff already is, one thing is missing. In some of my projects i would like to change some configuration parts at the run time and then persist it to the file or so. But at the time of writing this post, there was no way implemented to do this. Nevertheless as the GitHub-Page of the ASP.Net team shows, this feature is on the <a href="https://github.com/aspnet/Configuration/issues/386">backlog</a>.</p>

<h1 id="summary">Summary</h1>

<p>I think this extension of configuration is very helpful to create a clean and easy way to access your configuration data. I am very interested in how this component will evolve and what exciting functions will still be waiting for us.</p>

<p>In the reference section and in the language integration section you can find some additional links I used to learn and understand the functionality. I hope you find this article helpful. If this is the case or if you have some questions or find some bugs, please post in the comment section below. I will thankfully use your input to improve this blog-post</p>

<h1 id="references">References</h1>

<ul>
<li><a href="https://github.com/aspnet/Options">SourceCode</a></li>
<li><a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration">ASP.Net Core Documentation</a></li>
<li><a href="http://andrewlock.net/how-to-use-the-ioptions-pattern-for-configuration-in-asp-net-core-rc2/">How to use the IOptions pattern for configuration in ASP.NET Core RC2</a></li>
<li><a href="http://www.davidhayden.me/blog/asp-net-5-configuration-and-ioptions">IOptions</a></li>
</ul>]]></content:encoded></item><item><title><![CDATA[Segments and Slices]]></title><description><![CDATA[<h1 id="arraysegment">ArraySegment</h1>

<p>What the hell do I need that? That was my first thought as I once again tried to implement a TCP communication by using <code>System.Net.Sockets</code> in C#. Because I never used this type, I started to find out the difference between <code>IList&lt;ArraySegment&lt;byte&gt;</code></p>]]></description><link>https://proemmer.azurewebsites.net/2016/10/14/segments-and-slices/</link><guid isPermaLink="false">8f329aa4-e6db-46a0-b661-347a03631bc9</guid><dc:creator><![CDATA[Benjamin Prömmer]]></dc:creator><pubDate>Fri, 14 Oct 2016 14:51:03 GMT</pubDate><content:encoded><![CDATA[<h1 id="arraysegment">ArraySegment</h1>

<p>What the hell do I need that? That was my first thought as I once again tried to implement a TCP communication by using <code>System.Net.Sockets</code> in C#. Because I never used this type, I started to find out the difference between <code>IList&lt;ArraySegment&lt;byte&gt;&gt;</code> and <code>byte[]</code> which I used before. First of all I took a look on the <a href="https://msdn.microsoft.com/en-us/library/1hsbd92d(v=vs.110).aspx">MSDN</a> page where was written:</p>

<pre><code>ArraySegment&lt;T&gt; is a wrapper around an array that delimits a range of elements in that array. Multiple ArraySegment&lt;T&gt; instances can refer to the same original array and can overlap. The original array must be one-dimensional and must have zero-based indexing.

Note, however, that although the ArraySegment&lt;T&gt; structure can be used to divide an array into distinct segments, the segments are not completely independent of one another. The Array property returns the entire original array, not a copy of the array; therefore, changes made to the array returned by the Array property are made to the original array. If this is undesirable, you should perform operations on a copy of the array, rather than an ArraySegment&lt;T&gt; object that represents a portion of the array. 
</code></pre>

<p>Furthermore I found that this struct was part of the .NET Framework since version 2.0 (And is used in sockets since .NET Framework 3.5), and since version 4.6 <a href="https://msdn.microsoft.com/en-us/library/1hsbd92d(v=vs.110).aspx"><code>ArraySegment&lt;T&gt;</code></a> implements also the interface <a href="https://msdn.microsoft.com/en-us/library/hh881542(v=vs.110).aspx"><code>IReadOnlyCollection&lt;T&gt;</code></a> which represents a strongly-typed, read-only collection of elements. </p>

<p>The core benefit of this is that an <code>ArraySegment&lt;T&gt;</code> structure is useful whenever the elements of an array will be manipulated in distinct segments. But what does this mean in real? What is so useful? Why should it be better than a list or another container datatype?</p>

<p>To find that out, I was just playing around a little bit to show how I can use it. For this blog-post, I provided a <a href="https://github.com/proemmer/SegmentsAndSlices.Sample">sample project</a> with my tries on GitHub where I used the MSDN sample code as a Template:</p>

<pre><code class="language-c#">private static void Usage()  
{
    var buffer = new byte[10];
    var segment1 = new ArraySegment&lt;byte&gt;(buffer);
    var segment2 = new ArraySegment&lt;byte&gt;(buffer, 5, 3);

    Console.WriteLine("Origin:");
    PrintOut(buffer, segment1, segment2);
    Console.WriteLine();

    Console.WriteLine("Update Buffer[5]:");
    buffer[5] = 0x01;
    PrintOut(buffer, segment1, segment2);
    Console.WriteLine();

    Console.WriteLine("Update Segment1.Array[5]:");
    segment1.Array[5] = 0x02;
    PrintOut(buffer, segment1, segment2);
    Console.WriteLine();

    Console.WriteLine("Update Segment2.Array[Segment2.Offset]:");
    segment2.Array[segment2.Offset] = 0x03;
    PrintOut(buffer, segment1, segment2);
    Console.WriteLine();
}
</code></pre>

<p>This sample code from above produces the following output:</p>

<p><img src="https://proemmer.azurewebsites.net/content/images/2016/10/Output.PNG" alt=""></p>

<p>As we can see, it's easy to use, but where is the benefit? Getting access to a specific index, I also have to use the Array and Offset Property like <code>segemnt.Array[segment.Offset] = 1</code>. No, not in real, due to the explicit interface implementation of <code>IList&lt;T&gt;</code> you can do some cool stuff like this:</p>

<pre><code class="language-c#">(segment2 as IList&lt;byte&gt;)[2] = 0x04;
var x = (segment2 as IList&lt;byte&gt;)[2];  
</code></pre>

<p>Adding this code lines to our sample, we produces the output below:</p>

<p><img src="https://proemmer.azurewebsites.net/content/images/2016/10/Output2.PNG" alt=""></p>

<p>This fills the gap, but I find the explicit implementation not very common in use. The reason why this is done this way is because <code>ArraySegment&lt;T&gt;</code> implements <code>IList&lt;T&gt;</code> and <code>IReadOnlyList&lt;T&gt;</code> and for this they need a separation. I would prefer a second type, for example <code>ReadOnlyArraySegment&lt;T&gt;</code> to get a better usage.</p>

<h2 id="performance">Performance</h2>

<p>Ok, we saw the usage, now let's check the performance. In the sample you will also find a method to test that in case of memory and speed to see whether it pays off. </p>

<pre><code class="language-c#">Test("List        ", (arr, offset, elements) =&gt;  
                     new List&lt;int&gt;(arr.Skip(offset).Take(elements)));

Test("Array       ", (arr, offset, elements) =&gt;  
                     new List&lt;int&gt;(arr.Skip(offset).Take(elements)));

Test("ArraySegment", (arr, offset, elements) =&gt;  
                     new ArraySegment&lt;int&gt;(arr, offset, elements));

Test("ArrayCopy   ", (arr, offset, elements) =&gt;  
{
    var array = new int[elements];
    Array.Copy(arr, offset, array, 0, elements);
    return array;
});
</code></pre>

<p>I think the result speaks for itself:</p>

<p><em>Average Runtime in ms</em>
<img src="https://proemmer.azurewebsites.net/content/images/2016/10/AverageRuntime-1.PNG" alt="Average Runtime"></p>

<p><em>Average Total Memory in byte</em>
<img src="https://proemmer.azurewebsites.net/content/images/2016/10/AverageTotalMemory-1.PNG" alt="Average Total Memory"></p>

<h2 id="implementation">Implementation</h2>

<p>Referred to this evaluation I think it's clear why this is useful. Now, after this I took a look on the source code of this structure to see how this works. I extracted some parts to show you the basic use. As you can see in the following code, it is what it is, a wrapper around an array of T[] which supports the <code>IList&lt;T&gt;</code> and <code>IReadOnlyList&lt;T&gt;</code> interface explicit:</p>

<pre><code class="language-c#"> [Serializable]
 public struct ArraySegment&lt;T&gt; : IList&lt;T&gt;, IReadOnlyList&lt;T&gt;
 {
     private T[] _array;
     private int _offset;
     private int _count;

     public ArraySegment(T[] array, int offset, int count)
     {
        _array = array;
        _offset = offset;
        _count = count;
     }

     public T[] Array{ get { return _array;} }
     public int Offset{ get { return _offset;} }
     public int Count{ get { return _count;} }

     ...
     T IList&lt;T&gt;.this[int index]
     {
         get { return _array[_offset + index]; }
         set { _array[_offset + index] = value; }
     }
     ...
 }
</code></pre>

<p><em>Attention</em>: Microsoft insert a code comment for the <code>Count</code> and <code>Offset</code> property as following:</p>

<pre><code>Since copying value types is not atomic and callers cannot atomically read all three fields, we cannot guarantee that Count/Offset is within the bounds of Array.  That's our intent, but let's not specify it as a post condition - force callers to re-verify this themselves after reading each field out of an `ArraySegment` into their stack.  
</code></pre>

<p>To check this by yourself you can you an implementation such the class from which was used by Microsoft (<a href="https://raw.githubusercontent.com/dotnet/corefx/master/src/Common/src/System/Net/RangeValidationHelpers.cs">RangeValidatorHelper</a>) for the sockets. </p>

<h1 id="span">Span</h1>

<p>Now let us take a look into the future. In the last few section we could see what <code>ArraySegments</code> can be used for. But now Microsoft (formals <a href="https://github.com/joeduffy/slice.net">joeduffy</a>) is working on a new structure named <code>Span</code>, which is part of a preview nuget package called <code>System.Slices</code> that is placed on the nuget channel "<a href="https://dotnet.myget.org/F/dotnet-corefxlab/api/v3/index.json">https://dotnet.myget.org/F/dotnet-corefxlab/api/v3/index.json</a>" and maybe will be part of C# 7.</p>

<h2 id="description">Description</h2>

<p>Span is a uniform API for dealing with arrays and subarrays, strings and substrings, and unmanaged memory buffers. It adds minimal overhead to regular accesses and is a struct so that creation and subslicing do not require additional allocations. It is type- and memory-safe.</p>

<h2 id="samples">Samples</h2>

<p>To show the usage of the new span-type, I also created some methods in the sample project:</p>

<pre><code class="language-c#">private unsafe static void FillSpans()  
{
    // Over an array:
    Span&lt;int&gt; ints = new Span&lt;int&gt;(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });

    // Over a string (of chars):
    Span&lt;char&gt; chars = new Span&lt;char&gt;("Hello, Slice!".ToArray());

    // Over an unmanaged memory buffer:
    byte* bb = stackalloc byte[256];
    Span&lt;byte&gt;bytes = new Span&lt;byte&gt;(bb, 256);


    PrintSpan1(ints);
    PrintSpan1(chars);
    PrintSpan1(bytes);

    PrintSpan2(ints);
    PrintSpan2(chars);
    PrintSpan2(bytes);
}

private static void PrintSpan1&lt;T&gt;(Span&lt;T&gt; slice)  
{
    for (int i = 0; i &lt; slice.Length; i++)
        Console.Write("{0} ", slice[i]);
    Console.WriteLine();
}

private static void PrintSpan2&lt;T&gt;(Span&lt;T&gt; slice)  
{
    foreach (T t in slice)
        Console.Write("{0} ", t);
    Console.WriteLine();
}
</code></pre>

<p>As you see, this structure is similar to the <code>ArraySegment</code> but spans do not implement the two interfaces. Instead it implements <a href="https://msdn.microsoft.com/en-us/library/ms131187%28v=vs.110%29.aspx?f=255&amp;MSPPError=-2147217396"><code>IEquatable&lt;T[]&gt;</code></a>. <br>
<code>Span</code> provides a few constructors, which also support the initialization with a pointer, what we will discuss later in the section <a href="https://proemmer.azurewebsites.net/2016/10/14/segments-and-slices/## Unsafe To Safe">Unsafe To Safe</a>. In contrast to <code>ArraySegment</code> here we also can use the index operator direct, without casting. Also sub-slicing without additional allocations can be used as you can see in the following snippet:</p>

<pre><code class="language-c#">private static void Subslicing()  
{
    //Extract sub span
    Span&lt;int&gt; ints = new Span&lt;int&gt;(
                       new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
    Span&lt;int&gt; subints = ints.Slice(5, 3);

    //No reallocation of the string
    ReadOnlySpan&lt;char&gt; testSpan = "Span Test".Slice();
    int space = testSpan.IndexOf(' ');
    ReadOnlySpan&lt;char&gt; firstName = testSpan.Slice(0, space);
    ReadOnlySpan&lt;char&gt; lastName = testSpan.Slice(space + 1);
}
</code></pre>

<h2 id="unsafetosafe">Unsafe To Safe</h2>

<p>Another benefit of this type is, as we described previously the unsafe constructor. So the array can be initialized in an unsafe Method and then you it can be used anywhere else in an safe way like the following listing shows.</p>

<pre><code class="language-c#">unsafe void Unsafe(byte* payload, int length)  
{
    Safe(new Span&lt;byte&gt;(payload, length));
}

void Safe(Span&lt;byte&gt; payload)  
{
  //now the payload could be handled in a safe way because it is wrapped
}
</code></pre>

<h1 id="languageintegration">Language integration</h1>

<p>By writing this blog-post I red many discussions about this new type and I created a short list of the top 6:</p>

<ul>
<li><a href="https://github.com/dotnet/corefxlab/issues/816">https://github.com/dotnet/corefxlab/issues/816</a></li>
<li><a href="https://github.com/dotnet/roslyn/issues/98">https://github.com/dotnet/roslyn/issues/98</a></li>
<li><a href="https://github.com/dotnet/roslyn/issues/120">https://github.com/dotnet/roslyn/issues/120</a></li>
<li><a href="https://github.com/dotnet/roslyn/issues/10378">https://github.com/dotnet/roslyn/issues/10378</a></li>
<li><a href="https://github.com/dotnet/corefx/issues/7593">https://github.com/dotnet/corefx/issues/7593</a></li>
<li><a href="https://github.com/dotnet/corefx/issues/6740">https://github.com/dotnet/corefx/issues/6740</a></li>
</ul>

<p>Some really cool things will be coming if this type will be part of the language. One of the proposed usage I copied out of the discussion to show you the future (maybe): </p>

<pre><code class="language-c#">int[] primes = new int[] { 2, 3, 5, 7, 9, 11, 13 };  
int item = primes[1];   // Regular array access, producing the value 3  
int[:] a = primes[0:3]; // A slice with elements {2, 3, 5}  
int[:] b = primes[1:2]; // A slice with elements {3}  
int[:] c = primes[:5];  // A slice with elements {2, 3, 5, 7, 9}  
int[:] d = primes[2:];  // A slice with elements {5, 7, 9, 11, 13}  
int[:] e = primes[:];   // A slice with elements {2, 3, 5, 7, 9, 11, 13}  
int[:] f = a[1:2];      // A slice with elements {3}  
</code></pre>

<p>I think it will be very interesting to see the final version of Slices and I'm anxiously waiting on it.</p>

<p><code>Updated on 07.11.2016:</code> 
<a href="https://github.com/davidfowl/apireviews/tree/master/2016/11-04-SpanOfT">SpanOfT Review</a></p>

<h1 id="summary">Summary</h1>

<p>In the reference section and in the language integration section you can find some additional links I used to learn and understand the functionality. I hope you find this article helpful. If this is the case or if you have some questions or find some bugs, please post in the comment section below. I will thankfully use your input to improve this blog-post.</p>

<h1 id="references">References</h1>

<ul>
<li><a href="https://github.com/dotnet/coreclr/blob/32f0f9721afb584b4a14d69135bea7ddc129f755/src/mscorlib/src/System/ArraySegment.cs">System.ArraySegment</a></li>
<li><a href="https://github.com/dotnet/corefxlab/tree/master/src/System.Slices">System.Slices</a></li>
</ul>]]></content:encoded></item><item><title><![CDATA[Create and load code at runtime in .NET Core]]></title><description><![CDATA[<p>I think loading and compiling code at runtime is a very cool and helpful feature. That's why one of my first .NET Core projects (<a href="https://github.com/proemmer/webpac">webpac</a>) uses this technique to load user defined types at runtime. The dynamically created types are used to get structured access to data in a <a href="https://en.wikipedia.org/wiki/Programmable_logic_controller">PLC</a></p>]]></description><link>https://proemmer.azurewebsites.net/2016/10/06/create-and-load-code-at-runtime-in-dotnet-core/</link><guid isPermaLink="false">1e09eddb-aa0c-49ef-a952-726eeb89f546</guid><dc:creator><![CDATA[Benjamin Prömmer]]></dc:creator><pubDate>Thu, 06 Oct 2016 18:21:43 GMT</pubDate><content:encoded><![CDATA[<p>I think loading and compiling code at runtime is a very cool and helpful feature. That's why one of my first .NET Core projects (<a href="https://github.com/proemmer/webpac">webpac</a>) uses this technique to load user defined types at runtime. The dynamically created types are used to get structured access to data in a <a href="https://en.wikipedia.org/wiki/Programmable_logic_controller">PLC</a>. <br>
After some troubles with breaking changes in the RC versions, I started a second project called <a href="https://github.com/proemmer/scribi">scribi</a>. Scribi also uses dynamically created code that gets compiled to ASP.NET ApiControllers and SignalR hubs.</p>

<p>To run these tools, I used some classes that were not very good documented at the time of coding. One of these classes is used to find the references of my assembly, some others to compile the code from a file and to load the compiled assembly. Compared to old .NET code I developed, the reference finding and assembly loading is quite different now. The reason is that there is no <code>AppDomain.GetAssemblies()</code> and <code>Assembly.LoadFile()</code> in CoreClr. It took me some time to find a solution for this .NET Core.</p>

<p>For this blog-post I provided a project called <a href="https://github.com/proemmer/DynCode.Sample">DynCode.Sample</a> on GitHub, where you can try the functionality on a simple project.</p>

<h1 id="findreferencedassemblies">Find referenced assemblies</h1>

<p>First of all you need a reference of the dependency context which holds the references of an assembly.</p>

<pre><code class="language-c#">using System.Reflection; 

var myEntryAssembly = Assembly.GetEntryAssembly();  
var context = DependencyContext.Load(myEntryAssembly );  
</code></pre>

<p>If your context should be the context of your entry assembly (to get all references of your application) you could also use <code>DependencyContext.Default</code>.</p>

<p>You can use the following code snipet to show all assemblies your entry assembly is compiled against. To get detailed Information about the compiled libraries, you have to make the according settings (<code>compilationOptions.preserveCompilationContext : true</code>) in package.json:</p>

<pre><code class="language-json">    "compilationOptions": {
        "preserveCompilationContext": true,
        "emitEntryPoint": true
    },
    "dependencies": {
      ...
      "Microsoft.Extensions.DependencyModel": "1.0.1-beta-003206",
      ...
    },
</code></pre>

<pre><code class="language-c#">public static void ShowReferences()  
{
    var context = DependencyContext.Default;

    if (!context.CompileLibraries.Any())
        Console.WriteLine("Compilation libraries empty");

    foreach (var compilationLibrary in context.CompileLibraries)
    {
        foreach (var resolvedPath in compilationLibrary
                                      .ResolveReferencePaths())
        {
            Console.WriteLine($"Compilation {compilationLibrary.Name}:{Path.GetFileName(resolvedPath)}");
            if (!File.Exists(resolvedPath))
                Console.WriteLine($"Compilation library resolved to non existent path {resolvedPath}");
        }
    }

    foreach (var runtimeLibrary in context.RuntimeLibraries)
    {
        foreach (var assembly in runtimeLibrary.GetDefaultAssemblyNames(context))
            Console.WriteLine($"Runtime {runtimeLibrary.Name}:{assembly.Name}");
    }
}
</code></pre>

<h1 id="loadassemblies">Load assemblies</h1>

<p>In my application I would also implement the ability to load some additional assembly references (this could also be used if you support a plugin system). To do this you need another nuget package:</p>

<pre><code class="language-json">    "dependencies": {
        ...
        "System.Runtime.Loader": "4.0.0",
        ...
    }
</code></pre>

<p>This package contains a class called <a href="https://github.com/dotnet/coreclr/blob/master/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs"><code>AssemblyLoadContext</code></a> which is placed in the <code>System.Runtime.Loader.dll</code>.</p>

<p>To get the current load context, you can use the static property <code>AssemblyLoadContext.Defaul</code> or pass an assembly into the method <code>AssemblyLoadContext.GetLoadContext(asm);</code> for a different one. The <br>
resulting context gives you the opportunity to load assemblies (from file, by name, ...). </p>

<pre><code class="language-c#">AssemblyLoadContext.Default.Resolving += CustomResolving;  
var asm = AssemblyLoadContext.Default.LoadFromAssemblyPath(path);  
</code></pre>

<p>The context also provides a <code>Resolving</code>-event which could be used to bring in your resolving code, if an assembly could not be resolved byte the LoadContext itself.</p>

<pre><code class="language-c#">private static Assembly CustomResolving(AssemblyLoadContext arg1, AssemblyName arg2)  
{
    Console.WriteLine($"Try resolve: {arg2.FullName}");
    //Maybe Load from different path e.g. Addon Path.
    return arg1.LoadFromAssemblyPath(@"C:\Addons\" + arg2.Name + ".dll");
}
</code></pre>

<h1 id="compilefilesfromlocation">Compile files from location</h1>

<pre><code class="language-json">    "dependencies": {
        ...
        "Microsoft.CodeAnalysis.CSharp": "2.0.0-beta3",
        ...
    }
</code></pre>

<p>Now as we can determine the references and load assemblies, we can start to implement the compile method. This can be done very easily by using <br>
the .Net Compiler Platform (formally known as Roslyn). The following listing shows how this works. Each element of the list could be represent a file of C# source code.</p>

<pre><code class="language-c#">private static Assembly Compile(string assemblyName, IEnumerable&lt;string&gt; codes, IEnumerable&lt;string&gt; usings = null)  
{
    if (codes == null || !codes.Any())
        throw new ArgumentNullException(nameof(codes));

    //we need to get a tree per source
    var trees = new List&lt;SyntaxTree&gt;();
    var additionalUsings = usings != null 
                               ? usings.Select(s =&gt; 
                                                SyntaxFactory
                                                .UsingDirective(SyntaxFactory
                                                      .ParseName(s))).ToArray() 
                               : new UsingDirectiveSyntax[0];

    foreach (var code in codes)
    {
        // Parse the script to a SyntaxTree
        var syntaxTree = CSharpSyntaxTree.ParseText(code);
        var root = (CompilationUnitSyntax)syntaxTree.GetRoot();

        if (additionalUsings.Any())
            root = root.AddUsings(additionalUsings);

        trees.Add(SyntaxFactory.SyntaxTree(root));
    }

    // Compile the SyntaxTree to an in memory assembly
    var compilation = CSharpCompilation.Create(
        assemblyName,
        trees,
        GetMetaDataReferences(),
        new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
        );

    using (var outputStream = new MemoryStream())
    {
        using (var pdbStream = new MemoryStream())
        {
            var result = compilation.Emit(outputStream);
            if (result.Success)
            {
                outputStream.Position = 0;
                return AssemblyLoadContext.Default.LoadFromStream(outputStream);
            }
            else
            {
                Console.WriteLine(result.Diagnostics.Select(x =&gt; $"{x.ToString()}{Environment.NewLine}"));
                return null;
            }
        }
    }
}

private static IEnumerable&lt;MetadataReference&gt; GetMetaDataReferences()  
{
    return DependencyContext.Default
        .CompileLibraries
        .SelectMany(x =&gt; x.ResolveReferencePaths())
        .Where(path =&gt; !string.IsNullOrWhiteSpace(path))
        .Select(path =&gt; MetadataReference.CreateFromFile(path));
}
</code></pre>

<h1 id="summary">Summary</h1>

<p>In the reference section you can find some additional links I used to learn and understand the functionality. I hope you find this article helpful. If this is the case or if you have some questions or find some bugs, please post in the comment section below. I will thankfully use your input to improve this blog-post.</p>

<h1 id="references">References</h1>

<ul>
<li><a href="https://github.com/dotnet/coreclr/blob/d154b9394578aa4b7e39f8695dc1f773d1a6882b/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs">AssemblyLoadContext</a></li>
<li><a href="https://github.com/dotnet/corefx/tree/master/src/System.Runtime.Loader/tests">System.Loader.Tests</a></li>
<li><a href="http://shazwazza.com/post/custom-assembly-loading-with-aspnet-core/">CustomAssemblyLoader</a></li>
<li><a href="http://stackoverflow.com/questions/37895278/how-to-load-assemblies-located-in-a-folder-in-net-core-console-app">StackOverflow</a></li>
<li><a href="https://github.com/dotnet/coreclr/blob/0c88c2e67260ddcb1d400eb6adda19de627998f5/Documentation/mscorlib.md#calling-from-managed-to-native-code">Calling from managed to native code</a></li>
<li><a href="https://github.com/dotnet/coreclr/blob/d154b9394578aa4b7e39f8695dc1f773d1a6882b/src/vm/assemblynative.cpp">assemblynative</a></li>
<li><a href="https://github.com/dotnet/coreclr/issues/1187">issue</a></li>
<li><a href="https://github.com/dotnet/cli/blob/3a567e595773b61650f2dcd1c7ec2b53b91cd7a8/TestAssets/TestProjects/DependencyContextValidator/DependencyContextValidator/Validator.cs">DependencyContextValidator</a></li>
<li><a href="https://github.com/aspnet/Announcements/issues/149">Announcements</a></li>
</ul>]]></content:encoded></item></channel></rss>