Skip to content

Commit 89353de

Browse files
committed
Inititial .NET 6.0 Conversion
1 parent 00ff187 commit 89353de

File tree

7 files changed

+233
-309
lines changed

7 files changed

+233
-309
lines changed

src/AlbumViewerBusiness/AlbumViewerBusiness.csproj

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
<Project Sdk="Microsoft.NET.Sdk">
22
<PropertyGroup>
3-
<TargetFramework>net5.0</TargetFramework>
3+
<TargetFramework>net6.0</TargetFramework>
44
</PropertyGroup>
55
<ItemGroup>
66
<!--<ProjectReference Include="..\Westwind.Utilities\Westwind.Utilities.csproj" />-->
77
</ItemGroup>
88
<ItemGroup>
99
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.0" />
10-
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
11-
<PackageReference Include="Westwind.Utilities" Version="3.0.48" />
10+
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
11+
<PackageReference Include="Westwind.Utilities" Version="3.1.7" />
1212
</ItemGroup>
1313
<ItemGroup>
1414
<Folder Include="Properties\" />

src/AlbumViewerNetCore/AlbumViewerNetCore.csproj

+10-8
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,24 @@
11
<Project Sdk="Microsoft.NET.Sdk.Web">
22
<PropertyGroup>
3-
<TargetFramework>net5.0</TargetFramework>
3+
<TargetFramework>net6.0</TargetFramework>
44
<UserSecretsId>d900d6cb-0e21-403b-94a3-17412045e7b4</UserSecretsId>
55
<Version>1.1</Version>
66
<AssemblyVersion>1.1.0.0</AssemblyVersion>
77
<FileVersion>1.1.0.0</FileVersion>
88
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
9+
<GenerateDocumentationFile>True</GenerateDocumentationFile>
910
</PropertyGroup>
1011

1112

1213
<ItemGroup>
13-
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.0" />
14-
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.0" />
15-
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.0" />
16-
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.0" />
17-
<PackageReference Include="Serilog.Extensions.Logging" Version="3.0.1" />
18-
<PackageReference Include="Serilog.Sinks.RollingFile" Version="3.3.0" />
19-
<PackageReference Include="Westwind.AspNetCore" Version="3.2.15" />
14+
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.0" />
15+
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.0" />
16+
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.0" />
17+
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.0" />
18+
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
19+
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
20+
<PackageReference Include="Westwind.AspNetCore" Version="3.4.5" />
21+
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
2022
<ProjectReference Include="..\AlbumViewerBusiness\AlbumViewerBusiness.csproj" />
2123
</ItemGroup>
2224

src/AlbumViewerNetCore/Program.cs

+214-26
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,225 @@
1-
using Microsoft.AspNetCore;
2-
using Microsoft.AspNetCore.Hosting;
3-
using Microsoft.AspNetCore.Server.HttpSys;
1+
using System;
2+
using System.IO;
3+
using Newtonsoft.Json.Serialization;
4+
using System.Text;
5+
using System.Text.Encodings.Web;
6+
using AlbumViewerAspNetCore;
47
using Microsoft.Extensions.Configuration;
8+
using AlbumViewerBusiness;
9+
using AlbumViewerBusiness.Configuration;
10+
using Microsoft.AspNetCore.Authentication.JwtBearer;
11+
using Microsoft.AspNetCore.Builder;
12+
using Microsoft.AspNetCore.Diagnostics;
13+
using Microsoft.AspNetCore.Http;
14+
using Microsoft.EntityFrameworkCore;
15+
using Microsoft.Extensions.DependencyInjection;
16+
using Microsoft.Extensions.Hosting;
17+
using Microsoft.IdentityModel.Tokens;
518

6-
namespace AlbumViewerNetCore
19+
20+
var builder = WebApplication.CreateBuilder(args);
21+
var services = builder.Services;
22+
var configuration = builder.Configuration;
23+
24+
var host = builder.Host;
25+
var webHost = builder.WebHost;
26+
var environment = builder.Environment;
27+
28+
29+
services.AddDbContext<AlbumViewerContext>(builder =>
730
{
8-
public class Program
31+
string useSqLite = configuration["Data:useSqLite"];
32+
if (useSqLite != "true")
933
{
10-
public static void Main(string[] args)
11-
{
12-
var builder = CreateWebHostBuilder(args);
13-
builder.Build().Run();
14-
}
15-
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
34+
var connStr = configuration["Data:SqlServerConnectionString"];
35+
builder.UseSqlServer(connStr, opt => opt.EnableRetryOnFailure());
36+
}
37+
else
38+
{
39+
// Note this path has to have full access for the Web user in order
40+
// to create the DB and write to it.
41+
var connStr = "Data Source=" +
42+
Path.Combine(environment.ContentRootPath, "AlbumViewerData.sqlite");
43+
builder.UseSqlite(connStr);
44+
}
45+
});
46+
47+
48+
var config = new ApplicationConfiguration();
49+
configuration.Bind("Application", config);
50+
services.AddSingleton(config);
51+
52+
App.Configuration = config;
53+
54+
// Also make top level configuration available (for EF configuration and access to connection string)
55+
services.AddSingleton<IConfigurationRoot>(configuration);
56+
services.AddSingleton<IConfiguration>(configuration);
57+
58+
// Cors policy is added to controllers via [EnableCors("CorsPolicy")]
59+
// or .UseCors("CorsPolicy") globally
60+
services.AddCors(options =>
61+
{
62+
options.AddPolicy("CorsPolicy",
63+
builder => builder
64+
// required if AllowCredentials is set also
65+
.SetIsOriginAllowed(s => true)
66+
//.AllowAnyOrigin()
67+
.AllowAnyMethod() // doesn't work for DELETE!
68+
.WithMethods("DELETE")
69+
.AllowAnyHeader()
70+
.AllowCredentials()
71+
);
72+
});
73+
74+
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
75+
.AddJwtBearer(options =>
76+
{
77+
options.TokenValidationParameters = new TokenValidationParameters
1678
{
79+
ValidateIssuer = true,
80+
ValidIssuer = config.JwtToken.Issuer,
81+
ValidateAudience = true,
82+
ValidAudience = config.JwtToken.Audience,
83+
ValidateIssuerSigningKey = true,
84+
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config.JwtToken.SigningKey))
85+
};
86+
87+
});
1788

18-
var builder = WebHost.CreateDefaultBuilder(args)
19-
.UseStartup<Startup>();
20-
//.UseIIS()
21-
//.UseHttpSys(options =>
22-
//{
23-
// options.Authentication.Schemes = AuthenticationSchemes.None;
24-
// options.Authentication.AllowAnonymous = true;
25-
// options.MaxConnections = 100;
26-
// options.MaxRequestBodySize = 30000000;
27-
// options.UrlPrefixes.Add("http://localhost:5002");
28-
//})
29-
30-
31-
return builder;
89+
// Instance injection
90+
services.AddScoped<AlbumRepository>();
91+
services.AddScoped<ArtistRepository>();
92+
services.AddScoped<AccountRepository>();
3293

94+
// Per request injections
95+
services.AddScoped<ApiExceptionFilter>();
96+
97+
services.AddControllers()
98+
// Use classic JSON
99+
.AddNewtonsoftJson(opt =>
100+
{
101+
var resolver = opt.SerializerSettings.ContractResolver;
102+
if (resolver != null)
103+
{
104+
var res = resolver as DefaultContractResolver;
105+
res.NamingStrategy = null;
33106
}
34107

108+
if (environment.IsDevelopment())
109+
opt.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
110+
});
35111

36-
}
112+
//
113+
// *** BUILD THE APP
114+
//
115+
var app = builder.Build();
116+
117+
118+
// Get any injected items
119+
var albumContext = app.Services.CreateScope().ServiceProvider.GetService<AlbumViewerContext>();
120+
121+
122+
123+
//Log.Logger = new LoggerConfiguration()
124+
// .WriteTo.RollingFile(pathFormat: "logs\\log-{Date}.log")
125+
// .CreateLogger();
126+
127+
//loggerFactory
128+
// .AddSerilog();
129+
130+
131+
if (environment.IsDevelopment())
132+
{
133+
app.UseDeveloperExceptionPage();
134+
135+
//app.UseDatabaseErrorPage();
136+
}
137+
else
138+
{
139+
app.UseExceptionHandler(errorApp =>
140+
141+
// Application level exception handler here - this is just a place holder
142+
errorApp.Run(async (context) =>
143+
{
144+
context.Response.StatusCode = 500;
145+
context.Response.ContentType = "text/html";
146+
await context.Response.WriteAsync("<html><body>\r\n");
147+
await context.Response.WriteAsync(
148+
"We're sorry, we encountered an un-expected issue with your application.<br>\r\n");
149+
150+
// Capture the exception
151+
var error = context.Features.Get<IExceptionHandlerFeature>();
152+
if (error != null)
153+
{
154+
// This error would not normally be exposed to the client
155+
await
156+
context.Response.WriteAsync("<br>Error: " +
157+
HtmlEncoder.Default.Encode(error.Error.Message) +
158+
"<br>\r\n");
159+
}
160+
await context.Response.WriteAsync("<br><a href=\"/\">Home</a><br>\r\n");
161+
await context.Response.WriteAsync("</body></html>\r\n");
162+
await context.Response.WriteAsync(new string(' ', 512)); // Padding for IE
163+
}));
37164
}
165+
166+
//app.UseHttpsRedirection();
167+
168+
169+
app.UseStatusCodePages();
170+
app.UseDefaultFiles(); // so index.html is not required
171+
app.UseStaticFiles();
172+
173+
app.UseRouting();
174+
175+
app.UseCors("CorsPolicy");
176+
177+
app.UseAuthentication();
178+
app.UseAuthorization();
179+
180+
// don't use the new simpler syntax as it doesn't terminate
181+
// and always fires the catch-all route below
182+
// if you don't have a catch-all route then this syntax is preferrable
183+
// app.MapControllers();
184+
185+
186+
// endpoint handler terminates and allows for catch-all middleware below
187+
app.UseEndpoints(app =>
188+
{
189+
app.MapControllers();
190+
});
191+
192+
// catch-all handler for HTML5 client routes - serve index.html
193+
app.Run(async context =>
194+
{
195+
var path = context.Request.Path.Value;
196+
197+
// Make sure Angular output was created in wwwroot
198+
// Running Angular in dev mode nukes output folder!
199+
// so it could be missing.
200+
if (environment.WebRootPath == null)
201+
throw new InvalidOperationException("wwwroot folder doesn't exist. Please recompile your Angular Project before accessing index.html. API calls will work fine.");
202+
203+
context.Response.ContentType = "text/html";
204+
await context.Response.SendFileAsync(Path.Combine(environment.WebRootPath, "index.html"));
205+
});
206+
207+
// Initialize Database if it doesn't exist
208+
AlbumViewerDataImporter.EnsureAlbumData(albumContext, Path.Combine(environment.ContentRootPath, "albums.js"));
209+
210+
Console.ForegroundColor = ConsoleColor.DarkYellow;
211+
Console.WriteLine($@"----------------
212+
AlbumViewer Core
213+
----------------");
214+
Console.ResetColor();
215+
216+
Console.WriteLine("\r\nPlatform: " + System.Runtime.InteropServices.RuntimeInformation.OSDescription);
217+
Console.WriteLine(".NET Version: " + System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription);
218+
Console.WriteLine("Hosting Environment: " + environment.EnvironmentName);
219+
string useSqLite = configuration["Data:useSqLite"];
220+
Console.WriteLine(useSqLite == "true" ? "SqLite" : "Sql Server");
221+
222+
223+
224+
225+
app.Run();

src/AlbumViewerNetCore/Properties/launchSettings.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
"launchBrowser": true,
2525
"launchUrl": "https://localhost:5001",
2626
"environmentVariables": {
27-
"ASPNETCORE_ENVIRONMENT": "Production"
27+
"ASPNETCORE_ENVIRONMENT": "Development"
2828
},
2929
"ancmHostingModel": "InProcess"
3030
},

0 commit comments

Comments
 (0)