Thursday, July 20, 2017

Caching your static files in ASP.NET Core

In ASP.NET Core static files(images, css,…) are typically served using the Static file middleware. The static file middleware can be configured by adding a dependency on the Microsoft.AspNetCore.StaticFiles package to your project and then calling the UseStaticFiles extension method from Startup.Configure:

Unfortunately this code will not do its job in the most efficient way. By default, no caching is applied meaning that the browser will request these files again and again increasing the load on your server.

Luckily it’s not that hard to change the middleware configuration to introduce caching. In this example we set the caching to one day:

Remark: An alternative approach would be to let your proxy server(IIS,…) handle the static file requests as discussed here.

Wednesday, July 19, 2017

Guaranteeing “exactly once” semantics by using idempotency keys

A few weeks ago I had a discussion with a colleague about the importance of idempotency.

From http://www.restapitutorial.com/lessons/idempotency.html:

From a RESTful service standpoint, for an operation (or service call) to be idempotent, clients can make that same call repeatedly while producing the same result. In other words, making multiple identical requests has the same effect as making a single request. Note that while idempotent operations produce the same result on the server (no side effects), the response itself may not be the same (e.g. a resource's state may change between requests).

A good example where you can get into trouble is when your API withdraws some money from a customer account. If the user accidently calls your API twice the customer is double-charged, which I don’t think they’ll like very much…

A solution for this problem is the usage of idempotency keys. The idea is that the client generates a unique key that is send to the server along with the normal payload. The server captures the key and stores is together with the executed action. If a second requests arrives with the same key, the server can recognize the key and take the necessary actions.

What are situations that can happen?

  • Situation 1 – The request didn’t made it to the server; in this case when the second request arrives the server will not know the key and just process the request normally
  • Situation 2 –The request made it to the server but the operation failed somewhere in between; in this case when the second request arrives the server should pick up the work where it failed previously. This behavior can of course vary from situation to situation.
  • Situation 3 – The request made it to the server, the operation succeeded but the result didn’t reach the client; in this case when the second request arrives the server recognizes the key and returns the (cached) result of the succeeded operation.

Note: Idempotency keys get important when you are running systems that are not ACID compliant. If you are running an ACID transactional system, you can just re-execute the same operation as the previous operation should be rolled back(or at least that’s the theory Winking smile).

Tuesday, July 18, 2017

Check compatibility between .NET versions

Compatibility is a very important goal of the .NET team at Microsoft. The team always made a great deal to guarantee that newer versions will not break previous functionality. However sometimes this is unavoidable to address security issues, fix bugs or improve performance.

To understand the consequences you have to make a difference between runtime changes and retargeting changes:

  • Runtime changes: Changes that occur when a new runtime is placed on a machine and the same binaries are run, but expose different behavior
  • Retargeting changes: Changes that occur when an assembly that was targeting .NET FW version x is now set to target version y. 

To help you identify possible compatibility issues, Microsoft created the .NET Compatibility Diagnostics, a set of Roslyn based analyzers.

Here is how to use them:

  • First you have to choose if you want to check for Runtime changes or for Retargeting changes
  • Now you need to select the ‘From .NET Framework version’ and the ‘To .NET Framework version’:

image

  • After making your selection, you’ll get a list of all changes classified by their impact:

image

Monday, July 17, 2017

The state of Developer Ecosystem in 2017

JetBrains did a survey among 5000 developers to identify the current state of the Developer Ecosystem.

image

Here are some interesting facts that came out of it:

  • Java is the most popular primary programming language
  • JavaScript is the most used programming language
  • Go is the most promising programming language
  • Only 55% of the participants write unit tests Sad smile
  • 50% are full stack developers
  • Of the C# developers 66% are using ASP.NET MVC
  • Of the C# developers 92% use Visual Studio and only 3% use VS Code

Go explore all the results yourself at https://www.jetbrains.com/research/devecosystem-2017/

Friday, July 14, 2017

Improve your HTML and CSS editing skills in Visual Studio by using Emmet

Last week I discovered a great feature in VS Code that made my life so much easier; the support for Emmet snippet extension.

image

If you don’t know Emmet I suggest having a look at the demo at https://docs.emmet.io/first……………………… convinced? Let’s show you how this works in VS Code:

  • Open an HTML file inside VS code:

image

image

  • Hit ‘Tab’ and let the magic happen:

image

Thursday, July 13, 2017

Type check your JavaScript files

Starting from TypeScript 2.3 you can not only use the type checking and error reporting features of TypeScript in your .ts files but also in your .js files as well.

This new feature is an opt-in option that can be enabled by adding the --checkJs flag. this will enable type checking for all .js files by default.  Open your tsconfig.json file and add the following line “checkJs”:true :

image

If you now create a JavaScript file and introduce a type checking error, you’ll get a nice error message from the TypeScript transpiler;

image

By default setting this flag will enable this feature for all your .js files. It is still possible to selective include/exclude specific files/lines by using any of the following comments;

  • Use // @ts-check to enable type checking for a single file.
  • Use // @ts-nocheck to disable type checking for a single file.
  • Use // @ts-ignore to disable type checking for a single line.

Wednesday, July 12, 2017

SwashBuckle: Add support for operation overloading

By default SwashBuckle, doesn’t handle overloaded controller methods very well. A solution is the usage of an OperationFilter that changes the operationname in the UI:

Next step is to add this OperationFilter to your Swagger configuration:

Tuesday, July 11, 2017

WPF Debounce trick

Sometimes you have to appreciate the power and simplicity that WPF(and by extend XAML has to offer). While having to do a lot of voodoo magic with Reactive Extensions to support debouncing, in WPF it can be reduced to one binding property,  the Delay Binding Property.

image

You can use the WPF Delay binding property to debounce binding events. For example following code will debounces the key input until nothing changes for 0.5 seconds:

Text="{Binding UserName,UpdateSourceTrigger=PropertyChanged,Delay=500}"

Sweet!

Monday, July 10, 2017

Installing a Windows Service using Topshelf

For a Windows Service we are building, we are using Topshelf:

Topshelf is a framework for hosting services written using the .NET framework. The creation of services is simplified, allowing developers to create a simple console application that can be installed as a service using Topshelf. The reason for this is simple: It is far easier to debug a console application than a service. And once the application is tested and ready for production, Topshelf makes it easy to install the application as a service.

image

Great tool and a lot easier during debugging and development! However when I tried to install the final exe as a windows service using installutil.exe it failed with the following error message:

"No public installers with the RunInstallerAttribute.Yes attribute could be found in the SampleService.exe assembly."

Turns out that you don’t need the installutil.exe tool when you are using Topshelf. Instead you should invoke your executable with the ‘install’ option:

SampleService.exe install

More information:

http://docs.topshelf-project.com/en/latest/overview/commandline.html

Friday, July 7, 2017

SQL Server Profiler is depecrated

The SQL Server Profiler has been around for a very long time. It is very useful if you are trying to see in real time what SQL queries are being executed against your database. However, in the SQL Server 2016, Microsoft announced that the SQL Profiler will be deprecated in future versions.

Does this mean that there are no profiling options left in SQL Server? Luckily no, the SQL Profiler will be replaced by Extended Events(XE). Extended Events works via Event Tracing (ETW) which consumes less resources and allows much more flexibility. It also can monitor more events than the Profiler.

Where can I find these Extended Events?

  • Open SQL Server Management Studio( for SQL 2014 or higher) and connect to one of your Database instances
  • Go to Management>Extended Events:

image

  • Expand the Extended Events section, right click on Sessions and choose New Session Wizard

image

  • The Session wizard will help us to select the events we want to profile. Click on Next >

image

  • Specify a session name and click Next >

image

  • Now you can choose an existing template. Leave the Do not use a template radiobutton checked and click on Next >

image

  • The next screen is where the real work is done. Here you specify the events you want to monitor. Luckily you can search through them. Select some events you want to track and click Next >

image

  • Now you can specify any global fields(e.g. username, database name,…) you want to capture together with the events. Click Next > to continue

image

  • Next step is to apply some optional filters to limit the amount of data that is returned. Click Next > to continue

image

  • The session storage allows you to specify how to collect the data and store it.  Click Next >.

image

  • On the Summary you get an overview of the selected options. Click Finish to generate the Session.
    • Note: There is an option to generate a script from this configuration. So you can re-use it later.

image

  • After clicking Finish you end up on a Success page. Here you can start the session immediately and watch the data when it is captured.

image

Thursday, July 6, 2017

VSTS - WIKI

A long listed request finally arrived into VSTS, the introduction of a built-in Wiki. Before you had to fallback to the Wiki extension in the marketplace.  It’s still in preview but offers enough features to start playing with it. Open up your VSTS account and you’ll find the following new menu item:

image

When you click on it, you are welcomed with one button ‘Create Wiki’. Shall we?

image

After clicking on Create Wiki, an editor(with Markdown support) is opened that allows you to create your first Wiki page:

image

Let’s hit Save, specify some comments and there is our first Wiki page on VSTS:

image

Creating a link to another Wiki page is as simple as using a Markdown link, don’t forget to replace spaces by a ‘-‘ in the link URL:

image

What features are coming next ?

Our team is working hard to get you the next set of Wiki features, such as…

  • Wiki search across projects
  • Tags
  • Wiki integration with work items
  • Rich editing experience that support:
    • HTML tags
    • Resizing images
    • Mathematical formulas

More information in the official Wiki announcement and the documentation.

Wednesday, July 5, 2017

HTTP vs HTTPS

You sometimes here people say that they’ll keep using HTTP because it’s faster than HTTPS. This doesn’t have to be true(to spoil the surprise think HTTP2 Smile). Let’s try the test on https://www.httpvshttps.com/:

The first test is using HTTPS, loads 360 unique, non-cached images and completes in 0.716 seconds.

image

To proof there is no magic, here is the network traffic overview:

image

Let’s do the same test but with HTTP instead. 7.770 seconds! Auw, that hurts:

image

And an overview of the related traffic:

image

So where is the magic? As a I already revealed at the beginning of this post, the magic is in the usage of HTTP2. HTTP2 is the replacement for HTTP with a focus on speed. It only works on secured connections using SSL but as the tests above proof is a lot faster than HTTP.  So no excuses anymore to not start using HTTPS(and HTTP2)!

Tuesday, July 4, 2017

AlternativeTo–Crowdsourced software recommendations

A great tip from a colleague I wanted to share…

AlternativeTo is simple in its beauty. It allows you to search for alternatives for specific applications. A great help if you need to buy a new tool but want to compare some options.

From the site:

Don’t settle for crappy apps. We’ll help you find alternatives.

AlternativeTo is a new approach to finding good software. Tell us what application you want to replace and we give you great alternatives, based on user recommendations.

An example, let’s look at a replacement for Visual Studio(*): http://alternativeto.net/software/visual-studio/. I get 84 alternatives back. For every alternative you can vote if it’s a good replacement or not.

image

(*): I’m sorry, I’m not planning to replace my Visual Studio.

Monday, July 3, 2017

Team Foundation Server Code-Search Administration scripts

Starting from Team Foundation Server 2017, the Code Search feature that was available for a while in VSTS, gets an on-premise equivalent.

The feature is built on top of a customized version of ElasticSearch. However the integration between the 2 products(TFS and ElasticSearch) is rather limited right now.

To help you maintain your ElasticSearch instance, Microsoft has a set of Powershell scripts available that allow you to:

  • Pause and Restart indexing
  • Clean and reset your ElasticSearch instance
  • Trigger code indexing
  • Etc…

image

A must have for every TFS administrator…

Friday, June 30, 2017

Comparing local files using VsDiffMerge

If you ever did a merge operation in Visual Studio and you had merge conflicts to resolve, know that you were using VsDiffMerge.exe behind the scenes. But did you know that you can use this tool as well to compare local files that are not under source control?

Let’s demonstrate…

The VsDiffMerge.exe tool can be found inside your Visual Studio directory (for VS 2017: C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE)

To compare 2 files, you have to pass the filepath as an argument to the tool:

vsdiffmerge.exe" "File1" "File2"

An example:

vsdiffmerge.exe" "UnitTest1.cs" "UnitTest2.cs" starts up the Visual Studio IDE with “UnitTest1.cs” and “UnitTest2.cs” opened:
image

Thursday, June 29, 2017

Learning to use Flexbox

Flexbox is a ‘new’ way to layout your html page in CSS. No longer you need to use things like floats and positioning for creating CSS layouts. Instead you get a more flexible approach that scales from smartphone to smarttv. Browsers start to pick up this technique, so it’s time that you start learning it.

From MDN:

When elements are laid out as flexible boxes, they are laid out along two axes:

  • The main axis is the axis running in the direction the flex items are being laid out in (e.g. as rows across the page, or columns down the page.) The start and end of this axis are called the main start and main end.
  • The cross axis is the axis running perpendicular to the direction the flex items are being laid out in. The start and end of this axis are called the cross start and cross end.
  • The parent element that has display: flex set on it (the <section> in our example) is called the flex container.
  • The items being laid out as flexible boxes inside the flex container are called flex items (the <article> elements in our example).

flex_terms.png

A great example that helps you understand the different settings of a Flexbox layout is the Build With React has a great flexbox editor.

clip_image001

Another one that I personaly liked(childhood memories) is a game called Flexbox Froggy. It teaches the concepts in an enjoyable and accessible manner.

clip_image003

Remark: Know that you can combine Flexbox with other layouting techniques that you used before.

Wednesday, June 28, 2017

ASP.NET Core IIS error: HTTP error 502.5–Process failure

After enabling .NET Core on my web server I was finally ready to run my ASP.NET Core app. Or at least that was what I thought… When I opened my browser IIS welcomed me with the following error message:

clip_image002

After enabling stdout logging inside the web.config of my ASP.NET Core app I saw following error:

The specified framework 'Microsoft.NETCore.App', version '1.1.2' was not found.

  - Check application dependencies and target a framework version installed at:

      C:\Program Files\dotnet\shared\Microsoft.NETCore.App

  - The following versions are installed:

      1.0.4

      1.1.1

  - Alternatively, install the framework version '1.1.2'.

That is great and meaningful error message. I downloaded the latest runtime version 1.1.2, installed it, and was good to go!

Tuesday, June 27, 2017

Enable .NET Core on IIS

Just a quick reminder for myself. Lost some time last week searching how to be able to run .NET Core apps in IIS on my webserver.

The trick is that you need to install the .NET Core Windows Server Hosting bundle.

  • Install the .NET Core Windows Server Hosting bundle on the hosting system. The bundle will install the .NET Core Runtime, .NET Core Library, and the ASP.NET Core Module. The module creates the reverse-proxy between IIS and the Kestrel server. Note: If the system doesn't have an Internet connection, obtain and install the Microsoft Visual C++ 2015 Redistributable before installing the .NET Core Windows Server Hosting bundle.
  • Restart the system or execute net stop was /y followed by net start w3svc from a command prompt to pick up a change to the system PATH.
  • Create a new Application Pool. Set the .NET Framework version to ‘No Managed Code’.

image

More information: https://docs.microsoft.com/en-us/aspnet/core/publishing/iis

Monday, June 26, 2017

Error when using WebDeploy with ASP.NET Core

Last week I got into trouble when trying to use msdeploy for an ASP.NET Core app. Where I got no problems for the ‘old’ ASP.NET applications, every time I tried to deploy an ASP.NET Core app I got the following error message:

ERROR_USER_UNAUTHORIZED

I logged in on the target server and find a little bit more information in the Event Viewer:

IISWMSVC_AUTHORIZATION_SERVER_NOT_ALLOWED

Only Windows Administrators are allowed to connect using a server connection. Other users should use the 'Connect To Site or Application' task to be able to connect.

clip_image002

I was 100% sure that everything was configured correctly on the server. I used exactly the same steps as for my other applications, the only difference was that this was an ASP.NET Core app.

After some testing, I found an approach that worked for me:

Here are the things I had to change inside my Web Deploy pubxml file:

Friday, June 23, 2017

Visual Studio 2017 - Build Failure. Error: 'path' cannot be an empty string ("") or start with the null character.

After upgrading to Visual Studio 2017 version 15.2, building some of my projects started to fail with the following error message:

Build Failure. Error: 'path' cannot be an empty string ("") or start with the null character.

The problem only appeared for projects where I enabled the lightweight solution loading feature.

Lightweight solution loading:

Many common tasks, such as navigating through your codebase, editing code, and building your projects will not require any projects to be loaded at all. Therefore Microsoft created the lightweight Solution load feature. The effect is that Visual Studio will not fully load projects until you start working with them increasing performance especially for large projects.

As the problem only happened for these projects, I decided to disable Lightweight solution load again. This indeed solved the problem for me(note: I had to close and reopen the solution before I saw an effect).

image

Hopefully a bug fix will be released with the next update…

Thursday, June 22, 2017

Conway’s Law–The original paper

In the context of software architecture, people sometimes talk about Conway’s Law:

Any organization that designs a system (defined broadly) will produce a design whose structure is a copy of the organization's communication structure.

Although we apply it on software architecture, this definition is originally created in a more broader sense. If you are interested in reading the original paper, go check it out here; http://www.melconway.com/Home/Committees_Paper.html

image

The original paper in PDF format can be found here; http://www.melconway.com/Home/pdf/committees.pdf

Wednesday, June 21, 2017

NPM 5 - Hopes for the future

I’m not a big fan of NPM, it’s not persé the fault of the tool itself but you don’t get happy when you end up with 1000’s of packages and any package change has a ripple effect through your code base. It even gets better when package creators don’t follow the semantic versioning rules and breaking changes appear without a warning. Everything I have to open up a new codebased and NPM starts its magic behind the scenes, it is not without fear that I first start compiling my code.

Sidenote: You can say similar things about any other packaging tool I guess, e.g. NuGet

But hey, enough complaining, time for some good news. Last month, the NPM released version 5 and they promised a lot of improvements.

The announcement:

Starting today, typing `npm install npm@latest -g` will update you to npm version 5.0.1.
npm@5 is all new and packed with performance, reliability, and usability improvements we know you’ll love. These include a new approach to lockfiles, more robust caching, and incredible speed — for many common tasks, npm@5 is up to 5x faster than previous versions.
The update is available now and we recommend it for everyone.
You can learn more about npm@5
here.

Did the update and it is certainly faster! Made my day…

Tuesday, June 20, 2017

Angular 4–Visual Studio 2017 - error TS2420: Class 'MdButton' incorrectly implements interface 'CanDisable'. Property 'disabled' is missing in type 'MdButton'.

After upgrading to Angular 4, my Visual Studio turned red from all the TypeScript errors.

Some samples:

/node_modules/@angular/material/typings/button/button.d.ts(40,22): error TS2420: Class 'MdButton' incorrectly implements interface 'CanDisable'.
  Property 'disabled' is missing in type 'MdButton'.

/node_modules/@angular/material/typings/button/button.d.ts(40,39): error TS2507: Type '(new (...args: any[]) => CanDisable) & typeof MdButtonBase' is not a constructor function type.
The strange thing was, that when I used the Angular CLI and ng build(or serve) no errors appeared and everything seemed to work. 
I first tried to remove my node_modules folder and do a clean install –> didn’t help Sad smile
Then I removed my globally installed node_modules and reinstalled them as well –> didn’t help Sad smile
Then I upgraded my TypeScript version and the related Visual Studio tooling –> didn’t help Sad smile
In the end I found a solution that worked for me here, I had to update to Visual Studio 2017 Update 15.2. I don’t understand why upgrading an Angular version will get Visual Studio into trouble. I hope this experience will improve as I will become hesitant to upgrade Angular in the future.
Remark: Afterwards I noticed that a colleague already sent me an email telling me to update my Visual Studio before upgrading. Better read my mails next time… Confused smile

Monday, June 19, 2017

Getting up to speed with QuickApp, an ASPNET Core / Angular4 startup project template

I’m always disappointed to see the amount of work to get your application setup done(you know the typical ‘Sprint 0’ work). Creating your frontend and backend projects, setting up your authentication and authorization, configure the webpack magic and so on… Before you know it you are 2 weeks in your project and you didn’t deliver a single bit of business functionality.

So every tool, framework or library that can help you get up to speed is a welcome addition to our toolbox. Recently I discovered QuickApp, an ASP.NET Core/AngularX Project Template.

QuickApp Demo

From the documentation:

This application consists of:

  • Template pages using Angular4 and TypeScript
  • RESTful API Backend using ASP.NET Core MVC Web API
  • Database using Entity Framework Core
  • Authentication based on OpenID Connect
  • API Documentation using Swagger
  • Webpack2 for managing client-side libraries
  • Theming using Bootstrap

You get the benefits of:

  • A complete backend and frontend project structure to build on, with login, user and permission-based role management already integrated
  • Data Access Layer built with the Repository and Unit of Work Pattern
  • Code First Database
  • A RESTful API Design
  • Angular Directives Quidance
  • Angular Pipes Quidance
  • Angular Animations Quidance
  • Angular Services
  • Dialog and Notification Services
  • Configuration Page and Configuration Service
  • Integrated Internationaliztion
  • Theming with SASS
  • Ready-to-use email API
  • Handling Access and Refresh Tokens with WebStorage (Bearer authentication) - No Cookies
  • Jquery Integration (Ability to use standard Jquery libraries)
  • CRUD APIs