#NET – Seed data in DB (Codefirst)

Having a DB generated with CodeFirst we want it to be generated with initial data, if not try: XXX

1) In the Datacontext add method OnModelCreating

protected override void OnModelCreating(ModelBuilder modelBuilder)
{

}

2) create datetime values, we must use const value in the insert

var createdIn = new DateTime(2025, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var updatedIn = new DateTime(2025, 1, 1, 0, 0, 0, DateTimeKind.Utc);

3 Add each record data for Brands

modelBuilder.Entity<BrandModel>().HasData(

    new BrandModel { Id = 1, Name = "Sony", Description = "Japanese multinational conglomerate corporation", Enabled = true, CreatedIn = createdIn, UpdatedIn = updatedIn },

    new BrandModel { Id = 2, Name = "Microsoft", Description = "American multinational technology company", Enabled = true, CreatedIn = createdIn, UpdatedIn = updatedIn },

    new BrandModel { Id = 3, Name = "Nintendo", Description = "Japanese multinational consumer electronics and video game company", Enabled = true, CreatedIn = createdIn, UpdatedIn = updatedIn }

);

4) We can add the data for any record

modelBuilder.Entity<ConsoleModel>().HasData(

    new ConsoleModel { Id = 1, Name = "PlayStation 5", Description = "", BrandId = 1, Enabled = true, CreatedIn = createdIn, UpdatedIn = updatedIn },

    new ConsoleModel { Id = 2, Name = "Xbox Series X", Description = "", BrandId = 2, Enabled = true, CreatedIn = createdIn, UpdatedIn = updatedIn },

    new ConsoleModel { Id = 3, Name = "Nintendo Switch", Description = "", BrandId = 3, Enabled = true, CreatedIn = createdIn, UpdatedIn = updatedIn }

modelBuilder.Entity<GameModel>().HasData(

    new GameModel { Id = 1, Name = "Demon's Souls", Description = "", ConsoleId = 1, Enabled = true, CreatedIn = createdIn, UpdatedIn = updatedIn },

    new GameModel { Id = 2, Name = "Halo Infinite", Description = "", ConsoleId = 2, Enabled = true, CreatedIn = createdIn, UpdatedIn = updatedIn },

    new GameModel { Id = 3, Name = "The Legend of Zelda: Breath of the Wild", Description = "", ConsoleId = 3, Enabled = true, CreatedIn = createdIn, UpdatedIn = updatedIn }
);

5) Rebuild project

dotnet rebuild

6) Create migrations

dotnet ef migrations add InitialCreate

7) Create DB

dotnet ef database update

8) Use Postgresql extension to confirm the DB creation with the tables

9) Done

GitHub repository:

github.com/maqdel/Developing-101

Folder: 003_Csharp

#NET – Create a DB (Codefirst)

You must have a Codespace with .net 9.x and Postgresql, if not try: #React – Create a React app with TypeScrip using Vite

1) Create a console project:

dotnet new console -o EFCDB -f net9.0

EFCDB is the name for the folder and the console app

2) Go to the folder EFCDB

cd EFCDB

3) Install the global EF

dotnet tool install --global dotnet-ef --version 9.*

4) Install package EntityFrameworkCore

dotnet add package Microsoft.EntityFrameworkCore --version 9.0.7

5) Install package EntityFrameworkCore.tools

dotnet add package Microsoft.EntityFrameworkCore.tools --version 9.0.7

6) Install package EntityFrameworkCore.SqlServer

dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 9.0.7

7) Install package EntityFrameworkCore.PostgreSQL

dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL --version 9.0.4

8) Check the file: EFCDB.csproj, must looks like this:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>disable</ImplicitUsings>
    <Nullable>disable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.7" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="9.0.7" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.tools" Version="9.0.7">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
  </ItemGroup>

</Project>

9) Add folder: Models

10) Add class: BrandModel.cs

[Table("Brands", Schema = "dbo")]
public class BrandModel
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    [Required]
    [Column(TypeName = "varchar(50)")]
    public string Name { get; set; }
    [Required]
    [Column(TypeName = "varchar(250)")]
    public string Description { get; set; }
    [Required]
    public bool Enabled { get; set; }
    [Required]
    public DateTime CreatedIn { get; set; }
    [Required]
    public DateTime UpdatedIn { get; set; }
}

11) Add class: ConsoleModel.cs

[Table("Consoles", Schema = "dbo")]
public class ConsoleModel
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    [ForeignKey("brandId")]
    public BrandModel Brand { get; set; }       
    [Required]
    [Column(TypeName = "varchar(50)")]
    public string Name { get; set; }
    [Required]
    [Column(TypeName = "varchar(250)")]
    public string Description { get; set; }
    [Required]
    public bool Enabled { get; set; }
    [Required]
    public DateTime CreatedIn { get; set; }
    [Required]
    public DateTime UpdatedIn { get; set; }
}

12) Add class: GameModel.cs

[Table("Games", Schema = "dbo")]
public class GameModel
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    [ForeignKey("ConsoleId")]
    public ConsoleModel Console { get; set; }        
    [Required]
    [Column(TypeName = "varchar(50)")]
    public string Name { get; set; }
    [Required]
    [Column(TypeName = "varchar(250)")]
    public string Description { get; set; }
    [Required]
    public bool Enabled { get; set; }
    [Required]
    public DateTime CreatedIn { get; set; }
    [Required]
    public DateTime UpdatedIn { get; set; }
}

13) In the EFCDB folder add class: Datacontext.cs

public class DataContext : DbContext
{
    public DbSet<ConsoleModel> consoles { get; set; }
    public DbSet<GameModel> Games { get; set; }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseNpgsql(@"Host=localhost;Port=5432;Database=VideoGame;Username=postgres;Password=postgres");
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
    }
    static DataContext()
    {
        AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
    }
}

14) Replace the class Program.cs with this:

using System;

namespace EFCDB
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("EFCDB");

            Console.ReadLine();
        }
    }
}

15) Build the project

dotnet build

16) Add the initial migration

dotnet ef migrations add InitialCreate

This will create the folder “Migrations” with some files

17) Create the DB

dotnet ef database update

18) Use Postgresql extension to confirm the DB creation with the tables

19) Done

GitHub repository:

github.com/maqdel/Developing-101

Folder: 003_Csharp

#Codespaces – Update environment from .Net from 8 to 9

We start with the premise that we have a Codespace with .Net 8

1) Go to file “Dockerfile” in folder “.devcontainer” and find line:

FROM mcr.microsoft.com/devcontainers/dotnet:1-8.0

Replace 8 for 9

FROM mcr.microsoft.com/devcontainers/dotnet:1-9.0

2) Save the change and rebuild the container with Full Rebuild option in the Command palette (Ctrl+Shift+P)

>Codespaces: Rebuild Container

3) Open a terminal and type:

dotnet --info

4) Go to file “DI.csproj” in folder “002_Csharp\DI” and find line:

<TargetFramework>net8.0</TargetFramework>

Replace 8 for 9

<TargetFramework>net9.0</TargetFramework>

5) Save change and run the project

dotnet run

6) Done, Codespace and project with .Net 9

Github repository:

github.com/maqdel/Developing-101

Folders: .devcontainer and 002_Csharp\DI\

#WTHI? Dependency Injection(DI) with C#

Dependency Injection(DI) is a design pattern where an object receives its dependencies from another object instead of creating them (Inversion of Control: IoC).

Advantages:
Flexible code
Easy to test
Easy to maintain

Dependency and Coupling

Class dependency is when one class uses a method or object from another class; coupling is how much one class depends on another.

Let’s say we have 2 classes: VideoGamePlayer and Playstation

public class VideoGamePlayer
{
    public void Play()
    {
        var ps = new Playstation();
        ps.Name();
        ps.Play();
    }
}
public class Playstation
{
  public void Name()
  {
    Console.WriteLine("Playstation");
  }
  public void Start()
  {
    Console.WriteLine("Playing Playstation!!!");
  }
}
var vgp = new VideoGamePlayer();
vgp.Play();

In this scenario, the VideoGamePlayer class depends on the Playstation class to execute Name and Start.

The problem is that we have an implicit dependency (we don’t know that VideoGamePlayer instantiates VideoGamePlayer unless we have the code) and a hard dependency (we can’t change the dependency); and the coupling is high (VideoGamePlayer directly instantiates PlayStation).

Dependency Injection via Constructor

With dependency injection, we seek to eliminate previous problems by making dependencies explicit and reducing coupling.

The first thing is to make an interface between the VideoGamePlayer and PlayStation classes that defines the properties of the latter, IConsole

public interface IConsole
{
    public void Name()
    public void Start();
}

Let’s implement the interface to the PlaystationDI class

public class PlaystationDI : IConsole
{
  public void Name()
  {
    Console.WriteLine("Playstation");
  }
  public void Start()
  {
    Console.WriteLine("Playing Playstation!!!");
  }
}

Let’s update the VideoGamePlayerDI class by adding a constructor that receives the IConsole interface and assigns it to a private property.

public class VideoGamePlayerDI_A
{
    private readonly IConsole console;
    public VideoGamePlayerDI_A(IConsole console)
    {
        this.console = console;
    }
    public void Play()
    {
        console.Name();
        console.Start();
    }
}

Now we can call the VideoGamePlayerDI class and specify the PlaystationDI class

var vgpDIA = new VideoGamePlayerDI_A(new PlaystationDI());
vgpDIA.Play();

In this way we can inject into VideogameplayerDI class different dependencies

public class XboxDI : IConsole
{
  public void Name()
  {
    Console.WriteLine("Xbox");
  }
  public void Start()
  {
    Console.WriteLine("Playing Xbox!!!");
  }
}
public class SwitchDI : IConsole
{
  public void Name()
  {
    Console.WriteLine("Switch");
  }
  public void Start()
  {
    Console.WriteLine("Playing Switch!!!");
  }
}

Using the same VideoGamePlayerDI and just changing the console

var vgpDIA = new VideoGamePlayerDI_A(new PlaystationDI());
vgpDIA.Play();
vgpDIA = new VideoGamePlayerDI_A(new XboxDI());
vgpDIA.Play();
vgpDIA = new VideoGamePlayerDI_A(new SwitchDI());
vgpDIA.Play();

Dependency Injection via Setter

We follow the same principle but the injection is done through a Setter and not the Constructor; We remove the interface from the constructor and add a setter that receives the interface.

public class VideoGamePlayerDI_B
{
    private IConsole console;
    public IConsole Console
    {
        set { console = value; }
    }
    public VideoGamePlayerDI_B()
    {
    }
    public void Play()
    {
        console.Name();
        console.Start();
    }
}

Then we update the call passing the console from the setter

var vgpDIB = new VideoGamePlayerDI_B();
vgpDIB.Console = new PlaystationDI();
vgpDIB.Play();

Dependency Injection via Method

In this case we directly use the method to make the injection, we eliminate the setter

public class VideoGamePlayerDI_C
{
    public VideoGamePlayerDI_C()
    {
    }
    public void Play(IConsole console)
    {
        console.Name();
        console.Start();
    }
}

Then we do the injection directly on the method

var vgpDIC = new VideoGamePlayerDI_C();
vgpDIC.Play(new XboxDI());

GitHub repository:

Folder: 02_Csharp

github.com/maqdel/Developing-101

#React – Create a React app with TypeScrip using Vite

Steps to create a React app with TypeScript using Vite in Codespace (You can use others IDE but need to settled up first)

1) Open a terminal and type:

npm create vite@latest my-react-app -- --template react-ts

“my-react-app” will be used as the name of your application and the folder where it will be created

2) Choose React as framework and TypeScript as Variant

3) When is done, change to the folder: my-react-app

cd my-react-app

4) Install NPM packages for the project

npm install

5) Run de app

npm run dev

6) Open URL: localhost:5173/

8) All ready

github.com/maqdel/Developing-101

Folder: 001_React

#Codespaces – Setting up an environment with .Net 8, PostgreSQL, and Node.js

1) Create a Codespace in Github – github.com/codespaces

2) In the Codespace create a folder in the root with name: .devcontainer

3) In the new folder add a file with name: devcontainer.json

// For format details, see https://aka.ms/devcontainer.json. For config options, see the
// README at: https://github.com/devcontainers/templates/tree/main/src/dotnet-postgres
{
    "name": ".NET and PostgreSQL",
    "dockerComposeFile": "docker-compose.yml",
    "service": "app",
    "workspaceFolder": "/workspaces/${localWorkspaceFolderBasename}",

	// Features to add to the dev container. More info: https://containers.dev/features.
	// "features": {},

	// Configure tool-specific properties.
	// "customizations": {},

	// Use 'forwardPorts' to make a list of ports inside the container available locally.
	"forwardPorts": [5432],
	 "portsAttributes": {
			"5432": {
				"label": "DB-Postgres:14.3"}
		},

    // Use 'postCreateCommand' to run commands after the container is created.
    //"postCreateCommand": "dotnet --info"

	// Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
    //"remoteUser": "root",
    "customizations": {
        "vscode": {
            "extensions": [
                "GitHub.copilot"
            ]
        }
    }
}

4) Add a second file with name: docker-compose.yml

version: '3.8'

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile

    volumes:
      - ../..:/workspaces:cached

    # Overrides default command so things don't shut down after the process ends.
    command: sleep infinity

    # Runs app on the same network as the database container, allows "forwardPorts" in devcontainer.json function.
    network_mode: service:db

    # Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
    # user: root

    # Use "forwardPorts" in **devcontainer.json** to forward an app port locally.
    # (Adding the "ports" property to this file will not forward from a Codespace.)

  db:
    image: postgres:14.3
    restart: unless-stopped
    volumes:
      - postgres-data:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: postgres
      POSTGRES_USER: postgres
      POSTGRES_DB: postgres

    # Add "forwardPorts": ["5432"] to **devcontainer.json** to forward PostgreSQL locally.
    # (Adding the "ports" property to this file will not forward from a Codespace.)

volumes:
  postgres-data:

5) Add a third file with name: Dockerfile

FROM mcr.microsoft.com/devcontainers/dotnet:1-8.0
# Install Node.js
RUN curl -fsSL https://deb.nodesource.com/setup_14.x | bash -
RUN apt-get install -y nodejs \
    && apt-get install -y npm
# [Optional] Uncomment this section to install additional OS packages.
# RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
#     && apt-get -y install --no-install-recommends <your-package-list-here>

ENV PATH="${PATH}:/root/.dotnet/tools"
RUN dotnet tool install --global dotnet-ef --version 8.0.6

RUN echo "---------------------------------------"
RUN echo "All ready"
RUN echo "---------------------------------------"
# [Optional] Uncomment this line to install global node packages.
# RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g <your-package-here>" 2>&1

6) Rebuild the container with Full Rebuild option in the Command palette (Ctrl+Shift+P)

>Codespaces: Rebuild Container

7 Install VSCode extension: PostgreSQL (This only to test the database)

8 Create a connection to the database with the PostgreSQL extension

  • Host: localhost
  • Database: postgres
  • Username: postgres
  • Password: postgres

You can change this values editing the file: docker-compose.yml

7) To check the .Net installed open a terminal and type:

dotnet --list-sdks

8) To check Node.js installed open a terminal and type:

node --version

9) To check NPM installed open a terminal and type:

npm --version

github.com/maqdel/Developing-101

Folder: .devcontainer

  • .Net 8.0.410
  • PostgreSql 14.3
  • Node: 18.19.0
  • NPM: 9.2.0

#React Unique function for API calls with Axios catching errors

With Typescript

static async axiosAPICaller(
    apiMethod: string,
    apiURL: string,
    apiData: any,
    headers: any
    ): Promise<any>
{
  try {
    const response =
        await axios({
            method: apiMethod,
            url: apiURL,
            data: apiData,
            timeout: 0,
            headers: headers
        });
    const responseData = response.data;
    if (!responseData.asError) {
      return responseData;
    } else {
      throw new Error(responseData.errorMessage);
    }
  }
  catch (error) {
    const errorMessage =
        error instanceof Error ? error.message : "Unknown error message";
    const errorName =
        error instanceof Error ? error.name : "Unknown error name";
    const errorCode =
        error instanceof Error ? (error as any)?.code : "Unknown error code";
    throw
        new Error(`Error in axiosAPICaller: ${ errorMessage }, ${errorName}, ${errorCode}`);
  }
}

Axios 1.6.8

#WTHI? Rest URIs naming

GET
..example.com/items/{id}
POST
..example.com/items
PUT
..example.com/items/{id}
DELETE
..example.com/items/{id}

Retrieve all the collection of resources
..example.com/items
Retrieve a collection of resources with parameters
..example.com/items?paramA=1&paramB=2
Retrieve a specific resource
..example.com/items/{id}
Retrieve a specific resource value
..example.com/items/{id}/valueName

GET API Response Codes

200 – OK
404 – Not found
400 – Bad request

Create a resource (the values are in the body)
..example.com/items
Create a subresource to the specific resource (the values are in the body)
..example.com/items/{id}/subItems

POST API Response Codes

200 – OK
201 – Created
204 – No content

Update the specific resource (the values are in the body)
..example.com/items/{id}
Update the specific subresource from the specific resource (the values are in the body)
..example.com/items/{id}/subItems/{id2}

POST API Response Codes

200 – OK
201 – Created
204 – No content

Delete the specific resource (the values are in the body)
..example.com/items/{id}
Delete the specific subresource from the specific resource (the values are in the body)
..example.com/items/{id}/subItems/{id2}

DELETE API Response Codes

200 – OK
202 – Accepted
204 – No content
404 – Not found

#React add environment variables

-Having a react project created with Vite named “reactproject“, in the project root add the file “.env” (reactproject/.env)

VITE_VALUE_A = '123'
VITE_VALUE_B = 'ABC'

NOTE: Is important that each variable name begins with “VITE_“

-To access the value use:

readValue: import.meta.env.VITE_VALUE_A

Create your own website, free on WordPress.com.Create your own website.
Start free