DurableClient and OrchestrationTrigger cannot be used in .NET 7 Azure Function - c#

I am now upgrading to .NET 7 Durable Function
The attributes below are not available with these
[DurableClient] IDurableOrchestrationClient starter
[OrchestrationTrigger] IDurableOrchestrationContext context
[ActivityTrigger]
I get an error with .NET Worker
What is the equivalent with .NET 7?
EDIT
I have got this compiling now but I get IDurableOrchestrationClient being resolved from webjobs, whats the equivalent in .NET 7?
My current packages are below
Paul

Was currently attempting the same.
Out of process or isolated packages are still in RC as per https://github.com/microsoft/durabletask-dotnet and there are still features missing such as durable entities.
That said I could get to compile using .net 7, v4 of functions using below.
[DurableClient] DurableClientContext durableContext,
FunctionContext executionContext)
{
ILogger logger = executionContext.GetLogger(nameof(StartHelloCitiesTyped));
string instanceId = await durableContext.Client.ScheduleNewHelloCitiesTypedInstanceAsync();

This should be available now at:
https://github.com/Azure/azure-functions-dotnet-worker/issues/767

Related

Azure Functions - Adding project reference causes package error [duplicate]

I'm having the above error after running an azure function called "Test" that redirects to an external URL of a service we want to use.
[FunctionName("Test")]
public IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequest req)
{
Log.Information("C# HTTP trigger function processed a request.");
string url = _authenticationService.GetAuthorizationUri().ToString();
return new RedirectResult(url);
}
The site at the URL prompts the user to authorize use of their data and performs a redirect to the previously authorized url of our "AuthorizationCallback", along with a query string parameter.
[FunctionName("AuthorizationCallback")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req)
{
Log.Information("C# HTTP trigger function processed a request.");
string code = req.Query["code"];
try
{
if (!string.IsNullOrEmpty(code))
{
await _authenticationService.ExchangeCodeForAccessToken(code);
return new OkResult();
}
}
catch (System.Exception)
{
return new UnauthorizedResult();
}
return new NotFoundResult();
}
The AuthorizationCallback function is hit but produces the following error in the console:
These are the dependencies of the current project on the solution (which is set as the startup project):
I've tried installing both the latest stable version (5.0.0) and the version before that (3.1.13) of Microsoft.Extensions.Primitives in the current project, but I'm still getting the same error. I've noticed the package that can't be loaded is within microsoft.azure.webjobs (3.0.23), which is within microsoft.azure.webjobs.extensions.storage (4.0.4), but these are used in another project entirely, for another azure function (blob triggered). Any ideas on how to overcome this error? Thank you all.
The Azure Functions host for .NET Core 3 uses an in-process hosting model, which essentially means you are limited in what versions of Microsoft assemblies you can use. What's happening is that something in your project has a reference to a newer version of Microsoft.Extensions.Primitives, but an older version of that library is already loaded by the Azure Functions host application.
For Azure Functions .NET Core 3, you should restrict all Microsoft.Extensions.* libraries to v3.x. You currently have Microsoft.Extensions.DependencyInjection 5.0.1, which should be changed to 3.x. Check for any other Microsoft.Extensions.* libraries either at the Packages level or anywhere beneath (tip: you can find them quickly by putting Microsoft.Extensions in the input box at the top of the Solution Explorer). You may need to downgrade some other library that has Microsoft.Extensions.Primitives as a dependency.
You might also be able to get away with manually writing a bindingRedirect pointing the newer version to an older version. The Microsoft.Extensions.* packages are relatively stable across versions, so that may work. It would make me very nervous, though.

Method not found: 'System.Threading.Tasks.Task`1<!!0>

i'm using the Microsoft Graph Apps to retrieve or create OneDrive files. I made a POC last week and everything worked wonderfully.
Now i tried implementing the our App into an existing MVC website but i'm having weird messages that System.Threading.Tasks.Task cannot be found:
at Microsoft.Graph.DriveRequest.<GetAsync>d__6.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
at Microsoft.Graph.DriveRequest.GetAsync(CancellationToken cancellationToken)
at Microsoft.Graph.DriveRequest.GetAsync()
at BizzMine.Data.Repositories.OnlineEditorRepo.OnlineEditorRepository.<RequestSuccess>d__10.MoveNext() in C:\Users\geertverthe\Documents\repos\bizzmine\BizzMine.Data.Repositories\OnlineEditorRepo\OnlineEditorRepository.cs:line 89
I suspect that there is some kind of problem with binding references to System.Threading.Tasks or even System.Web.Http but i am not sure.
This is the (simple) code i use:
Drive myDrive = await _graphServiceClient.Me.Drive.Request().GetAsync();
And my GraphServiceClient is constructed like this:
_graphServiceClient = new GraphServiceClient(
new DelegateAuthenticationProvider(async (request) => {
request.Headers.Authorization = new AuthenticationHeaderValue("bearer", _tokens.AccessToken);
await Task.FromResult<object>(null);
}));
.NET Framework version is 4.6.1
I do have the correct consent permissions and do have a valid access token.
Any idea on why i receive such kind of error and how i can fix this?
Thank you very much
After lot of trying i managed to solve my issue. Since our solution and projects contain lots of nuget packages, one of them was system.net.http. Apparantly this came with a package NETStandard.Library.1.6.1.
I found it strange to have a nuget package for system.net.http as this is just in the framework itself.
I could delete the system.net.http nuget packages after upgrading NETSTandard.Library.1.6.1 to the latest version.
Only changes i had to do after this was referencing the FRAMEWORK system.net.http in projects where it was missing and removing an obsolete binding redirect in some projects.
It works fine now :-)

Firestore functionality on a Windows iot core: error loading native library grpc_csharp_ext.x86.dll

Relatively new to the windows ecosystem. After following the windows documentation on setting up a background application on iot and google's quickstart for C#, I am receiving this error that I cannot seem to solve:
System.IO.IOException: 'Error loading native library "C:\Data\Users\DefaultAccount\AppData\Local\DevelopmentFiles\BackgroundAppFirestoreOne-uwpVS.Debug_ARM.usernoname\grpc_csharp_ext.x86.dll". '
Stack Trace:
System.IO.IOException
HResult=0x80131620
Message=Error loading native library "C:\Data\Users\DefaultAccount\AppData\Local\DevelopmentFiles\BackgroundAppFirestoreOne-uwpVS.Debug_ARM.usernoname\grpc_csharp_ext.x86.dll".
Source=Grpc.Core
StackTrace:
at Grpc.Core.Internal.UnmanagedLibrary..ctor(String[] libraryPathAlternatives)
at Grpc.Core.Internal.NativeExtension.LoadUnmanagedLibrary()
at Grpc.Core.Internal.NativeExtension.LoadNativeMethods()
at Grpc.Core.Internal.NativeExtension..ctor()
at Grpc.Core.Internal.NativeExtension.Get()
at Grpc.Core.GrpcEnvironment.GrpcNativeInit()
at Grpc.Core.GrpcEnvironment..ctor()
at Grpc.Core.GrpcEnvironment.AddRef()
at Grpc.Core.Channel..ctor(String target, ChannelCredentials credentials, IEnumerable`1 options)
at Grpc.Core.Channel..ctor(String host, Int32 port, ChannelCredentials credentials, IEnumerable`1 options)
at Google.Api.Gax.Grpc.ChannelPool.GetChannel(ServiceEndpoint endpoint, IEnumerable`1 channelOptions, ChannelCredentials credentials)
at Google.Api.Gax.Grpc.ChannelPool.GetChannel(ServiceEndpoint endpoint, IEnumerable`1 channelOptions)
at Google.Cloud.Firestore.FirestoreDb.Create(String projectId, FirestoreClient client)
at BackgroundAppFirestoreOne.StartupTask.<Run>d__4.MoveNext() in C:\Users\usernoname\source\repos\BackgroundAppFirestoreOne\StartupTask.cs:line 95
The file is in the directory and does have the necessary permissions.
My environment:
Developing on Windows 10 with Visual Studios 2019 Enterprise
Deploying to a Dragonboard 410c with Windows 10 iot Core
Google.Cloud.Firestore NuGet referenced
I've tried:
Adding the gRPC.core as this suggested, as a NuGet package reference in VS2019, this did not solve the issue.
And I don't have any non-English characters as this suggests.
This error occurs when attempting to execute FirestoreDb db = FirestoreDb.Create(project);
(see line 44 of sample)
Does anyone know what this could be / what I could try to rectify?
I did not encount the exception with Google.Cloud.Firestore 1.1.0 on Windows IoT Core 17763. Could you please check the package version and OS version. BTW, it is not recommended to use the package in background app, since at the moment you can't register a headless app that uses filetypeAssociation, so that the app can not access the credential file(.json).

Scheduled .NET WebJob V3 example

I've upgraded my .NET (not .NET Core) WebJob from V2 (which was working fine) to V3. I'm having trouble getting it to run. I just want the webjob to call a function I've written according to this CRON schedule: "0 0 8,10,12,14,16,18,20 * * *". The website it's running with is .NET also, not .NET Core.
How do I do this? I just want a simple working .NET code sample. I've seen this question New Azure WebJob Project - JobHostConfiguration/RunAndBlock missing after NuGet updates and this example https://github.com/Azure/azure-webjobs-sdk/blob/00686a5ae3b31ca1c70b477c1ca828e4aa754340/sample/SampleHost/Program.cs and this documentation https://learn.microsoft.com/en-us/azure/app-service/webjobs-sdk-how-to#triggers but none of it is helpful.
Actually the use of .Net webjob or .Net Core webjob are almost same, cause the 3.0 sdk targets .NET standard 2.0. I test with Microsoft.Azure.WebJobs -version 3.0.4 and Microsoft.Azure.WebJobs.Extensions -version 3.0.1, i think your TimerTrigger doesn't work cause you lost call the AddTimers extension methods. You could find the description here:Binding types.
Other package I use:
Microsoft.Extensions.Logging -version 2.2.0
Microsoft.Extensions.Logging.Console -version 2.2.0
This is my main method:
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Hosting;
namespace ConsoleApp20
{
class Program
{
static void Main(string[] args)
{
var builder = new HostBuilder();
builder.ConfigureWebJobs(b =>
{
b.AddAzureStorageCoreServices();
b.AddTimers();
});
builder.ConfigureLogging((context, b) =>
{
b.AddConsole();
});
var host = builder.Build();
using (host)
{
host.Run();
}
}
}
}
This is my Functions.cs:
public static void Run([TimerTrigger("0 0 8,10,12,14,16,18,20 * * *")]TimerInfo myTimer, ILogger log)
{
log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
}
And use a appsettings.json(Don't forget set the Copy to Output Directory to Copy always) to configure the storage connection string.
Here is the result:
Scheduled .NET WebJob V3 example
No, it is not possible.
WebJob 3.x only support for .NET Core. Here is the article.
Here is a SO thread about Webjob 3.x for .net core to do some settings.

C# .NET Core 2.2 - C# MongoDB.Driver - Exception

I have 4 projects:
A - .NET Core 2.2 project - reference to B and D (knows nothing about C)
B - .NET 4.7.2 Class Library - reference to C and D
C - .NET 4.7.2 Class Library - reference D and the the MongoDB C# Driver (Version 2.7.30) installed with NuGet.
D - .NET 4.7.2 Class Library - just a container for DTO classes
All projects do build and run.
===
B is a generic data repository.
C is a database context, which uses the MongoDB C# driver.
Both projects B and C work well without any errors, when I use them in "normal" .NET 4.7.2, also 4.5.2 projects.
===
The error:
When I make a call from the .NET Core project A to B which ends in C, I get an error at this point:
private IMongoCollection<T> _Collection;
public IMongoCollection<T> Collection
{
get
{
if (_Collection == null)
{
//This is still ok!
_Collection = _DataBase.GetCollection<T>("MyTableName");
}
return _Collection;
}
}
public IEnumerable<T> All
{
get
{
try
{
//Collection is NOT Null and was loaded from the DB
return Collection.Find(new BsonDocument()).ToList();
}
catch (Exception ex)
{
//THE EXCEPTION APPEARS HERE
}
return null;
}
}
The exception details are:
{System.TypeLoadException: Could not load type 'System.Runtime.Remoting.Messaging.CallContext' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
at MongoDB.Driver.Core.Events.EventContext.AsyncLocal1.get_Value()
at MongoDB.Driver.Core.Events.EventContext.BeginOperation(Nullable1 operationId)
at MongoDB.Driver.Core.Operations.FindCommandOperation1.Execute(IReadBinding binding, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Operations.FindOperation1.Execute(IReadBinding binding, CancellationToken cancellationToken)
at MongoDB.Driver.OperationExecutor.ExecuteReadOperation[TResult](IReadBinding binding, IReadOperation1 operation, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl1.ExecuteReadOperation[TResult](IClientSessionHandle session, IReadOperation1 operation, ReadPreference readPreference, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl1.ExecuteReadOperation[TResult](IClientSessionHandle session, IReadOperation1 operation, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl1.FindSync[TProjection](IClientSessionHandle session, FilterDefinition1 filter, FindOptions2 options, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl1.<>c__DisplayClass41_01.b__0(IClientSessionHandle session)
at MongoDB.Driver.MongoCollectionImpl1.UsingImplicitSession[TResult](Func2 func, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl1.FindSync[TProjection](FilterDefinition1 filter, FindOptions2 options, CancellationToken cancellationToken)
at MongoDB.Driver.FindFluent2.ToCursor(CancellationToken cancellationToken)
at MongoDB.Driver.IAsyncCursorSourceExtensions.ToList[TDocument](IAsyncCursorSource`1 source, CancellationToken cancellationToken)
...}
(sorry for the full exception, but I thought it would help)
My question:
What can I do to solve this problem?
As I said earlier above - this seems to be a .NET Core problem, since the projects run without any error in other projects.
After debugging and testing countless scenarios, I figured out, what was wrong.
Man, that was really hard to find out, because there was only one little hint here on SO that helped me.
So the story from beginning to end:
1.) I have a "normal" .NET 4.7.2 DLL, which hosts my custom MongoDB context.
2.) To do this, I installed the MongoDB Nuget package into this DLL.
3.) The package worked well and as expected when in collaboration with other "normal" .NET 4.7.2 DLLs. No problem. Very happy.
4.) When trying to use my 4.7.2 DLL with a .NET Core project, I get the exception in the start post. Shit.
5.) What you have to keep in mind: When you install a nuget package, it seems to install and references the DLLs, that targets the same (nearest?) framework. In my case target was 4.7.2, so NuGet installed 4.5 versions of the MongoDB.Driver and MongoDB.Driver.Core.
6.) What you actually need, when working with .NET Core, are NOT the 4.5 versions, but the NetStandard 1.5 versions of BOTH MongoDB.Driver and MongoDB.Driver.Core.
7.) So I downloaded the Nuget packages of MongoDB.Driver and MongoDB.Driver.Core manually. NuGet packages are just *.zip files, so I changed the extension and unpacked them.
8.) Inside of each package you find a lib folder with two folders: net45 and netstandard1.5
9.) I extracted the netstandard 1.5 versions of BOTH MongoDB.Driver and MongoDB.Driver.Core.
10.) I replaced the references of BOTH MongoDB.Driver and MongoDB.Driver.Core inside my .NET 4.7.2 DLL with the Netstandard 1.5 versions - BOOM! Working!
So everything in summary:
If (.NET Core + MongoDB)
{
use MongoDB.Driver Netstandard 1.5;
use MongoDB.Driver.Core Netstandard 1.5;
}
If (.NET + MongoDB)
{
use MongoDB.Driver Net 4.5;
use MongoDB.Driver.Core Net 4.5;
}
I really hope, my answer saves others hours or even days of pure confusion.
In my case my Core standart library project has using normal library project even i have changed 4.5, 4.52, 4.61, 4.72 vs. but problem never ended until converting normal lib project to standart library project.
I suggest convert to standart lib

Categories

Resources