Simple Azure Durable function implementation 24st July 2021

howtoimplement

We have already discussed quite a bit about Azure Durable Functions. I did write up on a bit of history and why we need Azure Durable functions. You can read my blogs here to get more information.Links: Why do we need Azure Durable Functions and its history
I also wrote about What are Azure durable functions
What is difference between Azure Durable Function and Logic Apps
Patterns and Best Practises - Azure Durable Functions

All above is good but nothing better than actual implementation.And I wanted to keep things simple and straightforward. In this blog, I will implement  Azure Durable functions in the simplest possible way. I will show you step by step approach so that you don't get stuck. What will you need?

  • Some basic understanding of Azure Durable Functions. If you are not aware please read my blogs.Links given at the top of this blog
  • Visual Studio Code
  • Postman client

Create the project
1.
Open Visual Studio Code
2.
Go to Extensions. Img below
extensions

3.
Install below 2 extensions if you dont have them already
  • Azure Functions. Image below

  • azurefunctionsextension

  • C#.Image below
    cextension

4.
Then just follow the steps to create the project
  • Get to Command Palette. You can get to Command Palette by either clicking on View tab in Visual Studio. You can also press Cntl+Shift+P to get to Command Palette

    Please refer image below extensions

  • Select the type of project you want to create.I selected Azure Functionscreatenewproject

  • Select the folder you want to create your project in
  • Select the programming language you want to build you Azure Function in. I selected C#
  • Select the template for your project's first function. I chose DurableFunctionsOrchestration
    selecttemplate

  • Provide the function name, namespace . I chose default one. I named it DurableFunctionsOrchestrationCSharp1 ,gave namespace as Company.Function
5.
Now your project is created.Link it with storage account. You need to have your Azure Login or create a new Azure Login
6.
Once you login to Azure succesfully, you will be prompted to Select storage account or Create New Storage account
createnewstorageaccount

I just selected an existing storage account. The reason you need storage account is because you want to save the state of your function and it needs to be saved somewhere for later recovery.
7.
Then you just need to choose how you want to open your project. I want it to open in current window so I select that option.Once you select that your project will be created and you will see few files created including DurableFunctionsOrchestrationCSharp1.cs file we created in the Company.function namespace.The class also has few default functions with some sample code in it.It's given so that you can kickstart the project quickly without much of typing. Image for reference below
filesavailableafterprojectcreation

Above all will be same for you too except the orhestration.cs file which in my case is DurableFunctionsOrchestrationCSharp1.cs which is the name I gave. Second thing you will see different is ofcourse the .csproj filename which in my case is learnAzureFunctions.csproj because I created the function in learnAzureFunctions folder(I selected that folder in step 4 above)
8.
Above, like I mentioned in above point, there are three functions generated for you. Each functions has a FunctionName assoicated with it. It is done using FunctionName("**name of the function**") keyword. Runtime will know what these functions are and will create endpoints and clients will know how to call them

Lets discuss the code
There are three functions,namely:
  • HttpStart function
  • Orchestrator function
  • Activity function
Let's look at each one of them in detail:

HttpStart function
It all starts with HttpStart function, the one that kicks off everything.Image for reference below.
httpstart

This is the method which gets exposed to clients.This method takes 3 inputs
  • req- is of type "IHttpRequestMessage".It is incoming web request.This parameter is decorated by "HttpTrigger".HttpTrigger takes 2 parameteres of it's own,one "AuthorzationLevel" and the other 2 strings "get" and "post". Basically, it's listening to GET and POST requests from client
  • starter- is of type "IDurableOrchestrationClient"- this allows us to control the flow.It is the starter instance that calls "StartNewAsync()"" which produces "instance id". This instanceid helps us keep track of the workflow. Starter instance also allows to create an HTTP response by calling "CreateCheckStatusResponse()"
  • log is of type ILogger- Allows us to log messages. This can help us to debug while developing the code as these will be visible in the terminal.
Orchestrator function
Orchestrator function is the core of Azure Durable functions.We can say that this is where core of action happens beause we set up our flow here.We decide 3 W's i.e What,When and Why activity functions needs to be called. Lets look at Orchestrator code here.
orchestrator

There are three things to be noted above. I have marked them in red i.e 1,2 and 3
  • 1. is the orchestration function name. In this case DurableFunctionsOrchestrationCSharp1.
  • 2. It actually calls the activity function. My activity function is named DurableFunctionsOrchestrationCSharp1_Hello
  • 3. It is the parameter the Orchestrator function takes. It is of type IDurableOrchestrationContext. This parameters allows us to control the flow and also call the activity functions using CallActivityAsync method
Activity function
This is where the tasks are actually getting done.In our case the activity function is called DurableFunctionsOrchestrationCSharp1_Hello. Image for ref below
activityfunction

Above is the simplest activity function we can ever write. It just returns with a "hello **name**" where name is the value passed to it. Obviously, this particular egample has no much business value. In reality, this function may actually call a database, or call some API etc. It will get the data . Orchestrator function has no choice but to wait for this function to finish.


Let's get more handson
I love to debug as this opens up our understanding and helps us get hold over the code flow better. In order to debug, you need to actually call the client function using Postman.Let's see the steps below

Start Debugger
In VS code menu,click on Run/Start--> Debugging. Image for reference below

rundebugger

In order to debug the code,you must have Azure Function Core Tools installed. You will get a prompt if you don't have one.Prompt will redirect you to github link Github link to download core tools
Download the MSI that suits your machine. I downloaded Windows 64-bit MSI. Image for reference below
githublinktodownloadcoretools

Just follow default setup and install the MSI. Incase even after installing tools you are unable to run in debug mode, restart the visual studio code

See the terminal
Once you succesfully start in debug mode, watch your terminal, you should see something like below
terminalexposestheurl

Above you see the endpoint that clients can call and also the HTTP verbs exposed (GET and POST)

Install and use Postman
Postman is a client tool to hit HTTPEndpoints and test your API's quickly. You can install Postman app on your windows machine OR use Postman Web client too. For more details please refer my blogs on Postman Link here
You can also watch my youtube videos, if you dont like to read but instead want to watch and learn. Link to video

Call our client function route
  • To kick everything off, we need to hit the above URL "../api/DurableFunctionsOrchestrationCSharp1_HttpStart" .This is the URL we got in the terminal Use Postman to hit the above URL. Image below

    postmanapigethttpstart
  • Give a breakpoint in the HTTPStart function and then click the "Send" on Postman client (step above).Image for reference below
    postmanapigethttpstart_debughit

    let the debugger proceed
  • Now it will hit the orchestrator postmanapiorchestrator_debughit

    let the debugger go again
  • Now it will hit the activity function postmanapigetactivity_debughit

    let the debugger go again
  • Now it gets interesting, we hit orchestrator again.We start at first line but then go to second line before activity function is called.Thats because orchestrator now knows from it's history that it executed first line and the current pass is the second pass postmanapiorchestrator_secondpass_debughit

  • Now once activity function runs it will go back to Orchestrator function again and run for the third time with parameter as "London".It will keep going like this back and forth,between activity function and orchestrator until orchestrator is done.
HttpStart response

Once you run above, you will get below response on the client. In this case since we are using Postman you can see the response in the Postman Client
Image for ref below postmanresponse
What you should know is that what did orchestrator actually produce. For that you have to click on statusQueryGetApi and do another postman request.This time you will see below response. Image for ref below resultofStatusQueryGetUri
What we get as response is array consisting of the responses from all activity functions



Conclusion.

To conclude,I hope you would have got the basics of various application patterns available and that can benefit from Azure Durable function.

Email me at "techspacedeck@gmail.com" incase you have queries. Alternatively, you can fill the "CONTACT" form or drop a comment below

Did you like the blog or have questions, please add your comments