Я разрабатываю приложение ядра dotnet с Angular.
Я пытаюсь перейти на ядро dotnet 2.1 и Angular 6.
Мне удалось сначала перейти на ядро dotnet 2.1 безпроблемы, но когда я попытался перейти на последнюю версию Angular, я столкнулся с проблемами.
Проблема не в самом Angular, а в веб-пакете.Я обновил все пакеты в package.json (за исключением пакетов webpack) до последних версий без проблем, но HMR не работал, и я тоже не смог запустить
webpack --config webpack.config.vendor.js
.
Итак, я использовал
npm install npm-check-updates -g
ncu -u
npm install
для обновления веб-пакета.
Теперь у меня есть этот package.json:
{
"name": "SIGAD",
"private": true,
"version": "0.0.0",
"scripts": {
"start": "node --max-old-space-size=1600 app.js < /dev/null",
"test": "karma start ClientApp/test/karma.conf.js"
},
"dependencies": {
"@angular-cool/storage": "^1.0.1",
"@angular/animations": "^6.1.7",
"@angular/common": "^6.1.7",
"@angular/compiler": "^6.1.7",
"@angular/core": "^6.1.7",
"@angular/forms": "^6.1.7",
"@angular/http": "^6.1.7",
"@angular/platform-browser": "^6.1.7",
"@angular/platform-browser-dynamic": "^6.1.7",
"@angular/platform-server": "^6.1.7",
"@angular/router": "^6.1.7",
"@ng-idle/core": "^6.0.0-beta.3",
"@ng-idle/keepalive": "^6.0.0-beta.3",
"@ngx-translate/core": "^10.0.2",
"@ngx-translate/http-loader": "^3.0.1",
"@types/webpack-env": "^1.13.6",
"angular2-cool-storage": "^3.1.3",
"angular2-moment": "^1.9.0",
"angular2-template-loader": "0.6.2",
"aspnet-prerendering": "^3.0.1",
"aspnet-webpack": "^3.0.0",
"core-js": "^2.5.7",
"es6-shim": "0.35.3",
"isomorphic-fetch": "2.2.1",
"json-loader": "0.5.7",
"ng-pick-datetime": "^6.0.16",
"ng2-datepicker-bootstrap": "^1.0.0",
"raw-loader": "0.5.1",
"rxjs": "^6.3.2",
"rxjs-compat": "^6.3.2",
"to-string-loader": "1.1.5",
"webpack-hot-middleware": "^2.24.0",
"webpack-merge": "^4.1.4",
"zone.js": "^0.8.26"
},
"devDependencies": {
"@angular-devkit/build-angular": "^0.8.1",
"@angular/cdk": "^6.4.7",
"@angular/cli": "^6.2.1",
"@angular/compiler-cli": "^6.1.7",
"@angular/language-service": "^6.1.7",
"@angular/material": "^6.4.7",
"@ngtools/webpack": "^6.2.1",
"@types/chai": "4.1.5",
"@types/jasmine": "^2.8.8",
"@types/node": "^10.9.4",
"awesome-typescript-loader": "^5.2.1",
"bootstrap": "^4.1.3",
"chai": "4.1.2",
"codelyzer": "^4.4.4",
"css": "^2.2.4",
"css-loader": "^1.0.0",
"event-source-polyfill": "0.0.16",
"expose-loader": "^0.7.5",
"extract-text-webpack-plugin": "^4.0.0-beta.0",
"file-loader": "^2.0.0",
"html-loader": "^0.5.5",
"jasmine-core": "^3.2.1",
"jasmine-spec-reporter": "^4.2.1",
"jquery": "^3.3.1",
"karma": "^3.0.0",
"karma-chai": "0.1.0",
"karma-chrome-launcher": "^2.2.0",
"karma-cli": "^1.0.1",
"karma-jasmine": "^1.1.2",
"karma-jasmine-html-reporter": "^1.3.1",
"karma-webpack": "3.0.5",
"popper.js": "^1.14.4",
"preboot": "^6.0.0-beta.5",
"protractor": "^5.4.1",
"reflect-metadata": "^0.1.12",
"rxjs-tslint": "^0.1.5",
"style-loader": "^0.23.0",
"tslint": "^5.11.0",
"typescript": "^3.0.3",
"url-loader": "^1.1.1",
"webpack": "^4.18.1",
"webpack-cli": "^3.1.0"
},
"buildOptions": {
"emitEntryPoint": true
}
}
Проблема в том,Я получаю внутреннюю ошибку сервера при попытке запустить приложение.При отладке я ловлю это исключение:
System.IO.FileNotFoundException: Could not load the specified file.
File name: 'System.Net.Sockets.resources'
at System.Runtime.Loader.AssemblyLoadContext.ResolveUsingEvent(AssemblyName assemblyName)
Я не изменил свой код C #.Я обновил все зависимости после перехода на dotnet core 2.1 без проблем.
Мой файл Startup.cs:
namespace SIGAD
{
public class Startup
{
private static string databaseConnection = "";
private const string SecretKey = "iNivDmHLpUA223sqsfhqGbMRdRj1PVkH"; // todo: get this from somewhere secure
private readonly SymmetricSecurityKey _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));
public Startup(IConfiguration config)
{
Configuration = config;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
try {
services.AddAutoMapper();
databaseConnection = Configuration.GetConnectionString("DefaultConnection");
if (databaseConnection == null) databaseConnection = "Server=localhost\\SQLEXPRESS;Database=SIGADCORE;Trusted_Connection=true";
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(databaseConnection));
DatabaseConnection.ConnectionString = databaseConnection;
services.AddSingleton<IJwtFactory, JwtFactory>();
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// jwt wire up
// Get options from app settings
var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));
// Configure JwtIssuerOptions
services.Configure<JwtIssuerOptions>(options =>
{
options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
});
services.AddAuthorization(options =>
{
options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.ApiAccess));
});
// Add application services.
services.AddTransient<IEmailSender, EmailSender>();
services.AddNodeServices();
services.AddSingleton(Configuration);
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
catch (Exception e)
{
AddErrorToDatabase(e);
}
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider, ILoggerFactory loggerFactory)
{
try {
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true,
HotModuleReplacementEndpoint = "/dist/__webpack_hmr"
});
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseDefaultFiles();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],
ValidateAudience = true,
ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],
ValidateIssuerSigningKey = true,
IssuerSigningKey = _signingKey,
RequireExpirationTime = false,
ValidateLifetime = false,
ClockSkew = TimeSpan.Zero
};
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
});
CreateRoles(serviceProvider);
if (Thread.CurrentThread.CurrentUICulture.Name == "en-US")
SessionConstants.CultureInfo = CultureInfo.CreateSpecificCulture("ro-RO");
else
SessionConstants.CultureInfo = CultureInfo.CreateSpecificCulture("ro-RO");
Thread.CurrentThread.CurrentCulture = SessionConstants.CultureInfo;
Thread.CurrentThread.CurrentUICulture = SessionConstants.CultureInfo;
}
catch (Exception e)
{
AddErrorToDatabase(e);
}
}
private void CreateRoles(IServiceProvider serviceProvider)
{
var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
Task<IdentityResult> roleResult;
string[] roleNames = { RoleNames.Admin, RoleNames.Supraveghetor, RoleNames.Operator, RoleNames.OperatorCuModificare, RoleNames.OperatorCuVizualizare };
//Check that there is an Administrator role and create if not
foreach (var roleName in roleNames)
{
Task<bool> hasAdminRole = roleManager.RoleExistsAsync(roleName);
hasAdminRole.Wait();
if (!hasAdminRole.Result)
{
roleResult = roleManager.CreateAsync(new IdentityRole(roleName));
roleResult.Wait();
}
}
}
public static void AddErrorToDatabase(Exception e)
{
// Get stack trace for the exception with source file information
var st = new StackTrace(e, true);
// Get the stack frames
string file = "";
string fileTemp = "";
string method = "";
string lineNumber = "";
foreach (StackFrame frame in st.GetFrames())
{
// Get the file name from the stack frame
fileTemp = frame.GetFileName() ?? "";
fileTemp = fileTemp.Replace('\\', '-').Split('-').Last().Trim();
int line = frame.GetFileLineNumber();
if (line > 0)
{
file += "-> " + fileTemp + "\n";
// Get the method from the stack frame
method = "-> " + frame.GetMethod().ToString().Substring(frame.GetMethod().ToString().IndexOf(' '), frame.GetMethod().ToString().IndexOf('(') - frame.GetMethod().ToString().IndexOf(' ')) + "\n";
// Get the line number from the stack frame
lineNumber += "-> " + frame.GetFileLineNumber().ToString() + "\n";
}
}
string destails = e.Message;
if (e.InnerException != null)
{
var innerException = e;
Exception realerror = e;
while (realerror.InnerException != null)
{
realerror = realerror.InnerException;
destails += "\n" + realerror.Message;
}
}
if (databaseConnection != null)
{
string QueryString = "INSERT INTO Error(Description,Moment,[File],Method,Line) VALUES (@description,@moment,@file,@method,@line)";
System.Type tipProdus = e.GetType();
SqlConnection myConnection = new SqlConnection(databaseConnection);
SqlDataAdapter myCommand = new SqlDataAdapter(QueryString, myConnection);
DataSet ds = new DataSet();
// add the elements to the list
using (SqlConnection con = new SqlConnection(databaseConnection))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(QueryString, con))
{
cmd.Parameters.AddWithValue("@description", destails);
cmd.Parameters.AddWithValue("@moment", DateTime.Now);
cmd.Parameters.AddWithValue("@file", file);
cmd.Parameters.AddWithValue("@method", method);
cmd.Parameters.AddWithValue("@line", lineNumber);
cmd.ExecuteNonQuery();
}
con.Close();
}
}
else
{
//string folderPath = System.IO.Directory.GetCurrentDirectory();
string path = "errors" + DateTime.Now.ToString("ddMMyyyyhhmmss") + ".txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine(destails);
sw.WriteLine(DateTime.Now);
sw.WriteLine(file);
sw.WriteLine(method);
sw.WriteLine(lineNumber);
}
}
}
}
}
}
Не было ошибки, но изменения не были отражены вприложение.Я попытался запустить
webpack --config webpack.config.vendor.js
, но теперь я получаю сообщение об ошибке
ERROR in ./node_modules/bootstrap/dist/js/bootstrap.js
Module not found: Error: Can't resolve 'popper.js' in 'C:\Users\Andrei\Desktop\Bosch.SIGAD-Core\SIGAD\node_modules\bootstrap\dist\js'
, поэтому я установил его с
npm install popper.js -D
run
webpack --config webpack.config.vendor.js
снова, и это сработало, но теперь я получаю эту ошибку.
Я даже не знаю, с чего начать расследование этой ошибки.Любые идеи были бы хорошими.
Спасибо!
ОБНОВЛЕНИЕ:
, если я коммнюсь:
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true,
HotModuleReplacementEndpoint = "/dist/__webpack_hmr"
});
в Startup.cs, я неВнутренняя ошибка сервера, но я получаю
Uncaught Error: Type e is part of the declarations of 2 modules: e and e! Please consider moving e to a higher module that imports e and e. You can also create a new NgModule that exports and includes e then import that NgModule in e and e.
в консоли браузера ...
ОБНОВЛЕНИЕ 2:
Я хочу подчеркнуть, что даже если я создаю новыйпроект с ядром dotnet и Angular, после того как я
npm install npm-check-updates -g
ncu -u
npm install
я получаю эту ошибку, и я не могу запустить мое приложение
Я нашел это:
https://github.com/dotnet/coreclr/issues/14482
, которая, кажется, является той же самой проблемой, но я не вижу там никакого решения.