Azure function local development in VS cannot find function - c#

I'm currently developing a function app using Microsoft's Azure functions in Visual Studio. I am able to deploy and publish the functions on azure and it seems to run but whenever I try to run a function local the Hosting Environment is unable to find any "Jobs". I have included a picture below.
It must be stated that I was at some point able to deploy locally but I believe after some updates, I was unable to run my functions
The current version of Azure Function and Web Jobs Tools: 15.0.40424.0
I have tried to use Azure Functions V1 (.NET Frameworks) and Azure Functions V2 (.NET Core) when I create a new project but with unsuccessful results. I have also tried to create a new clean project, reinstall VS and also reset Windows in case of any strange setup.
Am I missing something and do I explicitly need state my functions somewhere such that the hosting environment can find them??
Hosting environment not finding any functions:
[6/20/2018 7:24:37 AM] Host configuration file read:
[6/20/2018 7:24:37 AM] {}
[6/20/2018 7:24:37 AM] Starting Host (HostId=2017noy-1005193785,
InstanceId=c8332a19-7eb3-4446-9b3e-4307f20a57bc, Version=2.0.11651.0,
ProcessId=15184, AppDomainId=1, Debug=False, ConsecutiveErrors=0,
StartupCount=1, FunctionsExtensionVersion=)
[6/20/2018 7:24:38 AM] Generating 0 job function(s)
[6/20/2018 7:24:38 AM] No job functions found. Try making your job classes
and methods public. If you're using binding extensions (e.g. ServiceBus,
Timers, etc.) make sure you've called the registration method for the
extension(s) in your startup code (e.g. config.UseServiceBus(),
config.UseTimers(), etc.).
Template Empty HTTPTrigger Function - Function1.cs:
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.WebJobs.Host;
using Newtonsoft.Json;
namespace FunctionApp1
{
public static class Function1
{
[FunctionName("Function1")]
public static IActionResult
Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route =
null)]HttpRequest req, TraceWriter log)
{
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");
}
}
}
CSPROJ File
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<AzureFunctionsVersion>v2</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="1.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>
local.settings.json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"AzureWebJobsDashboard": "UseDevelopmentStorage=true"
}
}

The function.json file is generated after VS build. Check whether it's in a folder named after your function, under ~\bin\Debug\netstandard2.0 folder.
If you don't see the folder like Function1(containing function.json inside), you may have met the same problem my colleague has.
Didn't find the rout cause, VS just failed to generate function.json on my colleagues's computer, but on my side things works fine(VS and Azure Function and Web Jobs Tools has the same version).
The workaround we found is to downgrade Microsoft.NET.Sdk.Functions to 1.0.12.
Just for your reference, we have also tried upgrading Azure Function and Web Jobs Tools and delete Microsoft.NET.Sdk.Functions in C:\Users\UserName\.nuget\packages\microsoft.net.sdk.functions\1.0.13 and install this package again.
Update
Upgrade Microsoft.NET.Sdk.Functions to latest version of 1.0.14 also works on our side.

I had a same issue but I have downgrade Microsoft.NET.Sdk.Functions from version 3.0.11 to 3.0.10 and then start a program and it has shown all my functions in the console application once the program successfully runs I have upgraded to the previous function 3.0.11 it worked.

Related

Azure Functions in .NET 7 (isolated) published to Azure, 0 functions loaded

I'm trying to deploy an Azure Function (isolated) with .NET 7 to MS Azure using a GitHub Actions workflow. Everything seems to run fine, but for some reason, the Function is not loaded when I deploy it to the cloud. When I run the function local host, everything is fine (works on my machine), once deployed it doesn't.
public class DemoFunction
{
private readonly ILogger _logger;
public DemoFunction(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<DemoFunction>();
}
[Function("DemoFunction")]
public HttpResponseData Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req)
{
var response = req.CreateResponse(HttpStatusCode.OK);
response.Headers.Add("Content-Type", "text/plain; charset=utf-8");
response.WriteString("Demo function works!");
return response;
}
}
The Function App contains only a single function with an HTTP binding (no authentication, anonymous requests allowed). I use Bicep to deploy infra and GH Actions to deploy the Function App. Log Analytics shows this:
So for some reason it does find the function, but not load it. If I navigate to the Functions blade in the Azure Portal I don't see any function. The project is just a POC project and hosted publicly available at https://github.com/nikneem/function-deployment-with-gh-actions
Any ideas?
Oh wow, I found the answer in the deployment process. In my GitHub Actions workflow, I did a dotnet publish of the Azure Functions project to an output folder. I zipped the content of the output folder and published that zip file as a workflow artifact.
Then in the deployment, I downloaded the workflow artifact (e.g. that zip file) and did a Zip Deployment using that zip file.
Now apparently, something went wrong with this zip file, so I removed that manual zip action, mainly because I found out the deployment step in the GitHub Action also works when you pass a folder containing all published files in.
So the publish step in my GH Actions workflow now looks like this:
publish-functions:
runs-on: ubuntu-latest
needs: versionize
steps:
- uses: actions/checkout#v3
- uses: actions/setup-dotnet#v3
with:
dotnet-version: "7.0.x"
- name: Restore packages
working-directory: src
run: dotnet restore
- name: Publish functions app
working-directory: src
run: dotnet publish $FUNCTIONS_PATH/$FUNCTIONS_PROJECT -c Release --no-restore -o functionsout /p:Version=${{needs.versionize.outputs.semver}}
- name: Upload functions artifact
uses: actions/upload-artifact#v3
with:
name: player-functions
path: src/functionsout/*
and the deployment step looks like this:
deploy-function-app:
runs-on: ubuntu-latest
needs: [publish-functions, deploy-infrastructure-prod]
steps:
- uses: actions/download-artifact#v3
with:
name: player-functions
path: function
- uses: azure/login#v1
with:
creds: ${{secrets.AZURE_PROD}}
- name: Deploy Azure Functions app
uses: Azure/functions-action#v1
with:
app-name: ${{needs.deploy-infrastructure-prod.outputs.functionResourceName}}
package: function
Taking a peek at the logs that the deployment process produces, it will still create a zip file and deploy that. But this is a different zip file than I created manually. All works fine now ;)
As per the note in this documentation:
To be able to publish your isolated function project to either a Windows or a Linux function app in Azure, you must set a value of dotnet-isolated in the remote FUNCTIONS_WORKER_RUNTIME application setting. To support zip deployment and running from the deployment package on Linux, you also need to update the linuxFxVersion site config setting to DOTNET-ISOLATED|7.0. To learn more, see Manual version updates on Linux.
I can see the relevant configuration settings appear to be set correctly in the infrastructure template with the exception of linuxFxVersion - this doesn't seem to be mentioned anywhere and the cicd workflow does appear to be performing a zip deployment.

Visual Studio .NET Framework 4.8 - Could not load file or assembly 'Azure.Core, Version=1.20.0.0,

We have a Microsoft Azure Function App in .NET Framework 4.8.
We want to retrieve via Managed Identity a document out of our blob.
We're trying the use the following code:
BlobContainerClient containerClient = new BlobContainerClient(new Uri(containerEndpoint), new DefaultAzureCredential());
BlobClient blobClient = containerClient.GetBlobClient(mapName);
var bytes = blobClient.DownloadContent().Value.Content.ToArray();
To make this work we're using nuGet packages:
Azure.Identity (latest version: 1.5.0)
Azure.Storage.Blobs (latest version: 12.11.0) => This needs to work with Azure.Core 1.22.0
Whenever we try to POST a message to our function, we directly receive an error:
Could not load file or assembly 'Azure.Core, Version=1.20.0.0, Culture=neutral, PublicKeyToken=92742159e12e44c8' or one of its dependencies. The system cannot find the file specified.
Adding Azure.Core package version 1.22.0 or 1.20.0 direclty into the project is not helping.
It works if we either use Azure.Identity or Azure.Storage.Blobs, but not when using both.
In the project.assets.json file, we can see a dependency to version Azure.Core 1.20:
"Azure.Identity/1.5.0": {
"type": "package",
"dependencies": {
"Azure.Core": "1.20.0",
"Microsoft.Identity.Client": "4.30.1",
"Microsoft.Identity.Client.Extensions.Msal": "2.18.4",
"System.Memory": "4.5.4",
"System.Security.Cryptography.ProtectedData": "4.5.0",
"System.Text.Json": "4.6.0",
"System.Threading.Tasks.Extensions": "4.5.4"
},
Is there any way how we can reference in our Function App to use version 1.22.0 of the Azure.Core package?
I have solved this previously by modifying the .csproj like below when i get the error Could not load file or assembly 'Azure.Core, Version=1.20.0.0
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net48</TargetFrameworks>
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>signingkey.snk</AssemblyOriginatorKeyFile>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
</PropertyGroup>

Running dotnet-isolated AzureFunction does not work

I have developed an Azure Function v4 with .net 6.0. It contains only http triggered functions.
Locally everything works fine, but after deploying it to Azure i only get 500 Status Code by calling any endpoint and it always throws InvalidOperationException at Microsoft.Azure.WebJobs.Script.Workers.Rpc.RpcFunctionInvocationDispatcherLoadBalancer.GetLanguageWorkerChannel : Did not find any initialized language workers
Application settings
Operating System: Windows
Runtime Version: 4.0.1.16815
Location: West Europe
Update Add more information
Project file:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<AzureFunctionsVersion>v4</AzureFunctionsVersion>
<OutputType>Exe</OutputType>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="11.0.0" />
<PackageReference Include="Microsoft.ApplicationInsights" Version="2.20.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.6.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.OpenApi" Version="1.0.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.0.13" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.3.0" OutputItemType="Analyzer" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
local.settings.json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
"StorageConnectionString": "UseDevelopmentStorage",
"APPINSIGHTS_INSTRUMENTATIONKEY": "MyInstrumentationKey"
},
"Host": {
"LocalHttpPort": 7071,
"CORS": "*"
}
}
One of the workaround to resolve this issue:
Created Azure Functions (Stack: .Net 6 Isolated) in Visual Studio and run locally:
After deploying of Function App in the Azure Portal (Stack: .Net 6, Location: West Europe, OS: Windows, Plan: Consumption, Function Runtime: Isolated)
This is the configuration:
After deploying, the function URL is running successfully:
As I can see a setting called WEBSITE_NODE_DEFAULT_VERSION is added into your .Net Function App Configuration Settings.
If your function is not created with node.js and if you are not using this application setting explicitly in your code then you can remove this property from your function app. This is stated in this MSFT Q&A.
The other reasons for this kind of error would be
The Functions Runtime is initialized but it failed to initialize the Language Worker. So, the Functions Runtime detects that the worker channel has not started and logs the error message on further invocations.
Note:
5. Try Re-creation of the Function App (.Net 6 - Windows OS- West Europe Location) in the Azure Portal and deploy your HTTP Trigger Function from Visual Studio.
Or
6. Try removing the WEBSITE_NODE_DEFAULT_VERSION setting > Save > Restart the app in the azure portal and run the function.
7. Make sure this setting is "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated" in your function app local.settings.json file.
8. This error may exist due to unmatching of Functions worker version and SDK version. If any updates available, please update them through NuGet Packet Manager:
Also, this error exist in previous version of dotnet Isolated is 5 and in Azure Functions Version V3.
References:
azure-functions-dotnet-worker/issues
https://github.com/Azure/azure-functions-host/issues/7618.
SO Thread1

ServiceBusTrigger not found in basic Azure Function project

I have created a brand new .NET Core 3.1 Azure Function project using the Visual Studio template
I am using V3 of the functions, i.e. the version created by the template
I have the latest VS - 16.10.2
Straight away, it fails with ServiceBusTrigger and Connection not found?
using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
namespace AzureFunctionTest
{
public static class Function1
{
[FunctionName("Function1")]
public static void Run([ServiceBusTrigger("AzureFunctionTest", "Research Subscription", Connection = "eventbus-connection")]string mySbMsg, ILogger log)
{
log.LogInformation($"C# ServiceBus topic trigger function processed message: {mySbMsg}");
}
}
}
Really strange how a template from MS itself does not work and a bit concerning this fails on the first hurdle!!
Here are the relevant parts of my project file
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AzureFunctionsVersion>v3</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Azure.Messaging.ServiceBus" Version="7.1.2" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.11" />
</ItemGroup>
Azure.Messaging.ServiceBus seems to be the latest package and the one recommended to use
What am I missing?
Paul
You should be using Microsoft.Azure.WebJobs.Extensions.ServiceBus package. Link.
You can read this official documentation for further information.

C# .NET standard 1.6 with excessive dependencies in published application

I am trying out Visual Studio 2017 and .NET Core in what is my first attempt at C#/.NET in a few years (returning from Golang). I tried to create a small hello world style networking application that just listens and echos the input from tcp clients:
using System;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
namespace TaskSockets
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
TcpListener server = new TcpListener(IPAddress.Any, 5555);
server.Start();
while (true)
{
TcpClient newClient = server.AcceptTcpClientAsync().Result;
Task.Run(async () => {
StreamWriter sWriter = new StreamWriter(newClient.GetStream(), Encoding.ASCII);
StreamReader sReader = new StreamReader(newClient.GetStream(), Encoding.ASCII);
Boolean bClientConnected = true;
String sData = null;
while (bClientConnected)
{
sData = await sReader.ReadLineAsync();
Console.WriteLine("Client: " + sData);
}
});
}
}
}
}
My project/build config looks like the following:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netstandard1.6</TargetFramework>
<RuntimeIdentifiers>win7-x64</RuntimeIdentifiers>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NETCore.Runtime.CoreCLR" Version="1.1.1" />
<PackageReference Include="Microsoft.NETCore.DotNetHostPolicy" Version="1.1.0" />
</ItemGroup>
</Project>
After publishing the application (dotnet publish) I get a folder with the executable I need. The problem I encounter, however, is that the folder contains 205 files (mostly .NET related DLL files) and is more than 30 MB in size. This includes dll files with reference to .NET libraries I don't even use such as System.Xml and Linq.
Is there any way to reduce the number of files and size of the published application so that just what I need is included?
UPDATE:
Tried to re-create the project from scratch using the dotnet tool rather than visual studio:
dotnet new console --language C# --name Socket --output Socket
--framework netcoreapp1.0
This created this project (which for some reason compiles to a dll despite the exe output type and console application target):
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp1.0</TargetFramework>
</PropertyGroup>
</Project>
Then manually modify the csproj file so it looks like this:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp1.0</TargetFramework>
<RuntimeIdentifiers>win7-x64</RuntimeIdentifiers>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NETCore.Runtime.CoreCLR" Version="1.0.6" />
</ItemGroup>
</Project>
Now publish with:
dotnet publish --runtime win7-x64 --configuration Release
And go to:
./bin/Release/netcoreapp1.0/win7-x64
Now suddenly there is a working exe-file and just a few DLL files that is approximately 1 MB in size. By deleting the subfolder called "publish" I now have something that works without most of the bloat. No idea why this worked and if its considered expected behavior. No idea what the publish folder is for either or whether or not its needed for deployment on a computer without .NET installed. Microsoft have some work to do on its documentation.
Have a look at https://learn.microsoft.com/en-us/dotnet/articles/core/deploying/index
In the 1st case, your publish command generates output for a Framework-dependent deployment that is relying on the presence of the .NET Core framework on the target machine. Your code (in the form of dll(s)) will be executed by the runtime.
In the 2nd case, when you specify the target runtime using the --runtime option, publish generates output for a Self-contained deployment in which the used version of the .NET Core framework is included. There's a way to reduce the total size of the output as described in the above mention article in the Deploying a self-contained deployment with a smaller footprintsection.
As for why <OutputType>Exe</OutputType> didn't generate a exe-file, check out https://learn.microsoft.com/en-us/dotnet/articles/core/tools/dotnet-build
It basically says the generated
binaries include the project's code in Intermediate Language (IL)
files with a .dll extension
and that the difference between specifying and not specifying <OutputType>Exe</OutputType>
is that the IL DLL for a library doesn't contain entry points and
can't be executed.

Categories

Resources