I am getting error in my .NET 5.0 framework Azure durable function project in VS2019
'IServiceCollection' does not contain a definition for 'AddPolicyHandler' and the best extension method overload 'PollyHttpClientBuilderExtensions.AddPolicyHandler(IHttpClientBuilder, IAsyncPolicy)' requires a receiver of type 'IHttpClientBuilder'
.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<AzureFunctionsVersion>v3</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="IdentityModel" Version="4.2.0" />
<PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.15.0" />
<PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.1.0" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.DurableTask" Version="2.5.1" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.ServiceBus" Version="4.3.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="3.1.0" />
<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="3.1.0" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.13" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
</Project>
Startup.cs
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Polly;
using Polly.Extensions.Http;
using System;
using System.Net.Http;
namespace Itel.DeliveryOrchestration
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddHttpClient()
.AddPolicyHandler(GetRetryPolicy());
}
private IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
{
return HttpPolicyExtensions
.HandleTransientHttpError()
.OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
.WaitAndRetryAsync(2, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
}
}
}
As I can see (based on the provided code sample) you have used the wrong Polly - HttpClient integration nuget package
using Polly.Extensions.Http;
builder.Services.AddHttpClient()
.AddPolicyHandler(GetRetryPolicy());
The Polly.Extensions.Http is deprecated and not updated anymore
You should prefer to use Microsoft.Extensions.Http.Polly package instead
Posting suggestion provided by #Nkosi in the comments as an answer so that it will be helpful for other community members who face similar kind of issues.
AddHttpClient with no arguments returns IServiceCollection while AddPolicyHandler applies to IHttpClientBuilder. You will need to use a named client
public static IServiceCollection AddHttpClient(this IServiceCollection services)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
//...
Referenced source code HttpClientFactoryServiceCollectionExtensions
Related
I am trying to get some values from the appsettings.json. But whatever I try with the AdditionalTextsProvider doesn't work. Here is my code
IncrementalValuesProvider<AdditionalText> textFiles = context.AdditionalTextsProvider.Where(static file => file.Path.Contains("appsettings.json")); // tried many things here, like EndsWith(".json") etc..
IncrementalValuesProvider<(string name, string content)> namesAndContents = textFiles.Select((text, cancellationToken) => (name: Path.GetFileNameWithoutExtension(text.Path), content: text.GetText(cancellationToken)!.ToString()));
context.RegisterSourceOutput(namesAndContents, (spc, nameAndContent) =>
{
nameAndContent.content; //always empty
nameAndContent.name; //always empty
});
From the other hand, when I implement the ISourceGenerator (same solution, same projects) this line of code just works!
var file = context.AdditionalFiles.FirstOrDefault(x => x.Path.Contains("appsettings.json"));
The project which is referencing the code generator:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.0.123" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Scrutor" Version="4.1.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.3.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\myproject\myproject.csproj" />
<ProjectReference Include="..\myproject.EFCore\myproject.EFCore.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>
<ItemGroup>
<AdditionalFiles Include="appsettings.json" />
</ItemGroup>
</Project>
Code generator project :
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild> <!-- Generates a package at build -->
<IncludeBuildOutput>false</IncludeBuildOutput> <!-- Do not include the generator as a lib dependency -->
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.1.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.3" PrivateAssets="all" />
</ItemGroup>
<ItemGroup>
<!-- Generator dependencies -->
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" GeneratePathProperty="true" PrivateAssets="all" />
</ItemGroup>
<PropertyGroup> <GetTargetPathDependsOn>$(GetTargetPathDependsOn);GetDependencyTargetPaths</GetTargetPathDependsOn>
</PropertyGroup>
<Target Name="GetDependencyTargetPaths">
<ItemGroup>
<TargetPathWithTargetPlatformMoniker Include="$(PKGNewtonsoft_Json)\lib\netstandard2.0\Newtonsoft.Json.dll" IncludeRuntimeDependency="false" />
</ItemGroup>
</Target>
<ItemGroup>
<!-- Package the generator in the analyzer directory of the nuget package -->
<None Include="$(OutputPath)\$(AssemblyName).dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
<!-- Package the props file -->
</ItemGroup>
</Project>
If you combine the additional text provider with the compilation it works for me (inspired by this great post):
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var files = context.AdditionalTextsProvider
.Where(a => a.Path.EndsWith("appsettings.json"))
.Select((a, c) => (Path.GetFileNameWithoutExtension(a.Path), a.GetText(c)!.ToString()));
var compilationAndFiles = context.CompilationProvider.Combine(files.Collect());
context.RegisterSourceOutput(compilationAndFiles, (productionContext, sourceContext) => Generate(productionContext, sourceContext));
}
void Generate(SourceProductionContext context, (Compilation compilation, ImmutableArray<(string, string)> files) compilationAndFiles)
{
//emit generated files...
}
Update:
Tested again with Visual Studio 17.4. and combination with compilation seems not to be necessary anymore. Generator is called as expected when appsettings.json changes with only AdditionalTextsProvider registered.
I have tried replicate but everything works for me.
I define my source generator as this
namespace ConsoleAppSourceGenerator
{
[Generator]
public class TxtGenerator : IIncrementalGenerator
{
private static int counter;
public void Initialize(IncrementalGeneratorInitializationContext initContext)
{
IncrementalValuesProvider<AdditionalText> textFiles = initContext.AdditionalTextsProvider
.Where(static file => file.Path.EndsWith(".txt"));
IncrementalValuesProvider<(string name, string content)> namesAndContents = textFiles
.Select((text, cancellationToken) => (name: Path.GetFileNameWithoutExtension(text.Path), content: text.GetText(cancellationToken)!.ToString()));
initContext.RegisterSourceOutput(namesAndContents, (spc, nameAndContent) =>
{
spc.AddSource($"TxtFile.{nameAndContent.name}.g.cs", $#"
// Counter {Interlocked.Increment(ref counter)}
public static partial class TxtFile
{{
public const string {nameAndContent.name} = ""{nameAndContent.content}"";
}}");
});
}
}
}
and source generator project as this
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<Nullable>enable</Nullable>
<LangVersion>Latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.1.0" />
</ItemGroup>
</Project>
Then in another project, where I have made a dummy foo.txt file I have
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>Generated</CompilerGeneratedFilesOutputPath>
</PropertyGroup>
<ItemGroup>
<Compile Remove="$(CompilerGeneratedFilesOutputPath)/**/*.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ConsoleAppSourceGenerator\ConsoleAppSourceGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>
<ItemGroup>
<AdditionalFiles Include="foo.txt"/>
</ItemGroup>
</Project>
If I through Visual Studio look at Dependencies->Analyzers->ConsoleAppSourceGenerator>TxtFile.foo.g.cs then it correctly increase the counter on every change I to in the file (see step 9).
I store generated files in path ConsoleApp/Generated/ConsoleAppSourceGenerator/ConsoleAppSourceGenerator.TxtGenerator and whenever I rebuild the project it correctly updates the files.
Have you remembered to add the [Generator] attribute to the IIncrementalGenerator?
Could you test this out and validates this doesn't either work for you?
"AdditionalFiles" in your consuming project file is the key to ensuring these files are captured by your source/incremental generator.
Found out that using a "<AdditionalFiles Include='...' />" is not necessary in some projects such as ASPNET Core projects for Source/IncrementalGenerators. The .cshtml files are included as additional files by default.
Also, file globbing patterns work with the "Include" parameter.
Good morning
I am building package for Xamrin.Forms. I follow how its done by James Montenango
Here are some important pieces of my .csproj
<TargetFrameworks>netstandard2.0;MonoAndroid10.0;Xamarin.iOS10</TargetFrameworks>
<ItemGroup>
<Compile Include="**\*.shared.cs" />
</ItemGroup>
<ItemGroup Condition=" $(TargetFramework.StartsWith('netstandard')) ">
<PackageReference Include="XTricks.Shared" Version="1.0.1" />
<PackageReference Include="Xamarin.Essentials" Version="1.6.1" />
</ItemGroup>
<ItemGroup Condition=" $(TargetFramework.StartsWith('MonoAndroid')) ">
<PackageReference Include="Xamarin.Forms" Version="5.0.0.2196" />
<PackageReference Include="Xamarin.GooglePlayServices.Location" Version="118.0.0.1" />
<PackageReference Include="XTricks.Shared" Version="1.0.1" />
<PackageReference Include="Xamarin.Essentials" Version="1.6.1" />
<Compile Include="**\*.android.cs" />
</ItemGroup>
<ItemGroup Condition=" $(TargetFramework.StartsWith('Xamarin.iOS')) ">
<PackageReference Include="Xamarin.Essentials" Version="1.6.1" />
<PackageReference Include="XTricks.Shared" Version="1.0.1" />
<Compile Include="**\*.apple.cs" />
</ItemGroup>
Everything is working except one important thing.
I would like to have two implementation of the same class for Android and for iOS.
For this purpose I declare and interface as:
IMyService.shared.cs
And I create two classes, one in Android folder called:
MyService.android.cs which implements IMyService.shared.cs
and second in Apple folder called MyService.apple.cs.
Now as is done in above library I would like to use service in shared code.
private static IMyService Service
{
get
{
#if NETSTANDARD1_0 || NETSTANDARD2_0
return null;
#else
return new MyService(); // And this code is red one. MyService cannot be found.
#endif
}
}
Basically I am stucked there. Does anyone know how to move foward?
Make sure you have same namespace to MyService class with your shared codes and then you just build your library.
I have downloaded one of my old projects and when I tried to run the Update-Database from the Package Manager Console I get the following message
Build started... Build succeeded. An error occurred while accessing
the Microsoft.Extensions.Hosting services. Continuing without the
application service provider. Error: Value cannot be null. (Parameter
's') No DbContext was found in assembly 'BusinessLogicLayer'. Ensure
that you're using the correct assembly and that the type is neither
abstract nor generic.
The difference between now and when I have used the application last time is that I have reset windows, and reinstalled all the programs back.
The application runs normally and I managed to add the migrations using
CreateHostBuilder(args)
.Build()
.MigrateDatabase<DataContext>()
.Run();
and all tables have been created and populated with the seed data.
The last time I have been working on this project everything was working just fine.
This is how I connect to the DB
services.AddDbContext<DataContext>(optionsBuilder =>
optionsBuilder.UseNpgsql("User ID=postgres;Password=my_actual_pass;Server=localhost;Port=5432;Database=medication_platform3;Integrated Security=true;Pooling=true;"));
Constructor for DataContext
public DataContext(DbContextOptions<DataContext> options)
: base(options) { }
DataAccessLayer
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Migrations\**" />
<EmbeddedResource Remove="Migrations\**" />
<None Remove="Migrations\**" />
</ItemGroup>
<ItemGroup>
<Compile Include="Migrations\20201207230245_InitialMigration.cs" />
<Compile Include="Migrations\20201207230245_InitialMigration.Designer.cs" />
<Compile Include="Migrations\DataContextModelSnapshot.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.Identity.Core" Version="5.0.0" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="5.0.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.8.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BusinessObjectLayer\BusinessObjectLayer.csproj" />
</ItemGroup>
</Project>
appsettings.json
{
"JwtKey": "SOME_RANDOM_KEY_DO_NOT_SHARE",
"JwtIssuer": "http://localhost:5001",
"JwtExpireDays": 1,
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
I can provide more information if needed.
After using update-database -verbose
I was able to track the line with the problem.
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
int port = int.Parse(Environment.GetEnvironmentVariable("PORT"));
....
}
This was a configuration made for the deployment and I forgot to change this line to
int port= 5001
I am trying to call api using Flurl and here is my request which only fails on my testserver but works on live server and localhost as well
PickUp responseAsPickUpPointServiceResponse = null;
try
{
responseAsPickUpPointServiceResponse =
await new Flurl.Url(_baseUrl + "/rest//v1/servicepoint/findByPostalCode.json")
.SetQueryParam("apikey", APIKEY_WEB1)
.SetQueryParam("countryCode", countrycode)
.SetQueryParam("postalCode", zipcode)
.WithHeader("Accept", "application/json;charset=UTF-8")
.GetJsonAsync<PickUp>();
}
BUt it fails with error
Method not found: 'System.Threading.Tasks.Task`1 Flurl.Http.GeneratedExtensions.GetJsonAsync(Flurl.Http.IFlurlRequest, System.Threading.CancellationToken, System.Net.Http.HttpCompletionOption)
Has anyone idea how to fix this?
Same here, I got the same error Method not found [...] GetJsonAsync when running my integration tests although it was working well with unit tests.
In my case, there were two projects where Flurl.Http versions mismatched :
main.csproj
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<PackageReference Include="Flurl" Version="3.0.0" />
<PackageReference Include="Flurl.Http" Version="3.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\other\imported.csproj" />
</ItemGroup>
</Project>
imported.csproj
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<PackageReference Include="Flurl" Version="2.8.2" />
<PackageReference Include="Flurl.Http" Version="2.4.2" />
</ItemGroup>
</Project>
The error was fixed by bumping Flurl version to 3.0.1 everywhere :
In both files :
<PackageReference Include="Flurl" Version="3.0.1" />
<PackageReference Include="Flurl.Http" Version="3.0.1" />
I have a new asp.net core 2.0 project and I trying to get my db context stored to the db via way of migrations now I have the dependencies installed via NuGet that should be there.
This is my DBContext
public class SolitudeDBContext : DbContext
{
public SolitudeDBContext(DbContextOptions options) : base(options) { }
public virtual DbSet<OrderHeader> OrderHeader { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema(schema: SchemaName.Portal);
base.OnModelCreating(modelBuilder);
}
public override int SaveChanges()
{
return base.SaveChanges();
}
}
My Appsettings where I store my Default connection.
{
"ConnectionStrings": {
"DefaultConnection": "Server=DESKTOP-JHIMUM4\\SQLEXPRESS2014;Database=solitude;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
}
I have been using
PM> dotnet ef migrations add firstDatabase
But the following error is thrown even though you can see the
references are installed also in models I have the item group fixed as
well. dotnet : No executable found matching command "dotnet-ef" At
line:1 char:1
+ dotnet ef migrations add firstDatabase
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (No executable f...and "dotnet-ef":String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
My project file
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
</ItemGroup>
<ItemGroup>
<Folder Include="Models\products\" />
<Folder Include="Models\stock\" />
</ItemGroup>
</Project>
Projects after second edit:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" />
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
</ItemGroup>
<ItemGroup>
<Folder Include="Models\products\" />
<Folder Include="Models\stock\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
</ItemGroup>
</Project>
You need to add Microsoft.EntityFrameworkCore.Tools.DotNet as a DotNetCliToolReference instead of a package reference. This will make the dotnet-ef commands available:
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
</ItemGroup>