AppSelfHoseBase generates error when starting in .net 5 - servicestack

I am trying to create an apphost in the testing project of a project created from .net 5.0 react template.
I am getting the error:
OneTimeSetUp: System.TypeLoadException : Could not load type 'Microsoft.Extensions.Primitives.InplaceStringBuilder' from assembly 'Microsoft.Extensions.Primitives, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.
And the breakpoint inside Configure() isn't hitting.
Same code seems to work fine in a .net 3.1 project.
Here is gist of app host:
public class MainAppHost : AppSelfHostBase
{
public MainAppHost() : base(nameof(MainAppHost), typeof(MyServices).Assembly) { }
public override void Configure(Container container)
{
//having this blank still triggers error
}
}
Seems error is thrown on AppHost.Start(url).
Stack trace:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) in /_/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeConstructorInfo.cs:line 375
at System.Reflection.ConstructorInfo.Invoke(Object[] parameters) in /_/src/libraries/System.Private.CoreLib/src/System/Reflection/ConstructorInfo.cs:line 18
at NUnit.Framework.Internal.Reflect.Construct(Type type, Object[] arguments) in /_/src/NUnitFramework/framework/Internal/Reflect.cs:line 113
at NUnit.Framework.Internal.TypeWrapper.Construct(Object[] args) in /_/src/NUnitFramework/framework/Internal/TypeWrapper.cs:line 252
at NUnit.Framework.Internal.Commands.ConstructFixtureCommand.<.ctor>b__0_0(TestExecutionContext context) in /_/src/NUnitFramework/framework/Internal/Commands/ConstructFixtureCommand.cs:line 51
at NUnit.Framework.Internal.Commands.BeforeTestCommand.Execute(TestExecutionContext context) in /_/src/NUnitFramework/framework/Internal/Commands/BeforeTestCommand.cs:line 48
at NUnit.Framework.Internal.Execution.CompositeWorkItem.PerformOneTimeSetUp() in /_/src/NUnitFramework/framework/Internal/Execution/CompositeWorkItem.cs:line 262
I saw a similar issue on NUnit github caused by 3.1 and 5.0 installed on same system so I uninstalled all older versions of SDK but it made no difference.
A simple NUnit test without the apphost works fine:
public class SimpleTestClass
{
[Test]
public void SimpleTest()
{
Assert.That(1 + 1 == 2);
}
}
But if I try to create the AppHost then I get the error:
public class SimpleTestClass
{
public SimpleTestClass()
{
var AppHost = new MainAppHost()
.Init()
.Start("http://localhost:5619/");
}
[Test]
public void SimpleTest()
{
Assert.That(1 + 1 == 2);
}
}
The testing and service layer both target .net 5.0 and the project runs fine, I just can't create an AppHost for testing.
Any idea what I am doing wrong?
edit:
I found exact reproduction steps:
x new react-spa TestAppHost
update all packages
run default integration test it will work
right click testing project and select "User Secrets", install prompted package.
run same integration test it now fails with error. Nunit tests without AppHost will still work fine.
Here is project file:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<DebugType>portable</DebugType>
<OutputType>Library</OutputType>
<UserSecretsId>1f094c52-e2b1-44e1-8e3a-9cf5189d8800</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\TestAppHost.ServiceInterface\TestAppHost.ServiceInterface.csproj" />
<ProjectReference Include="..\TestAppHost.ServiceModel\TestAppHost.ServiceModel.csproj" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="5.0.0" />
<PackageReference Include="NUnit" Version="3.13.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.17.*" />
<PackageReference Include="ServiceStack" Version="5.*" />
<PackageReference Include="ServiceStack.Kestrel" Version="5.*" />
</ItemGroup>
</Project>

Edit after repro steps provided. The issue is with referencing v5.0.0 of UserSecrets as ServiceStack's .NET Standard 2.0 builds used in .NET 5.0 Apps only references v2.2.0 which you can change it to to resolve the issue, i.e:
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="2.2.0" />
When .NET 6 LTS is out we'll provide a new framework target for all ServiceStack libraries targeting net6.0 which will let you reference the latest dependency versions.
Unfortunately I've never seen this issue or know how to repro it.
Here's a simple way to create an NUnit Integration test project:
$ mkdir SimpleTestCase && cd SimpleTestCase
$ x mix init-test
$ dotnet test
By default this runs the integration test in both .NET 5.0 and .NET Framework v4.7.2, which should result in the test passing in both .NET platforms:
You can change it to only run in .NET 5.0 by replacing:
<TargetFrameworks>net5.0;net472</TargetFrameworks>
with
<TargetFramework>net5.0</TargetFramework>
If that fails, find which versions of .NET Core you have installed:
$ dotnet --list-sdks
3.1.120 [C:\Program Files\dotnet\sdk]
3.1.414 [C:\Program Files\dotnet\sdk]
5.0.104 [C:\Program Files\dotnet\sdk]
Then create a global.json in your project directory with the latest v5 you have installed, e.g:
{
"sdk": {
"version": "5.0.104"
}
}
This ensures that specific .NET version is used to run/test your project, which you can verify by running:
$ dotnet --version

Related

Getting Bindingdata from Azure function .net6 (function v4)

In dotnet5 (function v3) we could fetch the metadata from FunctionContext by calling functionContext.BindingContext.BindingData.TryGetValue("Metadata", out var meta);
However dotnet 6 (v4) does not seem to have this option.
Azure function v3 (.net5)
Can anyone help me out by providing the correct implementation for the new dotnet 6 (v4) functions
To use .net6 with Function V4 we need VS 2022 environment or VS CODE .
I have tried with one simple blobtrigger azure function running with .net 5 and it works fine to fetch the meta data.
using System;
using System.IO;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
namespace testfuncapp
{
public static class Function1
{
[Function("Function1")]
public static void Run([BlobTrigger("test/{name}", Connection = "AzureWebJobsStorage")] string myBlob, string name,
FunctionContext context)
{
var logger = context.GetLogger("Function1");
logger.LogInformation($"C# Blob trigger function Processed blob\n Name: {name} \n Data: {myBlob}");
}
}
}
OUTPUT:-
And the same code we have tried with .net 6 environment and its works fine as well.
To do that Open VS CODE and update the .csproj file with .net 6 and function runtime version to V4
Install Function runtime v4 in your local .
NOTE: We need to install only one runtime version at our end.
Update .csproj file
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<AzureFunctionsVersion>v4</AzureFunctionsVersion>
<OutputType>Exe</OutputType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Storage" Version="4.0.4" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.2.0" OutputItemType="Analyzer" />
<PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.5.2" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
</Project>
And update the settings.json file to .net 6 and function runtime to V4 then save it .
And then use the command as below:
1- dotnet restore
2- dotnet build
3- func host start
OUTPUT:-
For more information please refer the below links:
BLOG : Migration from Asp.Net Core 5.0 to 6.0
MS Q&A : Migrating Auzre Function runtime version from 3.x to 4.x not working in VS 2019

Error in Azure Function App VS 2019 .NET 3.0 - Method not found: 'IFunctionsHostBuilder.get_Services()'

Issue with Azure Functions/EFSQLSERVER .NET CORE 3.0:
To reproduce:
Use Visual Studio 2019 16.2.1
Use Azure Function template to create a project.
Changed Target Framework to .NET Core 3.0
Add Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0"
reference via Nuget Package Manager.
Excecut Function App using F5
Results in an error as showing in the following snippets. Anyone came across this issue?
Azure Functions Core Tools (2.7.1633 Commit hash: 45c7d86a3bbc9ed0a80a8f4199aa7ea80ccfb24e)
Function Runtime Version: 2.0.12673.0
[10/4/2019 6:13:14 PM] Building host: startup suppressed:False, configuration suppressed: False
[10/4/2019 6:13:14 PM] Loading startup extension 'Startup'
[10/4/2019 6:13:14 PM] Loaded extension 'Startup' (1.0.0.0)
[10/4/2019 6:13:14 PM] Loading startup extension 'DurableTask'
[10/4/2019 6:13:14 PM] Loaded extension 'DurableTask' (1.0.0.0)
[10/4/2019 6:13:14 PM] A host error has occurred
[10/4/2019 6:13:14 PM] FunctionApp5: Method not found: 'Microsoft.Extensions.DependencyInjection.IServiceCollection Microsoft.Azure.Functions.Extensions.DependencyInjection.IFunctionsHostBuilder.get_Services()'.
Value cannot be null.
Parameter name: provider
My nuget packages from csproj file.
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.0.0" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.DurableTask" Version="1.8.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="1.0.29" />
</ItemGroup>
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
[assembly: FunctionsStartup(typeof(FunctionApp5.Startup))]
namespace FunctionApp5
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
**var x = builder.Services;**
}
}
}
For now,ASP.NET Core 3.0 not currently available for Azure App Service, check this Microsoft doc.
Azure Functions 3.0, which will be fully compatible with Core 3.0, will be available in October, check here. However it's not released now.
From this issue, you could find Azure Function 2.0 right now does not work with any Microsoft.Extensions.* 3.* packages and cannot share code with .Net Core 3.0 services.
Further more information about Azure Fuction 3.0 check this discussion.
You can now use .net core 3.0 to create azure functions. Update Microsoft.NET.Sdk.Functions to 1.0.30-beta2 and set AzureFunctionsVersion to v3-preview.
Read more about Develop Azure Functions using .NET Core 3.0 here
You can now use DI using IFunctionsHostBuilder
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
[assembly: FunctionsStartup(typeof(BI_Geo.AzureFunctions.Startup))]
namespace BI_Geo.AzureFunctions
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddScoped<IProcess, Process>();
}
}
}
This saved my day
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AzureFunctionsVersion>v3</AzureFunctionsVersion>
</PropertyGroup>
To add something else to look out for, the following was our issue:
Our functions app referenced a Domain project
Our Domain project referenced "Microsoft.Extensions.Localization version 5.0.1, which in turn referenced a 5.x version of Microsoft.Extensions.DependencyInjection, which was incompatible with our 3.x runtime. Once we downgraded to reference Microsoft.Extensions.Localization version 3.1.10, the Microsoft.Extensions.DependencyInjection reference downgraded with it and everything worked.
Until Azure Functions 3.0 is available as a stable release, the easiest seems to be to downgrade the Microsoft.Extensions.Http package to 2.2.0:
It helped me with the same problem as there seems to be no other workaround in place for now. Even the available beta packages aren't working on a build server.
More details here: Azure functions dependency injection - error when referencing class library (Github).

Can't import classes from custom NuGet package

I have a .NET Standard library with 1 interface and 1 class:
public interface ITestService
{
void Test(string test);
}
public class TestService : ITestService
{
public void Test(string test)
{
Console.WriteLine("Got this string: " + test);
}
}
I published the library using Azure Pipelines (dotnet pack and dotnet push) into Azure Artifacts using a nuspec file:
<?xml version="1.0"?>
<package>
<metadata>
<id>Service.Client</id>
<version>5.0.2</version>
<title>Service Client</title>
<authors>auth</authors>
<owners>owner</owners>
<projectUrl>https://dev.azure.com/yyy/</projectUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>My test nuget description</description>
<releaseNotes>Test release</releaseNotes>
<copyright>Copyright 2019</copyright>
<tags>latest 5.0.2</tags>
</metadata>
</package>
When importing this library (successfully) into my other project, I can't see the ITestService/TestService through VS2019, even though I can see them in the nupkg!
Can someone help me import my library?
I was using nuspec and the nuget pack command which didn't seem to work.
I switched using the csproj fields and Azure Devops to use dotnet pack command and it all works perfectly.
Thanks zivkan for the inspiration :)

Resharper fails to debug xunit Theory with ClassData

Recently, I tried to run a Theory test case with ClassData as test input. This is a completely normal behavior and it used to work in the past. The provided code works and I can easily run all tests in Visual Studio 2017 (15.9.2) with xunit 2.1 to 2.4.1 and Resharper 2018.2.3.
The Problem: When I try to debug a Theory test, the debugger starts start but stops before stopping my breakpoint in the Theory test case. Resharper shows an error "Unable to find any matching test cases". As far as I could reproduce this error, it only happens when I debug a Theory test case which uses a class (not a primitive type) as T in TheoryData.
TestMethod_StringClassData: Uses StringClassData with TheoryData of type string.
TestMethod_CultureInfoClassData: Does not step into the test case when trying to debug it. The only difference here is, that the test parameter is not a string, but a CultureInfo object.
Test cases to reproduce the error:
public class UnitTest1
{
[Theory]
[ClassData(typeof(StringClassData))]
public void TestMethod_StringClassData(string cultureInfo)
{
}
[Theory]
[ClassData(typeof(CultureInfoClassData))]
public void TestMethod_CultureInfoClassData(CultureInfo cultureInfo)
{
}
public class StringClassData : TheoryData<string>
{
public StringClassData()
{
this.Add("de");
}
}
public class CultureInfoClassData : TheoryData<CultureInfo>
{
public CultureInfoClassData()
{
this.Add(new CultureInfo("de"));
}
}
}
Update 1:
If I create a new VS2017 csproj with Microsoft.NET.Test.Sdk and select TargetFramework netcoreapp2.1, everything works fine again! If I select TargetFramework net47, no more xunit Theory debugging is possible.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.9.0" />
<PackageReference Include="xunit" Version="2.4.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
</ItemGroup>
</Project>

VSIX with Project Templates and NuGet Packages

I have been following this post about how to build a VSIX project that will add some custom MVC project types:
http://www.asp.net/mvc/tutorials/mvc-4/custom-mvc-templates
I also want to include some additional Nuget packages, so I was following this page from Nuget, but it seems to be for VS2010 and I'm working in 2012.
I have the project building, and everything works peachy on my machine. The install works, the new project type appears, and when I create a new project of this type, everything works perfectly.
However, when I send the installer to a coworker, things break. The installer works, they see the new project type, but when creating the project he gets error messages about not being able to install any of the packages in the extension node. I've confirmed the Product Id of the extension is correct (I intentionally malformed it in the .vstemplate file during testing and it gave an entirely different error). I've added the packages to the extension manifest, but it doesn't seem to make a difference. I've also confirmed the .nupkg files get deployed to %ProgramFiles(x86)%\Microsoft Visual Studio 11.0\Common7\IDE\Extensions.
Any suggestions on what to do?
Custom Project's .vstemplate section
<WizardExtension>
<Assembly>NuGet.VisualStudio.Interop, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</Assembly>
<FullClassName>NuGet.VisualStudio.TemplateWizard</FullClassName>
</WizardExtension>
<WizardData>
<packages repository="registry" keyName="AspNetMvc4VS11" isPreunzipped="true">
<package id="EntityFramework" version="5.0.0" skipAssemblyReferences="true" />
<package id="jQuery" version="1.8.2" />
<!-- snip -->
</packages>
<packages repository="extension" repositoryId="SampleExtensionId">
<package id="Unity" version="3.0.1304.0" targetFramework="net45" />
<package id="Unity.WebAPI" version="0.10" targetFramework="net45" />
<!-- snip -->
</packages>
</WizardData>
source.extension.vsixmanifest Asset tags
<Assets>
<Asset d:VsixSubPath="ProjectTemplates\CustomMVCTemplate" etc/>
<Asset Type="Unity.3.0.1304.0" Path="Packages\Unity.3.0.1304.0.nupkg" />
<Asset Type="Unity.WebAPI.0.10" Path="Packages\Unity.WebAPI.0.10.nupkg" />
<!-- snip -->
</Assets>
File Structure
Extension Project
Packages
NugetPackage 1
NugetPackage 2
etc
ProjectTemplates
CustomMVCTemplate
<custom project files>
source.extension.vsixmanifest
I've made a step by step video on how to make a VSIX that auto downloads nuget packages.
http://www.youtube.com/watch?v=_ZvsFz41H-E
Since there are many steps and I never wrote them down, I won't type them here. I've definitely tested my VSIX package on other people's machine and it worked so hopefully this will work for you.
To download latest versions of NuGet packages plus all their dependencies add a following class to your vsix:
public class MyProjectWizard : IWizard
{
IEnumerable<string> _packages;
public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
{
if (customParams.Length > 0) {
var vstemplate = XDocument.Load((string)customParams[0]);
_packages = vstemplate.Root
.ElementsNoNamespace("WizardData")
.ElementsNoNamespace("packages")
.ElementsNoNamespace("package")
.Select(e => e.Attribute("id").Value)
.ToList();
}
}
public void ProjectFinishedGenerating(Project project)
{
var componentModel = (IComponentModel)Package.GetGlobalService(typeof(SComponentModel));
var _installer = componentModel.GetService<IVsPackageInstaller2>();
foreach (var package in _packages) {
_installer.InstallLatestPackage(null, project, package, false, false);
}
}
}
And then use following in vstemplate:
<WizardExtension>
<Assembly>MyProjectWizard, Version=1.0.0.0, Culture=neutral, PublicKeyToken=22c2a1a5fa7b6905</Assembly>
<FullClassName>MyProjectWizard.MyProjectWizard</FullClassName>
</WizardExtension>
Check out this link http://samritchie.net/2012/09/17/nuget-packages-in-vs2012-templates/ which helped me. However, I'm still running into the issue where all my references' paths are empty.
Note especially the following comment from the article linked above:
I spent a considerable period of time attempting to work out what the v2 equivalent of CustomExtension was, but to cut a long story short, you don’t need to make any changes to the .vsixmanifest — it’s enough to include all of the packages in the VSIX under a ‘Packages’ directory.

Resources