Eric

Swagger and Swashbuckle with ASP.NET Core 2

This post is going to be very similar to a post from last December which can be found here. A lot has changed since then and this post is going to add Swagger to an existing ASP.NET Core application using Swashbuckle much like the one from last year. The starting point of the code can be found here.

What is Swagger?

Swagger is a specification used to document an API. As I am sure we all know API documentation tends to get out of date fast and a lot of times is a low priority.  Swagger aims to help solve that problem using a format that is both human and machine readable which can be maintained in either JSON or YAML. The documentation can be auto generated using a tool like Swashbuckle which provides away to keep your consumers up to date. Check out this post by the Swagger team for the full introduction.

What is Swashbuckle?

Swashbuckle provides auto generation of Swagger 2.0, a UI, etc. The project takes all the pain out of getting going with Swagger as well as providing tools and hooks for using and customizing Swagger related items. The full description can be found here.

Adding Swashbuckle

Using your favorite method of NuGet interaction, add the Swashbuckle.AspNetCore NuGet package to your project. Personally, I have gotten where I edit the csproj file to add new packages. If that is your style you would need to add the following package reference.

<PackageReference Include="Swashbuckle.AspNetCore" Version="1.0.0" />

This one package provides all the functionality we will need.

Wiring up Swashbuckle

Now that the Swashbuckle package is installed, there are a few changes that are needed in the Startup class to get everything wired up. First, in the ConfigureServices function, the Swagger generator needs to be added to DI.

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Info { Title = "Contacts API", Version = "v1"});
});

AddSwaggerGen allows for configuration of options, but here we are just setting a name and a minimal amount of information.

In the Configure function Swagger needs to be added to the request pipeline in order to expose the Swagger generated data. I placed this after UseMvc.

app.UseSwagger();

At this point, the Swagger generated JSON would be available at {yourBaseUrl}/swagger/v1/swagger.json. To take a step further let’s expose the UI that comes with Swashbuckle. Add the following just below app.UseSwagger().

app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Contacts API V1");
});

Now a UI based on your API is available at {yourBaseUrl}/swagger with zero extra work on your part. The following is the UI for the post contact route in the example project.

As you can see the UI provides a great view of your API as well as ways to try it out and the potential responses that should be expected from a call.

Controller Considerations

All of this wonderful functionality doesn’t come for free of course. In order for Swashbuckle to pick up your routes, your controller will need to use attribute based routing instead of depending on convention based routing.

In order for Swashbuckle to know the return types and of your controller actions may need to have some attributes added. This won’t be required if your action return a specific type, but if you are returning an IActionResult you should attribute your action with all the ProducesResponseType you need to cover the results of your action. For example, the following is the action definition for the Post in the screen shot above.

[HttpPost]
[ProducesResponseType(typeof(Contact), 200)]
[ProducesResponseType(typeof(IDictionary<string, string>), 400)]
[ProducesResponseType(typeof(void), 400)]
[ProducesResponseType(typeof(void), 404)]
[ProducesResponseType(typeof(void), 409)]
public async Task<IActionResult> PostContact([FromBody] Contact contact)

Wrapping up

Swashbuckle makes it easy to add Swagger to a project. I feel that it also provides a huge value for anyone trying to consume an API. It is of course not a magic bullet and communication with your API consumers about API changes will still be critical.

Microsoft’s docs have a great walk through which can be found here. It does more in-depth on customizing your setup and as far as modifying the look of the UI. I also recommend checking out the GitHub page for the project which can be found here.

The finished code can be found here.

Swagger and Swashbuckle with ASP.NET Core 2 Read More »

Identity Server: API Migration to ASP.NET Core 2

After writing the basic migration guide from ASP.NET Core 1.1.x to 2.0 I embarked on the task of upgrading the rest of the projects I have on GitHub. For the most part, it has been a pretty smooth transition. This post is going cover the differences that I hit while converting an API that is part of my IdentityServer sample project. This assumes that you have already followed my other migration post which can be found here.

Package Changes

The source of this conversion being different is that the IdentityServer4.AccessTokenValidation NuGet package is not currently supported on ASP.NET Core 2. Token validation can be done using bits provided by the framework. This is the recommended path suggested by the IdentityServer team as posted on this issue. Longer term you may want to switch back if you have a need for more features not provided by the Microsoft implementation as pointed out in this issue.

As for the actual change, just remove the reference to IdentityServer4.AccessTokenValidation from your project using the NuGet UI, Package Manager Console, or by editing the csproj file.

Startup

All the rest of the changes are in the Startup class. First, in the Configure function app.UseIdentityServerAuthentication gets replaced with app.UseAuthentication.

Before:
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
    Authority = "http://localhost:5000",
    RequireHttpsMetadata = false,
    ApiName = "apiApp"
});

After:
app.UseAuthentication();

In the ConfigureServices function is now where JWT Bearer options are set up. First, we have to add the type of authentication the API is going to use and then the options for JWT Bearer are set, which will match the settings that were being used before with the IdentityServer package.

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = 
                               JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = 
                               JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
    o.Authority = "http://localhost:5000";
    o.Audience = "apiApp";
    o.RequireHttpsMetadata = false;
});

Wrapping up

With the above, your API can run on ASP.NET Core 2 and still verify authorization using IdentityServer4. My IdentityServer sample project is taking the longest to update so I would expect at least one or two more posts on the process as each of the projects gets upgraded.

Identity Server: API Migration to ASP.NET Core 2 Read More »

All Migrations are not Created Equal

While trying to deploy my sample Identity Server set of applications to Azure I got the following error when the Entity Framework migrations attempted to run.

System.Data.SqlClient.SqlException (0x80131904): Column 'Id' in table 'AspNetRoles' is of a type that is invalid for use as a key column in an index

This was not something I would get when attempting to run locally, but it failed every time when using SQL Azure. Long store short is that the migrations that were trying to be applied were created when I was using Sqlite as a backing store (UseSqlite).

I deleted all the migrations and recreated them with the app being aware that it would be running on SQL Server (UseSqlServer) and all worked as it should. It makes total sense that the migrations would vary based on the data provider being used, but not something I had really thought about. Not something I will forget again.

All Migrations are not Created Equal Read More »

Create a .NET Standard Library with Visual Studio 2017

It has been almost a year since I wrote this post on creating a .NET Standard Library which was before Visual Studio 2017 was released. This post is going to cover the same basic idea, but for the new tooling which has vastly simplified the process.

.NET Standard Library

The .NET Standard Library specifies what .NET APIs are available based on the version of the .NET Standard Library being implemented. The following is a comparison to portable class libraries that really helped me understand the difference. This was pulled from the .NET Standard Library link above.

.NET Standard Library can be thought of as the next generation of Portable Class Libraries (PCL). The .NET Standard Library improves on the experience of creating portable libraries by curating a standard BCL and establishing greater uniformity across .NET runtimes as a result. A library that targets the .NET Standard Library is a PCL or a “.NET Standard-based PCL”. Existing PCLs are “profile-based PCLs”.

The .NET Standard Library and PCL profiles were created for similar purposes but also differ in key ways.

Similarities:

  • Defines APIs that can be used for binary code sharing.

Differences:

  • The .NET Standard Library is a curated set of APIs, while PCL profiles are defined by intersections of existing platforms.
  • The .NET Standard Library linearly versions, while PCL profiles do not.
  • PCL profiles represents Microsoft platforms while the .NET Standard Library is agnostic to platform.

Create a .NET Standard Library

In Visual Studio click File > New > Project.

This will launch the New Project dialog. Find the .NET Standard templates and select Class Library.

Now that the library has been created right click on the project and go to properties. On the Application tab, there is an option to for Target framework which currently defaults to .NETStandard 1.4. Depending on your platform your library needs to support will decide which version of the .NET Standard you need to use.

See the chart on this page for help with picking a version of the standard. The lower the version of the standard you target the more platforms your library will run on, but keep in mind the lower the version the smaller the API surface that is available.

Wrapping up

This process is so much easier than it was in Visual Studio 2015. The tooling around .NET Core and .NET Standard has gotten so much better. This type of library is the future and I highly recommend using .NET Standard when you have the option over portable class libraries.

Create a .NET Standard Library with Visual Studio 2017 Read More »

Unable to create an object of type ‘ApplicationDbContext’. Add an implementation of ‘IDesignTimeDbContextFactory

Forgive the long title, but this is an issue I have been fighting trying to upgrade an Identity Server 4 project to ASP.NET Core 2. There is an issue on GitHub dedicated to this exact error which can be found here. Before you go down the route of trying all the suggestions in the issue take a moment and make sure that nothing in the Startup class is doing anything that would try to hit the database with Entity Framework.

There is a nice section in the official migration docs titled “Move database initialization code” which I seemed to have missed. So before you head down any rabbit holes like I did make sure this isn’t what is causing your need to add an implementation of IdesignTimeDbContextFactory.

As stated in the migration docs move database related code out of the Configure function of the Startup class and into the Main function. The following is the example of this from the docs.

var host = BuildWebHost(args);

using (var scope = host.Services.CreateScope())
{
    var services = scope.ServiceProvider;

    try
    {
        // Requires using RazorPagesMovie.Models;
        SeedData.Initialize(services);
    }
    catch (Exception ex)
    {
        var logger = services.GetRequiredService<ILogger<Program>>();
        logger.LogError(ex, "An error occurred seeding the DB.");
    }
}

host.Run();

This will keep Entity Framework tooling from accidentally running code you didn’t expect.  With version 2 all the code in the Configure function gets run.

Unable to create an object of type ‘ApplicationDbContext’. Add an implementation of ‘IDesignTimeDbContextFactory‘ Read More »

Identity Server: External Authentication using Twitter

This post is going to cover adding authentication using Twitter to the same project that has been used in all of my IdentityServer examples. The same basic idea would apply to almost any third party authentication setup so this should give you a good starting point for any integration. The starting point of the code can be found here.

Create Twitter App

Before any code changes create a new application on Twitter via this page. Click Create New App to begin the process.

On the Create an application page enter all the requested information. Note that the website won’t allow a localhost address. If you don’t have a real address for your application just enter a random URL as I did here. When finished click Create your Twitter application.

Now that we have an application click on the Keys and Access Tokens tab. We will need both the Consumer Key and Consumer Secret when we get to the Identity Application.

Identity Application Changes

Now that we have a Twitter application ready to go let us dive into the changes needed to the Identity Application. The first step is to add a reference to Microsoft.AspNetCore.Authentication.Twitter via NuGet.

Next in the ConfigureServices function of the Startup class after app.UseIdentityServer() add the following.

app.UseTwitterAuthentication(new TwitterOptions
{
    AuthenticationScheme = "Twitter",
    DisplayName = "Twitter",
    SignInScheme = "Identity.External",
    ConsumerKey = Configuration["Authentication:Twitter:ConsumerKey"],
    ConsumerSecret = Configuration["Authentication:Twitter:ConsumerSecret"]
});

The first three options should a straight forward enough. The next two are the values from the Twitter application I mentioned above. In this example, I am storing the values using User Secrets which get pulled out of configuration. For more details on how to set up secrets, you can see this post.

The above are all the changes required. The Identity Application will now allow users to auth using Twitter.

Logging in using Twitter

As you can see below the login page now has a button for Twitter.

When the user chooses to log in using Twitter they are shown the following page where they must approve access to their Twitter account from your application.

If this is the first time a user has logged in with Twitter they will be prompted to enter an email address to finish registration.

Wrapping up

As you can see adding external authentication is super simple. Check out the Microsoft Docs on Twitter Auth (ASP.NET Core 2.0 so look out for differences if you are not on the preview bits) and IdentityServer Docs on External Auth for more information.

The finished code can be found here.

 

Identity Server: External Authentication using Twitter Read More »

Identity Server: Changing Angular OpenID Connect Clients

Thanks to Andrew Stegmaier opening this issue on the repo that goes with my IdentityServer exploration I was made aware of a certified OpendID Connect client specifically written for Angular (4+). The angular-auth-oidc-client was created by damienbod. This post is going to cover the transition to this new client. The starting point of the code can be found here. All the changes discussed in this post take place in the ClientApp project.

Package Changes

In package.json the following changes need to be made using your package manager of choice or manually changing the fill and doing a restore.

Remove:
"oidc-client": "1.3.0",
"babel-polyfill": "6.23.0"

Add:
"angular-auth-oidc-client": "^1.3.1"

App Module Changes

Both app.module.client.ts and app.module.server.ts got a little cleanup to remove the duplicate provider code. The following lines were deleted from both files.

import { AuthService } from './components/services/auth.service';		
import { GlobalEventsManager } from './components/services/global.events.manager';		
import { AuthGuardService } from './components/services/auth-guard.service';

The providers array moved to using providers imported from app.module.shared.ts.

Before:
providers: [
    AuthService, AuthGuardService, GlobalEventsManager
]

After:
providers: [
    ...sharedConfig.providers
]

Next, in app.module.shared.ts the following imports were removed.

import { CallbackComponent } from './components/callback/callback.component';
import { GlobalEventsManager } from './components/services/global.events.manager';

Then, the following import for the OpenId Connect client was added.

import { AuthModule } from 'angular-auth-oidc-client';

In the declarations array CallbackComponent was removed. In the imports array AuthModule.forRoot() was added. The route for CallbackComponent was removed and the canActivate condition was removed from the fetch-data route. Finally, the providers section is reduced to only the AuthService. That was a lot of changes, so I am including the full finished class below.

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';

import { AppComponent } from './components/app/app.component'
import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';
import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
import { CounterComponent } from './components/counter/counter.component';
import { UnauthorizedComponent } from './components/unauthorized/unauthorized.component';

import { AuthModule } from 'angular-auth-oidc-client';
import { AuthService } from './components/services/auth.service';

export const sharedConfig: NgModule = {
    bootstrap: [ AppComponent ],
    declarations: [
        AppComponent,
        NavMenuComponent,
        CounterComponent,
        FetchDataComponent,
        HomeComponent,
        UnauthorizedComponent
    ],
    imports: [
        AuthModule.forRoot(),
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
            { path: 'unauthorized', component: UnauthorizedComponent },
            { path: 'counter', component: CounterComponent },
            { path: 'fetch-data', component: FetchDataComponent  },
            { path: '**', redirectTo: 'home' }
        ])
    ],
    providers: [ AuthService ]
};

File Deletions

The following files were completely removed. Some of them may come back in a different form, but for the moment the functions they were handling are being dealt with in a different way.

auth-guard.service.ts
callback.component.ts
global.events.manager.ts

Auth Service

The AuthService class was pretty much rewritten since it is at the core of the interaction with the OpenId Connect client. It still contains pretty much all the functionality as before just using the new client. The following is most of the class. I removed all of the HTTP calls except for get to save space.

import { Injectable, Component, OnInit, OnDestroy } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { Subscription } from 'rxjs/Subscription';

import { OidcSecurityService, OpenIDImplicitFlowConfiguration } from 'angular-auth-oidc-client';

@Injectable()
export class AuthService implements OnInit, OnDestroy {
    isAuthorizedSubscription: Subscription;
    isAuthorized: boolean;

    constructor(public oidcSecurityService: OidcSecurityService,
        private http: Http) {

        const openIDImplicitFlowConfiguration = new OpenIDImplicitFlowConfiguration();
        openIDImplicitFlowConfiguration.stsServer = 'http://localhost:5000';

        openIDImplicitFlowConfiguration.redirect_url = 'http://localhost:5002/callback';
        // The Client MUST validate that the aud (audience) Claim contains its client_id value registered at the Issuer identified by the iss (issuer) Claim as an audience.
        // The ID Token MUST be rejected if the ID Token does not list the Client as a valid audience, or if it contains additional audiences not trusted by the Client.
        openIDImplicitFlowConfiguration.client_id = 'ng';
        openIDImplicitFlowConfiguration.response_type = 'id_token token';
        openIDImplicitFlowConfiguration.scope = 'openid profile apiApp';
        openIDImplicitFlowConfiguration.post_logout_redirect_uri = 'http://localhost:5002/home';
        openIDImplicitFlowConfiguration.start_checksession = true;
        openIDImplicitFlowConfiguration.silent_renew = true;
        openIDImplicitFlowConfiguration.startup_route = '/home';
        // HTTP 403
        openIDImplicitFlowConfiguration.forbidden_route = '/forbidden';
        // HTTP 401
        openIDImplicitFlowConfiguration.unauthorized_route = '/unauthorized';
        openIDImplicitFlowConfiguration.log_console_warning_active = true;
        openIDImplicitFlowConfiguration.log_console_debug_active = false;
        // id_token C8: The iat Claim can be used to reject tokens that were issued too far away from the current time,
        // limiting the amount of time that nonces need to be stored to prevent attacks.The acceptable range is Client specific.
        openIDImplicitFlowConfiguration.max_id_token_iat_offset_allowed_in_seconds = 10;

        this.oidcSecurityService.setupModule(openIDImplicitFlowConfiguration);
    }

    ngOnInit() {
        this.isAuthorizedSubscription = this.oidcSecurityService.getIsAuthorized().subscribe(
            (isAuthorized: boolean) => {
                this.isAuthorized = isAuthorized;
            });

        if (window.location.hash) {
            this.oidcSecurityService.authorizedCallback();
        }
    }

    ngOnDestroy(): void {
        this.isAuthorizedSubscription.unsubscribe();
    }

    authorizedCallback() {
        this.oidcSecurityService.authorizedCallback();
    }

    getIsAuthorized(): Observable<boolean> {
        return this.oidcSecurityService.getIsAuthorized();
    }

    login() {
        console.log('start login');
        this.oidcSecurityService.authorize();
    }

    logout() {
        console.log('start logoff');
        this.oidcSecurityService.logoff();
    }

    get(url: string, options?: RequestOptions): Observable<Response> {
        if (options) {
            options = this.setRequestOptions(options);
        }
        else {
            options = this.setRequestOptions();
        }
        return this.http.get(url, options);
    }

    private setRequestOptions(options?: RequestOptions) {
        if (options) {
            this.appendAuthHeader(options.headers);
        }
        else {
            options = new RequestOptions({ headers: this.getHeaders(), body: "" });
        }
        return options;
    }

    private getHeaders() {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');
        this.appendAuthHeader(headers);
        return headers;
    }

    private appendAuthHeader(headers: Headers) {       
        const token = this.oidcSecurityService.getToken();

        if (token == '') return;

        const tokenValue = 'Bearer ' + token;
        headers.append('Authorization', tokenValue);
    }
}

It doesn’t show the best in the world here so be sure and check it out on GitHub. All the IdentityServer configuration is done in the constructor using the OpenIDImplicitFlowConfiguration class.

Navigation Component

The NavMenuComponent class now needs some changes to match the new AuthService. First, the following change to the imports.

Before:
import { Component } from '@angular/core';
import { AuthService } from '../services/auth.service'
import { GlobalEventsManager } from '../services/global.events.manager'

After:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { AuthService } from '../services/auth.service';

The AuthService class now provides the ability to subscribe to changes in the user’s authorization. To handle the subscription and unsubscription the class will implement both OnInit and OnDestroy. Here is the new class declaration.

export class NavMenuComponent implements OnInit, OnDestroy

Next, here is the implementation of ngOnInit which handles the subscription to the change in isAuthorized.

ngOnInit() {
    this.isAuthorizedSubscription = 
            this.authService.getIsAuthorized().subscribe(
                   (isAuthorized: boolean) => {
                      this.isAuthorized = isAuthorized;
                    });

    if (window.location.hash) {
        this.authService.authorizedCallback();
    }
}

Then, ngOnDestroy handles the unsubscription.

ngOnDestroy(): void {
    this.isAuthorizedSubscription.unsubscribe();
}

The class level variable for _loggedIn is replaced with the following two variables.

isAuthorizedSubscription: Subscription;
isAuthorized: boolean;

The constructor has been greatly simplified and now only takes an instance of the AuthService.

constructor(public authService: AuthService) {
}

Finally, the login and logout functions have changed to match the new function names in the AuthService class.

public login() {
    this.authService.login();
}

public logout() {
    this.authService.logout();
}

Navigation Component UI

In the navmenu.component.html file, a couple of tweaks are required based on the new variable names used above. The first set is related to showing either Login or Logout.

Before:
<li *ngIf="!_loggedIn" [routerLinkActive]="['link-active']">
    <a (click)="login()" [routerLink]="['/login']">
        <span class="glyphicon glyphicon-user"></span> Login
    </a>
</li>

<li *ngIf="_loggedIn" [routerLinkActive]="['link-active']">
    <a (click)="logout()" [routerLink]="['/logout']">
        <span class='glyphicon glyphicon-log-out'></span> Logout
    </a>
</li>

After:
<li [routerLinkActive]="['link-active']">
    <a *ngIf="!isAuthorized" (click)="login()" [routerLink]="['/login']">
        <span class="glyphicon glyphicon-user"></span> Login
    </a>
</li>

<li [routerLinkActive]="['link-active']">
    <a *ngIf="isAuthorized" (click)="logout()">
        <span class='glyphicon glyphicon-log-out'></span> Logout</a>
</li>

The final change in this file was to make the link to fetch-data only show if the user is logging instead of sending the user to an unauthorized view.

Before:
<a [routerLink]="['/fetch-data']">
    <span class='glyphicon glyphicon-th-list'></span> Fetch data
</a>

After:
<a *ngIf="isAuthorized" [routerLink]="['/fetch-data']">
    <span class='glyphicon glyphicon-th-list'></span> Fetch data
</a>

Fetch Data Component

The final changes for the conversion to the new client are in the fetchdata.component.ts and they are only needed because of a rename of the HTTP Get helper in the AuthService.

Before:
authService.AuthGet(apiUrl + 'SampleData/WeatherForecasts').subscribe(result => {

After:
authService.get(apiUrl + 'SampleData/WeatherForecasts').subscribe(result => {

Wrapping Up

This change took a lot of changes, but in the long run, it is going to be a better choice since the new client is focused on Angular. Another great thing about this client is they are looking into ways to handle the first load not remembering the user is logged in due to server side rendering (issue #36).

The finished code for this post can be found here.

Identity Server: Changing Angular OpenID Connect Clients Read More »

JavaScriptServices: What happen to Aurelia, Vue, and Knockout Templates

With the release of Visual Studio 2017 version 15.3 there are now built in web application templates for Angular, React, and React and Redux.

This is an awesome addition and makes creating new applications with the most popular frameworks simple. What do you do if your framework isn’t one of the top 3 options? JavaScriptServices can help out here and has provided templates for Aurelia, Vue, and Knockout in the past.

Where have they gone?

This is where it gets a little tricky as the templates still exist and are still being maintained, but finding them is a little harder at the moment for some reason. Yeoman was how JavaScriptServices was used in the past, but that has now transitioned to using the .NET CLI and can be added using the following.

dotnet new --install Microsoft.AspNetCore.SpaTemplates::*

After that is complete you will see a list of templates that are now available.

Now you can create an Aurelia project using the following command.

dotnet new aurelia

Wrapping up

I was very happy to see that support for the other frameworks hadn’t been dropped. There are a ton of other templates available for dotnet new which can be found here.

 

JavaScriptServices: What happen to Aurelia, Vue, and Knockout Templates Read More »

NDepend Spotlight

Today I am going to be doing a tool spotlight on NDepend. NDepend has a ton of features to help you keep a handle on your applications including the following plus much more.

  • Code Rules
    • 200 default rules with ability to add custom rules using LINQ
  • Quality Gates
  • Visual Studio Integration
  • Build Process Integration
  • Dependency Graph
  • Dependency Matrix
  • Technical Debit Estimation

For full disclosure, NDepend reached out to me to give their tool a try. I am writing based on my experiences with their tool and will be including both the positive and negative aspects of my experience. None of the links in this post are referrals that would in any way provide me any sort of payment.

Installation

The download is a zip file that you then have to find out what you want to do with. This was the first negative I hit with the product. While it isn’t hard to figure out it would be much nicer if this were an installer where I could select what I wanted to install instead of having to look at the getting started docs right away. For non-build usage, the options to run the tool is either via a Visual Studio extension (NDepend.VisualStudioExtension.Installer) or as a stand alone application (VisualNDepend.exe).

I chose to go explore with the Visual Studio extension. As a hint that I didn’t notice until later, VisualNDepend provides an option to install the Visual Studio extension in addition to providing all the functionality of the Visual Studio extension.

Visual Studio Extention

After installing the NDepend extension there will be a new top level NDepend menu in Visual Studio.

With the solution you want to analyze already open select the NDepend > Attach New NDepend Project to Current VS Solution.

This will launch a dialog that allows you to select which assemblies you would like to analyze preloaded with the assemblies for the current application.

As you can see from the dialog there are a lot of options. If your project has other assemblies or solutions that you would like to be included as part of the analyses they are easy to add. When finished adding items to analyze click the Analyze button at the bottom. I am using a small project for this entry and the process took less than 10 seconds. I also tried it on a large project (500k+ lines of code) and it took less than 30 seconds.

After the analyses are complete the extension shows a dialog asking what to do next as well as launching a web page with the results of the analyses if you kept the Build Report check box checked. Following are the options in the dialog.

From here I chose to View NDepend Dashboard, but also make sure and check out the report that the analyses generated as it provides a great summary at the end of all the issues found. The following is a part of the dashboard.

There is a ton of data provided. If you notice at the top there is a Choose Baseline option which would allow comparisons of solutions over time. I can see this view of a project over time is very helpful, but not a feature I will get to explore here.

Exploration

Exploration of the data NDepend provides is something I could spend hours looking at even on a small project. For example, the following is an output to HTML (their output is much prettier than the version that is shown here) of the issues that make up the critical group in the Rules box in the dashboard above.

4 rules Issues Debt Annual Interest Breaking Point Category Full Name
Avoid methods with too many parameters 1 issue 1h 9min 5min 4 522d Project Rules \ Code Smells Rule
Avoid non-readonly static fields 12 issues 32min 4h 0min 48d Project Rules \ Immutability Rule
Avoid namespaces mutually dependent 2 issues 30min 1h 1min 179d Project Rules \ Architecture Rule
Avoid having different types with same name 3 issues 30min 1h 0min 182d Project Rules \ Naming Conventions Rule
Sum: 18 2h 41min 6h 6min 4 933d
Average: 4.5 40min 1h 31min 1 233d
Minimum: 1 30min 5min 48d
Maximum: 12 1h 9min 4h 0min 4 522d
Standard deviation: 4.39 16min 1h 28min 1 899d
Variance: 19.25 34d 979d overflow

Here is the same view inside the Queries and Rules Edit window.

Double click any line will take you to a detail view showing a listing of the rule broken down by project, namespace, and class.

The same window also shows the query that was used to find the rule violations. For example, the above is powered by the following query.

warnif count > 0
from f in Application.Fields
where f.IsStatic && 
     !f.IsEnumValue && 
     !f.IsGeneratedByCompiler &&
     !f.IsLiteral &&
     !f.IsInitOnly

let methodAssigningField = f.MethodsAssigningMe

select new { 
   f, 
   methodAssigningField,
   Debt = (2+8*methodAssigningField.Count()).ToMinutes().ToDebt(),
   Severity = Severity.High
}

The above is CQLinq or Code Query LINQ which is used to query the code model that the NDepend analysis creates. The detail of CQLinq are outside the scope of this post, but based on the above you can see how powerfully this could be.

Other considerations

Based on my usage to get the best value from NDepend your whole team would need to be licensed and making sure new code satisfies with all the rules your team wishes to follow. NDepend has a component that can be used as part of server based build processes which is needed, but I would want to use that component as a fail safe, not as a way to avoid buying licenses. If you use multiple computers it seems that you will need multiple licenses which will cause issues for some users.

Wrapping up

After trying NDepend out for awhile I am still amazed at the amount of data it provides. Not to mention the ability to add new queries and rules of your own. One blog post is never going to be enough to cover even a fraction of what this tool does. It feels like Resharper in it does so much that it takes a lot of time to learn and take advantage of the full set of features it provides.

NDepend Spotlight Read More »

Migration from ASP.NET Core 1.1.x to 2.0

On August 14th .NET Core 2.0 was released including corresponding versions of ASP.NET Core 2.0 and Entity Framework Core 2.0 which got with the finalization of .NET Standard 2.0. The links take you to the release notes for each item.

In this post, I will be covering taking the project used for the ASP.NET Basics series from 1.1.x to the 2.0 release. The starting point of the code can be found here. This post is only going to cover conversion of the Contacts project.

Installation

If you are a Visual Studio user make sure you have the latest version of Visual Studio 2017, which can be found here and at a minimum should be version 15.3.

Next, install the SDK for your operating system. The list of installs can be found here. For development, it is key that you install the SDK, not just the runtime. The following is a preview of what to expect on the download page.

Csproj

The csproj file of the project being upgraded is the best place to start the conversion. The TargetFramework needs to be changed to 2.0.

Before:
<TargetFramework>netcoreapp1.1</TargetFramework>

After:
<TargetFramework>netcoreapp2.0</TargetFramework>

Next, PackageTargetFallback changed to AssetTargetFallback.

Before:
<PackageTargetFallback>$(PackageTargetFallback);dotnet5.6;portable-net45+win8</PackageTargetFallback>

After:
<AssetTargetFallback>$(AssetTargetFallback);portable-net45+win8+wp8+wpa81</AssetTargetFallback>

There is a new Microsoft.AspNetCore.All package that bundles up what used to be a huge list of individual packages. Those individual packages still exist, but this new one wraps them and makes it much easier to get started. The following is the package list before and after.

Before:
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics" Version="1.1.1" />		
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="1.1.1" />		
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="1.1.1" />		
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />		
<PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="1.1.1" />		
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="1.1.1" />		
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />		
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.1" />		
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.1" />		
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.1.0" />		
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="1.1.1" />		
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.1" />		
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="1.1.1" />		
<PackageReference Include="Microsoft.Extensions.Logging" Version="1.1.1" />		
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.1.1" />		
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />		
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="1.1.1" />		
<PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.0" />		
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="1.1.0" />		

After:
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />

Last change in this file is to change the DotNetCliToolReference versions to 2.0.0.

Before:
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
<DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="1.0.0" />
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0" />

After:
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
<DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="2.0.0" />
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />

Program.cs

Program.cs is another area that has been simplified by creating a default builder that does all the same things that were happening before but hide the details. Keep in mind the old version still works and is valid to use if you use case needs it.

Before:
public static void Main(string[] args)
{
    var host = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();

    host.Run();
}

After:
public static void Main(string[] args)
{
    BuildWebHost(args).Run();
}

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
           .UseStartup<Startup>()
           .Build();

Identity

The remaining changes I had to make were all related to Identity. In the Startup class’s Configure function the following change was needed.

Before:
app.UseIdentity();

After:
app.UseAuthentication();

Next, in the ManageLoginsViewModel class, the type of the OtherLogins property changed.

Before:
public IList<AuthenticationDescription> OtherLogins { get; set; }

After:
public IList<AuthenticationScheme> OtherLogins { get; set; }

The SignInManager dropped the GetExternalAuthenticationSchemes function in favor of GetExternalAuthenticationSchemesAsync. This caused changes in a couple of files. First, in the ManageController the following change was made.

Before:
var otherLogins = _signInManager
                  .GetExternalAuthenticationSchemes()
                  .Where(auth => userLogins
                                 .All(ul => auth.AuthenticationScheme != ul.LoginProvider))
                  .ToList();

After:
var otherLogins = (await _signInManager
                   .GetExternalAuthenticationSchemesAsync())
                  .Where(auth => userLogins
                                 .All(ul => auth.Name != ul.LoginProvider))
                  .ToList();

The second set of changes were in the Login.cshtml file. First the function change.

Before:
var loginProviders = SignInManager.GetExternalAuthenticationSchemes().ToList();

After:
var loginProviders = (await SignInManager.GetExternalAuthenticationSchemesAsync()).ToList();

Then the change to deal with the changed property names.

Before:
<button type="submit" class="btn btn-default" 
        name="provider" value="@provider.AuthenticationScheme" 
        title="Log in using your @provider.DisplayName account">
    @provider.AuthenticationScheme
</button>

After:
<button type="submit" class="btn btn-default" 
        name="provider" value="@provider.Name" 
        title="Log in using your @provider.DisplayName account">
    @provider.Name
</button>

Wrapping up

With the changes in the Contacts project now works on ASP.NET Core 2.0!  Make sure to check out Microsoft’s regular migration guide. as well as their identity migration guide. A full list of breaking changes for this release can be found here.

There is a lot more to explore with this new release and I have a lot of projects to update. Don’t worry I won’t be doing a blog post on all of them, but if I do hit any issues I will create a new post of update this one with the fixes. The finished code can be found here.

Migration from ASP.NET Core 1.1.x to 2.0 Read More »