Getting Bindingdata from Azure function .net6 (function v4) - azure

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

Related

.netCore3.1 to .net6.0 function app upgrade - Unable to debug in local (DLL error)

I have been working on to upgrade my function app .netcore3.1 solution to .net6.0. After upgrading the solution and all the packages - when I run the solution in local - it is throwing below error. I am unable to debug the function app in local. It is throwing error in startup.cs class. Any solution for this ?
System.MissingMethodException: 'Method not found: 'Microsoft.Extensions.Configuration.IConfigurationBuilder Microsoft.Azure.WebJobs.Hosting.IWebJobsConfigurationBuilder.get_ConfigurationBuilder()'
.csproj file
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<AzureFunctionsVersion>v3</AzureFunctionsVersion>
<RootNamespace>Unilever.DigitalFactory_SPC_ControlCharts</RootNamespace>
<_FunctionsSkipCleanOutput>true</_FunctionsSkipCleanOutput>
</PropertyGroup>
I have created a Function App with.NET core 3.1 version.
My .csproj for .NET Core 3.1
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AzureFunctionsVersion>v3</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.1.1" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
</Project>
Migrated from .net core 3.1 to .net 6.0, when I tried with the .csproj provided in the code got the below errors.
In .csproj file, Change the AzureFunctionsVersion from v3 to v4.
Update Microsoft.NET.Sdk.Functions NuGet Package to latest version - 4.1.1
Output:
Code for FunctionsStartup in Startup.cs
using Function3Core;
using Microsoft.Azure.WebJobs.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
[assembly: FunctionsStartup(typeof(Startup))]
namespace Function3Core
{
class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
}
}
}
Code for WebJobsStartup in Startup.cs
using Function3Core;
using Microsoft.Azure.WebJobs.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
[assembly: WebJobsStartup(typeof(Startup))]
namespace Function3Core
{
class Startup : IWebJobsStartup
{
public void Configure(IWebJobsBuilder builder)
{
}
}
}

Why am I getting duplicate errors in my obj/Release/net6.0 folder after building and deploying Azure function in VS Code

My Azure function works, I can debug it, and deploy it no problem. But when I deploy it and it gets built into the release folder I see errors in the obj -> Release/net6.0 folder.
FYI - I deploy by using the Azure extension and in the Azure workspace panel I click on deploy, then choose my resource group and it runs on it's own and deploys no problem.
I'm wondering if it has something to do with the name I gave my project
"Functions" ?
I'll post what I see below.
Here is my .csproj file for the Azure function project
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<AzureFunctionsVersion>v4</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.1" />
<PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.1.0" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Core\Core.csproj" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Infrastructure\Infrastructure.csproj" />
</ItemGroup>
</Project>
I was having a similar/related problem a week ago (if you ask me to recall it, I'd need to go through heaps of my screenshots). I was able to deploy my Azure function via GitHub but it wouldn't work and I made satisfactory progress by changing (in the Azure Portal) the value of Configuration | Function Runtime Settings | Runtime Version to the value: ~4. However, just today, the portal is warning me to go back to the value: ~3. So, it is just something you might want to try and be prepared to undo.
On a loosely related topic, yesterday I started having problems with deployment again (via GitHub CI/CD). Today, in the Activity Log under a "Sync Web Apps Function Triggers" entry I saw the error: "Encountered an error (BadGateway) from host runtime". A few minutes later it was cleared (and it said it had run for 13 minutes). Now, I'd been in the portal about 15 minutes, so that might have fixed today's issue -- I figured the job was still in the queue and today it was able to pick it up and work it through. By visiting the function in the portal, it must have helped initialize it somehow. Still working on this one. I'll try resetting the Runtime Version value back to the suggested value ~3.
Good luck with your issue. Cheers, Henk.
I have tried replicating your setup (e.g. "Functions" name) on a Mac with Visual Studio details bellow, without any issues however. If you've used any preview version of VS or even Azure Function Extensions, then I suggest you re-create a new project and import your artifacts.
My setup is the following:
Release ID: 1703001972
Git revision: 8eb3c1bb0f14a8e54ee7c227c7047c46cff6ee8c. Build date: 2022-07-12 19:09:28+00
Build branch: release-17.3
Running on .NET 6.0.5 (64-bit)
Operating System: Mac OS X 12.4.0
Darwin 21.5.0 Darwin Kernel Version 21.5.0

Unable to user Memory Cache with Azure Function App

I have created Azure Function App with Http trigger in that I want to use memory cache from system.runtime namespace to cache the token. but when I run the application its throwing the error " System.Runtime.Caching: Could not load file or assembly 'System.Configuration.ConfigurationManager, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The system cannot find the file specified."
I have made sure the exact version is installed in the project. here is the csproj file.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AzureFunctionsVersion>v3</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.11" />
<PackageReference Include="System.Configuration.ConfigurationManager" Version="5.0.0" />
<PackageReference Include="System.Runtime.Caching" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
Here is the bare minimum version of the code where I am facing the issue.
public static class Function1
{
public static MemoryCache accessTokenCache = new MemoryCache("accessToken");
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
accessTokenCache.Add("123", "123", new CacheItemPolicy() { Priority = CacheItemPriority.Default });
return new OkObjectResult("");
}
}
above code works fine with system.runtime.caching nuget with version 4.7.0. I have downgraded for now to get it work.
I have also posted the issue in github for further follow up.
https://github.com/Azure/Azure-Functions/issues/1867

ASP .NET Core : Directory.EnumerateFiles and IIS hosting

When I publish my ASP .NET Core (v.2.2) web application on a IIS-server it throws an exception on this line:
Directory.EnumerateFiles(_environment.ContentRootPath + #"/Pages/API")
The exception:
An unhandled exception has occurred while executing the request.
Could not find a part of the path 'C:\Release\MySite\Pages\API'.
System.IO.DirectoryNotFoundException at
System.IO.Enumeration.FileSystemEnumerator`1.CreateDirectoryHandle(String
path, Boolean ignoreNotFound)
When I look inside the published folder there is no API folder, but should it not be inside of my website dll? Or can I not use relative or absolute paths to find files in my web project when I publish it on ISS?
Note: The pages in folder API have Build Action : content, and the code works without problem in development (with IIS-express).
For asp.net core, it will precompile views while publishing into Project.Views.dll. For Directory.EnumerateFiles, it only lists the real exist files in the disk.
For a solution, try to modify your project.csproj to add <MvcRazorCompileOnPublish>false</MvcRazorCompileOnPublish>.
Full
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
<MvcRazorCompileOnPublish>false</MvcRazorCompileOnPublish>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.0" />
</ItemGroup>
</Project>

External dependencies in Azure functions with netcore

I've been able to get Azure functions written in net core to run. I now have added a reference to "WindowsAzure.Storage" and am now getting loaderexceptions when I use the local test environment ("func host start").
I can not use the default table storage binder as I need to upsert records in different tables.
I use precompiled functions and am developing with VSCode on OSX. I can't find any info if this scenario is supported or not. Is it even possible to get external dependencies working with the 2.0 runtime of Azure functions.
The local SDK/runtime is
Azure Functions Core Tools (2.0.1-beta.21)
Function Runtime Version: 2.0.11370.0
My csproj file
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.WebJobs" Version="3.0.0-beta3" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions" Version="3.0.0-beta3" />
<PackageReference Include="WindowsAzure.Storage" Version="8.6.0" />
</ItemGroup>
<ItemGroup>
<Reference Include="Microsoft.CSharp" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="SearchTwitter\function.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
</Project>
Part of my function
namespace MyProject.Functions
{
public class SearchFunction
{
public async static Task Run(TimerInfo myTimer, Binder binder, TraceWriter log)
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(System.Environment.GetEnvironmentVariable("StorageConnection", EnvironmentVariableTarget.Process));
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
CloudTable searchMetaDataTable = tableClient.GetTableReference("SearchMetaData");
await searchMetaDataTable.CreateIfNotExistsAsync();
}
}
Function.json
{
"bindings": [
{
"type": "timerTrigger",
"direction": "in",
"schedule": "0 */15 * * * *",
"runOnStartup": true,
"name": "myTimer"
}
],
"scriptFile": "../MyProject.Functions.dll",
"entryPoint": "MyProject.Functions.SearchFunction.Run"
}
The Azure Storage Namespacee is available by default by the Azure Functions hosting environment. You can find more details here: https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-csharp#referencing-external-assemblies
However, if that’s not what you’re looking for, rest assured that you can consume any external NuGet package by adding it to your Function’s csproj file. For an example on how to do it, check the sample code in this GitHub repo https://github.com/lindydonna/CSharpHttpCore/blob/master/HttpTriggerCore/HttpTriggerCore.csproj
For precompiled functions, WindowsAzure.Storage package comes as sub-dependency of Microsoft.NET.Sdk.Functions, so you don't need to reference it separately.
If you still reference it, and the reference is of a wrong version, you will get conflicts all over the place.
Such care should be taken for any sub-dependency of Microsoft.NET.Sdk.Functions. Otherwise, referencing NuGets is perfectly supported.

Resources