07 Azure Functions
07 Azure Functions
Overview
What is Azure Functions?
Get Started
Create your first function
Create a webhook function
Create an Azure connected function
Create an event processing function
How To
Plan and design
Choose between Flow, Logic Apps, Functions, and WebJobs
Choose between hosting plans
Develop
Develop function apps
Work with triggers and bindings
Create a function from the Azure portal
Testing Azure Functions
Develop and debug locally
Best practices for Azure Functions
Use Azure Functions to perform a scheduled clean-up task
Manage
Configure settings for a function app
Deploy
Continuous deployment for Azure Functions
Deploy Functions using Infrastructure as Code
Monitor
Monitoring Azure Functions
Resources
Pricing
MSDN forum
Stack Overflow
Azure Functions GitHub repository
Service updates
Azure Functions Overview
1/18/2017 4 min to read Edit on GitHub
Azure Functions is a solution for easily running small pieces of code, or "functions," in the cloud. You can write just
the code you need for the problem at hand, without worrying about a whole application or the infrastructure to
run it. Functions can make development even more productive, and you can use your development language of
choice, such as C#, F#, Node.js, Python or PHP. Pay only for the time your code runs and trust Azure to scale as
needed.
This topic provides a high-level overview of Azure Functions. If you want to jump right in and get started with
Azure Functions, start with Create your first Azure Function. If you are looking for more technical information
about Functions, see the developer reference.
Features
Here are some key features of Azure Functions:
Choice of language - Write functions using C#, F#, Node.js, Python, PHP, batch, bash, or any executable.
Pay-per-use pricing model - Pay only for the time spent running your code. See the Consumption hosting
plan option in the pricing section.
Bring your own dependencies - Functions supports NuGet and NPM, so you can use your favorite libraries.
Integrated security - Protect HTTP-triggered functions with OAuth providers such as Azure Active Directory,
Facebook, Google, Twitter, and Microsoft Account.
Simplified integration - Easily leverage Azure services and software-as-a-service (SaaS) offerings. See the
integrations section for some examples.
Flexible development - Code your functions right in the portal or set up continuous integration and deploy
your code through GitHub, Visual Studio Team Services, and other supported development tools.
Open-source - The Functions runtime is open-source and available on GitHub.
Integrations
Azure Functions integrates with various Azure and 3rd-party services. These services can trigger your function and
start execution, or they can serve as input and output for your code. The following service integrations are
supported by Azure Functions.
Azure DocumentDB
Azure Event Hubs
Azure Mobile Apps (tables)
Azure Notification Hubs
Azure Service Bus (queues and topics)
Azure Storage (blob, queues, and tables)
GitHub (webhooks)
On-premises (using Service Bus)
Next Steps
Create your first Azure Function
Jump right in and create your first function using the Azure Functions quickstart.
Azure Functions developer reference
Provides more technical information about the Azure Functions runtime and a reference for coding functions
and defining triggers and bindings.
Testing Azure Functions
Describes various tools and techniques for testing your functions.
How to scale Azure Functions
Discusses service plans available with Azure Functions, including the Consumption hosting plan, and how to
choose the right plan.
Learn more about Azure App Service
Azure Functions leverages the Azure App Service platform for core functionality like deployments, environment
variables, and diagnostics.
Create your first Azure Function
2/9/2017 3 min to read Edit on GitHub
Overview
Azure Functions is an event-driven, compute-on-demand experience that extends the existing Azure application
platform with capabilities to implement code triggered by events occurring in other Azure services, SaaS
products, and on-premises systems. With Azure Functions, your applications scale based on demand and you
pay only for the resources you consume. Azure Functions enables you to create scheduled or triggered units of
code implemented in various programming languages. To learn more about Azure Functions, see the Azure
Functions Overview.
This topic shows you how to use the Azure Functions quickstart in the portal to create a simple "hello world"
JavaScript function that is invoked by an HTTP-trigger. You can also watch a short video to see how these steps
are performed in the portal.
Next steps
This quickstart demonstrates a simple execution of a basic HTTP-triggered function. To learn more about using
Azure Functions in your apps, see the following topics:
Best Practices for Azure Functions
Azure Functions developer reference
Programmer reference for coding functions and defining triggers and bindings.
Testing Azure Functions
Describes various tools and techniques for testing your functions.
How to scale Azure Functions
Discusses service plans available with Azure Functions, including the Consumption hosting plan, and how to
choose the right plan.
What is Azure App Service?
Azure Functions uses the Azure App Service platform for core functionality like deployments, environment
variables, and diagnostics.
Need some help?
Post questions in the Azure forums. - Visit MSDN
Tag questions with the keyword azure-functions . - Visit Stack Overflow
Create a webhook or API Azure Function
2/6/2017 3 min to read Edit on GitHub
Azure Functions is an event-driven, compute-on-demand experience that enables you to create scheduled or
triggered units of code implemented various programming languages. To learn more about Azure Functions, see
the Azure Functions Overview.
This topic shows you how to create a JavaScript function that is invoked by a GitHub webhook. The new function is
created based on a pre-defined template in the Azure Functions portal. You can also watch a short video to see how
these steps are performed in the portal.
The general steps in this tutorial can also be used to create a function in C# or F# instead of JavaScript.
Prerequisites
To complete this tutorial, you will need the following:
An active Azure account. If you don't already have an account, you can sign up for a free Azure acccount.
You can also use the Try Functions experience to complete this tutorial without an Azure account.
A GitHub account. You can sign up for a free GitHub account, if you don't already have one.
5. Copy and save the Function URL and GitHub Secret values. You will use these values in the next section to
configure the webhook in GitHub.
6. Click Test, note the predefined JSON body of an issue comment in the Request body, then click Run.
NOTE
You can always test a new template-based function right in the Develop tab by supplying any expected body JSON
data and clicking the Run button. In this case, the template has a predefined body for an issue comment.
Next, you will create the actual webhook in your GitHub repository.
3. Paste your function's URL and secret into Payload URL and Secret and select application/json for
Content type.
4. Click Let me select individual events, select Issue comment, and click Add webhook.
At this point, the GitHub webhook is configured to trigger your function when a new issue comment is added.
Now, it's time to test it out.
5. Back in the Functions portal, scroll down to the logs and see that the function has been triggered and the
value New GitHub comment: <Your issue comment text> is written to the streaming logs.
Next steps
See these topics for more information about Azure Functions.
Azure Functions developer reference
Programmer reference for coding functions.
Testing Azure Functions
Describes various tools and techniques for testing your functions.
How to scale Azure Functions
Discusses service plans available with Azure Functions, including the Consumption hosting plan, and how to
choose the right plan.
Need some help?
Post questions in the Azure forums. - Visit MSDN
Tag questions with the keyword azure-functions . - Visit Stack Overflow
Use Azure Functions to create a function that
connects to other Azure services
2/6/2017 5 min to read Edit on GitHub
This topic shows you how to create a function in Azure Functions that listens to messages on an Azure Storage
queue and copies the messages to rows in an Azure Storage table. A timer triggered function is used to load
messages into the queue. A second function reads from the queue and writes messages to the table. Both the
queue and the table are created for you by Azure Functions based on the binding definitions.
To make things more interesting, one function is written in JavaScript and the other is written in C# script. This
demonstrates how a function app can have functions in various languages.
You can see this scenario demonstrated in a video on Channel 9.
2. Enter myQueueItem for Message parameter name and functions-bindings for Queue name, select an
existing Storage account connection or click new to create a storage account connection, and then click
Save.
3. Back in the Develop tab, append the following code to the function:
function myQueueItem()
{
return {
msg: "some message goes here",
time: "time goes here"
}
}
4. Locate the if statement around line 9 of the function, and insert the following code after that statement.
This code creates a myQueueItem and sets its time property to the current timeStamp. It then adds the
new queue item to the context's myQueueItem binding.
5. Click Save and Run.
If the queue does not exist or is empty, there is most likely a problem with your function binding or code.
Create a function that reads from the queue
Now that you have messages being added to the queue, you can create another function that reads from the queue
and writes the messages permanently to an Azure Storage table.
1. Click New Function > QueueTrigger-CSharp.
2. Name the function FunctionsBindingsDemo2 , enter functions-bindings in the Queue name field, select an
existing storage account or create one, and then click Create.
3. (Optional) You can verify that the new function works by viewing the new queue in Storage Explorer as
before. You can also use Cloud Explorer in Visual Studio.
4. (Optional) Refresh the functions-bindings queue and notice that items have been removed from the
queue. The removal occurs because the function is bound to the functions-bindings queue as an input
trigger and the function reads the queue.
The TableItem class represents a row in the storage table, and you add the item to the myTable collection
of TableItem objects. You must set the PartitionKey and RowKey properties to be able to insert into the
table.
4. Click Save. Finally, you can verify the function works by viewing the table in Storage explorer or Visual
Studio Cloud Explorer.
5. (Optional) In your storage account in Storage Explorer, expand Tables > functionsbindings and verify that
rows are added to the table. You can do the same in Cloud Explorer in Visual Studio.
If the table does not exist or is empty, there is most likely a problem with your function binding or code.
For information about other bindings and triggers for Azure Functions, see Azure Functions triggers and bindings
developer reference
Next steps
See these topics for more information about Azure Functions.
Azure Functions developer reference
Programmer reference for coding functions and defining triggers and bindings.
Testing Azure Functions
Describes various tools and techniques for testing your functions.
How to scale Azure Functions
Discusses service plans available with Azure Functions, including the Consumption hosting plan, and how to
choose the right plan.
Need some help?
Post questions in the Azure forums. - Visit MSDN
Tag questions with the keyword azure-functions . - Visit Stack Overflow
Create an event processing Azure Function
1/17/2017 2 min to read Edit on GitHub
Azure Functions is an event-driven, compute-on-demand experience that enables you to create scheduled or
triggered units of code implemented in a variety of programming languages. To learn more about Azure Functions,
see the Azure Functions Overview.
This topic shows you how to create a new function in C# that executes based on an event timer to add messages to
a storage queue.
Prerequisites
A function app hosts the execution of your functions in Azure. If you don't already have an Azure account, check out
the Try Functions experience or create a free Azure acccount.
5. In Azure Storage Queue output, select an existing Storage account connection, or create a new one,
then click Save.
6. Back in the Develop tab, replace the existing C# script in the Code window with the following code:
using System;
public static void Run(TimerInfo myTimer, out string outputQueueItem, TraceWriter log)
{
// Add a new scheduled message to the queue.
outputQueueItem = $"Ping message added to the queue at: {DateTime.Now}.";
This code adds a new message to the queue with the current date and time when the function is executed.
7. Click Save and watch the Logs windows for the next function execution.
8. (Optional) Navigate to the storage account and verify that messages are being added to the queue.
9. Go back to the Integrate tab and change the schedule field to 0 0 * * * * . The function now runs once every
hour.
This is a very simplified example of both a timer trigger and a storage queue output binding. For more information,
see both the Azure Functions timer trigger and the Azure Functions triggers and bindings for Azure Storage topics.
Next steps
See these topics for more information about Azure Functions.
Azure Functions developer reference
Programmer reference for coding functions and defining triggers and bindings.
Testing Azure Functions
Describes various tools and techniques for testing your functions.
How to scale Azure Functions
Discusses service plans available with Azure Functions, including the Consumption hosting plan, and how to
choose the right plan.
Need some help?
Post questions in the Azure forums. - Visit MSDN
Tag questions with the keyword azure-functions . - Visit Stack Overflow
Choose between Flow, Logic Apps, Functions, and
WebJobs
1/20/2017 4 min to read Edit on GitHub
This article compares and contrasts the following services in the Microsoft cloud, which can all solve integration
problems and automation of business processes:
Microsoft Flow
Azure Logic Apps
Azure Functions
Azure App Service WebJobs
All these services are useful when "gluing" together disparate systems. They can all define input, actions, conditions,
and output. You can run each of them on a schedule or trigger. However, each service adds a unique set of value,
and comparing them is not a question of "Which service is the best?" but one of "Which service is best suited for
this situation?" Often, a combination of these services is the best way to rapidly build a scalable, full featured
integration solution.
FUNCTIONS WEBJOBS
Pricing Pay-per-use or part of App Service plan Part of App Service plan
Trigger events timer, Azure DocumentDB, Azure Event Azure Storage, Azure Service Bus
Hubs, HTTP/WebHook (GitHub, Slack),
Azure App Service Mobile Apps, Azure
Notification Hubs, Azure Service Bus,
Azure Storage
In-browser development x
PowerShell experimental x
C# x x
F# x
FUNCTIONS WEBJOBS
Bash experimental x
PHP experimental x
Python experimental x
JavaScript x x
Whether to use Functions or WebJobs ultimately depends on what you're already doing with App Service. If you
have an App Service app for which you want to run code snippets, and you want to manage them together in the
same DevOps environment, you should use WebJobs. If you want to run code snippets for other Azure services or
even 3rd-party apps, or if you want to manage your integration code snippets separately from your App Service
apps, or if you want to call your code snippets from a Logic app, you should take advantage of all the
improvements in Functions.
Next Steps
Get started with each of the services by creating your first flow, logic app, function app, or WebJob. Click any of the
following links:
Get started with Microsoft Flow
Create a logic app
Create your first Azure Function
Deploy WebJobs using Visual Studio
Or, get more information on these integration services with the following links:
Leveraging Azure Functions & Azure App Service for integration scenarios by Christopher Anderson
Integrations Made Simple by Charles Lamanna
Logic Apps Live Webcast
Microsoft Flow Frequently asked questions
Azure WebJobs documentation resources
Scaling Azure Functions
1/17/2017 3 min to read Edit on GitHub
Introduction
The Azure Functions platform allocates compute power when your code is running, scales out as necessary to
handle load, and then scales in when code is not running. This means you dont pay for idle VMs or have to
reserve capacity before it is needed. The mechanism for this capability is the Consumption service plan. This
article provides an overview of how the Consumption service plan works.
If you are not yet familiar with Azure Functions, see the Azure Functions overview article.
In Azure Functions, specific functions share a few core technical concepts and components, regardless of the
language or binding you use. Before you jump into learning details specific to a given language or binding, be
sure to read through this overview that applies to all of them.
This article assumes that you've already read the Azure Functions overview and are familiar with WebJobs SDK
concepts such as triggers, bindings, and the JobHost runtime. Azure Functions is based on the WebJobs SDK.
Function code
A function is the primary concept in Azure Functions. You write code for a function in a language of your
choice and save the code and configuration files in the same folder. The configuration is named function.json ,
which contains JSON configuration data. Various languages are supported, and each one has a slightly
different experience optimized to work best for that language.
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. The
following is an example function.json file.
{
"disabled":false,
"bindings":[
// ... bindings here
{
"type": "bindingType",
"direction": "in",
"name": "myParamName",
// ... more depending on binding
}
]
}
Set the disabled property to true to prevent the function from being executed.
The bindings property is where you configure both triggers and bindings. Each binding shares a few common
settings and some settings, which are specific to a particular type of binding. Every binding requires the
following settings:
Folder Structure
The code for all of the functions in a given function app lives in a root folder that contains a host configuration
file and one or more subfolders, each of which contain the code for a separate function, as in the following
example:
wwwroot
| - host.json
| - mynodefunction
| | - function.json
| | - index.js
| | - node_modules
| | | - ... packages ...
| | - package.json
| - mycsharpfunction
| | - function.json
| | - run.csx
The host.json file contains some runtime-specific configuration and sits in the root folder of the function app.
For information on settings that are available, see host.json in the WebJobs.Script repository wiki.
Each function has a folder that contains one or more code files, the function.json configuration and other
dependencies.
When setting-up a project for deploying functions to a function app in Azure App Service, you can treat this
folder structure as your site code. You can use existing tools like continuous integration and deployment, or
custom deployment scripts for doing deploy time package installation or code transpilation.
NOTE
Make sure to deploy your host.json file and function folders directly to the wwwroot folder. Do not include the
wwwroot folder in your deployments. Otherwise, you end up with wwwroot\wwwroot folders.
Parallel execution
When multiple triggering events occur faster than a single-threaded function runtime can process them, the
runtime may invoke the function multiple times in parallel. If a function app is using the Consumption hosting
plan, the function app could scale out automatically. Each instance of the function app, whether the app runs on
the Consumption hosting plan or a regular App Service hosting plan, might process concurrent function
invocations in parallel using multiple threads. The maximum number of concurrent function invocations in
each function app instance varies based on the type of trigger being used as well as the resources used by
other functions within the function app.
Repositories
The code for Azure Functions is open source and stored in GitHub repositories:
Azure Functions runtime
Azure Functions portal
Azure Functions templates
Azure WebJobs SDK
Azure WebJobs SDK Extensions
Bindings
Here is a table of all supported bindings.
Reporting Issues
ITEM DESCRIPTION LINK
Next steps
For more information, see the following resources:
Best Practices for Azure Functions
Azure Functions C# developer reference
Azure Functions F# developer reference
Azure Functions NodeJS developer reference
Azure Functions triggers and bindings
Azure Functions: The Journey on the Azure App Service team blog. A history of how Azure Functions was
developed.
Azure Functions C# developer reference
1/17/2017 6 min to read Edit on GitHub
The C# experience for Azure Functions is based on the Azure WebJobs SDK. Data flows into your C# function via
method arguments. Argument names are specified in function.json , and there are predefined names for
accessing things like the function logger and cancellation tokens.
This article assumes that you've already read the Azure Functions developer reference.
Binding to arguments
The various bindings are bound to a C# function via the name property in the function.json configuration. Each
binding has its own supported types which is documented per binding; for instance, a blob trigger can support a
string, a POCO, or several other types. You can use the type which best suits your need. A POCO object must
have a getter and setter defined for each property.
Logging
To log output to your streaming logs in C#, you can include a TraceWriter typed argument. We recommend that
you name it log . We recommend you avoid Console.Write in Azure Functions.
Async
To make a function asynchronous, use the async keyword and return a Task object.
public async static Task ProcessQueueMessageAsync(
string blobName,
Stream blobInput,
Stream blobOutput)
{
await blobInput.CopyToAsync(blobOutput, 4096, token);
}
Cancellation Token
In certain cases, you may have operations which are sensitive to being shut down. While it's always best to write
code which can handle crashing, in cases where you want to handle graceful shutdown requests, you define a
CancellationToken typed argument. A CancellationToken will be provided if a host shutdown is triggered.
Importing namespaces
If you need to import namespaces, you can do so as usual, with the using clause.
using System.Net;
using System.Threading.Tasks;
The following namespaces are automatically imported and are therefore optional:
System
System.Collections.Generic
System.IO
System.Linq
System.Net.Http
System.Threading.Tasks
Microsoft.Azure.WebJobs
Microsoft.Azure.WebJobs.Host .
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
The following assemblies are automatically added by the Azure Functions hosting environment:
mscorlib ,
System
System.Core
System.Xml
System.Net.Http
Microsoft.Azure.WebJobs
Microsoft.Azure.WebJobs.Host
Microsoft.Azure.WebJobs.Extensions
System.Web.Http
System.Net.Http.Formatting .
In addition, the following assemblies are special cased and may be referenced by simplename (e.g.
#r "AssemblyName" ):
Newtonsoft.Json
Microsoft.WindowsAzure.Storage
Microsoft.ServiceBus
Microsoft.AspNet.WebHooks.Receivers
Microsoft.AspNet.WebHooks.Common
Microsoft.Azure.NotificationHubs
If you need to reference a private assembly, you can upload the assembly file into a bin folder relative to your
function and reference it by using the file name (e.g. #r "MyAssembly.dll" ). For information on how to upload
files to your function folder, see the following section on package management.
Package management
To use NuGet packages in a C# function, upload a project.json file to the the function's folder in the function
app's file system. Here is an example project.json file that adds a reference to Microsoft.ProjectOxford.Face
version 1.1.0:
{
"frameworks": {
"net46":{
"dependencies": {
"Microsoft.ProjectOxford.Face": "1.1.0"
}
}
}
}
Only the .NET Framework 4.6 is supported, so make sure that your project.json file specifies net46 as shown
here.
When you upload a project.json file, the runtime gets the packages and automatically adds references to the
package assemblies. You don't need to add #r "AssemblyName" directives. Just add the required using
statements to your run.csx file to use the types defined in the NuGet packages.
How to upload a project.json file
1. Begin by making sure your function app is running, which you can do by opening your function in the
Azure portal.
This also gives access to the streaming logs where package installation output will be displayed.
2. To upload a project.json file, use one of the methods described in the How to update function app files
section of the Azure Functions developer reference topic.
3. After the project.json file is uploaded, you see output like the following example in your function's streaming
log:
Environment variables
To get an environment variable or an app setting value, use System.Environment.GetEnvironmentVariable , as
shown in the following code example:
Example mylogger.csx:
Using a shared .csx is a common pattern when you want to strongly type your arguments between functions
using a POCO object. In the following simplified example, a HTTP trigger and queue trigger share a POCO object
named Order to strongly type the order data:
Example run.csx for HTTP trigger:
#load "..\shared\order.csx"
using System.Net;
if (req.orderId == null)
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
else
{
await outputQueueItem.AddAsync(req);
return new HttpResponseMessage(HttpStatusCode.OK);
}
}
#load "..\shared\order.csx"
using System;
outputQueueItem = myQueueItem;
}
Example order.csx:
public class Order
{
public string orderId {get; set; }
public string custName {get; set;}
public string custAddress {get; set;}
public string custEmail {get; set;}
public string cartId {get; set; }
Next steps
For more information, see the following resources:
Best Practices for Azure Functions
Azure Functions developer reference
Azure Functions F# developer reference
Azure Functions NodeJS developer reference
Azure Functions triggers and bindings
Azure Functions F# Developer Reference
1/17/2017 6 min to read Edit on GitHub
F# for Azure Functions is a solution for easily running small pieces of code, or "functions," in the cloud. Data
flows into your F# function via function arguments. Argument names are specified in function.json , and there
are predefined names for accessing things like the function logger and cancellation tokens.
This article assumes that you've already read the Azure Functions developer reference.
Binding to arguments
Each binding supports some set of arguments, as detailed in the Azure Functions triggers and bindings
developer reference. For example, one of the argument bindings a blob trigger supports is a POCO, which can be
expressed using an F# record. For example:
Your F# Azure Function will take one or more arguments. When we talk about Azure Functions arguments, we
refer to input arguments and output arguments. An input argument is exactly what it sounds like: input to your
F# Azure Function. An output argument is mutable data or a byref<> argument that serves as a way to pass data
back out of your function.
In the example above, blob is an input argument, and output is an output argument. Notice that we used
byref<> for output (there's no need to add the [<Out>] annotation). Using a byref<> type allows your
function to change which record or object the argument refers to.
When an F# record is used as an input type, the record definition must be marked with [<CLIMutable>] in order
to allow the Azure Functions framework to set the fields appropriately before passing the record to your
function. Under the hood, [<CLIMutable>] generates setters for the record properties. For example:
[<CLIMutable>]
type TestObject =
{ SenderName : string
Greeting : string }
An F# class can also be used for both in and out arguments. For a class, properties will usually need getters and
setters. For example:
type Item() =
member val Id = "" with get,set
member val Text = "" with get,set
Logging
To log output to your streaming logs in F#, your function should take an argument of type TraceWriter . For
consistency, we recommend this argument is named log . For example:
Async
The workflow can be used, but the result needs to return a
async Task . This can be done with
Async.StartAsTask , for example:
Cancellation Token
If your function needs to handle shutdown gracefully, you can give it a CancellationToken argument. This can be
combined with async , for example:
Importing namespaces
Namespaces can be opened in the usual way:
open System.Net
open System.Threading.Tasks
#r "System.Web.Http"
open System.Net
open System.Net.Http
open System.Threading.Tasks
The following assemblies are automatically added by the Azure Functions hosting environment:
mscorlib ,
System
System.Core
System.Xml
System.Net.Http
Microsoft.Azure.WebJobs
Microsoft.Azure.WebJobs.Host
Microsoft.Azure.WebJobs.Extensions
System.Web.Http
System.Net.Http.Formatting .
In addition, the following assemblies are special cased and may be referenced by simplename (e.g.
#r "AssemblyName" ):
Newtonsoft.Json
Microsoft.WindowsAzure.Storage
Microsoft.ServiceBus
Microsoft.AspNet.WebHooks.Receivers
Microsoft.AspNEt.WebHooks.Common .
If you need to reference a private assembly, you can upload the assembly file into a bin folder relative to your
function and reference it by using the file name (e.g. #r "MyAssembly.dll" ). For information on how to upload
files to your function folder, see the following section on package management.
Editor Prelude
An editor that supports F# Compiler Services will not be aware of the namespaces and assemblies that Azure
Functions automatically includes. As such, it can be useful to include a prelude that helps the editor find the
assemblies you are using, and to explicitly open namespaces. For example:
#if !COMPILED
#I "../../bin/Binaries/WebJobs.Script.Host"
#r "Microsoft.Azure.WebJobs.Host.dll"
#endif
open Sytem
open Microsoft.Azure.WebJobs.Host
When Azure Functions executes your code, it processes the source with COMPILED defined, so the editor prelude
will be ignored.
Package management
To use NuGet packages in an F# function, add a project.json file to the the function's folder in the function
app's file system. Here is an example project.json file that adds a NuGet package reference to
Microsoft.ProjectOxford.Face version 1.1.0:
{
"frameworks": {
"net46":{
"dependencies": {
"Microsoft.ProjectOxford.Face": "1.1.0"
}
}
}
}
Only the .NET Framework 4.6 is supported, so make sure that your project.json file specifies net46 as shown
here.
When you upload a project.json file, the runtime gets the packages and automatically adds references to the
package assemblies. You don't need to add #r "AssemblyName" directives. Just add the required open statements
to your .fsx file.
You may wish to put automatically references assemblies in your editor prelude, to improve your editor's
interaction with F# Compile Services.
How to add a project.json file to your Azure Function
1. Begin by making sure your function app is running, which you can do by opening your function in the Azure
portal. This also gives access to the streaming logs where package installation output will be displayed.
2. To upload a project.json file, use one of the methods described in how to update function app files. If you
are using Continuous Deployment for Azure Functions, you can add a project.json file to your staging
branch in order to experiment with it before adding it to your deployment branch.
3. After the project.json file is added, you will see output similar to the following example in your function's
streaming log:
2016-04-04T19:02:48.745 Restoring packages.
2016-04-04T19:02:48.745 Starting NuGet restore
2016-04-04T19:02:50.183 MSBuild auto-detection: using msbuild version '14.0' from 'D:\Program Files
(x86)\MSBuild\14.0\bin'.
2016-04-04T19:02:50.261 Feeds used:
2016-04-04T19:02:50.261 C:\DWASFiles\Sites\facavalfunctest\LocalAppData\NuGet\Cache
2016-04-04T19:02:50.261 https://api.nuget.org/v3/index.json
2016-04-04T19:02:50.261
2016-04-04T19:02:50.511 Restoring packages for D:\home\site\wwwroot\HttpTriggerCSharp1\Project.json...
2016-04-04T19:02:52.800 Installing Newtonsoft.Json 6.0.8.
2016-04-04T19:02:52.800 Installing Microsoft.ProjectOxford.Face 1.1.0.
2016-04-04T19:02:57.095 All packages are compatible with .NETFramework,Version=v4.6.
2016-04-04T19:02:57.189
2016-04-04T19:02:57.189
2016-04-04T19:02:57.455 Packages restored.
Environment variables
To get an environment variable or an app setting value, use System.Environment.GetEnvironmentVariable , for
example:
open System.Environment
#load "logger.fsx"
logger.fsx
Paths provides to the #load directive are relative to the location of your .fsx file.
#load "logger.fsx" loads a file located in the function folder.
#load "package\logger.fsx" loads a file located in the package folder in the function folder.
#load "..\shared\mylogger.fsx" loads a file located in the shared folder at the same level as the function
folder, that is, directly under wwwroot .
The #load directive only works with .fsx (F# script) files, and not with .fs files.
Next steps
For more information, see the following resources:
F# Guide
Best Practices for Azure Functions
Azure Functions developer reference
Azure Functions C# developer reference
Azure Functions NodeJS developer reference
Azure Functions triggers and bindings
Azure Functions testing
Azure Functions scaling
Azure Functions JavaScript developer guide
2/6/2017 5 min to read Edit on GitHub
The JavaScript experience for Azure Functions makes it easy to export a function which is passed a context
object for communicating with the runtime, and for receiving and sending data via bindings.
This article assumes that you've already read the Azure Functions developer reference.
Exporting a function
All JavaScript functions must export a single function via module.exports for the runtime to find the function
and run it. This function must always include a context object.
Bindings of direction === "in" are passed along as function arguments, meaning you can use arguments to
dynamically handle new inputs (for example, by using arguments.length to iterate over all your inputs). This
functionality is very convenient if you only have a trigger with no additional inputs, as you can predictably access
your trigger data without referencing your context object.
The arguments are always passed along to the function in the order they occur in function.json, even if you don't
specify them in your exports statement. For example, if you have function(context, a, b) and change it to
function(context, a) , you can still get the value of b in function code by referring to arguments[3] .
All bindings, regardless of direction, are also passed along on the context object (see below).
context object
The runtime uses a context object to pass data to and from your function and to let you communicate with the
runtime.
The context object is always the first parameter to a function and should always be included because it has
methods such as context.done and context.log which are required to correctly use the runtime. You can name
the object whatever you like (i.e. ctx or c ).
context.bindings
The context.bindings object collects all your input and output data. The data is added onto the
context.bindings object via the name property of the binding. For instance, given the following binding
definition in function.json, you can access the contents of the queue via context.bindings.myInput .
{
"type":"queue",
"direction":"in",
"name":"myInput"
...
}
// myInput contains the input data which may have properties such as "name"
var author = context.bindings.myInput.name;
// Similarly, you can set your output data
context.bindings.myOutput = {
some_text: 'hello world',
a_number: 1 };
context.done([err],[propertyBag])
The context.done function tells the runtime that you're done running. This is important to call when you're done
with the function; if you don't, the runtime will still never know that your function completed.
The context.done function allows you to pass back a user-defined error to the runtime, as well as a property bag
of properties which will overwrite the properties on the context.bindings object.
context.log(message)
The context.log method allows you to output log statements that are correlated together for logging purposes.
If you use console.log , your messages will only show for process level logging, which isn't as useful.
The context.log method supports the same parameter format that the Node util.format method supports. So,
for example, code like this:
// You can access your http request off of the context ...
if(context.req.body.emoji === ':pizza:') context.log('Yay!');
// and also set your http response
context.res = { status: 202, body: 'You successfully ordered more coffee!' };
module.exports = function(context) {
// Using our imported underscore.js library
var matched_names = _
.where(context.bindings.myInput.names, {first: 'Carla'});
Environment variables
To get an environment variable or an app setting value, use process.env , as shown in the following code
example:
module.exports = function (context, myTimer) {
var timeStamp = new Date().toISOString();
context.done();
};
function GetEnvironmentVariable(name)
{
return name + ": " + process.env[name];
}
TypeScript/CoffeeScript support
There isn't, yet, any direct support for auto-compiling TypeScript/CoffeeScript via the runtime, so that would all
need to be handled outside the runtime, at deployment time.
Next steps
For more information, see the following resources:
Best Practices for Azure Functions
Azure Functions developer reference
Azure Functions C# developer reference
Azure Functions F# developer reference
Azure Functions triggers and bindings
Learn how to work with triggers and bindings in Azure
Functions
1/30/2017 9 min to read Edit on GitHub
This topic shows you how to use triggers and bindings in Azure Functions to connect your code to a variety of triggers and
Azure services and other cloud-based services. It features some of the advanced binding features and syntax supported by
all binding types.
For detailed information about working with a specific type of trigger or binding, see one of the following reference topics:
These articles assume that you've read the Azure Functions developer reference, and the C#, F#, or Node.js developer
reference articles.
Overview
Triggers are event responses used to trigger your custom code. They allow you to respond to events across the Azure
platform or on premise. Bindings represent the necessary meta data used to connect your code to the desired trigger or
associated input or output data. The function.json file for each function contains all related bindings. There is no limit to the
number of input and output bindings a function can have. However, only a single trigger binding is supported for each
function.
To get a better idea of the different bindings you can integrate with your Azure Function app, refer to the following table.
{
"bindings": [
{
"name": "myNewUserQueueItem",
"type": "queueTrigger",
"direction": "in",
"queueName": "queue-newusers",
"connection": "MY_STORAGE_ACCT_APP_SETTING"
}
],
"disabled": false
}
Your code may send different types of output depending on how the new queue item is processed. For example, you might
want to write a new record to an Azure Storage table. To do this, you create an output binding to an Azure Storage table.
Here is an example function.json that includes a storage table output binding that could be used with a queue trigger.
{
"bindings": [
{
"name": "myNewUserQueueItem",
"type": "queueTrigger",
"direction": "in",
"queueName": "queue-newusers",
"connection": "MY_STORAGE_ACCT_APP_SETTING"
},
{
"type": "table",
"name": "myNewUserTableBinding",
"tableName": "newUserTable",
"connection": "MY_TABLE_STORAGE_ACCT_APP_SETTING",
"direction": "out"
}
],
"disabled": false
}
The following C# function responds to a new item being dropped into the queue and writes a new user entry into an Azure
Storage table.
#r "Newtonsoft.Json"
using System;
using Newtonsoft.Json;
await myNewUserTableBinding.AddAsync(
new Person() {
PartitionKey = "Test",
RowKey = Guid.NewGuid().ToString(),
Name = order.name,
Address = order.address,
MobileNumber = order.mobileNumber }
);
}
For more code examples and more specific information regarding Azure storage types that are supported, see Azure
Functions triggers and bindings for Azure Storage.
To use the more advanced binding features in the Azure portal, click the Advanced editor option on the Integrate tab of
your function. The advanced editor allows you to edit the function.json directly in the portal.
Random GUIDs
Azure Functions provides a syntax to generate random GUIDs with your bindings. The following binding syntax writes
output to a new BLOB with a unique name in a Storage container:
{
"type": "blob",
"name": "blobOutput",
"direction": "out",
"path": "my-output-container/{rand-guid}"
}
The following C# code returns the output more naturally without using an out parameter in the function signature.
Async example:
This can also be used with multiple output parameters by designating a single output with $return .
Parameter binding
Instead of a static configuration setting for your output binding properties, you can configure the settings to be dynamically
bound to data that is part of your trigger's input binding. Consider a scenario where new orders are processed using an
Azure Storage queue. Each new queue item is a JSON string containing at least the following properties:
{
"name" : "Customer Name",
"address" : "Customer's Address",
"mobileNumber" : "Customer's mobile number in the format - +1XXXYYYZZZZ."
}
You might want to send the customer an SMS text message using your Twilio account as an update that the order was
received. You can configure the body and to field of your Twilio output binding to be dynamically bound to the name and
mobileNumber that were part of the input as follows.
{
"name": "myNewOrderItem",
"type": "queueTrigger",
"direction": "in",
"queueName": "queue-newOrders",
"connection": "orders_STORAGE"
},
{
"type": "twilioSms",
"name": "$return",
"accountSid": "TwilioAccountSid",
"authToken": "TwilioAuthToken",
"to": "{mobileNumber}",
"from": "%TWILIO_ACCT_PHONE%",
"body": "Thank you {name}, your order was received",
"direction": "out"
},
Now your function code only has to initialize the output parameter as follows. During execution, the output properties are
bound to the desired input data.
#r "Newtonsoft.Json"
#r "Twilio.Api"
using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Twilio;
// Even if you want to use a hard coded message and number in the binding, you must at least
// initialize the SMSMessage variable.
SMSMessage smsText = new SMSMessage();
// The following isn't needed since we use parameter binding for this
//string msg = "Hello " + order.name + ", thank you for your order.";
//smsText.Body = msg;
//smsText.To = order.mobileNumber;
return smsText;
}
Node.js:
// No need to set the properties of the text, we use parameters in the binding. We do need to
// initialize the object.
var smsText = {};
context.done(null, smsText);
}
where BindingTypeAttribute is the .NET attribute that defines your binding and T is the input or output type that's
supported by that binding type. T also cannot be an out parameter type (such as out JObject ). For example, the Mobile
Apps table output binding supports six output types, but you can only use ICollector or IAsyncCollector for T .
The following example code creates a Storage blob output binding with blob path that's defined at run time, then writes a
string to the blob.
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host.Bindings.Runtime;
BlobAttribute defines the Storage blob input or output binding, and TextWriter is a supported output binding type. As is, the
code gets the default app setting for the Storage account connection string (which is AzureWebJobsStorage ). You can specify a
custom app setting to use by adding the StorageAccountAttribute and passing the attribute array into BindAsync<T>() . For
example,
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host.Bindings.Runtime;
The following table shows you the corresponding .NET attribute to use for each binding type and which package to
reference.
DocumentDB Microsoft.Azure.WebJobs.DocumentDBAttribute# r
"Microsoft.Azure.WebJobs.Extensions.DocumentDB"
Twilio Microsoft.Azure.WebJobs.TwilioSmsAttribute #r
"Microsoft.Azure.WebJobs.Extensions.Twilio"
Next steps
For more information, see the following resources:
Testing a function
Scale a function
Azure Functions DocumentDB bindings
1/17/2017 6 min to read Edit on GitHub
This article explains how to configure and code Azure DocumentDB bindings in Azure Functions. Azure Functions
supports input and output bindings for DocumentDB.
This is reference information for Azure Functions developers. If you're new to Azure Functions, start with the
following resources:
Create your first Azure Function
Azure Functions developer reference
C#, F#, or Node developer reference
For more information on DocumentDB, see Introduction to DocumentDB and Build a DocumentDB console
application.
{
"name": "<Name of input parameter in function signature>",
"type": "documentDB",
"databaseName": "<Name of the DocumentDB database>",
"collectionName": "<Name of the DocumentDB collection>",
"id": "<Id of the DocumentDB document - see below>",
"connection": "<Name of app setting with connection string - see below>",
"direction": "in"
},
Input usage
This section shows you how to use your DocumentDB input binding in your function code.
In C# and F# functions, any changes made to the input document (named input parameter) is automatically sent
back to the collection when the function exits successfully. In Node.js functions, updates to the document in the
input binding are not sent back to the collection. However, you can use context.bindings.<documentName>In and
context.bindings.<documentName>Out to make updates to input documents. See how it is done in the Node.js
sample.
Input sample
Suppose you have the following DocumentDB input binding in the bindings array of function.json:
{
"name": "inputDocument",
"type": "documentDB",
"databaseName": "MyDatabase",
"collectionName": "MyCollection",
"id" : "{queueTrigger}",
"connection": "MyAccount_DOCUMENTDB",
"direction": "in"
}
See the language-specific sample that uses this input binding to update the document's text value.
C#
F#
Node.js
Input sample in C#
Input sample in F#
open FSharp.Interop.Dynamic
let Run(myQueueItem: string, inputDocument: obj) =
inputDocument?text <- "This has changed."
You need to add a project.json file that specifies the FSharp.Interop.Dynamic and Dynamitey NuGet
dependencies:
{
"frameworks": {
"net46": {
"dependencies": {
"Dynamitey": "1.0.2",
"FSharp.Interop.Dynamic": "3.0.0"
}
}
}
}
{
"name": "<Name of output parameter in function signature>",
"type": "documentDB",
"databaseName": "<Name of the DocumentDB database>",
"collectionName": "<Name of the DocumentDB collection>",
"createIfNotExists": <true or false - see below>,
"connection": "<Value of AccountEndpoint in Application Setting - see below>",
"direction": "out"
}
Output usage
This section shows you how to use your DocumentDB output binding in your function code.
When you write to the output parameter in your function, by default a new document is generated in your
database, with an automatically generated GUID as the document ID. You can specify the document ID of output
document by specifying the id JSON property in the output parameter. If a document with that ID already
exists, the output document overwrites it.
You can write to the output using any of the following types:
Any Object - useful for JSON-serialization. If you declare a custom output type (e.g. out FooType paramName ),
Azure Functions attempts to serialize object into JSON. If the output parameter is null when the function exits,
the Functions runtime creates a blob as a null object.
String - ( out string paramName ) useful for text blob data. the Functions runtime creates a blob only if the
string parameter is non-null when the function exits.
In C# functions you can also output to any of the following types:
TextWriter
Stream
CloudBlobStream
ICloudBlob
CloudBlockBlob
CloudPageBlob
To output multiple documents, you can also bind to ICollector<T> or IAsyncCollector<T> where T is one of
the supported types.
Output sample
Suppose you have the following DocumentDB output binding in the bindings array of function.json:
{
"name": "employeeDocument",
"type": "documentDB",
"databaseName": "MyDatabase",
"collectionName": "MyCollection",
"createIfNotExists": true,
"connection": "MyAccount_DOCUMENTDB",
"direction": "out"
}
And you have a queue input binding for a queue that receives JSON in the following format:
{
"name": "John Henry",
"employeeId": "123456",
"address": "A town nearby"
}
And you want to create DocumentDB documents in the following format for each record:
{
"id": "John Henry-123456",
"name": "John Henry",
"employeeId": "123456",
"address": "A town nearby"
}
See the language-specific sample that uses this output binding to add documents to your database.
C#
F#
Node.js
Output sample in C#
#r "Newtonsoft.Json"
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public static void Run(string myQueueItem, out object employeeDocument, TraceWriter log)
{
log.Info($"C# Queue trigger function processed: {myQueueItem}");
employeeDocument = new {
id = employee.name + "-" + employee.employeeId,
name = employee.name,
employeeId = employee.employeeId,
address = employee.address
};
}
Output sample in F#
open FSharp.Interop.Dynamic
open Newtonsoft.Json
type Employee = {
id: string
name: string
employeeId: string
address: string
}
You need to add a project.json file that specifies the FSharp.Interop.Dynamic and Dynamitey NuGet
dependencies:
{
"frameworks": {
"net46": {
"dependencies": {
"Dynamitey": "1.0.2",
"FSharp.Interop.Dynamic": "3.0.0"
}
}
}
}
context.bindings.employeeDocument = JSON.stringify({
id: context.bindings.myQueueItem.name + "-" + context.bindings.myQueueItem.employeeId,
name: context.bindings.myQueueItem.name,
employeeId: context.bindings.myQueueItem.employeeId,
address: context.bindings.myQueueItem.address
});
context.done();
};
Azure Functions Event Hub bindings
1/20/2017 4 min to read Edit on GitHub
This article explains how to configure and code Azure Event Hub bindings for Azure Functions. Azure Functions
supports trigger and output bindings for Event Hubs.
This is reference information for Azure Functions developers. If you're new to Azure Functions, start with the
following resources:
Create your first Azure Function
Azure Functions developer reference
C#, F#, or Node developer reference
If you are new to Azure Event Hubs, see the Azure Event Hub overview.
{
"type": "eventHubTrigger",
"name": "<Name of trigger parameter in function signature>",
"direction": "in",
"path": "<Name of the Event Hub>",
"consumerGroup": "Consumer group to use - see below",
"connection": "<Name of app setting with connection string - see below>"
}
consumerGroup is an optional property used to set the consumer group used to subscribe to events in the hub. If
omitted, the $Default consumer group is used.
connection must be the name of an app setting that contains the connection string to the event hub's
namespace. Copy this connection string by clicking the Connection Information button for the namespace, not
the event hub itself. This connection string must have at least read permissions to activate the trigger.
Additional settings can be provided in a host.json file to further fine tune Event Hub triggers.
Trigger usage
When an Event Hub trigger function is triggered, the message that triggers it is passed into the function as a
string.
Trigger sample
Suppose you have the following Event Hub trigger in the bindings array of function.json:
{
"type": "eventHubTrigger",
"name": "myEventHubMessage",
"direction": "in",
"path": "MyEventHub",
"connection": "myEventHubReadConnectionString"
}
See the language-specific sample that logs the message body of the event hub trigger.
C#
F#
Node.js
Trigger sample in C#
using System;
Trigger sample in F#
{
"type": "eventHub",
"name": "<Name of output parameter in function signature>",
"path": "<Name of event hub>",
"connection": "<Name of app setting with connection string - see below>"
"direction": "out"
}
connection must be the name of an app setting that contains the connection string to the event hub's
namespace. Copy this connection string by clicking the Connection Information button for the namespace, not
the event hub itself. This connection string must have send permissions to send the message to the event stream.
Output usage
This section shows you how to use your Event Hub output binding in your function code.
You can output messages to the configured event hub with the following parameter types:
out string
ICollector<string> (to output multiple messages)
IAsyncCollector<string> (async version of ICollector<T> )
Output sample
Suppose you have the following Event Hub output binding in the bindings array of function.json:
{
"type": "eventHub",
"name": "outputEventHubMessage",
"path": "myeventhub",
"connection": "MyEventHubSend",
"direction": "out"
}
See the language-specific sample that writes an event to the even stream.
C#
F#
Node.js
Output sample in C#
using System;
public static void Run(TimerInfo myTimer, out string outputEventHubMessage, TraceWriter log)
{
String msg = $"TimerTriggerCSharp1 executed at: {DateTime.Now}";
log.Verbose(msg);
outputEventHubMessage = msg;
}
Output sample in F#
module.exports = function(context) {
var timeStamp = new Date().toISOString();
var message = 'Event Hub message created at: ' + timeStamp;
context.bindings.outputEventHubMessage = [];
Next steps
For information about other bindings and triggers for Azure Functions, see Azure Functions triggers and bindings
developer reference
Azure Functions HTTP and webhook bindings
1/17/2017 11 min to read Edit on GitHub
This article explains how to configure and work with HTTP triggers and bindings in Azure Functions. With these,
you can use Azure Functions to build serverless APIs and respond to webhooks.
Azure Functions provides the following bindings:
An HTTP trigger lets you invoke a function with an HTTP request. This can be customized to respond to
webhooks.
An HTTP output binding allows you to respond to the request.
This is reference information for Azure Functions developers. If you're new to Azure Functions, start with the
following resources:
Create your first Azure Function
Azure Functions developer reference
C#, F#, or Node developer reference
HTTP trigger
The HTTP trigger will execute your function in response to an HTTP request. You can customize it to respond to a
particular URL or set of HTTP methods. An HTTP trigger can also be configured to respond to webhooks.
If using the Functions portal, you can also get started right away using a pre-made template. Select New
function and choose "API & Webhooks" from the Scenario dropdown. Select one of the templates and click
Create.
By default, an HTTP trigger will respond to the request with an HTTP 200 OK status code and an empty body. To
modify the response, configure an HTTP output binding
Configuring an HTTP trigger
An HTTP trigger is defined by including a JSON object similar to the following in the bindings array of
function.json:
{
"name": "req",
"type": "httpTrigger",
"direction": "in",
"authLevel": "function",
"methods": [ "GET" ],
"route": "values/{id}"
},
{
"name": "res",
"type": "http",
"direction": "out"
}
The trigger can additionally be tailored to a specific webhook provider (e.g., GitHub and Slack). If a provider is
specified, the Functions runtime can take care of the provider's validation logic for you.
Configuring Github as a webhook provider
To respond to GitHub webhooks, first create your function with an HTTP Trigger, and set the webHookType
property to "github". Then copy its URL and API key into your GitHub repository's Add webhook page. See
GitHub's Creating Webhooks documentation for more.
http://<yourapp>.azurewebsites.net/api/<funcname>
You can customize this route using the optional route property on the HTTP trigger's input binding. As an
example, the following function.json file defines a route property for an HTTP trigger:
{
"bindings": [
{
"type": "httpTrigger",
"name": "req",
"direction": "in",
"methods": [ "get" ],
"route": "products/{category:alpha}/{id:int?}"
},
{
"type": "http",
"name": "res",
"direction": "out"
}
]
}
Using this configuration, the function is now addressable with the following route instead of the original route.
http://<yourapp>.azurewebsites.net/api/products/electronics/357
This allows the function code to support two parameters in the address, "category" and "id". You can use any
Web API Route Constraint with your parameters. The following C# function code makes use of both parameters.
if (!id) {
context.res = {
// status: 200, /* Defaults to 200 */
body: "All " + category + " items were requested."
};
}
else {
context.res = {
// status: 200, /* Defaults to 200 */
body: category + " item with id = " + id + " was requested."
};
}
context.done();
}
By default, all function routes are prefixed with api. You can also customize or remove the prefix using the
http.routePrefix property in your host.json file. The following example removes the api route prefix by using an
empty string for the prefix in the host.json file.
{
"http": {
"routePrefix": ""
}
}
For detailed information on how to update the host.json file for your function, See, How to update function app
files.
For information on other properties you can configure in your host.json file, see host.json reference.
NOTE
Due to the elevated permissions granted by the master key, you should not share this key with third parties or distribute it
in native client applications. Exercise caution when choosing the admin authorization level.
https://<yourapp>.azurewebsites.net/api/<function>?code=<ApiKey>
The key can be included in a query string variable named code , as above, or it can be included in an
x-functions-key HTTP header. The value of the key can be any function key defined for the function, or any host
key.
You can choose to allow requests without keys or specify that the master key must be used by changing the
authLevel property in the binding JSON (see HTTP trigger).
NOTE
Function keys take precedence over host keys. If two keys are defined with the same name, the function key will be used.
{
"name": "req",
"type": "httpTrigger",
"direction": "in",
"authLevel": "function"
},
See the language-specific sample that looks for a name parameter either in the query string or the body of the
HTTP request.
C#
F#
Node.js
HTTP trigger sample in C#
using System.Net;
using System.Threading.Tasks;
You need a project.json file that uses NuGet to reference the FSharp.Interop.Dynamic and Dynamitey
assemblies, like this:
{
"frameworks": {
"net46": {
"dependencies": {
"Dynamitey": "1.0.2",
"FSharp.Interop.Dynamic": "3.0.0"
}
}
}
}
This will use NuGet to fetch your dependencies and will reference them in your script.
HTTP trigger sample in Node.JS
Webhook samples
Suppose you have the following webhook trigger in the bindings array of function.json:
{
"webHookType": "github",
"name": "req",
"type": "httpTrigger",
"direction": "in",
},
#r "Newtonsoft.Json"
using System;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;
Webhook sample in F#
open System.Net
open System.Net.Http
open FSharp.Interop.Dynamic
open Newtonsoft.Json
type Response = {
body: string
}
Next steps
For information about other bindings and triggers for Azure Functions, see Azure Functions triggers and
bindings developer reference
Azure Functions Mobile Apps bindings
1/17/2017 6 min to read Edit on GitHub
This article explains how to configure and code Azure Mobile Apps bindings in Azure Functions. Azure Functions
supports input and output bindings for Mobile Apps.
The Mobile Apps input and output bindings let you read from and write to data tables in your mobile app.
This is reference information for Azure Functions developers. If you're new to Azure Functions, start with the
following resources:
Create your first Azure Function
Azure Functions developer reference
C#, F#, or Node developer reference
{
"name": "<Name of input parameter in function signature>",
"type": "mobileTable",
"tableName": "<Name of your mobile app's data table>",
"id" : "<Id of the record to retrieve - see below>",
"connection": "<Name of app setting that has your mobile app's URL - see below>",
"apiKey": "<Name of app setting that has your mobile app's API key - see below>",
"direction": "in"
}
NOTE
Azure Functions stores your connection information and API keys as app settings so that they are not checked into
your source control repository. This safeguards your sensitive information.
Input usage
This section shows you how to use your Mobile Apps input binding in your function code.
When the record with the specified table and record ID is found, it is passed into the named JObject parameter
(or, in Node.js, it is passed into the context.bindings.<name> object). When the record is not found, the parameter
is null .
In C# and F# functions, any changes you make to the input record (input parameter) is automatically sent back to
the Mobile Apps table when the function exits successfully. In Node.js functions, use context.bindings.<name> to
access the input record. You cannot modify a record in Node.js.
Input sample
Suppose you have the following function.json, that retrieves a Mobile App table record with the id of the queue
trigger message:
{
"bindings": [
{
"name": "myQueueItem",
"queueName": "myqueue-items",
"connection":"",
"type": "queueTrigger",
"direction": "in"
},
{
"name": "record",
"type": "mobileTable",
"tableName": "MyTable",
"id" : "{queueTrigger}",
"connection": "My_MobileApp_Url",
"apiKey": "My_MobileApp_Key",
"direction": "in"
}
],
"disabled": false
}
See the language-specific sample that uses the input record from the binding. The C# and F# samples also
modify the record's text property.
C#
Node.js
Input sample in C#
#r "Newtonsoft.Json"
using Newtonsoft.Json.Linq;
{
"name": "<Name of output parameter in function signature>",
"type": "mobileTable",
"tableName": "<Name of your mobile app's data table>",
"connection": "<Name of app setting that has your mobile app's URL - see below>",
"apiKey": "<Name of app setting that has your mobile app's API key - see below>",
"direction": "out"
}
IMPORTANT
This API key must not be shared with your mobile app clients. It should only be distributed securely to service-side
clients, like Azure Functions.
NOTE
Azure Functions stores your connection information and API keys as app settings so that they are not checked into
your source control repository. This safeguards your sensitive information.
Output usage
This section shows you how to use your Mobile Apps output binding in your function code.
In C# functions, use a named output parameter of type out object to access the output record. In Node.js
functions, use context.bindings.<name> to access the output record.
Output sample
Suppose you have the following function.json, that defines a queue trigger and a Mobile Apps output:
{
"bindings": [
{
"name": "myQueueItem",
"queueName": "myqueue-items",
"connection":"",
"type": "queueTrigger",
"direction": "in"
},
{
"name": "record",
"type": "mobileTable",
"tableName": "MyTable",
"connection": "My_MobileApp_Url",
"apiKey": "My_MobileApp_Key",
"direction": "out"
}
],
"disabled": false
}
See the language-specific sample that creates a record in the Mobile Apps table endpoint with the content of the
queue message.
C#
Node.js
Output sample in C#
context.bindings.record = {
text : "I'm running in a Node function! Data: '" + myQueueItem + "'"
}
context.done();
};
Next steps
For information about other bindings and triggers for Azure Functions, see Azure Functions triggers and
bindings developer reference
Azure Functions Notification Hub output binding
2/9/2017 8 min to read Edit on GitHub
This article explains how to configure and code Azure Notification Hub bindings in Azure Functions.
This is reference information for Azure Functions developers. If you're new to Azure Functions, start with the
following resources:
Create your first Azure Function
Azure Functions developer reference
C#, F#, or Node developer reference
Your functions can send push notifications using a configured Azure Notification Hub with a few lines of code.
However, the Azure Notification Hub must be configured for the Platform Notifications Services (PNS) you want
to use. For more information on configuring an Azure Notification Hub and developing a client applications that
register to receive notifications, see Getting started with Notification Hubs and click your target client platform at
the top.
The notifications you send can be native notifications or template notifications. Native notifications target a
specific notification platform as configured in the platform property of the output binding. A template
notification can be used to target multiple platforms.
{
"bindings": [
{
"name": "notification",
"type": "notificationHub",
"tagExpression": "",
"hubName": "my-notification-hub",
"connection": "MyHubConnectionString",
"platform": "gcm",
"direction": "out"
}
],
"disabled": false
}
using System;
using Microsoft.Azure.NotificationHubs;
using Newtonsoft.Json;
// In this example the queue item is a new user to be processed in the form of a JSON string with
// a "name" value.
//
// The JSON format for a native APNS notification is ...
// { "aps": { "alert": "notification message" }}
#r "Microsoft.Azure.NotificationHubs"
#r "Newtonsoft.Json"
using System;
using Microsoft.Azure.NotificationHubs;
using Newtonsoft.Json;
// In this example the queue item is a new user to be processed in the form of a JSON string with
// a "name" value.
//
// The JSON format for a native GCM notification is ...
// { "data": { "message": "notification message" }}
using System;
using Microsoft.Azure.NotificationHubs;
using Newtonsoft.Json;
// In this example the queue item is a new user to be processed in the form of a JSON string with
// a "name" value.
//
// The XML format for a native WNS toast notification is ...
// <?xml version="1.0" encoding="utf-8"?>
// <toast>
// <visual>
// <binding template="ToastText01">
// <text id="1">notification message</text>
// </binding>
// </visual>
// </toast>
log.Info($"{wnsNotificationPayload}");
await notification.AddAsync(new WindowsNotification(wnsNotificationPayload));
}
if(myTimer.isPastDue)
{
context.log('Node.js is running late!');
}
context.log('Node.js timer trigger function ran!', timeStamp);
context.bindings.notification = {
location: "Redmond",
message: "Hello from Node!"
};
context.done();
};
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
public static void Run(string myQueueItem, out IDictionary<string, string> notification, TraceWriter log)
{
log.Info($"C# Queue trigger function processed: {myQueueItem}");
notification = GetTemplateProperties(myQueueItem);
}
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
public static void Run(string myQueueItem, out string notification, TraceWriter log)
{
log.Info($"C# Queue trigger function processed: {myQueueItem}");
notification = "{\"message\":\"Hello from C#. Processed a queue item!\"}";
}
#r "Microsoft.Azure.NotificationHubs"
using System;
using System.Threading.Tasks;
using Microsoft.Azure.NotificationHubs;
public static void Run(string myQueueItem, out Notification notification, TraceWriter log)
{
log.Info($"C# Queue trigger function processed: {myQueueItem}");
notification = GetTemplateNotification(myQueueItem);
}
Next steps
For information about other bindings and triggers for Azure Functions, see Azure Functions triggers and
bindings developer reference
Azure Functions Service Bus bindings
1/17/2017 6 min to read Edit on GitHub
This article explains how to configure and code Azure Service Bus bindings in Azure Functions. Azure Functions
supports trigger and output bindings for Notification Hubs queues and topics.
This is reference information for Azure Functions developers. If you're new to Azure Functions, start with the
following resources:
Create your first Azure Function
Azure Functions developer reference
C#, F#, or Node developer reference
{
"name" : "<Name of input parameter in function signature>",
"queueName" : "<Name of the queue>",
"connection" : "<Name of app setting that has your queue's connection string - see below>",
"accessRights" : "<Access rights for the connection string - see below>",
"type" : "serviceBusTrigger",
"direction" : "in"
}
topic trigger:
{
"name" : "<Name of input parameter in function signature>",
"topicName" : "<Name of the topic>",
"subscriptionName" : "<Name of the subscription>",
"connection" : "<Name of app setting that has your topic's connection string - see below>",
"accessRights" : "<Access rights for the connection string - see below>",
"type" : "serviceBusTrigger",
"direction" : "in"
}
Trigger behavior
Single-threading - By default, the Functions runtime processes multiple messages concurrently. To direct
the runtime to process only a single queue or topic message at a time, set serviceBus.maxConcurrrentCalls to
1 in host.json. For information about host.json, see Folder Structure and host.json.
Poison message handling - Service Bus does its own poison message handling, which can't be controlled
or configured in Azure Functions configuration or code.
PeekLock behavior - The Functions runtime receives a message in PeekLock mode and calls Complete on
the message if the function finishes successfully, or calls Abandon if the function fails. If the function runs
longer than the PeekLock timeout, the lock is automatically renewed.
Trigger usage
This section shows you how to use your Service Hub trigger in your function code.
In C# and F#, the Service Bus trigger message can be deserialized to any of the following input types:
string - useful for string messages
byte[] - useful for binary data
Any Object - useful for JSON-serialized data. If you declare a custom input type (e.g. FooType ), Azure
Functions attempts to deserialize the JSON data into your specified type.
BrokeredMessage - gives you the deserialized message with the BrokeredMessage.GetBody() method.
In Node.js, the Service Bus trigger message is passed into the function as either a string or, in the case of JSON
message, a JavaScript object.
Trigger sample
Suppose you have the following function.json:
{
"bindings": [
{
"queueName": "testqueue",
"connection": "MyServiceBusConnection",
"name": "myQueueItem",
"type": "serviceBusTrigger",
"direction": "in"
}
],
"disabled": false
}
See the language-specific sample that processes a Service Bus queue message.
C#
F#
Node.js
Trigger sample in C#
public static void Run(string myQueueItem, TraceWriter log)
{
log.Info($"C# ServiceBus queue trigger function processed message: {myQueueItem}");
}
Trigger sample in F#
{
"name" : "<Name of output parameter in function signature>",
"queueName" : "<Name of the queue>",
"connection" : "<Name of app setting that has your queue's connection string - see below>",
"accessRights" : "<Access rights for the connection string - see below>"
"type" : "serviceBus",
"direction" : "out"
}
topic output:
{
"name" : "<Name of output parameter in function signature>",
"topicName" : "<Name of the topic>",
"subscriptionName" : "<Name of the subscription>",
"connection" : "<Name of app setting that has your topic's connection string - see below>",
"accessRights" : "<Access rights for the connection string - see below>"
"type" : "serviceBus",
"direction" : "out"
}
Output usage
In C# and F#, Azure Functions can create a Service Bus queue message from any of the following types:
Any Object - Parameter definition looks like out T paramName (C#). Functions deserializes the object into a
JSON message. If the output value is null when the function exits, Functions creates the message with a null
object.
string - Parameter definition looks like out string paraName (C#). If the parameter value is non-null when
the function exits, Functions creates a message.
byte[] - Parameter definition looks like out byte[] paraName (C#). If the parameter value is non-null when
the function exits, Functions creates a message.
BrokeredMessage Parameter definition looks like out BrokeredMessage paraName (C#). If the parameter value is
non-null when the function exits, Functions creates a message.
For creating multiple messages in a C# function, you can use ICollector<T> or IAsyncCollector<T> . A message
is created when you call the Add method.
In Node.js, you can assign a string, a byte array, or a Javascript object (deserialized into JSON) to
context.binding.<paramName> .
Output sample
Suppose you have the following function.json, that defines a Service Bus queue output:
{
"bindings": [
{
"schedule": "0/15 * * * * *",
"name": "myTimer",
"runsOnStartup": true,
"type": "timerTrigger",
"direction": "in"
},
{
"name": "outputSbQueue",
"type": "serviceBus",
"queueName": "testqueue",
"connection": "MyServiceBusConnection",
"direction": "out"
}
],
"disabled": false
}
See the language-specific sample that sends a message to the service bus queue.
C#
F#
Node.js
Output sample in C#
public static void Run(TimerInfo myTimer, TraceWriter log, out string outputSbQueue)
{
string message = $"Service Bus queue message created at: {DateTime.Now}";
log.Info(message);
outputSbQueue = message;
}
Output sample in F#
Next steps
For information about other bindings and triggers for Azure Functions, see Azure Functions triggers and
bindings developer reference
Azure Functions Storage blob bindings
2/7/2017 9 min to read Edit on GitHub
This article explains how to configure and code Azure Storage blob bindings in Azure Functions. Azure Functions
supports trigger, input, and output bindings for Azure Storage blobs.
This is reference information for Azure Functions developers. If you're new to Azure Functions, start with the
following resources:
Create your first Azure Function
Azure Functions developer reference
C#, F#, or Node developer reference
NOTE
A blob only storage account is not supported. Azure Functions requires a general-purpose storage account to use with
blobs.
{
"name": "<Name of input parameter in function signature>",
"type": "blobTrigger",
"direction": "in",
"path": "<container to monitor, and optionally a blob name pattern - see below>",
"connection":"<Name of app setting - see below>"
}
This path would find a blob named original-Blob1.txt in the input container, and the value of the name variable
in function code would be Blob1 .
Another example:
"path": "input/{blobname}.{blobextension}",
This path would also find a blob named original-Blob1.txt, and the value of the blobname and blobextension
variables in function code would be original-Blob1 and txt.
You can restrict the file type of blobs by using a fixed value for the file extension. For example:
"path": "samples/{name}.png",
In this case, only .png blobs in the samples container trigger the function.
Curly braces are special characters in name patterns. To specify blob names that have curly braces in the name,
double the curly braces. For example:
"path": "images/{{20140101}}-{name}",
This path would find a blob named {20140101}-soundfile.mp3 in the images container, and the name variable
value in the function code would be soundfile.mp3.
Blob receipts
The Azure Functions runtime makes sure that no blob trigger function gets called more than once for the same
new or updated blob. It does so by maintaining blob receipts to determine if a given blob version has been
processed.
Blob receipts are stored in a container named azure-webjobs-hosts in the Azure storage account for your
function app (specified by the AzureWebJobsStorage app setting). A blob receipt has the following information:
The triggered function ("<function app name>.Functions.<function name>", for example:
"functionsf74b96f7.Functions.CopyBlob")
The container name
The blob type ("BlockBlob" or "PageBlob")
The blob name
The ETag (a blob version identifier, for example: "0x8D1DC6E70A277EF")
To force reprocessing of a blob, delete the blob receipt for that blob from the azure-webjobs-hosts container
manually.
Handling poison blobs
When a blob trigger function fails, Azure Functions retries that function up to 5 times by default (including the
first try) for a given blob. If all 5 tries fail, Functions adds a message to a Storage queue named webjobs-
blobtrigger-poison. The queue message for poison blobs is a JSON object that contains the following properties:
FunctionId (in the format <function app name>.Functions.<function name>)
BlobType ("BlockBlob" or "PageBlob")
ContainerName
BlobName
ETag (a blob version identifier, for example: "0x8D1DC6E70A277EF")
Blob polling for large containers
If the blob container watched by the binding contains more than 10,000 blobs, the Functions runtime scans log
files to watch for new or changed blobs. This process is not real time. A function might not get triggered until
several minutes or longer after the blob is created. In addition, storage logs are created on a "best efforts" basis.
There is no guarantee that all events are captured. Under some conditions, logs may be missed. If the speed and
reliability limitations of blob triggers for large containers are not acceptable for your application, the
recommended method is to create a queue message when you create the blob, and use a queue trigger instead
of a blob trigger to process the blob.
Trigger usage
In C# functions, you bind to the input blob data by using a named parameter in your function signature, like
<T> <name> . Where T is the data type that you want to deserialize the data into, and paramName is the name you
specified in the trigger JSON. In Node.js functions, you access the input blob data using context.bindings.<name>
.
The blob can be deserialized into any of the following types:
Any Object - useful for JSON-serialized blob data. If you declare a custom input type (e.g. FooType ), Azure
Functions attempts to deserialize the JSON data into your specified type.
String - useful for text blob data.
In C# functions, you can also bind to any of the following types, and the Functions runtime will attempt to
deserialize the blob data using that type:
TextReader
Stream
ICloudBlob
CloudBlockBlob
CloudPageBlob
CloudBlobContainer
CloudBlobDirectory
IEnumerable<CloudBlockBlob>
IEnumerable<CloudPageBlob>
Other types deserialized by ICloudBlobStreamBinder
Trigger sample
Suppose you have the following function.json, that defines a Storage blob trigger:
{
"disabled": false,
"bindings": [
{
"name": "myBlob",
"type": "blobTrigger",
"direction": "in",
"path": "samples-workitems",
"connection":""
}
]
}
See the language-specific sample that logs the contents of each blob that is added to the monitored container.
C#
Node.js
Trigger usage in C#
module.exports = function(context) {
context.log('Node.js Blob trigger function processed', context.bindings.myBlob);
context.done();
};
{
"name": "<Name of input parameter in function signature>",
"type": "blob",
"direction": "in"
"path": "<Path of input blob - see below>",
"connection":"<Name of app setting - see below>"
},
Input sample
Suppose you have the following function.json, that defines a Storage queue trigger, a Storage blob input, and a
Storage blob output:
{
"bindings": [
{
"queueName": "myqueue-items",
"connection": "MyStorageConnection",
"name": "myQueueItem",
"type": "queueTrigger",
"direction": "in"
},
{
"name": "myInputBlob",
"type": "blob",
"path": "samples-workitems/{queueTrigger}",
"connection": "MyStorageConnection",
"direction": "in"
},
{
"name": "myOutputBlob",
"type": "blob",
"path": "samples-workitems/{queueTrigger}-Copy",
"connection": "MyStorageConnection",
"direction": "out"
}
],
"disabled": false
}
See the language-specific sample that copies the input blob to the output blob.
C#
Node.js
Input usage in C#
public static void Run(string myQueueItem, string myInputBlob, out string myOutputBlob, TraceWriter log)
{
log.Info($"C# Queue trigger function processed: {myQueueItem}");
myOutputBlob = myInputBlob;
}
module.exports = function(context) {
context.log('Node.js Queue trigger function processed', context.bindings.myQueueItem);
context.bindings.myOutputBlob = context.bindings.myInputBlob;
context.done();
};
{
"name": "<Name of output parameter in function signature>",
"type": "blob",
"direction": "out",
"path": "<Path of input blob - see below>",
"connection": "<Name of app setting - see below>"
}
Output usage
In C# functions, you bind to the output blob by using the named out parameter in your function signature, like
out <T> <name> , where T is the data type that you want to serialize the data into, and paramName is the name
you specified in the output binding. In Node.js functions, you access the output blob using
context.bindings.<name> .
You can write to the output blob using any of the following types:
Any Object - useful for JSON-serialization. If you declare a custom output type (e.g. out FooType paramName ),
Azure Functions attempts to serialize object into JSON. If the output parameter is null when the function exits,
the Functions runtime creates a blob as a null object.
String - ( out string paramName ) useful for text blob data. the Functions runtime creates a blob only if the
string parameter is non-null when the function exits.
In C# functions you can also output to any of the following types:
TextWriter
Stream
CloudBlobStream
ICloudBlob
CloudBlockBlob
CloudPageBlob
ICollector<T> (to output multiple blobs)
IAsyncCollector<T> (async version of ICollector<T> )
Output sample
See input sample.
Next steps
For information about other bindings and triggers for Azure Functions, see Azure Functions triggers and
bindings developer reference
Azure Functions Storage queue bindings
1/19/2017 5 min to read Edit on GitHub
This article explains how to configure and code Azure Storage queue bindings in Azure Functions. Azure
Functions supports trigger and output bindings for Azure Storage queues.
This is reference information for Azure Functions developers. If you're new to Azure Functions, start with the
following resources:
Create your first Azure Function
Azure Functions developer reference
C#, F#, or Node developer reference
{
"name": "<Name of input parameter in function signature>",
"queueName": "<Name of queue to poll>",
"connection":"<Name of app setting - see below>",
"type": "queueTrigger",
"direction": "in"
}
connection must contain the name of an app setting that contains a storage connection string. In the Azure
portal, you can configure this app setting in the Integrate tab when you create a storage account or select an
existing one. To manually create this app setting, see Manage App Service settings.
Additional settings can be provided in a host.json file to further fine-tune storage queue triggers.
Handling poison queue messages
When a queue trigger function fails, Azure Functions retries that function up to five times for a given queue
message, including the first try. If all five attempts fail, Functions adds a message to a Storage queue named
<originalqueuename>-poison. You can write a function to process messages from the poison queue by
logging them or sending a notification that manual attention is needed.
To handle poison messages manually, you can get the number of times a message has been picked up for
processing by checking dequeueCount (see Queue trigger metadata).
Trigger usage
In C# functions, you bind to the input message by using a named parameter in your function signature, like
<T> <name> . Where T is the data type that you want to deserialize the data into, and paramName is the name
you specified in the trigger binding. In Node.js functions, you access the input blob data using
context.bindings.<name> .
Trigger sample
Suppose you have the following function.json, that defines a Storage queue trigger:
{
"disabled": false,
"bindings": [
{
"name": "myQueueItem",
"queueName": "myqueue-items",
"connection":"",
"type": "queueTrigger",
"direction": "in"
}
]
}
See the language-specific sample that retrieves and logs queue metadata.
C#
Node.js
Trigger sample in C#
public static void Run(string myQueueItem,
DateTimeOffset expirationTime,
DateTimeOffset insertionTime,
DateTimeOffset nextVisibleTime,
string queueTrigger,
string id,
string popReceipt,
int dequeueCount,
TraceWriter log)
{
log.Info($"C# Queue trigger function processed: {myQueueItem}\n" +
$"queueTrigger={queueTrigger}\n" +
$"expirationTime={expirationTime}\n" +
$"insertionTime={insertionTime}\n" +
$"nextVisibleTime={nextVisibleTime}\n" +
$"id={id}\n" +
$"popReceipt={popReceipt}\n" +
$"dequeueCount={dequeueCount}");
}
{
"name": "<Name of output parameter in function signature>",
"queueName": "<Name of queue to write to>",
"connection":"<Name of app setting - see below>",
"type": "queue",
"direction": "out"
}
connection must contain the name of an app setting that contains a storage connection string. In the Azure
portal, the standard editor in the Integrate tab configures this app setting for you when you create a storage
account or selects an existing one. To manually create this app setting, see Manage App Service settings.
Output usage
In C# functions, you write a queue message by using the named out parameter in your function signature, like
out <T> <name> . In this case, T is the data type that you want to serialize the message into, and paramName is
the name you specified in the output binding. In Node.js functions, you access the output using
context.bindings.<name> .
You can output a queue message using any of the data types in your code:
Any Object: out MyCustomType paramName
Used for JSON serialization. When you declare a custom output type, the runtime tries to serialize the object
into JSON. If the output parameter is null when the function exits, the runtime creates a queue message as a
null object.
String: out string paramName
Used for test messages. The runtime creates message only when the string parameter is non-null when the
function exits.
Byte array: out byte[]
Output sample
Suppose you have the following function.json, that defines a Storage queue trigger, a Storage blob input, and a
Storage blob output:
Example function.json for a storage queue output binding that uses a manual trigger and writes the input to a
queue message:
{
"bindings": [
{
"type": "manualTrigger",
"direction": "in",
"name": "input"
},
{
"type": "queue",
"name": "myQueueItem",
"queueName": "myqueue",
"connection": "my_storage_connection",
"direction": "out"
}
],
"disabled": false
}
See the language-specific sample that writes an output queue message for each input queue message.
C#
Node.js
Output sample in C#
public static void Run(string input, out string myQueueItem, TraceWriter log)
{
myQueueItem = "New message: " + input;
}
module.exports = function(context) {
// Define a new message for the myQueueItem output binding.
context.bindings.myQueueItem = "new message";
context.done();
};
module.exports = function(context) {
// Define a message array for the myQueueItem output binding.
context.bindings.myQueueItem = ["message 1","message 2"];
context.done();
};
Next steps
For an example of a function that uses aStorage queue triggers and bindings, see Create an Azure Function
connected to an Azure service.
For information about other bindings and triggers for Azure Functions, see Azure Functions triggers and
bindings developer reference
Azure Functions Storage table bindings
1/17/2017 6 min to read Edit on GitHub
This article explains how to configure and code Azure Storage table triggers and bindings in Azure Functions.
Azure Functions supports input and output bindings for Azure Storage tables.
The Storage table binding supports the following scenarios:
Read a single row in a C# or Node.js function - Set partitionKey and rowKey . The filter and take
properties are not used in this scenario.
Read multiple rows in a C# function - The Functions runtime provides an IQueryable<T> object bound to
the table. Type T must derive from TableEntity or implement ITableEntity . The partitionKey , rowKey ,
filter , and take properties are not used in this scenario; you can use the IQueryable object to do any
filtering required.
Read multiple rows in a Node function - Set the filter and take properties. Don't set partitionKey or
rowKey .
Write one or more rows in a C# function - The Functions runtime provides an ICollector<T> or
IAsyncCollector<T> bound to the table, where T specifies the schema of the entities you want to add.
Typically, type T derives from TableEntity or implements ITableEntity , but it doesn't have to. The
partitionKey , rowKey , filter , and take properties are not used in this scenario.
This is reference information for Azure Functions developers. If you're new to Azure Functions, start with the
following resources:
Create your first Azure Function
Azure Functions developer reference
C#, F#, or Node developer reference
{
"name": "<Name of input parameter in function signature>",
"type": "table",
"direction": "in",
"tableName": "<Name of Storage table>",
"partitionKey": "<PartitionKey of table entity to read - see below>",
"rowKey": "<RowKey of table entity to read - see below>",
"take": "<Maximum number of entities to read in Node.js - optional>",
"filter": "<OData filter expression for table input in Node.js - optional>",
"connection": "<Name of app setting - see below>",
}
In C# functions, you can also bind to any of the following types, and the Functions runtime will attempt to
deserialize the table data using that type:
Any type that implements ITableEntity
IQueryable<T>
Input sample
Supposed you have the following function.json, which uses a queue trigger to read a single table row. The JSON
specifies PartitionKey RowKey . "rowKey": "{queueTrigger}" indicates that the row key comes from the queue
message string.
{
"bindings": [
{
"queueName": "myqueue-items",
"connection": "MyStorageConnection",
"name": "myQueueItem",
"type": "queueTrigger",
"direction": "in"
},
{
"name": "personEntity",
"type": "table",
"tableName": "Person",
"partitionKey": "Test",
"rowKey": "{queueTrigger}",
"connection": "MyStorageConnection",
"direction": "in"
}
],
"disabled": false
}
Input sample in F#
[<CLIMutable>]
type Person = {
PartitionKey: string
RowKey: string
Name: string
}
{
"name": "<Name of input parameter in function signature>",
"type": "table",
"direction": "out",
"tableName": "<Name of Storage table>",
"partitionKey": "<PartitionKey of table entity to write - see below>",
"rowKey": "<RowKey of table entity to write - see below>",
"connection": "<Name of app setting - see below>",
}
You can serialize objects in Node.js or C# functions. In C# functions, you can also bind to the following types:
Any type that implements ITableEntity
ICollector<T> (to output multiple entities. See sample.)
IAsyncCollector<T> (async version of ICollector<T> )
CloudTable (using the Azure Storage SDK. See sample.)
Output sample
The following function.json and run.csx example shows how to write multiple table entities.
{
"bindings": [
{
"name": "input",
"type": "manualTrigger",
"direction": "in"
},
{
"tableName": "Person",
"connection": "MyStorageConnection",
"name": "tableBinding",
"type": "table",
"direction": "out"
}
],
"disabled": false
}
Output sample in F#
[<CLIMutable>]
type Person = {
PartitionKey: string
RowKey: string
Name: string
}
context.bindings.outputTable = [];
context.done();
};
The C# code adds a reference to the Azure Storage SDK so that the entity type can derive from TableEntity .
#r "Microsoft.WindowsAzure.Storage"
using Microsoft.WindowsAzure.Storage.Table;
Next steps
For information about other bindings and triggers for Azure Functions, see Azure Functions triggers and
bindings developer reference
Azure Functions timer trigger
1/17/2017 3 min to read Edit on GitHub
This article explains how to configure and code timer triggers in Azure Functions. Azure Functions supports the
trigger for timers. Timer triggers call functions based on a schedule, one time or recurring.
The timer trigger supports multi-instance scale-out. One single instance of a particular timer function is run
across all instances.
This is reference information for Azure Functions developers. If you're new to Azure Functions, start with the
following resources:
Create your first Azure Function
Azure Functions developer reference
C#, F#, or Node developer reference
Timer trigger
The timer trigger to a function uses the following JSON object in the bindings array of function.json:
{
"schedule": "<CRON expression - see below>",
"name": "<Name of trigger parameter in function signature>",
"type": "timerTrigger",
"direction": "in"
}
Alternatively, you could add a new app setting for your function app named WEBSITE_TIME_ZONE and set the
value to Eastern Standard Time. Then the following CRON expression could be used for 10:00 AM EST:
Schedule examples
Here are some samples of CRON expressions you can use for the schedule property.
To trigger once every 5 minutes:
Trigger usage
When a timer trigger function is invoked, the timer object is passed into the function. The following JSON is an
example representation of the timer object.
{
"Schedule":{
},
"ScheduleStatus": {
"Last":"2016-10-04T10:15:00.012699+00:00",
"Next":"2016-10-04T10:20:00+00:00"
},
"IsPastDue":false
}
Trigger sample
Suppose you have the following timer trigger in the bindings array of function.json:
{
"schedule": "0 */5 * * * *",
"name": "myTimer",
"type": "timerTrigger",
"direction": "in"
}
See the language-specific sample that reads the timer object to see whether it's running late.
C#
F#
Node.js
Trigger sample in C#
Trigger sample in F#
if(myTimer.isPastDue)
{
context.log('Node.js is running late!');
}
context.log('Node.js timer trigger function ran!', timeStamp);
context.done();
};
Next steps
For information about other bindings and triggers for Azure Functions, see Azure Functions triggers and
bindings developer reference
Azure Functions Twilio output binding
1/17/2017 4 min to read Edit on GitHub
This article explains how to configure and use Twilio bindings with Azure Functions.
This is reference information for Azure Functions developers. If you're new to Azure Functions, start with the
following resources:
Create your first Azure Function
Azure Functions developer reference
C#, F#, or Node developer reference
Azure Functions supports Twilio output bindings to enable your functions to send SMS text messages with a few
lines of code and a Twilio account.
{
"type": "twilioSms",
"name": "message",
"accountSid": "TwilioAccountSid",
"authToken": "TwilioAuthToken",
"to": "+1704XXXXXXX",
"from": "+1425XXXXXXX",
"direction": "out",
"body": "Azure Functions Testing"
}
using System;
using Newtonsoft.Json;
using Twilio;
public static void Run(string myQueueItem, out SMSMessage message, TraceWriter log)
{
log.Info($"C# Queue trigger function processed: {myQueueItem}");
// In this example the queue item is a JSON string representing an order that contains the name of a
// customer and a mobile number to send text updates to.
dynamic order = JsonConvert.DeserializeObject(myQueueItem);
string msg = "Hello " + order.name + ", thank you for your order.";
// Even if you want to use a hard coded message and number in the binding, you must at least
// initialize the SMSMessage variable.
message = new SMSMessage();
// A dynamic message can be set instead of the body in the output binding. In this example, we use
// the order information to personalize a text message to the mobile number provided for
// order status updates.
message.Body = msg;
message.To = order.mobileNumber;
}
Asynchronous
This asynchronous example code for an Azure Storage queue trigger sends a text message to a customer who
placed an order.
#r "Newtonsoft.Json"
#r "Twilio.Api"
using System;
using Newtonsoft.Json;
using Twilio;
public static async Task Run(string myQueueItem, IAsyncCollector<SMSMessage> message, TraceWriter log)
{
log.Info($"C# Queue trigger function processed: {myQueueItem}");
// In this example the queue item is a JSON string representing an order that contains the name of a
// customer and a mobile number to send text updates to.
dynamic order = JsonConvert.DeserializeObject(myQueueItem);
string msg = "Hello " + order.name + ", thank you for your order.";
// Even if you want to use a hard coded message and number in the binding, you must at least
// initialize the SMSMessage variable.
SMSMessage smsText = new SMSMessage();
// A dynamic message can be set instead of the body in the output binding. In this example, we use
// the order information to personalize a text message to the mobile number provided for
// order status updates.
smsText.Body = msg;
smsText.To = order.mobileNumber;
await message.AddAsync(smsText);
}
// In this example the queue item is a JSON string representing an order that contains the name of a
// customer and a mobile number to send text updates to.
var msg = "Hello " + myQueueItem.name + ", thank you for your order.";
// Even if you want to use a hard coded message and number in the binding, you must at least
// initialize the message binding.
context.bindings.message = {};
// A dynamic message can be set instead of the body in the output binding. In this example, we use
// the order information to personalize a text message to the mobile number provided for
// order status updates.
context.bindings.message = {
body : msg,
to : myQueueItem.mobileNumber
};
context.done();
};
Next steps
For information about other bindings and triggers for Azure Functions, see Azure Functions triggers and
bindings developer reference
Create a function from the Azure portal
2/6/2017 4 min to read Edit on GitHub
Overview
Azure Functions is an event-driven, compute-on-demand experience that extends the existing Azure application
platform with capabilities to implement code triggered by events occurring in other Azure services, SaaS products,
and on-premises systems. With Azure Functions, your applications scale based on demand and you pay only for
the resources you consume. Azure Functions enables you to create scheduled or triggered units of code
implemented in various programming languages. To learn more about Azure Functions, see the Azure Functions
Overview.
This topic shows you how to use the Azure portal to create a simple "hello world" Node.js Azure Function that is
invoked by an HTTP-trigger. Before you can create a function in the Azure portal, you must explicitly create a
function app in Azure App Service. To have the function app created for you automatically, see the other Azure
Functions quickstart tutorial, which is a simpler quickstart experience and includes a video.
Create a function
These steps create a function from the Azure Functions quickstart.
1. In the Quickstart tab, click WebHook + API and JavaScript, then click Create a function. A new
predefined Node.js function is created.
2. (Optional) At this point in the quickstart, you can choose to take a quick tour of Azure Functions features in
the portal. After you have completed or skipped the tour, you can test your new function by using the HTTP
trigger.
Next steps
This quickstart demonstrates a simple execution of a basic HTTP-triggered function. To learn more about using
Azure Functions in your apps, see the following topics:
Best Practices for Azure Functions
Azure Functions developer reference
Programmer reference for coding functions and defining triggers and bindings.
Testing Azure Functions
Describes various tools and techniques for testing your functions.
How to scale Azure Functions
Discusses service plans available with Azure Functions, including the Consumption hosting plan, and how to
choose the right plan.
What is Azure App Service?
Azure Functions uses the Azure App Service platform for core functionality like deployments, environment
variables, and diagnostics.
Need some help?
Post questions in the Azure forums. - Visit MSDN
Tag questions with the keyword azure-functions . - Visit Stack Overflow
Testing Azure Functions
2/6/2017 12 min to read Edit on GitHub
Overview
This topic demonstrates the various ways to test functions, which includes the following general approaches:
HTTP-based tools, such as cURL, Postman, and even a web browser for web-based triggers.
Storage explorer to test Azure Storage-based triggers.
Test tab in the Functions portal.
Timer-triggered function.
Testing application or framework.
All of the testing methods shown use an HTTP trigger function that accepts input through either a query string
parameter or the request body. You will create this function in the first section.
Append the name parameter to the query string using an actual name for the <Enter a name here> placeholder.
Paste the URL into your browser and you should get a response similar to the following.
This example is the Chrome browser, which wraps the returned string in XML. Other browsers display just the
string value.
In the portal Logs window, output similar to the following is logged while executing the function:
TIP
Use the HTTP testing tool that you are most comfortable with. Here are some alternatives to Postman:
Fiddler
Paw
{
"name" : "Wes testing with Postman",
"address" : "Seattle, W.A. 98101"
}
5. Click Send.
The following image shows testing the simple echo function example in this tutorial.
In the portal Logs window, output similar to the following is logged while executing the function:
This is the URL for triggering your function, we can test this by using the cURL command on the command-line
to make a GET ( -G or --get ) request against the function:
This particular example above requires a query string parameter which can be passed as Data ( -d ) in the cURL
command:
curl -G https://<Your Function App>.azurewebsites.net/api/<Your Function Name>?code=<your access code> -d
name=<Enter a name here>
Run the command and you see the following output of the function on the command-line:
In the portal Logs window, output similar to the following is logged while executing the function:
files
2. Click the + button to select or create the storage account you want to use. Then click Create.
3. Create a text file with the following text and save it:
4. Run Microsoft Azure Storage Explorer and connect to the blob container in the storage account being
monitored.
5. Click the Upload button and upload the text file.
The default blob trigger function code will report the processing of the blob in the logs:
{
"name" : "Wes testing Run button",
"address" : "USA"
}
In the portal Logs window, output similar to the following is logged while executing the function:
2016-03-23T08:03:12 Welcome, you are now connected to log-streaming service.
2016-03-23T08:03:17.357 Function started (Id=753a01b0-45a8-4125-a030-3ad543a89409)
2016-03-23T08:03:18.697 HTTP trigger function processed a request.
RequestUri=https://functions841def78.azurewebsites.net/api/wesmchttptriggernodejs1
2016-03-23T08:03:18.697 Request Headers = {"connection":"Keep-Alive","accept":"*/*","accept-
encoding":"gzip","accept-language":"en-US"}
2016-03-23T08:03:18.697 Processing user info from request body...
2016-03-23T08:03:18.697 Processing User Information...
2016-03-23T08:03:18.697 name = Wes testing Run button
2016-03-23T08:03:18.697 address = USA
2016-03-23T08:03:18.744 Function completed (Success, Id=753a01b0-45a8-4125-a030-3ad543a89409)
NOTE
If you use a different queue name, make sure the name you use conforms to the Naming Queues and MetaData rules.
Otherwise, you will get a HTTP Status code 400 : Bad Request.
1. In the Azure Portal for your Functions app, click New Function > QueueTrigger - C#.
2. Enter the queue name to be monitored by the queue function
queue-newusers
3. Click the + (add) button to select or create the storage account you want to use. Then click Create.
4. Leave this portal browser window opened so you can monitor the log entries for the default queue function
template code.
Create a timer trigger to drop a message in the queue
1. Open the Azure Portal in a new browser window and navigate to your Function app.
2. Click New Function > TimerTrigger - C#. Enter a cron expression to set how often the timer code will
execute testing your queue function. Then click Create. If you want the test to run every 30 seconds you
can use the following CRON expression:
*/30 * * * * *
myQueue
queue-newusers
7. Click the + (add) button to select the storage account you used previously with the queue trigger. Then click
Save.
8. Click the Develop tab for your timer trigger.
9. You can use the following code for the C# timer function as long as you used the same queue message
object name shown above. Then click Save
using System;
public static void Run(TimerInfo myTimer, out String myQueue, TraceWriter log)
{
String newUser =
"{\"name\":\"User testing from C# timer function\",\"address\":\"XYZ\"}";
myQueue = newUser;
}
At this point C# timer function will execute every 30 seconds if you used the example cron expression. The logs
for the timer function will report each execution:
In the browser window for the queue function, you will see the each message being processed:
var nameBodyJSON = {
name : "Wes testing with Node.JS code",
address : "Dallas, T.X. 75201"
};
var options = {
host: "functions841def78.azurewebsites.net",
//path: "/api/HttpTriggerNodeJS2?
code=sc1wt62opn7k9buhrm8jpds4ikxvvj42m5ojdt0p91lz5jnhfr2c74ipoujyq26wab3wk5gkfbt9&" + nameQueryString,
path: "/api/HttpTriggerNodeJS2?
code=sc1wt62opn7k9buhrm8jpds4ikxvvj42m5ojdt0p91lz5jnhfr2c74ipoujyq26wab3wk5gkfbt9",
method: "POST",
headers : {
"Content-Type":"application/json",
"Content-Length": Buffer.byteLength(bodyString)
}
};
callback = function(response) {
var str = ""
response.on("data", function (chunk) {
str += chunk;
});
response.on("end", function () {
console.log(str);
});
}
Output:
C:\Users\Wesley\testing\Node.js>node testHttpTriggerExample.js
*** Sending name and address in body ***
{"name" : "Wes testing with Node.JS code","address" : "Dallas, T.X. 75201"}
Hello Wes testing with Node.JS code
The address you provided is Dallas, T.X. 75201
In the portal Logs window, output similar to the following is logged while executing the function:
Example C# code:
if (args.Length > 0)
{
name = args[0];
}
if (args.Length > 1)
{
address = args[1];
}
In the browser window for the queue function, you will see the each message being processed:
2016-03-24T10:27:06 Welcome, you are now connected to log-streaming service.
2016-03-24T10:27:30.607 Function started (Id=e304450c-ff48-44dc-ba2e-1df7209a9d22)
2016-03-24T10:27:30.607 C# Queue trigger function processed: {"name":"Wes testing queues","address":"in a
console app"}
2016-03-24T10:27:30.607 Function completed (Success, Id=e304450c-ff48-44dc-ba2e-1df7209a9d22)
How to code and test Azure functions locally
1/17/2017 1 min to read Edit on GitHub
NOTE
The Azure Functions local development and tooling experience is currently in preview and the experience will be significantly
improved before the final release. The easiest way to run the Azure Functions host locally is use the Azure Functions CLI and
install it from npm. Currently, only Windows is supported. Full documentation is coming soon. To provide feedback or file
bugs on the Azure Functions CLI, please file an issue in the azure-webjobs-sdk-script GitHub repo.
Best Practices for Azure Functions
2/10/2017 3 min to read Edit on GitHub
Overview
This article provides a collection of best practices for you to consider when implementing function apps. Keep in
mind that your Azure Function App is an Azure App Service. So those best practices would apply.
Don't mix test and production code in the same function app.
Functions within a function app share resources. For example, memory is shared. If you're using a function app in
production, don't add test-related functions and resources to it. It can cause unexpected overhead during
production code execution.
Be careful what you load in your production function apps. Memory is averaged across each function in the app.
If you have a shared assembly referenced in multiple .Net functions, put it in a common shared folder. Reference
the assembly with a statement similar to the following example:
#r "..\Shared\MyAssembly.dll".
Otherwise, it is easy to accidentally deploy multiple test versions of the same binary that behave differently
between functions.
Don't use verbose logging in production code. It has a negative performance impact.
Next steps
For more information, see the following resources:
Azure Functions developer reference
Azure Functions C# developer reference
Azure Functions F# developer reference
Azure Functions NodeJS developer reference
Use Azure Functions to perform a scheduled clean-
up task
1/17/2017 3 min to read Edit on GitHub
This topic shows you how to use Azure Functions to create a new function in C# that runs based on an event timer
to clean-up rows in a database table. The new function is created based on a pre-defined template in the Azure
Functions portal. To support this scenario, you must also set a database connection string as an App Service setting
in the function app.
Prerequisites
Before you can create a function, you need to have an active Azure account. If you don't already have an Azure
account, free accounts are available.
This topic demonstrates a Transact-SQL command that executes a bulk cleanup operation in table named
TodoItems in a SQL Database. This same TodoItems table is created when you complete the Azure App Service
Mobile Apps quickstart tutorial. You can also use a sample database If you choose to use a different table, you will
need to modify the command.
You can get the connection string used by a Mobile App backend in the portal under All settings > Application
settings > Connection strings > Show connection string values > MS_TableConnectionString. You can also
get the connection string direct from a SQL Database in the portal under All settings > Properties > Show
database connection strings > ADO.NET (SQL authentication).
This scenario uses a bulk operation against the database. To have your function process individual CRUD
operations in a Mobile Apps table, you should instead use Mobile Table binding.
Now, you can add the C# function code that connects to your SQL Database.
#r "System.Configuration"
#r "System.Data"
using System.Configuration;
using System.Data.SqlClient;
using System.Threading.Tasks;
Next steps
See these topics for more information about Azure Functions.
Azure Functions developer reference
Programmer reference for coding functions and defining triggers and bindings.
Testing Azure Functions
Describes various tools and techniques for testing your functions.
How to scale Azure Functions
Discusses service plans available with Azure Functions, including the Consumption plan, and how to choose the
right plan.
Need some help?
Post questions in the Azure forums. - Visit MSDN
Tag questions with the keyword azure-functions . - Visit Stack Overflow
How to configure Azure Function app settings
1/17/2017 4 min to read Edit on GitHub
Settings overview
You can manage Azure Function Apps settings by clicking the Function App Settings link in the bottom-left
corner of the portal. Azure function app settings apply to all functions in the app.
1. Go to the Azure portal and sign-in with your Azure account.
2. Click Function App Settings in the bottom-left corner of the portal. This action reveals several configuration
options to choose from.
Develop
App Service Editor
The App Service Editor is an advaned in-portal editor that you can use to modify Json configuration files and code
files alike. Choosing this option launches a separate browser tab with a basic editor. This enables you to integrate
with Github, run and debug code, and modify function app settings.
Application settings
Manage environment variables, Framework versions, remote debugging, app settings, connection strings, default
docs, etc. These settings are specific to your Function App.
To configure app settings, click the Configure App Settings link.
Dev console
You can execute DOS style commands with the Azure functions in-portal console. Common commands include
directory and file creation and navigation, as well as executing batch files and scripts.
NOTE
You can upload scripts, but first you must configure an FTP client in the Azure Function's Advanced Settings.
Deploy
Continuous integration
You can integrate your Function App with GitHub, Visual Studio Team Services, and more.
1. Click the Configure continuous integration link. This opens a Deployments pane with options.
2. Click Setup in the Deployments pane to reveal a Deployment Source pane with one option: Click Choose
Source to show available sources.
3. Choose any of the deployment sources available: Visual Studio Team Services, OneDrive, Local Git
Repository, GitHub, Bitbucket, DropBox, or an External Repository by clicking it.
4. Enter your credentials and information as prompted by the various deployment sources. The credentials and
information requested may be slightly different depending on what source you have chosen.
Once you have setup CI, connected code you push to the configured source is automatically deployed to this
function app.
Kudu
Kudu allows you to access advanced administrative features of a Function App.
To open Kudu, click Go to Kudu. This action opens an entirely new browser window with the Kudu web admin.
NOTE
You can alternatively launch Kudu by inserting "scm" into your function's URL, as shown here:
https://<YourFunctionName>.scm.azurewebsites.net/
From the Kudu webpage, you can view and manage system information, app settings, environment variables, HTTP
headers, server variables, and more.
Manage: App Service settings
Manage your function app like any other App Service instance. This option gives you access to all the previously
discussed settings, plus several more.
To open advanced settings, click the Advanced Settings link.
For details on how to configure each App Service setting, see Configure Azure App Service Settings.
Manage: CORS
Normally, for security reasons, calls to your hosts (domains) from external sources, such as Ajax calls from a
browser, are not allowed. Otherwise, malicious code could be sent to and executed on the backend. The safest route
then is to blacklist all sources of code, except for a few of your own trusted ones. You can configure which sources
you accept calls from in Azure functions by configuring Cross-Origin Resource Sharing (CORS). CORS allows you
to list domains that are the source of JavaScript that can call functions in your Azure Function App.
1. To configure CORS, click the Configure CORS link.
2. Enter the domains that you want to whitelist.
Manage: Authentication/authorization
For functions that use an HTTP trigger, you can require calls to be authenticated.
1. To configure authentication click the Configure authentication link.
2. Toggle the App Service Authentication button to On.
Most authentication providers ask for an API Key/Client ID and a Secret; however, both the Microsoft Account and
Facebook options also allow you to define scopes (specific authorization credentials). Active Directory has several
express or advanced configuration settings you can set.
For details on configuring specific authentication providers, see Azure App Service authentication overview.
For more information on creating API definitions with Swagger, visit Get Started with API Apps, ASP.NET, and
Swagger in Azure.
Next steps
Need some help?
Post questions in the Azure forums. - Visit MSDN
Tag questions with the keyword azure-functions . - Visit Stack Overflow
Continuous deployment for Azure Functions
1/17/2017 5 min to read Edit on GitHub
Azure Functions makes it easy to configure continuous deployment for your function app. Functions uses Azure
App Service integration with BitBucket, Dropbox, GitHub, and Visual Studio Team Services (VSTS) to enable a
continuous deployment workflow where Azure pulls updates to your functions code when they are published to
one of these services. If you are new to Azure Functions, start with Azure Functions Overview.
Continuous deployment is a great option for projects where multiple and frequent contributions are being
integrated. It also lets you maintain source control on your functions code. The following deployment sources are
currently supported:
Bitbucket
Dropbox
Git local repo
Git external repo
GitHub
Mercurial external repo
OneDrive
Visual Studio Team Services
Deployments are configured on a per-function-app basis. After continuous deployment is enabled, access to
function code in the portal is set to read-only.
wwwroot
| - host.json
| - mynodefunction
| | - function.json
| | - index.js
| | - node_modules
| | | - ... packages ...
| | - package.json
| - mycsharpfunction
| | - function.json
| | - run.csx
The host.json file contains some runtime-specific configuration and sits in the root folder of the function app. For
information on settings that are available, see host.json in the WebJobs.Script repository wiki.
Each function has a folder that contains one or more code files, the function.json configuration and other
dependencies.
Set up continuous deployment
Use the following procedure to configure continuous deployment for an existing function app:
1. In your function app in the Azure Functions portal, click Function app settings > Configure continuous
integration > Setup.
You can also get to the Deployments blade from the Functions quickstart by clicking Start from source
control.
2. In the Deployment source blade, click Choose source, then fill-in the information for your chosen
deployment source and click OK.
After continuous deployment is configured, all changes files in your deployment source are copied to the function
app and a full site deployment is triggered. The site is redeployed when files in the source are updated.
Deployment options
The following are some typical deployment scenarios:
Create a staging deployment
Move existing functions to continuous deployment
Create a staging deployment
Function Apps doesn't yet support deployment slots. However, you can still manage separate staging and
production deployments by using continuous integration.
The process to configure and work with a staging deployment looks generally like this:
1. Create two function apps in your subscription, one for the production code and one for staging.
2. Create a deployment source, if you don't already have one. This example uses GitHub.
3. For your production function app, complete the above steps in Set up continuous deployment and set
the deployment branch to the master branch of your GitHub repo.
4. Repeat this step for the staging function app, but choose the staging branch instead in your GitHub repo. If
your deployment source doesn't support branching, use a different folder.
5. Make updates to your code in the staging branch or folder, then verify that those changes are reflected in
the staging deployment.
6. After testing, merge changes from the staging branch into the master branch. This will trigger deployment
to the production function app. If your deployment source doesn't support branches, overwrite the files in
the production folder with the files from the staging folder.
Move existing functions to continuous deployment
When you have existing functions that you have created and maintained in the portal, you need to download your
existing function code files using FTP or the local Git repository before you can set up continuous deployment as
described above. You can do this in the App Service settings for your function app. After your files are downloaded,
you can upload them to your chosen continuous deployment source.
NOTE
After you configure continuous integration, you will no longer be able to edit your source files in the Functions portal.
2. Type in a username and password, then click Save. You can now use these credentials to access your
function app from FTP or the built-in Git repo.
How to: Download files using FTP
1. In your function app in the Azure Functions portal, click Function app settings > Go to App Service
settings > Properties and copy the values for FTP/Deployment User, FTP Host Name, and FTPS Host
Name.
FTP/Deployment User must be entered as displayed in the portal, including the app name, in order to
provide proper context for the FTP server.
2. From your FTP client, use the connection information you gathered to connect to your app and download
the source files for your functions.
How to: download files using the local Git repository
1. In your function app in the Azure Functions portal, click Function app settings > Configure continuous
integration > Setup.
2. In the Deployments blade, click Choose source, Local Git repository, then click OK.
3. Click Go to App Service settings > Properties and note the value of Git URL.
4. Clone the repo on your local machine using a Git-aware command line or your favorite Git tool. The Git
clone command looks like the following:
5. Fetch files from your function app to the clone on your local computer, as in the following example:
If requested, supply the username and password for your function app deployment.
Automate resource deployment for your Azure
Functions app
2/7/2017 5 min to read Edit on GitHub
You can use an Azure Resource Manager template to deploy an Azure Functions app. Learn how to define the
baseline resources that are required for an Azure Functions app, and the parameters that are specified during
deployment. Depending on the triggers and bindings in your Functions app, for a successful Infrastructure as Code
configuration of your application, you might need to deploy additional resources.
For more information about creating templates, see Authoring Azure Resource Manager templates.
For examples of complete templates, see Create a Consumption plan-based Azure Functions app and Create an App
Service plan-based Azure Functions app.
Required resources
You can use the examples in this article to create a baseline Azure Functions app. You'll need these resources for
your app:
Azure Storage account
Hosting plan (Consumption plan or Azure App Service plan)
Functions app ( type : Microsoft.Web/Site, kind : functionapp)
Parameters
You can use Azure Resource Manager to define parameters for values that you want to specify when your template
is deployed. A template's Parameters section has all the parameter values. Define parameters for values that vary
based either on the project you are deploying, or on the environment you are deploying to.
Variables are useful for values that don't change based on an individual deployment, and for parameters that
require transformation before being used in a template (for example, to pass validation rules).
When you define parameters, use the allowedValues field to specify which values a user can provide during
deployment. To assign a value to the parameter, if no value is provided during deployment, use the defaultValue
field.
An Azure Resource Manager template uses the following parameters.
appName
The name of the Azure Functions app that you want to create.
"appName": {
"type": "string"
}
location
Where to deploy the Functions app.
NOTE
To inherit the location of the Resource Group, or if a parameter value isn't specified during a PowerShell or Azure CLI
deployment, use the defaultValue parameter. If you deploy your app from the Azure portal, select a value in the
allowedValues parameter drop-down box.
TIP
For an up-to-date list of regions where you can use Azure Functions, see Products available by region.
"location": {
"type": "string",
"allowedValues": [
"Brazil South",
"East US",
"East US 2",
"Central US",
"North Central US",
"South Central US",
"West US",
"West US 2"
],
"defaultValue": "[resourceGroup().location]"
}
sourceCodeRepositoryURL (optional)
"sourceCodeRepositoryURL": {
"type": "string",
"defaultValue": "",
"metadata": {
"description": "Source code repository URL"
}
sourceCodeBranch (optional)
"sourceCodeBranch": {
"type": "string",
"defaultValue": "master",
"metadata": {
"description": "Source code repository branch"
}
}
sourceCodeManualIntegration (optional)
"sourceCodeManualIntegration": {
"type": "bool",
"defaultValue": false,
"metadata": {
"description": "Use 'true' if you are deploying from the base repo. Use 'false' if you are deploying
from your own fork. If you use 'false', make sure that you have Administrator rights in the repo. If you get an
error, manually add GitHub integration to another web app, to associate a GitHub access token with your Azure
subscription."
}
}
Variables
Azure Resource Manager templates use variables to incorporate parameters, so you can use more specific settings
in your template.
In the next example, to meet Azure storage account naming requirements, we use variables to apply Azure
Resource Manager template functions to convert the entered appName value to lowercase.
"variables": {
"lowerSiteName": "[toLower(parameters('appName'))]",
"storageAccountName": "[concat(variables('lowerSiteName'))]"
}
Resources to deploy
Storage account
An Azure storage account is required for an Azure Functions app.
{
"type": "Microsoft.Storage/storageAccounts",
"name": "[variables('storageAccountName')]",
"apiVersion": "2015-05-01-preview",
"location": "[variables('storageLocation')]",
"properties": {
"accountType": "[variables('storageAccountType')]"
}
}
{
"type": "Microsoft.Web/serverfarms",
"apiVersion": "2015-04-01",
"name": "[variables('hostingPlanName')]",
"location": "[resourceGroup().location]",
"properties": {
"name": "[variables('hostingPlanName')]",
"computeMode": "Dynamic",
"sku": "Dynamic"
}
}
IMPORTANT
To create a successful Infrastructure as Code configuration for your application by using Azure Resource Manager, it's
important to understand how resources are deployed in Azure. In the following example, top-level configurations are applied
using siteConfig. It's important to set these configurations at a top level because they convey information to the Azure
Functions runtime and deployment engine. Top-level information is required before the child sourcecontrols/web resource
is applied. Although it's possible to configure these settings in the child-level config/appSettings resource, in some
scenarios, your Functions app and functions need to be deployed before config/appSettings is applied. In those cases, for
example, in Logic Apps, your functions are a dependency of another resource.
{
"apiVersion": "2015-08-01",
"name": "[parameters('appName')]",
"type": "Microsoft.Web/sites",
"kind": "functionapp",
"location": "[parameters('location')]",
"dependsOn": [
"[resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName'))]",
"[resourceId('Microsoft.Web/serverfarms', parameters('appName'))]"
],
"properties": {
"serverFarmId": "[variables('appServicePlanName')]",
"siteConfig": {
"alwaysOn": true,
"appSettings": [
{ "name": "FUNCTIONS_EXTENSION_VERSION", "value": "~1" },
{ "name": "Project", "value": "src" }
]
}
},
"resources": [
{
"apiVersion": "2015-08-01",
"name": "appsettings",
"type": "config",
"dependsOn": [
"[resourceId('Microsoft.Web/Sites', parameters('appName'))]",
"[resourceId('Microsoft.Web/Sites/sourcecontrols', parameters('appName'), 'web')]",
"[resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName'))]"
],
"properties": {
"AzureWebJobsStorage": "[concat('DefaultEndpointsProtocol=https;AccountName=',
variables('storageAccountName'), ';AccountKey=', listKeys(variables('storageAccountid'),'2015-05-01-
preview').key1)]",
"AzureWebJobsDashboard": "[concat('DefaultEndpointsProtocol=https;AccountName=',
variables('storageAccountName'), ';AccountKey=', listKeys(variables('storageAccountid'),'2015-05-01-
preview').key1)]"
}
},
{
"apiVersion": "2015-08-01",
"name": "web",
"type": "sourcecontrols",
"dependsOn": [
"[resourceId('Microsoft.Web/sites/', parameters('appName'))]"
],
"properties": {
"RepoUrl": "[parameters('sourceCodeRepositoryURL')]",
"branch": "[parameters('sourceCodeBranch')]",
"IsManualIntegration": "[parameters('sourceCodeManualIntegration')]"
}
}
]
}
TIP
This template uses the Project app settings value, which sets the base directory in which the Functions Deployment Engine
(Kudu) looks for deployable code. In our repository, our functions are in a subfolder of the src folder. So, in the preceding
example, we set the app settings value to src . If your functions are in the root of your repository, or if you are not
deploying from source control, you can remove this app settings value.
Markdown
[]
(https://portal.azure.com/#create/Microsoft.Template/uri/<url-encoded-path-to-azuredeploy-json>)
HTML
<a href="https://portal.azure.com/#create/Microsoft.Template/uri/<url-encoded-path-to-azuredeploy-json>"
target="_blank"><img src="http://azuredeploy.net/deploybutton.png"></a>
Next steps
Learn more about how to develop and configure Azure Functions.
Azure Functions developer reference
How to configure Azure Functions app settings
Create your first Azure function
Monitoring Azure Functions
1/17/2017 2 min to read Edit on GitHub
Overview
The Monitor tab for each function allows you to review each execution of a function.
Clicking an execution allows you to review the duration, input data, errors, and associated log files. This is useful
debugging and performance tuning your functions.
IMPORTANT
When using the Consumption hosting plan for Azure Functions, the Monitoring tile in the Function App overview blade will
not show any data. This is because the platform dynamically scales and manages compute instances for you, so these metrics
are not meaningful on a Consumption plan. To monitor the usage of your Function Apps, you should instead use the
guidance in this article.
The following screen-shot shows an example:
Real-time monitoring
Real-time monitoring is available by clicking live event stream as shown below.
The live event stream will be graphed in a new browser tab as shown below.
NOTE
There is a known issue that may cause your data to fail to be populated. If you experience this, you may need to close the
browser tab containing the live event stream and then click live event stream again to allow it to properly populate your
event stream data.
The live event stream will graph the following statistics for your function:
Executions started per second
Executions completed per second
Executions failed per second
Average execution time in milliseconds.
These statistics are real-time but the actual graphing of the execution data may have around 10 seconds of latency.
azure login
Use the following command to enable Azure CLI Service Management (ASM) mode:.
If you have multiple subscriptions, use the following commands to list your subscriptions and set the current
subscription to the subscription that contains your function app.
The following command will stream the log files of your function app to the command line:
PS C:\> Add-AzureAccount
If you have multiple subscriptions, you can list them by name with the following command to see if the correct
subscription is the currently selected based on IsCurrent property:
PS C:\> Get-AzureSubscription
If you need to set the active subscription to the one containing your function app, use the following command:
Stream the logs to your PowerShell session with the following command:
For more information refer to How to: Stream logs for web apps.
Next steps
For more information, see the following resources:
Testing a function
Scale a function