Dot Net Core - Lab
Dot Net Core - Lab
.NET Technology
LAB MANUAL
Compiled by:
Asst. Professor
Apex College
January 2020
.NET Technology
LAB PLAN
When a dialog box asks if you want to add required assets to the project,
select Yes.
o Creates a new web API project and opens it in Visual Studio Code.
o Adds the NuGet packages which are required in the next section.
.NET Technology
Lab 2:
Create a Web API Project
Follow this document and create REST API for your project.
⚫ https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-
api?view=aspnetcore-2.2&tabs=visual-studio-code
.NET Technology
Lab 3:
ER Diagram, Create Database Tables and N-Layered Architecture
Below is the ER Diagram for Restaurant and Customers.
-- Use db
USE ApexRestaurantDB;
-- Create table
CREATE TABLE Customers(
Id INT PRIMARY KEY IDENTITY(1,1),
FirstName NVARCHAR(200),
LastName NVARCHAR(200),
Address NVARCHAR(500),
PhoneRes NVARCHAR(50),
PhoneMob NVARCHAR(50),
EnrollDate DATETIME,
IsActive BIT,
.NET Technology
CreatedBy NVARCHAR(200),
CreatedOn DATETIME,
UpdatedBy NVARCHAR(200),
UpdatedOn DATETIME
);
Then insert a seed data to the table Customers. This is done to ensure that you
get at least one record to test your application.
Follow the same process for all the tables in your database.
Initializing Project Structure:
Create a folder D:\ApexRestaurant\ and initialize projects:
Create a solution:
dotnet new sln -n ApexRestaurant¶
Since you’re in a working state, initialize and put the project to git.
Go to github.com and create a new public repository, e.g. yourname_dotnet. You need to
submit a fully working instance of your github repository for project marks. I have
created a public repository as apexrestaurant. The public url of my github repository is
“https://github.com/bishwo633/apexrestaurant”.
Initialize git inside the folder “D:\ApexRestaurant\”
git init¶
Add all changed files to be tracked by git
git add .¶
Commit with message “initial commit”
git commit -m "initial commit"¶
Setup your github url as your remote git location
git remote add origin
https://github.com/bishwo633/apexrestaurant.git¶
Push to github
git push -u origin master¶
Go to your github location in browser and see the changes reflected online.
.NET Technology
Lab 4:
ApexRestaurant.Repository Setup
namespace ApexRestaurant.Repository
{
public interface IGenericRepository<T>
{
T Get(int id);
IQueryable<T> Query();
}
}
namespace ApexRestaurant.Repository
{
public abstract class GenericRepository<T> : IGenericRepository<T>
where T : class, new()
{
protected RestaurantContext DbContext { get; set; }
namespace ApexRestaurant.Repository
{
public static class RepositoryModule
{
public static void Register(IServiceCollection services, string connection,
string migrationsAssembly)
{
.NET Technology
services.AddDbContext<RestaurantContext>(options =>
options.UseSqlServer(connection, builder =>
builder.MigrationsAssembly(migrationsAssembly)));
services.AddTransient<ICustomerRepository, CustomerRepository>();
}
}
}
Note:
- Whenever you add a new repository, add a line similar to the highlighted line.
- Transient objects are always different; a new instance is provided to every controller
and every service. Scoped objects are the same within a request, but different across
different requests. Singleton objects are the same for every object and every request.
namespace ApexRestaurant.Repository
{
public class RestaurantContext : DbContext
{
}
}
Note:
- Whenever you add a new table, add a line similar to the highlighted line.
.NET Technology
Create a folder “Domain” and add a class “Customer.cs”.
using System;
namespace ApexRestaurant.Repository.Domain
{
public class Customer
{
public int Id { get; set; }
}
}
namespace ApexRestaurant.Repository.RCustomer
{
public class CustomerRepository : GenericRepository<Customer>, ICustomerRepository
{
public CustomerRepository(RestaurantContext dbContext)
{
DbContext = dbContext;
}
}
}
Good work! Your repository project is complete. Now build your project to ensure there
are no errors.
dotnet build¶
Follow the similar steps for other database models as per your ER diagram.
.NET Technology
Lab 5:
Buffer Lab
.NET Technology
Lab 6:
ApexRestaurant.Services Setup
Create an interface “IGenericService.cs”
using System.Collections.Generic;
namespace ApexRestaurant.Services
{
public interface IGenericService<T>
{
IList<T> GetAll();
T GetById(int id);
namespace ApexRestaurant.Services
{
public abstract class GenericService<T> : IGenericService<T>
where T : class, new()
{
protected GenericService(IGenericRepository<T> entityRepository)
{
EntityRepository = entityRepository;
}
namespace ApexRestaurant.Services
{
public static class ServicesModule
{
public static void Register(IServiceCollection services)
{
services.AddTransient<ICustomerService, CustomerService>();
}
.NET Technology
}
}
Note: Add similar line to the highlighted line for every new services.
namespace ApexRestaurant.Services.SCustomer
{
public interface ICustomerService : IGenericService<Customer>
{
}
}
namespace ApexRestaurant.Services.SCustomer
{
public class CustomerService : GenericService<Customer>, ICustomerService
{
public CustomerService(ICustomerRepository customerRepository) :
base(customerRepository)
{
}
}
}
Great work! Services project is setup. Build to ensure there are no erros.
cd ApexRestaurant.Services¶
dotnet build¶
Follow the similar steps for other models as per your ER diagram.
.NET Technology
Lab 7:
ApexRestaurant.Api Setup for Web Services/Web API & Testing via Postman
Navigate to “appsettings.json” file and add “ConnectionStrings” section:
{
"ConnectionStrings": {
"DefaultConnection": "Server=.;Database=ApexRestaurantDb;Trusted_Connection=True;"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
}
Navigate to “Startup.cs” and add entries for RepositoryModule and ServiceModule in the
method ConfigureServices as below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ApexRestaurant.Repository;
using ApexRestaurant.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace ApexRestaurant.Api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
.NET Technology
}
// This method gets called by the runtime. Use this method to add services to
the container.
public void ConfigureServices(IServiceCollection services)
{
RepositoryModule.Register(services,
Configuration.GetConnectionString("DefaultConnection"),
GetType().Assembly.FullName);
ServicesModule.Register(services);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the
HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseMvc();
}
}
}
namespace ApexRestaurant.Api.Controller
{
[Route("api/customer")]
public class CustomerController : ControllerBase
{
[HttpGet]
[Route("{id}")]
public IActionResult Get([FromRoute] int id)
{
var customer = _customerService.GetById(id);
if (customer == null)
return NotFound();
return Ok(customer);
}
[HttpGet]
[Route("")]
public IActionResult GetAll()
{
var customers = _customerService.GetAll();
return Ok(customers);
}
[HttpPost]
[Route("")]
public IActionResult Post([FromBody] Customer model)
{
_customerService.Insert(model);
.NET Technology
return Ok();
}
[HttpPut]
[Route("")]
public IActionResult Put([FromBody] Customer model)
{
_customerService.Update(model);
return Ok();
}
[HttpDelete]
[Route("")]
public IActionResult Delete([FromBody] Customer model)
{
_customerService.Delete(model);
return Ok();
}
}
}
GET: http://localhost:5000/api/customer/1/
.NET Technology
POST: http://localhost:5000/api/customer/
Notice the field “Status: 200 OK” for successful insertion of customer.
PUT: http://localhost:5000/api/customer/
.NET Technology
DELETE: http://localhost:5000/api/customer/
Lab 8&9:
Call Web API with jQuery/Ajax
https://www.codeofaninja.com/2015/06/php-crud-with-ajax-and-oop.html
.NET Technology
Lab 10:
Exam
Based on your commit history and correctness of working modules, your evaluation will
be done.
.NET Technology
Bonus Lab I:
ApexRestaurant.Mvc Setup
Let’s use CLI code generator “dotnet-aspnet-codegenerator” to generate controllers and
views for us.
First, install dotnet-aspnet-codegenerator.
dotnet tool install --global dotnet-aspnet-codegenerator ¶
cd ApexRestaurant\ApexRestaurant.Mvc ¶
Generate code:
References:
https://medium.com/@kmignaz/create-your-forecast-application-with-net-core-
and-dockerize-it-945329e0fa83
https://code-maze.com/net-core-web-api-ef-core-code-first/
https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-
api?view=aspnetcore-3.1&tabs=visual-studio-code
https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-
javascript?view=aspnetcore-3.1
https://docs.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-
swashbuckle?view=aspnetcore-3.1&tabs=visual-studio-code
https://docs.microsoft.com/en-
us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1
--- ---
BEST OF LUCK