<?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:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Lucas Araujo | Azure Coder on Medium]]></title>
        <description><![CDATA[Stories by Lucas Araujo | Azure Coder on Medium]]></description>
        <link>https://medium.com/@lucaslra?source=rss-52058c51d1df------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*2oT-1mf0KHAWM3t7aGSinQ.jpeg</url>
            <title>Stories by Lucas Araujo | Azure Coder on Medium</title>
            <link>https://medium.com/@lucaslra?source=rss-52058c51d1df------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 17:27:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lucaslra/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The History of .NET by Richard Campbell]]></title>
            <link>https://lucaslra.medium.com/the-history-of-net-by-richard-campbell-6a641842de09?source=rss-52058c51d1df------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a641842de09</guid>
            <category><![CDATA[history]]></category>
            <dc:creator><![CDATA[Lucas Araujo | Azure Coder]]></dc:creator>
            <pubDate>Tue, 03 Apr 2018 21:43:13 GMT</pubDate>
            <atom:updated>2018-04-03T21:43:18.366Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone,<br> I am preparing a nice post on Azure Functions for very soon but, today I would like to share some history with you.</p><p>I found today a really <strong>amazing</strong> video on YouTube about the History of .NET. The video is actually a recording of a talk at the NDC { London } 2018, just 2 months ago, by Richard Campbell (from .NET Rocks)</p><p>On the talk Richard, who is a great storyteller, explains the story of how Microsoft was cornered and had to reinvent itself many times along the last 20–25 years, and how it led to the creation of the .NET Framework and all the technologies that entangles it. He cannot avoid mentioning all the great people involved into this process, from the original designer of J++, Microsoft’s implementation of Java, to the current maintainers of the .NET Framework and C# Language, and even the current CEO.</p><p>It also, and it could not be different, explains a lot of the history of the Windows OS, Microsoft’s Web Browsers and the rise of Microsoft Azure!</p><p>If you code in any Microsoft Language and like .NET and a bit of History, I assure you it is worth every second of the (~) 1 hour and 10 minutes.</p><p>Here is the video:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FtrHTLFNFoWk%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DtrHTLFNFoWk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FtrHTLFNFoWk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/feceae7ded2acdcc0bb5a7271a505d9b/href">https://medium.com/media/feceae7ded2acdcc0bb5a7271a505d9b/href</a></iframe><p>So, what do you think? Great, wasn’t it?</p><h4>Links:</h4><ul><li><a href="https://www.dotnetrocks.com/">.NET Rocks</a></li><li><a href="https://ndcconferences.com/">NDC Conferences</a></li><li><a href="https://twitter.com/richcampbell">Richard Campbell’s Twitter</a></li></ul><p><em>Originally published at </em><a href="http://azurecoder.net/2018/04/03/the-history-of-dotnet/"><em>The Azure Coder</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a641842de09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating an OData v4 API with ASP.NET Core 2.0]]></title>
            <link>https://lucaslra.medium.com/creating-an-odata-v4-api-with-asp-net-core-2-0-f00287928987?source=rss-52058c51d1df------2</link>
            <guid isPermaLink="false">https://medium.com/p/f00287928987</guid>
            <category><![CDATA[odata]]></category>
            <dc:creator><![CDATA[Lucas Araujo | Azure Coder]]></dc:creator>
            <pubDate>Mon, 19 Feb 2018 11:30:55 GMT</pubDate>
            <atom:updated>2019-06-23T14:54:50.458Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jJ24kfRwFkpN6WmX.png" /></figure><p>Hallo Mensen :D Let’s talk OData, shall we?</p><p>In the last few years my work revolved a lot around REST APIs. I think most of us will agree that REST APIs are a really good way of obtaining data from a server without caring too much about details on how to get access to that data.</p><p>You call an URL with the proper parameters (including auth or not), headers, and HTTP verb and you get some data back. Easy enough, right?</p><p>The negative side is that these APIs are either very rigid on the way they are implemented, meaning that you can only get the data in the exact way defined by the server, or they are very verbose on their implementation, meaning that you will have <strong>a lot</strong> of code to maintain on the server side to make the API flexible.</p><p>Then what?… Use OData!</p><h4>What is the Open Data Protocol (OData)?</h4><figure><img alt="OData Logo" src="https://cdn-images-1.medium.com/max/300/0*bGXTDROudQD_B9pt.png" /><figcaption>OData Logo</figcaption></figure><p>OData, or <strong>O</strong>pen <strong>Data</strong> Protocol, is a set of ISO approved standards for building <em>and consuming</em> RESTul APIs, but what does it mean, in practice?</p><p>It means that OData is not really an implementation that you simply <em>use</em> but documentation specifying how you must implement it yourself. You can read a lot more about OData <a href="http://www.odata.org/documentation/">here</a>.</p><h4>Why would I want to use OData?</h4><p>There are a number of benefits that you will obtain from implementing OData standards, from an easier learning path on the usage of your API by your customers/consumers, to the fact that OData is easily readable by machines, and in this post I want to talk about the flexibility that implementing OData gives to your API through the OData URL Conventions.</p><p>Using URL Conventions you can expose a much cleaner and generic API and let the consumer specify their needs through the call.</p><h4><a href="http://docs.oasis-open.org/odata/odata/v4.0/odata-v4.0-part2-url-conventions.html">OData URL Conventions</a></h4><p>The OData URL Conventions are a set of <em>commands</em> that you can pass to the API through the HTTP call query string.</p><p>An OData URL is typically composed by three parts: service root URL, resource path and query options.</p><figure><img alt="OData Url Format" src="https://cdn-images-1.medium.com/max/702/0*EAhAVZSc_8tzu4FI.png" /></figure><ul><li>Service Root URL is the root address for the API.</li><li>Resource Path identifies exactly which resource you are trying to achieve.</li><li>Query Options is how you define to the API the format in which you need that data to be delivered.</li></ul><p>How does that sound? Simple enough, right? but also, with the proper options, extremely powerful. Let me give you a list of possible options within the Query Options block of the call:</p><ul><li><strong>$select:</strong> Allows you to define a subset of properties to return from that Resource.</li><li><strong>$expand:</strong> Allows you to include data from a related resource to your query results.</li><li><strong>$orderby:</strong> Not surprisingly, allows you to define the ordering of the returned dataset.</li><li><strong>$top:</strong> Allows you to select the top X results of the query.</li><li><strong>$skip:</strong> Allows you to skip X results of the query.</li><li><strong>$count: </strong>Allows you to get a count of items that would result from that query.</li><li><strong>$search: </strong>Allows for a free-text search on that particular resource</li><li><strong>$format:</strong> Allows you to define the format for the returned data in some query types</li><li><strong>$filter:</strong> Allows you to define a filter for your dataset.</li></ul><p>As you can see, many of the commands are pretty similar to what you have in most of the common query languages.</p><p>I will go into a bit more detail in each of those options on the Code sample.</p><h4>OData and ASP.NET</h4><p><strong>ASP.NET Core</strong> still don’t have a stable library to implement the OData protocol! But worry you not, as Microsoft has been working on it for some time and right now we have a really promising beta version on Nuget. You can find it <a href="https://www.nuget.org/packages/Microsoft.AspNetCore.OData/">here</a>.</p><p><strong>ASP.NET Framework</strong> has a really good library to implement OData, and it is quite stable by now. You can find it <a href="https://www.nuget.org/packages/Microsoft.AspNet.OData/">here</a>.</p><p>Enough with the theory, how can we implement this query protocol in my ASP.NET Core Application?</p><figure><img alt="letscode" src="https://cdn-images-1.medium.com/max/500/0*eimSWq3B9WGByA67.jpg" /></figure><h4>Implementing your API</h4><p>Let’s start creating a simple ASP.NET Core Web API Application on Visual Studio and creating our models.</p><pre>public class Author<br>{<br>    public Author()<br>    {<br>        Books = new Collection&lt;Book&gt;();<br>    }</pre><pre>    [Key]<br>    public int Id { get; set; }</pre><pre>    [Required]<br>    public string Name { get; set; }</pre><pre>    public virtual ICollection&lt;Book&gt; Books { get; set; }<br>}</pre><pre>public class Publisher<br>{<br>    public Publisher()<br>    {<br>        Books = new Collection&lt;Book&gt;();<br>    }</pre><pre>    [Key]<br>    public int Id { get; set; }</pre><pre>    [Required]<br>    public string Name { get; set; }</pre><pre>    public virtual ICollection&lt;Book&gt; Books { get; set; }<br>}</pre><pre>public class Book<br>{<br>    [Key]<br>    public int Id { get; set; }</pre><pre>    [Required]<br>    public string Name { get; set; }</pre><pre>    public int AuthorId { get; set; }<br>    public Author Author { get; set; }</pre><pre>    public int PublisherId { get; set; }<br>    public Publisher Publisher { get; set; }<br>}</pre><p>Also, let’s create our DbContext…</p><pre>public class BooksContext : DbContext<br>{<br>    public DbSet&lt;Book&gt; Books { get; set; }<br>    public DbSet&lt;Author&gt; Authors { get; set; }<br>    public DbSet&lt;Publisher&gt; Publishers { get; set; }</pre><pre>    public BooksContext() : base()<br>    {<br>    }</pre><pre>    public BooksContext(DbContextOptions options) : base(options)<br>    {<br>    }</pre><pre>    protected override void OnModelCreating(ModelBuilder modelBuilder)<br>    {<br>        modelBuilder.Entity&lt;Publisher&gt;()<br>            .HasMany(p =&gt; p.Books)<br>            .WithOne(b =&gt; b.Publisher)<br>            .HasForeignKey(b =&gt; b.PublisherId);</pre><pre>        modelBuilder.Entity&lt;Author&gt;()<br>            .HasMany(a =&gt; a.Books)<br>            .WithOne(b =&gt; b.Author)<br>            .HasForeignKey(b =&gt; b.AuthorId);<br>    }<br>}</pre><p>…and configure our Services.</p><pre>public void ConfigureServices(IServiceCollection services)<br>{<br>    services.AddDbContext&lt;BooksContext&gt;(options =&gt;<br>    {<br>        options.UseSqlite(&quot;Data Source=Books.db&quot;);<br>    });</pre><pre>    services.AddMvc().AddJsonOptions(opt =&gt;<br>    {<br>        opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();<br>        opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;<br>    });<br>}</pre><p>Good! Our plumbing is set, now we are going to seed some initial data to our database.</p><pre>internal static class BooksInitializer<br>{<br>    private static bool _initialized = false;<br>    private static object _lock = new object();<br>    private static List&lt;Author&gt; authors;<br>    private static List&lt;Book&gt; books;<br>    private static List&lt;Publisher&gt; publishers;</pre><pre>    public static void Seed(BooksContext context)<br>    {<br>        AddPublishers(context);<br>        AddAuthors(context);<br>        AddBooks(context);<br>    }</pre><pre>    internal static void Initialize(BooksContext context)<br>    {<br>        if (!_initialized)<br>        {<br>            lock (_lock)<br>            {<br>                if (_initialized)<br>                    return;</pre><pre>                InitializeData(context);<br>            }<br>        }<br>    }</pre><pre>    private static void AddAuthors(BooksContext context)<br>    {<br>        authors = new List&lt;Author&gt;<br>        {<br>            // Data<br>        };<br>        if (!context.Authors.Any())<br>        {<br>            context.Authors.AddRange(authors);<br>            context.SaveChanges();<br>        }<br>    }</pre><pre>    private static void AddBooks(BooksContext context)<br>    {<br>        books = new List&lt;Book&gt;<br>        {<br>            // Data<br>        };</pre><pre>        if (!context.Books.Any())<br>        {<br>            context.Books.AddRange(books);<br>            context.SaveChanges();<br>        }<br>    }</pre><pre>    private static void AddPublishers(BooksContext context)<br>    {<br>        publishers = new List&lt;Publisher&gt;<br>        {<br>            // Data<br>        };<br>        if (!context.Publishers.Any())<br>        {<br>            context.Publishers.AddRange(publishers);<br>            context.SaveChanges();<br>        }<br>    }</pre><pre>    private static void InitializeData(BooksContext context)<br>    {<br>        context.Database.Migrate();<br>        Seed(context);<br>    }<br>}</pre><p>And now we call our seeder on app startup.</p><pre>public static void Main(string[] args)<br>{<br>    var host = BuildWebHost(args);</pre><pre>    using (var scope = host.Services.CreateScope())<br>    {<br>        var services = scope.ServiceProvider;<br>        var context = services.GetRequiredService&lt;BooksContext&gt;();</pre><pre>        BooksInitializer.Initialize(context);<br>    }</pre><pre>    host.Run();<br>}</pre><p>We must not forget to add our migration.</p><pre>PS C:\BooksAPI\BooksAPI.REST&gt;dotnet ef migrations add Initial<br>Done. To undo this action, use &#39;ef migrations remove&#39;</pre><p>And last, but not least, let’s implement the simplest API possible on our 3 entities.</p><pre>[Produces(&quot;application/json&quot;)]<br>[Route(&quot;api/Authors&quot;)]<br>public class AuthorsController : Controller<br>{<br>    private readonly BooksContext context;</pre><pre>    public AuthorsController(BooksContext context) =&gt; this.context = context;</pre><pre>    // GET: api/Authors<br>    [HttpGet]<br>    public IEnumerable&lt;Author&gt; Get() =&gt; context.Authors.Include(r =&gt; r.Books).ThenInclude(b =&gt; b.Publisher);<br>}</pre><pre>[Produces(&quot;application/json&quot;)]<br>[Route(&quot;api/books&quot;)]<br>public class BooksController : Controller<br>{<br>    private readonly BooksContext context;</pre><pre>    public BooksController(BooksContext context) =&gt; this.context = context;</pre><pre>    // GET: api/books<br>    [HttpGet]<br>    public IEnumerable&lt;Book&gt; Get() =&gt; context.Books.Include(b =&gt; b.Author).Include(b =&gt; b.Publisher);<br>}</pre><pre>[Produces(&quot;application/json&quot;)]<br>[Route(&quot;api/Publishers&quot;)]<br>public class PublishersController : Controller<br>{<br>    private readonly BooksContext context;</pre><pre>    public PublishersController(BooksContext context) =&gt; this.context = context;</pre><pre>    // GET: api/Publishers<br>    [HttpGet]<br>    public IEnumerable&lt;Publisher&gt; Get() =&gt; context.Publishers.Include(r =&gt; r.Books).ThenInclude(b =&gt; b.Author);<br>}</pre><p>Done. Now we can test it using <a href="https://www.getpostman.com/">Postman:</a></p><p>Wow! It certainly looks like a nice API, doesn’t it? What is the problem with it? Why would I ever want to add OData to it?</p><p>Well, there are two fundamental problems with this approach to our API: the payload size and the querying of the data from the database.</p><h4>Payload Size</h4><p>The payload format is completely defined on the API/Server side of the application and the client cannot define which data he really needs to receive.</p><p>This can be made more flexible by adding complexity to the code (more parameters? more calls?) but this is not what we want right?</p><p>In the most common scenarios the client will simply have to ignore a lot of data that he doesn’t care about.</p><p>Look at the result of our query for Books below and tell me what should we do if I only want the <strong>name</strong> for the first book on the list?</p><p>We have no options here other than accept all this data and filter what we need on client side.</p><pre>[<br>  {<br>    &quot;id&quot;: 1,<br>    &quot;name&quot;: &quot;Into Thin Air&quot;,<br>    &quot;authorId&quot;: 4,<br>    &quot;author&quot;: {<br>      &quot;id&quot;: 4,<br>      &quot;name&quot;: &quot;Jon Krakauer&quot;,<br>      &quot;books&quot;: []<br>    },<br>    &quot;publisherId&quot;: 2,<br>    &quot;publisher&quot;: {<br>      &quot;id&quot;: 2,<br>      &quot;name&quot;: &quot;Anchor&quot;,<br>      &quot;books&quot;: []<br>    }<br>  },<br>  // ... a LOT more Data<br>  {<br>    &quot;id&quot;: 13,<br>    &quot;name&quot;: &quot;Harry Potter And The Goblet Of Fire&quot;,<br>    &quot;authorId&quot;: 3,<br>    &quot;author&quot;: {<br>      &quot;id&quot;: 3,<br>      &quot;name&quot;: &quot;J.K. Rowling&quot;,<br>      &quot;books&quot;: [<br>        {<br>          &quot;id&quot;: 10,<br>          &quot;name&quot;: &quot;Harry Potter and the Sorcerer&#39;s Stone&quot;,<br>          &quot;authorId&quot;: 3,<br>          &quot;publisherId&quot;: 3,<br>          &quot;publisher&quot;: {<br>            &quot;id&quot;: 3,<br>            &quot;name&quot;: &quot;Scholastic&quot;,<br>            &quot;books&quot;: [<br>              {<br>                &quot;id&quot;: 11,<br>                &quot;name&quot;: &quot;Harry Potter And The Chamber Of Secrets&quot;,<br>                &quot;authorId&quot;: 3,<br>                &quot;publisherId&quot;: 3<br>              },<br>              {<br>                &quot;id&quot;: 12,<br>                &quot;name&quot;: &quot;Harry Potter and the Prisoner of Azkaban&quot;,<br>                &quot;authorId&quot;: 3,<br>                &quot;publisherId&quot;: 3<br>              }<br>            ]<br>          }<br>        },<br>        {<br>          &quot;id&quot;: 11,<br>          &quot;name&quot;: &quot;Harry Potter And The Chamber Of Secrets&quot;,<br>          &quot;authorId&quot;: 3,<br>          &quot;publisherId&quot;: 3,<br>          &quot;publisher&quot;: {<br>            &quot;id&quot;: 3,<br>            &quot;name&quot;: &quot;Scholastic&quot;,<br>            &quot;books&quot;: [<br>              {<br>                &quot;id&quot;: 10,<br>                &quot;name&quot;: &quot;Harry Potter and the Sorcerer&#39;s Stone&quot;,<br>                &quot;authorId&quot;: 3,<br>                &quot;publisherId&quot;: 3<br>              },<br>              {<br>                &quot;id&quot;: 12,<br>                &quot;name&quot;: &quot;Harry Potter and the Prisoner of Azkaban&quot;,<br>                &quot;authorId&quot;: 3,<br>                &quot;publisherId&quot;: 3<br>              }<br>            ]<br>          }<br>        },<br>        {<br>          &quot;id&quot;: 12,<br>          &quot;name&quot;: &quot;Harry Potter and the Prisoner of Azkaban&quot;,<br>          &quot;authorId&quot;: 3,<br>          &quot;publisherId&quot;: 3,<br>          &quot;publisher&quot;: {<br>            &quot;id&quot;: 3,<br>            &quot;name&quot;: &quot;Scholastic&quot;,<br>            &quot;books&quot;: [<br>              {<br>                &quot;id&quot;: 10,<br>                &quot;name&quot;: &quot;Harry Potter and the Sorcerer&#39;s Stone&quot;,<br>                &quot;authorId&quot;: 3,<br>                &quot;publisherId&quot;: 3<br>              },<br>              {<br>                &quot;id&quot;: 11,<br>                &quot;name&quot;: &quot;Harry Potter And The Chamber Of Secrets&quot;,<br>                &quot;authorId&quot;: 3,<br>                &quot;publisherId&quot;: 3<br>              }<br>            ]<br>          }<br>        }<br>      ]<br>    },<br>    &quot;publisherId&quot;: 3,<br>    &quot;publisher&quot;: {<br>      &quot;id&quot;: 3,<br>      &quot;name&quot;: &quot;Scholastic&quot;,<br>      &quot;books&quot;: [<br>        {<br>          &quot;id&quot;: 10,<br>          &quot;name&quot;: &quot;Harry Potter and the Sorcerer&#39;s Stone&quot;,<br>          &quot;authorId&quot;: 3,<br>          &quot;author&quot;: {<br>            &quot;id&quot;: 3,<br>            &quot;name&quot;: &quot;J.K. Rowling&quot;,<br>            &quot;books&quot;: [<br>              {<br>                &quot;id&quot;: 11,<br>                &quot;name&quot;: &quot;Harry Potter And The Chamber Of Secrets&quot;,<br>                &quot;authorId&quot;: 3,<br>                &quot;publisherId&quot;: 3<br>              },<br>              {<br>                &quot;id&quot;: 12,<br>                &quot;name&quot;: &quot;Harry Potter and the Prisoner of Azkaban&quot;,<br>                &quot;authorId&quot;: 3,<br>                &quot;publisherId&quot;: 3<br>              }<br>            ]<br>          },<br>          &quot;publisherId&quot;: 3<br>        },<br>        {<br>          &quot;id&quot;: 11,<br>          &quot;name&quot;: &quot;Harry Potter And The Chamber Of Secrets&quot;,<br>          &quot;authorId&quot;: 3,<br>          &quot;author&quot;: {<br>            &quot;id&quot;: 3,<br>            &quot;name&quot;: &quot;J.K. Rowling&quot;,<br>            &quot;books&quot;: [<br>              {<br>                &quot;id&quot;: 10,<br>                &quot;name&quot;: &quot;Harry Potter and the Sorcerer&#39;s Stone&quot;,<br>                &quot;authorId&quot;: 3,<br>                &quot;publisherId&quot;: 3<br>              },<br>              {<br>                &quot;id&quot;: 12,<br>                &quot;name&quot;: &quot;Harry Potter and the Prisoner of Azkaban&quot;,<br>                &quot;authorId&quot;: 3,<br>                &quot;publisherId&quot;: 3<br>              }<br>            ]<br>          },<br>          &quot;publisherId&quot;: 3<br>        },<br>        {<br>          &quot;id&quot;: 12,<br>          &quot;name&quot;: &quot;Harry Potter and the Prisoner of Azkaban&quot;,<br>          &quot;authorId&quot;: 3,<br>          &quot;author&quot;: {<br>            &quot;id&quot;: 3,<br>            &quot;name&quot;: &quot;J.K. Rowling&quot;,<br>            &quot;books&quot;: [<br>              {<br>                &quot;id&quot;: 10,<br>                &quot;name&quot;: &quot;Harry Potter and the Sorcerer&#39;s Stone&quot;,<br>                &quot;authorId&quot;: 3,<br>                &quot;publisherId&quot;: 3<br>              },<br>              {<br>                &quot;id&quot;: 11,<br>                &quot;name&quot;: &quot;Harry Potter And The Chamber Of Secrets&quot;,<br>                &quot;authorId&quot;: 3,<br>                &quot;publisherId&quot;: 3<br>              }<br>            ]<br>          },<br>          &quot;publisherId&quot;: 3<br>        }<br>      ]<br>    }<br>  }<br>]</pre><h4>Querying the Data</h4><p>For much of the same reason, all the queries to the database have to be done in a very rigid way, not allowing for smaller queries whenever possible.</p><p>In the same query as above, we just sent a request for a list of books, and let’s have a look at what was sent to the database:</p><pre>SELECT &quot;b&quot;.&quot;Id&quot;, &quot;b&quot;.&quot;AuthorId&quot;, &quot;b&quot;.&quot;Name&quot;, &quot;b&quot;.&quot;PublisherId&quot;, &quot;b.Publisher&quot;.&quot;Id&quot;, &quot;b.Publisher&quot;.&quot;Name&quot;, &quot;b.Author&quot;.&quot;Id&quot;, &quot;b.Author&quot;.&quot;Name&quot;<br>FROM &quot;Books&quot; AS &quot;b&quot;<br>INNER JOIN &quot;Publishers&quot; AS &quot;b.Publisher&quot; ON &quot;b&quot;.&quot;PublisherId&quot; = &quot;b.Publisher&quot;.&quot;Id&quot;<br>INNER JOIN &quot;Authors&quot; AS &quot;b.Author&quot; ON &quot;b&quot;.&quot;AuthorId&quot; = &quot;b.Author&quot;.&quot;Id&quot;&quot;</pre><p>All this huge query just to get the name of one book. That doesn’t sound good, right?</p><p>Let’s make it better with OData :)</p><h4>Changing our API to OData</h4><p>The good news is that we can use much of the same structure for our OData API, we just need to make a few configurations. Let’s start by installing the package.</p><pre>PM&gt; Install-Package Microsoft.AspnetCore.Odata -Version 7.0.0-beta1<br>Successfully installed &#39;Microsoft.AspNetCore.OData 7.0.0-beta1&#39; to OData.Books</pre><p>As you can see the OData package for .NET Core is still in beta, as opposed to the .NET Framework version of the package, who is stable for a long time already. I have high hopes that this package will be out of beta in no time!</p><p>Let’s configure our entities to understand the OData commands.</p><pre>public class BooksModelBuilder<br>{<br>    public IEdmModel GetEdmModel(IServiceProvider serviceProvider)<br>    {<br>        var builder = new ODataConventionModelBuilder(serviceProvider);</pre><pre>        builder.EntitySet&lt;Book&gt;(nameof(Book))<br>                        .EntityType<br>                        .Filter() // Allow for the $filter Command<br>                        .Count() // Allow for the $count Command<br>                        .Expand() // Allow for the $expand Command<br>                        .OrderBy() // Allow for the $orderby Command<br>                        .Page() // Allow for the $top and $skip Commands<br>                        .Select();// Allow for the $select Command; </pre><pre>        builder.EntitySet&lt;Author&gt;(nameof(Author))<br>                        .EntityType<br>                        .Filter() // Allow for the $filter Command<br>                        .Count() // Allow for the $count Command<br>                        .Expand() // Allow for the $expand Command<br>                        .OrderBy() // Allow for the $orderby Command<br>                        .Page() // Allow for the $top and $skip Commands<br>                        .Select() // Allow for the $select Command<br>                        .ContainsMany(x =&gt; x.Books)<br>                        .Expand(); </pre><pre>        builder.EntitySet&lt;Publisher&gt;(nameof(Publisher))<br>                        .EntityType<br>                        .Filter() // Allow for the $filter Command<br>                        .Count() // Allow for the $count Command<br>                        .Expand() // Allow for the $expand Command<br>                        .OrderBy() // Allow for the $orderby Command<br>                        .Page() // Allow for the $top and $skip Commands<br>                        .Select() // Allow for the $select Command<br>                        .HasMany(x =&gt; x.Books)<br>                        .Expand(); </pre><pre>        return builder.GetEdmModel();<br>    }<br>}</pre><p>I commented the function of each call on this class, pay close attention to it, as the calls are paramount for the full use of the URL Conventions. And now let’s wire our OData configuration with the rest of the API.</p><pre>public void ConfigureServices(IServiceCollection services)<br>{<br>    // ... Other Configurations </pre><pre>    services.AddOData();<br>    services.AddTransient&lt;BooksModelBuilder&gt;();</pre><pre>    // ... MVC Service Configurations <br>}</pre><pre>public void Configure(IApplicationBuilder app, IHostingEnvironment env, BooksModelBuilder modelBuilder)<br>{<br>    // ... Other Configurations</pre><pre>    app.UseMvc(routeBuilder =&gt;<br>    {<br>        routeBuilder.MapODataServiceRoute(&quot;ODataRoutes&quot;, &quot;odata&quot;, modelBuilder.GetEdmModel(app.ApplicationServices));<br>    });<br>}</pre><p>All good! Finally, we must adjust our three controllers and have then accept OData URLs. Things you should notice were changed on the Controllers:</p><ul><li>All the controllers were renamed to be in the singular form. That is only necessary due to our configuration in the ModelBuilder, they can be configured to be plural.</li><li>The return types were all changed to IQueryable&lt;T&gt;</li><li>The .Include() calls were removed, as they are no longer necessary. The OData package will take care of this for you.</li><li>We are no longer inheriting from Controller but from ODataController</li><li>We have a new decorator for the API calls: [EnableQuery]</li></ul><pre>[Produces(&quot;application/json&quot;)]<br>public class AuthorController : ODataController<br>{<br>    private readonly BooksContext context;</pre><pre>    public AuthorController(BooksContext context) =&gt; this.context = context;</pre><pre>    // GET: odata/Author<br>    [EnableQuery]<br>    public IQueryable&lt;Author&gt; Get() =&gt; context.Authors.AsQueryable();<br>}</pre><pre>[Produces(&quot;application/json&quot;)]<br>public class BookController : ODataController<br>{<br>    private readonly BooksContext context;</pre><pre>    public BookController(BooksContext context) =&gt; this.context = context;</pre><pre>    // GET: odata/Book<br>    [EnableQuery]<br>    public IQueryable&lt;Book&gt; Get() =&gt; context.Books.AsQueryable();<br>}</pre><pre>[Produces(&quot;application/json&quot;)]<br>public class PublisherController : ODataController<br>{<br>    private readonly BooksContext context;</pre><pre>    public PublisherController(BooksContext context) =&gt; this.context = context;</pre><pre>    // GET: odata/Publisher<br>    [EnableQuery]<br>    public IQueryable&lt;Publisher&gt; Get() =&gt; context.Publishers.AsQueryable();<br>}</pre><p>And that is it! Our API is ready to be used with OData URL Conventions. Let’s try it?</p><h4>New API and Results</h4><p>You can play with the new API format on Postman:</p><p>The original call to get books would look like this:</p><blockquote><a href="http://localhost:5000/api/books">http://localhost:5000/api/books</a></blockquote><p>The new call will look like this</p><blockquote><a href="http://localhost:5000/odata/Book">http://localhost:5000/odata/Book</a></blockquote><p>First of all, let’s try to get a list of books and look at the results:</p><pre>{<br>  &quot;@odata.context&quot;: &quot;http://localhost:5000/odata/$metadata#Book&quot;,<br>    &quot;value&quot;: [<br>      {<br>        &quot;Id&quot;: 1,<br>        &quot;Name&quot;: &quot;Into Thin Air&quot;,<br>        &quot;AuthorId&quot;: 4,<br>        &quot;PublisherId&quot;: 2<br>      },<br>      // ... Other Books<br>      {<br>        &quot;Id&quot;: 13,<br>        &quot;Name&quot;: &quot;Harry Potter And The Goblet Of Fire&quot;,<br>        &quot;AuthorId&quot;: 3,<br>        &quot;PublisherId&quot;: 3<br>      }<br>    ]<br>}</pre><p>MUCH Cleaner, right? Let’s even make it smaller, as we just want the name of the first book on the list:</p><blockquote><a href="http://localhost:5000/odata/Book?$top=1">http://localhost:5000/odata/Book?$top=1</a></blockquote><pre>{<br>  &quot;@odata.context&quot;: &quot;http://localhost:5000/odata/$metadata#Book&quot;,<br>    &quot;value&quot;: [<br>      {<br>        &quot;Id&quot;: 1,<br>        &quot;Name&quot;: &quot;Into Thin Air&quot;,<br>        &quot;AuthorId&quot;: 4,<br>        &quot;PublisherId&quot;: 2<br>      }<br>    ]<br>}</pre><p>And let’s have a look at the database query for this call:</p><pre>SELECT &quot;$it&quot;.&quot;Id&quot;, &quot;$it&quot;.&quot;AuthorId&quot;, &quot;$it&quot;.&quot;Name&quot;, &quot;$it&quot;.&quot;PublisherId&quot;<br>FROM &quot;Books&quot; AS &quot;$it&quot;<br>ORDER BY &quot;$it&quot;.&quot;Id&quot;<br>LIMIT @__TypedProperty_0&quot;</pre><p>Yes! A much more efficient call! But wait… We just need the NAME of the book, why don’t we make it more specific?</p><blockquote><a href="http://localhost:5000/odata/Book?$top=1&amp;$select=Name">http://localhost:5000/odata/Book?$top=1&amp;$select=Name</a></blockquote><pre>{<br>  &quot;@odata.context&quot;: &quot;http://localhost:5000/odata/$metadata#Book(Name)&quot;,<br>    &quot;value&quot;: [<br>      {<br>        &quot;Name&quot;: &quot;Into Thin Air&quot;<br>      }<br>    ]<br>}</pre><p>And that is an awesomely small payload! And the query is also more efficient</p><pre>SELECT &quot;$it&quot;.&quot;Id&quot; AS &quot;Value0&quot;, &quot;$it&quot;.&quot;Name&quot; AS &quot;Value&quot;<br>FROM &quot;Books&quot; AS &quot;$it&quot;<br>ORDER BY &quot;Value0&quot;<br>LIMIT @__TypedProperty_0&quot;</pre><p>What if you want details about any specific Author and all his related books?</p><blockquote><a href="http://localhost:5000/odata/Author?$expand=Books&amp;$filter=Name">http://localhost:5000/odata/Author?$expand=Books&amp;$filter=Name</a> eq ‘J.K. Rowling’</blockquote><pre>{<br>  &quot;@odata.context&quot;: &quot;http://localhost:5000/odata/$metadata#Author&quot;,<br>    &quot;value&quot;: [<br>      {<br>        &quot;Id&quot;: 3,<br>        &quot;Name&quot;: &quot;J.K. Rowling&quot;,<br>        &quot;Books@odata.context&quot;: &quot;http://localhost:5000/odata/$metadata#Author(3)/Books&quot;,<br>        &quot;Books&quot;: [<br>          {<br>            &quot;Id&quot;: 10,<br>            &quot;Name&quot;: &quot;Harry Potter and the Sorcerer&#39;s Stone&quot;,<br>            &quot;AuthorId&quot;: 3,<br>            &quot;PublisherId&quot;: 3<br>          },<br>          {<br>            &quot;Id&quot;: 11,<br>            &quot;Name&quot;: &quot;Harry Potter And The Chamber Of Secrets&quot;,<br>            &quot;AuthorId&quot;: 3,<br>            &quot;PublisherId&quot;: 3<br>          },<br>          {<br>            &quot;Id&quot;: 12,<br>            &quot;Name&quot;: &quot;Harry Potter and the Prisoner of Azkaban&quot;,<br>            &quot;AuthorId&quot;: 3,<br>            &quot;PublisherId&quot;: 3<br>          },<br>          {<br>            &quot;Id&quot;: 13,<br>            &quot;Name&quot;: &quot;Harry Potter And The Goblet Of Fire&quot;,<br>            &quot;AuthorId&quot;: 3,<br>            &quot;PublisherId&quot;: 3<br>          }<br>        ]<br>      }<br>    ]<br>}</pre><p>Amazing, isn’t it? That can really increase the quality of our APIs.</p><p>As a last piece of information, let’s not forget that OData is designed to be readable by machines! So we have a couple of out-of-the-box urls with documentation on our API:</p><blockquote><a href="http://localhost:5000/odata/$metadata">http://localhost:5000/odata/$metadata</a></blockquote><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;edmx:Edmx Version=&quot;4.0&quot; xmlns:edmx=&quot;http://docs.oasis-open.org/odata/ns/edmx&quot;&gt;<br>  &lt;edmx:DataServices&gt;<br>    &lt;Schema Namespace=&quot;BooksAPI.OData.Models&quot; xmlns=&quot;http://docs.oasis-open.org/odata/ns/edm&quot;&gt;<br>      &lt;EntityType Name=&quot;Book&quot;&gt;<br>        &lt;Key&gt;<br>          &lt;PropertyRef Name=&quot;Id&quot; /&gt;<br>        &lt;/Key&gt;<br>        &lt;Property Name=&quot;Id&quot; Type=&quot;Edm.Int32&quot; Nullable=&quot;false&quot; /&gt;<br>        &lt;Property Name=&quot;Name&quot; Type=&quot;Edm.String&quot; Nullable=&quot;false&quot; /&gt;<br>        &lt;Property Name=&quot;AuthorId&quot; Type=&quot;Edm.Int32&quot; /&gt;<br>        &lt;Property Name=&quot;PublisherId&quot; Type=&quot;Edm.Int32&quot; /&gt;<br>        &lt;NavigationProperty Name=&quot;Author&quot; Type=&quot;BooksAPI.OData.Models.Author&quot;&gt;<br>          &lt;ReferentialConstraint Property=&quot;AuthorId&quot; ReferencedProperty=&quot;Id&quot; /&gt;<br>        &lt;/NavigationProperty&gt;<br>        &lt;NavigationProperty Name=&quot;Publisher&quot; Type=&quot;BooksAPI.OData.Models.Publisher&quot;&gt;<br>          &lt;ReferentialConstraint Property=&quot;PublisherId&quot; ReferencedProperty=&quot;Id&quot; /&gt;<br>        &lt;/NavigationProperty&gt;<br>      &lt;/EntityType&gt;<br>      &lt;EntityType Name=&quot;Author&quot;&gt;<br>        &lt;Key&gt;<br>          &lt;PropertyRef Name=&quot;Id&quot; /&gt;<br>        &lt;/Key&gt;<br>        &lt;Property Name=&quot;Id&quot; Type=&quot;Edm.Int32&quot; Nullable=&quot;false&quot; /&gt;<br>        &lt;Property Name=&quot;Name&quot; Type=&quot;Edm.String&quot; Nullable=&quot;false&quot; /&gt;<br>        &lt;NavigationProperty Name=&quot;Books&quot; Type=&quot;Collection(BooksAPI.OData.Models.Book)&quot; ContainsTarget=&quot;true&quot; /&gt;<br>      &lt;/EntityType&gt;<br>      &lt;EntityType Name=&quot;Publisher&quot;&gt;<br>        &lt;Key&gt;<br>          &lt;PropertyRef Name=&quot;Id&quot; /&gt;<br>        &lt;/Key&gt;<br>        &lt;Property Name=&quot;Id&quot; Type=&quot;Edm.Int32&quot; Nullable=&quot;false&quot; /&gt;<br>        &lt;Property Name=&quot;Name&quot; Type=&quot;Edm.String&quot; Nullable=&quot;false&quot; /&gt;<br>        &lt;NavigationProperty Name=&quot;Books&quot; Type=&quot;Collection(BooksAPI.OData.Models.Book)&quot; /&gt;<br>      &lt;/EntityType&gt;<br>    &lt;/Schema&gt;<br>    &lt;Schema Namespace=&quot;Default&quot; xmlns=&quot;http://docs.oasis-open.org/odata/ns/edm&quot;&gt;<br>      &lt;EntityContainer Name=&quot;Container&quot;&gt;<br>        &lt;EntitySet Name=&quot;Book&quot; EntityType=&quot;BooksAPI.OData.Models.Book&quot;&gt;<br>          &lt;NavigationPropertyBinding Path=&quot;Author&quot; Target=&quot;Author&quot; /&gt;<br>          &lt;NavigationPropertyBinding Path=&quot;Publisher&quot; Target=&quot;Publisher&quot; /&gt;<br>        &lt;/EntitySet&gt;<br>        &lt;EntitySet Name=&quot;Author&quot; EntityType=&quot;BooksAPI.OData.Models.Author&quot; /&gt;<br>        &lt;EntitySet Name=&quot;Publisher&quot; EntityType=&quot;BooksAPI.OData.Models.Publisher&quot;&gt;<br>          &lt;NavigationPropertyBinding Path=&quot;Books&quot; Target=&quot;Book&quot; /&gt;<br>        &lt;/EntitySet&gt;<br>      &lt;/EntityContainer&gt;<br>    &lt;/Schema&gt;<br>  &lt;/edmx:DataServices&gt;<br>&lt;/edmx:Edmx&gt;</pre><p>Cool, isn’t it?</p><h4>What’s Next?</h4><p>Well, now that you know how simple it is to implement the OData protocol in .NET, I would recommend that you spend some time getting familiar with the Protocol itself, you can find all the guidance that you need <a href="http://www.odata.org/getting-started/">here</a>.</p><p>Also, if you have the intention to use the protocol with .NET Core, I suggest that you keep a close eye on the <a href="https://www.nuget.org/packages/Microsoft.AspNetCore.OData/">Nuget Package page</a> and also the <a href="https://github.com/OData/WebApi/issues/939">feature request on GitHub</a>.</p><h4>Source Code</h4><p>You can find the whole source code for this solution on my <a href="https://github.com/lucaslra/AzureCoder-BooksAPI">GitHub</a>.</p><p>And that is all for today folks :)</p><p>I hope you enjoyed it, and don’t hesitate to use the comments section if you were left with any questions.</p><h4>Sources:</h4><ul><li><a href="http://www.odata.org/">Official OData Website</a></li><li><a href="https://dotnetthoughts.net/getting-started-with-odata-in-aspnet-core/">DotNetThoughts</a></li><li><a href="https://restfulapi.net/">RESTful API</a></li><li><a href="https://www.getpostman.com/">Postman</a></li><li><a href="https://www.nuget.org/packages/Microsoft.AspNetCore.OData/">Microsoft.AspNetCore.OData</a></li></ul><p><em>Originally published at </em><a href="http://azurecoder.net/2018/02/19/creating-odata-api-asp-net-core-2-0/"><em>The Azure Coder</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f00287928987" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[.NET Core 2.1 is coming! (and I will be back)]]></title>
            <link>https://lucaslra.medium.com/net-core-2-1-is-coming-and-i-will-be-back-765918bab873?source=rss-52058c51d1df------2</link>
            <guid isPermaLink="false">https://medium.com/p/765918bab873</guid>
            <category><![CDATA[entity-framework-core]]></category>
            <dc:creator><![CDATA[Lucas Araujo | Azure Coder]]></dc:creator>
            <pubDate>Wed, 07 Feb 2018 21:00:01 GMT</pubDate>
            <atom:updated>2018-02-07T21:00:09.465Z</atom:updated>
            <content:encoded><![CDATA[<p>Hallo Mensen :)<br> I know I’ve been away from my blog for a long time and I’ll not try to make an excuse for this, but I want to make it clear that I intend to start writing again some time this quarter!</p><p>Today I just wanted to share with you two new videos from Channel 9 with some <strong>cool demos</strong> on the new features for .NET Core 2.1. In particular I would advise you to pay close attention to the improvements on the HttpClient and the Entity Framework support for CosmosDb. Enjoy!</p><h4>What is new in .NET Core 2.1?</h4><p><a href="https://channel9.msdn.com/Shows/On-NET/NET-Core-21-Roadmap-PT1/player#ccLang=pt">.NET Core 2.1 Roadmap PT.1</a></p><h4>The Demos!!</h4><p><a href="https://channel9.msdn.com/Shows/On-NET/NET-Core-21-Roadmap-PT2/player#ccLang=pt">.NET Core 2.1 Roadmap PT.2</a></p><p>One last thing to mention. Pay close attention to the benchmarks on the build process for .NET Core 2.1, it is amazing!</p><figure><img alt="Incremental Build Improvements for .NET Core 2.1 SDK" src="https://cdn-images-1.medium.com/max/1024/0*g_4IIURXYIYzhrpn.png" /></figure><p>Really excited for the Future of .NET Core :D</p><p>.NET Core 2.1 should have its first previews released still in this February and the RTM Version is planned to this Summer!</p><p>Source: <a href="https://blogs.msdn.microsoft.com/dotnet/2018/02/02/net-core-2-1-roadmap/">.NET Core 2.1 Roadmap | .NET Blog</a></p><p><em>Originally published at </em><a href="http://azurecoder.net/2018/02/07/net-core-2-1-is-coming/"><em>The Azure Coder</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=765918bab873" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Code — Robert C. Martin]]></title>
            <link>https://lucaslra.medium.com/clean-code-robert-c-martin-b109b3dbbacc?source=rss-52058c51d1df------2</link>
            <guid isPermaLink="false">https://medium.com/p/b109b3dbbacc</guid>
            <dc:creator><![CDATA[Lucas Araujo | Azure Coder]]></dc:creator>
            <pubDate>Tue, 22 Aug 2017 07:20:35 GMT</pubDate>
            <atom:updated>2017-08-22T07:20:38.037Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>If we have learned anything over the last couple of decades, it is that programming is a craft more than it is a science.</blockquote><p><em>Originally published at </em><a href="http://azurecoder.net/2017/08/22/clean-code-robert-c-martin/"><em>The Azure Coder</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b109b3dbbacc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[ASP.NET Core MVC Pipeline] Routing Middleware — Route Handler]]></title>
            <link>https://lucaslra.medium.com/asp-net-core-mvc-pipeline-routing-middleware-route-handler-6432229fe706?source=rss-52058c51d1df------2</link>
            <guid isPermaLink="false">https://medium.com/p/6432229fe706</guid>
            <category><![CDATA[mvc-pipeline]]></category>
            <dc:creator><![CDATA[Lucas Araujo | Azure Coder]]></dc:creator>
            <pubDate>Wed, 19 Jul 2017 20:08:07 GMT</pubDate>
            <atom:updated>2017-07-19T20:08:11.312Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s move on with our series about the Core MVC Pipeline. What is the next step? Last time we learned how to point a request to a specific Router, and what if we need to handle a route in a custom way? Let’s create our custom Route Handler.</p><figure><img alt="Middleware Pipeline" src="https://cdn-images-1.medium.com/max/277/0*m8jSEjQlElOpljic.png" /><figcaption>Middleware Pipeline</figcaption></figure><p>As we can see, the Route Handler is the last step inside our Routing Middleware and, as long as the request matches any of the routes, is also the last step inside the Middleware Pipeline, we are almost ready to move on to the next phase on the Core MVC Pipeline.</p><p>But what exactly does the Route Handler do? Let’s think functionally:</p><ol><li>Our Web Server received a request and, since it is a valid request, passed it to our application.</li><li>Our application passed the request to our Middleware pipeline which running the request through every middleware until one of them decides to end the request.</li><li>The request went through a lot of processes and reached our Routing Middleware.</li><li>Our routing middleware will pass the request to our Router who will see if this request matches any known route. If it doesn’t, the middleware will pass the request to the next middleware, or initiate the response.</li></ol><p>But what if the request <strong>matches</strong> any known route? What is next? That is where our Route Handler gets to do its magic!</p><p>The Route Handler is the component that defines what to do with the Request that matches a Route on our system. The default implementation for this component is the <em>MvcRouteHandler</em>, which usually handle every single request accepted by the Router, but now we are going to implement our own Route Handler.</p><figure><img alt="Let&#39;s Code" src="https://cdn-images-1.medium.com/max/400/0*nLbIBAqELzIBuMVV.jpg" /><figcaption>Let’s Code</figcaption></figure><h4>The Code</h4><p>This component suffered a great deal of changes in the way it is structured on the Full .NET Framework in comparison with the .NET Core implementation.</p><p>To implement our Route Handler we are simply going to need a <em>RequestDelegate</em>. This request delegate will contain all the logic that must be executed against a matched route and create a response.</p><p>The code for this example will be very simple, as this is a very specialized component, and I don’t see it getting overriding frequently.</p><pre>private static RequestDelegate CustomRouteHandler()<br>{<br>    return async (c) =&gt;<br>    {<br>        await Task.Run(() =&gt; c.Response.Redirect(&quot;http://azurecoder.net&quot;));<br>    };<br>}</pre><p>It is this simple! In this example any request matched and sent to our <em>RouteHandler</em> will redirect the user to this Blog :) The object “<strong>c</strong>” is a HttpContext object, so anything that can be done with a request/response flow can be done in the RouteHandler as well.</p><p>Now we only have to hook up our <em>RouteHandler</em> on the Routing Middleware:</p><pre>app.UseMvc(routes =&gt;<br>{<br>    routes.MapRoute(&quot;blog/{*path}&quot;, CustomRouteHandler());<br><br>    // Main Route<br>    routes.MapRoute(<br>        name: &quot;default&quot;,<br>        template: &quot;{controller=Home}/{action=Index}/{id?}&quot;);<br>});</pre><p>In the case (line 3) we created a Route that will match ANY request in which the URI starts with “blog/” and send it to our custom router, which will redirect the request.</p><p>And that is all there is for a simple custom router :)<br> There is of course other ways to implement Route Handlers but this should be more than enough for the very specific cases where this is necessary.</p><p>This wraps up our talk about the Middleware part of the MVC Pipeline! In the next post we start the talk on the Controller Initialization!</p><p>See you next time :)</p><figure><img alt="That&#39;s All Folks" src="https://cdn-images-1.medium.com/max/500/0*JGwlIFCIkfxFKb77.gif" /><figcaption>That’s All Folks</figcaption></figure><p><em>Originally published at </em><a href="http://azurecoder.net/2017/07/19/route-handler/"><em>The Azure Coder</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6432229fe706" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Fallacy of Premature Optimization]]></title>
            <link>https://lucaslra.medium.com/the-fallacy-of-premature-optimization-5704c3ac0e08?source=rss-52058c51d1df------2</link>
            <guid isPermaLink="false">https://medium.com/p/5704c3ac0e08</guid>
            <category><![CDATA[perfomance]]></category>
            <category><![CDATA[azurecoder]]></category>
            <dc:creator><![CDATA[Lucas Araujo | Azure Coder]]></dc:creator>
            <pubDate>Sat, 15 Jul 2017 10:08:36 GMT</pubDate>
            <atom:updated>2017-07-15T10:12:21.248Z</atom:updated>
            <content:encoded><![CDATA[<p>I guess most of the professionals working on the software industry have already heard the following quote about optimization.</p><blockquote>Premature optimization is the root of all evil.</blockquote><p>This quote was popularized by Donald E. Knuth on his paper <a href="https://www.cs.sjsu.edu/~mak/CS185C/KnuthStructuredProgrammingGoTo.pdf">Structured Programming with <em>go to</em> statements</a>, what most of us ignore is that the quote, in his most acknowledged form was taken out of the context. A more complete quote goes like this:</p><blockquote>We should forget about small efficiencies, say about 97% of the time: <strong>premature optimization is the root of all evil.</strong><br> Yet we should not pass up our opportunities in that critical 3%.</blockquote><blockquote>A good programmer will not be lulled into complacency by such reasoning, he will be wise to look carefully at the critical code.</blockquote><p>As you can see, in a more complete context, the quote has quite a different perspective from ignoring the opportunity of optimizing your code prematurely.</p><p>You can, and you should, identify the <strong>3%</strong> of your application that is really the critical path for your users, and the optimization of this part of the code should never be ignored, as it can cause you big problems at some point in the future.</p><p>Application performance is a subject that has been ignored for a few years with the increase of computational power, but now we are in a moment where users and systems demand the best possible performance from your application, so they can also deliver their results.</p><p>It is, of course, you option to identify this <strong>3%</strong> as soon as you can, or to let your users find it for you. :)</p><p>Sources: <a href="https://channel9.msdn.com/Events/Build/2017/B8082">Surviving Success</a></p><p><em>Originally published at </em><a href="http://azurecoder.net/2017/07/15/fallacy-premature-optimization/"><em>The Azure Coder</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5704c3ac0e08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Favor Composition Over Inheritance Part 2 | Source: Coding Delight]]></title>
            <link>https://lucaslra.medium.com/favor-composition-over-inheritance-part-2-source-coding-delight-67cca4c7907a?source=rss-52058c51d1df------2</link>
            <guid isPermaLink="false">https://medium.com/p/67cca4c7907a</guid>
            <category><![CDATA[reblog]]></category>
            <category><![CDATA[via-bookmarklet]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Lucas Araujo | Azure Coder]]></dc:creator>
            <pubDate>Wed, 12 Jul 2017 15:35:13 GMT</pubDate>
            <atom:updated>2017-07-13T18:50:58.259Z</atom:updated>
            <content:encoded><![CDATA[<p>And here is the second part of the article</p><p>Yesterday I wrote part one of my two-part series on why we should favor the technique of composition over inheritance. I began by looking at how a purely inheritance-based model quickly becomes unworkable as the properties and methods of base classes often lead to an inflexible design. Today, by contrast, I will look at solving the same problem by the use of composition. Specifically, we will look at how using interfaces for composition in C# allows for a highly flexible design.</p><p>The problem posed yesterday was to model the behavior of a car when a driver applies changes to it. I want to be able to track the angle of the wheels and the speed at which the wheels have been turned by the engine. The first car to model is the Toyota Corolla.</p><p>Yesterday, the first class that was designed was the BaseCar class, which contained a number of abstract methods which defined our behavior. It also contained our wheels. Today, instead, I am going to look at the behaviors of the car. It seems to me that there are two separate behaviors which are independent of each other. There is steering and there is driving (or accelerating). These behaviors will form the basis for our interface design. A car also has a manufacturer, so we will create an interface for that too.</p><pre>interface IDriving<br><br>{<br><br>  void Accelerate(double kph);<br><br>}</pre><pre>interface ISteering<br><br>{<br><br>  void TurnLeft(double degrees);<br><br>  void TurnRight(double degrees);<br><br>}</pre><pre>interface IManufacturer<br><br>{<br><br>  string Name { get; }<br><br>}</pre><p>There are a couple of ways that we could look at designing the car interface. We could say that an ICar inherits from both ISteering and IDriving, but instead I think we should say that an ICar has both an ISteering and IDriving. This seems to make the most sense.</p><pre>interface ICar<br><br>{<br><br>  IWheel FrontLeft { get; }<br><br>  IWheel FrontRight { get; }<br><br>  IWheel RearLeft { get; }<br><br>  IWheel RearRight { get; }<br><br><br><br>  ISteering Steering { get; }<br><br>  IDriving Driving { get; }<br><br>  IManufacturer Manufacturer { get; }<br><br>}</pre><p>Already we can see that simply by thinking about the components and how they logically relate to each other, we have created a different design from before. The interfaces help us think more abstractly than base classes would otherwise had. Now that we have designed our interfaces (and the astute reader might have noticed that the Wheel class has now become an IWheel interface too, though defining either is beyond the scope of these articles) we can get started on defining the functionality of our classes.</p><p>First we will create a TwoWheelDrive class which implements the IDriving interface.</p><pre>class TwoWheelDrive : IDriving<br><br>{<br><br>  private readonly IWheel left;<br><br>  private readonly IWheel right;<br><br><br><br>  public TwoWheelDrive(IWheel left, IWheel right)<br><br>  {<br><br>    this.left = left;<br><br>    this.right = right;<br><br>  }<br><br><br><br>  public void Accelerate(double kph)<br><br>  {<br><br>    this.left.RotationSpeed += kph;<br><br>    this.right.RotationSpeed += kph;<br><br>  }<br><br>}</pre><p>Immediately it can be seen that this class can be used for both types of two-wheel drive car — front or rear. All we will have to do is pass either the front or rear wheels to it. Next up we’ll implement the two-wheel steering functionality in much the same way. Note that in this case, the steering class has to be a “front” steering class or a “rear” steering class, as each type of steering requires the wheels to turn in opposite directions to achieve the same outcome for the driver.</p><pre>class FrontSteering : ISteering<br><br>{<br><br>  private readonly IWheel frontLeft;<br><br>  private readonly IWheel frontRight;<br><br><br><br>  public FrontSteering(IWheel frontLeft, IWheel frontRight)<br><br>  {<br><br>    this.frontLeft = frontLeft;<br><br>    this.frontRight = frontRight;<br><br>  }<br><br><br><br>  public void TurnLeft(double degrees)<br><br>  {<br><br>    this.frontLeft.Angle -= degrees;<br><br>    this.frontRight.Angle -= degrees;<br><br>  }<br><br><br><br>  public void TurnRight(double degrees)<br><br>  {<br><br>    this.frontLeft.Angle += degrees;<br><br>    this.frontRight.Angle += degrees;<br><br>  }<br><br>}</pre><p>And next, my Toyota manufacturer class. I’ve implemented it as a singleton because that will be sufficient for this problem.</p><pre>class Toyota : IManufacturer<br><br>{<br><br>  private static IManufacturer instance;<br><br><br><br>  private Toyota() { }<br><br><br><br>  public string Name { get { return &quot;Toyota&quot;; } }<br><br><br><br>  public static IManufacturer GetInstance()<br><br>  {<br><br>    return instance ?? (instance = new Toyota());<br><br>  }<br><br>}</pre><p>Finally, I can create my ToyotaCorolla class.</p><pre>class ToyotaCorolla : ICar<br><br>{<br><br>  public ToyotaCorolla()<br><br>  {<br><br>    this.FrontLeft = new Wheel();<br><br>    this.FrontRight = new Wheel();<br><br>    this.RearLeft = new Wheel();<br><br>    this.RearRight = new Wheel(0, 0);<br><br>    this.Steering = new FrontSteering(this.FrontLeft, this.FrontRight);<br><br>    this.Driving = new TwoWheelDrive(this.FrontLeft, this.FrontRight);<br><br>    this.Manufacturer = Toyota.GetInstance();<br><br>  }<br><br><br><br>  public IWheel FrontLeft { get; private set; }<br><br>  public IWheel FrontRight { get; private set; }<br><br>  public IWheel RearLeft { get; private set; }<br><br>  public IWheel RearRight { get; private set; }<br><br>  <br><br>  public ISteering Steering { get; private set; }<br><br>  public IDriving Driving { get; private set; }<br><br>  public IManufacturer Manufacturer { get; private set; }<br><br>}</pre><p>Now when the customer comes along and asks for the rear wheel drive sports edition, I can create the following class for them.</p><pre>class ToyotaCorollaSports : ICar<br><br>{<br><br>  public ToyotaCorollaSports()<br><br>  {<br><br>    this.FrontLeft = new Wheel();<br><br>    this.FrontRight = new Wheel();<br><br>    this.RearLeft = new Wheel();<br><br>    this.RearRight = new Wheel(0, 0);<br><br>    this.Steering = new FrontSteering(this.FrontLeft, this.FrontRight);<br><br>    this.Driving = new TwoWheelDrive(this.RearLeft, this.RearRight);<br><br>    this.Manufacturer = Toyota.GetInstance();<br><br>  }<br><br><br><br>  public IWheel FrontLeft { get; private set; }<br><br>  public IWheel FrontRight { get; private set; }<br><br>  public IWheel RearLeft { get; private set; }<br><br>  public IWheel RearRight { get; private set; }<br><br>  <br><br>  public ISteering Steering { get; private set; }<br><br>  public IDriving Driving { get; private set; }<br><br>  public IManufacturer Manufacturer { get; private set; }<br><br>}</pre><p>In fact, it is at this point that you can quite easily see that the only difference between ToyotaCorollas lies in the parameters that are passed into the driving constructor. A pattern is emerging. We now have the ability to do away entirely with our ToyotaCorolla class. The only difference is in our constructor parameters. What I can do instead is refactor my code and use constructor parameters to define our classes.</p><pre>class Car : ICar<br><br>{<br><br>  public Car(IWheel frontLeft, IWheel frontRight, IWheel rearLeft,<br><br>            IWheel rearRight, ISteering steering, IDriving driving, <br><br>            IManufacturer manufacturer, string carName)<br><br>  {<br><br>    this.FrontLeft = frontLeft;<br><br>    this.FrontRight = frontRight;<br><br>    this.RearLeft = rearLeft;<br><br>    this.RearRight = rearRight;<br><br>    this.Steering = steering;<br><br>    this.Driving = driving;<br><br>    this.Manufacturer = manufacturer;<br><br>    this.Name = carName;<br><br>  }<br><br><br><br>  public IWheel FrontLeft { get; private set; }<br><br>  public IWheel FrontRight { get; private set; }<br><br>  public IWheel RearLeft { get; private set; }<br><br>  public IWheel RearRight { get; private set; }<br><br>  <br><br>  public ISteering Steering { get; private set; }<br><br>  public IDriving Driving { get; private set; }<br><br>  public IManufacturer Manufacturer { get; private set; }<br><br>  public string Name { get; private set; }<br><br>}</pre><pre>static class CarFactory<br><br>{<br><br>  public static ICar ToyotaCorolla()<br><br>  {<br><br>    IWheel frontLeft = new Wheel();<br><br>    IWheel frontRight = new Wheel();<br><br>    return new Car(frontLeft, frontRight, new Wheel(), new Wheel(), <br><br>      new FrontSteering(frontLeft, frontRight), <br><br>      new TwoWheelDrive(frontLeft, frontRight), Toyota.GetInstance(), <br><br>      &quot;Corolla&quot;);<br><br>  }<br><br>  public static ICar ToyotaCorollaSports()<br><br>  {<br><br>    IWheel frontLeft = new Wheel();<br><br>    IWheel frontRight = new Wheel();<br><br>    IWheel rearLeft = new Wheel();<br><br>    IWheel rearRight = new Wheel();<br><br>    return new Car(frontLeft, frontRight, rearLeft, rearRight, <br><br>      new FrontSteering(frontLeft, frontRight), <br><br>      new TwoWheelDrive(rearLeft, rearRight), Toyota.GetInstance(), <br><br>      &quot;Corolla Sports&quot;);<br><br>  }<br><br>}</pre><p>So as you can see, by using composition we have created a much more flexible design. We can reuse the bits that make sense to be reused and ignore the bits that don’t. The interfaces have helped us think abstractly and separated out how the objects relate to each other from how the objects work. We can use a car without knowing how the steering is implemented or whether it is a front, rear or four-wheel drive. We no longer have a complicated object hierarchy and adding new car designs takes a little effort. When it comes time to design a car with four-wheel drive, all we need to do is create a four-wheel drive class and a factory method.</p><p>Far too many professional developers think in an “is-a” mindset when they want to reuse code. I hope that I have sufficiently demonstrated that composition helps us reuse code far more efficiently and with a lot less complexity than using inheritance. As always, leave a comment, I would love to hear your feedback!</p><p>I am taking two weeks holiday, after which I will be (hopefully) blogging on a regular basis.</p><p>Source: <a href="https://codingdelight.com/2014/01/17/favor-composition-over-inheritance-part-2/">Favor Composition Over Inheritance part 2 | Coding Delight</a></p><p><em>Originally published at </em><a href="http://azurecoder.net/2017/07/12/favor-composition-over-inheritance-part-2/"><em>The Azure Coder</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67cca4c7907a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[ASP.NET Core MVC Pipeline] Routing Middleware — Custom IRouter]]></title>
            <link>https://lucaslra.medium.com/asp-net-core-mvc-pipeline-routing-middleware-custom-irouter-d101202e0a14?source=rss-52058c51d1df------2</link>
            <guid isPermaLink="false">https://medium.com/p/d101202e0a14</guid>
            <category><![CDATA[mvc-pipeline]]></category>
            <dc:creator><![CDATA[Lucas Araujo | Azure Coder]]></dc:creator>
            <pubDate>Sun, 09 Jul 2017 12:55:51 GMT</pubDate>
            <atom:updated>2017-07-09T12:55:54.166Z</atom:updated>
            <content:encoded><![CDATA[<p>What if you want to add some custom logic to the routing system?</p><p>There are two main components where we can inject our code to bend some rules on the framework. The first one is the IRouter.</p><figure><img alt="Middleware Pipeline - Routing" src="https://cdn-images-1.medium.com/max/277/0*Qz6adlriQ9KqdfSe.png" /><figcaption>Middleware Pipeline</figcaption></figure><p>In our flow the IRouter is represented by the “<em>Matching to Route Entry</em>” box and that is what it is. The role of the IRouter in the Routing system is to match something on a request, usually on the URI, and point it to the right <em>IRouteHandler</em>. We are going to learn more about the <em>RouteHandler</em> component in a future post.</p><h4>Why would I do that?</h4><p>As previously said, the role of the IRouter in the pipeline is to evaluate the request and pass it to the <em>IRouteHandler</em> that is the best fit, but what might be mentioned is that you can also use the IRouter to make modifications to the incoming request. In this way, whenever you have a request that matches a certain criteria you can add, remove or edit some information and let the default RouteHandler do the rest.</p><p>In my experience, that is the most common case. I don’t see complete custom implementation of the Routing system so frequently.</p><h4>The Basics</h4><p>A bit different from the custom middleware, which is entirely implemented through conventions, the custom Router must implement an Interface called IRouter. This interface is quite simple:</p><pre>namespace Microsoft.AspNetCore.Routing<br>{<br>    public interface IRouter<br>    {<br>        VirtualPathData GetVirtualPath(VirtualPathContext context);<br>        Task RouteAsync(RouteContext context);<br>    }<br>}</pre><p>The first method, <em>GetVirtualPath</em>, is used internally by the framework to generate urls based on this route in methods like the <em>HTML.ActionLink</em> one, the second method, <em>RouteAsync</em>, is where our logic will really reside.</p><p>Our class should start with something like this:</p><pre>public class CustomRouter : IRouter<br>{<br>    private IRouter _defaultRouter;<br><br>    public CustomRouter(IRouter defaultRouter)<br>    {<br>        _defaultRouter = defaultRouter;<br>    }<br><br>    public VirtualPathData GetVirtualPath(VirtualPathContext context)<br>    {<br>        return _defaultRouter.GetVirtualPath(context);<br>    }<br><br>    public Task RouteAsync(RouteContext context)<br>    {<br>        throw new NotImplementedException();<br>    }<br>}</pre><h4>Routing our Requests</h4><p>The concept behind the <em>RouteAsync</em> method is quite simple and straightforward, we do all the checking necessary to see if the provided route matches our IRouter context and, if it does, we execute the needed logic and inform the Routing middleware that the request has been handled.</p><pre>public class CustomRouter : IRouter<br>{<br>    private IRouter _defaultRouter;<br><br>    public CustomRouter(IRouter defaultRouteHandler)<br>    {<br>        _defaultRouter = defaultRouteHandler;<br>    }<br><br>    public VirtualPathData GetVirtualPath(VirtualPathContext context)<br>    {<br>        return _defaultRouter.GetVirtualPath(context);<br>    }<br><br>    public async Task RouteAsync(RouteContext context)<br>    {<br>        var headers = context.HttpContext.Request.Headers;<br>        var path = context.HttpContext.Request.Path.Value.Split(&#39;/&#39;);<br>        <br>        // Look for the User-Agent Header and Check if the Request comes from a Mobile <br>        if (headers.ContainsKey(&quot;User-Agent&quot;) &amp;&amp;<br>            headers[&quot;User-Agent&quot;].ToString().Contains(&quot;Mobile&quot;))<br>        {<br>            var action = &quot;Index&quot;;<br>            var controller = &quot;&quot;;<br>            if (path.Length &gt; 1)<br>            {<br>                controller = path[1];<br>                if (path.Length &gt; 2)<br>                    action = path[2];<br>            }<br><br>            context.RouteData.Values[&quot;controller&quot;] = $&quot;Mobile{controller}&quot;;<br>            context.RouteData.Values[&quot;action&quot;] = action;<br><br>            await _defaultRouter.RouteAsync(context);<br>        }<br>    }<br>}</pre><p>We are doing the <strong>checking</strong> part on the if statement where we analyze if the request comes from a Mobile User-Agent (there are certainly better and more secure ways to do this but it is enough for the purpose of the demonstration) and if our Router finds that the request comes from such an agent, we apply some logic to change the <em>controller</em> and <em>action</em> values in our <em>RouteData</em>, therefore ensuring that our request will be redirected to the right Action.</p><p>If everything works as expected, then we send our modified context to the Default RouteHandler, and let it process it. The RouteHandler will set the value for the <em>Handler</em> property in our context, and it will let the framework know that the request has been Handled by our Router and no longer need to be processed by other Routers.</p><h4>Hooking up to the Routing Middleware</h4><p>Now we have a nice and functional Custom <em>Router</em> but if you run the application you will see that it is never touched by your request and that is because we never hooked our Router to the Routing Middleware.</p><p>The Routing Middleware has a stack of Routers that it will use to try and match a request, hence we need to add our Custom Router to this Stack. Let’s do it.</p><pre>public void Configure(IApplicationBuilder app, IHostingEnvironment env)<br>{<br>    app.UseStaticFiles();<br><br>    app.UseMvc(routes =&gt;<br>    {<br>        routes.Routes.Add(new CustomRouter(routes.DefaultHandler));<br><br>        routes.MapRoute(<br>            name: &quot;default&quot;,<br>            template: &quot;{controller=Home}/{action=Index}/{id?}&quot;);<br>    });<br>}</pre><p>Now we add a new Router to the <strong>Routes</strong> collection and we passed the Default Handler, which will be used by our Routing flow.</p><p>And that is all we have to do to make our Router capture every request that comes from a mobile User-Agent and redirect them to specific controllers/actions.</p><p>To be completely honest, creating a custom Router will usually be a bit of an overkill as you can achieve most of the desired behaviors through the usage of easier components on the pipeline (including the middleware), but I think that is important to go through all the major components that we can customize.</p><p>What do you think? Sounds like something that you can use in your application?</p><p>Thanks for Reading! Tot ziens :)</p><p>MVC Pipeline Series</p><ul><li><a href="http://azurecoder.net/2017/07/05/middleware-pipeline/">[ASP.NET Core MVC Pipeline] Middleware Pipeline</a></li><li><a href="http://azurecoder.net/2017/07/03/asp-net-core-mvc-pipeline/">The ASP.NET Core MVC Pipeline</a></li></ul><p>Sources</p><ul><li><a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing">Routes in ASP.NET Core</a></li></ul><p><em>Originally published at </em><a href="http://azurecoder.net/2017/07/09/routing-middleware-custom-irouter/"><em>The Azure Coder</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d101202e0a14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[ASP.NET Core MVC Pipeline] Middleware Pipeline]]></title>
            <link>https://lucaslra.medium.com/asp-net-core-mvc-pipeline-middleware-pipeline-cd9375db0d03?source=rss-52058c51d1df------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd9375db0d03</guid>
            <category><![CDATA[mvc-pipeline]]></category>
            <dc:creator><![CDATA[Lucas Araujo | Azure Coder]]></dc:creator>
            <pubDate>Wed, 05 Jul 2017 18:05:16 GMT</pubDate>
            <atom:updated>2017-07-05T18:05:22.441Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s play with the Middleware Pipeline :)</p><p>Do you guys remember the flow that I showed you in the first post? No? Let’s revisit it:</p><figure><img alt="The ASP.NET Core MVC Pipeline" src="https://cdn-images-1.medium.com/max/567/0*MG0-dxMWOqNAaLkL.png" /><figcaption>The ASP.NET Core MVC Pipeline</figcaption></figure><p>So, what do we want to do here is to start from the beginning and in this post we are going to focus on the Blue part of the flow, the Middleware Pipeline:</p><figure><img alt="Middleware Pipeline" src="https://cdn-images-1.medium.com/max/277/0*Qm8xKkDMUPKt2Nt5.png" /><figcaption>Middleware Pipeline</figcaption></figure><h4>What is a Middleware?</h4><p>So, what is a middleware in the context of the Core MVC Pipeline, and why should we care about it?</p><blockquote>Middleware is software that is assembled into an application pipeline to handle requests and responses. Each component chooses whether to pass the request on to the next component in the pipeline, and can perform certain actions before and after the next component is invoked in the pipeline.</blockquote><p>Hmmm… so each middleware is actually a piece of code, which follow some patterns, that we can ‘pile’ forming what we call a pipeline. Each of those pieces of code can (and should) implement its own logic and, that is the most interesting part, can decide whether or not to pass on a request! Because of that, each middleware is empowered to end an HTTP request and ignore every other middleware after if it decides to. Let me draw it for you:</p><figure><img alt="Middleware Pipeline" src="https://cdn-images-1.medium.com/max/781/0*XadwogmNjgoo0Y1M.png" /><figcaption>Middleware Pipeline</figcaption></figure><p>In the example on the left, the request pass through all the middleware in the Pipeline and finally gets answered by the Routing Middleware.</p><p>In the example on the right, the request is cut short by a custom middleware that send the response itself rather than pass it along to next one.</p><p>A couple of important things to notice:</p><ul><li>A middleware can execute successfully its function and still pass the request to next middleware, therefore allowing for more changes before sending the response.</li><li>The routing middleware is certainly an important one but he is not vital on the middleware pipeline. It is vital to the MVC Framework, but you could have a perfectly working application without the routing middleware.</li></ul><h4>Our first Middleware</h4><p>The sequence of middleware is defined on the <strong>Configure</strong> method of the <strong>Startup.cs</strong> class.</p><pre>public class Startup<br>    {<br>       // ... More Code<br><br>        public void Configure(IApplicationBuilder app, IHostingEnvironment env)<br>        {<br>            app.UseDeveloperExceptionPage(); // Exception Handling Page Middleware<br><br>            app.UseStaticFiles(); // Static Files serving Middleware<br><br>            app.UseMvcWithDefaultRoute(); // MVC Routing Middleware<br>        }<br>    }</pre><p>Each of the “<em>Use…</em>” methods define a middleware. Let’s inject our own super simple middleware on the stack:</p><pre>public void Configure(IApplicationBuilder app, IHostingEnvironment env)<br>        {<br>            app.UseDeveloperExceptionPage(); // Exception Handling Page Middleware<br><br>            app.UseStaticFiles(); // Static Files serving Middleware<br><br>            /* Custom Middleware Inline */<br>            app.Use(async (context, next) =&gt;<br>            {<br>                if (context.Request.Method == &quot;GET&quot;)<br>                    await next();<br>                else<br>                    await context.Response.WriteAsync(&quot;Invalid method&quot;);<br>            });<br>            /* End Custom Middleware Inline */<br><br>            app.UseMvcWithDefaultRoute(); // MVC Routing Middleware<br>        }</pre><p>In this case we are defining that only the requests sent with the HTTP method <em>GET</em> are going to be pass on to the Routing Middleware. Other HTTP methods will be answered directly by our middleware and will never reach the Routing system. Notice that we defined our middleware inline, inside the <em>Configure</em> method and that is <strong>not</strong> a good practice because it worsen readability and break the <em>Single Responsibility</em> principle.</p><p>Pretty simple, ahn? Let’s get into some details.</p><h4>Order Matters</h4><p>Keep it in mind, the order in which your middleware is set up inside the <em>Configure</em> method matters! It matters because this is the order in which they are going to be executed when a request is received. In our example our custom middleware would never be hit if the user requests an existing static resource (like an image, or a JS file) because the <em>UseStaticFiles</em> middleware would have handle the request and sent a response to the user shortcutting the request.</p><h4>Before AND After the next Middleware</h4><p>We can see in our example that the execution of the next middleware in the pipeline is represented by a call to the <em>next()</em> delegate, and that means that we can execute some logic before <strong>and after</strong> the next delegate execution.</p><pre>public void Configure(IApplicationBuilder app, IHostingEnvironment env)<br>        {<br>            app.UseStaticFiles();<br><br>            app.Use(async (context, next) =&gt;<br>            {<br>                    // Execute some BEFORE before calling the next middleware<br>                    await next();<br>                    // Execute some AFTER before calling the next middleware<br>            });<br><br>            app.UseMvcWithDefaultRoute();<br>        }</pre><h4>Use, Run or Map</h4><p>Every middleware must run using one those three methods that define a specific behavior for the middleware.</p><p>Use</p><p>First of all, the most common method, the ‘<em>Use…</em>’. This method is the one that allows our middleware to receive a request, process it and, if necessary, pass it on to the next middleware on the pipeline.</p><p>Use(IApplicationBuilder, Func&lt;HttpContext, Func, Task&gt;)</p><p>We receive a delegate with an <em>HTTPContext</em> with all the details available about the request and another delegate, which is actually the call to the next middleware. As a result we can call the next middleware in the pipeline whenever we want or not even call it, if our logic says it is not necessary.</p><pre>app.Use(async (context, next) =&gt; { <br>    // Our custom logic <br>    if(something) <br>    { <br>        await next(); <br>        // More custom logic <br>    } <br>    else <br>    { <br>        // Next middleware is never called on this path<br>    } <br>});</pre><p>Run</p><p>Then we have the ‘<em>Run…</em>’ method and this method allows us to define a middleware that will <strong>always</strong> end the execution, simply because it has no knowledge of a next middleware in the pipeline.</p><p>Run(IApplicationBuilder, RequestDelegate)</p><p>In this case, the only thing we receive is the delegate with the custom logic of our own middleware.</p><p>Map &amp; MapWhen</p><p>And then we have the ‘<em>Map…</em>’ method which, as the name implies, allows us to map a request to a middleware depending on the <strong>Path</strong> of the request.</p><p>Map is a little bit different from the previous methods in the sense that you only map the request to a middleware, but you are still going to need to set an ‘<em>Use…</em>’ or ‘<em>Run…</em>’ method to actually execute our logic.</p><p>Map(IApplicationBuilder, PathString, Action)</p><p>So the Map method actually pass on an instance of the IApplicationBuilder interface! Which allows us to define a new middleware depending on the mapped request.</p><pre>app.Map(&quot;/CustomPath&quot;, (appPath1) =&gt;<br>            {<br>                appPath1.Use(async (context, next) =&gt;<br>                {<br>                    // Cuustom Middleware code for Path 1<br>                    await next();<br>                });<br>            });<br><br>            app.Map(&quot;/AnotherCustomPath&quot;, (appPath2) =&gt;<br>            {<br>                appPath2.Run(async (context) =&gt;<br>                {<br>                    // Custom Middleware code for Path 2<br>                    await context.Response.WriteAsync(&quot;Done&quot;);<br>                });<br>            });</pre><p>The Map method also has a variant called MapWhen that allows us to map the middleware against some condition on the HttpContext.</p><pre>app.MapWhen(context =&gt; context.Request.IsHttps, appContext =&gt;<br>            {<br>                appContext.Use(async (context, next) =&gt;<br>                {<br>                    // Custom Logic<br>                    await next();<br>                });<br>            });<br><br>            app.MapWhen(context =&gt; context.Request.Method == &quot;GET&quot;, appContext =&gt;<br>              {<br>                  appContext.Run(async context =&gt;<br>                  {<br>                      await context.Response.WriteAsync(&quot;Done!&quot;);<br>                  });<br>              });</pre><p>So, those four methods are supposed to give us all the flexibility that we need to create our middleware.</p><p>I think it is possible to notice that creating a middleware inline is not a great idea, right? It gets messy really quick and we don’t want that. Let’s start creating a real Middleware in a more decent way.</p><h4>Creating our Custom Middleware</h4><p>First of all we need to do is to create a new class and, to do that, we are going to follow some simple conventions. Our Middleware’s class and filename must end with the word ‘Middleware’:</p><pre>public class CustomHeadersMiddleware<br>    {<br>        private readonly RequestDelegate next;<br><br>        public CustomHeadersMiddleware(RequestDelegate next)<br>        {<br>            this.next = next;<br>        }<br><br>        public Task Invoke(HttpContext context)<br>        {<br>            return next(context);<br>        }<br>    }</pre><p>This code, by itself, is already a working middleware. It won’t do anything, except calling the next middleware, but it will work. :)</p><p>Now I expect you to be asking “Where is the Base Class?”, “You forgot to implement the interface?” or “Where are the overridden methods?” and believe, I asked myself these exact same questions. The answer is simple, the framework will understand and use our Middleware based on the conventions we followed:</p><ul><li>The Middleware must have a Constructor that accepts one RequestDelegate</li><li>The Middleware must have a public Method that receives an HttpContext as parameter and returns a Task type.</li></ul><p>Pretty straightforward, right?</p><p>Let’s implement some logic to our Middleware. Worth mentioning that there should be better ways to implement what we are doing here, but for the purpose of the Post Series, it should be enough.</p><pre>public class CustomHeadersMiddleware<br>    {<br>        private readonly RequestDelegate next;<br><br>        public CustomHeadersMiddleware(RequestDelegate next)<br>        {<br>            this.next = next;<br>        }<br><br>        public async Task Invoke(HttpContext context)<br>        {<br>            if (context.Request.Method == &quot;GET&quot;)<br>            {<br>                context.Response.Headers.Add(&quot;AzureCoderBlog&quot;, DateTime.UtcNow.ToString());<br>                await next(context);<br>            }<br>            else<br>            {<br>                await context.Response.WriteAsync(&quot;Method not Allowed&quot;);<br>            }<br>        }<br>    }</pre><p>Basically what our middleware is doing is making sure that only requests with the “GET” method ever reach the next middleware and if any other method is used than the request will be shortcut.</p><p>Looks much better than having all this code <em>inline</em> right? But we are not ready yet!</p><h4>Hookup with the Middleware Pipeline!</h4><p>While this is a working code for a middleware we haven’t hooked this up to our pipeline. Let’s do this now. Back to our <strong>Startup.cs</strong> Class, in our configure method, we want our new middleware to be added like this:</p><pre>public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)<br>        {<br>            app.UseStaticFiles();<br><br>            app.UseMiddleware&lt;CustomHeadersMiddleware&gt;();<br><br>            app.UseMvcWithDefaultRoute();<br>        }</pre><p>Looking really good now, isn’t it? Let’s make look more like the rest of the middleware pipeline by creating one extension method for our middleware.</p><pre>public static class CustomHeadersMiddlewareExtensions<br>    {<br>        public static IApplicationBuilder UseCustomHeaders(this IApplicationBuilder app)<br>        {<br>            return app.UseMiddleware&lt;CustomHeadersMiddleware&gt;();<br>        }<br>    }</pre><p>And now we can set up our Middleware like this:</p><pre>public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)<br>        {<br>            app.UseStaticFiles();<br><br>            app.UseCustomHeaders();<br><br>            app.UseMvcWithDefaultRoute();<br>        }</pre><p>And that is it! We have a custom middleware setup and working. Our pipeline now should work like this:</p><figure><img alt="Middleware Samples" src="https://cdn-images-1.medium.com/max/1024/0*L5A70-0dObOINI6i.png" /><figcaption>Middleware Samples</figcaption></figure><p>And that is it for the first post of the Core MVC Pipeline. What do you think? Can you imagine some scenarios where changing the Middleware Pipeline would be useful for your application?</p><p>On the next post we will start talking about the Routing Middleware, where we can introduce some logic to change the Routing rules :)</p><p>Tot ziens!</p><p>Source:</p><ul><li><a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware">ASP.NET Core Docs</a></li></ul><p><em>Originally published at </em><a href="http://azurecoder.net/2017/07/05/middleware-pipeline/"><em>The Azure Coder</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd9375db0d03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The ASP.NET Core MVC Pipeline]]></title>
            <link>https://lucaslra.medium.com/the-asp-net-core-mvc-pipeline-8cf7e1ef4a45?source=rss-52058c51d1df------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cf7e1ef4a45</guid>
            <category><![CDATA[mvc-pipeline]]></category>
            <dc:creator><![CDATA[Lucas Araujo | Azure Coder]]></dc:creator>
            <pubDate>Mon, 03 Jul 2017 19:42:55 GMT</pubDate>
            <atom:updated>2017-07-03T19:42:56.937Z</atom:updated>
            <content:encoded><![CDATA[<p>Hallo Iedereen :)<br> I decided to start a series of posts about custom components for the ASP.NET Core MVC Pipeline.</p><p>Most of you should know by now that ASP.NET Core was mostly redesigned to be more modular, extensible and to deal with the ‘platform agnostic’ nature of the new framework. This redesign also allows us to customize the way every request is processed, adding custom components in each step of the pipeline.</p><h4>The ASP.NET Core MVC Pipeline</h4><figure><img alt="The ASP.NET Core MVC Pipeline" src="https://cdn-images-1.medium.com/max/567/0*Vnz_9urnFp7D-qJ2.png" /><figcaption>The ASP.NET Core MVC Pipeline</figcaption></figure><p>The idea is to have one post for each of the small blocks on the pipeline, precisely because it is possible to hook up your custom code in any of those points.</p><p>I’ll start by providing a brief overview of which is the role of each block on the pipeline:</p><h4>Middleware Pipeline</h4><figure><img alt="Middleware Pipeline" src="https://cdn-images-1.medium.com/max/277/0*b0FzQofHLTP00c2b.png" /><figcaption>Middleware Pipeline</figcaption></figure><p>The middleware pipeline is the entry point for each request in an HTTP Request, it is basically a stack of components that can execute some logic and decide whether to pass the request to the next middleware, or to send the response back to the client.</p><h4>Routing Middleware</h4><p>The routing middleware is just one of many that can be used by the ASP.NET Core but is of major importance to the Core MVC Pipeline. The reason for this it that this is the Middleware that ‘captures’ an incoming request and really starts the MVC Pipeline. If an incoming request url does not match any registered Route the request is passed onward to the next Middleware, ignoring the MVC Pipeline, but when the request url matches a known route, that is when the MVC Pipeline really begins.</p><h4>Controller Initialization</h4><figure><img alt="Controller Initialization" src="https://cdn-images-1.medium.com/max/276/0*6XM1L-RoqMGDUrMV.png" /><figcaption>Controller Initialization</figcaption></figure><p>Once a route is found by the Routing middleware, the next step is to find a controller that matches the route and instantiate it. The process of finding the best suitable Controller and Action for a Route can also be customized.</p><h4>Action Execution</h4><figure><img alt="Action Execution" src="https://cdn-images-1.medium.com/max/567/0*9aYCZ3gioYzrHCyb.png" /><figcaption>Action Execution</figcaption></figure><p>Now we are in the core of what really is the MVC pattern. The Action Execution is the process that will really process the incoming request and, after that, generate a Result. This is also the process where we can hook up most of our components.</p><h4>Model Binding</h4><p>One of the greatest features on the MVC Framework is the ability to bind request data to POCO Objects. I’ll try to explain a bit about how the standard Models Binders work, and how you can create your own Model Binder.</p><h4>Filters</h4><p>Filters are components that can be injected at many stages of the Action Execution and that will allow us to define behaviors that we want in our Actions, but that are not necessarily part of the LOB Logic.</p><h4>Action Result</h4><p>Finally, the action result is the last step of the Action Execution, and it involves basically to create a ‘Result’ type that will be processed by the Result Execution.</p><h4>Result Execution</h4><figure><img alt="Result Execution" src="https://cdn-images-1.medium.com/max/276/0*2El8aRX4_vT9O6o-.png" /><figcaption>Result Execution</figcaption></figure><p>And the last step in the Core MVC Pipeline has arrived! Here is where our ‘Result’ will be analysed and processed accordingly. Here we can also inject some filters before and after our processing, allowing us to change the way the result will be processed.</p><h4>Where do we start?</h4><p>From the beginning! Of course :) We will start creating a Custom Middleware that will be executed before the Routing Middleware.</p><p>The first post will be up very soon!</p><p>Tot ziens! (And I just spent all my Dutch in this post)</p><p>Source:</p><ul><li><a href="http://www.dotnettricks.com/">DotNetTricks</a></li></ul><p><em>Originally published at </em><a href="http://azurecoder.net/2017/07/03/asp-net-core-mvc-pipeline/"><em>The Azure Coder</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cf7e1ef4a45" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>