Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Azure Cosmos DB

To use Azure Cosmos DB in serverless mode, choose Serverless as the Capacity mode when creating your account.

1.Register binding extensions

Code Block
languagego
dotnet add package Microsoft.Azure.WebJobs.Extensions.CosmosDB --version 3.0.10

2.Add an output binding

Code Block
languagec#
[CosmosDB(databaseName: "my-database", collectionName: "my-container",
    ConnectionStringSetting = "CosmosDbConnectionString"
    )]IAsyncCollector<dynamic> documentsOut,

3.Add code that uses the output binding

Code Block
languagec#
[FunctionName("HttpExample")]
public static async Task<IActionResult> Run(HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
    [CosmosDB(
        databaseName: "my-database",
        collectionName: "my-container",
        ConnectionStringSetting = "CosmosDbConnectionString")]IAsyncCollector<dynamic> documentsOut,ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");
    string name = req.Query["name"];

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;

    if (!string.IsNullOrEmpty(name))
    {
        // Add a JSON document to the output container.
        await documentsOut.AddAsync(new
        {
            // create a random ID
            id = System.Guid.NewGuid().ToString(),
            name = name
        });
    }
    string responseMessage = string.IsNullOrEmpty(name)
        ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
        : $"Hello, {name}. This HTTP triggered function executed successfully.";

    return new OkObjectResult(responseMessage);
}

Azure SQL

Verify that your Azure Function will be able to access the Azure SQL Database by checking the server's firewall settings : Network Access Controls - Azure SQL Database & Azure Synapse Analytics | Microsoft Learn. Navigate to the server blade on the Azure portal, and under Security, select Networking. The exception for Allow Azure services and resources to access this server should be checked.

1.Register binding extensions

Code Block
languagego
dotnet add package Microsoft.Azure.Functions.Worker.Extensions.Sql

2.Add an output binding

Add the following ToDoItem class, which defines the object that is written to the database.

Code Block
languagec#
namespace AzureSQL.ToDo
{
    public class ToDoItem
    {
        public Guid Id { get; set; }
        public int? order { get; set; }
        public string title { get; set; }
        public string url { get; set; }
        public bool? completed { get; set; }
    }
}

The toDoItems parameter is an IAsyncCollector<ToDoItem> type, which represents a collection of ToDo items that are written to your Azure SQL Database when the function completes.

Code Block
languagec#
[Sql(commandText: "dbo.ToDo", connectionStringSetting: "SqlConnectionString")] IAsyncCollector<ToDoItem> toDoItems)

3.Add code that uses the output binding

Code Block
languagec#
[FunctionName("HttpExample")]
public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
    [Sql(commandText: "dbo.ToDo", connectionStringSetting: "SqlConnectionString")] IAsyncCollector<ToDoItem> toDoItems,ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");
    string name = req.Query["name"];

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;

    if (!string.IsNullOrEmpty(name))
    {
        // Add a JSON document to the output container.
        await toDoItems.AddAsync(new
        {
            // create a random ID
            id = System.Guid.NewGuid().ToString(),
            title = name,
            completed = false,
            url = ""
        });
    }

    string responseMessage = string.IsNullOrEmpty(name)
        ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
        : $"Hello, {name}. This HTTP triggered function executed successfully.";

    return new OkObjectResult(responseMessage);
}