### Install npm packages Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-task-scheduler/quickstart-portable-durable-task-sdks?source=recommendations&tabs=linux Install the necessary npm packages before starting the worker or client. ```bash npm install ``` -------------------------------- ### Example Request to Start Orchestrator Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-http-api An example HTTP POST request to start a 'RestartVMs' orchestrator function, including a JSON payload for input parameters. ```HTTP POST /runtime/webhooks/durabletask/orchestrators/RestartVMs?code=XXX Content-Type: application/json Content-Length: 83 { "resourceGroup": "myRG", "subscriptionId": "aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e" } ``` -------------------------------- ### Start an Orchestration Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-http-api?source=recommendations Example of initiating an orchestration using a POST request and the resulting response containing management URIs. ```Bash curl -X POST "http://localhost:7071/runtime/webhooks/durabletask/orchestrators/ProcessOrder" \ -H "Content-Type: application/json" \ -d '{ "orderId": "ORD-12345", "customerId": "CUST-789", "amount": 150.00 }' ``` ```JSON { "id": "abc123def456", "statusQueryGetUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/abc123def456?code=XXX", "sendEventPostUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/abc123def456/raiseEvent/{eventName}?code=XXX", "terminatePostUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/abc123def456/terminate?reason={text}&code=XXX" } ``` -------------------------------- ### Start an orchestration instance with a specific version Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-orchestration-versioning Use these examples to initiate a new orchestration instance with a custom version string. ```C# [Function("HttpStart")] public static async Task HttpStart( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req, [DurableClient] DurableTaskClient client, FunctionContext executionContext) { var options = new StartOrchestrationOptions { Version = "1.0" }; string instanceId = await client.ScheduleNewOrchestrationInstanceAsync( "ProcessOrderOrchestrator", orderId, options); // ... } ``` ```JavaScript const HttpStart: HttpHandler = async (request: HttpRequest, context: InvocationContext): Promise => { const client = df.getClient(context); const instanceId = await client.startNew("ProcessOrderOrchestrator", { input: orderId, version: "1.0" }); // ... }; ``` ```Python @myApp.route(route="orchestrators/{functionName}") @myApp.durable_client_input(client_name="client") async def http_start(req: func.HttpRequest, client): instance_id = await client.start_new("ProcessOrderOrchestrator", client_input=order_id, version="1.0") # ... ``` ```PowerShell param($Request, $TriggerMetadata) $instanceId = Start-DurableOrchestration -FunctionName "ProcessOrderOrchestrator" -Input $orderId -Version "1.0" # ... ``` ```Java @FunctionName("HttpStart") public HttpResponseMessage httpStart( @HttpTrigger(name = "req", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage> request, @DurableClientInput(name = "durableContext") DurableClientContext durableContext, final ExecutionContext context) { DurableTaskClient client = durableContext.getClient(); NewOrchestrationInstanceOptions options = new NewOrchestrationInstanceOptions().setVersion("1.0"); String instanceId = client.scheduleNewOrchestrationInstance( "ProcessOrderOrchestrator", orderId, options); // ... ``` -------------------------------- ### C# Example Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-instance-management Example of how to use the `CreateHttpManagementPayload` method in C# to get webhook URLs and store them in Azure Cosmos DB. ```csharp using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.DurableFunctions; using Microsoft.Azure.WebJobs.Extensions.CosmosDB; public static class SendInstanceInfo { [FunctionName("SendInstanceInfo")] public static void SendInstanceInfo( [ActivityTrigger] IDurableActivityContext ctx, [DurableClient] IDurableOrchestrationClient client, [CosmosDB( databaseName: "MonitorDB", containerName: "HttpManagementPayloads", Connection = "CosmosDBConnectionSetting")]out dynamic document) { HttpManagementPayload payload = client.CreateHttpManagementPayload(ctx.InstanceId); // send the payload to Azure Cosmos DB document = new { Payload = payload, id = ctx.InstanceId }; } } ``` -------------------------------- ### Start Local Infrastructure Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-task-scheduler/durable-task-scheduler-opentelemetry-tracing?pivots=durable-functions&tabs=csharp Command to start the defined Docker services. ```bash docker compose up -d ``` -------------------------------- ### Execute Fan-Out/Fan-In Pattern Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-task-scheduler/quickstart-portable-durable-task-sdks Commands to install dependencies, start the worker process, and trigger the client orchestration. ```bash npm install ``` ```bash npm run worker ``` ```bash npm run client ``` ```bash npm run client -- 15 ``` -------------------------------- ### Install project dependencies Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/quickstart-python-vscode?source=recommendations Install the packages specified in requirements.txt using pip. ```bash python -m pip install -r requirements.txt ``` -------------------------------- ### Install all extensions via CLI Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-extension-upgrade Installs the latest versions of all extensions supported by Extension Bundles. ```bash func extensions install ``` -------------------------------- ### Example profile.ps1 Configuration Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-powershell-v2-sdk-migration-guide A sample profile.ps1 file demonstrating how to initialize the environment and authenticate with MSI. ```powershell # Azure Functions profile.ps1 # # This profile.ps1 will get executed every "cold start" of your Function App. # "cold start" occurs when: # # * A Function App starts up for the very first time # * A Function App starts up after being de-allocated due to inactivity # # You can define helper functions, run commands, or specify environment variables # NOTE: any variables defined that are not environment variables will get reset after the first execution # Authenticate with Azure PowerShell using MSI. # Remove this if you are not planning on using MSI or Azure PowerShell. if ($env:MSI_SECRET) { Disable-AzContextAutosave -Scope Process | Out-Null Connect-AzAccount -Identity } # Uncomment the next line to enable legacy AzureRm alias in Azure PowerShell. # Enable-AzureRmAlias # You can also define functions or aliases that can be referenced in any of your PowerShell functions. ``` -------------------------------- ### Navigate to Sample Directory Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-task-scheduler/durable-task-scheduler-auto-scaling?tabs=portal Use this command to navigate into the specific sample directory for deployment. ```bash cd /path/to/Durable-Task-Scheduler/samples/scenarios/AutoscalingInACA ``` -------------------------------- ### Install specific Durable Functions extension version example Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-extension-upgrade?source=recommendations An example of how to install a specific version of the Durable Functions extension, in this case, version 2.9.1. ```console func extensions install -p Microsoft.Azure.WebJobs.Extensions.DurableTask -v 2.9.1 ``` -------------------------------- ### Navigate to .NET SDK sample directory Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-task-scheduler/quickstart-portable-durable-task-sdks?source=recommendations&tabs=linux Change directory to the .NET SDK sample for Durable Task Scheduler. ```bash cd samples/durable-task-sdks/dotnet/FanOutFanIn ``` -------------------------------- ### Build the sample project Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-task-scheduler/quickstart-work-item-filtering-durable-task Compile the .NET project before running the workers. ```bash dotnet build ``` -------------------------------- ### Get Entity Example Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-http-api Example request and response for retrieving the state of a 'Counter' entity. ```HTTP GET /runtime/webhooks/durabletask/entities/Counter/steps ``` ```JSON { "currentValue": 5 } ``` -------------------------------- ### Navigate to sample directory Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-task-scheduler/quickstart-work-item-filtering-durable-task Change the working directory to the specific sample location. ```bash cd samples/scenarios/WorkItemFilteringSplitActivities ``` -------------------------------- ### Example HTTP Response for Orchestration Start Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-http-features?source=recommendations&tabs=csharp-inproc This is an example of the HTTP 202 Accepted response received after successfully starting a Durable Functions orchestration. It includes URIs for checking status, sending events, and terminating the instance. ```http HTTP/1.1 202 Accepted Content-Type: application/json; charset=utf-8 Location: http://localhost:7071/runtime/webhooks/durabletask/instances/abc123?code=XXX Retry-After: 10 { "id": "abc123", "purgeHistoryDeleteUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/abc123?code=XXX", "sendEventPostUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/abc123/raiseEvent/{eventName}?code=XXX", "statusQueryGetUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/abc123?code=XXX", "terminatePostUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/abc123/terminate?reason={text}&code=XXX" } ``` -------------------------------- ### Navigate to SDK sample directories Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-task-scheduler/quickstart-portable-durable-task-sdks Commands to change the working directory to the specific SDK sample folder. ```Bash cd samples/durable-task-sdks/dotnet/FanOutFanIn ``` ```Bash cd samples/durable-task-sdks/python/fan-out-fan-in ``` ```Bash cd samples/durable-task-sdks/java/fan-out-fan-in ``` ```Bash cd samples/durable-task-sdks/javascript/fan-out-fan-in ``` -------------------------------- ### C# Example for Getting Status Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-instance-management?tabs=csharp An example demonstrating how to use the `GetStatusAsync` method in C# to retrieve the status of an orchestration instance. ```csharp ```csharp [FunctionName("GetStatus")] public static async Task Run( [DurableClient] IDurableOrchestrationClient client, [QueueTrigger("check-status-queue")] string instanceId) { DurableOrchestrationStatus status = await client.GetStatusAsync(instanceId); // do something based on the current status. } ``` ``` -------------------------------- ### Navigate to Java SDK sample directory Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-task-scheduler/quickstart-portable-durable-task-sdks?source=recommendations&tabs=linux Change directory to the Java SDK sample for Durable Task Scheduler. ```bash cd samples/durable-task-sdks/java/fan-out-fan-in ``` -------------------------------- ### Start Orchestration from Entity Operation Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-dotnet-entities?source=recommendations An example of an entity operation that starts a new orchestration when a condition is met, passing the entity ID as an input. ```csharp public void Add(int amount) { if (this.Value < 100 && this.Value + amount >= 100) { Entity.Current.StartNewOrchestration("MilestoneReached", Entity.Current.EntityId); } this.Value += amount; } ``` -------------------------------- ### Example Client Output (Fan-Out/Fan-In) Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-task-scheduler/quickstart-portable-durable-task-sdks?source=recommendations&tabs=linux This output shows the client initiating a fan-out/fan-in orchestration, processing parallel tasks, and aggregating the results. ```text Starting fan out/fan in orchestration with 10 items Waiting for 10 parallel tasks to complete Orchestrator yielded with 10 task(s) and 0 event(s) outstanding. Processing work item: 1 Processing work item: 2 Processing work item: 10 Processing work item: 9 Processing work item: 8 Processing work item: 7 Processing work item: 6 Processing work item: 5 Processing work item: 4 Processing work item: 3 Orchestrator yielded with 9 task(s) and 0 event(s) outstanding. Orchestrator yielded with 8 task(s) and 0 event(s) outstanding. Orchestrator yielded with 7 task(s) and 0 event(s) outstanding. Orchestrator yielded with 6 task(s) and 0 event(s) outstanding. Orchestrator yielded with 5 task(s) and 0 event(s) outstanding. Orchestrator yielded with 4 task(s) and 0 event(s) outstanding. Orchestrator yielded with 3 task(s) and 0 event(s) outstanding. Orchestrator yielded with 2 task(s) and 0 event(s) outstanding. Orchestrator yielded with 1 task(s) and 0 event(s) outstanding. All parallel tasks completed, aggregating results Orchestrator yielded with 1 task(s) and 0 event(s) outstanding. Aggregating results from 10 items Orchestration completed with status: COMPLETED ``` -------------------------------- ### Get Orchestration Status in JavaScript Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-instance-management?source=recommendations Use the `durable-functions` npm package to get the status of a running orchestration instance by its ID. Ensure the `durable-functions` package is installed. ```javascript const df = require("durable-functions"); module.exports = async function(context, instanceId) { const client = df.getClient(context); const status = await client.getStatus(instanceId); // do something based on the current status. // example: if status.runtimeStatus === df.OrchestrationRuntimeStatus.Running: ... } ``` -------------------------------- ### HTTP GET Request for Orchestration Instance Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-custom-orchestration-status This is an example of an HTTP GET request to retrieve the status of a specific orchestration instance. The URL includes the instance ID. ```HTTP GET /runtime/webhooks/durabletask/instances/instance123 ``` -------------------------------- ### Navigate to Durable Task SDK Sample Directory (C#) Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-task-scheduler/quickstart-container-apps-durable-task-sdk Navigate to the C# sample directory for Durable Task SDKs. Ensure you have .NET 8 SDK or later installed, Docker for the emulator, and Azure Developer CLI. ```bash cd /samples/durable-task-sdks/dotnet/FunctionChaining ``` -------------------------------- ### Start Orchestration with Task Hub in C# Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-task-hubs?source=recommendations&tabs=csharp%2Cportal Use the DurableClient attribute with the TaskHub property set to an app setting to start a new orchestration. This example is for Durable Functions 2.x. ```csharp [FunctionName("HttpStart")] public static async Task Run( [HttpTrigger(AuthorizationLevel.Function, methods: "post", Route = "orchestrators/{functionName}")] HttpRequestMessage req, [DurableClient(TaskHub = "%MyTaskHub%")] IDurableOrchestrationClient starter, string functionName, ILogger log) { // Function input comes from the request content. object eventData = await req.Content.ReadAsAsync(); string instanceId = await starter.StartNewAsync(functionName, eventData); log.LogInformation($"Started orchestration with ID = '{instanceId}'."); return starter.CreateCheckStatusResponse(req, instanceId); } ``` -------------------------------- ### Start Singleton Orchestration (Python) Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-singletons?source=recommendations Starts a new orchestration instance if one with the specified ID does not already exist or has completed. This example uses the Durable Task SDK client. ```python event_data = req.get_body() instance_id = await client.start_new(function_name, instance_id, event_data) logging.info(f"Started orchestration with ID = '{instance_id}'.") return client.create_check_status_response(req, instance_id) ``` ```python return func.HttpResponse( body=f"An instance with ID '{instance_id}' already exists.", status_code=409, ) ``` -------------------------------- ### Start Singleton Orchestration (Java) Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-singletons?source=recommendations Starts a new orchestration instance if one with the specified ID does not already exist or is not running. This Java example uses the Durable Task SDK client. ```java @FunctionName("HttpStartSingle") public HttpResponseMessage runSingle( @HttpTrigger(name = "req") HttpRequestMessage req, @DurableClientInput(name = "durableContext") DurableClientContext durableContext) { String instanceID = "StaticID"; DurableTaskClient client = durableContext.getClient(); // Check to see if an instance with this ID is already running OrchestrationMetadata metadata = client.getInstanceMetadata(instanceID, false); if (metadata.isRunning()) { return req.createResponseBuilder(HttpStatus.CONFLICT) .body("An instance with ID '" + instanceID + "' already exists.") .build(); } // No such instance exists - create a new one. De-dupe is handled automatically // in the storage layer if another function tries to also use this instance ID. client.scheduleNewOrchestrationInstance("MyOrchestration", null, instanceID); return durableContext.createCheckStatusResponse(req, instanceID); } ``` -------------------------------- ### Device Provisioning Orchestration (Python) Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-sub-orchestrations Provides a device provisioning workflow example in Python using Durable Functions. It demonstrates calling activities and waiting for external events within an orchestrator function. ```python import azure.functions as func import azure.durable_functions as df def orchestrator_function(context: df.DurableOrchestrationContext): device_id = context.get_input() # Step 1: Create an installation package in blob storage and return a SAS URL. sas_url = yield context.call_activity("CreateInstallationPackage", device_id) # Step 2: Notify the device that the installation package is ready. yield context.call_activity("SendPackageUrlToDevice", { "id": device_id, "url": sas_url }) # Step 3: Wait for the device to acknowledge that it has downloaded the new package. yield context.call_activity("DownloadCompletedAck") # Step 4: ... ``` -------------------------------- ### HTTP-triggered function to start orchestration Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/quickstart-java?source=recommendations This Java function is triggered by HTTP requests and starts a new Durable Functions orchestration. It uses `DurableClientContext` to get a `DurableTaskClient` and schedule a new instance of the 'Cities' orchestration. ```java import com.microsoft.azure.functions.annotation.*; import com.microsoft.azure.functions.*; import java.util.*; import com.microsoft.durabletask.*; import com.microsoft.durabletask.azurefunctions.DurableActivityTrigger; import com.microsoft.durabletask.azurefunctions.DurableClientContext; import com.microsoft.durabletask.azurefunctions.DurableClientInput; import com.microsoft.durabletask.azurefunctions.DurableOrchestrationTrigger; public class DurableFunctionsSample { /** * This HTTP-triggered function starts the orchestration. */ @FunctionName("StartOrchestration") public HttpResponseMessage startOrchestration( @HttpTrigger(name = "req", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage> request, @DurableClientInput(name = "durableContext") DurableClientContext durableContext, final ExecutionContext context) { context.getLogger().info("Java HTTP trigger processed a request."); DurableTaskClient client = durableContext.getClient(); String instanceId = client.scheduleNewOrchestrationInstance("Cities"); context.getLogger().info("Created new Java orchestration with instance ID = " + instanceId); return durableContext.createCheckStatusResponse(request, instanceId); } /** * This is the orchestrator function, which can schedule activity functions, create durable timers, * or wait for external events in a way that's completely fault-tolerant. */ @FunctionName("Cities") public String citiesOrchestrator( @DurableOrchestrationTrigger(name = "taskOrchestrationContext") TaskOrchestrationContext ctx) { String result = ""; result += ctx.callActivity("Capitalize", "Tokyo", String.class).await() + ", "; result += ctx.callActivity("Capitalize", "London", String.class).await() + ", "; result += ctx.callActivity("Capitalize", "Seattle", String.class).await() + ", "; result += ctx.callActivity("Capitalize", "Austin", String.class).await(); return result; } /** * This is the activity function that is invoked by the orchestrator function. */ @FunctionName("Capitalize") public String capitalize(@DurableActivityTrigger(name = "name") String name, final ExecutionContext context) { context.getLogger().info("Capitalizing: " + name); return name.toUpperCase(); } } ``` -------------------------------- ### Initialize Local Event Grid Listener Project Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-event-publishing?source=recommendations Steps to create a local directory, initialize the project, and add an Event Grid trigger function. ```Bash mkdir EventGridListenerFunction cd EventGridListenerFunction ``` ```Bash func init --name EventGridListener --runtime dotnet-isolated ``` ```Bash func new --template "Event Grid trigger" --name EventGridTrigger ``` -------------------------------- ### Start Durable Orchestration from a Queue Trigger in Java Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-instance-management?source=recommendations&tabs=csharp This Java function, triggered by a queue, starts a Durable Functions orchestration. It uses the `DurableClientInput` to get the client and schedules a new instance of the 'HelloWorld' orchestration. ```java @FunctionName("HelloWorldQueueTrigger") public void helloWorldQueueTrigger( @QueueTrigger(name = "input", queueName = "start-queue", connection = "Storage") String input, @DurableClientInput(name = "durableContext") DurableClientContext durableContext, final ExecutionContext context) { DurableTaskClient client = durableContext.getClient(); String instanceID = client.scheduleNewOrchestrationInstance("HelloWorld"); context.getLogger().info("Scheduled orchestration with ID = " + instanceID); } ``` -------------------------------- ### Navigate to Python SDK sample directory Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-task-scheduler/quickstart-portable-durable-task-sdks?source=recommendations&tabs=linux Change directory to the Python SDK sample for Durable Task Scheduler. ```bash cd samples/durable-task-sdks/python/fan-out-fan-in ``` -------------------------------- ### Navigate to Durable Task SDK Sample Directory (Java) Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-task-scheduler/quickstart-container-apps-durable-task-sdk Navigate to the Java sample directory for Durable Task SDKs. Ensure you have Java 8 or 11 installed, Docker for the emulator, and Azure Developer CLI. ```bash cd /samples/durable-task-sdks/java/function-chaining ``` -------------------------------- ### Get Orchestration Status in TypeScript (Durable Task SDK) Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-instance-management This TypeScript example demonstrates how to get the state of an orchestration instance using the Durable Task SDK. Ensure you have the correct connection string to initialize the client. ```typescript import { createAzureManagedClient } from "@microsoft/durabletask-js-azuremanaged"; const client = createAzureManagedClient(connectionString); // Get the status of an orchestration instance const state = await client.getOrchestrationState(instanceId, true); if (state) { const status = state.runtimeStatus; // do something based on the current status } ``` -------------------------------- ### Initialize Client Work Items in Python Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-task-scheduler/quickstart-portable-durable-task-sdks?source=recommendations&tabs=linux Prepares input data for the orchestration based on command-line arguments. ```Python # Generate work items (default 10 items if not specified) count = int(sys.argv[1]) if len(sys.argv) > 1 else 10 work_items = list(range(1, count + 1)) logger.info(f"Starting new fan out/fan in orchestration with {count} work items") ``` -------------------------------- ### Start Orchestration from Entity Operation Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-dotnet-entities Example of triggering a new orchestration from within an entity operation when a condition is met. ```C# public void Add(int amount) { if (this.Value < 100 && this.Value + amount >= 100) { Entity.Current.StartNewOrchestration("MilestoneReached", Entity.Current.EntityId); } this.Value += amount; } ``` -------------------------------- ### Construct SQL Connection Strings Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/quickstart-mssql Examples for building connection strings for managed identity or standard password authentication. ```Bash dbserver= sqlDB= clientId= sqlconnstr="Server=tcp:$dbserver.database.windows.net,1433;Initial Catalog=$sqlDB;Persist Security Info=False;User ID=$clientId;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Authentication='Active Directory Managed Identity';" ``` ```Bash dbserver= sqlDB= username= password= sqlconnstr="Server=tcp:$dbserver.database.windows.net,1433;Initial Catalog=$sqlDB;Persist Security Info=False;User ID=$username;Password=$password;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" ``` -------------------------------- ### JavaScript Orchestrator Function Example (V4 Model) Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-sequence An example of a JavaScript orchestrator function using the V4 programming model. It calls an activity function multiple times with different inputs. Ensure 'durable-functions' v3.x is installed. ```javascript const df = require("durable-functions"); const helloActivityName = "sayHello"; df.app.orchestration("helloSequence", function* (context) { context.log("Starting chain sample"); const output = []; output.push(yield context.df.callActivity(helloActivityName, "Tokyo")); output.push(yield context.df.callActivity(helloActivityName, "Seattle")); output.push(yield context.df.callActivity(helloActivityName, "Cairo")); return output; }); ``` -------------------------------- ### Navigate to JavaScript SDK sample directory Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-task-scheduler/quickstart-portable-durable-task-sdks?source=recommendations&tabs=linux Change directory to the JavaScript SDK sample for Durable Task Scheduler. ```bash cd samples/durable-task-sdks/javascript/fan-out-fan-in ``` -------------------------------- ### HTTP Orchestration Lifecycle Requests Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-sequence Examples of HTTP requests to start, monitor, and retrieve results from Durable Functions orchestrations. ```http POST http://{host}/orchestrators/E1_HelloSequence ``` ```http HTTP/1.1 202 Accepted Content-Length: 719 Content-Type: application/json; charset=utf-8 Location: http://{host}/runtime/webhooks/durabletask/instances/96924899c16d43b08a536de376ac786b?taskHub=DurableFunctionsHub&connection=Storage&code={systemKey} (...trimmed...) ``` ```http GET http://{host}/runtime/webhooks/durabletask/instances/96924899c16d43b08a536de376ac786b?taskHub=DurableFunctionsHub&connection=Storage&code={systemKey} ``` ```http HTTP/1.1 200 OK Content-Length: 179 Content-Type: application/json; charset=utf-8 {"runtimeStatus":"Completed","input":null,"output":["Hello Tokyo!","Hello Seattle!","Hello London!"],"createdTime":"2017-06-29T05:24:57Z","lastUpdatedTime":"2017-06-29T05:24:59Z"} ``` -------------------------------- ### Create and Upload Sample Files to Azure Files Share Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/tutorial-durable-text-analysis-azure-files?tabs=mount-config Bash script to create sample text files, upload them to an Azure Files share, and then clean up the local files. Requires Azure CLI. ```bash # 2. Upload sample text files to Azure Files # --------------------------------------------------------------------------- echo "📝 Creating sample text files..." cat > sample1.txt << 'EOF' The Azure Functions Flex Consumption plan provides optimal cost-efficiency for serverless workloads. It automatically scales based on demand and charges only for the resources actually consumed during execution. This makes it ideal for workloads with variable traffic patterns, batch processing jobs, and event-driven architectures where requests can spike unpredictably. Key benefits include per-second billing, automatic scaling to zero when idle, and the ability to set maximum instance counts to control costs. The plan supports multiple language runtimes including Python, Node.js, and .NET. EOF cat > sample2.txt << 'EOF' Durable Functions enable stateful workflows in serverless environments without requiring developers to manage state persistence manually. The framework provides several application patterns including function chaining, fan-out and fan-in, async HTTP APIs, monitoring, and human interaction. The fan-out/fan-in pattern is particularly powerful for parallel processing tasks. An orchestrator function can dispatch work to multiple activity functions simultaneously, wait for all of them to complete, and then aggregate the results. This is perfect for scenarios like batch processing, map-reduce operations, and parallel data analysis across multiple files or data sources. EOF cat > sample3.txt << 'EOF' Azure Files provides fully managed file shares in the cloud that are accessible via the industry-standard SMB and NFS protocols. When mounted as OS-level shares in Azure Functions Flex Consumption apps, they enable functions to read and write files using standard filesystem APIs — no SDK or special client needed. This is especially useful for scenarios that require shared state between function instances, large binary tools like FFmpeg, or processing pipelines that work with files on disk. The mount appears as a regular directory path such as /mounts/data/ and supports concurrent reads from multiple instances. EOF echo "⬆️ Uploading sample files to Azure Files share..." ACCOUNT_KEY=$(az storage account keys list \ --resource-group "$RESOURCE_GROUP" \ --account-name "$STORAGE_ACCOUNT" \ --query "[0].value" -o tsv) az storage file upload --account-name "$STORAGE_ACCOUNT" --share-name "$FILE_SHARE" --source sample1.txt --account-key "$ACCOUNT_KEY" az storage file upload --account-name "$STORAGE_ACCOUNT" --share-name "$FILE_SHARE" --source sample2.txt --account-key "$ACCOUNT_KEY" az storage file upload --account-name "$STORAGE_ACCOUNT" --share-name "$FILE_SHARE" --source sample3.txt --account-key "$ACCOUNT_KEY" rm -f sample1.txt sample2.txt sample3.txt echo "✅ Sample text files uploaded to Azure Files." echo "" ``` -------------------------------- ### HTTP Triggered Orchestration Polling Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-custom-orchestration-status?source=recommendations&tabs=csharp Examples of starting an orchestration via HTTP and polling for a custom status before returning a response. ```csharp [FunctionName("HttpStart")] public static async Task Run( [HttpTrigger(AuthorizationLevel.Function, methods: "post", Route = "orchestrators/{functionName}")] HttpRequestMessage req, [DurableClient] IDurableOrchestrationClient starter, string functionName, ILogger log) { // Function input comes from the request content. dynamic eventData = await req.Content.ReadAsAsync(); string instanceId = await starter.StartNewAsync(functionName, (string)eventData); log.LogInformation($"Started orchestration with ID = '{instanceId}'."); DurableOrchestrationStatus durableOrchestrationStatus = await starter.GetStatusAsync(instanceId); while (durableOrchestrationStatus.CustomStatus.ToString() != "London") { await Task.Delay(200); durableOrchestrationStatus = await starter.GetStatusAsync(instanceId); } HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(JsonConvert.SerializeObject(durableOrchestrationStatus)) }; return httpResponseMessage; } } ``` ```javascript const df = require("durable-functions"); module.exports = async function(context, req) { const client = df.getClient(context); // Function input comes from the request content. const eventData = req.body; const instanceId = await client.startNew(req.params.functionName, undefined, eventData); context.log(`Started orchestration with ID = '${instanceId}'.`); let durableOrchestrationStatus = await client.getStatus(instanceId); while (durableOrchestrationStatus.customStatus.toString() !== "London") { await new Promise((resolve) => setTimeout(resolve, 200)); durableOrchestrationStatus = await client.getStatus(instanceId); } const httpResponseMessage = { status: 200, body: JSON.stringify(durableOrchestrationStatus), }; return httpResponseMessage; }; ``` ```python import json import logging import azure.functions as func import azure.durable_functions as df from time import sleep async def main(req: func.HttpRequest, starter: str) -> func.HttpResponse: client = df.DurableOrchestrationClient(starter) instance_id = await client.start_new(req.params.functionName, None, None) logging.info(f"Started orchestration with ID = '{instance_id}'.") durable_orchestration_status = await client.get_status(instance_id) while durable_orchestration_status.custom_status != 'London': sleep(0.2) durable_orchestration_status = await client.get_status(instance_id) return func.HttpResponse(body='Success', status_code=200, mimetype='application/json') ``` -------------------------------- ### Upload Sample Files to Azure Files via Bash Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/tutorial-durable-text-analysis-azure-files Creates local sample text files and uploads them to an Azure Files share using the Azure CLI. ```bash # 2. Upload sample text files to Azure Files # --------------------------------------------------------------------------- echo "📝 Creating sample text files..." cat > sample1.txt << 'EOF' The Azure Functions Flex Consumption plan provides optimal cost-efficiency for serverless workloads. It automatically scales based on demand and charges only for the resources actually consumed during execution. This makes it ideal for workloads with variable traffic patterns, batch processing jobs, and event-driven architectures where requests can spike unpredictably. Key benefits include per-second billing, automatic scaling to zero when idle, and the ability to set maximum instance counts to control costs. The plan supports multiple language runtimes including Python, Node.js, and .NET. EOF cat > sample2.txt << 'EOF' Durable Functions enable stateful workflows in serverless environments without requiring developers to manage state persistence manually. The framework provides several application patterns including function chaining, fan-out and fan-in, async HTTP APIs, monitoring, and human interaction. The fan-out/fan-in pattern is particularly powerful for parallel processing tasks. An orchestrator function can dispatch work to multiple activity functions simultaneously, wait for all of them to complete, and then aggregate the results. This is perfect for scenarios like batch processing, map-reduce operations, and parallel data analysis across multiple files or data sources. EOF cat > sample3.txt << 'EOF' Azure Files provides fully managed file shares in the cloud that are accessible via the industry-standard SMB and NFS protocols. When mounted as OS-level shares in Azure Functions Flex Consumption apps, they enable functions to read and write files using standard filesystem APIs — no SDK or special client needed. This is especially useful for scenarios that require shared state between function instances, large binary tools like FFmpeg, or processing pipelines that work with files on disk. The mount appears as a regular directory path such as /mounts/data/ and supports concurrent reads from multiple instances. EOF echo "⬆️ Uploading sample files to Azure Files share..." ACCOUNT_KEY=$(az storage account keys list \ --resource-group "$RESOURCE_GROUP" \ --account-name "$STORAGE_ACCOUNT" \ --query "[0].value" -o tsv) az storage file upload --account-name "$STORAGE_ACCOUNT" --share-name "$FILE_SHARE" --source sample1.txt --account-key "$ACCOUNT_KEY" az storage file upload --account-name "$STORAGE_ACCOUNT" --share-name "$FILE_SHARE" --source sample2.txt --account-key "$ACCOUNT_KEY" az storage file upload --account-name "$STORAGE_ACCOUNT" --share-name "$FILE_SHARE" --source sample3.txt --account-key "$ACCOUNT_KEY" rm -f sample1.txt sample2.txt sample3.txt echo "✅ Sample text files uploaded to Azure Files." echo "" ``` -------------------------------- ### Navigate to Durable Task SDK Sample Directory (JavaScript) Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-task-scheduler/quickstart-container-apps-durable-task-sdk Navigate to the JavaScript sample directory for Durable Task SDKs. Ensure you have Node.js 22 or later installed, Docker for the emulator, and Azure Developer CLI. ```bash cd /samples/durable-task-sdks/javascript/function-chaining ``` -------------------------------- ### Orchestration Status Response Examples Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/quickstart-java?source=recommendations JSON responses showing the initial orchestration start status and the final completed status with output. ```json { "id": "d1b33a60-333f-4d6e-9ade-17a7020562a9", "purgeHistoryDeleteUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/d1b33a60-333f-4d6e-9ade-17a7020562a9?code=ACCupah_QfGKo...", "sendEventPostUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/d1b33a60-333f-4d6e-9ade-17a7020562a9/raiseEvent/{eventName}?code=ACCupah_QfGKo...", "statusQueryGetUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/d1b33a60-333f-4d6e-9ade-17a7020562a9?code=ACCupah_QfGKo...", "terminatePostUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/d1b33a60-333f-4d6e-9ade-17a7020562a9/terminate?reason={text}&code=ACCupah_QfGKo..." } ``` ```json { "name": "Cities", "instanceId": "d1b33a60-333f-4d6e-9ade-17a7020562a9", "runtimeStatus": "Completed", "input": null, "customStatus": "", "output":"TOKYO, LONDON, SEATTLE, AUSTIN", "createdTime": "2022-12-12T05:00:02Z", "lastUpdatedTime": "2022-12-12T05:00:06Z" } ``` -------------------------------- ### Start a sub-orchestration with a specific version Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-orchestration-versioning Use these examples to call a sub-orchestrator from within an existing orchestrator function using a specific version. ```C# [Function("MainOrchestrator")] public static async Task RunMainOrchestrator( [OrchestrationTrigger] TaskOrchestrationContext context) { var subOptions = new SubOrchestratorOptions { Version = "1.0" }; var result = await context.CallSubOrchestratorAsync( "ProcessPaymentOrchestrator", orderId, subOptions); // ... ``` ```JavaScript const RunMainOrchestrator: OrchestrationHandler = function* (context: OrchestrationContext) { const paymentResult = yield context.df.callSubOrchestrator( "ProcessPaymentOrchestrator", orderId, { version: "1.0" } ); // ... }; ``` ```Python @myApp.orchestration_trigger(context_name="context") def run_main_orchestrator(context: df.DurableOrchestrationContext): payment_result = yield context.call_sub_orchestrator( "ProcessPaymentOrchestrator", order_id, version="1.0" ) # ... ``` ```PowerShell param($Context) $paymentResult = Invoke-SubOrchestrator -FunctionName "ProcessPaymentOrchestrator" -Input $orderId -Version "1.0" ``` -------------------------------- ### Client Output Example Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-sequence Sample output showing the result of a chained orchestration. ```text Started orchestration with ID: abc123 Orchestration completed with result: "Hello World! How are you today? I hope you're doing well!" ``` -------------------------------- ### Start Orchestration with C# Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-bindings Demonstrates starting an orchestration using the Durable Functions client in C# for both in-process and isolated process models. ```C# [FunctionName("QueueStart")] public static Task Run( [QueueTrigger("durable-function-trigger")] string input, [DurableClient] IDurableOrchestrationClient starter) { // Orchestration input comes from the queue message content. return starter.StartNewAsync("HelloWorld", input); } ``` ```C# [Function("QueueStart")] public static Task Run( [QueueTrigger("durable-function-trigger")] string input, [DurableClient] DurableTaskClient client) { // Orchestration input comes from the queue message content. return client.ScheduleNewOrchestrationInstanceAsync("HelloWorld", input); } ``` -------------------------------- ### Get detailed help for a specific cmdlet Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-powershell-v2-sdk-migration-guide Displays full documentation, including usage examples, for the specified Durable Functions cmdlet. ```PowerShell Get-Help Invoke-DurableOrchestration -Full ``` -------------------------------- ### Example Worker Output Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-task-scheduler/quickstart-portable-durable-task-sdks?source=recommendations&tabs=linux This output indicates that the Durable Functions worker has started, connected to the local emulator, and is ready to process work items. ```text Starting Fan Out/Fan In pattern worker... Using taskhub: default Using endpoint: http://localhost:8080 Starting gRPC worker that connects to http://localhost:8080 Successfully connected to http://localhost:8080. Waiting for work items... ``` -------------------------------- ### Clone the sample repository Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/tutorial-durable-text-analysis-azure-files Initializes the local environment by cloning the Azure Functions sample repository. ```Bash git clone https://github.com/Azure-Samples/Azure-Functions-Flex-Consumption-with-Azure-Files-OS-Mount-Samples.git ``` -------------------------------- ### Initial HTTP-Triggered Function Response Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/quickstart-java This is an example of the initial response from an HTTP-triggered Durable Function. It confirms the orchestration has started and provides URIs for further interaction, such as checking status. ```json { "id": "d1b33a60-333f-4d6e-9ade-17a7020562a9", "purgeHistoryDeleteUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/d1b33a60-333f-4d6e-9ade-17a7020562a9?code=ACCupah_QfGKo...", "sendEventPostUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/d1b33a60-333f-4d6e-9ade-17a7020562a9/raiseEvent/{eventName}?code=ACCupah_QfGKo...", "statusQueryGetUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/d1b33a60-333f-4d6e-9ade-17a7020562a9?code=ACCupah_QfGKo...", "terminatePostUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/d1b33a60-333f-4d6e-9ade-17a7020562a9/terminate?reason={text}&code=ACCupah_QfGKo..." } ``` -------------------------------- ### Device Provisioning Orchestration (In-Process Model) Source: https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-sub-orchestrations Demonstrates a device provisioning workflow using the in-process model in C#. This version differs in how the orchestration context is accessed and input is retrieved. ```csharp public static async Task DeviceProvisioningOrchestration( [OrchestrationTrigger] IDurableOrchestrationContext context) { string deviceId = context.GetInput(); // Step 1: Create an installation package in blob storage and return a SAS URL. Uri sasUrl = await context.CallActivityAsync("CreateInstallationPackage", deviceId); // Step 2: Notify the device that the installation package is ready. await context.CallActivityAsync("SendPackageUrlToDevice", Tuple.Create(deviceId, sasUrl)); // Step 3: Wait for the device to acknowledge that it has downloaded the new package. await context.WaitForExternalEvent("DownloadCompletedAck"); // Step 4: ... } ```