Run ASP.NET5 web application with Kestrel server on Windows - asp.net-core

I have successfully run the 'HelloWeb' sample from the ASP.NET5 GitHub repo with the Kestrel server on Windows 8.1 by using:
dnx . kestrel
Now I want to run my own application with kestrel. I tried it from Visual Studio 2015RC and with several runtimes using dnx directly. The result is always:
System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the
requested types. Retrieve the LoaderExceptions property for more information.
at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
at System.Reflection.RuntimeAssembly.get_DefinedTypes()
at Microsoft.AspNet.Hosting.Server.ServerLoader.LoadServerFactory(String serv
erFactoryIdentifier)
at Microsoft.AspNet.Hosting.Internal.HostingEngine.BuildApplication()
at Microsoft.AspNet.Hosting.Internal.HostingEngine.Start()
at Microsoft.AspNet.Hosting.Program.Main(String[] args)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Framework.Runtime.Common.EntryPointExecutor.Execute(Assembly ass
embly, String[] args, IServiceProvider serviceProvider)
at Microsoft.Framework.ApplicationHost.Program.ExecuteMain(DefaultHost host,
String applicationName, String[] args)
at Microsoft.Framework.ApplicationHost.Program.Main(String[] args)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Framework.Runtime.Common.EntryPointExecutor.Execute(Assembly ass
embly, String[] args, IServiceProvider serviceProvider)
at dnx.host.Bootstrapper.RunAsync(List`1 args, IRuntimeEnvironment env)
at dnx.host.RuntimeBootstrapper.ExecuteAsync(String[] args)
at dnx.host.RuntimeBootstrapper.Execute(String[] args)
Is there any way I can find what types cannot be loaded?
Update
Here is the project.json
{
"webroot": "wwwroot",
"version": "1.0.0-*",
"dependencies": {
"Microsoft.AspNet.Mvc": "6.0.0-beta6-14023",
"Microsoft.AspNet.Server.IIS": "1.0.0-beta6-11864",
"Microsoft.AspNet.Server.WebListener": "1.0.0-beta6-12245",
"Microsoft.AspNet.StaticFiles": "1.0.0-beta6-11996",
"EntityFramework.SqlServer": "7.0.0-beta6-13336",
"EntityFramework.Commands": "7.0.0-beta6-13336",
"Microsoft.Framework.ConfigurationModel.Json": "1.0.0-beta5-11337",
"Microsoft.AspNet.Identity.EntityFramework": "3.0.0-beta6-12521",
"Microsoft.AspNet.SignalR.Server": "3.0.0-beta6-12519",
"Microsoft.AspNet.Authentication.OAuthBearer": "1.0.0-beta4",
"Kestrel": "1.0.0-beta4"
},
"commands": {
"web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5000",
"kestrel": "Microsoft.AspNet.Hosting --server Kestrel --server.urls http://localhost:5004",
"ef": "EntityFramework.Commands"
},
"frameworks": {
"dnx451": { },
"dnxcore50": { }
},
"exclude": [
"wwwroot",
"node_modules",
"bower_components"
],
"publishExclude": [
"node_modules",
"bower_components",
"**.xproj",
"**.user",
"**.vspscc"
]
}
I tried to start it with Kestrel from within VS and set Kestrel to use the following runtime which resulted in the shown error messages in VS.
Runtime: 1.0.0-beta6-11921 .NET Framework x86
Exception thrown: 'System.Reflection.ReflectionTypeLoadException' in mscorlib.dll
Exception thrown: 'System.Reflection.TargetInvocationException' in mscorlib.dll
Exception thrown: 'System.Reflection.ReflectionTypeLoadException' in mscorlib.dll
Exception thrown: 'System.Reflection.ReflectionTypeLoadException' in Microsoft.Framework.ApplicationHost.dll
Exception thrown: 'System.Reflection.TargetInvocationException' in mscorlib.dll
Exception thrown: 'System.Reflection.ReflectionTypeLoadException' in mscorlib.dll
Exception thrown: 'System.Reflection.ReflectionTypeLoadException' in dnx.host.dll
Final update
The problem was the kestrel package version. For whatever reason the Nuget manager only suggested me Kestrel beta 4 while all other packages got installed as beta 6. After manually setting Kestrel to beta 6 in project.json everything worked. I accept Gerald Davies answer as he gave me the right direction.

The error would seem to indicate a mismatch between the runtime being used, the runtime expected by the application, and possibly the dependencies available for the specific runtime.
First use dnvm list and verify which runtime is being used (active). Please post that in an update. If the wrong runtime is set to active you will need to change that using dnvm use. Also compare this to the values in global.json for your solution.
You may need to restore dependencies. This can happen if the build in VS is using a different runtime than what is set as active by dnvm. You can force a dependency restore by dnu restore.
A `dnu restore' is always needed but VS sometimes hides this by doing it automatically as dependencies change but only for the current runtime VS is executing against. Remember dependencies may vary by runtime.
This is complicated by the fact the VS uses global.json to determine which dnx to execute against (version, runtime, and architecture) but on the command line unless explicitly indicated dnx/dnu use the "active" runtime set by dnvm. Technically dnvm just sets the path to a particular runtime so when use execute dnx or dnu you are running a specific one (version, runtime, and architecture) depending on what the path is.
The key thing is that the dnx that VS executes against and the dnx that you execute against on the command line are not necessarily the same. Changing the "target" in VS (global.json) or in dnvm (dnvm use) doesn't automatically update the other.
So for example VS may automatically restore dependencies for the beta4 version of non-core clr x86 dnx but due to the path (set by dnvm) when you execute on the command line you are executing against beta6 version of the core clr x64. If those dependencies have not be restored then you will get an error.

To find the real cause of the exception, you can debug this error by using --debug switch of dnx. Try:
dnx --debug . kestrel
Then you can attach to dnx.exe with Visual Studio and see the exact exception and retrieve it's LoaderExceptions property. I had similar problems, both caused by runtime mismatch and source code errors.

Related

Sitecore Express Migration Tool 3.0 - Error on run

I am trying to migrate a Sitecore 8.0 installation to Sitecore 9.0, and the documentation in the Sitecore Developer portal suggests using the Sitecore Express Migration Tool as the most painless way to do this. However, when I run the application I get an immediate error:
An unexpected error has occured. Please restart the tool and try again. For more information, see the log files.
I checked the log files and I only see this:
[ 1] 11:40:43.421 INFO [WizardCore] Moving to the next step. Current step key: ''.
[ 1] 11:40:43.510 ERROR Unable to perform wizard step transition. Source: <no>, Target: basic_parameters_step.
System.NotSupportedException: An attempt was made to load an assembly from a network location which would have caused the assembly to be sandboxed in previous versions of the .NET Framework. This release of the .NET Framework does not enable CAS policy by default, so this load may be dangerous. If this load is not intended to sandbox the assembly, please enable the loadFromRemoteSources switch. See http://go.microsoft.com/fwlink/?LinkId=155569 for more information.
at System.Reflection.RuntimeAssembly.nLoadFile(String path, Evidence evidence)
at System.Reflection.Assembly.LoadFile(String path)
at Sitecore.ExpressMigration.Core.Plugin.PluginRepository.LoadPlugins() in C:\BA\e849cf469cb4cf58\src\Sitecore.ExpressMigration.Core\Plugin\PluginRepository.cs:line 44
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at Sitecore.ExpressMigration.Pipelines.WizardSteps.CreateBasicParameters.AddModuleVersionSelectors.Process(CreateBasicParametersArgs args) in C:\BA\e849cf469cb4cf58\src\Sitecore.ExpressMigration\Pipelines\WizardSteps\CreateBasicParameters\30_AddModuleVersionSelectors.cs:line 54
at Sitecore.ExpressMigration.Core.Pipelines.PipelinesService.Pipeline.Run[T](T args) in C:\BA\e849cf469cb4cf58\src\Sitecore.ExpressMigration.Core\Pipelines\PipelinesService\Pipeline.cs:line 54
at Sitecore.ExpressMigration.Wizard.Steps.Start.BasicParameters.BasicParametersStep.CreateRootDataRequest(Migration migration) in C:\BA\e849cf469cb4cf58\src\Sitecore.ExpressMigration\Wizard\Steps\Start\BasicParameters\BasicParametersStep.cs:line 119
at Sitecore.ExpressMigration.Wizard.Steps.Start.BasicParameters.BasicParametersStep.<OnBeforeStepEnterAsync>d__29.MoveNext() in C:\BA\e849cf469cb4cf58\src\Sitecore.ExpressMigration\Wizard\Steps\Start\BasicParameters\BasicParametersStep.cs:line 84
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Sitecore.ExpressMigration.Wizard.Core.WizardCore.<PerformStepTransitionAsync>d__51.MoveNext() in C:\BA\e849cf469cb4cf58\src\Sitecore.ExpressMigration\Wizard\Core\WizardCore.cs:line 220
[ 1] 11:41:06.247 INFO [WizardCore] Moved to the next step. Current step key: ''.
This is default, without any configuration changes; the system paths referenced do not exist on my system (C:\BA\e849cf469cb4cf58) and I'm not sure how to specify where my actual Sitecore project folder is. I've been looking through the migration document on the Developer portal, but everything documented is written assuming starting the application worked.
What can I do to get past this error? Is there some configuration changes I need to make?
Open Sitecore.ExpressMigration.exe.config
Add the following line <loadFromRemoteSources enabled="true" /> to the <runtime> section

FluentValidation 6.4.0-beta* Nuget Package restore failed, operation timed out

I was trying to add FluentValidation to my asp.net core project.
Originally i want to use Nuget FluentValidation.AspNetCore/6.4.0-beta9 and this pakage depends on Nuget FluentValidation/6.4.0-beta9. So I added the FluentValidation to project.json.
{
"dependencies": {
"Microsoft.NETCore.App": {
"version": "1.0.1",
"type": "platform"
},
"Microsoft.AspNetCore.Mvc": "1.0.1",
"Microsoft.AspNetCore.Routing": "1.0.1",
"Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
"Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
"Microsoft.Extensions.Configuration.Json": "1.0.0",
"Microsoft.Extensions.Logging": "1.0.0",
"Microsoft.Extensions.Logging.Console": "1.0.0",
"Microsoft.Extensions.Logging.Debug": "1.0.0",
"Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
...,
"FluentValidation": "6.4.0-beta9"
},
....
}
This results in a package restore failed Message with following Output.
log : Restoring packages for C:\Users\asdf\devel\BTnetCorePoc\NcCqrsPoc\src\NcCqrsPos.Web.Commands\project.json...
log : Retrying 'FindPackagesByIdAsyncCore' for source 'http://10.0.10.49/NugetServer/nuget_error/FindPackagesById()?id='FluentValidation''.
log : An error occurred while sending the request.
log : The operation timed out
log : Retrying 'FindPackagesByIdAsyncCore' for source 'http://10.0.10.49/NugetServer/nuget_error/FindPackagesById()?id='System.Text.RegularExpressions''.
log : An error occurred while sending the request.
log : The operation timed out
....
error: Failed to retrieve information from remote source 'http://10.0.10.49/NugetServer/nuget_error/FindPackagesById()?id='FluentValidation''.
error: An error occurred while sending the request.
error: Failed to retrieve information from remote source 'http://10.0.10.49/NugetServer/nuget_error/FindPackagesById()?id='System.Text.RegularExpressions''.
error: An error occurred while sending the request.
So it results in any kind of TimeOut, i not really well understand how nuget package publishing works. Timeout seems to me there are a server not available or sth like that, but the nuget package page linked above worked well (but i think that is just an indices page). And that ip 10.0.10.49 seems to be wierd ip for restoring a package. Does I probably missconfigured any nuget source path in vs Studio? (that throws me in mind while writing this question, i will check that later)
To use FluentValidation.AspNetCore, I need at least the version of FluentValidation 6.4.0-beta1. So i tried the most versions for
FluentValidation 6.4.0-beta1 to FluentValidation 6.4.0-beta9 (which i targeted)
and every try failes with the same timeout error (becuz of timeout it takes some minutes, i dont know how to hard stop, the restoring process)
After that i was trying to restore earlier Versions of FluentValidation which i cant use (FluentValidation.AspNetCore needs at least FluentValiedation 6.4.0-beta1), i checked if nuget restore works with older and stable FluentValidation. I tried following versions:
FluentValidation 6.2.1 (latest stable)
FluentValidation 6.2.1-beta1
FluentValidation 6.3.3-alpha
FluentValidation 6.3.4-alpha
Restoring these Versions works well so i think the error could not be any kind of missconfigured VS on my Machine. So where could be the Problem else? And what should be my next steps? I created an FluentValidation Github Repo Issue after this.
Like JeremySkinner suggested in the FluentValidation Github Issue. I removed the additional configured Package Source, configured in VS2015 (Tools->Options->Nuget Packager Manager->Packager Sources: deactivate my addidional custom 10.0.10.49/NugetServer->OK)
Trying now to restore FluentValidation 6.4.0-beta9 works well.
So there is a strange behavior which i cant figure out why this issue happening when additional Package Sources is defined. I just keep that in mind. I dont need that additional Package Source, so just deactivate it, works for that issue.

ASP.NET Core targeting net461 in Azure

Can an ASP.NET Core project target net461 and run on an Azure Website?
Here is what have been tried and failed.
It works when targeting netcoreapp1.0 but when I change it to net461(including some other needed changes to compile) I get the following error:
Unhandled Exception: System.TypeInitializationException: The type initializer for 'Microsoft.Extensions.PlatformAbstractions.PlatformServices' threw an exception. ---> System.IO.FileNotFoundException: Could not load file or assembly 'System.AppContext, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
at Microsoft.Extensions.PlatformAbstractions.ApplicationEnvironment.GetApplicationBasePath()
at Microsoft.Extensions.PlatformAbstractions.ApplicationEnvironment..ctor()
at Microsoft.Extensions.PlatformAbstractions.PlatformServices..ctor()
at Microsoft.Extensions.PlatformAbstractions.PlatformServices..cctor()
--- End of inner exception stack trace ---
at Microsoft.AspNetCore.Hosting.WebHostBuilder.BuildHostingServices()
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
at WebApplication1.Program.Main(String[] args) in C:\Users\a\WebApplication1\Program.cs:line 14
Specifically
System.IO.FileNotFoundException: Could not load file or assembly 'System.AppContext, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
Locally it works fine.
I've naively added nuget packages to include the needed assemblies.
{
"dependencies": {
"Microsoft.AspNetCore.Diagnostics": "1.0.0",
"Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
"Microsoft.AspNetCore.StaticFiles": "1.0.0",
"Microsoft.Extensions.Logging.Console": "1.0.0",
"Newtonsoft.Json": "9.0.1",
"System.AppContext": "4.1.0",
"System.Reflection.TypeExtensions": "4.1.0",
"System.Security.Cryptography.X509Certificates": "4.1.0"
},
Eventually I got a different kind of errors:
warn: Microsoft.AspNetCore.Server.Kestrel[0]
Unable to bind to http://localhost:7762 on the IPv6 loopback interface.
System.AggregateException: One or more errors occurred. ---> Microsoft.AspNetCore.Server.Kestrel.Internal.Networking.UvException: Error -4089 EAFNOSUPPORT address family not supported
at Microsoft.AspNetCore.Server.Kestrel.Internal.Networking.Libuv.Check(Int32 statusCode)
at Microsoft.AspNetCore.Server.Kestrel.Internal.Networking.Libuv.tcp_bind(UvTcpHandle handle, SockAddr& addr, Int32 flags)
at Microsoft.AspNetCore.Server.Kestrel.Internal.Networking.UvTcpHandle.Bind(ServerAddress address)
at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.TcpListener.CreateListenSocket()
at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Listener.<>c.<StartAsync>b__6_0(Object state)
--- End of inner exception stack trace ---
I'm not sure where to go from here.
Although the publish profile had the option checked to "remove additional files at destination" there must still have been some files left.
Using FTP and manually delete all files before publishing solved the project.
ASP.NET Core targeting net461 works on Azure assuming you have not published any other frameworks there previously.
These NuGet packages I added in the question was not needed either and can safely be removed from the project.
"System.AppContext": "4.1.0",
"System.Reflection.TypeExtensions": "4.1.0",
"System.Security.Cryptography.X509Certificates": "4.1.0"

running asp.net5 application using latest dnx version fails

I pulled the latest code from https://github.com/aspnet/MusicStore/tree/dev
Without making any changes to the code. I built the application for
dnx version : 1.0.0-rc2-16308 coreclr x64
The application builds successfully , however when I try to run the application,
I get the below error.
System.NullReferenceException: Object reference not set to an instance of an object.
at Xunit.Runner.Dnx.Program.GetAvailableRunnerReporters()
at Xunit.Runner.Dnx.Program.Run(String[] args)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Dnx.Runtime.Common.EntryPointExecutor.Execute(Assembly assembly, String[] args, IServiceProvider serviceProvider)
at System.Threading.Tasks.Task`1.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
Please Note , The same code base worked successfully couple of days back.
We're in the process of migrating from dnx to dotnet. The migration happens on the dev branch so all the code there might not compile or fail at runtime. This is most likely one of those cases.
From the callstack I assume you're trying to run the tests. In the dotnet world, we run tests a little different and we haven't got yet to MusicStore with the conversion.
Sorry for the inconvenience.
RC2 is not stable. Downgrade to RC1
https://github.com/aspnet/MusicStore/releases

Running ASP.NET 5 on Nano Server throws "Unable to load DLL 'kernel32'"

I have created a simple ASP.NET 5 project based on the ASP.NET 5 beta 8 Visual Studio template.
I have published the project using this command
dnu publish <path to project.json> --out <path to publish folder> --configuration Release --runtime dnx-coreclr-win-x64.1.0.0-beta8 --wwwroot-out "wwwroot" --no-source
After I run the web.cmd on nano server I received this error:
.\web.cmd : System.DllNotFoundException: Unable to load DLL 'kernel32': The specified module could not be found. (Exception from HRESULT:
0x8007007E)
+ CategoryInfo : NotSpecified: (System.DllNotFo...LT: 0x8007007E):String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
at Microsoft.AspNet.Server.Kestrel.Networking.PlatformApis.WindowsApis.LoadLibrary(String dllToLoad)
at Micros
oft.AspNet.Server.Kestrel.Networking.Libuv.Load(String dllToLoad)
at Microsoft.AspNet.Server.Kestrel.ServerFactory.Start(IFeatureCollection serverFeatures, Func`2 application)
at Microsoft.AspNet.Hosting.Internal.HostingEngine.Start()
at Microsoft.AspNet.Hosting.Program.Main(String[] args)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Dnx.Runtime.Common.EntryPointExecutor.Execute(Assembly assembly, String[] args, IServiceProvider serviceProvider)
at Microsoft.Dnx.ApplicationHost.Program.ExecuteMain(DefaultHost host, String applicationName, String[] args)
at Microsoft.Dnx.ApplicationHost.Program.Main(String[] args)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Dnx.Runtime.Common.EntryPointExecutor.Execute(Assembly assembly, String[] args, IServiceProvider serviceProvider)
at Microsoft.Dnx.Host.Bootstrapper.RunAsync(List`1 args, IRuntimeEnvironment env, String appBase, FrameworkName targetFramework)
at Microsoft.Dnx.Host.RuntimeBootstrapper.ExecuteAsync(String[] args, BootstrapperContext bootstrapperContext)
at Microsoft.Dnx.Host.RuntimeBootstrapper.Execute(String[] args, BootstrapperContext bootstrapperContext)
The same command doesn't throw this error when running on Windows 10. The application works fine on Windows 10.
Nano Server does not have kernel32.dll and advapi32.dll so code that is not linked against default libs won't work. You need to either link your code against onecore.lib or install reverse forwarders.
Reverse forwarders redirect calls to kernel32.dll/advapi32.dll APIs to the counterparts available on Nano Server.
On some OneCore systems (e.g. Win10 IoT Core on Raspberry Pi 2), reverse forwarders are installed by default. This is not the case in case of the Nano Server, since the goal is to make it as small as possible. Hence the need to install reverse forwarders manually if you need them.
To relate this to Asp.Net 5 - both Http Platform Handler and Kestrel (or to be more specific libuv) are linked against default libs. Therefore, to run Asp.Net 5 on Nano, you need forwarders, unless you use WebListener (which should work fine without forwarders).
Hypothesis
You mention that this application is working fine on Windows. How are you running it on Windows? There's a good chance you are using dnx451 and not dnxcore50 (CoreCLR) as your target platform.
This is a problem because you are publishing for CoreCLR. (--runtime dnx-coreclr-win-x64.1.0.0-beta8), and there's a good chance when you are running locally, it is using the full .NET framework.
Does It Work with CoreCLR on Windows 10?
Here's what I'd do: Try to run the web app in the Developer Command Prompt for Visual Studio 2015 using dnx.
Switch to the CoreCLR version of .NET using dnvm:
dnvm use 1.0.0-beta-8 -r coreclr
Restore packages
dnu restore
Run
dnx web
If this fails, we know what is the issue. If this succeeds, there's a chance that Nano doesn't provide the native Windows APIs your code is trying to execute. If that is the case, you have to identify the code that is causing this and use something else.
How to target only CoreCLR in Visual Studio
You can remove the dnx451 target from your project.json so that Visual Studio is forced to use the dnxcore50 (CoreCLR) version. Ideally we want to be running the exact same version / environment we are publishing to.