Friday, January 3, 2020

Using EF 3.0 Core database provider for Azure CosmosDB with ASP.NET MVC

Azure Cosmos DB is Microsoft's globally distributed, multi-model database service. You can interact with the database using four favorite API including SQL, MongoDB, Cassandra, Tables, or Gremlin. In this tutorial we will be accessing Azure Cosmos DB using the SQL API.

A native Entity Framework Core provider for Azure Cosmos DB was released with .NET Core 3.0. This makes it much easier for developers who are familiar with EF Core to work with Azure Cosmos DB.

Source Code: https://github.com/medhatelmasry/CosmosEfWeb

Video: https://youtu.be/VklO8olYTL8 

Prerequisites


Before you can start this tutorial, it is assumed that you have the following:


1) At the time of writing, the latest version of .NET Core is 3.1. As a result, I am using .NET Core 3.1. You can, however, use and version of .NET Core as long as it is 3.0 or later.


2) You need to have an Azure account in order to work with Azure Cosmos DB.


3) In order to make this tutorial work on any operating system (Linux, Mac and Windows), I will be using the VS Code editor.


Prior knowledge of ASP.NET MVC is a big bonus because I will not explain the what the roles and responsibilities of Models, Views and Controllers in this article.



Creating a database in Azure Cosmos DB


The first step is to create a database in on Azure Cosmosdb. Login into your Azure account by going to https://portal.azure.com. Click on the "Create a resource" button.



In the filter field, enter the word "cosmos" the select "Azure Cosmos DB".



On the next page, click on the blue Create button.



On the "Create Azure Cosmos DB Account" page:

1) Create a new resource group. I named my resource group CosmosEfWeb-RG.

2) Give your Cosmos DB an account name. I named mine cosmos-ef-web. Not that the name needs to be all in lower case letters.


3) Do not change the API. To use Entity Framework Core we must use "Core (SQL)".


4) Finally, choose the location closest you. Since I reside on the west coast of Canada, I chose "(US) West US 2".




Click on the "Review + create" button. The next page will look like this:



Note the message that indicates that it will take about six minutes to create the account. Click on the blue Create button.

Once the provisioning is completed, you will see a page that looks like this.



Click on the blue "Go to resource" button. Click on "Data Explorer" on the left-side navigation.



Click on the "New Container" dropdown-list then select "New Database".



Give the database a name. I named my database "CollegeDB" because I will soon create an MVC app that does CRUD operations with student data.



Click on the blue OK button. After the database is created, click on the three dots on the right-side of the database then select "New Container". A container is equivalent to a collection or table in a database.



Note that this is where you can delete the entire database.


Enter a container-id. I named my container students because I will be adding a list of students. I added a partition key of /id.

Note: The Partition Key is used to automatically partition data among multiple servers for scale-ability. Choose a JSON property name that has a wide range of values and is likely to have evenly distributed access patterns.

Click on the blue OK button.

At this point our database is ready and we can start populating it with data with an application that we are about to build. We need, however, some credentials. Click on Keys on the left-side menu.



On the next page, you will need the URI and the "PRIMARY KEY". Copy both values and park them in a text editor.



We can now start developing our application.

Building an ASP.NET Core MVC app.


Open a terminal window in a working directory on your computer.

Type the following command to determine which version of .NET Core SDK you have.

dotnet --list-sdks

The following versions were listed on my computer:

2.2.104 [C:\Program Files\dotnet\sdk]
3.0.100 [C:\Program Files\dotnet\sdk]
3.1.100 [C:\Program Files\dotnet\sdk]

Create a folder named CosmosEfWeb with the following terminal command:

mkdir CosmosEfWeb

Change to the new folder with this command:

cd CosmosEfWeb

Now, if you want to use the exact version of .NET Core that I created my application with, then you can create a global.json file for version 3.1.100 with next command. Note that is optional.

dotnet new globaljson --sdk-version 3.1.100

Next, let us create a new MVC app with this command:

dotnet new mvc

In order to use the new Entity Framework .NET Core 3.0 provider, you must add the Nuget package Microsoft.EntityFrameworkCore.Cosmos. Add this package with the following terminal command:

dotnet add package Microsoft.EntityFrameworkCore.Cosmos

Now let's open our application in the VS Code editor. I was able to do so by simply entering the following command in a terminal window:

code .

We are going to model students. Therefore, add the following very simple Student.cs class inside the Models folder:

public class Student {
  [JsonProperty(PropertyName = "id")]
  public string Id { get; set; }

  [Required]
  [JsonProperty(PropertyName = "firstname")]
  public string FirstName { get; set; }

  [Required]
  [JsonProperty(PropertyName = "lastname")]
  public string LastName { get; set; }

  [Required]
  [JsonProperty(PropertyName = "school")]
  public string School { get; set; }
}


Let us add the database credentials. Add the following section to the appsettings.json file:

"CosmosDb": {
  "Endpoint": "https://cosmos-ef-web.documents.azure.com:443/",
  "Key": "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ1234451234567890ABCDEFGHIJKLMN==",
  "DatabaseName": "CollegeDB",
  "ContainerName": "Students"
}


Endpoint comes from URI and Key comes from PRIMARY KEY.

Service class


We will next create a service that is the middle tier between our controller and the database. Create a folder named Services.

In the Services folder, add the following interface file:

public interface ICosmosDbService {
  Task<IEnumerable<Student>> GetStudentsAsync(string query);
  Task<Student> GetStudentAsync(string id);
  Task AddStudentAsync(Student student);
  Task UpdateStudentAsync(string id, Student student);
  Task DeleteStudentAsync(string id);
}

Also, in the same Services folder, add a class file named CosmosDbService, that implements ICosmosDbService. The CosmosDbService.cs file contains the following code:

public class CosmosDbService : ICosmosDbService {
  private Microsoft.Azure.Cosmos.Container _container;

  public CosmosDbService(
    CosmosClient dbClient,
    string databaseName,
    string containerName) {
    this._container = dbClient.GetContainer(databaseName, containerName);
  }

  public async Task AddStudentAsync(Student student) {
    await this._container.CreateItemAsync<Student>(student, new PartitionKey(student.Id));
  }

  public async Task DeleteStudentAsync(string id) {
    await this._container.DeleteItemAsync<Student>(id, new PartitionKey(id));
  }

  public async Task<Student> GetStudentAsync(string id) {
    try {
        ItemResponse<Student> response = await this._container.ReadItemAsync<Student>(id, new PartitionKey(id));
        return response.Resource;
    }
    catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound) {
        return null;
    }
  }

  public async Task<IEnumerable<Student>> GetStudentsAsync(string queryString) {
    var query = this._container.GetItemQueryIterator<Student>(new QueryDefinition(queryString));
    List<Student> results = new List<Student>();
    while (query.HasMoreResults) {
        var response = await query.ReadNextAsync();

        results.AddRange(response.ToList());
    }

    return results;
  }

  public async Task UpdateStudentAsync(string id, Student student) {
      await this._container.UpsertItemAsync<Student>(student, new PartitionKey(id));
  }
}


To Startup.cs, add a method named InitializeCosmosClientInstanceAsync that is responsible for reading the database credentials from appsettings.json and returning the service. Add the following method to Startup.cs:

/// <summary>
/// Creates a Cosmos DB database and a container with the specified partition key.
/// </summary>
/// <returns></returns>
private static async Task<CosmosDbService> InitializeCosmosClientInstanceAsync(IConfigurationSection configurationSection)
{
  string databaseName = configurationSection.GetSection("DatabaseName").Value;
  string containerName = configurationSection.GetSection("ContainerName").Value;
  string account = configurationSection.GetSection("Endpoint").Value;
  string key = configurationSection.GetSection("Key").Value;

  CosmosClientBuilder clientBuilder = new CosmosClientBuilder(account, key);
  CosmosClient client = clientBuilder
                      .WithConnectionModeDirect()
                      .Build();
  CosmosDbService cosmosDbService = new CosmosDbService(client, databaseName, containerName);
  DatabaseResponse database = await client.CreateDatabaseIfNotExistsAsync(databaseName);
  await database.Database.CreateContainerIfNotExistsAsync(containerName, "/id");

  return cosmosDbService;
}


Also in Startup.cs, add the following code to the ConfigureServices method in order to create a singleton object representing the service:

services.AddSingleton<ICosmosDbService>(InitializeCosmosClientInstanceAsync(Configuration.GetSection("CosmosDb")).GetAwaiter().GetResult());


Students controller


Let us now create a controller with methods that enable listing, add, edit, and display of student data. In the Controllers folder add a file named StudentsController.cs with the following code:

public class StudentsController : Controller {
  private readonly ICosmosDbService _cosmosDbService;

  public StudentsController(ICosmosDbService cosmosDbService) {
    _cosmosDbService = cosmosDbService;
  }

  [ActionName("Index")]
  public async Task<IActionResult> Index() {
    return View(await _cosmosDbService.GetStudentsAsync("SELECT * FROM c"));
  }

  [ActionName("Create")]
  public IActionResult Create() {
    return View();
  }

  [HttpPost]
  [ActionName("Create")]
  [ValidateAntiForgeryToken]
  public async Task<ActionResult> CreateAsync(Student student) {
    if (ModelState.IsValid) {
      student.Id = Guid.NewGuid().ToString();
      await _cosmosDbService.AddStudentAsync(student);
      return RedirectToAction("Index");
    }

    return View(student);
  }

  [ActionName("Edit")]
  public async Task<ActionResult> EditAsync(string id) {
    if (id == null) return BadRequest();

    Student student = await _cosmosDbService.GetStudentAsync(id);
    if (student == null) return NotFound();

    return View(student);
  }

  [HttpPost]
  [ActionName("Edit")]
  [ValidateAntiForgeryToken]
  public async Task<ActionResult> EditAsync(Student student) {
    if (ModelState.IsValid) {
      await _cosmosDbService.UpdateStudentAsync(student.Id, student);
      return RedirectToAction("Index");
    }

    return View(student);
  }

  [ActionName("Delete")]
  public async Task<ActionResult> DeleteAsync(string id) {
    if (id == null) return BadRequest();

    Student student = await _cosmosDbService.GetStudentAsync(id);
    if (student == null) return NotFound();

    return View(student);
  }

  [HttpPost]
  [ActionName("Delete")]
  [ValidateAntiForgeryToken]
  public async Task<ActionResult> DeleteConfirmedAsync(string id) {
    await _cosmosDbService.DeleteStudentAsync(id);
    return RedirectToAction("Index");
  }

  [ActionName("Details")]
  public async Task<ActionResult> DetailsAsync(string id) {
    return View(await _cosmosDbService.GetStudentAsync(id));
  }
}

Views

Let us add a menu item on the layout that leads to the Students controller. Add the following line item to the ordered list in _Layout.cshtml:

<li class="nav-item">
  <a class="nav-link text-dark" asp-area="" asp-controller="Students" asp-action="Index">Students</a>
</li>


The next step is to add all the views necessary for listing, adding, editing, displaying and deleting data. 


Create folder Students under Views. In the Views/Students folder add files Index.cshtml, Create.cshtml, Edit.cshtml, Details.cshtml and Delete.cshtml. Below is the code for each of these files.


Index.cshtml


@model IEnumerable<CosmosEfWeb.Models.Student>
@{
  ViewData["Title"] = "List of students";
}

<h1>@ViewData["Title"]</h1>
<p>
  <a asp-action="Create" class="btn btn-success btn-sm">Create New Student</a>
</p>
<table class="table">
  <thead>
    <tr>
      <th>
        @Html.DisplayNameFor(model => model.FirstName)
      </th>
      <th>
        @Html.DisplayNameFor(model => model.LastName)
      </th>
      <th>
        @Html.DisplayNameFor(model => model.School)
      </th>
      <th></th>
    </tr>
  </thead>
  <tbody>
@foreach (var item in Model) {
      <tr>
        <td>
          @Html.DisplayFor(modelItem => item.FirstName)
        </td>
        <td>
          @Html.DisplayFor(modelItem => item.LastName)
        </td>
        <td>
          @Html.DisplayFor(modelItem => item.School)
        </td>
        <td>
          @Html.ActionLink("Edit", "Edit", new { id=item.Id }, new { @class = "btn btn-primary btn-sm" }) |
          @Html.ActionLink("Details", "Details", new { id=item.Id }, new { @class = "btn btn-primary btn-sm" }) |
          @Html.ActionLink("Delete", "Delete", new { id=item.Id }, new { @class = "btn btn-primary btn-sm" })
        </td>
      </tr>
}
  </tbody>
</table>


Create.cshtml


@model CosmosEfWeb.Models.Student

@{
  ViewData["Title"] = "Create New Student";
}

<h1>@ViewData["Title"]</h1>
<hr />
<div class="row">
  <div class="col-md-4">
    <form asp-action="Create">
      <div asp-validation-summary="ModelOnly" class="text-danger"></div>

      <div class="form-group">
        <label asp-for="FirstName" class="control-label"></label>
        <input asp-for="FirstName" class="form-control" />
        <span asp-validation-for="FirstName" class="text-danger"></span>
      </div>
      <div class="form-group">
        <label asp-for="LastName" class="control-label"></label>
        <input asp-for="LastName" class="form-control" />
        <span asp-validation-for="LastName" class="text-danger"></span>
      </div>
      <div class="form-group">
        <label asp-for="School" class="control-label"></label>
        <input asp-for="School" class="form-control" />
        <span asp-validation-for="School" class="text-danger"></span>
      </div>
      <div class="form-group">
        <input type="submit" value="Create" class="btn btn-primary" />
      </div>
    </form>
  </div>
</div>

<div>
  <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}


Edit.cshtml


@model CosmosEfWeb.Models.Student
@{
  ViewData["Title"] = "Edit Student";
}

<h1>@ViewData["Title"]</h1>
<hr />
<div class="row">
  <div class="col-md-4">
    <form asp-action="Edit">
      <div asp-validation-summary="ModelOnly" class="text-danger"></div>
      <input type="hidden" asp-for="Id" />

      <div class="form-group">
        <label asp-for="FirstName" class="control-label"></label>
        <input asp-for="FirstName" class="form-control" />
        <span asp-validation-for="FirstName" class="text-danger"></span>
      </div>
      <div class="form-group">
        <label asp-for="LastName" class="control-label"></label>
        <input asp-for="LastName" class="form-control" />
        <span asp-validation-for="LastName" class="text-danger"></span>
      </div>
      <div class="form-group">
        <label asp-for="School" class="control-label"></label>
        <input asp-for="School" class="form-control" />
        <span asp-validation-for="School" class="text-danger"></span>
      </div>
      <div class="form-group">
        <input type="submit" value="Save" class="btn btn-primary btn-sm" /> |
        <a asp-action="Index" class="btn btn-primary btn-sm">Back to List</a>
      </div>
    </form>
  </div>
</div>

@section Scripts {
  @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}


Details.cshtml


@model CosmosEfWeb.Models.Student

@{
  ViewData["Title"] = "Student Details";
}

<h1>@ViewData["Title"]</h1>
<div>
  <hr />
  <dl class="row">
    <dt class = "col-sm-2">
      @Html.DisplayNameFor(model => model.FirstName)
    </dt>
    <dd class = "col-sm-10">
      @Html.DisplayFor(model => model.FirstName)
    </dd>
    <dt class = "col-sm-2">
      @Html.DisplayNameFor(model => model.LastName)
    </dt>
    <dd class = "col-sm-10">
      @Html.DisplayFor(model => model.LastName)
    </dd>
    <dt class = "col-sm-2">
      @Html.DisplayNameFor(model => model.School)
    </dt>
    <dd class = "col-sm-10">
          @Html.DisplayFor(model => model.School)
    </dd>
  </dl>
</div>
<div>
  @Html.ActionLink("Edit", "Edit", new { id = Model.Id }, new { @class = "btn btn-primary btn-sm" }) |
  <a asp-action="Index" class="btn btn-primary btn-sm">Back to List</a>
</div>


Delete.cshtml


@model CosmosEfWeb.Models.Student
@{
  ViewData["Title"] = "Delete Student";
}

<h1>@ViewData["Title"]</h1>
<h3>Are you sure you want to delete this student?</h3>
<div>
  <hr />
  <dl class="row">
    <dt class = "col-sm-2">
      @Html.DisplayNameFor(model => model.FirstName)
    </dt>
    <dd class = "col-sm-10">
      @Html.DisplayFor(model => model.FirstName)
    </dd>
    <dt class = "col-sm-2">
      @Html.DisplayNameFor(model => model.LastName)
    </dt>
    <dd class = "col-sm-10">
      @Html.DisplayFor(model => model.LastName)
    </dd>
    <dt class = "col-sm-2">
      @Html.DisplayNameFor(model => model.School)
    </dt>
    <dd class = "col-sm-10">
          @Html.DisplayFor(model => model.School)
      </dd>
  </dl>
 
  <form asp-action="Delete">
    <input type="submit" value="Delete" class="btn btn-danger btn-sm" /> |
    <a asp-action="Index" class="btn btn-primary btn-sm">Back to List</a>
  </form>
</div>


Run application


We have not yet run our application. I am sure you are very curious about the fruits of your very hard work. 

From a terminal window, run the following command:

dotnet run

To view the application, point your browser to http://localhost:5000 or https://localhost:5001. You will see a home page that looks like this:




Click on Students on the top menu bar. Click on green "Create New Student" button on the next page:


Next add some data pertaining to a student in the "Create New Student" form:




When I added Bob Fox in the school of Wildlife, I was redirected to the Index.cshtml page with the following list:


Below are the Edit, Details and Delete pages that should work as expected.







I hope you use this tutorial as a launching pad for much more useful applications that take advantage of the many good features that Azure Cosmos DB has to offer.

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:



Friday, August 9, 2019

ASP.NET Core 2.2 Web API application that works with Mongo database

You can do this tutorial on Linux, Mac or Windows.

In this tutorial I will show you how to develop an ASP.NET 2.2 API application that interacts with MongoDB. In order to proceed you will need the following pre-requisites:
  • Docker - used to host MongoDB. This is my preferred approach because it is quick and does not take too many resources on the computer.
  • .NET Core 2.2
  • Visual Studio Code
Source code for this tutorial can be found at https://github.com/medhatelmasry/AspMongo.
Video: https://youtu.be/TgD4qYrvBaY

The Database

Run the following command in a terminal window to start a MongoDB container named mdb:

docker run -p 22222:27017 --name mdb -d mongo:4.0.11

You can verify that the container is running by typing the following command in a terminal window:

docker ps -a

Let us start a bash session inside the container so that we can create a database and add some sample data to it. Enter the following command to start an interactive bash session inside the container:

docker exec -it mdb bash

We can then use the mongo command line interface (CLI) to create a database and then add some sample data to a collection of students. Type the following command:

mongo

This takes you into a mongo session command prompt. Enter the following command to create a database named CollegeDB:

use CollegeDB

Next, let's create a collection named students and add to it six sample students:

db.Students.insertMany(
[
  {'FirstName':'Sue','LastName':'Fox','School':'Business'},
  {'FirstName':'Tom','LastName':'Max','School':'Mining'},
  {'FirstName':'Ann','LastName':'Lee','School':'Nursing'},
  {'FirstName':'Joe','LastName':'Roy','School':'Tourism'},
  {'FirstName':'Jan','LastName':'Ash','School':'Communications'},
  {'FirstName':'Eva','LastName':'Day','School':'Medicine'},
]);

You can retrieve the list of students with the following command:

db.Students.find({}).pretty();

To exit the mongo command prompt by typing:

CTRL+C

You can also exit the bash session and return to the host operating system by typing:

exit

Creating an ASP.NET 2.2 MVC application

Find out what versions of .NET Core SDKs you have on your computer by running this command in a terminal windows:

dotnet --list-sdks

You will see a list like this:

2.1.504 [C:\Program Files\dotnet\sdk]
2.1.505 [C:\Program Files\dotnet\sdk]
2.1.602 [C:\Program Files\dotnet\sdk]
2.1.700 [C:\Program Files\dotnet\sdk]
2.1.800-preview-009677 [C:\Program Files\dotnet\sdk]
2.2.104 [C:\Program Files\dotnet\sdk]
3.0.100-preview6-012264 [C:\Program Files\dotnet\sdk]

I chose to use the exact version 2.2.104.

Choose a suitable workspace on your computer then create a directory named AspMongo. While in a terminal window inside of the AspMongo directory, add a global.json file that targets ASP.NET Core 2.2 with the following command:

dotnet new globaljson --sdk-version 2.2.104 

The above command generated a global.json file that looks like this:
{
 "sdk": {
    "version": "2.2.104"
  }
}
The next step is to create an ASP.NET 2.2 MVC template application. This is accomplished by entering this command:

dotnet new mvc

Let us see what our application looks like. Run the application by executing:

dotnet run

The above command builds and runs the application in a web server. Point your browser to https://localhosy:5001. This is what you should see:


Stop the web server by hitting CTRL+C on the keyboard.

Building the Students API

Find the latest version of MongoDB driver from https://www.nuget.org/packages/MongoDB.Driver/. At the time of writing, the latest version was 2.8.1. Add the MongoDB driver Nuget package with the following command:

dotnet add package MongoDB.Driver --version 2.8.1

Now that we have the driver, we can proceed with coding our API. I will use Visual Studio Code because it is operating system agnostic. To load your application workspace into VS Code, simply type in the following command from the root folder of your application:

code .

We need a Student class to represent the schema for student documents in the Students collection in MongoDB. Inside the Models folder, add a file named Student.cs with the following code:

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace AspMongo.Models {
  public class Student {
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string StudentId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    [BsonElement("School")]
    public string Department { get; set; }
  }
}

In the preceding class, the StudentId property:
  • Is required for mapping the Common Language Runtime (CLR) object to the MongoDB collection.
  • Is annotated with [BsonId] to designate this property as the document's primary key.
  • Is annotated with [BsonRepresentation(BsonType.ObjectId)] to allow passing the parameter as type string instead of an ObjectId structure. Mongo handles the conversion from string to ObjectId.
The Department property is annotated with the [BsonElement] attribute. The attribute's value of School represents the property name in the MongoDB collection.
Add the following to appsettings.json:

"StudentDatabaseSettings": {
  "StudentsCollectionName": "Students",
  "ConnectionString": "mongodb://localhost:22222",
  "DatabaseName": "CollegeDB"
},

The entire contents of appsettings.json will look like this:

{
  "StudentDatabaseSettings": {
    "StudentsCollectionName": "Students",
    "ConnectionString": "mongodb://localhost:22222",
    "DatabaseName": "CollegeDB"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}
Add StudentDatabaseSettings.cs to the Models folder with this code:

namespace AspMongo.Models {
  public class StudentDatabaseSettings : IStudentDatabaseSettings {
      public string StudentsCollectionName { get; set; }
      public string ConnectionString { get; set; }
      public string DatabaseName { get; set; }
  }
  public interface IStudentDatabaseSettings {
      string StudentsCollectionName { get; set; }
      string ConnectionString { get; set; }
      string DatabaseName { get; set; }
  }   
}

The above StudentDatabaseSettings class is used to store the appsettings.json file's StudentDatabaseSettings property values. The JSON and C# property names are named identically to ease the mapping process.

Add the following code to Startup.ConfigureServices():

services.Configure<StudentDatabaseSettings>(
  Configuration.GetSection(nameof(StudentDatabaseSettings)));

services.AddSingleton<IStudentDatabaseSettings>(sp =>
  sp.GetRequiredService<IOptions<StudentDatabaseSettings>>().Value);
In the above code:
  • The configuration instance to which the appsettings.json file's StudentDatabaseSettings section binds is registered in the Dependency Injection (DI) container.
  • The IStudentDatabaseSettings interface is registered in DI with a singleton service lifetime. When injected, the interface instance resolves to a StudentDatabaseSettings object.
Create a folder named Services and add to it a file named Studentservice.cs with the following code:

using System.Collections.Generic;
using AspMongo.Models;
using MongoDB.Driver;
namespace AspMongo.Services {
  public class StudentService {
    private readonly IMongoCollection<Student> _Students;
    public StudentService(IStudentDatabaseSettings settings) {
      var client = new MongoClient(settings.ConnectionString);
      var database = client.GetDatabase(settings.DatabaseName);
      _Students = database.GetCollection<Student>(settings.StudentsCollectionName);
    }
    public List<Student> Get() =>
      _Students.Find(student => true).ToList();
    public Student Get(string id) =>
      _Students.Find<Student>(student => student.StudentId == id).FirstOrDefault();
    public Student Create(Student student) {
      _Students.InsertOne(student);
      return student;
    }
    public void Update(string id, Student studentIn) =>
      _Students.ReplaceOne(student => student.StudentId == id, studentIn);
    public void Remove(Student studentIn) =>
      _Students.DeleteOne(student => student.StudentId == studentIn.StudentId);
    public void Remove(string id) =>
      _Students.DeleteOne(student => student.StudentId == id);
  }
}

In the above code, an IStudentDatabaseSettings instance is retrieved from DI via constructor injection. Also, the above class knows how to connect to the MongoDB server and use the available driver methods to retrieve, insert, update and delete data.

To register the StudentService class with DI to support constructor injection, add the following to Startup.ConfigureServices():

services.AddSingleton<StudentService>();

Add a StudentsController.cs class to the Controllers directory with the following code:

using System.Collections.Generic;
using AspMongo.Models;
using AspMongo.Services;
using Microsoft.AspNetCore.Mvc;
namespace AspMongo.Controllers {
  [Route("api/[controller]")]
  [ApiController]
  public class StudentsController : ControllerBase {
      private readonly StudentService _StudentService;
      public StudentsController(StudentService studentService) {
          _StudentService = studentService;
      }
      [HttpGet]
      public ActionResult<List<Student>> Get() =>
          _StudentService.Get();
      [HttpGet("{id:length(24)}", Name = "GetStudent")]
      public ActionResult<Student> Get(string id) {
          var student = _StudentService.Get(id);
          if (student == null)
              return NotFound();
          return student;
      }
      [HttpPost]
      public ActionResult<Student> Create(Student student) {
          _StudentService.Create(student);
          return CreatedAtRoute("GetStudent", new { id = student.StudentId.ToString() }, student);
      }
      [HttpPut("{id:length(24)}")]
      public IActionResult Update(string id, Student studentIn) {
          var student = _StudentService.Get(id);
          if (student == null)
              return NotFound();
          _StudentService.Update(id, studentIn);
          return NoContent();
      }
      [HttpDelete("{id:length(24)}")]
      public IActionResult Delete(string id) {
          var student = _StudentService.Get(id);
          if (student == null)
              return NotFound();
          _StudentService.Remove(student.StudentId);
          return NoContent();
      }
  }
}

The StudentsController class:
  • Uses the StudentService class to perform CRUD operations.
  • Contains action methods to support GET, POST, PUT, and DELETE HTTP requests.
  • Calls CreatedAtRoute in the Create action method to return an HTTP 201 response.

Running the application

Start the application by executing the this command from a terminal windows at the root of the application:

dotnet run

You can view the data by pointing your browser to https://localhost:5001/api/Students. This is the expected output:

Go ahead and test the other API endpoints for POST, PUT and DELETE using your favorite tool like Postman or curl. It should all work.

I hope you learned something new in this tutorial, Until next time, happy coding.

Thursday, July 4, 2019

Blazor server-side app with CRUD operations that talk directly to SQL Server & built with VS Code on Windows 10

Source code for this tutorial can be found at: https://github.com/medhatelmasry/ServerBlazorEF.git
Companion Video Tutorial: https://youtu.be/wDVLRg_HCE4

In a previous post, I discussed a Blazor server-side app with CRUD operations against a Web API endpoint. In this post, I will build a Blazor application with similar functionality. However, this time the Server-side Blazor app talks directly to SQL Server Express. This is a very realistic option since both blazor and the database server run on the server.

Overview

Blazor is a framework for developing interactive client-side web applications using C# instead of JavaScript.

Architecture

The architecture of the application that we will be building will look like this:



ASP.NET Core hosts the server-side app and sets up SignalR endpoint where clients connect. SignalR is responsible for updating the DOM on the client with any changes. The Blazor application on the server connects directly to the database using Entity Framework Core.

What are we going to do in this Tutorial?

In this tutorial I will show you how to build a server-side Blazor application that connects directly with SQL Server Express using Entity Framework Core.

Perquisites

This tutorial was written while Blazor was in preview mode. The specific preview version of .NET Core 3.0 used in this tutorial is 3.0.100-preview6-012264. I used the following site for setting up my environment: https://docs.microsoft.com/en-us/aspnet/core/blazor/get-started

This is how I setup my development environment:

- .NET Core 3.0 Preview SDK installed from https://dotnet.microsoft.com/download/dotnet-core/3.0
- Visual Studio Code
- The latest C# for Visual Studio Code extension

Let's start coding

1) In a terminal window, go to your working directory. Enter the following command to create a Server-Side Blazor application inside a directory called ServerBlazorEF:
dotnet new blazorserverside -o ServerBlazorEF
2) Open the ServerBlazorEF folder in Visual Studio Code.

3) For a Blazor server-side project, the IDE requests that you add assets to build and debug the project. Select Yes.

4) Hit Ctrl F5 to run the application. Your default browser will load a page that looks like this:



Our objective is to extend the above application so that it talks to SQL Server Express using Entity Framework Core. To this end, we will be dealing with a very simple student model. Therefore, add a Student.cs class file in a folder named Models with the following  content:
using System.ComponentModel.DataAnnotations;

namespace ServerBlazorEF.Models {
  public class Student {
    public string StudentId { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    [Required]
    public string School { get; set; }
  }
}
Since we will be using SQL Server, we will need to add the appropriate Entity Framework packages. From within a terminal window at the root of your ServerBlazorEF project,  run the following commands that will add the appropriate database related packages:
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.SqlServer.Design
We need to add a connection string for the database. Add the following to the top of the appsettings.json file:
"ConnectionStrings": {
  "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=CollegeDB;Trusted_Connection=True;MultipleActiveResultSets=true"
},
We will be using the Entity Framework Code First approach. The starting point is to create a database context class. Add a C#  class file named SchoolDbContext.cs in the Data folder with the following class code:
using System;
using Microsoft.EntityFrameworkCore;

namespace ServerBlazorEF.Models {
  public class SchoolDbContext : DbContext {
    public DbSet<Student> Students { get; set; }

    public SchoolDbContext(DbContextOptions<SchoolDbContext> options) : base(options) { }

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

      builder.Entity<Student>().HasData(
        new {
          StudentId = Guid.NewGuid().ToString(),
          FirstName = "Jane",
          LastName = "Smith",
          School = "Medicine"
        }, new {
          StudentId = Guid.NewGuid().ToString(),
          FirstName = "John",
          LastName = "Fisher",
          School = "Engineering"
        }, new {
          StudentId = Guid.NewGuid().ToString(),
          FirstName = "Pamela",
          LastName = "Baker",
          School = "Food Science"
        }, new {
          StudentId = Guid.NewGuid().ToString(),
          FirstName = "Peter",
          LastName = "Taylor",
          School = "Mining"
        }
      );
    }
  }
}
Notice the above code is adding four records of seed data into the database.
In the Startup.cs file, add the following code to the ConfigureServices() method so that our application can use SQL Server:
services.AddDbContext<SchoolDbContext>(
  option => option.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
We are now ready to apply Entity Framework migrations, create the database and seed data. If you have not done so already, you will need to globally install the Entity Framework CLI tool. This tooling has changed in .NET Core 3.0 and is installed globally on your computer by running the following command in a terminal window:
dotnet tool install --global dotnet-ef --version 3.0.0-*
Remember to build your entire solution before proceeding. Then, from within a terminal window in the SchoolAPI root directory, run the following command to create migrations:
dotnet-ef migrations add initial_migration
I experienced the following error:
Unable to create an object of type 'SchoolDbContext'. For the different patterns 
supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
I followed the suggested link which obliged me to create DbContextFactory class. This class needs to read the connection string from appsettings.json without dependency injection. For this purpose, I added this helper class in the Models folder that helps read configuration settings from appsettings.json:
using Microsoft.Extensions.Configuration;

namespace ServerBlazorEF.Models {
  public class ConfigurationHelper {
    public static string GetCurrentSettings(string key) {
      var builder = new ConfigurationBuilder()
        .SetBasePath(System.IO.Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddEnvironmentVariables();

      IConfigurationRoot configuration = builder.Build();

      return configuration.GetValue<string>(key);
    }
  }
}
Next, create another class file named SchoolDbContextFactory.cs in the Data folder. This file extends from IDesignTimeDbContextFactory<T> and will be used to create the database context:
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;

namespace ServerBlazorEF.Models {
  public class SchoolDbContextFactory : IDesignTimeDbContextFactory<SchoolDbContext> {
    public SchoolDbContext CreateDbContext(string[] args) {
      var optionsBuilder = new DbContextOptionsBuilder<SchoolDbContext>();
      var connStr = ConfigurationHelper.GetCurrentSettings("ConnectionStrings:DefaultConnection");
      optionsBuilder.UseSqlServer(connStr);
      return new SchoolDbContext(optionsBuilder.Options);
    }
  }
}
After builing your application, execute the following terminal command again:
dotnet-ef migrations add initial_migration
You should get no errors and this results in the creation of a migration file ending with the name ....initial_migration.cs in the Migrations folder. In my case, this file looked like this:
using Microsoft.EntityFrameworkCore.Migrations;

namespace ServerBlazorEF.Migrations {
  public partial class initial_migration : Migration {
    protected override void Up(MigrationBuilder migrationBuilder) {
      migrationBuilder.CreateTable(
        name: "Students",
      columns: table => new {
          StudentId = table.Column<string>(nullable: false),
          FirstName = table.Column<string>(nullable: false),
          LastName = table.Column<string>(nullable: false),
          School = table.Column<string>(nullable: false)
        }, constraints: table => {
          table.PrimaryKey("PK_Students", x => x.StudentId);
        });

      migrationBuilder.InsertData(
        table: "Students",
        columns: new[] { "StudentId", "FirstName", "LastName", "School" },
        values: new object[,] {
          { "22ced2e2-ff02-4fdb-b690-292df3eecef7", "Jane", "Smith", "Medicine" },
          { "733548c4-aa07-40e7-bb79-737fb91a32fd", "John", "Fisher", "Engineering" },
          { "48c713d5-0609-47ea-a0f8-7a962ffc0232", "Pamela", "Baker", "Food Science" },
          { "48eb4c23-c8af-420c-950d-f74be1a43b98", "Peter", "Taylor", "Mining" }
        });
    }

    protected override void Down(MigrationBuilder migrationBuilder) {
      migrationBuilder.DropTable(
        name: "Students");
    }
  }
}
Note that the above code also includes commands for inserting sample data.
The next step is to create the CollegeDB database in SQL Server. This is done by running the following command from inside a terminal window at the root folder of the application.
dotnet-ef database update
If no errors are encountered, you can assume that the database was created and properly seeded with data.

Add a class file named StudentService.cs in the Data folder. Replace the class with the following code:
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace ServerBlazorEF.Models {
  public class StudentService {
      SchoolDbContext _context;
      public StudentService(SchoolDbContext context) {
        _context = context;
      }

      public async Task<List<Student>> GetStudentsAsync() {
        return await _context.Students.ToListAsync();
      }

      public async Task<Student> GetStudentByIdAsync(string id) {
        return await _context.Students.FindAsync(id);
      }

      public async Task<Student> InsertStudentAsync(Student student) {
        _context.Students.Add(student);
        await _context.SaveChangesAsync();

        return student;
      }

      public async Task<Student> UpdateStudentAsync(string id, Student s) {
        var student = await _context.Students.FindAsync(id);
        
        if (student == null)
          return null;

        student.FirstName = s.FirstName;
        student.LastName = s.LastName;
        student.School = s.School;

        _context.Students.Update(student);
        await _context.SaveChangesAsync();

        return student;
      }

      public async Task<Student> DeleteStudentAsync(string id)
      {
        var student = await _context.Students.FindAsync(id);
        
        if (student == null)
          return null;

        _context.Students.Remove(student);
        await _context.SaveChangesAsync();

        return student;
      }

      private bool StudentExists(string id) {
        return _context.Students.Any(e => e.StudentId == id);
      }
  }
}
The above StudentService class provides all the necessary methods for CRUD operations involving data retrieval, insertion, update and delettion.

We need to configure the StudentService class as a scoped service so that we can use dependency injection. Scoped lifetime services are created once per client request (connection).
Add the following statement to the ConfigureServices() method in Startup.cs:
services.AddScoped<StudentService>();
Make a duplicate copy of the FetchData.razor file in the Pages node and name the new file Students.razor. Replace its contents with the following code:
@page "/students"
@using ServerBlazorEF.Models
@inject StudentService studentService

<h1>Students</h1>

<p>This component demonstrates managing students data.</p>

@if (students == null) {
  <p><em>Loading...</em></p>
} else {
  <table class='table table-hover'>
    <thead>
      <tr>
        <th>ID</th>
        <th>First Name</th>
        <th>Last Name</th>
        <th>School</th>
      </tr>
    </thead>
    <tbody>
      @foreach (var item in students)
      {
        <tr>
          <td>@item.StudentId</td>
          <td>@item.FirstName</td>
          <td>@item.LastName</td>
          <td>@item.School</td>
        </tr>
        }
    </tbody>
  </table>
}


@functions {
  List<Student> students;

  protected override async Task OnInitAsync() {
    await load();
  }

  protected async Task load() {
    students = await studentService.GetStudentsAsync();
  }
}
Let us focus on the @functions block. The OnInitAsyns() method is called when the page gets loaded. It calls a local load() method. The load() method makes a call to the student service which loads a list of students array with data from the database. The remaining HTML/Razor code simply displays the data in a table.

Let's add a menu item to the left-side navigation of our application. Open Shared/NavMenu.razor in the editor and add the following <li> to the <ul> block (around line 24):
<li class="nav-item px-3">
  <NavLink class="nav-link" href="students">
    <span class="oi oi-list-rich" aria-hidden="true"></span> Students
  </NavLink>
</li>
You must be eager to test out the server-side Blazor project. To run your app, hit CTRL F5 to run the application without debugging. If you select the Students link on the left-side navigation, this is what the output will look like:

Adding data 

Our Blazor app is not complete without add, edit and delete functionality. We shall start with adding data. Place the following instance variables just above the OnInitAsyc() method:
string studentId;
string firstName;
string lastName;
string school;
We need an HTML form to add data. Add the following RAZOR code just before @functions:
@if (students != null) // Insert form 
{
  <input placeholder="First Name" @bind="@firstName" /><br />
  <input placeholder="Last Name" @bind="@lastName" /><br />
  <input placeholder="School" @bind="@school" /><br />
  <button @onclick="@Insert" class="btn btn-warning">Insert</button>
}
When the Insert button is clicked, an Insert() method is called. Add the following Insert() method inside the @functions() block:
protected async Task Insert() {

  Student s = new Student() {
    StudentId = Guid.NewGuid().ToString(),
    FirstName = firstName,
    LastName = lastName,
    School = school
  };

  await studentService.InsertStudentAsync(s);
  ClearFields();
  await load();
}
After data is inserted, the above code clears the fields then loads the data again into an HTML table. 
Add the following ClearFields() method:
protected void ClearFields() {
  studentId = string.Empty;
  firstName = string.Empty;
  lastName = string.Empty;
  school = string.Empty;
}
Run the Blazor server-side project and select Students from the left-side navigation menu. This is what it should look like:


I entered Harry, Green and Agriculture for data and when I clicked on the Insert button I got the following data inserted into the database:

Updating & Deleting data

To distinguish between INSERT and EDIT/DELETE mode, we shall add an enum declaration to our code. Add the following to the list of instance variables:
private enum MODE { None, Add, EditDelete };
MODE mode = MODE.None;
Student student;
We will add a button at the top of our table for adding data. Add the following markup just above the opening <table> tag:
<button @onclick="@Add"  class="btn btn-success">Add</button>
Here is the Add() method that is called when the above button is clicked:
protected void Add() { 
  ClearFields();
  mode = MODE.Add;
}
Around line 37, change the @if (students != null) statement to: 
@if (students != null && mode==MODE.Add) // Insert form 
Run the server-side Blazor project. The form for inserting data only displays when the Add button is clicked:

After we successfully insert data, we want the insert form to disappear. Add the following code to the bottom of the Insert() method:
mode = MODE.None;
Let us now add a form that only appears when we wish to update or delete data. Add the following just before @functions:
@if (students != null && mode==MODE.EditDelete) // Update & Delete form
{
  <input type="hidden" @bind="@studentId" /><br />
  <input placeholder="First Name" @bind="@firstName" /><br />
  <input placeholder="Last Name" @bind="@lastName" /><br />
  <input placeholder="School" @bind="@school" /><br />
  <button @onclick="@Update" class="btn btn-primary">Update</button>
  <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
  <button @onclick="@Delete" class="btn btn-danger">Delete</button>
}
Add these Update() and Delete() methods as shown below:
protected async Task Update() {

  Student s = new Student() {
    StudentId = studentId,
    FirstName = firstName,
    LastName = lastName,
    School = school
  };

  await studentService.UpdateStudentAsync(studentId, s);
  ClearFields();
  await load();
  mode = MODE.None;
}

protected async Task Delete() {
  await studentService.DeleteStudentAsync(studentId);
  ClearFields();
  await load();
  mode = MODE.None;
}
We want to be able to select a row of data and update or delete it. We will add an onclick handler to a row. In the HTML table, replace the opening <tr> tag, under the @foreach statement, with this:
<tr @onclick="@(() => Show(item.StudentId))">
The above would pass the appropriate studentId to a method named Show() whenever a row is clicked. Add the following Show() method that retrieves a student from the service and displays it in the Update/Delete form:
protected async Task Show(string id) {
  student = await studentService.GetStudentByIdAsync(id);
  studentId = student.StudentId;
  firstName = student.FirstName;
  lastName = student.LastName;
  school = student.School;
  mode = MODE.EditDelete;
}
Let us test our app by adding, updating and deleting data. Run the application:

Click on the Add button to insert data.


Enter data then click on the Insert button. The data should get added to the database:


To update the data, click on a row. The selected data should display in the update/delete form.


I selected James Bond and changed Bond to Gardner.


After I clicked on Update, last name was successfully changed to Gardner.


Lastly, let us delete data. I clicked on the Harry Green row. Data was displayed in the Update/Delete form.


When I clicked on Delete, Harry Green got removed.


I hope you learned something new in this tutorial and trust that you will build much more sophisticated Blazor apps than this.

Good Luck!