<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="https://blog.dangl.me/rss/xslt"?>
<rss xmlns:a10="http://www.w3.org/2005/Atom" version="2.0">
  <channel>
    <title>Dangl.Blog();</title>
    <link>https://blog.dangl.me/</link>
    <description>Blogging about .Net, DevOps, Networking and BIM. Home of the free GAEB Converter.</description>
    <generator>Articulate, blogging built on Umbraco</generator>
    <item>
      <guid isPermaLink="false">1439</guid>
      <link>https://blog.dangl.me/archive/setting-the-language-in-chrome-headless-for-e2e-tests/</link>
      <category>Web Development</category>
      <title>Setting the Language in Chrome Headless for E2E Tests</title>
      <description>&lt;p&gt;For End-to-End (E2E) testing of web apps, the headless mode of Chrome is a great choice. We're using it in our projects to ensure some true end to end test coverage, often for stories like happy paths for important actions. E2E tests are usually quite cumbersome to write, and tend to be brittle during upgrades, but they give you a lot of confidence when doing automated deployments, and free up valuable developer time from having to do repeated, manual tests and verifications. I've blogged before about them, for example hows to &lt;a data-udi="umb://document/97c1f03c1f504869b17557ed82d8069a" href="/archive/running-fully-automated-e2e-tests-in-electron-in-a-docker-container-with-playwright/" title="Running Fully Automated E2E Tests in Electron in a Docker Container with Playwright"&gt;instrument them via Playwright&lt;/a&gt; or how you can use &lt;a data-udi="umb://document/bcf39609aba94771a7795e140656ff03" href="/archive/improving-aspnet-core-end-to-end-tests-with-selenium-docker-images/" title="Improving ASP.NET Core End-to-End Tests with Selenium Docker Images"&gt;Selenium in a Docker container&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;One thing that's been missing is the ability to set a language for the headless Chrome instance when testing. Especially if you have multilingual apps that automatically detect the users language, you might experience problems in testing when you're checking for text contents or trying to find Html elements via their labels. There was a long open issue with Chrome, where the &lt;a href="https://bugs.chromium.org/p/chromedriver/issues/detail?id=1925" title="Chromedriver Issue 1925: Expose content settings in headless mode" data-anchor="?id=1925"&gt;language supplied via a command line argument was simply not set in headless mode&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;But, this has changed with &lt;a href="https://developer.chrome.com/articles/new-headless/" title="New Chrome Headless Mode"&gt;the new headless option for chrome&lt;/a&gt;!&lt;/p&gt;
&lt;p&gt;Finally, when you start headless via &lt;span class="Code"&gt;--headless=new&lt;/span&gt;, you can simply set the language with another switch: &lt;span class="Code"&gt;--lang=en&lt;/span&gt;. This makes testing so much easier, and allows to provide a consistent developer experience, no matter the local language settings.&lt;/p&gt;
&lt;p&gt;Happy testing!&lt;/p&gt;</description>
      <pubDate>Thu, 01 Jun 2023 10:17:26 Z</pubDate>
      <a10:updated>2023-06-01T10:17:26Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1437</guid>
      <link>https://blog.dangl.me/archive/changing-the-order-of-parameters-in-swagger-openapi-documents-when-using-nswag-to-generate-the-swaggerfile/</link>
      <category>Web Development</category>
      <title>Changing the Order of Parameters in Swagger / OpenAPI Documents when using NSwag to Generate the Swaggerfile</title>
      <description>&lt;p&gt;Our &lt;a href="https://www.dangl-it.com/products/avacloud-gaeb-saas/" title="Dangl IT GmbH - AVACloud"&gt;AVACloud SaaS&lt;/a&gt; product has been available for a few years already. While that's a great achievement in itself, it also comes with drawbacks: The API is used by a lot of customers by now, which requires us to keep it stable and not introduce breaking changes or incompatibilities with existing implementations. &lt;em&gt;Move fast&lt;/em&gt; still applies, but the &lt;em&gt;break things&lt;/em&gt; part would now be a problem.&lt;/p&gt;
&lt;p&gt;So, we've recently updated one endpoint to support additional parameters. It's a simple REST endpoint that takes a file, some options, and does a conversion. In the.NET backend, the controller receives three parameters: The file, and two options objects for the import respectively export configuration. That maps nicely, and introducing additional parameters is as easy as adding a new property to a view model used for the bindings. Many clients generated via Swagger can follow the same approach of using options objects for the client interface, thus no problem there.&lt;/p&gt;
&lt;p&gt;However, the objects are transported as query parameters. This means that from a Swagger perspective, we've now added two new query parameters. This can cause problems when the new parameters are not sorted to the end, thus generating a new client version would break existing implementations and require attention and a rewrite from every consumer of the API.&lt;/p&gt;
&lt;p&gt;Luckily, we're using &lt;a href="https://github.com/RicoSuter/NSwag" title="GitHub - RicoSuter - NSwag"&gt;NSwag in the backend&lt;/a&gt;, which allows a great deal of customization. When we set up Swagger generation, we can simply inject custom code in the &lt;span class="Code"&gt;PostProcess&lt;/span&gt; callback and sort the parameters however we want.&lt;/p&gt;
&lt;p&gt;&lt;code data-gist-id="ecf19226ac8edc162862058dc38d7d0d" data-gist-file="SwaggerExtensions.cs"&gt;&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;We're just getting the current parameters, apply our custom sort logic which ensures the new parameters are at the end, and then clear and refill the parameter list.&lt;/p&gt;
&lt;p&gt;There are other options available, such as using custom &lt;span class="Code"&gt;x-position&lt;/span&gt; attributes, but I've found that relying on such non-standard features often causes problems later with some client generators. So, let's keep it simple and stupid😀&lt;/p&gt;
&lt;p&gt;Happy customizing!&lt;/p&gt;</description>
      <pubDate>Sun, 16 Apr 2023 20:15:53 Z</pubDate>
      <a10:updated>2023-04-16T20:15:53Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1434</guid>
      <link>https://blog.dangl.me/archive/updating-azure-app-service-on-linux-for-docker-via-webhooks-from-c/</link>
      <category>Web Development</category>
      <title>Updating Azure App Service on Linux for Docker via Webhooks from C#</title>
      <description>&lt;p&gt;If you're using Azure App Service to run Docker images, you already know how easy it is to get your app running. Azure nicely abstracts everything for you - it may be a bit more expensive than hosting your own Kubernetes cluster on cloud VMs, but it makes more than up for it in simplicity.&lt;/p&gt;
&lt;p&gt;Among the cooler features of using Azure App Service to run Docker ist that you automatically get a &lt;a data-udi="umb://document/0755700f9ef045ee98f516729840107e" href="/archive/deploy-to-azure-app-service-with-no-downtime-by-using-staging-slots/" title="Deploy to Azure App Service with no Downtime by using Staging Slots"&gt;green/blue deployment&lt;/a&gt;. All you have to do is update the Docker image for the App Service and after a few moments, you're running the latest version, without any downtime. This is super convenient when you're deploying Docker to Azure Container Registry, setting up automatic updates is then just a single click.&lt;br /&gt;However, it's a bit more complicated when you're using something else, e.g. GitHub Packages for hosting your Docker containers, since then you're responsible for calling a webhook in Azure to let it know there's a new container version available.&lt;/p&gt;
&lt;p&gt;That's in itself not very complicated, but it has one little point that's worth mentionioning, as you see in the code below:&lt;/p&gt;
&lt;p&gt;&lt;code data-gist-id="70473da2fb96f38f0e0e4091a3dd71c1" data-gist-file="DockerWebhook.cs"&gt;&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;The webhook url in Azure includes an &lt;span class="Code"&gt;UserInfo&lt;/span&gt; part, meaning it's got &lt;span class="Code"&gt;username:password&lt;/span&gt; right there in the url. Most tools will support that out of the box, but in case you're using .NET to send the webhooks, you should be aware that you need to parse that information and use it with Http Basic Authentication.&lt;/p&gt;
&lt;p&gt;By the way, for real life implementations, you probably don't want to hardcode the webhook uri in your build script😀&lt;/p&gt;
&lt;p&gt;Happy deploying!&lt;/p&gt;</description>
      <pubDate>Sun, 16 May 2021 17:43:01 Z</pubDate>
      <a10:updated>2021-05-16T17:43:01Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1430</guid>
      <link>https://blog.dangl.me/archive/improving-aspnet-core-end-to-end-tests-with-selenium-docker-images/</link>
      <category>Web Development</category>
      <title>Improving ASP.NET Core End-to-End Tests with Selenium Docker Images</title>
      <description>&lt;p&gt;Last year, &lt;a data-udi="umb://document/399075438e934a2ebc7c10226d8cb86c" href="/archive/performing-end-to-end-tests-for-a-net-core-web-api-with-an-angular-frontend-in-docker-with-jenkins/" title="Performing End-to-End Tests for a .NET Core Web API with an Angular Frontend in Docker with Jenkins"&gt;I've blogged about automating end-to-end (E2E) tests&lt;/a&gt; with an ASP.NET Core application. Quickly summarized, you're setting up your environment locally via Docker and then use Seleniums ChromeDriver to automate UI tests for your web application. This worked well, but had one big drawback - when you're executing the tests, you need to have Chrome installed on the build agent or on your local machine. While most who do web development probably have Chrome available, it's a bit of a hassle with testing - you need to make sure that your Selenium version matches the current Chrome version.&lt;/p&gt;
&lt;p&gt;Luckily, &lt;a href="https://github.com/SeleniumHQ/docker-selenium" title="GitHub - SeleniumHQ - docker-selenium"&gt;Selenium provides Docker containers&lt;/a&gt; with an embedded Chrome and their own RemoteWebDriver. This means to be able to access an automated browser via Selenium, you just have to spin up a container and connect to it. That's pretty great and makes versioning really easy!&lt;/p&gt;
&lt;p&gt;Building on &lt;a data-udi="umb://document/399075438e934a2ebc7c10226d8cb86c" href="/archive/performing-end-to-end-tests-for-a-net-core-web-api-with-an-angular-frontend-in-docker-with-jenkins/" title="Performing End-to-End Tests for a .NET Core Web API with an Angular Frontend in Docker with Jenkins"&gt;the previous post&lt;/a&gt;, you just have to follow these steps:&lt;/p&gt;
&lt;h2&gt;Docker Configuration&lt;/h2&gt;
&lt;p&gt;&lt;code data-gist-id="7f33008d2fffdef4eee932eb2a8dde90" data-gist-file="docker-compose.yml" data-gist-highlight-line="43-47"&gt;&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;I'm using the &lt;span class="Code"&gt;selenium/standalone-chrome:3.141.59&lt;/span&gt; image and make sure to assign it enough memory, as per the official recommendation.&lt;/p&gt;
&lt;h2&gt;Test Setup&lt;/h2&gt;
&lt;p&gt;&lt;code data-gist-id="7f33008d2fffdef4eee932eb2a8dde90" data-gist-file="E2eTestsBase.cs" data-gist-highlight-line="32-37"&gt;&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;In the test project, I simply check if the containerized Selenium driver should be used and return a &lt;span class="Code"&gt;RemoteWebDriver&lt;/span&gt; instead of a &lt;span class="Code"&gt;ChromeDriver&lt;/span&gt;. For context, I do sometimes let the tests run with my local version of Chrome and have the debugger attached, so I'm not using the headless mode there but instead can track the actions.&lt;/p&gt;
&lt;h2&gt;Browser Automation&lt;/h2&gt;
&lt;p&gt;&lt;code data-gist-id="7f33008d2fffdef4eee932eb2a8dde90" data-gist-file="SignupAsync.cs"&gt;&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Finally, here's a simple method that automates the sign up process. You'll note that writing E2E tests is quite cumbersome, because you're really just describing step-by-step what's happening. But you'll be able to test your actual project in real world conditions and have it run automatically, which is pretty much worth it!&lt;br /&gt;You're now able to fully test your app in any environment, all you need is Docker.&lt;/p&gt;
&lt;p&gt;Happy testing!&lt;/p&gt;</description>
      <pubDate>Wed, 20 May 2020 13:28:10 Z</pubDate>
      <a10:updated>2020-05-20T13:28:10Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1420</guid>
      <link>https://blog.dangl.me/archive/performing-end-to-end-tests-for-a-net-core-web-api-with-an-angular-frontend-in-docker-with-jenkins/</link>
      <category>Web Development</category>
      <title>Performing End-to-End Tests for a .NET Core Web API with an Angular Frontend in Docker with Jenkins</title>
      <description>&lt;p&gt;If you've been following my blog in the last few years, you might have noticed that I kind of like testing &amp;amp; automation. Mostly, I'm working with .NET and TypeScript in cloud and backend services, so plain old integration testing gets me pretty far. Recently, however, I've done a bit more on the frontend side and I wasn't happy with the way I setup my testing.&lt;/p&gt;
&lt;p&gt;Basically, I had separate tests for the frontend and backend, with just very rudimentary end to end tests that were run on a pre-production slot in Azure. If these passed, the slot was switched live and a new version was deployed.&lt;/p&gt;
&lt;p&gt;This approach worked, but had three big drawbacks:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;It was slow. The app had to be built and deployed to the cloud. Results from this could take up to 10 minutes until I had feedback&lt;/li&gt;
&lt;li&gt;It couldn't be run locally, since it really was more of a pre-deployment check than an actual test. This also meant I didn't get feedback on all code changes, only on those in a branch that got deployed&lt;/li&gt;
&lt;li&gt;Testing was limited to operations that didn't change any production data, such as creating new users or assigning roles&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;It was a really uncomfortable situation to be in, and the solution was clear: Automate it, dockerize everything and have full end to end tests run on every single commit in a headless Chrome browser. It took me a bit to get started with all this, so in this article, I'll describe in detail how I did it.&lt;/p&gt;
&lt;h2&gt;What are end-to-end tests?&lt;/h2&gt;
&lt;p&gt;In automated testing, there are different types or categories of tests you write. The definitions are always a bit fuzzy, everyone has a different opinion on them. The most fundamental tests are called unit tests, checking the behavior of a small, independent unit. Integration tests verify that multiple components in conjunction work as expected, usually with a longer run time than unit tests. Finally, automated end-to-end or e2e tests are performed on the whole application, from a users perspective. Think browser or UI automation.&lt;/p&gt;
&lt;p&gt;You should call them what's most appropriate in your situation. For example, is an automated test checking the REST API endpoints of your backend, hooked up to a local database, still an integration test or already end-to-end? I'd say it's an integration test, since your users typically don't access the API directly. Except when they're developers themselves and do... So, don't get caught up in semantics😊&lt;/p&gt;
&lt;p&gt;For this article, end-to-end tests are tests that simulate the users behavior in a browser, they test both the frontend code and the backend together, simulating real user actions on your production system.&lt;/p&gt;
&lt;h2&gt;Overview&lt;/h2&gt;
&lt;p&gt;This post won't go into some details that are out of the focus here. I'll assume you have &lt;a data-udi="umb://document/8e45943c37d9451894adcf73e2449f5c" href="/archive/installing-and-configuring-jenkins-on-windows-server-with-iis/" title="Installing and Configuring Jenkins on Windows Server with IIS"&gt;some understanding of using Jenkins&lt;/a&gt; to automate your tests (or any other CI service, like Azure DevOps or AppVeyor), are familiar with Docker as well as basic unit testing approaches and frameworks such as xUnit. Additionally, I'm using &lt;a data-udi="umb://document/6ecb73fad5484466b0fc73c1a80f79c3" href="/archive/escalating-automation-the-nuclear-option/" title="Escalating Automation - The Nuclear Option"&gt;the NUKE build system&lt;/a&gt; to orchestrate the setup, but simple bash or PowerShell commands will be perfectly fine for you.&lt;/p&gt;
&lt;h2&gt;Docker Setup&lt;/h2&gt;
&lt;p&gt;The easiest way for me was to run all required services in Docker Compose. Let's take a quick look at the following script:&lt;/p&gt;
&lt;p&gt;&lt;code data-gist-id="99d4649000834d825a5f717834a4dca4" data-gist-file="docker-compose.yml"&gt;&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;My setup consists of three images:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Dangl.Identity, which is the app under test. It's &lt;a href="https://identity.dangl-it.com" title="Dangl.Identity"&gt;an OpenID server with user, rights &amp;amp; role management and related services&lt;/a&gt;, built on IdentityServer4, that we're using at Dangl&lt;strong&gt;IT&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;Dangl.Icons, which is a really small service that's similar to Gravatar, it essentially generates user icons&lt;/li&gt;
&lt;li&gt;SQL Server, to match the setup of the production environment&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The setup is app specific and likely quite different in your case, but the gist is that we'll have a full featured app with all required services, mirroring the production environment, available at &lt;em&gt;http://localhost:&lt;/em&gt;&lt;span&gt;&lt;em&gt;44848&lt;/em&gt; when running this composition.&lt;/span&gt;&lt;/p&gt;
&lt;h2&gt;&lt;span&gt;Test Configuration&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;&lt;span&gt;To actually perform the test, a mix of technologies is used: While xUnit is the test framework itself, I'm using Selenium for browser automation. A minimal .csproj looks like this:&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;code data-gist-id="99d4649000834d825a5f717834a4dca4" data-gist-file="Dangl.Identity.E2E.Tests.csproj"&gt;&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;The main object you'll be using for e2e tests is the &lt;span class="Code"&gt;ChromeDriver&lt;/span&gt;. It's your context for interacting with the browser and really easy to setup:&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;code data-gist-id="99d4649000834d825a5f717834a4dca4" data-gist-file="E2eTestsBase.cs"&gt;&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;You'll notice that I check if the debugger is attached to check if I'm running it locally in Visual Studio, otherwise I set it to headless and simulate a Full HD resolution. This example class makes use of xUnits &lt;em&gt;Fixture&lt;/em&gt;, but that's just for performing some initialization for the test environment, you can skip that.&lt;/span&gt;&lt;/p&gt;
&lt;h2&gt;&lt;span&gt;Test Implementation&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;&lt;span&gt;Now you're ready to write tests! I'm usually separating them again at this point, one category represents simple, minimal tests while the other covers &lt;em&gt;user stories&lt;/em&gt;, e.g. complex tasks from registration to login to performing some tasks on the site.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Let's take a look at a simple test, checking if the UI disables the &lt;em&gt;Register&lt;/em&gt; button when the user missed filling in her username:&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;code data-gist-id="99d4649000834d825a5f717834a4dca4" data-gist-file="RegistrationPage.cs"&gt;&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;The code should be simple to follow, I hope😊 More complex tests aren't much different, it's just more code. You'll generally notice a trend here - while unit tests require very little code, e2e tests quickly grow into dozens of lines if you're doing more complex actions.&lt;/span&gt;&lt;/p&gt;
&lt;h2&gt;&lt;span&gt;Running your Tests&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;Depending on how you're automating your pipeline, you're using bash or PowerShell or something similar. I'm a huge fan of the &lt;a data-udi="umb://document/6ecb73fad5484466b0fc73c1a80f79c3" href="/archive/escalating-automation-the-nuclear-option/" title="Escalating Automation - The Nuclear Option"&gt;NUKE build system&lt;/a&gt;, so that's what I naturally use for all my automation needs. Let's take a look at the implementation:&lt;/p&gt;
&lt;p&gt;&lt;code data-gist-id="99d4649000834d825a5f717834a4dca4" data-gist-file="Build.cs"&gt;&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Examining it closely, it does just two things: It runs &lt;span class="Code"&gt;docker-compose up&lt;/span&gt; to start the Docker environment in a non-blocking way and then executes &lt;span class="Code"&gt;dotnet test&lt;/span&gt;. xUnit test results are both printed to the console and saved as &lt;span class="Code"&gt;testresults.xml&lt;/span&gt; for further analyzing.&lt;/p&gt;
&lt;h2&gt;&lt;span&gt;Running Tests in Jenkins&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;The Jenkins pipeline is configured via a &lt;em&gt;Docker E2E Tests&lt;/em&gt; build step. It's configured to run on a Linux node, executes NUKE with the &lt;span class="Code"&gt;E2ETests&lt;/span&gt; target and then reports the test results:&lt;/p&gt;
&lt;p&gt;&lt;code data-gist-id="99d4649000834d825a5f717834a4dca4" data-gist-file="Jenkinsfile"&gt;&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;You'll see it's worth the effort when a nice, all-green stage view greets you in Jenkins:&lt;/p&gt;
&lt;p&gt;&lt;img style="display: block; margin-left: auto; margin-right: auto;" src="https://blog.dangl.me/media/1192/jenkins_e2e_pipeline_view.png" alt="Jenkins Pipeline View for End to End Tests" data-udi="umb://media/6e81b6d1482c4c91853abd9861166a5e" /&gt;&lt;/p&gt;
&lt;h2&gt;&lt;span&gt;Summary&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;While there are quite a few steps involved in performing proper end-to-end testing, the payoff is worth it: You're able to validate a mirror of your production setup in exactly the same way your users are using the app. While this post has just scratched the surface of what you can do, it hopefully gave you a good starting point to implement your own strategy.&lt;/p&gt;
&lt;p&gt;Happy testing!&lt;/p&gt;</description>
      <pubDate>Fri, 26 Jul 2019 18:12:04 Z</pubDate>
      <a10:updated>2019-07-26T18:12:04Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1399</guid>
      <link>https://blog.dangl.me/archive/caching-bundled-and-minified-css-and-javascript-with-the-wrong-file-extension-in-the-free-tier-on-cloudflare-with-umbraco/</link>
      <category>Web Development</category>
      <title>Caching Bundled and Minified CSS and JavaScript with the Wrong File Extension in the Free Tier on CloudFlare with Umbraco</title>
      <description>&lt;p&gt;I've been using &lt;a href="https://www.cloudflare.com" title="CloudFlare"&gt;CloudFlare&lt;/a&gt; for quite some time now, on this blog and on many of my other websites. It's a great service that offers lots of value even in it's free tier. Most useful, for me, is it's built-in CDN (&lt;em&gt;Content Delivery Network&lt;/em&gt;) functionality. This means basically the following:&lt;/p&gt;
&lt;p&gt;This blog here is hosted on an Azure server somewhere in Europe. That's great for people living near, but bad for all the visitors outside of Europe. Or even just a few hundred kilometers away from my server. It's bad in the sense that web requests take a lot of time when the physical locations of client and server are continents apart. Even worse, when the first request to my main page is finished, a second round of requests retrieves images, CSS and JavaScript files. That's where CloudFlare comes into play: They'll cache all my assets on their servers, of which they have many around the world. So they're kind of a proxy between this blog and it's visitors and they optimize delivery by caching my content, meaning typical page loads from North America, for example, no longer take 8 seconds to complete. Most web requests don't even hit my server, at all.&lt;/p&gt;
&lt;p&gt;I'm using the free tier on this site, which works well enough but has some limitations. For example, they're only caching &lt;a href="https://support.cloudflare.com/hc/en-us/articles/200172516-Which-file-extensions-does-Cloudflare-cache-for-static-content-" title="CloudFlare Support - Which file extensions does Cloudflare cache for static content?"&gt;a handful of file extensions&lt;/a&gt;, so &lt;span class="Code"&gt;.js&lt;/span&gt; and &lt;span class="Code"&gt;.css&lt;/span&gt; files are cached but, &lt;span class="Code"&gt;.axd&lt;/span&gt; are not. Since I'm using &lt;a href="https://umbraco.com" title="Umbraco"&gt;Umbraco&lt;/a&gt; on this blog, the built-in &lt;a href="https://github.com/Shazwazza/ClientDependency" title="GitHub - Shazwazza - ClientDependency"&gt;ClientDependency package&lt;/a&gt; makes sure that all my JavaScript and CSS files are bundled and minified in production builds. The package internally works by routing the requests through a custom handler via a route similar to &lt;span class="Code"&gt;/DependencyHandler.axd?s=h4sh&amp;amp;t=JavaScript&lt;/span&gt;. Bundling and minification is great and what we want, but we also want CloudFlare to cache the requests. We'll have to get Umbraco to serve it via urls with the correct file extensions then!&lt;/p&gt;
&lt;p&gt;First, you need to create a custom renderer that outputs the desired file endings in your website links to the bundles:&lt;/p&gt;
&lt;p&gt;&lt;code data-gist-id="a3782d74e339f7ed46666776ccf30def" data-gist-file="NonAxdDependenciesRenderer.cs"&gt;&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;This new renderer should be registered in your &lt;span class="Code"&gt;ClientDependency.config&lt;/span&gt; file. Simply replace the old one:&lt;/p&gt;
&lt;p&gt;&lt;code data-gist-id="a3782d74e339f7ed46666776ccf30def" data-gist-file="ClientDependency.config"&gt;&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Now, for the magic to work, we're using a rewrite rule in IIS' &lt;span class="Code"&gt;web.config&lt;/span&gt; file to map requests that come to either &lt;span class="Code"&gt;DependencyHandler.js&lt;/span&gt; or &lt;span class="Code"&gt;DependencyHandler.css&lt;/span&gt; internally to the route &lt;span class="Code"&gt;DependencyHandler.axd&lt;/span&gt;:&lt;/p&gt;
&lt;p&gt;&lt;code data-gist-id="a3782d74e339f7ed46666776ccf30def" data-gist-file="web.config"&gt;&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Happy caching!&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Update, one week after the original post:&lt;/strong&gt; With this approach, I managed to increase the cached bandwith via CloudFlare from about 20% to over 60%! Most of the uncached content now is the &lt;a data-udi="umb://document/26371a3f96164b2eb78ef953e792764a" href="/gaeb-converter/" title="GAEB Converter"&gt;dynamic content generated by the GAEB converter&lt;/a&gt;. Virtually everything else doesn't cost me any more bandwith!&lt;/p&gt;</description>
      <pubDate>Fri, 11 Jan 2019 19:47:44 Z</pubDate>
      <a10:updated>2019-01-11T19:47:44Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1395</guid>
      <link>https://blog.dangl.me/archive/deploy-to-azure-app-service-with-no-downtime-by-using-staging-slots/</link>
      <category>Web Development</category>
      <title>Deploy to Azure App Service with no Downtime by using Staging Slots</title>
      <description>&lt;p&gt;My company provides the &lt;a rel="noopener" href="https://www.dangl-it.com/products/avacloud-gaeb-saas/" target="_blank" title="Dangl IT - AVACloud - GAEB SaaS"&gt;&lt;strong&gt;AVA&lt;/strong&gt;Cloud webservice&lt;/a&gt; as a SaaS offering. It's used to integrate tendering workflows for the &lt;a data-udi="umb://document/83feb7e86c454aeab940a924425cc23a" href="/archive/what-is-gaeb/" title="What is GAEB?"&gt;German GAEB standard&lt;/a&gt; in my customers' apps. In fact, it's also used to power the &lt;a data-udi="umb://document/26371a3f96164b2eb78ef953e792764a" href="/gaeb-converter/" title="GAEB Converter"&gt;free GAEB Converter&lt;/a&gt; here on this blog.&lt;br /&gt;When running software as a service, it's mandatory that you have no downtime - this means for deployment scenarios, you can't afford to shut down your app, update it and slowly restart it. In fact, even warmup times in the range of 10 to 20 seconds are sometimes considered service interruptions, and they certainly don't make your service look professional and your customers happy!&lt;/p&gt;
&lt;p&gt;Traditionally, you'd host multiple instances of your app with a central load balancer in front of it. When you update the app, you drain single instances until they have no more open connections, update them and repeat this process until all your nodes are at the latest version. This works fine, but is often a bit tedious to manage, especially from a DevOps perspective. Luckily, Azure App Service has the concept of deployment slots built in. You're only managing a single site, deploy to a staging slot, wait for it to warm up and then seamlessly swap it with the production instance. This can even be done automatically, so all you have to do is deploy to your staging slot and you're good to go.&lt;/p&gt;
&lt;p&gt;However, sometimes you want to do some integration tests after deployment to ensure that the site works correctly, so you can't use the auto swap feature. In the following snippet, I'll show you how to use the &lt;a href="https://www.nuget.org/packages/Microsoft.Azure.Management.Fluent/" title="NuGet - Microsoft.Azure.Management.Fluent"&gt;Microsoft.Azure.Management.Fluent&lt;/a&gt; package to manage your App Services via C#.&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/aac6b7ea1ce3fd578fc8bddc4de199ec.js"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;To ensure that the app is healthy and working as expected, I'm doing a simple check on the &lt;a rel="noopener" href="https://avacloud-api.dangl-it.com/status" target="_blank" title="AVACloud App Health"&gt;https://avacloud-api.dangl-it.com/status&lt;/a&gt; endpoint. The app would report an unhealthy status if anything's not right. In your real life scenario, you might do a bit more than checking a single http response.&lt;/p&gt;
&lt;blockquote&gt;&lt;strong&gt;Tip:&lt;/strong&gt; If disaster strikes, keep calm and remember that with deployment slots in Azure, you're just one single action away from doing a rollback to your latest working versions!&lt;/blockquote&gt;
&lt;p&gt;To set this up, you need to create a service principal in Azure with access rights to your App Service instance. Just &lt;a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/howto-create-service-principal-portal" title="Microsoft Docs - Create an Azure Service Principal"&gt;follow the official docs&lt;/a&gt;, they're describing it in great detail. Just remember to follow best security practices and only allow access to a single App Service, not your whole subscription!&lt;/p&gt;
&lt;p&gt;If you're interested how to do more DevOps &amp;amp; build automation directly with C#, &lt;a data-udi="umb://document/6ecb73fad5484466b0fc73c1a80f79c3" href="/archive/escalating-automation-the-nuclear-option/" title="Escalating Automation - The Nuclear Option"&gt;have a look at the introduction for NUKE&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Happy swapping!&lt;/p&gt;</description>
      <pubDate>Tue, 13 Nov 2018 19:20:07 Z</pubDate>
      <a10:updated>2018-11-13T19:20:07Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1394</guid>
      <link>https://blog.dangl.me/archive/different-response-schemas-in-aspnet-core-swagger-api-definition-with-nswag/</link>
      <category>Web Development</category>
      <title>Different Response Schemas in ASP.NET Core Swagger API Definition with NSwag</title>
      <description>&lt;p&gt;I'm using automatically generated Swagger API definitions in some of my projects, such as &lt;a rel="noopener" href="https://avacloud-api.dangl-it.com/swagger-internal" target="_blank" title="AVACloud Swagger Specification"&gt;AVACloud&lt;/a&gt; and &lt;a rel="noopener" href="https://identity.dangl-it.com" target="_blank" title="Dangl.Identity"&gt;Dangl.Identity&lt;/a&gt;. Against best practices, I've got some controllers that might return different types of response objects. For example, I've developed &lt;a rel="noopener" href="https://github.com/GeorgDangl/LightQuery" target="_blank" title="GitHub - GeorgDangl - LightQuery"&gt;LightQuery&lt;/a&gt; to enablie pagination and sorting in ASP.NET API controllers with the single addition of a &lt;span class="Code"&gt;[LightQuery]&lt;/span&gt; attribute.&lt;br /&gt;This means that, depending on the request, the response might be a simple JSON array of objects or it might be paginated and wrapped in a response container with information about the current subset, similar to how OData structures its responses.&lt;/p&gt;
&lt;p&gt;On top of that, I'm a big fan of doing as little work as possible. In the context of web APIs, this means I'll use &lt;a rel="noopener" href="https://github.com/RSuter/NSwag" target="_blank" title="GitHub - RSuter - NSwag"&gt;NSwag&lt;/a&gt; on the server side to automatically generate &lt;a rel="noopener" href="https://swagger.io" target="_blank" title="Swagger"&gt;Swagger&lt;/a&gt; API definitions, which I subsequently use to drive the automatic generation of, for example, .NET or TypeScript clients for libraries and web frontends. To facilitate that, I'm annotating my controllers with a bit of metadata, such as the &lt;span class="Code"&gt;[ProducesResponseType]&lt;/span&gt; attribute.&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/acecc279b2cbf7f366a6487eb50d3833.js?file=Controller_Invalid.cs"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;As you can see, I've used the attribute twice - once to indicate the plain response, a second time to state what the paginated response will look like. Up until NSwag v11.19, this produced correct code - both schemas were included in the action descriptor of the API specification. This meant that my .NET clients did type the response as &lt;span class="Code"&gt;object&lt;/span&gt; and I had to handle it at the consumer side.&lt;/p&gt;
&lt;p&gt;However, after upgrading NSwag to v11.20, I've noticed that it was only picking up the first defined response type, thus simply ignoring all others:&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/acecc279b2cbf7f366a6487eb50d3833.js?file=swagger_invalid.json"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;For obvious reasons, this is bad - the generated spec did not match with the actual behavior of my server. After doing a bit of digging around, I did not find anything about this change being intentional. However, I've also discovered that you should preferably use the attributes shipped in the &lt;span class="Code"&gt;NSwag.Annotations&lt;/span&gt; namespace.&lt;/p&gt;
&lt;p&gt;Swapping the attribute leads to this action definition:&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/acecc279b2cbf7f366a6487eb50d3833.js?file=Controller_Fixed.cs"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;which promptly produces correct API definitions again:&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/acecc279b2cbf7f366a6487eb50d3833.js?file=swagger_fixed.json"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;You can spot the difference in the generated .NET / C# client, where it now correctly produces the response as &lt;span class="Code"&gt;object&lt;/span&gt; again:&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/acecc279b2cbf7f366a6487eb50d3833.js?file=SwaggerGenerated.cs"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;Finally, to support my striving for having to do as little work as possible, I've added two tests to ensure I'll never run into this specific problem again.&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/acecc279b2cbf7f366a6487eb50d3833.js?file=UnitTests.cs"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;The first test requests the generated Swagger specification from the In-Memory TestHost instance and just ensures that a particular action I know to have two response schemas actually has two schemas. The second one is just a safeguard - I'm using reflection to ensure I do never use two &lt;span class="Code"&gt;[ProducesResponseType]&lt;/span&gt; attributes on the same controller action to define valid responses.&lt;/p&gt;
&lt;p&gt;In summary, I'm really happy with automatically generating Swagger specifications, but I'm learning something new about it every week. If you're relying on such generated documents, I'd recommend you have good integration tests for your projects and use them. Changes might come in suddenly when doing package upgrades without you necessarily noticing them early.&lt;/p&gt;
&lt;p&gt;Happy coding!&lt;/p&gt;</description>
      <pubDate>Sat, 27 Oct 2018 19:46:52 Z</pubDate>
      <a10:updated>2018-10-27T19:46:52Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1393</guid>
      <link>https://blog.dangl.me/archive/migrating-an-umbraco-site-from-a-server-to-an-azure-web-app/</link>
      <category>Web Development</category>
      <title>Migrating an Umbraco Site from a Server to an Azure Web App</title>
      <description>&lt;p&gt;&lt;a rel="noopener" href="https://umbraco.com" target="_blank" title="Umbraco CMS"&gt;Umbraco&lt;/a&gt; is a great choice for a .NET based CMS, in fact, this blog and &lt;a rel="noopener" href="https://www.dangl-it.com" target="_blank" title="Dangl IT Homepage"&gt;my professional site&lt;/a&gt; both run on Umbraco. It is, however, still running on the full .NET Framework, with ASP.NET Core compatibility far, far out on the roadmap. This means that it's sometimes not as easy to handle as more modern solutions.&lt;/p&gt;
&lt;p&gt;But this doesn't stop you from running it in Azure - in fact, as you'll see, it's quite easy to migrate from a regular, Windows Server hosted solution to an Azure Web App, with all the benefits included, such as auto scaling or easy blue-green deployments. My main reason for porting was to consolidate all my production infrastructure in Azure, as well as benefit from the much higher availability in contrast to a server I have to manage. Just last week, my virtual server was down for over an hour due to scheduled updates to mitigate the latest Intel processor flaws.&lt;/p&gt;
&lt;h2&gt;Migration Steps&lt;/h2&gt;
&lt;p&gt;You'll have to do three basic steps to migrate your Umbraco site while keeping all the content:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Migrate your SQL database to one hosted in Azure.&lt;/li&gt;
&lt;li&gt;Copy your Umbraco &lt;span class="Code"&gt;media&lt;/span&gt; folder, which includes all your uploaded files, to an Azure Blob Storage.&lt;/li&gt;
&lt;li&gt;Update your Umbraco repository and configure it to deploy to Azure.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;SQL Migration&lt;/h3&gt;
&lt;p&gt;Microsoft has made it really easy to move On Premise SQL databases to Azure. There's a simple tool, &lt;a rel="noopener" href="https://docs.microsoft.com/en-us/azure/sql-database/sql-database-migrate-your-sql-server-database" target="_blank" title="Microsoft - Data Migration Assistant - Documentation"&gt;the Data Migration Assistant&lt;/a&gt;, which should handle everything automatically. Just follow the linked tutorial and you're good to go. You will get some warnings when migrating the database structure, related to no longer supported Xml data types, but you can ignore those. Also, make sure your target database name does not contain a &lt;span class="Code"&gt;.&lt;/span&gt; in it's name, as that will cause a bug and make it unable to connect to your Azure SQL instance.&lt;/p&gt;
&lt;h3&gt;Media Migration&lt;/h3&gt;
&lt;p&gt;In Umbraco, all the files you upload are saved by default in the &lt;span class="Code"&gt;media&lt;/span&gt; folder, relative to the root of your website. In Azure, that's a big no no. For once, disk access in your Web App tends to be not the fastest. Also, you'll run into issues as soon as you scale to multiple instances - your uploaded media files might get out of sync between instances and even disappear completely when you scale down again.&lt;/p&gt;
&lt;p&gt;The recommended approach is to use the Azure Blob Storage service for this. Simplified, it's just storage as a service, driven by a REST API. This means you have to configure a storage account in Azure, then install the &lt;a rel="noopener" href="https://github.com/JimBobSquarePants/UmbracoFileSystemProviders.Azure" target="_blank" title="GitHub - JimBobSquarePants - UmbracoFileSystemProviders.Azure"&gt;Umbraco extension for Azure Storage&lt;/a&gt; as a NuGet package and you're done. The NuGet installation script will automatically update your config files to make use of the new provider. Keep the old config around, as you might need it for local debugging of your Umbraco instance. I've chosen to simply include both config files and swap the right one in via a build task, depending on the environment.&lt;/p&gt;
&lt;p&gt;Now all that's left is to put the actual data you already have in your Blob Storage. There's &lt;a rel="noopener" href="https://docs.microsoft.com/en-us/azure/storage/common/storage-use-azcopy" target="_blank" title="Azure Documentation - AzCopy"&gt;AzCopy&lt;/a&gt;, which simply let's you do this via a PowerShell cmdlet. I've also written &lt;a rel="noopener" href="https://github.com/GeorgDangl/AzureFolderMigrator" target="_blank" title="GitHub - GeorgDangl - AzureFolderMigrator"&gt;a really small console app for this&lt;/a&gt;, which does the same and is a simple .NET Core dll executed with two arguments.&lt;/p&gt;
&lt;h3&gt;Umbraco Configuration &amp;amp; Deployment&lt;/h3&gt;
&lt;p&gt;There's little you have to do different regarding Umbraco's configuration and deployment strategy. When you've configured Azure SQL and Blob Storage, your website works as before.&lt;/p&gt;
&lt;p&gt;However, there's one tip when hosting in Azure: To mitigate the really slow startup times for fresh deployments or app restarts, you might want to &lt;a rel="noopener" href="https://docs.microsoft.com/en-us/azure/app-service/web-sites-staged-publishing#configure-auto-swap" target="_blank" title="Azure Docs - Web App Staging Slots with Auto Swap"&gt;configure a staging slot with auto swap enabled&lt;/a&gt; and &lt;a rel="noopener" href="https://docs.microsoft.com/en-us/iis/configuration/system.webServer/applicationInitialization/" target="_blank" title="Microsoft Docs - web.config Application Initialization"&gt;configure initialization actions&lt;/a&gt; to warm your site up before it's getting traffic. This means you'll no longer have to wait up to two minutes until your site responds to traffic!&lt;/p&gt;
&lt;p&gt; &lt;/p&gt;
&lt;p&gt;If you're looking for options to automate your deployments, you can &lt;a data-udi="umb://document/6ecb73fad5484466b0fc73c1a80f79c3" href="/archive/escalating-automation-the-nuclear-option/" title="Escalating Automation - The Nuclear Option"&gt;take a look at the NUKE build tool&lt;/a&gt;. It's open source, flexible and comes with lots of stuff built in - I use it literally everywhere.&lt;/p&gt;
&lt;p&gt; &lt;/p&gt;
&lt;p&gt;Happy blogging!&lt;/p&gt;</description>
      <pubDate>Fri, 14 Sep 2018 18:38:56 Z</pubDate>
      <a10:updated>2018-09-14T18:38:56Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1392</guid>
      <link>https://blog.dangl.me/archive/securing-aspnet-core-controllers-with-a-policy-and-api-keys/</link>
      <category>Web Development</category>
      <title>Securing ASP.NET Core Controllers with a Policy and Api Keys</title>
      <description>&lt;p&gt;In a typical ASP.NET Core web service request pipeline, you'll find authentication pretty early on, then some authorization and finally the execution of the desired action.&lt;/p&gt;
&lt;p&gt;For most cases, that's great. However, you surely have encountered situations where all you needed was a simple yes/no validation - often for services that don't return stored information but simply perform some action based on your inputs.  Integrating that in full-blown approaches like OpenId flows can often be cumbersome. Imagine you'll want to store your build artifacts on some web service you own - passing a single, secret &lt;span class="Code"&gt;Api key&lt;/span&gt; through your CI pipeline is much easier than setting up complicated, multi-step authentication setups.&lt;/p&gt;
&lt;p&gt;Generally speaking, when your action does neither retrieve information nor alter existing data, you're safe to use an Api key.&lt;/p&gt;
&lt;p&gt;With ASP.NET Core, you'd do that by creating a custom &lt;span class="Code"&gt;Policy&lt;/span&gt; that guards certain actions. These components are essential:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;An &lt;span class="Code"&gt;IAuthorizationRequirement&lt;/span&gt;, which &lt;em&gt;defines&lt;/em&gt; the requirement&lt;/li&gt;
&lt;li&gt;Accompanied by an &lt;span class="Code"&gt;AuthorizationHandler&lt;/span&gt;, which &lt;em&gt;checks&lt;/em&gt; the requirement&lt;/li&gt;
&lt;li&gt;A bit of plumbing in your app to make them work&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Let's walk through the implementation!&lt;/p&gt;
&lt;p&gt;First, define an &lt;span class="Code"&gt;ApiKeyRequirement&lt;/span&gt;:&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/87db6426962bf50933b093e0952570e1.js?file=ApiKeyRequirement.cs"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;It's an implementation of the &lt;span class="Code"&gt;IAuthorizationRequirement&lt;/span&gt; interface and simply stores the list of all valid Api keys in-memory.&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/87db6426962bf50933b093e0952570e1.js?file=ApiKeyRequirementHandler.cs"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;The corresponding &lt;span class="Code"&gt;ApiKeyRequirementHandler&lt;/span&gt; is responsible for evaluating incoming requests for their compliance with the requirement, in this case by checking if the Api key is given in the request header.&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/87db6426962bf50933b093e0952570e1.js?file=Startup.cs"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;This has to be wired together in your &lt;span class="Code"&gt;Startup&lt;/span&gt; class. First, you have to add a custom authorization policy with a unique name - &lt;span class="Code"&gt;ApiKeyPolicy&lt;/span&gt; in this case. An instance of the &lt;span class="Code"&gt;ApiKeyRequirement&lt;/span&gt; is added to it. Secondly, you have to register the &lt;span class="Code"&gt;ApiKeyRequirementHandler&lt;/span&gt; in your service collection.&lt;/p&gt;
&lt;p&gt;When everything is correctly set up and configured, you can now reference this authorization policy in your controllers:&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/87db6426962bf50933b093e0952570e1.js?file=Controller.cs"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Please consider this post simply as an example!&lt;/strong&gt; For production use, you'd want to implement at least storing the Api keys hashed in your database, with the option to revoke them and with some connection between users and Api keys&lt;/p&gt;
&lt;p&gt;Happy Authenticating!&lt;/p&gt;
&lt;p&gt;PS: If you're looking for an approach to implement custom authentication, you can take a look at how that is &lt;a data-udi="umb://document/cdb8080983c84831bf184f373bf56cdc" href="/archive/http-basic-authentication-in-aspnet-core-projects/" title="Http Basic Authentication in Asp.Net Core Projects"&gt;implemented with using Http Basic Authentication as example&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Edit, 30.01.2020&lt;/em&gt;: It's always great to get feedback, especially when a blog post was able to help somebody! &lt;a href="https://randommer.io/" title="Randommer.io"&gt;Valentin from randommer.io&lt;/a&gt; used this example to quickly secure their API with keys.&lt;/p&gt;</description>
      <pubDate>Thu, 12 Jul 2018 19:45:05 Z</pubDate>
      <a10:updated>2018-07-12T19:45:05Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1391</guid>
      <link>https://blog.dangl.me/archive/excluding-assemblies-in-aspnet-core-mvc-controller-discovery/</link>
      <category>Web Development</category>
      <title>Excluding Assemblies in ASP.NET Core MVC Controller Discovery</title>
      <description>&lt;p&gt;I'm a big fan of using the &lt;a href="https://www.nuget.org/packages/Microsoft.AspNetCore.TestHost" title="NuGet - Microsoft.AspNetCore.TestHost"&gt;Microsoft.AspNetCore.TestHost&lt;/a&gt; package to perform &lt;a href="https://github.com/GeorgDangl/Dangl.Data.Shared/tree/develop/test/Dangl.Data.Shared.AspNetCore.Tests.Integration" title="GitHub - GeorgDangl/Dangl.Data.Shared - Integration Tests"&gt;integration tests&lt;/a&gt; for ASP.NET Core web projects. Even so much that I've put my central OpenId server using &lt;a href="https://github.com/IdentityServer/IdentityServer4" title="GitHub - IdentityServer4"&gt;IdentityServer4&lt;/a&gt; in a NuGet package, hosting itself in-memory. This let's me perform my integration tests as close to the staging and production environments as possible.&lt;/p&gt;
&lt;p&gt;In one project, however, I've had some undesired behavior: Both the OpenId server and the actual project under test defined a route &lt;span class="Code"&gt;GET /status&lt;/span&gt;, so when I tried to request that I got an exception stating that multiple routes matched. That was weird, since there's two TestHost instances in memory. It turns out that with the latest updates, ASP.NET Core scans all loaded assemblies for controllers, so my &lt;em&gt;application under test&lt;/em&gt; did also include the controllers from my &lt;em&gt;integration test authentication service&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;It's quite an easy fix, though:&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/6ba8339308857d6d04eb11c8880247c6.js?file=Startup.cs"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;Simply make sure that when you're configuring MVC, explicitly exclude assemblies for controller discovery that you want to ignore.&lt;/p&gt;
&lt;p&gt;Happy Testing!&lt;/p&gt;
&lt;p&gt; &lt;/p&gt;</description>
      <pubDate>Tue, 10 Jul 2018 17:09:21 Z</pubDate>
      <a10:updated>2018-07-10T17:09:21Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1390</guid>
      <link>https://blog.dangl.me/archive/altering-outbound-traffic-from-iis-with-rewrite-rules/</link>
      <category>Web Development</category>
      <title>Altering Outbound Traffic from IIS with Rewrite Rules</title>
      <description>&lt;p&gt;Sometimes, you're hosting apps in IIS where you can't or won't access the source code. For example, I'm hosting a private Git server with &lt;a href="https://bonobogitserver.com" title="Bonobo Git Server"&gt;Bonobo.Git&lt;/a&gt;, which I'm using to mirror repositories for &lt;a href="https://www.dangl-it.com/products/gaeb-ava-net-library/" title="Dangl IT - Libraries with Source Code Access"&gt;customers that get source code access&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;My main development happens on GitHub, but for some commercial projects I offer source code access. Since I can't do that via GitHub (it would be reselling of their services), I have set up a private instance of Bonobo Git.&lt;/p&gt;
&lt;p&gt;While Bonobo Git is Open Source, I do use their prepackaged versions for deployments, instead of maintaining a fork. It works great out of the box and requires very little configuration. I had just one little requirement that was not offered: Hiding the list of users who have access to the source code since I don't have permission to share my customers data with each other.&lt;/p&gt;
&lt;p&gt;While you could add some custom JavaScript or CSS, this wouldn't solve the issue - the server should not send the data at all, instead of relying it to be hidden by the client. That's &lt;strong&gt;a big No-No&lt;/strong&gt;!&lt;/p&gt;
&lt;p&gt;Luckily, there's a lot you can do with plan old IIS &lt;span class="Code"&gt;web.config&lt;/span&gt; entries, like using a rewrite rule that simply removes the section completely from the response before it's sent over the wire.&lt;/p&gt;
&lt;p&gt;Take this little snippet:&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/7c5f8dc150d897d938e5d74bdde6eaa8.js?file=web.config.xml"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;There's an &lt;span class="Code"&gt;outboundRule&lt;/span&gt; called &lt;span class="Code"&gt;Remove Git Repository Contributors&lt;/span&gt; which does the following:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;It's active only for urls like &lt;span class="Code"&gt;/Repository/Detail/{RepoId}&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Only when the response content type starts with &lt;span class="Code"&gt;text/html&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Text that matches a defined regular expression on the page is simply replaced with an empty string&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This single rule takes care of preventing sensible information to ever be sent out from the server!&lt;/p&gt;
&lt;p&gt;Additionally, there's one restriction with content-altering outbound rules: They work only for non-compressed content. This means, in case you have enabled compression, you must disable it for this to work:&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/7c5f8dc150d897d938e5d74bdde6eaa8.js?file=web.compression.config.xml"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;Depending on your setup, you might have to tweak this a bit. Most of the time, you are probably fine with just disabling compression for certain url patterns or content types. In my case, since I'm hosting behind &lt;a href="https://www.cloudflare.com" title="Cloudflare"&gt;Cloudflare&lt;/a&gt;, it didn't matter much - my content will be compressed by their CDN anyways, so I was safe to turn it off.&lt;/p&gt;
&lt;p&gt;Happy rewriting!&lt;/p&gt;</description>
      <pubDate>Wed, 04 Jul 2018 12:42:48 Z</pubDate>
      <a10:updated>2018-07-04T12:42:48Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1388</guid>
      <link>https://blog.dangl.me/archive/serving-localized-angular-single-page-applications-with-aspnet-core/</link>
      <category>Web Development</category>
      <title>Serving Localized Angular Single Page Applications with Asp.Net Core</title>
      <description>&lt;p&gt;I'm doing most of my web development with an ASP.NET Core backend and an Angular frontend these days, and I'm quite happy with how these two work together.&lt;/p&gt;
&lt;p&gt;ASP.NET Core serves both my API endpoints as well as the static files, so all I have to deploy is just a single website. Angular files are in this case served from the &lt;span class="Code"&gt;wwwroot/dist&lt;/span&gt; folder. This works fine as long as you only have to support a single language, but causes a bit of trouble as soon as you need internationalization, or i18n for short.&lt;/p&gt;
&lt;p&gt;With Angular, there's no possibility to switch languages at runtime. That's because so much of the templates is compiled internally when you do a production build. So when you need a multilanguage app, you're actually deploying two independent Angular apps and need some way to serve different language files at runtime. For a lot of sites, going with different domains, e.g. &lt;span class="Code"&gt;.com&lt;/span&gt; for English and &lt;span class="Code"&gt;.de&lt;/span&gt; for German, is a viable approach. But many projects require that the user can select a language, without having to change domains or paths. And who wants to see &lt;span class="Code"&gt;/de&lt;/span&gt; in their urls, anyways?&lt;/p&gt;
&lt;p&gt;As always, there's lots of solutions for how to solve this. The two most prominent ones are probably using a dedicated SPA controller that would return the correct entry point to your SPA, or simple re-route all not served requests to the SPA entries &lt;span class="Code"&gt;index.html&lt;/span&gt; at the end of your pipeline. I've chosen to do the latter.&lt;/p&gt;
&lt;h2&gt;Configuring Angular for Multilanguage Builds&lt;/h2&gt;
&lt;p&gt;This post isn't going to detail how to set up i18n in Angular, but here's a short recap: At first, you have to configure multiple configurations in your &lt;span class="Code"&gt;angular.json&lt;/span&gt;, one for each locale. Make sure that each one has a distinct &lt;span class="Code"&gt;deployUrl&lt;/span&gt; parameter that maps to where the static files will be put later, because that's going to be used as path for the injected references in &lt;span class="Code"&gt;index.html&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/70c01f40b2a2d49bbee58c3dffd7bad7.js?file=angular.json"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;Then, make sure to have build scripts that you run before publishing the app in &lt;span class="Code"&gt;project.json&lt;/span&gt;:&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/70c01f40b2a2d49bbee58c3dffd7bad7.js?file=package.json"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;h2&gt;Adding a Localized SPA Middleware to ASP.NET Core&lt;/h2&gt;
&lt;p&gt;To be able to serve different files based on a users locale, you have to implement something like &lt;span class="Code"&gt;IUserLanguageService&lt;/span&gt;:&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/70c01f40b2a2d49bbee58c3dffd7bad7.js?file=IUserLanguageService.cs"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;It's up to you how you implement it, but I've decided to either use a stored Cookie set by the Angular frontend (so I can have a language switcher in the app) or default to the &lt;span class="Code"&gt;Accept-Language&lt;/span&gt; http header. Make sure your &lt;span class="Code"&gt;UserLanguageService&lt;/span&gt; implements some default language as fallback, since not all clients will send the required header or have Cookies set.&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/70c01f40b2a2d49bbee58c3dffd7bad7.js?file=UserLanguageService.cs"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;Next, there needs to be some provider that can generate the different paths on disk to the localized files, like &lt;span class="Code"&gt;dist/en&lt;/span&gt; and &lt;span class="Code"&gt;dist/de&lt;/span&gt;:&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/70c01f40b2a2d49bbee58c3dffd7bad7.js?file=LocalizedSpaStaticFilePathProvider.cs"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;The &lt;span class="Code"&gt;LocalizedSpaStaticFilePathProvider&lt;/span&gt; simply builds the path to where each localized Angular app is stored.&lt;/p&gt;
&lt;p&gt;Now you have to wire this together, for example in an extension class:&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/70c01f40b2a2d49bbee58c3dffd7bad7.js?file=LocalizedSpaStaticFilesExtensions.cs"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;The &lt;span class="Code"&gt;LocalizedSpaStaticFilesExtensions&lt;/span&gt; configures the services required for our implementation of a localized SPA middleware. We're just providing it the list of &lt;span class="Code"&gt;availableLocales&lt;/span&gt;, so that the &lt;span class="Code"&gt;UserLanguageService&lt;/span&gt; won't return a locale we don't have a translation for. The &lt;span class="Code"&gt;spaRootPath&lt;/span&gt; parameter just indicates where, relative to &lt;span class="Code"&gt;wwwroot&lt;/span&gt;, we put all the localized builds.&lt;/p&gt;
&lt;p&gt;For the application builder, we define a middleware that reroutes all requests to the localized &lt;span class="Code"&gt;defaultFile&lt;/span&gt;, e.g. &lt;span class="Code"&gt;index.html&lt;/span&gt;, for the current user and then have the regular ASP.NET Core StaticFiles middleware handle it. It's important to note that the &lt;span class="Code"&gt;applicationBuilder.UseStaticFiles();&lt;/span&gt; call &lt;strong&gt;does not&lt;/strong&gt; replace the regular static files middleware, it's just being called a second time. You must put &lt;span&gt;&lt;span class="Code"&gt;UseLocalizedSpaStaticFiles()&lt;/span&gt; at the end of your request pipeline, because it alters all requests to your SPA entry point. That's required because your SPA most likely has routes of its own defined that your backend doesn't know, so you want to just return your SPA and let it handle client side routing.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Finally, configure everything in your &lt;span class="Code"&gt;Startup&lt;/span&gt; class:&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/70c01f40b2a2d49bbee58c3dffd7bad7.js?file=Startup.cs"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;&lt;span&gt;That's how you get a localized app!&lt;/span&gt;&lt;span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Happy translating!&lt;/span&gt;&lt;/p&gt;</description>
      <pubDate>Wed, 23 May 2018 16:49:05 Z</pubDate>
      <a10:updated>2018-05-23T16:49:05Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1384</guid>
      <link>https://blog.dangl.me/archive/simple-sorting-and-pagination-in-aspnet-core-with-lightquery/</link>
      <category>Web Development</category>
      <title>Simple Sorting and Pagination in ASP.NET Core with LightQuery</title>
      <description>&lt;p&gt;With &lt;a href="https://github.com/GeorgDangl/LightQuery" title="GitHub - GeorgDangl - LightQuery"&gt;LightQuery&lt;/a&gt;, I've written a really small yet powerful library that assists you in paging and sorting ASP.NET Core web apps. It's a great alternative if you're looking for a simple substitution for OData or similar, heavyweight frameworks that come with great functionality but usually require a bit of setup. Additionally, LightQuery comes with clients both written in C# for .NET and also for Angular 5+ applications.&lt;/p&gt;
&lt;p&gt;It's available both on &lt;a href="https://www.nuget.org/packages/LightQuery" title="NuGet.org - GeorgDangl - LightQuery"&gt;NuGet&lt;/a&gt; as well as &lt;a href="https://www.npmjs.com/package/ng-lightquery" title="npmjs.com - GeorgDangl - ng-lightquery"&gt;on npm&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Motivation&lt;/h2&gt;
&lt;p&gt;Some time ago, I was looking to implement pagination in an ASP.NET Core Web Api call. OData wasn't yet released for .NET Core (I think it still isn't?), and all the other solutions I found required quite a bit of setup. I didn't want to deal with complex setup scenarios and neither did I want to leak library code in my controller actions, for example by specifying custom arguments or requiring setup voodoo.&lt;/p&gt;
&lt;p&gt;All I wanted was some simple &lt;span class="Code"&gt;[LightQuery]&lt;/span&gt; attribute that I could add to any controller action and have it take care of sorting &amp;amp; pagination. So here's how you have to annotate a controller action in LightQuery:&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/e1e62268234e4d47c6480b659a6a02b0.js?file=Controller.cs"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;Just add the &lt;span class="Code"&gt;[LightQuery]&lt;/span&gt; attribute, everything else is handled by the library and optional.&lt;/p&gt;
&lt;p&gt;I'm using it extensively for typical, CRUD / data entry style apps, like showing thousands of users in a paged table layout. It works fine for such use cases, but it's nowhere near some feature monsters like OData.&lt;/p&gt;
&lt;blockquote&gt;&lt;strong&gt;Tip:&lt;/strong&gt; Use &lt;span class="Code"&gt;[AsyncLightQuery]&lt;/span&gt; if you're working with Entity Framework Core for async / await support.&lt;/blockquote&gt;
&lt;h2&gt;How Does it Work&lt;/h2&gt;
&lt;p&gt;LightQuery is purposely kept very simple. It's just a few lines and inherits from ASP.NET Cores &lt;span class="Code"&gt;ActionFilterAttribute&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;ASP.NET Core executes the attributes &lt;span class="Code"&gt;OnResultExecuting()&lt;/span&gt; (or &lt;span class="Code"&gt;OnResultExecutionAsync()&lt;/span&gt; with Entity Framework Core) and passes the current request context. It checks for query parameters like &lt;span class="Code"&gt;page&lt;/span&gt;, &lt;span class="Code"&gt;pageSize&lt;/span&gt; or &lt;span class="Code"&gt;sort&lt;/span&gt; in the request url. If there are any, or the attribute is set to always enforce pagination, it applies the query transformation to an &lt;span class="Code"&gt;ObjectResult.Value&lt;/span&gt; property on the response. If there's no &lt;span class="Code"&gt;ObjectResult&lt;/span&gt; returned by your controller action, or its &lt;span class="Code"&gt;Value&lt;/span&gt; is not of type &lt;span class="Code"&gt;IQueryable&lt;/span&gt;, nothing happens. &lt;a href="https://github.com/GeorgDangl/LightQuery/blob/dev/src/LightQuery/LightQueryAttribute.cs" title="GitHub - GeorgDangl - LightQuery - LightQueryAttribute.cs"&gt;Go check out the source&lt;/a&gt;!&lt;/p&gt;
&lt;h2&gt;Controlling Pagination &amp;amp; Sorting on the Client Side&lt;/h2&gt;
&lt;p&gt;For clients, it's just as easy to request paged results (and thus save bandwith and time).&lt;/p&gt;
&lt;p&gt;To paginate, send &lt;span class="Code"&gt;page&lt;/span&gt; and &lt;span class="Code"&gt;pageSize&lt;/span&gt; as url parameters in the request, like this:&lt;/p&gt;
&lt;p&gt;&lt;span class="Code"&gt;https://my-api.com/users?page=2&amp;amp;pageSize=3&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/e1e62268234e4d47c6480b659a6a02b0.js?file=ExampleResponse.json"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;There are clients both for .NET and Angular 5+ already available as prebuilt packages.&lt;/p&gt;
&lt;p&gt;If you further want to sort by properties, you can add the &lt;span class="Code"&gt;sort&lt;/span&gt; parameter and optionally specify &lt;span class="Code"&gt;desc&lt;/span&gt; for descending sort order, otherwise it defaults to ascending. If you specify a non-existent property, there'll be no sorting. The following request returns the users, sorted by descending &lt;span class="Code"&gt;email&lt;/span&gt; property:&lt;/p&gt;
&lt;p&gt;&lt;span class="Code"&gt;https://my-api.com/users?page=2&amp;amp;pageSize=3&amp;amp;sort=email desc&lt;/span&gt;&lt;/p&gt;
&lt;blockquote&gt;&lt;strong&gt;Tip:&lt;/strong&gt; Title casing is taken care of, so &lt;span class="Code"&gt;email&lt;/span&gt; works both for &lt;span class="Code"&gt;Email&lt;/span&gt; and &lt;span class="Code"&gt;email&lt;/span&gt; properties.&lt;/blockquote&gt;
&lt;p&gt;Do you want to know more? &lt;a href="https://github.com/GeorgDangl/LightQuery" title="GitHub - GeorgDangl - LightQuery"&gt;Head over to the GitHub repository&lt;/a&gt; to find more examples.&lt;/p&gt;
&lt;p&gt;Happy Paging!&lt;/p&gt;</description>
      <pubDate>Tue, 13 Mar 2018 22:49:28 Z</pubDate>
      <a10:updated>2018-03-13T22:49:28Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1369</guid>
      <link>https://blog.dangl.me/archive/adding-custom-claims-when-logging-in-with-aspnet-core-identity-cookie/</link>
      <category>Web Development</category>
      <title>Adding Custom Claims when Logging In with Asp.Net Core Identity Cookie</title>
      <description>&lt;p&gt;When working with Asp.Net Core applications, Asp.Net Core Identity is a great and easy to use choice for managing app authentication and authorization. By default, logins happen via an application cookie. This means that on a successful login, a cookie is set in the users browser that can be verified by the server on each request, without requiring database roundtrips. It also stores a few claims (pieces of information about the logged in user) directly in the cookie, such as the username or roles. You can even easily define your own claims, and the default implementation will automatically store this information in the cookie as well, allowing you to access it in every request.&lt;/p&gt;
&lt;p&gt;However, sometimes you don't want to store a claim as persistent in the database, but still attach some information to a login sessions or context. This could be for claims that are somehow stored not as regular claims, like a team the user is associated with, or even data generated on the fly, like if the login happened on a Tuesday. If you take a look at Asp.Net Core Identities &lt;span class="Code"&gt;SignInManager&lt;/span&gt;s &lt;a rel="noopener noreferrer" href="https://github.com/aspnet/Identity/blob/eb3ff7fc32dbfff65a1ba6dfdca16487e0f6fc41/src/Microsoft.AspNetCore.Identity/SignInManager.cs#L186-L197" target="_blank" title="GitHub - Asp.Net Core Identity - SignInManager"&gt;source&lt;/a&gt;, you see it just generates a &lt;span class="Code"&gt;ClaimsPrincipal&lt;/span&gt; for the user and then performs the sign in action (generating the cookie and appending it to the http response as a &lt;span class="Code"&gt;Set-Cookie&lt;/span&gt; header). This means, if you want to intercept that action and append more claims to the generated principal, you can do that either by providing your own &lt;span&gt;&lt;span class="Code"&gt;ClaimsFactory&lt;/span&gt; or, as what I'll show you, just provide a custom &lt;span class="Code"&gt;SignInHandler&lt;/span&gt;.&lt;/span&gt;&lt;/p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/d82f33488745c37f913caff325a7f464.js?file=CustomClaimsCookieSignInHelper.cs"&gt;&lt;/script&gt;
&lt;p&gt;&lt;span&gt;The &lt;span class="Code"&gt;CustomClaimsCookieSignInHelper&amp;lt;TIdentityUser&amp;gt;&lt;/span&gt; provides just a wrapping mechanism around the core sign in functionality. It's easy to use in your &lt;span class="Code"&gt;AccountController&lt;/span&gt;s login action:&lt;/span&gt;&lt;/p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/d82f33488745c37f913caff325a7f464.js?file=AccountController.cs"&gt;&lt;/script&gt;
&lt;p&gt;To add custom claims, simply pass them as arguments to the &lt;span class="Code"&gt;SignInHandler.SignInUserAsync()&lt;/span&gt; method. If you want to go further down that route, you should check out &lt;a rel="noopener noreferrer" href="https://github.com/aspnet/Identity/blob/eb3ff7fc32dbfff65a1ba6dfdca16487e0f6fc41/src/Microsoft.Extensions.Identity.Core/UserClaimsPrincipalFactory.cs" target="_blank" title="GitHub - Asp.Net Core Identity - UserClaimsPrincipalFactory"&gt;the official implementation&lt;/a&gt; for the &lt;span class="Code"&gt;UserClaimsPrincipalFactory&lt;/span&gt;.&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Merry Christmas and happy authenticating!&lt;/span&gt;&lt;/p&gt;</description>
      <pubDate>Sun, 24 Dec 2017 12:25:10 Z</pubDate>
      <a10:updated>2017-12-24T12:25:10Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1368</guid>
      <link>https://blog.dangl.me/archive/chasing-a-bug-when-working-with-an-rxjs-observable/</link>
      <category>Web Development</category>
      <title>Chasing a Bug when Working with an RxJS Observable</title>
      <description>&lt;p&gt;I'm the author of &lt;a rel="noopener noreferrer" href="https://github.com/GeorgDangl/LightQuery" target="_blank" title="GitHub - GeorgDangl - LightQuery"&gt;LightQuery&lt;/a&gt;, a library that offers simple pagination and sorting functionalities for Asp.Net Core web services. I've also created client libraries to consume these services, both for .Net and TypeScript with Angular. It's useful for these ever-repeating tables of data that you find in almost any app and integrates nicely with popular table and pagination modules, such as from Angular Material or ngx-bootstrap.&lt;/p&gt;
&lt;p&gt;Both client apps provide a generic implementation of &lt;span class="Code"&gt;PaginationBaseService&amp;lt;T&amp;gt;&lt;/span&gt;, which handle all the sorting and paging of list resources. In one of my apps, I've extended this service with methods like &lt;span class="Code"&gt;getElementById(id: string)&lt;/span&gt;. They make use of the service caching the last retrieved pagination result from the server. If the requested item is locally available, I can directly return a resolved Promise instead of requerying over http. This is as simple as in the following snippet:&lt;/p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/730faceaa465fcf50f84f0d9471a2066.js?file=extended.service.ts"&gt;&lt;/script&gt;
&lt;p&gt;There's a detail view component as part of the app. You select an item from a list or table, then you can view it in detail. If desired, you can toggle an editor mode to modify the record. CRUD 101, you've written that yourself often enough. The detail component watches the editor. If it's being informed that the entity was updated, it forces the pagination service to update it's current record set and then follow on with a retrieval of the item by its &lt;span class="Code"&gt;id&lt;/span&gt;.&lt;/p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/730faceaa465fcf50f84f0d9471a2066.js?file=calling.component.ts"&gt;&lt;/script&gt;
&lt;p&gt;Now that implementation is not very efficient. When I do update a single record, it doesn't use the actual response from the server but just requeries the whole list again. But it worked as a first iteration. Or did it?&lt;/p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/730faceaa465fcf50f84f0d9471a2066.js?file=pagination-base.service.ts"&gt;&lt;/script&gt;
&lt;p&gt;The snippet above is from the service implementation. It's of interest that the local cache variable &lt;span class="Code"&gt;lastPaginationResult&lt;/span&gt; is only updated after the Observable has emitted the latest result. And that's the catch. I didn't pay attention to the order of execution for subscribed actions to Observables, but I should have. As soon as an Observable emits a value, it's subscriber actions are invoked. Meaning that there's quite a lot of stuff happening between lines &lt;span class="Code"&gt;12&lt;/span&gt; and &lt;span class="Code"&gt;13&lt;/span&gt;. Looking back at the &lt;span class="Code"&gt;subscribe()&lt;/span&gt; in the main component: It's querying for a single element as soon as the &lt;span class="Code"&gt;paginationResult&lt;/span&gt; is updated. Since an element with this &lt;span class="Code"&gt;id&lt;/span&gt; is still in the (stale!) cache, there's no asynchronous actions being invoked. The execution happens &lt;strong&gt;directly&lt;/strong&gt; in a single chain, deterministic without interruption. And &lt;strong&gt;before updating the services local cache&lt;/strong&gt;. I've since created &lt;a rel="noopener noreferrer" href="https://github.com/GeorgDangl/LightQuery/commit/a4e6af70246b35d005c60671e8d10faa6b119ec5#diff-3b39c7288dddd6934e6d63af768f1fe5" target="_blank" title="GitHub - GeorgDangl - LightQuery Test"&gt;a unit test to catch that behavior&lt;/a&gt;, and the fix was as easy as simply &lt;a rel="noopener noreferrer" href="https://gist.github.com/GeorgDangl/730faceaa465fcf50f84f0d9471a2066#file-fixed-pagination-base-service-ts" target="_blank" title="GitHub - GeorgDangl - LightQueryFix"&gt;changing the order of two statements&lt;/a&gt; in my code.&lt;/p&gt;
&lt;p&gt;This was a lucky catch for me, the bug was subtle but interesting, easy to diagnose and fix, yet it alerted me to pay closer attention when working with reactive patterns. The service was later refactored to use the server response to the &lt;span class="Code"&gt;PUT&lt;/span&gt; request to directly refresh its cache and list without additional network roundtrips. If I had done that right from the start, I wouldn't have caught this subtle bug. And I would also have continued to use reactive patterns wrong.&lt;/p&gt;
&lt;p&gt;Happy Debugging and Merry Christmas!&lt;/p&gt;</description>
      <pubDate>Thu, 21 Dec 2017 19:55:46 Z</pubDate>
      <a10:updated>2017-12-21T19:55:46Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1366</guid>
      <link>https://blog.dangl.me/archive/attention-when-working-with-the-aspnet-core-testhost-and-its-httpmessagehandler/</link>
      <category>Web Development</category>
      <title>Attention when working with the Asp.Net Core TestHost and its HttpMessageHandler</title>
      <description>&lt;p&gt;I'm a big fan of the &lt;a rel="noopener noreferrer" href="https://www.nuget.org/packages/Microsoft.AspNetCore.TestHost" target="_blank" title="NuGet - AspNetCore.TestHost"&gt;Asp.Net Core TestHost package&lt;/a&gt;, which allows you to easily write integration tests of your applications without the need to do actual network calls.&lt;/p&gt;
&lt;p&gt;&lt;span class="Code"&gt;TestServer&lt;/span&gt;s feature a nice method &lt;span class="Code"&gt;CreateClient()&lt;/span&gt; that returns an &lt;span class="Code"&gt;HttpClient&lt;/span&gt; instance which will interface with the &lt;span class="Code"&gt;TestServer&lt;/span&gt; but not make any actual network calls. So basically, to perform an integration test against one of your endpoints, you treat the client as you would treat a regular one. This can also be used where you have dependencies in your code that themselves need to call your server, for example a &lt;a rel="noopener noreferrer" href="https://jwt.io" target="_blank" title="jwt.io"&gt;Json Web Token&lt;/a&gt; authority validation utility.&lt;/p&gt;
&lt;p&gt;For these cases, you can supply your own &lt;span class="Code"&gt;HttpMessageHandler&lt;/span&gt;:&lt;/p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/0e128bfb3fff96e51a0bbc89ea331e89.js?file=errorenous-setup.cs"&gt;&lt;/script&gt;
&lt;p&gt;Did you spot the error?&lt;/p&gt;
&lt;p&gt;Yeah, i actually made the handler to delegate it's call to a new &lt;span class="Code"&gt;HttpClient&lt;/span&gt;. This means a request travels like this: &lt;span class="Code"&gt;HttpClient&lt;/span&gt; -&amp;gt; &lt;span class="Code"&gt;IntegrationTestsHttpMessageHandler&lt;/span&gt; -&amp;gt; &lt;span class="Code"&gt;HttpClient&lt;/span&gt;. If you're familiar with how request are handled internally, you've noticed that the first &lt;span class="Code"&gt;HttpClient&lt;/span&gt; marks the request as sent and the second one then refuses to send the message again with a nice &lt;span class="Code"&gt;System.InvalidOperationException: Cannot send the same request message multiple times&lt;/span&gt;. Luckily, the &lt;span class="Code"&gt;TestServer&lt;/span&gt; has direct access to a &lt;span class="Code"&gt;HttpMessageHandler&lt;/span&gt;:&lt;/p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/0e128bfb3fff96e51a0bbc89ea331e89.js?file=correct-setup.cs"&gt;&lt;/script&gt;
&lt;p&gt;I've spent the better part of an evening figuring this out...&lt;/p&gt;
&lt;p&gt;Happy testing!&lt;/p&gt;</description>
      <pubDate>Tue, 21 Nov 2017 23:39:22 Z</pubDate>
      <a10:updated>2017-11-21T23:39:22Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1364</guid>
      <link>https://blog.dangl.me/archive/use-any-authentication-handler-for-all-actions-in-aspnet-core-20/</link>
      <category>Web Development</category>
      <title>Use Any Authentication Handler for all Actions in Asp.Net Core 2.0</title>
      <description>&lt;p&gt;In Single Page Applications, it's common to use &lt;span class="Code"&gt;Bearer&lt;/span&gt; authentication, for example with OAuth2 integration, to make the API available to client applications. While this can also be used on the web frontend, I enjoy the simplicity of the Cookie based authentication that's the default for Asp.Net Core Identity projects.&lt;/p&gt;
&lt;p&gt;Unfortunately, the latest release of Asp.Net Core 2.0 introduced a behavior that's different: There is only one default authentication scheme, others are only invoked and challenged when it's further specified, for example with an &lt;span class="Code"&gt;[Authorize]&lt;/span&gt; attribute or a policy. Shawn Wildermuth wrote &lt;a rel="noopener noreferrer" href="https://wildermuth.com/2017/08/19/Two-AuthorizationSchemes-in-ASP-NET-Core-2" target="_blank" title="Two AuthorizationSchemes in ASP.NET Core 2"&gt;a good post&lt;/a&gt; about that. I didn't want to clutter my code with annotations everywhere, and I also wanted to use multiple authentication schemes on non-authorized controllers to get user info, no matter if the request is done via Cookie or Bearer authentication.&lt;/p&gt;
&lt;p&gt;Luckily, you can get the old behavior back: By defining a global catch-all policy that specifies all supported authentication schemes. It's simple to set up:&lt;/p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/dffdcd69090cc939575a45cf91d18553.js?file=configure-identity.cs"&gt;&lt;/script&gt;
&lt;p&gt;First, you configure all authentication methods in your Startups &lt;span class="Code"&gt;ConfigureServices&lt;/span&gt; method, in the example it's the regular Asp.Net Core Identity cookie authentication and &lt;a rel="noopener noreferrer" href="https://github.com/IdentityServer/IdentityServer4" target="_blank" title="GitHub - IdentityServer4"&gt;IdentityServer4&lt;/a&gt;s OAuth2 functionality.&lt;/p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/dffdcd69090cc939575a45cf91d18553.js?file=configure-policy.cs"&gt;&lt;/script&gt;
&lt;p&gt;In the configuration for MVC,there's a &lt;span&gt;&lt;span class="Code"&gt;defaultPolicy&lt;/span&gt; which specifies all authentication schemes used in your app. Since policies mandate at least one requirement, we'll add an assertion that simply returns true for all requests: &lt;span class="Code"&gt;.RequireAssertion(c =&amp;gt; &lt;span class="pl-c1"&gt;true&lt;/span&gt;)&lt;/span&gt;. The effect of the policy is now that it doesn't enforce authentication, but tries to challenge all schemes. So without further configuration, your actions should now make use of either Cookie or Bearer authentication. &lt;/span&gt;&lt;span&gt;If required, the policy can be further tweaked to define exceptions where it's not applicable.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Happy authenticating!&lt;/p&gt;</description>
      <pubDate>Wed, 08 Nov 2017 22:03:50 Z</pubDate>
      <a10:updated>2017-11-08T22:03:50Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1355</guid>
      <link>https://blog.dangl.me/archive/blank-screen-after-login-to-umbraco-backoffice/</link>
      <category>Web Development</category>
      <title>Blank Screen after Login to Umbraco Backoffice</title>
      <description>&lt;p&gt;For the last two years, I've been using &lt;a rel="noopener noreferrer" href="https://umbraco.com" target="_blank" title="Umbraco"&gt;Umbraco CMS&lt;/a&gt; for a few sites. It's a great content management system, giving you much freedom and easy extensibility while still maintaining a &lt;em&gt;reasonably&lt;/em&gt; learning curve. It's probably not suited for typical 1-click-end-user-install scenarios, but it integrates really well in a .Net / Microsoft technologies stack with source control and continuous integration.&lt;/p&gt;
&lt;p&gt;Today, however, I wanted to log in to the backend of one site to change something. It didn't work. The login was successful, but then I only got 401 responses from the server, rendering only a blank, white screen instead of the expected Backoffice. Another site, the same problem. Every Umbraco site on that server showed the same symptoms. The front ends were rendering just fine, with everything working as expected, but I could not access the administration section of any of them. I tried quite a few things, from different browsers to different devices to different ISPs, but the problem persisted. Search results for this issue were not particularly helpful, most being outdated and the bugs been fixed since a few versions ago. The logs were no sources of wisdom either, just showing a lot of successful login attempts without follow up actions or failures. Nothing had been changed on the sites, so I didn't really suspect it to be an issue with Umbraco anyway, and I went on to check the server.&lt;/p&gt;
&lt;p&gt;The Let's Encrypt extension did update two certificates in IIS that day, but that's happened before and shouldn't cause any problems. By chance, while being remote on the server, I noticed that &lt;strong&gt;the servers time was off&lt;/strong&gt;. A good two hours. I fixed the time, tried to log in and - success!&lt;/p&gt;
&lt;p&gt;Maybe I can save you some time digging through Umbraco issues when all you should do is check your servers time.&lt;/p&gt;
&lt;p&gt;Happy logging in!&lt;/p&gt;</description>
      <pubDate>Tue, 17 Oct 2017 21:10:52 Z</pubDate>
      <a10:updated>2017-10-17T21:10:52Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1277</guid>
      <link>https://blog.dangl.me/archive/using-the-stackexchange-miniprofiler-with-an-angular-single-page-application/</link>
      <category>Web Development</category>
      <title>Using the StackExchange MiniProfiler with an Angular Single Page Application</title>
      <description>&lt;p&gt;Profiling your application is important. While optimization is rarely the highest priority, you should at least have an idea of what your computing resources are being spent on. I've found the &lt;a rel="noopener noreferrer" href="http://miniprofiler.com" target="_blank" title="MiniProfiler Homepage"&gt;MiniProfiler&lt;/a&gt;, developed by the StackExchange team and extensively used at Stack Overflow, to be a great tool for that.&lt;/p&gt;
&lt;p&gt;I love it mostly for two things:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;You get an idea of how long each step of your requests take&lt;/li&gt;
&lt;li&gt;It profiles and analyzes your SQL calls. This is great for finding slow queries and identifying where you have N+1 problems&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The &lt;a rel="noopener noreferrer" href="http://miniprofiler.com/dotnet/AspDotNetCore" target="_blank" title="MiniProfiler Asp.Net Core Setup"&gt;server side configuration&lt;/a&gt; doesn't differ when you're designing a Single Page Application (SPA), but the (current) client side snippet does not yet support Angular 2, Angular 4 or newer frameworks. Whenever you do a profiled request, MiniProfiler attaches a &lt;span&gt;&lt;span class="Code"&gt;x-miniprofiler-ids&lt;/span&gt; Http header with ids to relate the profiling results. Now your client side code should request them and display them for you, but this doesn't integrate yet in Angular without implementing a custom hook in Angulars &lt;span class="Code"&gt;Http&lt;/span&gt; class.&lt;/span&gt;&lt;/p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/2807d11b367540e1de5629502289f5a8.js?file=mini-profiler-http.ts"&gt;&lt;/script&gt;
&lt;p&gt;&lt;span&gt;The &lt;span class="pl-en"&gt;&lt;span class="Code"&gt;MiniProfilerHttp&lt;/span&gt; class just extends Angulars &lt;span class="Code"&gt;Http&lt;/span&gt; provider. It's checking every response for profiler ids and, if any are found, requests the results.&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/2807d11b367540e1de5629502289f5a8.js?file=app.module.ts"&gt;&lt;/script&gt;
&lt;p&gt;&lt;span&gt;You have to alter your applications &lt;span class="Code"&gt;NgModule&lt;/span&gt; to provide the derived class instead of Angulars &lt;span class="Code"&gt;Http&lt;/span&gt; provider.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;Now, your applications API requests should make MiniProfiler display you the results without having to do a full refresh of the site:&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;&lt;img id="__mcenew" style="display: block; margin-left: auto; margin-right: auto;" src="https://blog.dangl.me/media/1132/example.png" alt="MiniProfiler Results in an Angular SPA" data-udi="umb://media/eaace9aedead44d4b079793f81ed8e24" /&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span&gt;If you've configured the backend correctly and added the MiniProfiler includes to your website, you'll see the results being displayed in the top left of your page.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Happy profiling!&lt;/p&gt;</description>
      <pubDate>Thu, 27 Jul 2017 10:49:57 Z</pubDate>
      <a10:updated>2017-07-27T10:49:57Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1276</guid>
      <link>https://blog.dangl.me/archive/validating-usernames-in-an-angular-frontend-with-aspnet-core-identity-on-the-server/</link>
      <category>Web Development</category>
      <title>Validating Usernames in an Angular Frontend with Asp.Net Core Identity on the Server</title>
      <description>&lt;p&gt;In Angular, you've got the built-in &lt;span class="Code"&gt;[pattern]&lt;/span&gt; form validation directive that makes it easy to validate an input with a regular expression. Today, I wanted to check usernames consistently across my app and I found out that the Asp.Net Core Identity backend uses just a long string which contains all allowed characters. This could look like this: &lt;span class="Code"&gt;"abcACB123._"&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;It's configured this way in your &lt;span class="Code"&gt;Startup&lt;/span&gt;s &lt;span class="Code"&gt;ConfigureServices&lt;/span&gt; method:&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/ac53a94ccd83e3b52dd0bdf8501f09ff.js?file=Startup.cs"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;That's not regex, so you've got two options: convert it into regex or create a custom directive that validates consistently with your backend. I've chosen option two, and want to share how quick that was:&lt;/p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/ac53a94ccd83e3b52dd0bdf8501f09ff.js?file=validate-username.directive.ts"&gt;&lt;/script&gt;
&lt;p&gt;The &lt;span class="Code"&gt;ValidateUsernameDirective&lt;/span&gt; simply checks the input string letter-by-letter for illegal chars. In template forms, you use it just like this:&lt;/p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/ac53a94ccd83e3b52dd0bdf8501f09ff.js?file=example.html"&gt;&lt;/script&gt;
&lt;p&gt;Happy validating!&lt;/p&gt;</description>
      <pubDate>Wed, 05 Jul 2017 22:06:55 Z</pubDate>
      <a10:updated>2017-07-05T22:06:55Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1274</guid>
      <link>https://blog.dangl.me/archive/mocking-an-aspnet-core-httpclient-for-unit-tests-with-moq/</link>
      <category>Web Development</category>
      <title>Mocking an Asp.Net Core HttpClient for Unit Tests with Moq</title>
      <description>&lt;p&gt;When you design services around Http requests, you should really just &lt;a rel="noopener noreferrer" href="https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/" target="_blank" title="ASP.NET Monsters - YOU'RE USING HTTPCLIENT WRONG AND IT IS DESTABILIZING YOUR SOFTWARE"&gt;inject your HttpClient as a dependency&lt;/a&gt; instead of wrapping it in a &lt;span class="Code"&gt;using&lt;/span&gt; statement in-place. This has the nice effect of making your code both easier to maintain and test. While doing a project recently, I decided to give &lt;a rel="noopener noreferrer" href="https://github.com/moq/moq" target="_blank" title="GitHub - moq/moq"&gt;Moq&lt;/a&gt; a try and use it to generate a &lt;span class="Code"&gt;HttpMessageHandler&lt;/span&gt; &lt;span&gt;(that's the class the &lt;span class="Code"&gt;HttpClient&lt;/span&gt; uses internally for sending the network requests)&lt;/span&gt; for the &lt;span class="Code"&gt;HttpClient&lt;/span&gt; instead of providing my own &lt;span class="Code"&gt;HttpClient&lt;/span&gt; implementation. It's a really awesome mocking framework, but it took me a bit to set it up correctly. That's why I hope this snippet might save some of you a few minutes:&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/c0a85589616cf3ddffff054ee7cb585d.js"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;Happy mocking!&lt;/p&gt;</description>
      <pubDate>Sat, 03 Jun 2017 12:08:48 Z</pubDate>
      <a10:updated>2017-06-03T12:08:48Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1248</guid>
      <link>https://blog.dangl.me/archive/http-basic-authentication-in-aspnet-core-projects/</link>
      <category>Web Development</category>
      <title>Http Basic Authentication in Asp.Net Core Projects</title>
      <description>&lt;p&gt;There are many different ways how requests to an Asp.Net Core web application can be authenticated. &lt;a href="https://github.com/aspnet/Identity" target="_blank" title="GitHub - Asp.Net Core Identity"&gt;Asp.Net Core Identity&lt;/a&gt; offers a great built in identity provider with some options for authentication, but there's no built in support for Http Basic authentication. The &lt;a href="https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/basic-authentication" target="_blank" title="Basic Authentication in ASP.NET Web API"&gt;Microsoft docs for the old Web Api&lt;/a&gt; framework have a bit of background information about the disadvantages of Http Basic Authentication, especially that credentials are being sent &lt;strong&gt;with every request&lt;/strong&gt;. Generally, it's not a great idea to support it, but unfortunately, you can't always enforce it when there are dependent services of your application. To support the Http Basic Authentication scheme, you've got to insert a small middleware in your app that validates &lt;span class="Code"&gt;Authorization&lt;/span&gt; headers, which can be done with the following code. I've split it up into a few classes to be more readable and easy to test, but here you go:&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/70dca6188e351496145e83f2f76b2385.js?file=BasicAuthenticationMiddleware.cs"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;The &lt;span class="Code"&gt;BasicAuthenticationMiddleware&lt;/span&gt; checks if there's already an authenticated user for the request and if not, checks for Http Basic Authentication and tries to set the user identity for this request.&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/70dca6188e351496145e83f2f76b2385.js?file=BasicAuthenticationHeaderValue.cs"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;Http Basic headers are, essentially, passed as &lt;span class="Code"&gt;Base64("Username":"Password")&lt;/span&gt;. &lt;span class="Code"&gt;BasicAuthenticationHeaderValue&lt;/span&gt; decodes that.&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/70dca6188e351496145e83f2f76b2385.js?file=BasicAuthenticationSignInManager.cs"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;A wrapper to perform the actual sign in action for the user. It's not persisting the login via, for example, a cookie.&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/70dca6188e351496145e83f2f76b2385.js?file=MiddlewareExtensions.cs"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;script src="https://gist.github.com/GeorgDangl/70dca6188e351496145e83f2f76b2385.js?file=Startup.cs"&gt;&lt;/script&gt;
&lt;/p&gt;
&lt;p&gt;The &lt;span class="Code"&gt;MiddlewareExtensions&lt;/span&gt; just give you a nicer syntax to add the middleware to your &lt;span class="Code"&gt;Startup&lt;/span&gt; class.&lt;/p&gt;
&lt;p&gt;Just remember that when using this, &lt;strong&gt;there is absolutely no way you can use unencrypted traffic&lt;/strong&gt;! While unencrypted login pages themselves are bad enough (just ask &lt;a href="https://www.bleepingcomputer.com/news/security/developer-complains-firefox-labels-his-site-as-insecure-hilarity-ensues/" target="_blank" title="Developer Complains Firefox Labels His Site as Insecure, Hilarity Ensues"&gt;devGeorge&lt;/a&gt;), &lt;strong&gt;Http Basic sends the username and password with every request&lt;/strong&gt;. This makes eavesdropping so much more likely since &lt;strong&gt;any&lt;/strong&gt; intercepted request now contains your full login data. Just use &lt;a data-id="1235" href="/archive/grabbing-a-lets-encrypt-certificate-with-umbraco/" target="_blank" title="Grabbing a Let's Encrypt Certificate with Umbraco"&gt;Let's Encrypt&lt;/a&gt;. While you're at it, use it everywhere. Use it for your staging environment. Use it for static pages hosting demos. Really, &lt;strong&gt;use encryption&lt;/strong&gt;! Make the lock 🔒 in the browser bar your minimum requirement for every website. And educate your users to stop requiring Http Basic.&lt;/p&gt;
&lt;p&gt;Otherwise, happy authenticating!&lt;/p&gt;</description>
      <pubDate>Thu, 23 Mar 2017 13:31:17 Z</pubDate>
      <a10:updated>2017-03-23T13:31:17Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1244</guid>
      <link>https://blog.dangl.me/archive/netcoreheroes-angular2-with-net-core-in-visual-studio-2015-part-vi/</link>
      <category>Web Development</category>
      <title>NetCoreHeroes: Angular 2 with .Net Core in Visual Studio 2015, Part VI</title>
      <description>&lt;p&gt;&lt;strong&gt;The source code for this project is &lt;a rel="noopener noreferrer" href="https://github.com/GeorgDangl/NetCoreHeroes" target="_blank" title="GitHub - Georg Dangl - NetCoreHeroes"&gt;available at GitHub&lt;/a&gt; and &lt;a rel="noopener noreferrer" href="http://netcoreheroes.dangl.me" target="_blank" title="NetCoreHeroes Live Demo"&gt;here's a live example&lt;/a&gt; of the website.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;While the first five parts of the tutorial cover everything from setting up the development environment to finally deploying a unit-tested app, this part will briefly describe how an app that uses system.js for client side module loading can be set up to use &lt;a rel="noopener noreferrer" href="https://webpack.github.io" target="_blank" title="webpack"&gt;webpack&lt;/a&gt;. The steps I'll be describing here will work nicely in Visual Studio for a great development experience. &lt;a rel="noopener noreferrer" href="https://github.com/GeorgDangl/NetCoreHeroes/commit/bc1a15d2dc81c9e228e21dcf8b8ee515f1878a72" target="_blank" title="GitHub - GeorgDangl - NetCoreHeroes - Webpack merge commit"&gt;This commit&lt;/a&gt; covers the required steps for the demo project.&lt;/p&gt;
&lt;h2&gt;What's a module loader used for?&lt;/h2&gt;
&lt;p&gt;Apps that are written in JavaScript (or TypeScript, Coffescript...) are getting ever more complex. For this, just like in traditional object oriented frameworks like Java and the .Net system, using, referencing and managing module dependencies is becoming really important and quite hard to do by hand. Small apps might get away with just a few source files and then just merging them together (or even just loading them in the correct order), but this is simply too tedious and error prone for rich applications. Here come module bundlers into play. Basically, you give them your applications entry point (something like a &lt;span class="Code"&gt;main.js&lt;/span&gt; file) and a bit of configuration and they'll take care of dynamic loading of dependencies or even bundling.&lt;/p&gt;
&lt;h2&gt;Why prefer webpack over system.js?&lt;/h2&gt;
&lt;p&gt;webpack does, as it's name implies, pack your app for the web. This means you'll generate one or a few bundle files that are then loaded in the browser. In contrast, system.js might potentially load dozens of different JavaScript files from the server if you've got a lot of components. So while system.js is easier to set up, the webpack approach offers a lot of ways to optimize size and speed of your application. Since usual browser configurations do not allow for more than 5 concurrent requests to the same domain, loading many small files initially just takes a whole lot longer. Finally, webpack offers features like &lt;a rel="noopener noreferrer" href="https://webpack.github.io/docs/hot-module-replacement.html" target="_blank" title="webpack Hot Module Replacement"&gt;Hot Module Replacement&lt;/a&gt; which makes changes in your source code almost instantly appear in your debug sessions browser window.&lt;/p&gt;
&lt;h2&gt;npm dependencies in package.json&lt;/h2&gt;
&lt;script src="https://gist.github.com/GeorgDangl/eb0846eadea01752aa9bef0e0d40d503.js?file=package.json"&gt;&lt;/script&gt;
&lt;p&gt;Mainly &lt;span class="Code"&gt;webpack&lt;/span&gt; and loaders for different file types are the novelty here. Note that &lt;span class="Code"&gt;systemjs&lt;/span&gt; is still around. I'm using that for the unit tests of my TypeScript code with Chutzpah and found it way simpler and faster to configure than webpack, so I'll still have it as a &lt;span class="Code"&gt;devDependency&lt;/span&gt;.&lt;/p&gt;
&lt;h2&gt;webpack configuration for your own modules&lt;/h2&gt;
&lt;script src="https://gist.github.com/GeorgDangl/eb0846eadea01752aa9bef0e0d40d503.js?file=webpack.config.js"&gt;&lt;/script&gt;
&lt;p&gt;That's a very basic configuration for webpack. What's happening is that webpack enters the file defined in &lt;span class="Code"&gt;entry&lt;/span&gt; (on line 8) and from there on walks the tree of your dependencies to build your bundle. On line 16, you see that these two loaders are chained: &lt;span class="Code"&gt;[&lt;span class="pl-s"&gt;&lt;span class="pl-pds"&gt;'&lt;/span&gt;awesome-typescript-loader?silent=true&lt;span class="pl-pds"&gt;'&lt;/span&gt;&lt;/span&gt;, &lt;span class="pl-s"&gt;&lt;span class="pl-pds"&gt;'&lt;/span&gt;angular2-template-loader&lt;span class="pl-pds"&gt;'&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span&gt;&lt;span class="Code"&gt;]&lt;/span&gt;, meaning that every matching file is first fed into the &lt;span class="Code"&gt;angular2-template-loader&lt;/span&gt; and then into the &lt;span class="Code"&gt;awesome-typescript-loader&lt;/span&gt;. That's a really cool feature here, because the first loader will replace the template and style urls of your Angular 2 components with &lt;span class="Code"&gt;require()&lt;/span&gt; statements so they're being inlined in the generated bundle, massively lowering requests to the server in production! For this to work though, you must set the resolution of &lt;span class="Code"&gt;.ts&lt;/span&gt; file extensions before &lt;span class="Code"&gt;.js&lt;/span&gt; files on line 6, otherwise webpack will just use the (already compiled) JavaScript file and happily ignore the loaders you've specified for TypeScript.&lt;/span&gt;&lt;/p&gt;
&lt;h2&gt;webpack configuration for dependencies&lt;/h2&gt;
&lt;script src="https://gist.github.com/GeorgDangl/eb0846eadea01752aa9bef0e0d40d503.js?file=webpack.config.vendor.js"&gt;&lt;/script&gt;
&lt;p&gt;There's not much to see here. You'll just have to specify all the modules that change not as frequent as your custom code in a separate bundle to save on compilation time and possible bandwidth if you're iterating fast while your app is already in use. Line 28 contains the configuration of the Dll plugin, which itself is referenced by the bundle of your code.&lt;/p&gt;
&lt;h2&gt;App entry point&lt;/h2&gt;
&lt;script src="https://gist.github.com/GeorgDangl/eb0846eadea01752aa9bef0e0d40d503.js?file=main.ts"&gt;&lt;/script&gt;
&lt;p&gt;Since &lt;span class="Code"&gt;zone.js&lt;/span&gt; and &lt;span class="Code"&gt;reflect-metadata&lt;/span&gt; will no longer be loaded separately from the browser, you'll need to import them at the entry point of your app so they're available. Additionally, I'm using the style-loader to load global CSS into the app. The style loader will insert the content of the file at runtime in the documents &lt;span class="Code"&gt;&amp;lt;head&amp;gt;&lt;/span&gt; section, making it available for the whole app.&lt;/p&gt;
&lt;h2&gt;Updating your Asp.Net Core view&lt;/h2&gt;
&lt;script src="https://gist.github.com/GeorgDangl/eb0846eadea01752aa9bef0e0d40d503.js?file=Index.cshtml"&gt;&lt;/script&gt;
&lt;p&gt;Finally, you can remove all the single bundles and just include two scripts in your view: &lt;span class="Code"&gt;vendor.js&lt;/span&gt; and &lt;span class="Code"&gt;main.js&lt;/span&gt;. Just make sure to either defer loading them or put them below your &lt;span class="Code"&gt;&amp;lt;my-app&amp;gt;&lt;/span&gt; tag, otherwise you'll get an error from Angular 2 telling you that it can't find the app root element.&lt;/p&gt;
&lt;h2&gt;Result&lt;/h2&gt;
&lt;p&gt;Here's how much faster (and smaller!) the example app becomes after using webpack:&lt;/p&gt;
&lt;p&gt;&lt;img id="__mcenew" style="display: block; margin-left: auto; margin-right: auto;" src="https://blog.dangl.me/media/1110/webpackbundleloadtimes.png" alt="Webpack File Response Times in the Browser" data-id="1247"&gt;&lt;/p&gt;
&lt;p&gt;Happy bundling!&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Update 28.05.2017:&lt;/strong&gt;&lt;span&gt; Updated Angular to 4.1.3 and Asp.Net Core to 1.1.2. Switched to Visual Studio 2017 csproj format&lt;/span&gt;&lt;/p&gt;</description>
      <pubDate>Tue, 21 Feb 2017 21:25:20 Z</pubDate>
      <a10:updated>2017-02-21T21:25:20Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1236</guid>
      <link>https://blog.dangl.me/archive/signing-in-users-for-integration-testing-with-the-asp-net-core-testhost/</link>
      <category>Web Development</category>
      <title>Signing in Users for Integration Testing with the Asp.Net Core TestHost</title>
      <description>&lt;p&gt;When developing Asp.Net Core web apps, there's a really simple way to create integration tests for your project with the &lt;a href="https://www.nuget.org/packages/Microsoft.AspNetCore.TestHost/" target="_blank" title="NuGet Gallery Microsoft.AspNetCore.TestHost"&gt;Microsoft.AspNetCore.TestHost&lt;/a&gt; package. In any web project, there's likely some form of authentication and authorization for specific users. Luckily, there's a really simple way that you can use to sign in users in an integration test scenario by means of evaluating a custom header without having to pass Asp.Net Core Identity cookies back and forth.&lt;/p&gt;
&lt;p&gt;Place the following request handler method in the &lt;span class="Code"&gt;Startup&lt;/span&gt; class you're using for integration tests:&lt;/p&gt;
&lt;pre class="brush: c-sharp;"&gt;public async Task SignInIntegrationTestUser(HttpContext context)
{
    var integrationTestsUserHeader = context.Request.Headers["IntegrationTestLogin"];
    if (integrationTestsUserHeader.Count &amp;gt; 0)
    {
        var userName = integrationTestsUserHeader[0];
        var userManager = context.RequestServices.GetRequiredService&amp;lt;UserManager&amp;lt;ApplicationUser&amp;gt;&amp;gt;();
        var user = await userManager.FindByEmailAsync(userName);
        if (user == null)
        {
            return;
        }
        var signInManager = context.RequestServices.GetRequiredService&amp;lt;SignInManager&amp;lt;ApplicationUser&amp;gt;&amp;gt;();
        var userIdentity = await signInManager.CreateUserPrincipalAsync(user);
        context.User = userIdentity;
    }
}&lt;/pre&gt;
&lt;p&gt;Configure it in the request pipeline after &lt;span class="Code"&gt;app.UseIdentity()&lt;/span&gt; but before &lt;span class="Code"&gt;app.UseMvc()&lt;/span&gt; in your &lt;span class="Code"&gt;Startup.Configure()&lt;/span&gt; method.&lt;/p&gt;
&lt;pre class="brush: c-sharp;"&gt;public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    using (var serviceScope = app.ApplicationServices.GetRequiredService&amp;lt;IServiceScopeFactory&amp;gt;().CreateScope())
    {
        // Seed with integration tests specific data
        ServerInitialization.InitializeIntegrationTestsDatabase(serviceScope.ServiceProvider).Wait();
    }
    app.UseStaticFiles();
    app.UseIdentity();
    // To log in a user for integration tests
    // DO NOT USE IN PRODUCTION
    app.Use(next =&amp;gt; async context =&amp;gt;
    {
        await SignInIntegrationTestUser(context);
        await next.Invoke(context);
    });
    app.UseMvc();
}&lt;/pre&gt;
&lt;p&gt;Generating authenticated clients is now as simple as attaching a custom header:&lt;/p&gt;
&lt;pre class="brush: c-sharp;"&gt;public static HttpClient AdminClient
{
    get
    {
        var client = _testServer.CreateClient();
        client.DefaultRequestHeaders.Add("IntegrationTestLogin", "admin@example.com");
        return client;
    }
}&lt;/pre&gt;
&lt;p&gt;You can use the client to perform web requests to the TestHost, all your controllers will be aware of the &lt;span class="Code"&gt;UserPrincipal&lt;/span&gt;.&lt;/p&gt;
&lt;pre class="brush: c-sharp;"&gt;[Fact]
public async Task StatusOkForAdminUser()
{
    var client = ServerInitialization.AdminClient;
    var response = await client.GetAsync(ACTION_ROUTE);
    Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode);
}&lt;/pre&gt;
&lt;p&gt;Just be careful not to ever let this come near Production code!&lt;/p&gt;
&lt;p&gt;Happy testing!&lt;/p&gt;</description>
      <pubDate>Mon, 12 Dec 2016 16:32:30 Z</pubDate>
      <a10:updated>2016-12-12T16:32:30Z</a10:updated>
    </item>
  </channel>
</rss>