I have the following C# function code:
[FunctionName("UpdateCohortsByTenantFunction")]
[return: Queue("my-queue", Connection = "MyStorage")]
//note - I have tried both method decoration and parameter decoration
public static async Task Run([TimerTrigger("* * * * * *")]TimerInfo myTimer, IAsyncCollector<AudienceMessage> output)
{
//some logic
foreach (var audience in audiences)
{
await output.AddAsync(new AudienceMessage
{
AudienceId = audience.Id,
TenantId = tenant.Id
});
}
}
Which produces the following function.json:
{
"generatedBy": "Microsoft.NET.Sdk.Functions.Generator-1.0.6",
"configurationSource": "attributes",
"bindings": [
{
"type": "timerTrigger",
"schedule": "* * * * * *",
"useMonitor": true,
"runOnStartup": false,
"name": "myTimer"
}
],
"disabled": false,
"scriptFile": "../bin/MyApp.App.Tasks.Functions.dll",
"entryPoint": "MyApp.App.Tasks.Functions.UpdateCohortsByTenantFunction.Run"
}
According to the documentation here the json output should contain an binding to my queue with an "out" direction. Ie:
{
"type": "queue",
"direction": "out",
"name": "$return",
"queueName": "outqueue",
"connection": "MyStorageConnectionAppSetting",
}
When I try to run the queue via the npm tools (config described here), I get the following error:
Run: Microsoft.Azure.WebJobs.Host: Error indexing method 'UpdateCohortsByTenantFunction.Run'. Microsoft.Azure.WebJobs.Host: Cannot bind parameter 'output' to type IAsyncCollector`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.).
The documentation contains no references to binding via startup code. My understanding is that this is done via the attributes described in the Microsoft documentation linked above, and in my example code, but the error message suggests otherwise.
You should decorate your parameter with attribute, not return value:
public static async Task Run(
[TimerTrigger("* * * * * *")]TimerInfo myTimer,
[Queue("my-queue", Connection = "MyStg")] IAsyncCollector<AudienceMessage> output)
No output binding in function.json is to be expected. Attribute-defined bindings are not transferred to generated function.json. They will still work, don't worry.
Related
I have an Azure Function with a Timer trigger. The schedule is "*/6 * * * *" (running every six minutes). I cannot run it manually and it does not fire automatically. Below is my function.json:
{
"generatedBy": "Microsoft.NET.Sdk.Functions-1.0.31",
"configurationSource": "attributes",
"bindings": [
{
"type": "timerTrigger",
"schedule": "%TimerTriggerPeriod%",
"useMonitor": true,
"runOnStartup": false,
"name": "myTimer"
}
],
"disabled": false,
"scriptFile": "../bin/AccessChangeMonitoring.dll",
"entryPoint": "Microsoft.IT.Security.AccessChangeMonitoring.AccessChangeMonitoring.InitiateChangeMonitoring"
}
%TimerTriggerPeriod% is defined in my local.settings.json file ("TimerTriggerPeriod": "0 */6 * * * *"). Looking at the Application Function Count metric display on the dashboard, it shows that my function has been executed 0 times:
Below is my host.json:
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingExcludedTypes": "Request",
"samplingSettings": {
"isEnabled": true
}
}
},
"functionTimeout": "00:07:00"
}
Below is the function code:
[FunctionName("InitiateChangeMonitoring")]
public static async Task InitiateChangeMonitoring([TimerTrigger("%TimerTriggerPeriod%")] TimerInfo myTimer, ILogger log)
{
log.LogInformation("Change Monitoring started.");
// Reset the listing of app ids we need to retrieve delta role assignments for
oneAuthZAppIds = new List<string>();
await GetOneAuthZAppIdsAsync();
// Create the necessary Cosmos DB infastructure
await CreateDatabaseAsync();
await CreateContainerAsync();
await CreateDeltaAPICallDatabaseAsync();
await CreateDeltaAPICallContainerAsync();
await CreateManagerMappingDatabaseAsync();
await CreateManagerMappingContainerAsync();
// Compute the authentication token needed to access the PAP Service API
log.LogInformation("\nRetrieve PAPServiceAPIToken");
string PAPServiceAPIToken = await GetTokenAsync(Environment.GetEnvironmentVariable("OneAuthZAppUri"), Environment.GetEnvironmentVariable("OneAuthZAppId"),
PAPAuthenticationSecret);
log.LogInformation("PAPServiceAPIToken = " + PAPServiceAPIToken);
string GraphAPIAuthenticationToken = await GetTokenAsync(Environment.GetEnvironmentVariable("GraphAppUri"), Environment.GetEnvironmentVariable("GraphClientId"),
graphKey);
log.LogInformation("graphAPIAuthenticationToken = " + GraphAPIAuthenticationToken);
await runChangeMonitoringSystemAsync(PAPServiceAPIToken);
}
First, I notice you specify you are using local.settings.json to save the environment variable and at the same time you show the metric on azure.
So, I think the first problem why your azure function can not be triggered is because you don't set the environment variable on azure.
You should set in this place instead of local.settings.json (because when a function is deployed to Azure, it will never take environment variable from local.settings.json):
(Don't forget to save the edit.)
Second, as Ivan says, your format of cron is wrong. The format of timetrigger should be in this format:
{second} {minute} {hour} {day} {month} {day of week}
I have an Azure function that does this:
public static int Run(int myvalue, TraceWriter log)
{
log.Info($"C# manually triggered function called with input: {myvalue}");
if (myvalue == 1) return 1;
return (myvalue + 1);
}
I created it directly in the portal; however, my attempt at the bindings are probably wrong:
{
"bindings": [
{
"type": "manualTrigger",
"direction": "in",
"name": "myvalue"
},
{
"type": "int",
"direction": "out",
"name": "$return"
}
],
"disabled": false
}
When I run it inside the portal, it gives me a 202 (accepted), but doesn't output the return value from the function.
My question is, basically, why am I not getting any output; however, I suppose my first question should be (is), should I be getting output; and if so, what's wrong with my binding?
This is a simplified version of a slightly more complex function, that I intend to use as a condition inside a logic app (hence why I need a return value).
int is not a supported type for manual trigger. You should be seeing an error like this in the logs:
[Error] Microsoft.Azure.WebJobs.Host: Error indexing method 'Functions.ManualTriggerCSharp1'. Microsoft.Azure.WebJobs.Script: Can't bind ManualTriggerAttribute to type 'System.Int32'.
If you change the parameter type to string, logging should work:
public static void Run(string myvalue, TraceWriter log)
{
log.Info($"C# manually triggered function called with input: {myvalue}");
}
Now, there is no point in returning anything from manual trigger. You can keep returning an int but it will be ignored. But remove the second binding:
{
"bindings": [
{
"type": "manualTrigger",
"direction": "in",
"name": "myvalue"
}
],
"disabled": false
}
To return a value, you probably need to switch to HTTP trigger, read the data from HTTP request and return HTTP response.
I'm setting up a durable Function that should run infinitely with by invoking itself every hour and keeping a state. The function compiles, bus fails at run with the following error:
2017-07-12T07:04:05.614 Exception while executing function: Functions.DurableTimer.
Microsoft.Azure.WebJobs.Host: Exception binding parameter 'context'.
Microsoft.Azure.WebJobs.Extensions.DurableTask: Cannot convert to DurableOrchestrationContext.
Function code
#r "Microsoft.Azure.WebJobs.Extensions.DurableTask"
using System;
using System.Threading;
public static async Task Run(DurableOrchestrationContext context, TraceWriter log)
{
log.Info($"Durable function executed at: {context.CurrentUtcDateTime}");
// sleep for one hour between calls
DateTime nextExecution = context.CurrentUtcDateTime.AddHours(1);
await context.CreateTimer(nextExecution, CancellationToken.None);
int counterState = context.GetInput<int>();
log.Info($"Counter state: {counterState}");
counterState++;
context.ContinueAsNew(counterState);
}
function.json
{
"bindings": [
{
"name": "context",
"type": "orchestrationTrigger",
"direction": "in"
}
],
"disabled": false
}
My guess is that you are trying to manually trigger the orchestration function in the portal UI, which unfortunately is not supported at this time. I verified by trying to reproduce your exact scenario and clicking the Run button in the portal. I've opened a bug to track this issue: https://github.com/Azure/azure-functions-durable-extension/issues/10
Assuming that's the case, you can workaround it by creating a separate function which knows how to trigger your orchestrator function. Here is the example I posted in the GitHub issue:
Code
#r "Microsoft.Azure.WebJobs.Extensions.DurableTask"
using System;
public static async Task Run(string functionName, DurableOrchestrationClient starter, TraceWriter log)
{
log.Info($"Starting orchestration named: {functionName}");
string instanceId = await starter.StartNewAsync(functionName, null);
log.Info($"Started orchestration with ID = '{instanceId}'.");
}
function.json
{
"bindings": [
{
"type": "manualTrigger",
"direction": "in",
"name": "functionName"
},
{
"name": "starter",
"type": "orchestrationClient",
"direction": "in"
}
],
"disabled": false
}
This is a generic function that can start any orchestrator function by name. In your case, you can put DurableTimer as the input.
Apologies that this is non-obvious and thanks for your patience as we smooth out the experience. :)
I am trying to use Azure function with to invoke the same function with different time and different param(url).
I didn't find any good example that shows how to pass some data. I want to pass link to function.
My code is:
var rp = require('request-promise');
var request = require('request');
module.exports = function (context //need to get the url) {
and the function
{
"bindings": [
{
"name": "myTimer",
"type": "timerTrigger",
"direction": "in",
"schedule": "0 0 */1 * * *"
}
],
"disabled": false
}
If your settings are relatively static (but you still don't want to hard code them), you may use app settings to store them, and then read e.g.
let url = process.env['MyUrl'];
If URL should be determined per request, you may use HTTP trigger and read the URL from query parameters:
let url = req.query.myurl;
I'm not sure what exactly you are trying to achieve with parameterized timer-triggered function.
Another possibility is if your parameters are stored somewhere in e.g. Azure Document DB (Cosmos).
You could still use a TimerTrigger to invoke the function, and include a DocumentDB input binding allowing you to query for the specific parameter values needed to execute the function.
Here's a C# example triggered by Timer, with a DocumentDB input binding. Note: I'm using the latest VS2017 Preview tooling for Azure functions.
[FunctionName("TimerTriggerCSharp")]
public static void Run(
[TimerTrigger("0 */1 * * * *")]TimerInfo myTimer, TraceWriter log,
[DocumentDB("test-db-dev", "TestingCollection", SqlQuery = "select * from c where c.doc = \"Test\"")] IEnumerable<dynamic> incomingDocuments)
{..}
With the following binding json:
{
"bindings": [
{
"name": "myTimer",
"type": "timerTrigger",
"direction": "in",
"schedule": "0 */5 * * * *"
},
{
"type": "documentDB",
"name": "incomingDocuments",
"databaseName": "test-db-dev",
"collectionName": "TestingCollection",
"sqlQuery": "select * from c where c.docType = \"Test\"",
"connection": "my-testing_DOCUMENTDB",
"direction": "in"
}
],
"disabled": false
}
I have an Azure Function that I created in the Azure portal and now want to recreate it using the visual studio azure tooling associated with VS2017 Preview.
My function is Timer triggered, and also has an input binding for Azure DocumentDB (with a query) and an output binding to an Azure Service Bus queue.
Here's the functions.json definition from the portal:
{
"bindings": [
{
"name": "myTimer",
"type": "timerTrigger",
"direction": "in",
"schedule": "0 */5 * * * *"
},
{
"type": "serviceBus",
"name": "outputQueue",
"queueName": "test-output-requests",
"connection": "send-refresh-request",
"accessRights_": "Send",
"direction": "out"
},
{
"type": "documentDB",
"name": "incomingDocuments",
"databaseName": "test-db-dev",
"collectionName": "TestingCollection",
"sqlQuery": "select * from c where c.docType = \"Test\"",
"connection": "my-testing_DOCUMENTDB",
"direction": "in"
}
],
"disabled": false
}
In VS2017, I create an Azure Function project, then a Azure function using the TimerTriggered template:
public static void Run([TimerTrigger("0 */5 * * * *")] TimerInfo myTimer, TraceWriter log, ICollector<dynamic> outputQueue, IEnumerable<dynamic> incomingDocuments)
{
log.Info($"C# Timer trigger function executed at: {DateTime.Now}");
//Inspect incomingDocuments .. push messages to outputQueue
}
Running locally, the timer is triggered as expected - but how do I recreate the input and output bindings in code? I'm not sure what attributes I should use, and what I need in json config files to wire it up.
Add reference to following nuget pacakge
https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.DocumentDB/
Add using Microsoft.Azure.WebJobs
Update the documentDb Parameter as follows (Add other properties as well)
[DocumentDB(ConnectionStringSetting = "")]IEnumerable<dynamic> incomingDocuments
Update the serviceBus Parameter as follows
[ServiceBus("test-output-requests",Connection = "ConnectionValue")]
Verify the generated function.json in the bin/functionName/function.json
Thanks,
Naren