Friday, August 19, 2016

Static Code Analysis in ASP.NET Core

To ensure conformance of coding styles in team, I wanted to enable the Static Code Analysis on our ASP.NET Core project. I spent couple of hours identifying the current version of StyleCop and additional few hours to configure it on my solution. This blog outlines the configuration of my project to perform StyleCop static code analysis and also to override some of the default rules.

For the .NET Compiler Platform ("Roslyn") StyleCop provides the static code analysis. Here is the GitHub location for this tool.

As per the documentation mentioned on the GitHub site, StyleCop can be installed using NuGet Package Manager.

Alternatively you can manually add the dependency in project.json
    "StyleCop.Analyzers": "1.0.0"

It is recommended that the package be marked as build type as shown below:
    "StyleCop.Analyzers": {
      "version": "1.0.0",
      "type": "build"

Once StyleCop is installed, you can notice the warnings after building the project

To effectively utilize StyleCop, it needs to be configured as below:

  • One of the default rule, SA1633, requires that you need to specify the copyright information. Here is the copyright text I am using on top of each class file

// <copyright file="ChartFactory.cs" company="Nootus">
//  Copyright (c) Nootus. All rights reserved.
// </copyright>
// <description>
//  This is factory class which is used to create and format data for displaying charts
// </description>

  • For this copyright to properly work, we need to define a config file
  • Add “stylecop.json” to the project or solution
  • Specify the proper copyrightText. Here is my stylecop.json

  "$schema": "",
  "settings": {
    "documentationRules": {
      "companyName": "Nootus",
      "copyrightText": "Copyright (c) Nootus. All rights reserved."
  • The compiler needs to be told about this config file. For that add the following to the project.json

  "buildOptions": {
    "additionalArguments": [ "/additionalfile:stylecop.json" ]
  • Note that you need to specify the relative path of stylecop.json

The above configuration should enable default rules on the project.

In addition to running the default rules, you can also specify particular rules or override any of the rules. For my requirement, I want to disable the xmlDoc option (rule SA1652). Below are the configuration steps need to disable this rule.
  • Create a rule file where you can specify the override. I am calling this file as stylecop.ruleset. Here is my rule file where I am specifying not to check the SA1652 rule.

<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="Override Rules" Description="Override Rules for the solution." ToolsVersion="14.0">
  <Rules AnalyzerId="StyleCop.Analyzers" RuleNamespace="StyleCop.Analyzers">
    <Rule Id="SA1652" Action="None" />
  •  This rule file needs to be specified in the build option of the compiler. Modify the project.json to include the rulefile as shown below

"buildOptions": {
  "additionalArguments": [ "/ruleset:stylecop.ruleset", "/additionalfile:stylecop.json"]

With the above configuration our project will be ready for the Static Code Analysis by StyleCop. Next step is to get conformance of coding styles in team. Happy coding :)

Monday, July 11, 2016

Middleware - Multi-Tenant Claim Based Identity for ASP.NET Core - Part 4 of 10

This part 4 of 10 part series which outlines my implementation of Multi-Tenant Claim Based Identity. For more details please see my index post.

With ASP.NET Core, Microsoft introduced application pipeline to handle requests and responses. This is roughly similar to HttpModules, but this Middleware behavior significantly differs from HttpModules. HttpModules are event driven, whereas Middleware is a pipeline, so we clearly know the order of execution.

In my Multi-Tenant Claim Based Identity, I am using this Middleware to store the user profile details such as UserId, UserName, CompanyId etc in the current context so that this info can be readily available throughout the application. With ASP.NET Core we use async/await and HttpContext is the not the right way to store this context information, hence I am storing this data into the CallContext. For more details see my other blog post on this ASP.NET Core Async Context Data.

Here is my Middleware code:

public class ProfileMiddleware
    private RequestDelegate next;

    public ProfileMiddleware(RequestDelegate next)
    { = next;

    public async Task Invoke(HttpContext context, SignInManager<ApplicationUser> signInManager, UserManager<ApplicationUser> userManager)
        if (context.User.Identity.IsAuthenticated)
        //automatically logging in in the dev mode
        else if (SiteSettings.IsEnvironment(SecurityConstants.DevEnvironment))
            ApplicationUser user = await userManager.FindByNameAsync(SecuritySettings.NootusProfileUserName);
            await signInManager.SignInAsync(user, false);

        await next(context);


    public void SetNTContext(HttpContext context)
        var claims = context.User.Claims;

        string companyId = context.Request.Headers[SecurityConstants.HeaderCompanyId];
        companyId = companyId ?? context.User.Claims.Where(c => c.Type == NTClaimTypes.CompanyId).Select(c => c.Value).FirstOrDefault();

        NTContextModel model = new NTContextModel()
            UserId = claims.First(c => c.Type == ClaimTypes.NameIdentifier).Value,
            UserName = context.User.Identity.Name,
            FirstName = claims.First(c => c.Type == NTClaimTypes.FirstName).Value,
            LastName = claims.First(c => c.Type == NTClaimTypes.LastName).Value,
            CompanyId = Convert.ToInt32(companyId ?? "0")

        //setting the Group CompanyId
        model.GroupCompanyId = PageService.CompanyClaims[model.CompanyId]?.ParentCompanyId ?? model.CompanyId;

        NTContext.Context = model;

The below are the salient points in the above code:
  • For Authenticated users I am storing the user info in the context. As outlined in my other blog ASP.NET Core Async Context Data, I am using my internal class NTContext to store the context.
  • During Development, I am hardcoding the user and doing a login so that there is no need to login
  • The TenantID, in my case CompanyId, is passed through the Http Headers. I am retrieving this CompanyId from the HttpHeaders and storing this in the Context
  • Similarly I am retrieving User details from the Claims and storing them in the Context as well.

As you see I am using this Middleware to retrieve and store user profile details in the context so that this data is available throughout the application.

Wednesday, June 15, 2016

ASP.NET Core Async Context Data

With classical ASP.NET MVC (wow ASP.NET MVC is already classical), I use HttpContext.Items to pass context sensitive data from one layer to another or from one child control to another child control. Logged in user info is a typical use case for this scenario. On every request I used to get the user profile or user data and store that in the HttpContext and then use that user info throughout the current request.

With ASP.NET Core, HttpContext is not recommended. Further it is recommended to use async/await to take advantage of freeing threads. Please see my other blog “ASP.NET Core / MVC 6 HttpContext.Current” on how to use HttpContext to store the data as done earlier.

Instead of using HttpContext.Items, I decided to use Asynchronous context to pass the data from one layer to another. For this I wrote a static class which creates this context. I am also using this static class to pass the HttpContext also.

Here is the code I used to create the context and hold data in that context:

public static class NTContext
        public static NTContextModel Context
                return (NTContextModel)CallContext.LogicalGetData("MegaMineContext");
                NTContextModel model = value;
                if (model == null)
                    model = new NTContextModel();

                NTContextModel contextModel = Context;

                if (contextModel == null)
                    CallContext.LogicalSetData("MegaMineContext", model);
                    contextModel = Mapper.Map<NTContextModel, NTContextModel>(model, contextModel);


        public static HttpContext HttpContext
                return (HttpContext)CallContext.LogicalGetData("HttpContext");
                CallContext.LogicalSetData("HttpContext", value);


Friday, April 15, 2016

Database Schema - Multi-Tenant Claim Based Identity for ASP.NET Core - Part 3 of 10

This part 3 of 10 part series which outlines my implementation of Multi-Tenant Claim Based Identity. For more details please see my index post.

I implemented Multi-Tenant feature on top the ASP.NET Identity Framework. Hence I will be leveraging the Identity tables and in addition I will have my own database tables.

First briefly look at the Identity tables provided by the ASP.NET Identity Framework. Please note that I renamed these table names to fit with rest of my schema naming convention. Also I created these tables under security database schema. I am utilizing database schemas to logically partition my application. For more details, please look at my other blog post Microservices and Database Schemas

Here is a brief description on these tables and how I intended to use them:

IdentityUser (AspNetUsers): This table as the name suggests contains list of users in application. UserName should be unique. Even for multi-tenancy we need to maintain this unique user across all companies. I am planning to use Email address as user name across all tenants.

IdentityUserLogin (AspNetUserLogins): This is used for connecting to different providers such as facebook etc. As this is not my current requirement, I am not using this functionality.

IdentityUserClaim (AspNetUserClaims): This table contains the claims attached to the user. As there will be numerous claims when using claim based access control, using this table to permission each user is hard. Instead I use this table as an override feature to the role based authorization. So if I want to provide additional claims than what roles provides or remove claims from a user than I use this table.

IdentityRole (AspNetRoles): As the name indicates, this contains all the roles. In my application, roles are dynamically created by the end users (administrators). In addition, the system also provides few super user or administrative roles.

IdentityRoleClaim (AspNetRoleClaims): This table persists the claims attached to a role. Similar to the IdentityRole, this table also gets populated when the user assigns claims for a particular role

In addition to the above tables I created the below tables to fit my requirements outlined in my previous post (Requirements - Multi-Tenant Claim Based Identity for ASP.NET Core)

Here are the details and purpose of these additional tables:

UserProfile: This table contains the Users of the system. As we need to support Multi-Tenancy, I added CompanyId as a foreign key to this table.

Company:  This, as the name indicates, contains the Companies in the system. Company is the tenant key for our system. In addition, I am also providing a group company concept, where there will be a parent company and a bunch of child companies. The system needs to permission this concept also.

UserCompany: This is many-to-many relationship between Company and User. In other words, a Company can have multiple users and a User can belong to multiple companies. If a user has permissions to more than one company, the application should allow User to pick a company and work within that company.

IdentityClaim: This table contains all the claims within the system. This is the master data for the claims.

: This table stores the permissions for each company. With this table we can selectively assign permissions to each company. For example out of 8 modules, we can assign 6 or 7 modules for a company. Similarly within a module, we can remove certain features.

IdentityPage: This table contains all the controller actions (APIs) within the system. This will be a like a fa├žade layer which keeps list of the features exposed by the system.

IdentityMenuPage: This table helps us to dynamically create the menu.

IdentityPageClaim: This contains the claims required for accessing or invoking each page action method. This table will be used for authorizing the user to call the action methods in the system.

IdentityRoleHierarchy: This table helps us to define the relationship between administrative roles. System assumes that there is parent child relationship within the admin roles. For example, a GroupAdmin role will have CompanyAdmin as children, similarly a CompanyAdmin will have ModuleAdmins as children

Finally here is my DbContext code:

public class SecurityDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
    public DbSet<IdentityClaimEntity> IdentityClaims { get; set; }
    public DbSet<IdentityPageEntity> IdentityPages { get; set; }
    public DbSet<IdentityMenuPageEntity> IdentityMenuPages { get; set; }
    public DbSet<IdentityPageClaimEntity> IdentityPageClaims { get; set; }
    public DbSet<IdentityRoleHierarchyEntity> IdentityRoleHierarchies { get; set; }
    public DbSet<IdentityCompanyClaimEntity> IdentityCompanyClaims { get; set; }
    public DbSet<UserProfileEntity> UserProfiles { get; set; }
    public DbSet<UserCompanyEntity> UserCompanies { get; set; }
    public DbSet<CompanyEntity> Companies { get; set; }
    protected override void OnModelCreating(ModelBuilder builder)
        builder.Entity<IdentityRoleHierarchyEntity>(entity =>
            entity.HasKey(e => new { e.RoleId, e.ChildRoleId });

        builder.Entity<UserCompanyEntity>(entity =>
            entity.HasKey(e => new { e.UserProfileId, e.CompanyId });


        //renaming identity tables
        builder.Entity<ApplicationUser>().ToTable("IdentityUser", "security");
        builder.Entity<ApplicationRole>().ToTable("IdentityRole", "security");
        builder.Entity<IdentityRoleClaim<string>>().ToTable("IdentityRoleClaim", "security");
        builder.Entity<IdentityUserClaim<string>>().ToTable("IdentityUserClaim", "security");
        builder.Entity<IdentityUserLogin<string>>().ToTable("IdentityUserLogin", "security");
        builder.Entity<IdentityUserRole<string>>().ToTable("IdentityUserRole", "security");