I'm doing some simple benchmarks, and I'm finding that .NET 7, compiled to WASM, is 16x slower than vanilla JS:
namespace Benchmark
{
public partial class MainJS
{
public static async Task Main()
{
var watch = new System.Diagnostics.Stopwatch();
watch.Start();
Int64 x = 0;
for (int i = 0; i < 100000000; i++)
x += i;
watch.Stop();
Console.WriteLine($"Execution Time: {watch.ElapsedMilliseconds} ms {x}");
}
}
}
Results in:
Execution Time: 16482 ms 4999999950000000
While vanilla js:
console.time("a")
let x = 0;
for (i=0; i<100000000; i++)
x += i
console.timeEnd("a")
console.log(x)
Results in:
a: 1084.294921875 ms
4999999950000000
I'm having a hard time seeing the benefit of dotnet wasm for web apps when its runtime performance is so abysmal.
The issue is that my C# was not being ahead-of-time compiled to WASM.
I had to make sure I had
<PropertyGroup>
<RunAOTCompilation>true</RunAOTCompilation>
</PropertyGroup>
in my .csproj and then run
dotnet publish -c Release
This ensures your C# is ahead-of-time (AOT) compiled to WASM. If you don't do this, then your C# will be compiled to an intermediate language (IL) in a .DLL file. The browser then downloads the .DLL file and passes it to the .NET runtime inside the WASM runtime (which is orders of magnitude slower since you are basically running a VM inside a VM).
Related
I have a .NET Core command-line app (netcoreapp3.1) and I am configuring it using environment variables:
var configuration = new ConfigurationBuilder()
.AddEnvironmentVariables("myapp_")
.Build();
When the program is run from the command line, the environment variable values are those that existed when the command line window was opened. If I run the program under the debugger from Visual Studio, then the environment variable values are those that existed when that instance of Visual Studio started.
This isn't acceptable, because I am forgetful and because it is onerous to restart these things when I want to change the value of a configuration setting. How can I get the up-to-date values at the time my program starts (not the values that were in place when whatever "thing" is running my program was itself started)?
It is not possible to use the while-runtime-changed environment variables in the IConfiguration constuct.
The configuration is read one time while the host startup:
Resource on github
But you can use a file instead. Just change the file content instead of environment variables. The console app can react on these file changes and use the new parameters.
Example with appsettings.json changes while runtime
var i = 0;
while(!token.IsCancellationRequested)
{
i++;
// _options is of type: IOptionsMonitor<Settings>
_logger.LogInformation(_options.CurrentValue.Test);
await Task.Delay(TimeSpan.FromSeconds(1), token);
if(i == 2)
{
// just for demo purpose change the appsettings.json file
// on the fly to display the new config settings
_logger.LogWarning("Change 'Test' = 2");
File.WriteAllText("appsettings.json", "{\"Test\": \"2\"}");
}
if(i > 5)
{
break;
}
}
Full example on dotnetfiddle
Usage of IOptionsMonitor<T>
With the configured appsettings.json file and reloadOnChange: true an IOptionsMonitor<T> can be used to always get the current value of the configuration.
return new HostBuilder()
.UseEnvironment("BETA")
.ConfigureAppConfiguration(builder => builder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true))
.ConfigureLogging(builder => builder.AddConsole())
.ConfigureServices((ctx, services) =>
services.AddOptions()
.Configure<Settings>(ctx.Configuration)
.AddHostedService<TestHost>());
For completeness the IOptionsMonitor documentation
I have a .NET Core 3.1 console application that is running some background cron jobs. There are different jobs doing different things and they will start every x minute, do its thing and then stop. Most of the time they run fine, but lately these jobs have been starting to hang. They just never finish, the process is stuck.
I don't really know how to debug this or how to figure out what is causing it to hang. What I've done is:
Create a DMP file from the task manager
Load this using dotnet dump analyze myfile.DMP
Run dumpasync -stacks
This gives a list of all the stacks. I've created a few DMP files from different workers (doing different things), but they all have in common that there is one task on Npgsql.NpgsqlReadBuffer.
This is one example:
000001ed01aa18c8 00007ffca0c9e3d8 128 1 Npgsql.NpgsqlReadBuffer+<>c__DisplayClass34_0+<<Ensure>g__EnsureLong|0>d
Async "stack":
.000001ed01aa1988 (1) Npgsql.NpgsqlConnector+<>c__DisplayClass160_0+<<DoReadMessage>g__ReadMessageLong|0>d
..000001ed01aa1a40 (5) Npgsql.NpgsqlDataReader+<NextResult>d__44
...000001ed01aa1ae0 (0) Npgsql.NpgsqlCommand+<ExecuteReaderAsync>d__102
....000001ed01aa1b90 (0) Npgsql.NpgsqlCommand+<ExecuteDbDataReaderAsync>d__97
.....000001ed01aa1c10 (1) Dapper.SqlMapper+<QueryAsync>d__33`1[[System.__Canon, System.Private.CoreLib]]
......000001ed021ac5d8 (3) Acme.Common.Data.Dapper.Repositories.AccountItems.GetDapperAccountItemsHandlerSql+<GetAccountItemsAsync>d__3
.......000001ed021ac638 (0) Acme.Common.Data.Dapper.Repositories.ItemRepository`1+<GetAccountItemsHigherThanIdAsync>d__9[[Acme.Core.Db.Dapper.DapperReaderConnection, Acme.Core.Db.Dapper]]
........000001ed021ac698 (1) Acme.Common.Services.EmailReport.ReportDataService+<MakeInstantAlertDto>d__20
.........000001ed00badd90 (3) Acme.Common.Services.EmailReport.ReportDataService+<GetReportDtoAsync>d__19
..........000001ed0105f968 (2) Acme.Common.Services.EmailReport.InstantAlertReportService+<SendInstantAlertReportAsync>d__6
...........000001ed0105f9c8 (0) Acme.Common.Services.EmailReport.EmailReportWorkerService+<SendInstantAlertReportsAsync>d__10
............000001ed01b902d0 System.Threading.Tasks.TaskFactory+CompleteOnInvokePromise
I don't know if this means that npgsql is the cause of the hang, but it seems to be what is common between all of them.
The connection is created like this:
public async Task<IEnumerable<MyDto>> GetData()
{
using (var dbConnection = await _dapperConnection.OpenAsync())
{
var sql = "SELECT * FROM ....";
var result = await dbConnection.QueryAsync<MyDto>(sql);
return result;
}
}
private async Task<NpgsqlConnection> OpenAsync(CancellationToken cancellationToken = default)
{
var connection = new NpgsqlConnection(_connectionString);
await connection.OpenAsync(cancellationToken);
return connection;
}
The connection string looks like this:
User ID=<userid>;Password=<password>;Host=<host>;Port=5432;Database=<databasename>;Pooling=true;Maximum Pool Size=200;Keepalive=30;
How can I debug this further? What would help?
Further technical details
Npgsql version: 4.1.3
PostgreSQL version: 9.6
Operating system: Windows
I need to create an ASP.NET Core 2 application that can be extensible.
An extension, is a project that reference the main assembly and can extends it adding new controllers, models (with EF migrations), views, razor pages, etc.
Because the extensions need use the main application base classes like base controller, base model or view/page layout, the main application cannot reference the module project (avoid circular references).
I'm not sure how can I achieve this, but the idea is an installation of the main project, can add new functionality simple putting the modules DLL (or by online market in the main application, that download the DLL).
In my research, I found Applications parts, but my problem here is I need specify the part assembly in Startup class, and I need in installed the capacity of install modules without doing any changes in the code.
Some modules, need be extensible too, for example, an accounting module, need to connect with bank, and it have an interface that defines the methods of working with the bank, for example:
public interface IBankingOperation
{
public async void PayInvoiceAsync(Invoice invoice);
// More methods...
}
Then, differents projects can reference the banking assembly and provide implementation for differents banks.
In the main application, this modules can be installed like other modules, but checking the base module is intalled, for example, I can install the Santander module like other module, but only if banking module is installed (module dependency).
In conclusion, I need to create a modular ASP.NET Core 2 application, but the main assembly cannot reference the modules, the modules must reference the main assembly. The modules can contain Controllers, Models, Views, Pages, Etc.
In the main web app you would call a class which loads the extensions in the memory
ModuleManager.LoadModules(Path.Combine(_env.ContentRootPath, "Modules"));
this is the load modules function
public static void LoadModules(string modulesFolder)
{
var appsFolders = new DirectoryInfo(modulesFolder).GetDirectories();
foreach (var appFolder in appsFolders)
{
var binFolder = new DirectoryInfo(Path.Combine(appFolder.FullName, "bin"));
if (!binFolder.Exists)
{
continue;
}
var assemblies = AssemblyProvider.GetAssemblies(binFolder.FullName);
foreach (var assembly in assemblies)
{
var iModuleClass = assembly.GetTypes().FirstOrDefault(type => type.GetInterfaces().Contains(typeof(IModule))
&& type.GetConstructor(Type.EmptyTypes) != null);
if (iModuleClass != null)
{
var module = Activator.CreateInstance(iModuleClass) as IModule;
module.ModuleFolder = appFolder;
Modules.Add(module);
Assemblies.Add(assembly);
break;
}
}
}
}
then you should have an interface which should be implemented by each module the class which implement this interface should do the work of registering services and database models and all staff needed and you will load them as follows
public static IEnumerable<IExtensionRegister> GetModuleRegistrars()
{
lock (Modules)
{
return Modules.Select(item => item.Registrar).Where(item=>item!=null).ToList();
}
}
I just created a new deployment slot for my app, imported the publishing profile to Visual Studio, but after deployment I get this error message:
Error 8: An error occurred while creating the WebJob schedule: No website could be found which matches the WebSiteName [myapp__staging] and WebSiteUrl [http://myapp-staging.azurewebsites.net] supplied.
I have 2 webjobs, a continuous and a scheduled webjob.
I already signed in to the correct Azure account, as stated by this answer.
Will I need to set something else up in order to deploy my app to a staging Deployment Slot with webjobs?
My app is using ASP.NET, if it makes a difference?
There are a few quirks when using the Azure Scheduler. The recommendation is to use the new CRON support instead. You can learn more about it here and here.
Jeff,
As David suggested, you can/should migrate to the new CRON support. Here's an example. The WebJob will be deployed as a continuous WebJob.
Keep in mind that in order to use this you need to install the WebJobs package and extensions that are currently a prerelease. You can get them on Nuget.
Install-Package Microsoft.Azure.WebJobs -Pre
Install-Package Microsoft.Azure.WebJobs.Extensions -Pre
Also, as David suggested if you're not using the WebJobs SDK, you can also run this using a settings.job file. He provided an example here.
Program.cs
static void Main()
{
//Set up DI (In case you're using an IOC container)
var module = new CustomModule();
var kernel = new StandardKernel(module);
//Configure JobHost
var storageConnectionString = "your_connection_string";
var config = new JobHostConfiguration(storageConnectionString) { JobActivator = new JobActivator(kernel) };
config.UseTimers(); //Use this to use the CRON expression.
//Pass configuration to JobJost
var host = new JobHost(config);
// The following code ensures that the WebJob will be running continuously
host.RunAndBlock();
}
Function.cs
public class Functions
{
public void YourMethodName([TimerTrigger("00:05:00")] TimerInfo timerInfo, TextWriter log)
{
//This Job runs every 5 minutes.
//Do work here.
}
}
You can change the schedule in the TimerTrigger attribute.
UPDATE Added the webjob-publish-settings.json file
Here's an example of the webjob-publiss-settings.json
{
"$schema": "http://schemastore.org/schemas/json/webjob-publish-settings.json",
"webJobName": "YourWebJobName",
"startTime": null,
"endTime": null,
"jobRecurrenceFrequency": null,
"interval": null,
"runMode": "Continuous"
}
I'm playing around with the preview, and tried adding insights to a IIS web application deployed locally on my machine. It's a .Net 4.5 application running in a nothing out of the ordinary application pool. When starting the application after adding insights, I get this exception:
Could not load file or assembly 'Microsoft.ApplicationInsights.Extensions.Intercept_x64.dll' or one of its dependencies. The module was expected to contain an assembly manifest.
I tried "Enable 32-Bit Applications" to both true and false with no difference in result.
Has anyone experienced a similar error?
Unfortunately ASP.NET tries to load literally everything that is in \bin as managed assemblies
Microsoft.ApplicationInsights.Extensions.Intercept_x64.dll is not a managed assembly, but ASP.NET Web App should not fail with yellow page in this case, you would see it only in FusLogvw.
Do you use any web publishing?
Did you precompile your web site on publish?
Could you provide full stack trace of the exception?
I've just come across this issue, and after a few hours found it was due to a conflict with FluentSecurity.
It's detailed here: https://github.com/kristofferahl/FluentSecurity/issues/70
The work-around was to add the following lines just before calling SecurityConfigurator.Configure():
SecurityDoctor.Current.EventListenerScannerSetup = scan =>
{
scan.ExcludeAssembly(file => Path.GetFileName(file).Equals("Microsoft.ApplicationInsights.Extensions.Intercept_x64.dll"));
scan.ExcludeAssembly(file => Path.GetFileName(file).Equals("Microsoft.ApplicationInsights.Extensions.Intercept_x86.dll"));
};
Hope this helps somebody else.
My inner exception pointed to WebActivator. So I Uninstall-Package WebActivator -Force, added the appropriate calls in Application_Start and all was good again.
I'm still testing this but I think I've resolved this problem....
The solution is based on the same solution as the SQL Spatial Types native .dll solution; if you know this you'll see the similarity between this and that package.
Step 1
Go Create a new subdirectory in the MVC project and under this two more sub-directories; I used :
MVCRoot ---> ApplicationInsights/x86
---> ApplicationInsights/x64
Under each directory add a linked item from the package directory, this was :
../packages\Microsoft.Diagnostics.Instrumentation.Extensions.Intercept.0.12.0-build02810\lib\native\x64\Microsoft.ApplicationInsights.Extensions.Intercept_x64.dll
and
../packages\Microsoft.Diagnostics.Instrumentation.Extensions.Intercept.0.12.0-build02810\lib\native\x86\Microsoft.ApplicationInsights.Extensions.Intercept_x86.dll
respectively.
I then add this code in a file in the 'root' of the AppplicationInsights folder called loader.cs which looked like this:
using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
namespace ApplicationInsights
{
/// <summary>
/// Utility methods related to CLR Types for SQL Server
/// </summary>
internal class Utilities
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr LoadLibrary(string libname);
/// <summary>
/// Loads the required native assemblies for the current architecture (x86 or x64)
/// </summary>
/// <param name="rootApplicationPath">
/// Root path of the current application. Use Server.MapPath(".") for ASP.NET applications
/// and AppDomain.CurrentDomain.BaseDirectory for desktop applications.
/// </param>
public static void LoadNativeAssemblies(string rootApplicationPath)
{
var nativeBinaryPath = IntPtr.Size > 4
? Path.Combine(rootApplicationPath, #"ApplicationInsights\x64\")
: Path.Combine(rootApplicationPath, #"ApplicationInsights\x86\");
CheckAddDllPath(nativeBinaryPath);
// LoadNativeAssembly(nativeBinaryPath,
// IntPtr.Size > 4
// ? "Microsoft.ApplicationInsights.Extensions.Intercept_x64.dll"
// : "Microsoft.ApplicationInsights.Extensions.Intercept_x86.dll");
}
public static void CheckAddDllPath(string dllPath)
{
// find path to 'bin' folder
var pathsToAdd = Path.Combine(new string[] { AppDomain.CurrentDomain.BaseDirectory, dllPath });
// get current search path from environment
var path = Environment.GetEnvironmentVariable("PATH") ?? "";
// add 'bin' folder to search path if not already present
if (!path.Split(Path.PathSeparator).Contains(pathsToAdd, StringComparer.CurrentCultureIgnoreCase))
{
path = string.Join(Path.PathSeparator.ToString(), new string[] { path, pathsToAdd });
Environment.SetEnvironmentVariable("PATH", path);
}
}
private static void LoadNativeAssembly(string nativeBinaryPath, string assemblyName)
{
var path = Path.Combine(nativeBinaryPath, assemblyName);
var ptr = LoadLibrary(path);
if (ptr == IntPtr.Zero)
{
throw new Exception(string.Format(
"Error loading {0} (ErrorCode: {1})",
assemblyName,
Marshal.GetLastWin32Error()));
}
}
}
}
I then added this to the global.asax this so:
protected override void Application_Start(object sender, EventArgs e)
{
ApplicationInsights.Utilities.LoadNativeAssemblies(Server.MapPath("~/bin"));
}
So far it seems to be passed events so far as I can tell. All come back and update this should I find a problem with what I've done.
At least the MVC application now starts :-)
UPDATE: This is not the end of the story :-(
I had to also modify the Microsoft.Diagnostics.Instrumentation.Extensions.Intercept.props file which is under the build directory of the package to make it not include the files into the bin directory.
When I was done it looked like this :
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<None Include="$(MSBuildThisFileDirectory)\..\lib\native\x86\Microsoft.ApplicationInsights.Extensions.Intercept_x86.dll">
<CopyToOutputDirectory>None</CopyToOutputDirectory>
</None>
<None Include="$(MSBuildThisFileDirectory)\..\lib\native\x64\Microsoft.ApplicationInsights.Extensions.Intercept_x64.dll">
<CopyToOutputDirectory>None</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
I've had to check in this package into my source control system as I think I'm now going to be faced with the problem with Continuous Build restoring a fresh copy of the package which I don't want.
I can't wait for MS to come up with a proper fix for this.
I've just deleted everything in my /bin folder and it seemed to have resolved the issue. Not sure what happen or anything, it's a project i haven't touched in ages. But it solved it :)