Showing posts with label SQL Server Express. Show all posts
Showing posts with label SQL Server Express. Show all posts

Monday, October 14, 2019

Produce & Consume a .NET Core 3.0 gRPC DB Driven Service

gRPC is a method of web communication like WCF. .NET Remoting, SOAP, etc. It is a standard created by Google and is widely used. It relies on known configuration shared between client and server. Contracts are called protocol buffers. 

gRPC was introduces to the world of .NET with .NET Core 3.0. In this tutorial we shall build a gRPC service that talks with LocalDB using Entity Framework.

Source Code: https://github.com/medhatelmasry/GrpcWorld.git

Video:  https://youtu.be/Xh47x_C-aMM

Let’s build a gRPC server then client.
You need .NET Core 3.0
Visual Studio 2019 >> Create New Project >> gRPC Service

Project Name: GrpcServer
Solution Name: GrpcRocks


Similar to Web API, this service sits and listens for calls.

The proto file defines the contract between the server and the client.

greet.proto

syntax = "proto3";
option csharp_namespace = "GrpcServer";
package Greet;
// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply);
}
// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}
If you navigate to the definition of GreeterBase, you will find a generated file named GreetGrpc.cs where the abstract class is defined. This file is regenerated with every build. If you hit CTRL F5, this is what you will see:
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: E:\play\gRPC\GrpcDemo\GrpcServer
When you point your browser to https://localhost:5001, this is what appears:

Communication with gRPC endpoints must be made through a gRPC client. 
To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909 
This tells us that we need to create a client.

Add a console App to the solution.

Name the project GrpcClient.

Add the following three packages to GrpcClient project:
dotnet add package Google.Protobuf
dotnet add package Grpc.Net.Client
dotnet add package Grpc.Tools
Copy the Protos folder from the server project to the client project.

Edit the GrpcClient.csproj file.

Change : <Protobuf Include="Protos\greet.proto" GrpcServices="Server" />
To: <Protobuf Include="Protos\greet.proto" GrpcServices="Client" />

Rebuild the CLIENT app.

Replace the Main() method in Program.cs with this code:
static async Task Main(string[] args) {
  var input = new HelloRequest { Name = "Jane Bond" };
  var channel = GrpcChannel.ForAddress("https://localhost:5001");
  var client = new Greeter.GreeterClient(channel);
  var reply = await client.SayHelloAsync(input);
  Console.WriteLine(reply.Message);
  Console.ReadLine();
}
Right-click on solution >> Properties.

Select “Multiple startup projects”.

Choose Start for both projects, but make GrpcServer start before GrpcClient.


CTRL F5. This is the output:

Student Database Model

Add the following packages to the GrpcService project:
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.SqlServer.Design
dotnet add package Microsoft.EntityFrameworkCore.Tools
dotnet add package Grpc.Tools
Add this connection string to the appsettings.json file:
"ConnectionStrings": {
  "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=School;Trusted_Connection=True;MultipleActiveResultSets=true"
},
Create Data & Models folders.

Add the following Student class to the Models folder:
 public class Student {
  public int StudentId { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string School { get; set; }
}
Add the following database context class named SchoolDbContext to the Data folder:
public class SchoolDbContext  : DbContext {
  public SchoolDbContext (DbContextOptions options) : base(options) { }
  protected override void OnModelCreating(ModelBuilder builder) {
    builder.Entity<Student>().HasData(
      GetStudents()
    );
  }
  public DbSet<Student> Students { get; set; }
  private static List<Student> GetStudents() {
    List<Student> students = new List<Student>() {
      new Student() {    // 1
        StudentId=11,
        FirstName="Ann",
        LastName="Fox",
        School="Nursing",                
      },
      new Student() {    // 2
        StudentId=22,
        FirstName="Sam",
        LastName="Doe",
        School="Mining",                
      },
      new Student() {    // 3
        StudentId=33,
        FirstName="Sue",
        LastName="Cox",
        School="Business",                
      },
      new Student() {    // 4
        StudentId=44,
        FirstName="Tim",
        LastName="Lee",
        School="Computing",                
      },
      new Student() {    // 5
        StudentId=55,
        FirstName="Jan",
        LastName="Ray",
        School="Computing",                
      },
    };
    return students;
  }
}
We will need access to the Configuration object in Startup class. Therefore add this instance variable and constructor to Startup.cs:
private IConfiguration _configuration { get; }
public Startup(IConfiguration configuration) {
  _configuration = configuration;
}
Add the following code to ConfigureServices() method in the Startup.cs file:
services.AddDbContext<SchoolDbContext>(options =>
  options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection")));

Rebuild the SERVER app.

Now we can add migrations. Execute the following commands from within a terminal window in the GrpcServer folder:
dotnet-ef migrations add InitialCreate –o Data/Migrations
dotnet-ef database update
Check the database to make sure that tables and data were created:

Students Service

Let us setup our own gRPC service. Comment out the content of the Main() method on the client side Program.cs.

Inside the Protos folder in GrpcServer project, add a new file named students.proto.


The content of students.proto is:
syntax = "proto3";
option csharp_namespace = "GrpcServer.Protos";
// The student service definition.
service RemoteStudent {
  rpc GetStudentInfo (StudentLookupModel) returns (StudentModel);
}
// The request message 
message StudentLookupModel {
  int32 studentId = 1;
}
// The response message 
message StudentModel {
  string studentId = 1;  
  string firstName = 2;
  string lastName = 3;
  string school = 4;
}
Right-click on students.proto >> Properties.

Set “Build Action” value to “Protobuf compiler”. Note: if you do not see this option then you are missing the Grpc.Tools package.

Set “gRPC Stub Classes” value to “Server only”.

Rebuild the SERVER app.

Add a class named StudentsService into the Services folder. Contents of StudentsService.cs are:
public class StudentsService : RemoteStudent.RemoteStudentBase {
  private readonly ILogger<StudentsService> _logger;
  private readonly SchoolDbContext _context;
  public StudentsService(ILogger<StudentsService> logger, SchoolDbContext context) {
    _logger = logger;
    _context = context;
  }

  public override Task<StudentModel> GetStudentInfo(StudentLookupModel request, ServerCallContext context)
  {
    StudentModel output = new StudentModel();
    var student = _context.Students.Find(request.StudentId);
    _logger.LogInformation("Sending Student response");
    if (student != null) {
      output.StudentId = student.StudentId;
      output.FirstName = student.FirstName;
      output.LastName = student.LastName;
      output.School = student.School;
    }
    return Task.FromResult(output);
  }
}
On the server-side GrpcServer project, in Startup.cs file’s Configure() method, add the following endpoint mapping:
endpoints.MapGrpcService<StudentsService>();

Rebuild the SERVER app.

Copy students.proto from GrpcServer project to GrpcClient project.

In the GrpcClient.csproj file, change Server to Client for Protos\students.proto.

Rebuild the SERVER & CLIENT apps.

Except for the Console.ReadLine() statement, comment previous code in Main() method on client-side Program.cs and, instead, add this code:
var channel = GrpcChannel.ForAddress("https://localhost:5001");
var studentClient = new RemoteStudent.RemoteStudentClient(channel);
var studentInput = new StudentLookupModel { StudentId = 33 };
var studentReply = await studentClient.GetStudentInfoAsync(studentInput);
Console.WriteLine($"{studentReply.FirstName} {studentReply.LastName}");
Run application. You should see this result:



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

Friday, March 16, 2018

Dockerising both ASP.NET Core 2.0 and SQL Server Express in Windows containers

In a previous post I showed how you can have an ASP.NET Core 2.0 application work with a containerized SQL Server Express database server running in a Windows container. In this post I will take this one step further by also containerizing the ASP.NET Core 2.0 application.

Please go through my previous post before continuing with this tutorial.

We will generate the release version of the application by executing the following command from a terminal window in the root directory of your ASP.NET 2.0 project:

dotnet publish --framework netcoreapp2.0 --configuration Release --output dist

The above command instructs the dotnet utility to produce the release version of the application in the dist directory. This results in output similar to the following:

Microsoft (R) Build Engine version 15.6.82.30579 for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

  Restore completed in 340.14 ms for E:\_aspnet\_docker\AspCoreSqlExpress\AspCoreSqlExpress.csproj.
  Restore completed in 340.57 ms for E:\_aspnet\_docker\AspCoreSqlExpress\AspCoreSqlExpress.csproj.
  Restore completed in 339.79 ms for E:\_aspnet\_docker\AspCoreSqlExpress\AspCoreSqlExpress.csproj.
  Restore completed in 346.67 ms for E:\_aspnet\_docker\AspCoreSqlExpress\AspCoreSqlExpress.csproj.
  AspCoreSqlExpress -> E:\_aspnet\_docker\AspCoreSqlExpress\bin\Debug\netcoreapp2.0\AspCoreSqlExpress.dll
  AspCoreSqlExpress -> E:\_aspnet\_docker\AspCoreSqlExpress\dist\

If you inspect the dist directory, you will see content similar to the following:


The highlighted file in the above folder screen capture is my main DLL file that is the entry point into the web application.

Let us run the release version of the web application. To do this, change directory to the dist directory with the following terminal instruction:

cd dist

You can then run your main DLL file. In my case, this file is AspCoreSqlExpress.dll. I executed the following command:

dotnet AspCoreSqlExpress.dll

This generates an understandable error, if the SQL Server Express container is not running, because the application is unable to connect to a database:

Application startup exception: System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) ---> System.ComponentModel.Win32Exception (0x80004005): The network path was not found

Contents of the /dist folder give us a good idea about ASP.NET Core 2.0 artifacts that need to be copied into a container. We shall simply copy contents of the dist directory into a Docker container that has the .NET Core 2.0 runtime.

Return to the root directory of your project by typing the following in a terminal window:

cd ..

Code in Startup.cs will need to be modified so that we can pass environment variables into the ASP.NET Core application. Therefore, open Startup.cs in your favorite editor and find method ConfigureServices(). Comment out (or delete) the following code:

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

Replaced the above code with:

var host = Configuration["DBHOST"] ?? "localhost";
var db = Configuration["DBNAME"] ?? "AspCoreSqlExpress";
var port = Configuration["DBPORT"] ?? "1433";
var username = Configuration["DBUSERNAME"] ?? "sa";
var password = Configuration["DBPASSWORD"] ?? "Sql!Expre55";

string connStr = $"Data Source={host},{port};Integrated Security=False;";
connStr += $"User ID={username};Password={password};Database={db};";
connStr += $"Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";

services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connStr));

Five environment variables are used in the database connection string. These are: DBHOST, DBNAME, DBPORT, DBUSERNAME and DBPASSWORD. If these environment variables are not found then they will take up default values: localhost, AspCoreSqlExpress, 1433, sa and Sql!Expre55 respectively.

We need to create a Windows docker image that will contain the .NET Core 2.0 runtime. A suitable image for this purpose is: microsoft/aspnetcore:2.0-nanoserver-sac2016

Create a text file named Dockerfile.windows and add to it the following content:

FROM microsoft/aspnetcore:2.0-nanoserver-sac2016
COPY dist /app
WORKDIR /app
EXPOSE 80/tcp
ENV ASPNETCORE_URLS http://+:80
ENTRYPOINT ["dotnet", "AspCoreSqlExpress.dll"]

Above are instructions to create a Windows Docker image that will contain our ASP.NET Core 2.0 application. I explain each line below:

FROM microsoft/aspnetcore:2.0-nanoserver-sac2016 Base Windows image microsoft/aspnetcore:2.0-nanoserver-sac2016 will be used
COPY dist /app Contents of the dist directory on the host computer will be copied to directory /app in the container
WORKDIR /app The working directory in the container is /app
EXPOSE 80/tcp Port 80 will be exposed in the container
ENV ASPNETCORE_URLS http://+:80 Expose port 80 for the Web API traffic
ENTRYPOINT ["dotnet", "AspCoreSqlExpress.dll"] The main ASP.NET Core 2.0 web application will be launched by executing "dotnet AspCore4Docker.dll"

There is a risk that the web application container (mvc) starts earlier than the SQL Server container. We need to figure out a way to have the web application wait for the database server to be ready. We can use a PowerShell script to accomplish this task. Create a PowerShell file named wait4port1433.ps1 in the root of the ASP.NET Core 2.0 web application. Add to it the following script:

do {
  Write-Host "waiting..."
  sleep 3      
} until(Test-NetConnection db -Port 1433 | ? { $_.TcpTestSucceeded } )

dotnet AspCoreSqlExpress.dll

The above PowerShell script waits until port 1433 is available on the db container. Once the port is available then it will start the web application by running dotnet demo-docker.dll.

Open the .csproj file and add this markup just before the closing </Project> tag:

<ItemGroup>
   <Content Include="wait4port1433.ps1" CopyToOutputDirectory="Always" />
</ItemGroup>

The above markup ensures that the PowerShell script file is published together with all other required files into the dist folder. After saving the .csproj file, remove the dist folder and re-publish your web application by running the following pair of commands from a terminal window:

rmdir dist /S /Q
dotnet publish --framework netcoreapp2.0 --configuration Release --output dist

We will next compose a docker yml file that orchestrates the entire system which involves two Windows containers: a SQL Server Express database container and a container that holds our web application. In the root folder of your application, create a text file named docker-compose.yml and add to it the following content:

version: '3'

services:
  db:
    image: microsoft/mssql-server-windows-express:2016
    volumes:
       - sqldatavol:c:\sqldata
    restart: always
    networks:
      - aspsqlnet
    environment:
      - sa_password=Sql!Expre55
      - ACCEPT_EULA=Y

  mvc:
    build:
      context: .
      dockerfile: Dockerfile.windows
    depends_on:
      - db
    networks:
      - aspsqlnet
    ports:
      - "8888:80"
    #restart: always
    environment:
      - DBHOST=db
      - DBNAME=sql-docker
      - DBPORT=1433
      - DBUSERNAME=sa
      - DBPASSWORD=Sql!Expre55
      - ASPNETCORE_ENVIRONMENT=Development
    entrypoint: powershell "c:\app\wait4port1433.ps1"

volumes:
  sqldatavol:

networks:
  aspsqlnet:

Below is an explanation of what this file does.

We will have two Windows containers. Each container is considered to be a service. The first service is named db and will host SQL Server Express. The second service is named mvc and will host our ASP.NET Core 2.0 web application.

The most current version of docker-compose is version 3. This is the first line in our docker-compose.yml file.

The SQL Server Express Container

image
Image microsoft/mssql-server-windows-express:2016 will be used for the SQL Server Express container.

volumes
A folder on the host machine named sqldatavol is mapped to folder c:\sqldata in the container. This is so that data is persisted on the host machine in case the container is destroyed as we do not want to lose valuable data.

restart
restart: always is so that if the container stops, it is automatically restarted.

networks
The db container will exist in a virtual network named aspsqlnet.

environment
The sa password will be Sql!Expre55 when SQL Server Express is configured. This is set by the sa_password environment variable. Environment variable ACCEPT_EULA pertains to acceptance of the End-User Licensing Agreement, which is a required setting for the SQL Server image.

The ASP.NET Core 2.0 Web Application Container

build
The container will be built using the instructions in the Dockerfile.windows file and the context used is the current directory.

depends_on
depends_on indicates that the web application relies on the SQL Server Express container (db) to properly function.

networks
The mvc container will also exist in a virtual network named aspsqlnet.

ports
Port 80 in the mvc container is mapped to port 8888 on the host computer.

environment
The environment variables needed by the web app are:

- DBHOST pointing to the SQL Server Express service
- DBNAME is the name we wish to give to the database
- DBPORT is the port number that SQL Server Express is listening on
- DBUSERNAME is the database server user-name. This is set to the admin user-name 'sa'
- DBPASSWORD is the password for user-name 'sa'.
- ASPNETCORE_ENVIRONMENT is set to Development. In reality, you should change this to Production once you determine that your web application container works as expected.

entrypoint
We override the entry point declared in Dockerfile.windows. This entry point calls the PowerShell script file wait4port1433.ps1 that waits for port 1433 to exist. Once it becomes available, it then starts the web application by running dotnet demo-docker.dll.

Running the yml file

To find out if this all works, go to a terminal window in the root folder of the ASP.NET Core 2.0 application and run the following command:

docker-compose up

Point your browser to http://localhost:8888/ and you should see the main web page. To ensure that the database works properly, register a user by clicking on the Register link in the top right corner.

In my case, I received confirmation that a user was indeed registered:


As you can see in the top-right corner, the user with email a@a.a has been successfully registered.

To shutdown the two containers container, go to a terminal window in the root folder of the ASP.NET Core 2.0 application and run the following command:

docker-compose down

This opens up a whole new world for containerizing your ASP.NET Core 2.0 web applications in Windows Docker containers.

References:


Thursday, March 15, 2018

SQL Server database in a Windows docker container with an ASP.NET Core 2.0 web app on host computer

This article shows how to use SQL Server Express in a Windows Docker container communicating with an ASP.NET Core 2.0 app running on the host computer.

The following is assumed:

1) You have .NET Core 2.0 installed on your computer. Go to https://www.microsoft.com/net to download and install .NET Core 2.0.
2) You have Docker for Windows installed on your computer. Refer to https://docs.docker.com/docker-for-windows/install/ for instructions on how to install "Docker for Windows".

Let's get started.

Right-click on the whale docker icon in the tray and make sure it is in Windows Container mode. This is the case if it displays “Switch to Linux containers…” as shown below:


Create a working directory somewhere on your computer's hard drive. I did so by creating a folder named AspCoreMySQL with the following terminal command:

mkdir AspCoreSqlExpress

Thereafter, go into the new folder with:

cd AspCoreSqlExpress

We will create an ASP.NET Core 2.0 application that uses individual authentication with Sql Server Local DB as follows:

dotnet new mvc --auth individual --use-local-db

To run the web application and see what it looks like, enter the following command:

dotnet run

You will see a message in the terminal window that resembles the following:

Hosting environment: Production
Content root path: E:\_aspnet\_docker\AspCoreSqlExpress
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.

The above message indicates that the Kestrel web server is running and listening on port 5000. Start your browser and enter URL http://localhost:5000. You should see a page that looks like this:


Close your browser and stop the web server in the terminal window by hitting CTRL + C.

Let's look at the code to determine what database is being used by the application. Suitable IDEs for this tutorial are Visual Studio 2017 or Visual Studio Code. You can use any other editor of your choice. 

Open Startup.cs in an editor and look at the ConfigureServices() method. The following code confirms that SQL Server is being used:

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

The connection string is being read from the appsettings.json file, which looks like thois:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-AspCoreSqlExpress-22CD843B-79FF-412C-8F1D-6D6FE7CCC468;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

Add the following code to the Configure() method in the Startup.cs file right before app.UseMvc():

using (var srvc = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
   var context = srvc.ServiceProvider.GetService<ApplicationDbContext>();
   context.Database.Migrate();
}

The above code will process any outstanding Entity Framework migrations.

We shall now download a suitable Docker image for SQLServer Express. Run the following command from a terminal window:

docker pull microsoft/mssql-server-windows-express:2016 

This image is about 5 GB in size, so it will take some time to download. Once fully downloaded, then  create a container from the Docker image with the following command:

docker run -d -p 7000:1433 --env sa_password=Sql!Expre55 --env ACCEPT_EULA=Y microsoft/mssql-server-windows-express:2016

The above Docker command will create an image with the following parameters:

- inside the container, the SQL Server database will listen on its default port number 1433. This port number is mapped to port 7000 on the host computer
- sa password is Sql!Expre55
- environment variable ACCEPT_EULA is set to Y

Check that the SQL Server container is running by typing the following Docker command in a terminal window:

docker ps -a

This should show a message that looks like this:

CONTAINER ID        IMAGE                                         COMMAND                    CREATED             STATUS              PORTS                    NAMES
327d371b6f39        microsoft/mssql-server-windows-express:2016   "cmd /S /C 'powershe…"     6 minutes ago       Up 3 minutes        0.0.0.0:1433->1433/tcp   musing_hopper

According to the above message, the container status is Up 3 minutes, which means that it is indeed running.

Now let's try to connect to it from our ASP.NET Core 2.0 application. To do this, we will need to get the internal IP address of the container. Identify the first three characters of your Container ID. In the above example it is 327. This will be used to obtain the container IP address by executing the following command in a terminal window:

docker inspect 327

        Note: You will need to replace 327 above with the first three characters of your Container ID.

A JSON formatted listing of container parameters will be shown. Identify the value for Networks >> nat >> IPAddress. In my case, the container IP address is 172.18.211.55:



Edit appsettings.json and change the connection string with key DefaultConnection so that it has a value similar to the following:

Data Source=172.18.211.55;User ID=sa;Password=Sql!Expre55;Connect Timeout=30;Database=AspCoreSqlExpress;

        Note: The IP address should match the one you identified for the container earlier on.

The SQL Server database listens on port 7000 on the host machine. This means that we can have an alternative connection string that looks like this:

Data Source=localhost,7000;User ID=sa;Password=Sql!Expre55;Connect Timeout=30;Database=AspCoreSqlExpress;

After saving the appsettings.json file, you can test your web application. Run the following commands from a terminal window:

dotnet restore
dotnet run

If all goes well, you will see a message that indicates that the web server is listening on port 5000. Point your browser to http://localhost:5000. The same web page will appear as before. Click on the Register link on the top right side.

I entered an Email, Password and Confirm password then clicked on the Register button. I was then rewarded with the following confirmation that the credentials were indeed saved in the SQL Server Express database inside the container:



The message on the top right side confirms that a user was saved and that communication between the ASP.NET Core 2.0 application and SQL Server Express inside the container is working properly.

Let us directly access the container and list all the databases that exist. Using the first three characters of the Container ID, run the following Docker command in a separate terminal window:

docker exec -it 327 sqlcmd

        Note: You need to replace 327 above with the first three characters of your Container ID.

The –i switch is for interactive and –t is for pseudo-TTY.

You will see a window that looks like this:


Enter the following pair of commands to display existing databases:

EXEC sp_databases
go

The output will look like this:



Enter these commands to display tables & views in the AspCoreSqlExpress database:

USE AspCoreSqlExpress
EXEC sp_tables
go

You can, alternatively, execute this command to see only base tables:

SELECT  * FROM AspCoreSqlExpress.INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE';
go

Enter these commands to display the content of the AspNetUsers table:

SELECT * FROM AspNetUsers 
go

To exit the sqlcmd terminal window type exit and hit ENTER.

In my next post I will demonstrate how we can also containerize our ASP.NET Core 2.0 web application.