Thursday, May 31, 2018

TypeScript 2.7–Definite Assignment Assertions

While looking through some TypeScript 2.7 samples, I noticed the following syntax:

class User {
    // Notice the exclamation mark 
    username!: string;

    constructor(username: string) {
        this.initialize(username);
    }

    private initialize(username: string) {
        this.username = username;
    }
}
This syntax comes into play when you use another TypeScript 2.7 compiler option; strict property initialization. If the --strictPropertyInitialization flag is enabled, the type checker verifies that each instance property declared in a class either
  • has a type that includes undefined,
  • has an explicit initializer
  • is initialized within the constructor

This is problematic if you want to initialize a property within a helper method or have a dependency injection framework do it for you. To solve this situation you can use a definite assignment assertion using the exclamation mark: (!) . Now the type checker will no longer complain.

Remark: By using a definite assignment assertion it becomes your responsibility to make sure the property gets set.


Wednesday, May 30, 2018

Running security audits using NPM audit

After running NPM install I saw some extra output that I didn’t notice before (no clue how long this feature exists).

This is the extra security related info I got:

added 1106 packages from 1280 contributors and audited 21854 packages in 116.791s

found 13 vulnerabilities (9 low, 4 high)

  run `npm audit fix` to fix them, or `npm audit` for details

clip_image002

Nice feature. This warns me immediatelly if one of my packages has security vulnerabilities.

Let’s try ‘npm audit’:

SEMVER WARNING: Recommended action is a potentially breaking change

  Low             Regular Expression Denial of Service

  Package         debug

  Dependency of   karma [dev]

  Path            karma > socket.io > debug

  More info       https://nodesecurity.io/advisories/534

  Low             Regular Expression Denial of Service

  Package         debug

  Dependency of   karma [dev]

  Path            karma > socket.io > engine.io > debug

  More info       https://nodesecurity.io/advisories/534

  Low             Regular Expression Denial of Service

  Package         debug

  Dependency of   karma [dev]

  Path            karma > socket.io > socket.io-adapter > debug

  More info       https://nodesecurity.io/advisories/534

# Run  npm update ws --depth 4  to resolve 1 vulnerability

  High            Denial of Service

  Package         ws

  Dependency of   protractor [dev]

  Path            protractor > webdriver-js-extender > selenium-webdriver > ws

  More info       https://nodesecurity.io/advisories/550

found 13 vulnerabilities (9 low, 4 high) in 21854 scanned packages

  run `npm audit fix` to fix 1 of them.

  12 vulnerabilities require semver-major dependency updates.

By running ‘npm audit fix’ I can ask npm to update the impacted packages as long as no breaking changes will happen(according to the semantic versioning rules).

More information: https://docs.npmjs.com/getting-started/running-a-security-audit

Tuesday, May 29, 2018

Techorama 2018–ElasticSearch- Search Done Right

Last week I gave a session at Techorama about ElasticSearch. Once again it was a great edition where I loved the sessions but the conversations between the sessions even more!

Techorama2018-Robot1

If you are interested in my slides and/or the demo code, you can find them here:

Monday, May 28, 2018

AsyncFixer–Avoid common async/await anti-patterns

I spend a large part of my day reviewing other people’s code. Seeing all this code over the years has brought me to at least one conclusion; software development is hard and multithreaded programming is even harder.

Although the introduction of the Task Parallel Library and the async/await keywords has helped to simplify multithreaded programming a lot, I still see developers making a lot of mistakes when using async/await.

A good code analyzer that I can recommend to avoid some of these mistakes is AsyncFixer.

It will help you to avoid the following anti-patterns:

  • Unnecessary async/await Methods
  • Using Long-running Operations under Async Methods
  • Fire & Forget Async void Methods
  • Fire & Forget Async Call In the Using Block
  • Implicit Downcasting from Task<T> to Task

If you want to learn more about these and other mistakes, have a look at http://www.learnasync.net/.

Usage

The easiest way to start using it is by adding the AsyncFixer nuget package to your project.

After installing it, you get another code analyzer in your list of analyzers:

image

Now when you make a mistake, the refactoring tools in Visual Studio will prompt you to correct it:

image

    Friday, May 25, 2018

    Angular 6 CLI issue

    After installing the new Angular 6 CLI, I was eager to try it out. So I opened up a command prompt and invoked ng new MyNewAngular6App.

    But instead of getting a new Angular project, I got the following error message:

    Schematic input does not validate against the Schema: {"dryRun":false,"version":"6.0.4","skipGit":false,"skipInstall":false,"linkCli":false,"commit":true,"newProjectRoot":"projects","inlineStyle":false,"inlineTemplate":false,"routing":false,"prefix":"app","style":"css","skipTests":false}
    Errors:
    
      Data path "" should NOT have additional properties(dryRun).
    I talked to a collegae who installed Angular 6 before and he didn’t had the same problem. While comparing our projects I noticed that he had an older version of the Angular CLI; 6.0.3 where I was using the 6.0.4 version. So this looks like an issue specifically linked to Angular CLI 6.0.4.
    I tried to downgrade to 6.0.3 after which ng new finally worked:

    npm uninstall -g @angular/cli
    npm cache verify
    npm install -g @angular/cli@6.0.3

    Remark: The Angular team is already aware of this issue and did a new release 6.05 which is a rollback to 6.0.3, https://github.com/angular/angular-cli/releases/tag/v6.0.5

    Tuesday, May 22, 2018

    Angular 6–Dependency Injection changes

    One of the smaller changes that the Angular team introduced with the Angular 6 release is the support for tree-Shakable providers.

    From the documentation:

    Tree shaking is the ability to remove code that is not referenced in an application from the final bundle. Tree-shakable providers give Angular the ability to remove services that are not used in your application from the final output. This significantly reduces the size of your bundles.

    To enable this scenario, you have to change your code and move from modules referencing services to services referencing modules.

    Until now we always provided a service by registering it as part of our ngModule providers:

    The problem with the code above is that the Angular compiler cannot identify at build time if this service will be required or not. Because it's always possible to inject a service directly using injector.get(Service), Angular cannot identify all of the places in your code where this injection could happen. Thus, services provided in modules are not tree-shakeable.

    To make our service tree-shakeable, the information about how to construct an instance of the service (the provider definition) needs to be a part of the service class itself.

    Remark: If necessary you can further configure the service using a factory function on the injector.

    Wednesday, May 9, 2018

    Visual Studio Code can do that?!

    If you want to get the most out of the great Visual Studio Code editor, check out the ever growing list of tips on https://vscodecandothat.com.

    image

    Tuesday, May 8, 2018

    Akka.NET–Testing the exceptional flow (Continued)

    Yesterday I blogged about our approach to test Exceptions thrown by your Akka.NET actors. Today I want to talk about an issue we encountered when using our own ActorSystem.

    In the example yesterday we were using the Sys property of the Akka.NET Testkit which gives us access to a built-in Actor System created for us:

    var actor = Sys.ActorOf(Props.Create(() => new SampleActor()));

    var filter = CreateEventFilter(Sys);

    However when we tried to run the same test but using our own ActorSystem instance instead the test failed and no Exception was received by the EventFilter.

    To understand why this fails, you have to understand what TestKit is doing behind the scenes when creating an ActorSystem for you. For every test you run it creates a new ActorSystem instance using the following configuration:

    The important line here is the following:

    loggers = ["Akka.TestKit.TestEventListener, Akka.TestKit"]

    This line will link the TestKit EventFilter to the ActorSystem. As we didn’t had any configuration setup for our own ActorSystem, the EventFilter didn’t pick up any event.

    To fix it, we included the configuration above in our app.config:

    Monday, May 7, 2018

    Akka.NET–Testing the exceptional flow

    We are currently building an actor based system using Akka.NET. Creating the system itself is a breeze thanks to Akka.NET, but the introduction of the actor model and actors makes testing somewhat harder.

    The scenario we struggled the most with is when an Actor executes a task but reports no message back. In that case we don’t know what happened inside the actor itself making it hard to assert what is going on. Anyway today I wanted to talk about another scenario; how to test if an Actor throws an Exception.

    I couldn’t find a good example that showed how to handle this test case, so here is how we do it(any feedback is welcome):

    Remark: We are using NUnit in combination with Akka.TestKit.NUnit.

    Friday, May 4, 2018

    Generate Test data using Bogus

    On one of the projects I’m working on, we needed tons of test data to feed our integration tests. Before we carefully crafted the test data ourselves which worked but was a time consuming and cumbersome process. We got quite bored doing this and decided it was time to find a better alternative.

    We ended up using Bogus.

    From the documentation:

    Bogus is a simple and sane fake data generator for .NET languages like C#, F# and VB.NET. Bogus is fundamentally a C# port of faker.js and inspired by FluentValidation's syntax sugar.

    Bogus will help you load databases, UI and apps with fake data for your testing needs.

    Getting started

    To get started with Bogus, you first need to install the NuGet package in your test project:

    Install-Package Bogus
    Next step is to create a Faker object and specify the rules for all your properties:
    Some of the features of Bogus I really like are:
    • Support for multiple locales: You can generate test data in multiple languages
    • Generate default object data:  You can easily generate realistic test data for a large set of objects like countries, addresses, persons, creditcards, emailaddresses,…
    • A fluent API: Thanks to the Fluent api configuring your rules becomes easy as pie

    Remark: If you find the default Fluent API too repetitive, you can use the Bulk api instead:

    Thursday, May 3, 2018

    ASP.NET Core 2.0 Authorization

    With the release of ASP.NET Core 2.0, a lot of things were changed from a security perspective. To help you getting started I can recommend the  ASP.NET Core Authorization Lab created by Barry Dorans.

    image

    In this workshop you will learn how to:

    • Setup and configure the authentication middleware
    • Add global authorization using authorization policies
    • Configure role based access control
    • Create simple claim based policies and more advanced code based policies
    • Add resource bases requirements
    • Applying authorization in your MVC views

    Wednesday, May 2, 2018

    DevOps Resource Center

    Microsoft created a consolidated resource site with all kinds of information related to DevOps. It not only contains learning material about DevOps practices but also about Agile Methods, Git version control. You can also see how Microsoft is applying DevOps for their own products and assess you own DevOps maturity.

    image