Default Azure Function app base path D:\home\site\wwwroot Azure Function 2.x - azure

Currently, by default, Azure function base path is set to "D:\home\site\wwwroot". For example, when publishing, VS uploads app to this folder.
I need to read config file from this folder. We have problem of ExecutionContext is null via dependency injection via constructor
Setting a new environment variable might cause issue if the path is changed in the future.
My question is that how can I use app base path that is reliable and stable, that works with DI via constructor.
Azure Function 2.x
VS 2017

you can use function.json to have your configuration key pairs.
for example:
System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
and in function.json you can do like this:
"mykey": "myvalue"
{
"generatedBy": "Microsoft.NET.Sdk.Functions-1.0.24",
"configurationSource": "attributes",
"bindings": [
{
"direction":"in",
"type": "timerTrigger",
"useMonitor": true,
"runOnStartup": false,
"name": "myTimer",
"mykey": "myvalue"
}
],
"disabled": false,
"scriptFile": "../bin/**.dll",
"entryPoint": "**.Run"
}

There is an environment variable pointing to home directory. This would not change as many services including function app take dependency on it. Below is how function runtime fetches it in azure environment.
string home = GetEnvironmentVariable("HOME");
Path = System.IO.Path.Combine(home, "site", "wwwroot");

Related

Output binding and generation of function.json

I'm trying to create an Azure function that will output to a table. I'm using the Azure Function App, and so, as I currently understand it, the function.json is generated for me by the SDK. My function definition is as follows:
public static HttpResponseMessage Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req,
TraceWriter log,
[StorageAccount("table_storage")] ICollector<TableItem> outputTable)
I've defined TableItem as a class that inherits from TableEntity. When I deploy this and look at the generated function.json, it doesn't mention the output parameter binding:
{
"generatedBy": "Microsoft.NET.Sdk.Functions.Generator-1.0.7",
"configurationSource": "attributes",
"bindings": [
{
"type": "httpTrigger",
"methods": [
"post"
],
"authLevel": "function",
"name": "req"
}
],
"disabled": false,
"scriptFile": "../bin/FunctionApp5.dll",
"entryPoint": "FunctionApp5.DeliveryComplete.Run"
}
If I run this from Visual Studio, I get the following error:
Cannot bind parameter 'outputTable' to type ICollector`1
I have a few questions about this behaviour: the first and main one is, why is function.json not showing the output binding? Secondly, I understand why this can't be edited when you deploy from VS, but is there a way to manage the bindings without guesswork (I came across using ICollector in this post), but I can't find anywhere else that says it should or shouldn't be there.
Finally, how does (or does) running this from the desktop interact with the published function: does it connect to the published version of the function, or does it generate the function.json locally?
That's a common source of confusion, but input and output bindings are not visible in generated function.json, only trigger does. They will still work normally.
If you are trying to write to Table Storage, you should use Table attribute instead of StorageAccount. ICollector is mentioned in Azure Table storage bindings for Azure Functions.
When running locally, the files stay locally and run in local runtime, without deployment to Azure. They might still interact with real Azure services via bindings.

Include dll in azure function and move the code by ARM tempate into resource group

In my ARM template i have piece of code:
"name": "[variables('logicappname')]",
"type": "Microsoft.Logic/workflows",
"location": "[resourceGroup().location]",
"apiVersion": "2016-06-01",
"dependsOn": [
"[resourceId('Microsoft.Web/connections', variables('servicebusConnectionName'))]",
"[resourceId('Microsoft.Web/sites/sourcecontrols', variables('functionAppName'), 'web')]"
],
"tags": {
"displayName": "display-name"
},
And in resources array:
{
"apiVersion": "2015-08-01",
"name": "web",
"type": "sourcecontrols",
"dependsOn": [
"[resourceId('Microsoft.Web/Sites', variables('functionAppName'))]"
],
"properties": {
"RepoUrl": "[parameters('repoURL')]",
"branch": "[variables('branch')]",
"IsManualIntegration": true
}
}
variables('branch') = 'master-dev'
variables('repoUrl') = https://user:token#MYREPO.visualstudio.com/DefaultCollection/PROJECTNAME/_git/REPO
In my repo I have azure functions project, which has this structure:
function-1, function-1/function.json, function-1/run.csx
function-2, function-2/function.json, function-2/run.csx
.gitignore
.appsettings.json
host.json
local.settings.json
read_me.html
README.md
In this case everything works well.
Now I need to create few new projects in the same solution - Core, tests.
The structure now looks like that (let's ignore the tests proj):
Core
Core/Properties/AssemblyInfo.cs
Core/bin/Debug/Core.dll
Core/Core.csproj
OrdersService.cs
function-1, function-1/function.json, function-1/run.csx
function-2, function-2/function.json, function-2/run.csx
.gitignore
.appsettings.json
host.json
local.settings.json
read_me.html
README.md
Once i have Core.dll which has some code I can include the dll in my function-1 (run.csx):
#r ".\..\Core\bin\Debug\Core.dll"
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
var service = Core.OrdersService.GetInstance();
return req.CreateResponse(HttpStatusCode.OK, service.GetOrderHistory());
}
Now when I deploying the azure function into the portal (by current arm template) I can't finish deployment. I have an error that the function "function-1" doesn't exist. When I go to the portal it's the same - the azure function has been created, but inside the function, there are no any methods.
P.S. Changes on local work well - I can call endpoints http://localhost:7071/api/function-1 (in debug and normal mode).
I guess, the problem is with "Core" folder, which does not match an azure function/method and by this way, i can't publish my repo into the azure portal.
My questions:
It's possible to specify in a repoUrl or by Microsoft.sourcecontrols resource, that I want to create Azure functions with some method, but from a specified subfolder? By this way, i'll solve it, just by copying the azure function project into the specific folder and then start to use them in azure function.
It's possible to specify that I want to use some specific files/folders in deployment from my VSO repo into the azure function?
My first suggestion would be that you can move to just using class libraries for everything. .csx is only needed if you want the ability to edit in the portal, but you can use normal .dll's for your functions. Check out this blog post: https://blogs.msdn.microsoft.com/webdev/2017/11/15/improvements-to-azure-functions-in-visual-studio/
Git deploy will copy all files over, so not sure why it's not including everything.
If you could share your exact error logs you see from the deployment, that'd help to debug this specific case, but I think the new VS tooling would have a cleaner experience for you than just using C# script.

Error with Azure Function Service Bus Output Binding

I'm having an issue with an Azure Service Bus output binding that I'm uncertain about how to proceed with. I've had no luck finding a similar question, so I apologize if this is a duplicate.
I'm trying to use the local VS 2017 development process, so the function.json bindings should be generated automatically. The function signature is as follows:
[FunctionName("RequestNewPaladinInvitation")]
public static HttpResponseMessage Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "post")]HttpRequestMessage req,
[ServiceBus("thequeue")] ICollector<Invitation> invitationOutputQueue,
TraceWriter log)
{
//Do some stuff and write to the queue
invitationOutputQueue.Add(invite);
}
I get the following error when running the function locally.
Microsoft.Azure.WebJobs.Host: Error indexing method
'RequestNewPaladinInvitation.Run'. Microsoft.Azure.WebJobs.Host:
Cannot bind parameter 'invitationOutputQueue' to type ICollector`1.
Make sure the parameter Type is supported by the binding. 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.).
[9/1/2017 5:42:49 PM] Error indexing method
'RequestNewPaladinInvitation.Run'
Both my host.json and local.settings.json are defined as follows:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "<MyStorageAccountInfo>",
"AzureWebJobsDashboard": "<MyDashboardInfo>",
"AzureWebJobsServiceBus": "<MyServiceBusConnectionString>"
}
}
I was under the impressing that defining the AzureWebJobsServiceBus value would make that the default ServiceBusAccount for any ServiceBus bindings throughout the function app.
I also tried explicitly pointing the ServiceBus binding to the connection string for the account with the following alternative attribute [ServiceBus("createpaladininvitation",Connection = "ServiceBus")]. My understanding of the convention is that the AzureWebJobs portion of the property should not be included. Just in case I misunderstood, I tried [ServiceBus("createpaladininvitation",Connection = "AzureWebJobsServiceBus")] as well. I even tried to decorate both the method and parameter with the following attribute, [ServiceBusAccount("ServiceBus")]. I also tried the same variations as with the Connection parameter for the ServiceBus attribute.
In all cases, I get the same function.json output, which shows no binding generated for the ServiceBus output binding.
Here's the function.json:
{
"generatedBy": "Microsoft.NET.Sdk.Functions-1.0.0.0",
"configurationSource": "attributes",
"bindings": [
{
"type": "httpTrigger",
"methods": [
"post"
],
"authLevel": "anonymous",
"name": "req"
}
],
"disabled": false,
"scriptFile": "..\\bin\\AzureFunctionsPoc.dll",
"entryPoint": "AzureFunctionsPoc.RequestNewPaladinInvitation.Run"
}
It feels like I'm missing something obvious.
[Update]
As I tried to continue to figure out what's going on, I ran the function locally and edited the generated function.json file and added the binding that I think should have been generated. The resulting manually edited function.json is:
{
"generatedBy": "Microsoft.NET.Sdk.Functions-1.0.0.0",
"configurationSource": "attributes",
"bindings": [
{
"type": "httpTrigger",
"methods": [
"post"
],
"authLevel": "anonymous",
"name": "req"
},
{
"type": "serviceBus",
"name": "invitationOutputQueue",
"queueName": "createpaladininvitation",
"connection": "ServiceBus",
"direction": "out"
}
],
"disabled": false,
"scriptFile": "..\\bin\\AzureFunctionsPoc.dll",
"entryPoint": "AzureFunctionsPoc.RequestNewPaladinInvitation.Run"
}
With those edits, the method works exactly as expected.
This feels even more like either a syntax or convention issue that I'm missing, or a tooling bug.
There is currently an outstanding tooling bug in regards to ServiceBus output triggers. It will work if you 'deploy' your app to Azure Functions, just not locally with the tooling
Please see relevant GitHub issues here: Service Bus output binding issue
and here: Latest v1.0.0 not working with ServiceBus. alpha 6 still works.
This is related to the lazy load. We're not picking up the service bus extension, hence the indexing error. (Azure/azure-webjobs-sdk-script#1637)
The reason for that is that ServiceBus extension is different than the others. We expect extensions to have a public parameterless config object that implements IExtensionConfigProvider.
SB is internal (https://github.com/Azure/azure-webjobs-sdk/blob/663a508e8a851629c26a51e7de3af36629dfd120/src/Microsoft.Azure.WebJobs.ServiceBus/Config/ServiceBusExtensionConfig.cs#L17 ) so our scan for ExportedTypes misses it (see https://github.com/Azure/azure-webjobs-sdk-script/blob/b1445485807bb190ba0716af1a8dc81a864b5228/src/WebJobs.Script/Host/ScriptHost.cs#L735) .
SB's config does not have a parameterless ctor, so the Activator.createInstance call will fail too.
This hotfix (which we made to script runtime) Azure/azure-webjobs-sdk-script#1804 would fix it; but that would need to be pulled to CLI.

What is the purpose of the .json files in Azure Functions?

It seems there are many types, although certain projects only include one or two of them.
Create a new Function in Visual Studio preview, and it gives you a host.json and local.settings.json.
I've also seen projects with function.json and project.json.
The Function docs illustrate what function.json is for:
The function.json file defines the function bindings and other configuration settings. The runtime uses this file to determine the events to monitor and how to pass data into and return data from function execution.
An example:
{
"disabled": false,
"bindings": [
// ... bindings here
{
"type": "bindingType",
"direction": "in",
"name": "myParamName",
// ... more depending on binding
}
]
}
host.json also has a purpose, per the Azure webjobs SDK:
In the root script directory, there should be a host.json metadata file that contains the global configuration options affecting all functions. The Script runtime will map these settings into their corresponding WebHobs SDK JobHostConfiguration settings when initializing the host.
So what does local.settings.json and project.json do?
local.settings.json is to store the application settings for your local development environment, see Local settings file. Production settings will be taken from Azure environment configuration.
project.json is to reference any custom NuGet packages that your function utilizes, see this answer.

Azure-functions: Can environment variables be used in function.json?

I'm currently using the git push deployment option to deploy a few copies of an azure-function. The function's function.json file has multiple "connection" entries linking to different storage accounts (i.e. for a blob trigger & table output). In different copies of the deployed function I'd like to connect to different storage accounts. Is there any special syntax that can be used in function.json to populate the "connection" string from an environment variable?
I guess an alternative would be to edit function.json as part of a custom kudu step, but environment variables seems more consistent with the other azure app service offerings.
This already works, and is actually the recommended way for you to handle connection strings, since you don't want those checked in with your source code. You can use an app setting name for the connection value, and we'll resolve it. In the following EventHub triggered function, the values MyEventHubReceiver, MyEventHubSender and MyEventHubPath will be auto resolved from app settings:
"bindings": [
{
"type": "eventHubTrigger",
"name": "input",
"direction": "in",
"connection": "MyEventHubReceiver",
"path": "%MyEventHubPath%"
},
{
"type": "eventHub",
"name": "output",
"direction": "out",
"connection": "MyEventHubSender",
"path": "%MyEventHubPath%"
}
]
}
In general, most of the binding properties support the %% resolution syntax, allowing you to store the actual values in app settings for both security as well as configurability.

Resources