---
# System prepended metadata

title: CSharp Full Stack
tags: [Template]

---

###### tags: `Template`

# CSharp Full Stack
---
- In following this anything inside the [{<>}] is somthing that will need to be changed. Pay attention to the words inside to know what to put.  I will use the same words through out so if it is called ProjectName forexample everywhere you see that it should be changed to the same thing.  If coppied to your VS code it will most likely already have red squigglies

## Step 1:
- Create the project
- Make sure that you are where you want the project folder to be

```
dotnet new mvc --no-https -o [{<ProjectName>}]
```

## Step 2:
- cd into the new folder.
- Add the following packages
```
dotnet add package Pomelo.EntityFrameworkCore.MySql --version 6.0.1
dotnet add package Microsoft.EntityFrameworkCore.Design --version 6.0.3
```
- Verify the packages have been added by looking in the .csproj file

## Step 3:
- Open the appsettings.json file and either copy all of the following or add just the DefaultConnection part
```
{  
    "Logging": {    
        "LogLevel": {      
            "Default": "Information",      
            "Microsoft.AspNetCore": "Warning"    
        }  
    },
    "AllowedHosts": "*",    
    "ConnectionStrings":    
    {        
        "DefaultConnection": "Server=localhost;port=3306;userid=root;password=root;database=monsterdb;"    
    }
}
```
- Make sure to update the userid, password, and database inside the DefaultConnection to be what your workbench is.  (This will need to be changed again if you deploy your app to match what the host has)

## Step 4:
- Edit the Program.cs file to have the following. (Most will be there so you can edit the missing lines)
```
using Microsoft.EntityFrameworkCore;
using [{<ProjectName>}].Models;

var builder = WebApplication.CreateBuilder(args);

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");

builder.Services.AddControllersWithViews();

builder.Services.AddHttpContextAccessor();  
builder.Services.AddSession();  

builder.Services.AddDbContext<MyContext>(options =>
{
    options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
});


var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.UseSession();    

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();
```

## Step 5:
- Add a new modle file called MyContext.cs and add the following
- Be sure to change the current last line of text to your ClassName and plural ClassName and repeat this line for every class you create.  Not the file just that line
```
#pragma warning disable CS8618

using Microsoft.EntityFrameworkCore;
namespace [{<YourProjectName>}].Models;

public class MyContext : DbContext 
{    
    public MyContext(DbContextOptions options) : base(options) { }    
   
    public DbSet<ClassName> ClassNames { get; set; } 
}

```
## Step 6:
- Update the HomeController file to referance MyContext as this example has
```
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using [{<ProjectName>}].Models;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;

namespace [{<ProjectName>}].Controllers;

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

    private MyContext db;  // or use _context instead of db

    public HomeController(ILogger<HomeController> logger, MyContext context)
    {
        _logger = logger;
        db = context; // if you use _context above use it here too
    }

    public IActionResult Index()
    {
        return View();  
    }

    public IActionResult Privacy()
    {
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}
public class SessionCheckAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        // Find the session, but remember it may be null so we need int?
        int? uid = context.HttpContext.Session.GetInt32("uid");
        // Check to see if we got back null
        if(uid == null)
        {
            // Redirect to the Index page if there was nothing in session
            // "Home" here is referring to "HomeController", you can use any controller that is appropriate here
            context.Result = new RedirectToActionResult("Index", "User", null);
        }
    }
}

```
## Step 7:
- Next is to build your class/Model files Each should contain the following
```
#pragma warning disable CS8618
using System.ComponentModel.DataAnnotations;
namespace [{<ProjectName>}].Models;

public class <ClassName> {
    [Key]
    public int ClassNameId {get; set;}
    // add more attributes here
    
    
    public DateTime CreatedAt { get; set; } = DateTime.Now;
    public DateTime UpdatedAt { get; set; } = DateTime.Now;
}
```
## Step 8:
- Once all the Model files have been created you can now run the following commands to create your database
```
dotnet ef migrations add FirstMigration

dotnet ef database update
```

## Step 9:
- From here you will add a controller file for every class you have created
```
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using [{<ProjectName>}].Models;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;

namespace [{<ProjectName>}].Controllers;

public class [{<ClassNameController>}] : Controller 
{

    private MyContext db;  // or use _context instead of db (Make sure this matches on all controller files)
    
    public [{<ClassNameController>}](MyContext context)
    {
        db = context; // if you use _context above use it here too (Make sure this matches on all controller files)
    }
    private int? uid {
        get {
            return HttpContext.Session.GetInt32("uid");
        }
    }
    
    // Recommend routeName and FunctionName be the same
    
    [HttpGet("/ClassName/routeName")]
    public IActionResult FunctionName() {
    
    }
    
    
}
```

## Step 10:
- View folders will need to be created for every Controller file you create.
- cshtml files will be added as per the controller file