Tuesday, June 14, 2022

Create and Use Azure functions in .Net Core

 Azure functions  

What : Azure function is a small pieces of code/small program which runs on cloud. Azure function is serverless i.e. no need to worry about infrastructure ,scaling etc. everything handled by provider for you. Basically it’s a Event triggered code.Keep in mind you should not write huge block of code or use as a replacement of webapi ,function should be lightweight and small piece of code.

Why to Use- We can use azure function when we have requirement to run program which might takes time.

o   File Processing

o   Scheduled Tasks

o   Reminders and Notifications

o   Sending background emails

o   Running background backup tasks

Language/script support

 All types of programming language support like C#,Java, JavaScript etc.

Types :Event triggered code

  •       HTTP trigger
  •       Timer Trigger
  •       Blob Trigger
  •       Event Grid Trigger
  •       Event Hub Trigger
  •       Queue Trigger
  •       Service Bus Trigger and so many other triggers through which azure function can run.

Prerequisites:

  •     Install azure development sdk in visual studio

Here we are going to focus Http trigger and Blob Trigger only.

Http Trigger- As per naming it a http request call , function execute when we send http request

Lets see how to create and use this ,good thing is that we don’t need to deploy azure function for testing during development in visual studio there is storage emulator which can be used for development and testing :

To create follow the steps :

Open Visual Studio -> Create New Project -> Search for Azure functions Templates and click Next

1.      .


1.Enter project name “azfunctionHttpTrigger” and click Next

2.In next section you need to select Trigger Type ,so select HttpTrigger and keep storage emulator in right side , if you want to use azure storage you can browse and choose.

3.In authorization field leave default one i.e function 

 



In solution explorer you can see project created with 3 files

  •       Function1.cs
  •       Host.json
  •       local.settings.json



Let see uses of these files

Local.settings.json : In this file configure storage account and runtime framework. It has key-value code.

{

    "IsEncrypted": false,

    "Values": {

        "AzureWebJobsStorage": "UseDevelopmentStorage=true",

        "FUNCTIONS_WORKER_RUNTIME": "dotnet"

    }

}

AzureWebJobsStorage : can be replaced with azure storage connection string otherwise for development you can keep as it is.


Host.json : I will explain bit later.

Function1.cs: This is the class where you will put your logic what you want to get done from this app.Since we selected HttpTrigger ,automatically added template .just need to replace required code in the code block. 

Lets rename function name as ‘azhttpTriggeredFunction

Default :

public static class Function1

    {

        [FunctionName("Function1")]

        public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,

            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;
            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);

        }
    }

 

Now lets run and see if function is working or not.press F5 and see the output.

.

If you observe the above output  ,you can see the url for http call. Copy this url and paste in browser

http://localhost:7071/api/azhttpTriggeredFunction and you can see the below output



Now Lets see details in this function :

[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]


Http request method -get ,post. At template creation time it added by default. Can be removed one of them as required.

Route – This is the endpoint for http request.You can change the route name as "routeName"/{name}(query string). So url with new route name will be formed.

If you have noticed in the url http://localhost:7071/api/azhttpTriggeredFunction  ,

api has been appended . this is the default route prefix which is added. If you need to change this you can change in host.json.



Lets change route prefix as apiPrefix

http://localhost:7071/apiPrefix/azhttpTriggeredFunction new url with changed prefix.

Pass query string value in the url http://localhost:7071/apiPrefix/azhttpTriggeredFunction?name=%27manoj%27 and out put will be below

 



Thats it for httpTriggered function .In next section will see BlobTriggered.


 you can download all the azure samples code : https://github.com/mkumar8184/azure-sdk-services-samples

1 comment:

  1. a to z what I was looking for about azure function

    ReplyDelete

Thanks for your valuable comments

Convert Html to Pdf in azure function and save in blob container

 In this post  I am going to create an azure function ( httpTrigger ) and send html content  which will be converted into PDF and save in bl...