<lidata-marpit-fragment="1">Give a <em>Project name</em> and set a <em>Location</em> for the repository, and check <em>Place solution and project in the same directory</em>. Click <em>Next</em> in the bottom right corner.</li>
<lidata-marpit-fragment="1">Give a <em>Project name</em> and set a <em>Location</em> for the repository, and check <em>Place solution and project in the same directory</em>. Click <em>Next</em> in the bottom right corner.</li>
<lidata-marpit-fragment="2">Select <em>.NET 9.0</em> under <em>Framework</em>. <em>Authentication type</em> should be <em>None</em> for now. Uncheck <em>Configure for HTTPS</em>. Click <em>Create</em> in the bottom right corner.</li>
<lidata-marpit-fragment="2">Select <em>.NET 9.0</em> under <em>Framework</em>. <em>Authentication type</em> should be <em>None</em> for now. Uncheck <em>Configure for HTTPS</em>. Click <em>Create</em> in the bottom right corner.</li>
<lidata-marpit-fragment="1">Add <ahref="https://learn.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-8.0&tabs=visual-studio">Swagger</a> to your project. Go to <em>View > Other Windows > Package Manager Console</em> and run the following command:<preis="marp-pre"data-auto-scaling="downscale-only"><code>Install-Package Swashbuckle.AspNetCore -Version 6.6.2
<lidata-marpit-fragment="1">Add <ahref="https://learn.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-8.0&tabs=visual-studio">Swagger</a> to your project. Go to <em>View > Other Windows > Package Manager Console</em> and run the following command:<preis="marp-pre"data-auto-scaling="downscale-only"><code>Install-Package Swashbuckle.AspNetCore -Version 6.6.2
<lidata-marpit-fragment="1">Make sure <code>Program.cs</code> includes the following lines:<preis="marp-pre"data-auto-scaling="downscale-only"><codeclass="language-csharp">builder.Services.AddControllers();
<lidata-marpit-fragment="1">Make sure <code>Program.cs</code> includes the following lines:<preis="marp-pre"data-auto-scaling="downscale-only"><codeclass="language-csharp">builder.Services.AddControllers();
<lidata-marpit-fragment="1">Start debugging from the top (the <imgclass="emoji"draggable="false"alt="▶"src="https://cdn.jsdelivr.net/gh/jdecked/twemoji@14.1.2/assets/svg/25b6.svg"data-marp-twemoji=""/> button with the text <em>http</em>).
<lidata-marpit-fragment="1">Start debugging from the top (the <imgclass="emoji"draggable="false"alt="▶"src="https://cdn.jsdelivr.net/gh/jdecked/twemoji@14.1.2/assets/svg/25b6.svg"data-marp-twemoji=""/> button with the text <em>http</em>).
<ul>
<ul>
<lidata-marpit-fragment="2">Click OK to trust the sertificates.</li>
<lidata-marpit-fragment="2">Click <em>Yes</em> twice to trust the certificates.</li>
<lidata-marpit-fragment="1">A web page should open, showing SwaggerUI for a weather forecast API. Click it open <imgclass="emoji"draggable="false"alt="🔽"src="https://cdn.jsdelivr.net/gh/jdecked/twemoji@14.1.2/assets/svg/1f53d.svg"data-marp-twemoji=""/>.</li>
<lidata-marpit-fragment="1">A web page should open, showing SwaggerUI for a weather forecast API. Click it open <imgclass="emoji"draggable="false"alt="🔽"src="https://cdn.jsdelivr.net/gh/jdecked/twemoji@14.1.2/assets/svg/1f53d.svg"data-marp-twemoji=""/>.</li>
<lidata-marpit-fragment="2">Click <em>Try it out</em>, and 11. <em>Execute</em> the <strong>GET</strong> request and see what it returns.</li>
<lidata-marpit-fragment="2">Click <em>Try it out</em>, and 11. <em>Execute</em> the <strong>GET</strong> request and see what it returns.</li>
<lidata-marpit-fragment="1">Close the window. Browse through the source files on Solution Explorer on the right and check where the weather forecasts come from.</li>
<lidata-marpit-fragment="1">Close the window. Browse through the source files on Solution Explorer on the right and check where the weather forecasts come from.</li>
<h3id="aspnet-core-web-api-contents">ASP.NET Core Web API contents</h3>
<h3id="aspnet-core-web-api-contents">ASP.NET Core Web API contents</h3>
<ul>
<ul>
<lidata-marpit-fragment="1">In the previous exercise, we chose an API template for our new project, which have some files and dependencies already added</li>
<lidata-marpit-fragment="1">In the previous exercise, we chose an API template for our new project, which have some files and dependencies already added</li>
<h3id="a-default-server-program">A default server program</h3>
<h3id="a-default-server-program">A default server program</h3>
<ul>
<ul>
<lidata-marpit-fragment="1">The <code>Program.cs</code> file in ASP.NET 7 is where the <em><strong>services</strong></em> for the web application are configured and the <em><strong>middleware</strong></em> is defined</li>
<lidata-marpit-fragment="1">The <code>Program.cs</code> file in ASP.NET 7 is where the <em><strong>services</strong></em> for the web application are configured and the <em><strong>middleware</strong></em> is defined</li>
<lidata-marpit-fragment="1">Handling of each HTTP request is defined as a set of <ahref="https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-9.0">middlewares</a></li>
<lidata-marpit-fragment="1">Handling of each HTTP request is defined as a set of <ahref="https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-9.0">middlewares</a></li>
<lidata-marpit-fragment="1"><em><strong>Attributes</strong></em> (<ahref="/education/csharp-basics/src/branch/main/15-design-patterns-in-csharp.md#attributes">see C# Basics: Lecture 15</a>) are a way of attaching metadata to entities (classes, methods, properties, etc.)</li>
<lidata-marpit-fragment="1"><em><strong>Attributes</strong></em> (<ahref="/education/csharp-basics/src/branch/main/15-design-patterns-in-csharp.md#attributes">see C# Basics: Lecture 15</a>) are a way of attaching metadata to entities (classes, methods, properties, etc.)</li>
<lidata-marpit-fragment="1">The URI parameters can be made optional with '?'</li>
<lidata-marpit-fragment="1">The URI parameters can be made optional with '?'</li>
<lidata-marpit-fragment="2">A default value must be then set for the method parameter:<preis="marp-pre"data-auto-scaling="downscale-only"><codeclass="language-csharp">[<spanclass="hljs-meta">Route(<spanclass="hljs-string">"api"</span>)</span>]
<lidata-marpit-fragment="2">A default value must be then set for the method parameter:<preis="marp-pre"data-auto-scaling="downscale-only"><codeclass="language-csharp">[<spanclass="hljs-meta">Route(<spanclass="hljs-string">"api"</span>)</span>]
<lidata-marpit-fragment="1">Apply constraints for the parameters by setting them after <code>:</code></li>
<lidata-marpit-fragment="1">Apply constraints for the parameters by setting them after <code>:</code></li>
<lidata-marpit-fragment="2">If the URI doesn't fit the constraints, the response will hold a <code>404</code> status code<preis="marp-pre"data-auto-scaling="downscale-only"><codeclass="language-csharp">[<spanclass="hljs-meta">HttpGet(<spanclass="hljs-string">"products/{id:int}"</span>)</span>] <spanclass="hljs-comment">// Required type: int</span>
<lidata-marpit-fragment="2">If the URI doesn't fit the constraints, the response will hold a <code>404</code> status code<preis="marp-pre"data-auto-scaling="downscale-only"><codeclass="language-csharp">[<spanclass="hljs-meta">HttpGet(<spanclass="hljs-string">"products/{id:int}"</span>)</span>] <spanclass="hljs-comment">// Required type: int</span>
<h3id="benefits-of-using-postman">Benefits of using Postman</h3>
<h3id="benefits-of-using-postman">Benefits of using Postman</h3>
<ul>
<ul>
<lidata-marpit-fragment="1">When developing APIs, tools like Postman will almost always surface in the development cycle</li>
<lidata-marpit-fragment="1">When developing APIs, tools like Postman will almost always surface in the development cycle</li>
@ -458,7 +458,7 @@ instead of<br />
<lidata-marpit-fragment="4">Supports all the necessary HTTP requests, like <code>GET</code>, <code>POST</code>, <code>PUT</code> and <code>DELETE</code></li>
<lidata-marpit-fragment="4">Supports all the necessary HTTP requests, like <code>GET</code>, <code>POST</code>, <code>PUT</code> and <code>DELETE</code></li>
* set up routes with attributes to connect request URIs with methods,
* set up routes with attributes to connect request URIs with methods,
* respond with HTTP responses
* respond with HTTP responses
* The problem is that all this functionality is scattered here and there around the program, meaning we have no structure to what we are doing
* The problem is that all this functionality is scattered here and there around the program, meaning we have no structure to what we are doing
* In order to write production level code, your API should follow the __MVC pattern__
* In order to write production level code with ASP.NET, your API should follow the *__MVC pattern__*
# The MVC Pattern (continued)
### What is the MVC Pattern?
* Helps to enforce __separation of concerns__ , and induce code readability and testability
* [MVC](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) is a software architectural pattern, an acronym for Model - View - Controller
* Acronym for Model - View - Controller
* Traditionally used for desktop graphical user interfaces
* Model
* Helps to enforce __*separation of concerns*__
* When an entity in code has only a single job:
* It is easier to read and write
* It is easier to test and debug
* $\Rightarrow$ It's easier to scale the application in complexity
* ASP.NET Core includes an [MVC Framework](https://learn.microsoft.com/en-us/aspnet/core/mvc/overview?view=aspnetcore-9.0) for implementing this design pattern
* Could also include some logic to retrieve and save the data
* Can also include some logic to retrieve and save the data
* View
</div>
* The data that is shown to the client, e.g. web page
<divmarkdown='1'>
* More often than not different from the Model - client does not need to (and often shouldn't) see all possible data
* Controller
#### View
* The data that is shown to the client, e.g. a web page
* More often than not different from the Model - client does not need to (and often *shouldn't*) see all possible data
</div>
<divmarkdown='1'>
#### Controller
* Communicates with the Model and the View
* Communicates with the Model and the View
* How the data (models) will be processed before sending it forwards to the client or to the view
* How the data (models) will be processed before sending it forwards to the client or to the view
</div>
</div>
In an API, the pattern is implemented like this:
### MVC implementation
class User
* In an ASP.NET Core API, the pattern is implemented like this:
{
<divclass='columns111'markdown='1'>
<divmarkdown='1'>
public int Id {get; set;}
#### Model
public string Name {get; set;}
`Models/User.cs`
```csharp
namespace MyApi.Models
{
public class User
{
public int Id {get; set;}
public string Name {get; set;}
}
}
}
```
Get()
</div>
<divmarkdown='1'>
Post()
...
#### View
```csharp
{
{
"id": 1
"id": 1
"name": "Sonja"
"name": "Sonja"
}
}
```
(Basically just JSON data that ASP.NET can show automatically)
---
</div>
<divmarkdown='1'>
The "view" in APIs is basically just JSON data
# Exercise 1. Setting up the Project
#### Controller
Create a new ASP.NET Core Web API template project. Name it CourseAPI. Delete WeatherForecastController.cs and WeatherForecast.cs.
`Controllers/UserController.cs`
```csharp
using Microsoft.AspNetCore.Mvc;
using MyApi.Models;
namespace MyApi.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
[HttpGet("{id}")]
public IActionResult GetUser(int id)
// ...
}
}
```
Add a new controller CoursesController by right-clicking the Controllers folder and selecting _Add_ > _Controller… > API Controller > Empty_
</div>
</div>
Add a new folder Models. Inside, add a new class file ( _Add > Class…_ ) Course.cs
### The controller
To the Course class, create the properties int Id, string Name and int Credits
<divclass='columns32'markdown='1'>
<divmarkdown='1'>
# Exercise 2: Creating GET Endpoints
```csharp
using Microsoft.AspNetCore.Mvc;
using MyApi.Models;
namespace MyApi.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
[HttpGet("{id}")]
public IActionResult GetUser(int id)
{
var person = new Person
{
Id = 1,
Name = "Sonja"
};
return Ok(person);
}
}
}
```
Inside the Controller class, initialize a list of courses with a couple of test courses
</div>
<divmarkdown='1'>
Create endpoints for GET requests with URIs api/courses and api/courses/{id} which return all courses and a single course with a corresponding ID, respectively
* Here's an extended implementation of the earlier controller, showcasing the HTTP `GET` method
* The object that gets sent to the View (the webpage) as a JSON is just hardcoded here, but normally the data comes from a ***database***
# Repositories
</div>
</div>
* When following the _separation of concerns_ principle, the controllers or models should NOT be accessing the database directly
### Exercise 1. Setting up the Project
* Instead, the web app should have some kind of repository for reading from and writing to the database
<!--_class: "exercise invert" -->
* For now, we can just create a mock repository to a new folder called "Repositories" for our needs, and make it static so that it can be accessed everywhere
* Later on, we will add services to make the repository available within our program via dependency injection
# Repository Example
1) Create a new ASP.NET Core Web API template project. Name it `CourseAPI`. Delete `WeatherForecastController.cs` and `WeatherForecast.cs`.
2) Add a new controller `CoursesController` by right-clicking the `Controllers` folder and selecting *Add > Controller... > API Controller > Empty*
3) Add a new folder `Models`. Inside, add a new class file ( _Add > Class..._ ) named `Course.cs`
* To the Course class, create the properties `int Id`, `string Name` and `int Credits`
public class MockRepo
### Exercise 2. Creating `GET` endpoints
<!--_class: "exercise invert" -->
{
1) Inside the Controller class, initialize a list of courses with a couple of test courses
2) Create endpoints for `GET` requests with URIs `api/courses` and `api/courses/{id}` which return all courses and a single course with a corresponding ID, respectively
// Replace this later on with a database context
## Repositories
private List<Student> Students { get; set; }
### Accessing data with repositories
// Constructor to initialize student list
* When following the **_separation of concerns_** principle, the controllers or models should NOT be accessing the database directly
* Instead, the web app should have some kind of ***repository*** for reading from and writing to the database
* (Not to be confused with a Git repository!)
* For now, we can just create a mock repository to a new folder called `Repositories` for our needs, and make it static so that it can be accessed everywhere
* Later on, we will add services to make the repository available within our program via ***dependency injection***
private MockRepo(){
### Repository Example
Students = new List<Student>();
<divclass='columns32'markdown='1'>
<divmarkdown='1'>
```csharp
// Repositories/ContactRepository.cs
public class MockRepo
{
// Replace this later on with a database context
private List<Contact> Contacts { get; set; }
// Constructor to initialize contact list
private MockRepo()
{
Contacts = new List<Contact>();
}
}
// Replace this later on with dependency injection
// Replace this later on with dependency injection
public static MockRepo Instance { get; } =
new MockRepo();
public static MockRepo Instance { get; } = new MockRepo();
public List<Contact> GetContacts() => Contacts;
public List<Student> GetStudents() => Students;
// Update database here later
// Update database here later
// Other methods to read/write from database
// Other methods to read/write from database
// ...
// ...
}
}
```
---
</div>
<divmarkdown='1'>
At this point, implementation of the db is up to you
Later, real database is added
# Repository Example (continued)
In the controller class:
```csharp
// Controllers/ContactsController.cs
// ...
[HttpGet]
[HttpGet]
public List<Contact> Get()
public List<Student> Get()
{
{
return MockRepo.Instance.GetContacts();
return MockRepo.Instance.GetStudents();
}
}
// ...
```
---
* At this point, implementation of the "database" is up to you
* Later, a real database is added
At this point, implementation of the db is up to you
</div>
Later, real database is added
</div>
# Exercise 3: Using a Repository
### Exercise 3: Using a Repository
<!--_class: "exercise invert" -->
Continue working on CourseAPI.
Continue working on CourseAPI.
Within the solution, create a folder called Repositories
1) Within the solution, create a folder called `Repositories`
2) Add a mock repository to the folder. Move the course list from the controller to the repository to simulate our database for now. Add methods to get all courses in the list and a single course by ID.
3) Modify the controller so that it uses the repository for getting courses.
Add a mock repository to the folder. Move the course list from the controller to the repository to simulate our database for now. Add methods to get all courses in the list and a single course by ID.
## Services
Modify the controller so that it uses the repository for getting courses.
### Repository, as a service
# Services
* Services and [dependency injection (DI)](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.1) have been introduced earlier in this training
* [Services and dependency injection](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.1) (DI) have been mentioned during this course
* Recap: DI allows for ***loose coupling*** between classes and their dependencies
* Recap: DI allows for loose coupling between classes and their dependencies
* This decreases complexity, makes refactoring easier and increases code testability
* This decreases complexity, makes refactoring easier and increases code testability
* DI is used in ASP.NET to distribute services to classes in a controlled way
* DI is used in ASP.NET to distribute services to classes in a controlled way
* Let's get started by making a repository service
* Let's get started by making a repository service
@ -153,148 +246,138 @@ Modify the controller so that it uses the repository for getting courses.
* Repositories should be accessible within the API from multiple controllers
* Repositories should be accessible within the API from multiple controllers
* Logical step is to make it a service!
* Logical step is to make it a service!
# Services (continued)
### Service interface
Create a service interface and a class implementing it:
<divclass='columns'markdown='1'>
<divmarkdown='1'>
* Create a ***service interface*** and a class implementing it:


---
* ***A rule of thumb:*** Create a separate repository for all ***tightly coupled*** models, not necessarily every model
Repository for each model?
1 repo for all tightly coupled models
Add _all _ methods of the service to the interface:
</div>
<divmarkdown='1'>
* Add **_all_** methods of the service to the interface:
```csharp
public interface IContactRepository
public interface IContactRepository
{
{
Contact GetContact(int id);
Contact GetContact(int id);
List<Contact> GetContacts();
List<Contact> GetContacts();
void AddContact(Contact contact);
void AddContact(Contact contact);
void UpdateContact(int id, Contact contact);
void UpdateContact(int id, Contact contact);
void DeleteContact(int id);
void DeleteContact(int id);
// UpdateDataBase() later on...
// UpdateDataBase() later on...
}
}
```
Create the class which implements the interface:
</div>
</div>
public class ContactRepository : IContactRepository
* Next, we'll create a class that implements this interface.
{
### Implementing the interface
```csharp
public class ContactRepository : IContactRepository
{
// Replace this with database context in a real life application
// Replace this with database context in a real life application
private static List<Contact> Contacts = new List<Contact>
private static List<Contact> Contacts = new List<Contact>
{
{
new Contact{Id=0, Name="Johannes Kantola", Email="johkant@example.com"},
new Contact{Id=0, Name="Johannes Kantola", Email="johkant@example.com"},
new Contact{Id=1, Name="Rene Orosz", Email="rene_king@example.com"}
new Contact{Id=1, Name="Rene Orosz", Email="rene_king@example.com"}
};
};
public void AddContact(Contact contact) => Contacts.Add(contact);
public void AddContact(Contact contact) => Contacts.Add(contact);
Create an interface ICourseRepository with methods for getting a single course or all courses. Rename your mock repository to CourseRepository and make sure the interface is fully implemented.
1) Create an interface `ICourseRepository` with methods for getting a single course or all courses. Rename your mock repository to `CourseRepository` and make sure the interface is fully implemented.
2) Add `CourseRepository` as a service, and refactor the controller to use methods for `ICourseRepository`
Add CourseRepository as a service, and refactor the controller to use methods for ICourseRepository
## Wrapping Things Up
# Wrapping Things Up
At this point, the flow of your API should be in line with this chart:
At this point, the flow of your APIs should be in lines with this chart:

Client (e.g. Postman)
### Project hierarchy

* In solution explorer, the project hierarchy would look like this
<divclass='columns32'markdown='1'>
<divmarkdown='1'>
* In solution explorer, the project hierarchy would look like this.
* Once you start adding new classes, they should have their own models and controllers
* Once you start adding new classes, they should have their own models and controllers
* One repository can store multiple models, and there can be multiple repositories
* One repository can store multiple models, and there can be multiple repositories
* Every server/database/API you use should have its own repository!
* Every server/database/API you use should have its own repository!
# What the Heck Does This Do?
</div>
<divmarkdown='1'>

</div>
</div>
### What the Heck Does This Do?
* A lot of the functionality in ASP.NET comes from the base class library
* A lot of the functionality in ASP.NET comes from the base class library
* At beginning, trying to remember all the methods and what did what can feel overwhelming
* When starting out, trying to remember all the methods and what does what can feel overwhelming
* If you ever end up getting confused about what did what, Ctrl + click Type name to go to definition
* If you ever end up getting confused what any method does, Ctrl + click *Type name* to go to definition
* There is always a summary about the method
* There is always a summary about the method
* Also looking up the method from Microsoft documentation is helpful
* Also looking up the method from Microsoft documentation is helpful