ConfigurationBuilder not working in azure function - c#

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).

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.

How can I make a GRPC call for a service which is inside a subdirectory? (in .Net Framework)

I am trying to connect to a gRPC service in a .NetFramework 4.5 windows application. I am currently using metapackage nuget Grpc which I know is only in maintenance mode now...
I need to access the service which is not at a host:port location, but has a subpath, subdirectory. My service is located here "https://example.com/mySubpath"
Is there a way to specify a subdirectory, subpath for gRPC calls in .NetFramework?
For .NetFramework4.5, if I specify the full path (which contains the "mySubpath" part) it doesn't work
var channel = new Channel("example.com/mySubpath", ChannelCredentials.SecureSsl);
I saw that I could also add a List<ChannelOption> parameter to the Channel constructor, but don't know if there is one option which I could use for that.
I am currently trying to upgrade to .NetFramework 4.6.1 to see if I can use Grpc.Net.Client which I understood it has some support over .NetFramework 4.6.1 if a WinHttpHandler is used. (https://learn.microsoft.com/en-us/aspnet/core/grpc/netstandard?view=aspnetcore-6.0)
I have found a solution here https://github.com/grpc/grpc-dotnet/issues/880 for .NetCore and I am trying to see if I can use that to the .NetFramework 4.6. I used the SubdirectoryHandler class as it is defined in the link to change the RequestUri and assigned a WinHttpHandler
var handler = new SubdirectoryHandler(new WinHttpHandler(), subpath);
var httpClient = new HttpClient(handler);
GrpcChannel channel = GrpcChannel.ForAddress(address, new GrpcChannelOptions { HttpClient = httpClient });
but I am getting an exception related to assembly System.Buffers, Version=4.0.2.0.
StatusCode="Unavailable",
Detail="Error starting gRPC call. HttpRequestException: Error while copying content to a stream. FileLoadException: Could not load file or assembly 'System.Buffers, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)",
I think this is because Grpc.Net.Client references version=4.0.2.0, while the System.Net.Http.WinHttpHandler references version 4.0.3.0.
Any idea what I need to change to be able to use the subdirectory,subpath for .NetFramework 4.6.1 or for .NetFramework4.5?

Could not load file or assembly Microsoft.IdentityModel.Tokens problem

I am trying to verify users with a JWT token. The code I used below works perfectly fine in a console application. But when I want to apply it in my Azure function it gives me the error:
Could not load file or assembly Microsoft.IdentityModel.Tokens
I do have one other Azure function in my solution but it doesn't use this NuGet package. I already took a look at this link:
Could not load file or assembly 'Microsoft.IdentityModel.Tokens, Version=5.2.0.0
I can't get anything out of that. So what am I doing wrong? Thanks in advance
string key = "";
var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
var header = new JwtHeader(credentials);
var payload = new JwtPayload
{
{ "some ", "hello "},
{ "scope", "http://dummy.com/"},
};
var secToken = new JwtSecurityToken(header, payload);
var handler = new JwtSecurityTokenHandler();
var tokenString = handler.WriteToken(secToken);
var token = handler.ReadJwtToken(tokenString);
log.LogInformation(token.ToString());
Solved it by adding a line of code in the .csproj file
<PropertyGroup>
<_FunctionsSkipCleanOutput>true</_FunctionsSkipCleanOutput>
</PropertyGroup>
I had this problem not when running in development, but on deployed projects. This did not relate to Azure project, but to a web application deployed onto a remote windows web server
I took these steps to resolve it:
Get the files names of the DLLs from references
Find these DLLS in the packages subfolder of your vs project.
Make sure you have the right version for your .net framework version
Copy the DLLs to a folder, we called it "deployments"
Remove the Nuget packages
Reference the DLLs directly with copylocal=true
You may or may not need to add the DLLs to the bin folder in your deployment package. The packages we needed are shown below

Error with Azure Function and Docker

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.

tweetinvi working on local host but throwing dll error on azure server

The error below occurs when attempting to make an api request using tweetinvi running on an azure web role.
Could not load file or assembly 'System.Threading.Tasks,
Version=2.6.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or
one of its dependencies. The system cannot find the file specified.
I tried installing the nuget package for this dll, but then I get a compilation error (same type being declared in two places,) because apparently, system.threading.tasks in bundled inside of mscorlib.dll
.NET version: 4.5
tweetinvi version : v4.0.30319 strong name
I assume that you mentioned tweetinvi version is the Runtime Version. I do a demo using TweetinviAPI. It works correctly on my side. If it is possible, please have a try to redeploy it again or create new cloudservie to test it again..
The following is my detail steps:
1.Create cloudservive project and with WebRole.
2.Reference the tweetinvi with Nuget
3.Create Tweetinvi application (https://apps.twitter.com/) and get the Consumer Key,Consumer Secret, Access Token, Access Token Secret
4.Add the following code in the HomeController About() to test it.
Auth.SetUserCredentials(string consumerKey, string consumerSecret, string userAccessToken, string userAccessSecret);
// Publish the Tweet "Hello Tweetinvi" on your Timeline
Tweet.PublishTweet("Hello Tweetinvi! ");
5.Publish the cloudservice to Azure and visit(http://xxxxx.cloudapp.net/Home/About) get the test result.
6.Check from twitter, it works correctly

Categories

Resources