Compare commits

..

3 Commits

Author SHA1 Message Date
Shuozhe 0733b933da connecting with database.. 2021-06-05 02:23:38 +02:00
Shuozhe ee92564bf2 added logging 2021-06-04 02:43:16 +02:00
Shuozhe 39ca7cba3b added (unused) database stuffs 2021-06-04 01:53:27 +02:00
12 changed files with 177 additions and 24 deletions

View File

@ -6,8 +6,9 @@ using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using ProjectGrid.Data;
namespace vue_dotnet_example.Controllers namespace ProjectGrid.Controllers
{ {
[ApiController] [ApiController]
public class UsersController : ControllerBase public class UsersController : ControllerBase
@ -15,7 +16,8 @@ namespace vue_dotnet_example.Controllers
private readonly ILogger<UsersController> _logger; private readonly ILogger<UsersController> _logger;
static readonly Models.IUserRepository repository = new Models.UserRepository(); //static readonly Models.IUserRepository repository = new Models.UserRepository();
static readonly Models.IUserRepository repository = DataAccessContext.GetInstance();
public UsersController(ILogger<UsersController> logger) public UsersController(ILogger<UsersController> logger)
{ {

61
Data/DataAccessContext.cs Normal file
View File

@ -0,0 +1,61 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using ProjectGrid.Models;
namespace ProjectGrid.Data
{
public class DataAccessContext : DbContext, IUserRepository
{
private static DataAccessContext _instance;
public static DataAccessContext GetInstance() => _instance;
public DataAccessContext(DbContextOptions<DataAccessContext> options) : base(options)
{
_instance = this;
}
public DbSet<UserData> Users { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<UserData>().ToTable("USER");
}
public IEnumerable<UserModel> GetAll()
{
return Users.Select<UserData, UserModel>( data => data.ToModel() );
}
public UserModel Add(UserModel user)
{
// TODO: check if exist
Users.Add(new UserData(user));
SaveChanges();
return user;
}
}
public class UserData
{
public int? Id { get; set; }
public string Name1 { get; set; }
public string Name2 { get; set; }
public string Email { get; set; }
public UserData() { }
public UserData(UserModel model)
{
Name1 = model.firstName;
Name2 = model.lastName;
Email = model.email;
}
public UserModel ToModel()
{
return new UserModel {firstName = Name1, lastName = Name2, email = Email};
}
}
}

39
Data/DemoData.cs Normal file
View File

@ -0,0 +1,39 @@
using ProjectGrid.Models;
using System;
using System.Linq;
namespace ProjectGrid.Data
{
public static class DbInitializer
{
public static void Initialize(DataAccessContext context)
{
context.Database.EnsureCreated();
// Look for any UserDatas.
if (context.Users.Any())
{
return; // DB has been seeded
}
var users = new UserData[]
{
new UserData{Name1="Carson",Name2="Alexander",Email="test@abc.com"},
new UserData{Name1="Meredith",Name2="Alonso",Email="test@abc.com"},
new UserData{Name1="Arturo",Name2="Anand",Email="test@abc.com"},
new UserData{Name1="Gytis",Name2="Barzdukas",Email="test@abc.com"},
new UserData{Name1="Yan",Name2="Li",Email="test@abc.com"},
new UserData{Name1="Peggy",Name2="Justice",Email="test@abc.com"},
new UserData{Name1="Laura",Name2="Norman",Email="test@abc.com"},
new UserData{Name1="Nino",Name2="Olivetto",Email="test@abc.com"}
};
foreach (UserData s in users)
{
context.Users.Add(s);
}
context.SaveChanges();
}
}
}

View File

@ -1,7 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace vue_dotnet_example.Models namespace ProjectGrid.Models
{ {
public interface IUserRepository public interface IUserRepository
{ {

View File

@ -1,4 +1,4 @@
namespace vue_dotnet_example.Models namespace ProjectGrid.Models
{ {
public class UserModel public class UserModel
{ {

View File

@ -1,7 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace vue_dotnet_example.Models namespace ProjectGrid.Models
{ {
public class UserRepository: IUserRepository public class UserRepository: IUserRepository
{ {

View File

@ -1,3 +1,5 @@
using ProjectGrid.Data;
using Microsoft.Extensions.DependencyInjection;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -7,17 +9,42 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace vue_dotnet_example namespace ProjectGrid
{ {
public class Program public class Program
{ {
private static ILogger _logger;
public static void Main(string[] args) public static void Main(string[] args)
{ {
CreateHostBuilder(args).Build().Run(); var host = CreateHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
_logger = services.GetRequiredService<ILogger<Program>>();
try
{
var context = services.GetRequiredService<DataAccessContext>();
DbInitializer.Initialize(context);
}
catch (Exception ex)
{
_logger.LogError(ex, "An error occurred while seeding the database.");
}
}
host.Run();
} }
public static IHostBuilder CreateHostBuilder(string[] args) => public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args) Host.CreateDefaultBuilder(args)
.ConfigureLogging(loggingBuilder =>
{
loggingBuilder.ClearProviders();
loggingBuilder.AddDebug().AddConsole();
})
.ConfigureWebHostDefaults(webBuilder => .ConfigureWebHostDefaults(webBuilder =>
{ {
webBuilder.UseStartup<Startup>(); webBuilder.UseStartup<Startup>();

View File

@ -8,6 +8,11 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="5.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.6" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="5.0.1" />
<PackageReference Include="Microsoft.Extensions.Logging.ApplicationInsights" Version="2.17.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="5.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
</ItemGroup> </ItemGroup>

View File

@ -17,7 +17,7 @@
"ASPNETCORE_ENVIRONMENT": "Development" "ASPNETCORE_ENVIRONMENT": "Development"
} }
}, },
"vue_dotnet_example": { "ProjectGrid": {
"commandName": "Project", "commandName": "Project",
"dotnetRunMessages": "true", "dotnetRunMessages": "true",
"launchBrowser": true, "launchBrowser": true,

View File

@ -1,47 +1,60 @@
using System; using Microsoft.ApplicationInsights.Channel;
using System.Collections.Generic; using Microsoft.ApplicationInsights.Extensibility;
using System.Linq; using Microsoft.Extensions.DependencyInjection;
using System.Threading.Tasks; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.ApplicationInsights;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
using Microsoft.EntityFrameworkCore;
using ProjectGrid.Data;
namespace vue_dotnet_example namespace ProjectGrid
{ {
public class Startup public class Startup
{ {
public Startup(IConfiguration configuration) ILogger _logger;
public Startup()
{ {
Configuration = configuration; Configuration = new ConfigurationBuilder()
.AddJsonFile("appSettings.json") // Get Connectionstring from appsetting.json
.Build();
} }
public IConfiguration Configuration { get; } public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container. // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
{ {
var connectionString = Configuration.GetConnectionString("DefaultConnection");
// Cant log here..
//_logger.LogInformation($"Try to connect to Database with {connectionString}");
services.AddDbContext<DataAccessContext>(options => options.UseSqlServer(connectionString));
//_logger.LogInformation($"DataAccessContext registered with {connectionString}");
// TODO: for Testing
//services.AddDatabaseDeveloperPageExceptionFilter();
services.AddControllers(); services.AddControllers();
services.AddSwaggerGen(c => services.AddSwaggerGen(c =>
{ {
c.SwaggerDoc("v1", new OpenApiInfo { Title = "vue_dotnet_example", Version = "v1" }); c.SwaggerDoc("v1", new OpenApiInfo { Title = "ProjectGrid", Version = "v1" });
}); });
} }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
{ {
_logger = logger;
if (env.IsDevelopment()) if (env.IsDevelopment())
{ {
app.UseDeveloperExceptionPage(); app.UseDeveloperExceptionPage();
app.UseSwagger(); app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "vue_dotnet_example v1")); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ProjectGrid v1"));
} }
app.UseHttpsRedirection(); app.UseHttpsRedirection();

View File

@ -1,9 +1,12 @@
{ {
"ConnectionStrings": {
"DefaultConnection": "Server=hello-world.games;Database=ProjectGrid;Driver=SQL Server;uid=net;pwd=15123456"
},
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
"Default": "Information", "Default": "Information",
"Microsoft": "Warning", "Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information" "Microsoft.Hosting.Lifetime": "Information"
} }
} }
} }

View File

@ -1,4 +1,7 @@
{ {
"ConnectionStrings": {
"DefaultConnection": "Server=hello-world.games;Database=ProjectGrid;uid=net;pwd=15123456"
},
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
"Default": "Information", "Default": "Information",