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.
Related
I'm trying to create non-static functions in my Azure Function projet in .NET 5 (VS 2022) and the Startup Configure method is not being called.
Here's my start up class
[assembly: FunctionsStartup(typeof(AuthenticationGateway.Functions.Startup))]
namespace AuthenticationGateway.Functions
{
class Startup : FunctionsStartup //public or not, still does not get called.
{
public override void Configure(IFunctionsHostBuilder builder)
{
//break point here never gets hit...
}
}
}
And here's the function in question:
namespace AuthenticationGateway.Functions
{
public class CreationConnection
{
private AuthenticationGatewayContext Context { get; set; }
public CreationConnection(AuthenticationGatewayContext context)
{
Context = context;
}
[Function("CreationConnection")]
public HttpResponseData Run([HttpTrigger(AuthorizationLevel.Function, "get")] HttpRequestData req,
FunctionContext executionContext)
{
var response = req.CreateResponse(HttpStatusCode.OK);
return response;
}
}
}
I've tried commenting all of the code in Configure just in case it was a problem with it, not working either. Also tried marking the startup class as public too, no go.
Here are the dependencies for the projet in question
They are not the default dependencies the projet has when creating an Azure Function projet but as I tried other solutions to fix the issue, it lead me to plug those in.
Here's what the console is saying when starting the project:
Azure Functions Core Tools Core Tools Version: 3.0.3904 Commit
hash: c345f7140a8f968c5dbc621f8a8374d8e3234206 (64-bit) Function
Runtime Version: 3.3.1.0
Anything I missed ?
EDIT: I have reverted to the following dependencies as the previous ones made it so no functions would be found in the project.
On this page here it says those following dependencies have to be installed:
Microsoft.Azure.Functions.Extensions
Microsoft.NET.Sdk.Functions package version 1.0.28 or later
Microsoft.Extensions.DependencyInjection (currently, only version 3.x and earlier supported)
I have done so, except the last one because it is incompatible with .NET 5 it seems. Also, the project is now unbuildable:
error MSB4062: The "GenerateFunctionMetadata" task could not be loaded from the assembly
I have tried to reproduce the same issue which you got by following the below steps:
Created the Azure Functions (Stack: .Net5-v3) in VS2022.
Before adding Microsoft.Net.Sdk.functions to the project, it was built successfully.
After adding Microsoft.Net.Sdk.functions to the project, it has run to the same issue MSB4062 error as below:
By referencing these SO Thread1 and Thread2, removing Microsoft.Net.Sdk.functions will solve the compile issue.
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 :-)
When I try to Initialize the NltkNet object in my dotnet core web application I receive an error saying an assembly is not found or has a different manifest definition than its assembly reference.
The code is fairly simple, it does nothing at all except initialize an NltkNet object when a button is clicked.
public IActionResult Upload()
{
Nltk.Init(new List<string>()
{
#"C:\IronPython27\Lib",
#"C:\IronPython27\Lib\site-packages",
});
return View();
}
I was able to get the exact same code to work in my console application without issue.
Is this a configuration issue on my end or is ASP.NET core MVC web application support not available for NltkNet?
I have discovered that NltkNet does not support dotnet core.
I'm using azure functions template project in VS2017 and choosing version 2 (beta). I published it unchanged and it worked.
I added nuget package Microsoft.Extensions.Configuration and wrote a single statement to initialize an instance of ConfigurationBuilder
public static class Function1
{
[FunctionName("Function1")]
public static IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequest req, TraceWriter log)
{
var cb = new ConfigurationBuilder();// <<<<< added line
log.Info("C# HTTP trigger function processed a request.");
string name = req.Query["name"];
string requestBody = new StreamReader(req.Body).ReadToEnd();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
return name != null
? (ActionResult)new OkObjectResult($"Hello, {name}")
: new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}
}
With this code the function crashes with 500 - internal server error and I cannot find any reason.
Am I missing something? How do I access configuration information in Azure functions (v2.0)
Edit:
Executing in Compute emulator throws
System.Private.CoreLib: Exception while executing function: Function1. Aweton.Labs.AzureFunc1: Could not load file or assembly 'Microsoft.Extensions.Configuration, Version=2.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the file specified. System.Private.CoreLib: Could not load the specified file.
I was having the same issue. You need following nuget packages to be installed for these to work elegantly
You need to install Microsoft.Extensions.Configuration for this to init at first place
Additionally
SetBasePath() requires:
Microsoft.Extensions.Configuration.Abstractions
AddJsonFile() requires:
Microsoft.Extensions.Configuration.FileExtensions
Microsoft.Extensions.Configuration.Json
AddEnvironmentVariables() requires:
Extensions.Configuration.EnvironmentVariables
and possibly Microsoft.Extensions.Configuration.UserSecrets
Please refer below for more info
https://www.koskila.net/how-to-access-azure-function-apps-settings-from-c/
Disclaimer: I believe my Visual Studio 2017 environment is kept up to date by notification services as of 15.7.3.
Setup: Created fresh Azure Function project (Add New Project, Cloud, Azure Functions [ENTER], Azure Functions v2 Preview (.NET Standard))
Once VS completes restoring dependencies set new project as the startup point in the solution and press F5 to run local debug.
VS2017 starts dotnet and you can find a line like
http://localhost:7071/api/Function1
Navigate your browser to the URL to make sure the project works OK.
Now stop the debugger.
To reproduce behavior:
Open nuget package manager and find Microsoft.Extensions.Configuration. At the time of writing it has stable latest version 2.1.0. Add this package to the project.
Also, just for fun, add System.Data.SqlClient, (latest version 4.5.0)
Now make sure your project really depends on the DLLs.
For example write the following as the first statements in method Run;
var cb = new Microsoft.Extensions.Configuration.ConfigurationBuilder();
var sc = new System.Data.SqlClient.SqlConnection();
Now Start debug again. (F5)
The Functions host is still loading OK, but as you try refresh the browser the console window will report
[10.06.2018 15:37:28] Executing 'Function1' (Reason='This function was programmatically called via the host APIs.', Id=6804e02c-441a-4e62-b6a4-6b02154ec7fb)
[10.06.2018 15:37:29] Executed 'Function1' (Failed, Id=6804e02c-441a-4e62-b6a4-6b02154ec7fb)
[10.06.2018 15:37:29] System.Private.CoreLib: Exception while executing function: Function1. FunctionApp-repro: Could not load file or assembly 'System.Data.SqlClient, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified. System.Private.CoreLib: Could not load the specified file.
Work around:
Open nuget package manager and "Update"
System.Data.SqlClient to version 4.1.0
And
Microsoft.Extensions.Configuration to version 2.0.0
You can access configuration file, e.g. dev.settings.json, with ConfigurationBuilder by specifying base path and file name.
public static IActionResult Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequest req, TraceWriter log, ExecutionContext context)
{
var config = new ConfigurationBuilder()
.SetBasePath(context.FunctionAppDirectory)
.AddJsonFile("dev.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
var values = config["Values"];
...
}
This should be resolved on the latest version of the Azure Functions runtime (2.0.11888, CLI 2.0.1-beta.31).
I am trying to implement the ICS creator sample for Azure Functions: https://github.com/Azure-Samples/azure-functions-create-ics-file-using-csharp-sample.
I followed all the steps there, but the difference with my implementation is that I'm running the function locally with Docker, and I am getting this error:
An unhandled exception occurred while processing the request.
CompilationErrorException: Script compilation failed.
Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker+d__26.MoveNext()
in DotNetFunctionInvoker.cs, line 313
FunctionInvocationException: Exception while executing function:
Functions.swinvite
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Per my understanding, the error is related with the ical.net library, that is not being imported to the image.
Any ideas?
Thank you in advance.
You are right, error is related to Ical.net library. You can try this repository.
More details
The guide you follow is to create function in function runtime 1.x(.net framework), where packages will be restored according to project.json. But you want to run using docker(image uses runtime 2.x, based on .net core), where project.json is invalid. So the file can be dropped.
Then we have to add Ical.Net related assemblies manually. We can download latest version package as the one in that guide is out of date.
After downloading the package, create a bin folder under ~\GetInvite. Copy Ical.Net.dll and NodaTime.dll(dependency of Ical.Net) to this folder.
And some changes in run.csx.
// add assembly
#r "Ical.Net.dll"
// remove some unnecessary namespaces
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using Ical.Net;
using Ical.Net.DataTypes;
using Ical.Net.CalendarComponents;
using Ical.Net.Serialization;
// remove async as the method has no await method
public static HttpResponseMessage Run(HttpRequestMessage req, TraceWriter log)
{
... // remain the same
// Event is deprecated in new version, use CalendarEvent
var icalevent = new CalendarEvent{...}
... // remain the same
}
One more point, in function.json change authLevel from function to anonymous. Or you will get 401 error.