init push

This commit is contained in:
Christopher Sanden
2026-03-27 14:06:21 +01:00
committed by Chris
parent e8497b617b
commit 9f094d1171
369 changed files with 85890 additions and 0 deletions

View File

@@ -0,0 +1,15 @@
# Default ignored files
/shelf/
/workspace.xml
# Rider ignored files
/modules.xml
/projectSettingsUpdater.xml
/contentModel.xml
/.idea.Example.iml
# Ignored default folder with query files
/queries/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
# Editor-based HTTP Client requests
/httpRequests/

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding" addBOMForNewFiles="with BOM under Windows, with no BOM otherwise" />
</project>

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="UserContentModel">
<attachedFolders />
<explicitIncludes />
<explicitExcludes />
</component>
</project>

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/../.." vcs="Git" />
</component>
</project>

View File

@@ -0,0 +1,3 @@
@{
Layout = "/Views/Shared/_Layout.cshtml";
}

View File

@@ -0,0 +1,93 @@
using Microsoft.AspNetCore.Mvc;
using Example.Data;
using Example.Models;
namespace Example.Controllers;
public class AuthorsController : Controller
{
// Added private field for the application db context
private readonly ApplicationDbContext _db;
// Constructor with db context as a parameter
public AuthorsController(ApplicationDbContext db)
{
_db = db;
}
// GET
public IActionResult Index()
{
// Fetch authors from the database
var authors = _db.Authors.ToList();
// Send the list to the view. The view declares its model as @model IEnumerable<Author> to match.
return View(authors);
}
[HttpGet]
public IActionResult Add()
{
// Send in an empty model to the view. Required because the view must receive a model object.
return View(new Author());
}
[HttpPost]
public IActionResult Add(Author author)
{
// Return the page with the current form values if the model is invalid. Allows the user to fix their mistakes.
if (!ModelState.IsValid)
return View(author);
// Add and save the new author
_db.Authors.Add(author);
_db.SaveChanges();
// Return back to the index view (the one with the list of authors)
return RedirectToAction(nameof(Index));
}
[HttpGet]
public IActionResult Edit(int id)
{
// Find the existing author based on primary key
var author = _db.Authors.Find(id);
// Return 404 not found if the author does not exist
if (author == null)
return NotFound();
// Reuse the add view
return View("Add", author);
}
[HttpPost]
public IActionResult Edit(int id, Author author)
{
// Return the page with the current form values if the model is invalid. Allows the user to fix their mistakes.
if (!ModelState.IsValid)
return View("Add", author);
_db.Authors.Update(author);
_db.SaveChanges();
// Return back to the index view (the one with the list of authors)
return RedirectToAction(nameof(Index));
}
public IActionResult Delete(int id)
{
// Find the existing author based on primary key
var author = _db.Authors.Find(id);
// Return 404 not found if the author does not exist
if (author == null)
return NotFound();
_db.Authors.Remove(author);
_db.SaveChanges();
// Return back to the index view (the one with the list of authors)
return RedirectToAction(nameof(Index));
}
}

View File

@@ -0,0 +1,33 @@
using System.Diagnostics;
using Example.Data;
using Microsoft.AspNetCore.Mvc;
using Example.Models;
namespace Example.Controllers;
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
// Added application db context as parameter
public HomeController(ILogger<HomeController> logger, ApplicationDbContext db)
{
_logger = logger;
}
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 });
}
}

View File

@@ -0,0 +1,17 @@
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Example.Models;
namespace Example.Data;
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Author> Authors => Set<Author>();
public DbSet<Book> Books => Set<Book>();
public DbSet<Review> Reviews => Set<Review>();
}

View File

@@ -0,0 +1,30 @@
using Example.Models;
namespace Example.Data
{
public static class ApplicationDbInitializer
{
public static void Initialize(ApplicationDbContext db)
{
// Delete the database before we initialize it. This is common to do during development.
db.Database.EnsureDeleted();
// Recreate the database and tables according to our models
db.Database.EnsureCreated();
// Add test data to simplify debugging and testing
var authors = new[]
{
new Author("Author 1", "Author 1", new DateTime(1981, 1, 1)),
new Author("Author 2", "Author 2", new DateTime(1982, 2, 2)),
new Author("Author 3", "Author 3", new DateTime(1983, 3, 3))
};
db.Authors.AddRange(authors);
// Finally save the added relationships
db.SaveChanges();
}
}
}

View File

@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>aspnet-Example-334f5f9d-b4ba-4f6a-bab2-dd40704d3fd3</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<None Update="app.db" CopyToOutputDirectory="PreserveNewest" ExcludeFromSingleFile="true" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="8.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="8.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.2" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="8.0.1" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,35 @@
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace Example.Models
{
public class Author
{
public Author() {}
public Author(string firstName, string lastName, DateTime birthdate)
{
FirstName = firstName;
LastName = lastName;
Birthdate = birthdate;
}
public int Id { get; set; }
[Required]
[StringLength(100)]
[DisplayName("First name")]
public string FirstName { get; set; } = string.Empty;
[Required]
[StringLength(100)]
[DisplayName("Last name")]
public string LastName { get; set; } = string.Empty;
[DataType(DataType.Date)]
[DisplayName("Birthdate")]
public DateTime Birthdate { get; set; }
public ICollection<Review> Reviews { get; set; } = new List<Review>();
}
}

View File

@@ -0,0 +1,21 @@
using System.ComponentModel.DataAnnotations;
namespace Example.Models
{
public class Book
{
public Book() {}
public int Id { get; set; }
[Required]
[StringLength(200)]
public string Title { get; set; } = string.Empty;
[StringLength(1000)]
public string Summary { get; set; } = string.Empty;
[DataType(DataType.Date)]
public DateTime Published { get; set; }
}
}

View File

@@ -0,0 +1,8 @@
namespace Example.Models;
public class ErrorViewModel
{
public string? RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}

View File

@@ -0,0 +1,21 @@
using System.ComponentModel.DataAnnotations;
namespace Example.Models
{
public class Review
{
Review() {}
public int Id { get; set; }
[Range(1, 5)]
public int Stars { get; set; }
[StringLength(1000)]
public string Text { get; set; } = string.Empty;
public int AuthorId { get; set; }
public Author? Author { get; set; }
}
}

View File

@@ -0,0 +1,51 @@
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Example.Data;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Call the database initializer
using (var services = app.Services.CreateScope())
{
var db = services.ServiceProvider.GetRequiredService<ApplicationDbContext>();
ApplicationDbInitializer.Initialize(db);
}
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();
app.Run();

View File

@@ -0,0 +1,28 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:25776",
"sslPort": 44381
}
},
"profiles": {
"Example": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7115;http://localhost:5224",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -0,0 +1,36 @@
@model Author
@{
ViewBag.Title = "title";
Layout = "_Layout";
}
<h2>Add / edit author</h2>
<form method="post">
<div class="row mb-3">
<label asp-for="FirstName" class="col-sm-2 col-form-label"></label>
<div class="col-sm-3">
<input asp-for="FirstName" class="form-control">
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="LastName" class="col-sm-2 col-form-label"></label>
<div class="col-sm-3">
<input asp-for="LastName" class="form-control">
<span asp-validation-for="LastName" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="Birthdate" class="col-sm-2 col-form-label"></label>
<div class="col-sm-3">
<input asp-for="Birthdate" class="form-control">
<span asp-validation-for="Birthdate" class="text-danger"></span>
</div>
</div>
<input type="submit" class="btn btn-primary" value="Save">
</form>

View File

@@ -0,0 +1,23 @@
@model IEnumerable<Author>
@{
ViewBag.Title = "title";
Layout = "_Layout";
}
<h2>Authors</h2>
<ul>
@foreach (var author in Model)
{
<li>
@author.FirstName @author.LastName |
<a asp-controller="Authors" asp-action="Edit" asp-route-id="@author.Id">Edit</a> |
<a asp-controller="Authors" asp-action="Delete" asp-route-id="@author.Id">Delete</a>
</li>
}
</ul>
<p><a asp-controller="Authors" asp-action="Add">Add new Author</a></p>

View File

@@ -0,0 +1,8 @@
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

View File

@@ -0,0 +1,6 @@
@{
ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>
<p>Use this page to detail your site's privacy policy.</p>

View File

@@ -0,0 +1,25 @@
@model ErrorViewModel
@{
ViewData["Title"] = "Error";
}
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
@if (Model.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@Model.RequestId</code>
</p>
}
<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>

View File

@@ -0,0 +1,53 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - Example</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container-fluid">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">Example</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Authors" asp-action="Index">Authors</a>
</li>
</ul>
<partial name="_LoginPartial" />
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
&copy; 2022 - Example - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
<partial name="_ValidationScriptsPartial" />
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>

View File

@@ -0,0 +1,48 @@
/* Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
for details on configuring this project to bundle and minify static web assets. */
a.navbar-brand {
white-space: normal;
text-align: center;
word-break: break-all;
}
a {
color: #0077cc;
}
.btn-primary {
color: #fff;
background-color: #1b6ec2;
border-color: #1861ac;
}
.nav-pills .nav-link.active, .nav-pills .show > .nav-link {
color: #fff;
background-color: #1b6ec2;
border-color: #1861ac;
}
.border-top {
border-top: 1px solid #e5e5e5;
}
.border-bottom {
border-bottom: 1px solid #e5e5e5;
}
.box-shadow {
box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .05);
}
button.accept-policy {
font-size: 1rem;
line-height: inherit;
}
.footer {
position: absolute;
bottom: 0;
width: 100%;
white-space: nowrap;
line-height: 60px;
}

View File

@@ -0,0 +1,26 @@
@using Microsoft.AspNetCore.Identity
@inject SignInManager<IdentityUser> SignInManager
@inject UserManager<IdentityUser> UserManager
<ul class="navbar-nav">
@if (SignInManager.IsSignedIn(User))
{
<li class="nav-item">
<a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @User.Identity?.Name!</a>
</li>
<li class="nav-item">
<form class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="@Url.Action("Index", "Home", new { area = "" })">
<button type="submit" class="nav-link btn btn-link text-dark">Logout</button>
</form>
</li>
}
else
{
<li class="nav-item">
<a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Register">Register</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Login">Login</a>
</li>
}
</ul>

View File

@@ -0,0 +1,2 @@
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>

View File

@@ -0,0 +1,3 @@
@using Example
@using Example.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

View File

@@ -0,0 +1,3 @@
@{
Layout = "_Layout";
}

BIN
Example/Example/app.db Normal file

Binary file not shown.

View File

@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@@ -0,0 +1,12 @@
{
"ConnectionStrings": {
"DefaultConnection": "DataSource=app.db;Cache=Shared"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,20 @@
{
"runtimeOptions": {
"tfm": "net8.0",
"frameworks": [
{
"name": "Microsoft.NETCore.App",
"version": "8.0.0"
},
{
"name": "Microsoft.AspNetCore.App",
"version": "8.0.0"
}
],
"configProperties": {
"System.GC.Server": true,
"System.Reflection.NullabilityInfoContext.IsSupported": true,
"System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization": false
}
}
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More