Saturday, June 30, 2018

Seeding & Extending Users and Roles with ASP.NET Core 2.1 Identity in Visual Studio 2017

In this post I shall describe the steps you need to follow if you want to add more data fields to the standard users & roles database table and seed both users and roles data. The approach being followed is code first development with Entity Framework Core. In order to proceed with this tutorial you need to have the following prerequisites:
  • You are using Visual Studio 2017 running under the Windows 10 operating system
  • You have installed ASP.NET 2.1 Core

Getting Started

In Visual Studio 2017, start a new ASP.NET Core 2.1 application by clicking on File >> New >> Project

Select ASP.NET Core Web Application and name your project with a name like IdentityCore.

Click on the OK button. On the next dialog:
  • select ASP.NET Core 2.1 from the drop-down list
  • select "Web Application (Model-View-Controller)" from the templates
  • click on the "Change Authentication" button and choose "Individual User Accounts"

Click on OK. Run the application by hitting Ctrl + F5 on your keyboard. Click on the Register link on the top-right side of your keyboard to add a new user. 

When you click on the Register button, you may receive a message that looks like this:

Do not be alarmed. The message simple reminds you that the Entity Framework migrations have not been applied yet. Simple click on the blue "Apply Migrations" button then refresh the page in your browser. The home page will display as shown below:


Click on Logout in the top-right corner.

Suppose we want to capture more data about the user, in addition to email and password. Let us assume we want to extend user data with the following properties:

FirstName
LastName
Street
City
Province
PostalCode

An easy way to do this is to create a new class that extends IdentityUser and adds the above properties. In the Models folder, add a new class named ApplicationUser and add to it the following class code:

    public class ApplicationUser : IdentityUser
    {

        public ApplicationUser() : base() { }

        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Street { get; set; }
        public string City { get; set; }
        public string Province { get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }
    }

We may also wish to extend the standard roles table with these properties:

Description
CreatedDate

Just like we did with users, we will also create another class for roles that inherits from IdentityRole. In the Models folder, create a new class named ApplicationRole and add to it the following class code:

    public class ApplicationRole : IdentityRole
    {

        public ApplicationRole() : base() { }

        public ApplicationRole(string roleName) : base(roleName) { }

        public ApplicationRole(string roleName, string description,
            DateTime createdDate)
            : base(roleName)
        {
            base.Name = roleName;

            this.Description = description;
            this.CreatedDate = createdDate;
        }

        public string Description { get; set; }
        public DateTime CreatedDate { get; set; }

    }

Edit Data/ApplicationDbContext.cs file and get ApplicationDbContext to inherit from IdentityDbContext<ApplicationUser, ApplicationRole, string>. The ApplicationDbContext class code should look like this:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string> {
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options) { }
}

Let us now create some sample data for roles and users. Create class named DummyData in Data folder, then add to it the following method:

public class DummyData {
    public static async Task Initialize(ApplicationDbContext context,
                          UserManager<ApplicationUser> userManager,
                          RoleManager<ApplicationRole> roleManager)
    {
        context.Database.EnsureCreated();

        String adminId1 = "";
        String adminId2 = "";

        string role1 = "Admin";
        string desc1 = "This is the administrator role";
        
        string role2 = "Member";
        string desc2 = "This is the members role";

        string password = "P@$$w0rd";

        if (await roleManager.FindByNameAsync(role1) == null) {
            await roleManager.CreateAsync(new ApplicationRole(role1, desc1, DateTime.Now));
        }
        if (await roleManager.FindByNameAsync(role2) == null) {
            await roleManager.CreateAsync(new ApplicationRole(role2, desc2, DateTime.Now));
        }

        if (await userManager.FindByNameAsync("aa@aa.aa") == null) {
            var user = new ApplicationUser {
                UserName = "aa@aa.aa",
                Email = "aa@aa.aa",
                FirstName = "Adam",
                LastName = "Aldridge",
                Street = "Fake St",
                City = "Vancouver",
                Province = "BC",
                PostalCode = "V5U K8I",
                Country = "Canada",
                PhoneNumber = "6902341234"
            };

            var result = await userManager.CreateAsync(user);
            if (result.Succeeded) {
                await userManager.AddPasswordAsync(user, password);
                await userManager.AddToRoleAsync(user, role1);
            }
            adminId1 = user.Id;
        }

        if (await userManager.FindByNameAsync("bb@bb.bb") == null) {
            var user = new ApplicationUser {
                UserName = "bb@bb.bb",
                Email = "bb@bb.bb",
                FirstName = "Bob",
                LastName = "Barker",
                Street = "Vermont St",
                City = "Surrey",
                Province = "BC",
                PostalCode = "V1P I5T",
                Country = "Canada",
                PhoneNumber = "7788951456"
            };

            var result = await userManager.CreateAsync(user);
            if (result.Succeeded) {
                await userManager.AddPasswordAsync(user, password);
                await userManager.AddToRoleAsync(user, role1);
            }
            adminId2 = user.Id;
        }

        if (await userManager.FindByNameAsync("mm@mm.mm") == null) {
            var user = new ApplicationUser {
                UserName = "mm@mm.mm",
                Email = "mm@mm.mm",
                FirstName = "Mike",
                LastName = "Myers",
                Street = "Yew St",
                City = "Vancouver",
                Province = "BC",
                PostalCode = "V3U E2Y",
                Country = "Canada",
                PhoneNumber = "6572136821"
            };

            var result = await userManager.CreateAsync(user);
            if (result.Succeeded) {
                await userManager.AddPasswordAsync(user, password);
                await userManager.AddToRoleAsync(user, role2);
            }
        }

        if (await userManager.FindByNameAsync("dd@dd.dd") == null) {
            var user = new ApplicationUser {
                UserName = "dd@dd.dd",
                Email = "dd@dd.dd",
                FirstName = "Donald",
                LastName = "Duck",
                Street = "Well St",
                City = "Vancouver",
                Province = "BC",
                PostalCode = "V8U R9Y",
                Country = "Canada",
                PhoneNumber = "6041234567"
            };

            var result = await userManager.CreateAsync(user);
            if (result.Succeeded) {
                await userManager.AddPasswordAsync(user, password);
                await userManager.AddToRoleAsync(user, role2);
            }
        }
    }
}

In the Startup class, replace the call to services.AddDefaultIdentity so that it uses the new ApplicationUser. Add the call to AddDefaultUI with the following code replacement:

services.AddIdentity<ApplicationUser, ApplicationRole>(
    options => options.Stores.MaxLengthForKeys = 128)
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultUI()
    .AddDefaultTokenProviders();

Edit Views/Shared/_LoginPartial.cshtml and change:

@inject SignInManager<IdentityUser> SignInManager
@inject UserManager<IdentityUser> UserManager

TO


@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

We will use the magic of dependency injection to make available to us the ApplicationDbContext, RoleManager and UserManager objects in the Configure() method in Startup.cs. Change the signature of the Configure() method by adding additional arguments (UserManager & RoleManager) so that it looks like this:

public void Configure(IApplicationBuilder app, 
  IHostingEnvironment env,
  ApplicationDbContext context,
  RoleManager<ApplicationRole> roleManager,
  UserManager<ApplicationUser> userManager
)
{ . . . . . }

Add the following to the bottom of the Configure() method in Startup.cs:

DummyData.Initialize(context, userManager, roleManager).Wait();// seed here

Note that in the Data/Migrations folder there are Entity Framework Code First migrations files that were added by the initial Visual Studio project template.


Since we changed the model for both users and roles, we need to add another migration and subsequently update the database. Therefore, execute the following commands from inside the Package Manager Console (Tools >> Nuget Package Manager >> Package Manager Console):

Add-Migration ExtendedUserRole -Context ApplicationDbContext

Update-Database -Context ApplicationDbContext

At this stage the tables are created, however data is not yet seeded. Let us run our application so that the sample roles and users get seeded. Hit CTRL + F5 on your keyboard. When the application starts, Logout if you are already logged in.

To prove that user and role data have been successfully seeded, login with one of the below credentials that were previously seeded:

Email: a@a.a    Password: P@$$w0rd
Email: b@b.b    Password: P@$$w0rd
Email: d@d.d    Password: P@$$w0rd
Email: m@m.m    Password: P@$$w0rd


The next task we need to accomplish is to modify the registration page so that the application can capture extended data such as First Name, Last Name, Street, City, Province, Postal Code and Country. ASP.NET Core 2.1 (and later) provide ASP.NET Core Identity as a Razor Class Library. This means that the registration UI is baked into the assemblies and is surfaced with the .AddDefaultUI() option with the services.AddIdentity() command in the ConfigureServices() method in Startup.cs.

Since we need to modify the registration controller and view, we instruct the scaffolder to generate the code used for registration. To do this, right-click on the project node in the Solution Explorer pane then:  Add >> New Scaffolded Item:


On the next Add Scaffold dialog, click on Identity on the left side, highlight Identity in the middle pane then click on the Add button.

On the Add Identity dialog, enable the "Override all files" checkbox, select the ApplicationDbContext class then click on the Add button.

Many Razor view pages will be generated for you under folder Areas/Identity/Pages/Account.


Edit the code-behind file Areas\Itentity\Pages\Account\Register.cshtml.cs. Add the following properties to the InputModel class:

[Required]
[DataType(DataType.Text)]
[StringLength(50, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 2)]
[Display(Name ="First Name")]
public string FirstName { get; set; }

[Required]
[DataType(DataType.Text)]
[StringLength(50, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 2)]
[Display(Name = "Last Name")]
public string LastName { get; set; }

[DataType(DataType.Text)]
[MaxLength(50)]
public string Street { get; set; }

[DataType(DataType.Text)]
[MaxLength(50)]
public string City { get; set; }

[DataType(DataType.Text)]
[MaxLength(50)]
public string Province { get; set; }

[DataType(DataType.Text)]
[MaxLength(15)]
[Display(Name = "Postal Code")]
public string PostalCode { get; set; }

[DataType(DataType.Text)]
[MaxLength(35)]
public string Country { get; set; }

In the same  \Itentity\Pages\Account\Register.cshtml.cs code-behind file, edit the code in the OnPostAsync() method so that line:

var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email };

is changed to:

var user = new ApplicationUser {
  UserName = Input.Email,
  Email = Input.Email,
  FirstName = Input.FirstName,
  LastName = Input.LastName,
  Street = Input.Street,
  City = Input.City,
  Province = Input.Province,
  PostalCode = Input.PostalCode,
  Country = Input.Country
};

Next, let's update the UI. Edit the Razor view page Areas\Itentity\Pages\Account\Register.cshtml. Add the following markup to the form right before the email block:

<div class="form-group">
  <label asp-for="Input.FirstName"></label>
  <input asp-for="Input.FirstName" class="form-control" />
  <span asp-validation-for="Input.FirstName" class="text-danger"></span>
</div>
<div class="form-group">
  <label asp-for="Input.LastName"></label>
  <input asp-for="Input.LastName" class="form-control" />
  <span asp-validation-for="Input.LastName" class="text-danger"></span>
</div>
<div class="form-group">
  <label asp-for="Input.Street"></label>
  <input asp-for="Input.Street" class="form-control" />
  <span asp-validation-for="Input.Street" class="text-danger"></span>
</div>
<div class="form-group">
  <label asp-for="Input.City"></label>
  <input asp-for="Input.City" class="form-control" />
  <span asp-validation-for="Input.City" class="text-danger"></span>
</div>
<div class="form-group">
  <label asp-for="Input.Province"></label>
  <input asp-for="Input.Province" class="form-control" />
  <span asp-validation-for="Input.Province" class="text-danger"></span>
</div>
<div class="form-group">
  <label asp-for="Input.PostalCode"></label>
  <input asp-for="Input.PostalCode" class="form-control" />
  <span asp-validation-for="Input.PostalCode" class="text-danger"></span>
</div>
<div class="form-group">
  <label asp-for="Input.Country"></label>
  <input asp-for="Input.Country" class="form-control" />
  <span asp-validation-for="Input.Country" class="text-danger"></span>
</div>

Run the web application and click on the Register button on the top-right side.

When you click on the register button all the user data is saved in the database. You can verify that data has indeed been saved by viewing data in the AspNetUsers database table using "SQL Server Object Explorer":


We have succeeded in seeding user and role data and subsequently updating the registration page so that additional user data is captured. Thanks for coming this far in the tutorial.

References:

ASP.NET Core 2.1.0-preview1: Introducing Identity UI as a library

Tuesday, June 26, 2018

ASP.NET Core 2.1 MVC Code 1st Development with EF in Visual Studio

This post introduces the reader to developing an ASP.NET Core 2.1 application that uses the Code 1'st approach with SQL Server. Before you proceed with this tutorial, make sure that the following pre-requisites are met:
  • You are using the Windows 10 Operating System
  • You have Visual Studio 2017 installed on your computer
  • ASP.NET Core 2.1 is installed on your computer
The objective is to model NHL (National Hockey League) teams and players as shown below:

Team

TeamName
City
Province
Country

Player

PlayerId
FirstName
LastName
Position

The Visual Studio Project

Start your Visual Studio 2017
File >> New >> Project...
Select ASP.NET Core Web Application
Give your project a name (like MvcEfCore)


On the next dialog, after you click on OK, choose ASP.NET Core 2.1 and Web Application (Model-View-Controller). Click on the Change Authentication button and select Individual User Accounts.


Click on OK.

Let us add two classes (Team & Player) that represent the entities that were mentioned beforehand. Create two class files in the Models folder: Team.cs & Player.cs. Replace the class code with the following:

Team class

public class Team {
    [Key]
    [MaxLength(30)]
    public string TeamName { get; set; }
    public string City { get; set; }
    public string Province { get; set; }
    public string Country { get; set; }

    public List<Player> Players { get; set; }
}

Make sure you resolve the namespaces for the "Key" and "MaxLength" classes.

Player class

public class Player {
    public int PlayerId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Position { get; set; }

    public string TeamName { get; set; }
    public Team Team { get; set; }
}

Next we need to add a Entity Framework context class. Create a class file named NhlContext in the Data folder. Replace the class code with the following:

    public class NhlContext : DbContext
    {
        public NhlContext(DbContextOptions options) : base(options) { }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
        }

        public DbSet<Team> Teams { get; set; }
        public DbSet<Player> Players { get; set; }
    }

Make sure you resolve the inherited DbContext, Team, and Player classes.

Build your application to ensure that you do not have any compiler errors.
Add the following code to the ConfigureServices() method in Startup.cs:

services.AddDbContext<NhlContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

The above code ensures that we can use the NhlContext class in dependency injection and that it uses the DefaultConnection connection string in appsettings.json.

Open appsettings.json for editing and change the database name so that it is simply NHL and not a long non-sense name. The appropriate connection string setting in appsettings.json will look like this:

"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=NHL;Trusted_Connection=True;MultipleActiveResultSets=true"

Developers prefer having sample data when building data driven applications. Therefore we will create some dummy data to ensure that our application behaves as expected. Create a class file named DummyData in the Data directory and add to it the following code:

public class DummyData {
  public static void Initialize(IApplicationBuilder app) { 
    using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope()) {
      var context = serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
      context.Database.EnsureCreated();
      //context.Database.Migrate();

      // Look for any teams.
      if (context.Teams!=null && context.Teams.Any()) {
          return;   // DB has already been seeded
      }

      var teams = DummyData.GetTeams().ToArray();
      context.Teams.AddRange(teams);
      context.SaveChanges();

      var players = DummyData.GetPlayers(context).ToArray();
      context.Players.AddRange(players);
      context.SaveChanges();
    }
  }

    public static List<Team> GetTeams() {
        List<Team> teams = new List<Team>() {
            new Team() {
                TeamName="Canucks",
                City="Vancouver",
                Province="BC",
                Country="Canada",
            },
            new Team() {
                TeamName="Sharks",
                City="San Jose",
                Province="CA",
                Country="USA",
            },
            new Team() {
                TeamName="Oilers",
                City="Edmonton",
                Province="AB",
                Country="Canada",
            },
            new Team() {
                TeamName="Flames",
                City="Calgary",
                Province="AB",
                Country="Canada",
            },
            new Team() {
                TeamName="Leafs",
                City="Toronto",
                Province="ON",
                Country="Canada",
            },
            new Team() {
                TeamName="Ducks",
                City="Anaheim",
                Province="CA",
                Country="USA",
            },
            new Team() {
                TeamName="Lightening",
                City="Tampa Bay",
                Province="FL",
                Country="USA",
            },
            new Team() {
                TeamName="Blackhawks",
                City="Chicago",
                Province="IL",
                Country="USA",
            },
        };

        return teams;
    }

    public static List<Player> GetPlayers(NhlContext context) {
        List<Player> players = new List<Player>() {
            new Player {
                FirstName = "Sven",
                LastName = "Baertschi",
                TeamName = context.Teams.Find("Canucks").TeamName,
                Position = "Forward"
            },
            new Player {
                FirstName = "Hendrik",
                LastName = "Sedin",
                TeamName = context.Teams.Find("Canucks").TeamName,
                Position = "Left Wing"
            },
            new Player {
                FirstName = "John",
                LastName = "Rooster",
                TeamName = context.Teams.Find("Flames").TeamName,
                Position = "Right Wing"
            },
            new Player {
                FirstName = "Bob",
                LastName = "Plumber",
                TeamName = context.Teams.Find("Oilers").TeamName,
                Position = "Defense"
            },
        };

        return players;
    }
}


Resolve all outstanding namespaces.

Add the following code to seed data to the end of the Configure() method in Startup.cs:

DummyData.Initialize(app);

It is time to run some migration script. This can be done either at the terminal window or in the package manager console.

Option 1: Package Manager Console

To access the package manager console, click on Tools >> NuGet Package Manager >> Package Manager Console. This will open a window in a bottom pane in Visual Studio.

Type the following commands:

Add-Migration InitialCreate -Context NhlContext -o Data/Migrations/NHL
Update-Database -Context NhlContext

The first command produces the code that is needed to create the Players and Teams tables in the database. This code will be found in the Data/Migrations/NHL folder.

The second command will actually create the Teams & Players tables in the database.

Option 2: Terminal window using dotnet CLI

Drop into a terminal window in the project folder that contains the .csproj file.

Type the following dotnet CLI commands:

dotnet ef migrations add InitialCreate -c NhlContext -o Data/Migrations/NHL
dotnet ef database update -c NhlContext

Test Application

We are now ready to run the application. Hit Ctrl+F5 on your keyboard. The application will run and will look like this:


Of course there is no sight of the data that was created. To view the sample data in Visual Studio, click on View >> SQL Server Object Explorer. This opens up a pane in Visual Studio. Expand nodes database server >> Databases >> NHL >> Tables.



Right-click on dbo.Teams then select View Data. You should see Teams sample data in the database.


Likewise, view Players sample data.


Notice that the last column in the Players entity is a foreign key into the Teams entity.

Let us now scaffold the MVC controllers for both of these entities. Back in Solution Explorer, right-click on Controllers then select Add >> Controller. Select "MVC Controller with views, using Entity Framework".


Choose Team for Model class and NhlContext for Data context class.

When you click on the Add button, the controller for Teams is scaffold-ed for you. This includes the action methods for displaying, creating, editing and deleting data.

Just like you created a controller for the Team table, do the same for the Player table.


To view the output of the controllers created, you can run the application by hitting Ctrl + F5 then add either /teams or /players to view the Teams or Players controllers respectively.

The Teams controller




The Players controller


There is one thing we need to fix in the Teams index view. Since team name is a primary key it does not display in the tabls. The team-name is important to us so we need to modify Views/Teams/Index.cshtml. Open the file in Visual Studio and add the following HTML code as the first column title in the table:

<th>
@Html.DisplayNameFor(model => model.TeamName)
</th>

Also, add the following column data to the table with this HTML code:

<td>
@Html.DisplayFor(modelItem => item.TeamName)
</td>

When you run the application with /teams added to the address line, you should see team names.

Let us add menu items on the home page of our application for Team & Player so we do not have to always access these controllers by typing into the address line. To do this, edit Views/Shared/_Layout.cshtml. Add the following HTML code right before the closing </ul> tag:

<li><a asp-action="Index" asp-area="" asp-controller="Teams" href="https://www.blogger.com/null">Team</a></li>
<li><a asp-action="Index" asp-area="" asp-controller="Players" href="https://www.blogger.com/null">Player</a></li>

Now, when you run the application you will see two new menu buttons for Team & Player.


I hope you found this article useful. Meantime, cheers until we meet again.