Running dotnet-isolated AzureFunction does not work - c#

I have developed an Azure Function v4 with .net 6.0. It contains only http triggered functions.
Locally everything works fine, but after deploying it to Azure i only get 500 Status Code by calling any endpoint and it always throws InvalidOperationException at Microsoft.Azure.WebJobs.Script.Workers.Rpc.RpcFunctionInvocationDispatcherLoadBalancer.GetLanguageWorkerChannel : Did not find any initialized language workers
Application settings
Operating System: Windows
Runtime Version: 4.0.1.16815
Location: West Europe
Update Add more information
Project file:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<AzureFunctionsVersion>v4</AzureFunctionsVersion>
<OutputType>Exe</OutputType>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="11.0.0" />
<PackageReference Include="Microsoft.ApplicationInsights" Version="2.20.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.6.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.OpenApi" Version="1.0.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.0.13" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.3.0" OutputItemType="Analyzer" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
local.settings.json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
"StorageConnectionString": "UseDevelopmentStorage",
"APPINSIGHTS_INSTRUMENTATIONKEY": "MyInstrumentationKey"
},
"Host": {
"LocalHttpPort": 7071,
"CORS": "*"
}
}

One of the workaround to resolve this issue:
Created Azure Functions (Stack: .Net 6 Isolated) in Visual Studio and run locally:
After deploying of Function App in the Azure Portal (Stack: .Net 6, Location: West Europe, OS: Windows, Plan: Consumption, Function Runtime: Isolated)
This is the configuration:
After deploying, the function URL is running successfully:
As I can see a setting called WEBSITE_NODE_DEFAULT_VERSION is added into your .Net Function App Configuration Settings.
If your function is not created with node.js and if you are not using this application setting explicitly in your code then you can remove this property from your function app. This is stated in this MSFT Q&A.
The other reasons for this kind of error would be
The Functions Runtime is initialized but it failed to initialize the Language Worker. So, the Functions Runtime detects that the worker channel has not started and logs the error message on further invocations.
Note:
5. Try Re-creation of the Function App (.Net 6 - Windows OS- West Europe Location) in the Azure Portal and deploy your HTTP Trigger Function from Visual Studio.
Or
6. Try removing the WEBSITE_NODE_DEFAULT_VERSION setting > Save > Restart the app in the azure portal and run the function.
7. Make sure this setting is "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated" in your function app local.settings.json file.
8. This error may exist due to unmatching of Functions worker version and SDK version. If any updates available, please update them through NuGet Packet Manager:
Also, this error exist in previous version of dotnet Isolated is 5 and in Azure Functions Version V3.
References:
azure-functions-dotnet-worker/issues
https://github.com/Azure/azure-functions-host/issues/7618.
SO Thread1

Related

Azure function DefaultAzureCredential Method not Found Azure.Core.TokenRequestContext

I'm trying to read secrets from a Azure Key Vault in my azure function c# script, but I'm facing an error
I already create a function.proj file with content below
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Azure.Identity" Version="1.6.0" />
<PackageReference Include="Azure.Security.KeyVault.Secrets" Version="4.3.0" />
</ItemGroup>
</Project>
I enabled the System assigned from my Function App and it created a Object Id number.
Then copied this number and added it to my Key Vault Access policies at Select principal option and choose Get and List for Secret Permissions
When I try this code below:
string keyVaultUri = "https://my-vault-test.vault.azure.net/";
var client = new SecretClient(new Uri(keyVaultUri), new DefaultAzureCredential());
var secret = client.GetSecret("first-secret");
error:
2022-05-04T16:41:51.383 [Error] Executed 'Functions.myFff' (Failed,
Id=number..., Duration=574ms) Method not found: 'Void
Azure.Core.TokenRequestContext..ctor(System.String[], System.String,
System.String, System.String)'.
I changed the versions of the packages and it worked well...
1.5.0 for Azure.Identity
4.2.0 for Azure.Security.KeyVault.Secrets

NETSDK1073: The FrameworkReference 'Microsoft.AspNetCore.App' was not recognized

I use .NET Core 5.0.100-preview.7.20366.6 , Blazor webassembly, Microsoft Visual Studio Community 2019 Preview Version 16.7.0 Preview 6.0
file foo.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<RuntimeIdentifier>browser-wasm</RuntimeIdentifier>
<UseBlazorWebAssembly>true</UseBlazorWebAssembly>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DevExpress.Blazor" Version="20.1.5" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="5.0.0-preview.7.20365.19" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="5.0.0-preview.7.20365.19" PrivateAssets="all" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Authentication" Version="5.0.0-preview.7.20365.19" />
<PackageReference Include="System.Net.Http.Json" Version="5.0.0-preview.7.20364.11" />
</ItemGroup>
</Project>
When press F5 to run debug:
Error
NETSDK1073: The FrameworkReference 'Microsoft.AspNetCore.App' was not
recognized
How to fix it?
For .NET Core 3.1 apps, adding <GenerateErrorForMissingTargetingPacks>false</GenerateErrorForMissingTargetingPacks> to the .csproj file will prevent this error:
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<GenerateErrorForMissingTargetingPacks>false</GenerateErrorForMissingTargetingPacks>
</PropertyGroup>
I just resolved the same issue with this process:
-Close the project
-Delete the bin and obj folders in the Blazor.Client project
-Reopen the project
-Open Nuget Console: Tools -> Nuget Package Manager -> Nuget Package Manager Console
-Enter dotnet restore in the command line
After that I hit F5 and the project compiled, and started

code coverage in gitlab ci/cd for .net applications?

I recently started working with C# and I am working on one of the legacy system we have. I am trying to figure out what is the code coverage for this legacy system. Here is my Sample.UnitTests.csproj file:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoFixture.AutoMoq" Version="4.2.1" />
<PackageReference Include="AutoFixture.NUnit3" Version="4.2.1" />
<PackageReference Include="coverlet.msbuild" Version="2.9.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Moq" Version="4.8.2" />
<PackageReference Include="nunit" Version="3.9.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.9.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.5.0" />
<PackageReference Include="WireMock.Net" Version="1.0.4.17" />
<PackageReference Include="Utf8Json" Version="1.3.7" />
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="System.Buffers" Version="4.5.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../Sample/Sample.csproj" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="dotnet-reportgenerator-cli" Version="4.2.10" />
</ItemGroup>
</Project>
I did some research and found out we can use coverlet which can generate cobertura style report. I followed exactly as mentioned here on my mac box and everything works fine and I can see the report being generated correctly on my console and also it generates index.html file which we can use to visualize as well.
dotnet add package coverlet.msbuild
dotnet restore
dotnet build
dotnet test /p:CollectCoverage=true
dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura /p:Exclude="[xunit*]\*" /p:CoverletOutput="./TestResults/"
dotnet reportgenerator "-reports:TestResults/coverage.cobertura.xml" "-targetdir:TestResults/html" -reporttypes:HTML;
Now since we use gitlab ci/cd pipeline for our project - Is there any way I can make this part of my .gitlab-ci.yml file so that it can generate report automatically for me whenever build happens and everybody in my team can see it successfully. Since as of now it's all manual as I need to run those above commands on my local mac box and I can see it from my console only by clicking index.html file.
These are my stages of .gitlab-ci.yml file as shown below. If needed I can provide my yml file as well but any simple example where it can demonstrate how can I do this then it will be of great help. I tried searching a lot and couldn't find this at all on how can I do it through gitlab pipeline which uses coverlet and cobertura style report for .net applications..
stages:
- test
- publish
- increment
- deploy
- integrationTests
- release
Can this be done through webhook as well if needed?
May need to use the actual GUID instead of *.
stages:
- test
- publish
- increment
- deploy
- integrationTests
- release
build-and-test:
stage: test
image: mcr.microsoft.com/dotnet/sdk:6.0
script:
- dotnet add package coverlet.msbuild
- dotnet restore
- dotnet build
- 'dotnet test --collect:"XPlat Code Coverage"'
artifacts:
reports:
cobertura: TestResults/*/coverage.cobertura.xml
GitLab can diff with previous Cobertura reports.
If you want HTML instead, simply include it among the artifacts. May also publish it to GitLab Pages.
The other answer didn't work for me because of folder confusion. Coverlet puts the test results in folders relative to the respective unit test projects. So
Either you have to tell gitlab to search for TestResults folders everywhere via wildcards, by setting path to something like ./**/TestResults/**/coverage.cobertura.xml.
Or you provide the --results-directory option (short version -r), to tell dotnet test where to put those files in the first place.
I went for the second option, gathering all results in a cobertura folder in the repo root. Here is a full, valid .gitlab-ci.yml for running tests for merge requests:
image : mcr.microsoft.com/dotnet/sdk:6.0
stages:
- test
test:
stage: test
only:
- merge_requests
script:
- 'dotnet test DotNetSolution
--collect:"XPlat Code Coverage"
-r cobertura'
artifacts:
reports:
coverage_report:
coverage_format: cobertura
path: cobertura/*/coverage.cobertura.xml

Is it possible/sensible to split ASP.Net Core 2 (.NET Framework) Web Api into Class Library and Hosting projects?

I'm trying to port an existing WCF Web API (targeting .NET Framework 4.6.1) to ASP.Net Core 2 using Visual Studio 2017 (v15.4.5) and am having trouble figuring out good/common/supported ways to organize projects, and what types of project they should be.
For example:
Single project for Server and Hosting, or Class Library for Server and Console application for Hosting
Windows Classic Desktop project for Console application and (new style csproj) Web Application for Server library, or both Web Applications (one outputting a Class Library, the other a Console Application)
I have the sneaking suspicion that there is something fundamental that I'm missing which means that one approach should be favoured over the others, or is even mandatory, but have found it hard to discover this from the ASP.Net Core 2 documentation.
Specific Requirements
Should target .NET Framework 4.6.1
Since I need to access the Windows Registry from the internals of the Web API, I am targeting .NET Framework 4.6.1 rather than .NET Core.
Host using HTTP.sys
I intend to use Windows Authentication in future and believe that Kestrel will not support that (Based upon HTTP.sys features).
Host should run as a Windows Service
Ultimately, the Web API should be installed by Windows Installer and run as a service.
For the moment, I'm just trying to get the API to build/work correctly stand-alone, but would also appreciate any insight into how the choice of projects might affect publishing/deployment.
Preferred Solution
Whilst, by default, a new ASP.NET Core 2 Web Application is a single project outputting a Console Application, I would prefer to split the solution into 2 main projects:
"Server" - An ASP.NET Core 2 (.NET Framework) Class Library containing the business logic of the Web API, controllers and Startup class
"Host" - Console application which references "Server" and is responsible for hosting the Web API
This arrangement seems appropriate to me since any unit/integration test projects can reference the "Server" class library, not an executable (according to advice in Is it a bad practice to reference an exe file in C# project).
Furthermore, I'm led to believe this is reasonable because I can change the Output Type to "Class Library" in the project properties.
I'm assuming that since I'm targeting the .Net Framework, so long as I install the same NuGet packages as the "Server" project, there is no reason why the "Host" project cannot be a Windows Classic Desktop Console application.
Are there any hidden issues, perhaps relating to publishing/deployment, that make this arrangement a bad idea?
Would there be any advantage to making the Hosting project a Web Application (which would still reference the Server project)?
Attempt
Here are the steps I used to try to achieve my preferred project organization. Whilst it works, I get warnings generated during the build - see below.
Server
Add New Project "Server"
Choose Visual C#, Web, ASP.NET Core Web Application
In the following dialog, target .NET Framework, ASP.NET Core 2.0, and choose Web API
Change Output Type in Project properties to "Class Library"
Delete Program.cs
Host
Add New Project "Host"
Choose Visual C#, Windows Classic Desktop, Console App (.NET Framework)
Replace contents of Program.cs with:
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using Server;
namespace Host
{
internal class Program
{
private static void Main(string[] args)
{
BuildWebHost(args).Run();
}
private static IWebHost BuildWebHost(string[] args) =>
new WebHostBuilder()
.UseStartup<Startup>()
.UseHttpSys(options =>
{
options.UrlPrefixes.Add("http://localhost:8080/");
})
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConsole();
logging.AddDebug();
})
.Build();
}
}
Add a reference to the Server project
Install these NuGet packages
Microsoft.AspNetCore (2.0.1)
Microsoft.AspNetCore.Mvc (2.0.1)
Microsoft.AspNetCore.Server.HttpSys (2.0.2)
Set as Startup Project
Problem: Build generates warnings
This solution runs under debugging, and responds correctly to http://localhost:8080/api/values and http://localhost:8080/api/values/1, but the following warnings are shown after building the solution:
Warning The referenced component 'System.Security.Cryptography.Encoding' could not be found. Host
Warning The referenced component 'System.Xml.XPath' could not be found. Host
Warning The referenced component 'System.IO.FileSystem.Primitives' could not be found. Host
Warning The referenced component 'System.IO.FileSystem' could not be found. Host
Warning The referenced component 'System.Diagnostics.StackTrace' could not be found. Host
Warning The referenced component 'System.Xml.XmlDocument' could not be found. Host
Warning The referenced component 'System.Security.Cryptography.X509Certificates' could not be found. Host
Warning The referenced component 'System.Diagnostics.FileVersionInfo' could not be found. Host
Warning The referenced component 'System.Security.Cryptography.Algorithms' could not be found. Host
Warning The referenced component 'System.Xml.ReaderWriter' could not be found. Host
Warning The referenced component 'System.Security.Cryptography.Primitives' could not be found. Host
Warning The referenced component 'System.ValueTuple' could not be found. Host
Warning The referenced component 'System.Xml.XPath.XDocument' could not be found. Host
Warning The referenced component 'System.IO.Compression' could not be found. Host
Warning The referenced component 'System.AppContext' could not be found. Host
Warning The referenced component 'System.Threading.Thread' could not be found. Host
Warning The referenced component 'System.Console' could not be found. Host
If this is a reasonable arrangement of projects, why am I getting these warnings?
We are doing something similar. Our host is a .NET Framework 4.7.1 project:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net471</TargetFramework>
<IsPackable>true</IsPackable>
<PlatformTarget>x86</PlatformTarget>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNet.WebApi.Core" Version="5.2.6" />
<PackageReference Include="Microsoft.AspNetCore" Version="2.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="2.1.0" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.1.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="2.1.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.0" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Business.csproj" />
<ProjectReference Include="..\Apis.Shared.csproj" />
<ProjectReference Include="..\Apis.Contracts.csproj" />
</ItemGroup>
</Project>
And our library projects are NetStandard2.0:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>full</DebugType>
<DebugSymbols>true</DebugSymbols>
</PropertyGroup>
</Project>
Program.cs looks like this:
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.ConfigureServices(services => services.AddAutofac())
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
Startup.cs looks like this:
public class Startup
{
public Startup(IHostingEnvironment hostingEnvironment)
{
Settings = new AppSettings(hostingEnvironment);
}
public AppSettings Settings { get; private set; }
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddOptions();
// any other services registrations...
var builder = new ContainerBuilder();
// all autofac registrations...
builder.Populate(services);
return new AutofacServiceProvider(builder.Build(););
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}

How to create a new dotnet core application that has both auth and EF?

I can create a new dotnetcore app that has authentication/identity using the command line:
dotnet new mvc --auth Individual
How can i include entity framework in the project also?
TL;DR
You already have it in your project
Long form answer
After creating your application, it should have Entity Framework as a dependency. I'm assuming that you're running the .NET Core 2.0 SDK.
Here's the output from my machine
$ dotnet new mvc --auth Individual --name testForStackOverflow
The template "ASP.NET Core Web App (Model-View-Controller)" was created successfully.
This template contains technologies from parties other than Microsoft, see https://aka.ms/template-3pn for details.
Processing post-creation actions...
Running 'dotnet restore' on testForStackOverflow/testForStackOverflow.csproj...
Restoring packages for testForStackOverflow/testForStackOverflow.csproj...
Restore completed in 40.17 ms for testForStackOverflow/testForStackOverflow.csproj.
Restore completed in 40.17 ms for testForStackOverflow/testForStackOverflow.csproj.
Restore completed in 25.25 ms for testForStackOverflow/testForStackOverflow.csproj.
Generating MSBuild file testForStackOverflow/obj/testForStackOverflow.csproj.nuget.g.props.
Generating MSBuild file testForStackOverflow/obj/testForStackOverflow.csproj.nuget.g.targets.
Restore completed in 2.84 sec for testForStackOverflow/testForStackOverflow.csproj.
Restore succeeded.
I then look a look at the csproj which was generated:
$ cd testForStackOverflow/
~/testForStackOverflow$ ls
app.db Data Startup.cs
appsettings.Development.json Extensions testForStackOverflow.csproj
appsettings.json Models Views
bower.json obj wwwroot
bundleconfig.json Program.cs
Controllers Services
~/testForStackOverflow$ cat testForStackOverflow.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<UserSecretsId>aspnet-testForStackOverflow-AD382505-1A70-4A75-8059-1E0E3897A088</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<None Update="app.db" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.0" PrivateAssets="All" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
<DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="2.0.0" />
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
</ItemGroup>
</Project>
The important line of the csproj is here:
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
This is a reference to the ASP.NET Core metapackage. This package contains all of the common ASP.NET Core NuGet packages, including Entity Framework Core - as per this screen shot from NuGet (captured a few moments ago)
This means that part of the package restore operation included restoring EF Core into your project.
I would say that you should take a look at this documentation for EF Core - the link should take you directly to the section labelled "The Model". You don't need the stuff in the preceding section (labelled "Get Entity Framework Core") as you already have it.
Of course, if you're using version 1.x of the .NET Core SDK, then it's a slightly different story.

Categories

Resources