How To Create Azure Functions In Visual Studio

How To Create Azure Functions In Visual Studio

In this Azure tutorial, we will discuss How To Create Azure Functions In Visual Studio. Along with this, we will also discuss the below topics.

  • How To Create Azure Functions In Visual Studio 2019
  • How To Create Azure Function Apps In The Azure Portal
  • How to write a azure functions
  • Deploying the Azure Function using Visual Studio
  • Deploying the Azure Function using Visual Studio 2019

How To Create Azure Functions In Visual Studio

Well, Let’s Discuss How To Create Azure Functions In Visual Studio. You can able to develop the Azure Functions using Visual Studio, just like you develop a .NET Project. When you are choosing the Visual Studio as IDE to develop the Azure Function, you will get a lot of benefits out of it like you can able built, debug and test the functionality in your local machine properly before moving to the Cloud.

Once you will develop and test your Azure function successfully in your local machine, you can able to publish your Azure Function directly from your local environment to the Azure directly with the help of Visual Studio in a fraction of seconds.

You can write the code for your function in C# and also you can use the C# attribute to declare your Azure Function and utilize all the benefits of Visual Studio.

In this article, we will see how to develop and deploy the Azure Functions using Visual Studio. We will be creating a new Azure Function project. We will see how we can build and run the Project in our local environment and then we will see how we can publish that to Azure from our Visual Studio.

We will learn here Creating an Azure Functions app in Visual Studio 2019 and Deploying the Azure Functions using Visual Studio 2019.

Before starting the actual development activities, we need few thing as a Prerequisites

Prerequisites

  • The first thing we need is an Azure Account or Azure Subscription. If you don’t have an Azure Account till now, create an Azure Free Account now.
  •  Visual Studio 2019 with Azure development workload installed. If you don’t have Visual Studio 2019 installed in your machine, install Visual Studio 2019 now.
  • We need Updated Azure Function tools
  • An Azure Storage Account. If you don’t have an Azure Storage Account till now, create an Azure Storage Account now.

Now Let’s discuss How To Create Azure Functions In Visual Studio.

Creating an Azure Functions app in Visual Studio 2019

Let’s follow the below steps for Creating an Azure Functions app in Visual Studio 2019. So we will use the latest version of Visual Studio i.e Visual Studio 2019 for our development activities. As part of the development activity, we will create the Azure Function first, and then after we will see Deploying the Azure Functions using Visual Studio.

Step-1: Open the Visual Studio 2019.

How To Create Azure Functions In Visual Studio

Step-2: Once the Visual Studio loaded successfully, click on the Create a new project button from the Get started window.

How To Create Azure Functions In Visual Studio 2019

Step-3: On the Create a new project window, Search for the Azure Functions template and choose the Azure Functions and then click on the Next button.

Develop And Deploy Azure Function Using Visual Studio

Step-4: On the Configure Your new Project window, Enter the Project name, and choose a location where you want to create the project and then click on the Create button.

how to create an Azure function, debug and push to Azure environment using Visual Studio 2019

Step-5: On the Create a new Azure Functions Application window, we need to choose the trigger for our Azure Function, so choose the Http trigger as the trigger option and For the Storage Account (AzureWebJobsStorage) option, select Storage Emulator and Choose the Authorization level option as Function. So basically keep all the default options as it is as of now.

Creating an Azure Functions app in Visual Studio

Step-6: Now if you can see below the Project got created successfully without any issue.

Creating an Azure Functions app in Visual Studio 2019

Step-7: Open the local.settings.json file and check it contains the below piece of code with a key-value pair of Azure Storage connection string.

{
    "IsEncrypted": false,
    "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet"
    }
}
Create Azure Functions In Visual Studio

Step-8: If you will open the Function1.cs file, you can able to see a predefined method like below

This function will help to perform both the get and post-operation. if you are performing a GET request, then it will get the value from the query string in the URL with the key as name and if you are performing a POST operation it will get name key value from the request body and then it will return with the string “Hello {name value}” to us.

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

            return name != null
                ? (ActionResult)new OkObjectResult($"Hello, {name}")
                : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
        }
Build Your First Azure Function in Visual Studio

Now Press F5 to run the project and once it runs successfully, We can check with the post man tool if it is working fine

Creating Azure Functions in Visual Studio 2019

Now open the Post man app and then try to run the above endpoint http://localhost:7071/api/Function1. You can able to see, we got the desired output.

How to create Azure functions in Visual Studio 2017

So, We performed the GET operation, Now the time came to see the post-operation. Let’s modify the function a bit and remove the GET from there only we will keep POST only there like below.

 [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            // string jsonContent = await req.Content.ReadAsStringAsync();
            //string jsonContent = await req.Content.ReadAsStringAsync();
            //var myDetails = JsonConvert.DeserializeObject<UserDetails>(jsonContent);
            //log.LogInformation($"Order {myDetails.UserId} received from {myDetails.UserEmail} for product{myDetails.UserId}");
            //await outputQueue.AddAsync(myDetails);


            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;

            return name != null
                ? (ActionResult)new OkObjectResult($"Hello, {name}")
                : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
        }

Function should look like exactly below

Create Azure Functions In Visual Studio 2019

Now Run the application by pressing F5 or you can click on the Start Debugging option. You can see the below screen. Copy the function URL http://localhost:7071/api/Function1.

Create Azure Functions In Visual Studio 2017

Open the Postman app and paste the URL there and select the Post option there and click on the Send button. Now it will show you “Please pass a name on the query string or in the request body”.

create azure function in visual studio 2015

Now we need to provide a query string parameter along with the URL and then again click on the Send button. Now if you can see below, we got the expected output and the Status code is 200 OK.

Create a function in Azure using Visual Studio

You can also debug the function by putting the breakpoint in the function and make a request. You can able to see now, the name parameter set to “Raj” as shown in the below screen shot.

Create a function in Azure using Visual Studio 2019

This is How To Create Azure Functions In Visual Studio 2019 by following the above steps.

Deploying the Azure Function using Visual Studio 2019

Well, Let’s discuss here the steps for Deploying the Azure Function using Visual Studio 2019.

Step-1: The first step is, Right-click on the project from Solution Explorer and select the “Publish” Option like below.

Deploying the Azure Function using Visual Studio

Step-2: On the Pick a publish target window, choose the Azure Functions Consumption Plan and then you can select the Existing plan if you have or Choose the Create New option and then click on the Create Profile button to create the new Azure Functions Consumption Plan.

Deploying the Azure Function using Visual Studio

Step-3: Now on the App Service window, Provide a name, choose your subscription, Choose your Resource group, Select the Location and then choose your Existing Storage Account or click on the New button to create a new Azure Storage Account and then finally click on the Create button.

Deploying the Azure Function using Visual Studio 2017

Step-4: Now you can see the publish profile will be created like below. Now click on the Publish button.

Deploying the Azure Function using Visual Studio 2015

Step-5: Now You can able to see the App services that we have created.

Deploying the Azure Function using Visual Studio IDE

Now click on that, and then click on the Functions from the left navigation, you can able to see the Function that you published from the VisualStudio.

publish azure function from visual studio 2019

Click on the Function. In my case, it is Function1 and then clicks on the Get Function Url. Now click on the Copy button to copy the complete function URL as highlighted below

publish azure function from visual studio

Now you can Use this URL in the Postman app to check if it is working fine.

The URL will be like below

https://mydemoazurefunction20200809135307.azurewebsites.net/api/Function1?code=vXBC2oPeWSbJimTNWpnLVjPJomatnBhWc21GTZPtE8Dap3ufxnT1LA==

Open the Postman app again and paste the above URL there and choose the POST option, now click on the Send button. It is asking to pass a name on the query string or in the request body.

create azure function in visual studio 2017

Now Choose the raw option and then select the JSON format and use exactly the same format as below for the name parameter and specify a name. You can able to see it provides us the expected output as below.

create azure function in visual studio 2019

So, we discussed Deploying the Azure Function using Visual Studio 2019 by following the above mentioned steps.

How To Create Azure Function Apps In The Azure Portal

Well, we have discussed above, How To Create Azure Functions In Visual Studio. Now, we will discuss, How To Create Azure Function Apps In The Azure Portal.

Before going to discuss the steps, as a prerequisites we need the below things

  • You should have a valid Azure Subscription or an Azure Account. If you don’t have an Azure Account till now, create an Azure Free Account now.
  • You should have an Azure Storage Account. If you don’t have a storage account till now, Create a storage account now.

How To Write a Azure Functions

Follow the below steps to create Azure functions in Azure portal.

Step-1: Login to Azure Portal (https://portal.azure.com/)

Step-2: Click on the + Create a resource and from the New Window, click on “Compute”. Now, choose “Function App”.

How To Create Azure Function Apps In The Azure Portal

Step-3: On the Create Function App window, on the Basics tag, provide the below details.

  • Subscription: Choose your Correct Subscription.
  • Resource Group: Choose your Existing Resource Group and if you don’t have any existing resource group, you can create a new one by clicking the Create new link.
  • Function App name: Enter a valid Function App name.
  • Publish: Choose the Code option.
  • Runtime stack: Choose the .NET Core Option.
  • Version: You can choose the 3.1
  • Region: Select the Region for the Function App.

Click on the Next : Hosting > button now.

Create Azure Function Apps In The Azure Portal

On the Hosting tab, Select the storage account or create a new storage account by clicking on Create new link.

Creating an Azure Function

Keep the default option for all other tabs as it is. The next is click on the Review + create button, Now it will validate all the fields and it will show the create button. Now click on the Create button to create the Function App.

Now, you can see the deployment is completed successfully.

How To Create Azure Function Apps Using The Azure Portal

Now you can see the new Azure function app is created Successfully.

Create Azure Function Apps Using The Azure Portal

So we have created our Azure Function App, Now we need to create the Functions. So click on the Functions link from the left navigation and click on the + Add button to create the Functions.

create azure functions in azure portal

The next is select the HTTP trigger on the New Function window.

create azure functions using azure portal

On the New Function Window, you can keep the default name as it is or you can provide a new name and then Choose the Authorization level as Function. Finally, click on the Create Function to create the function.

create azure function in azure

Now, you can see the Function created successfully.

create azure function using azure portal

Now you can see the function created successfully, click on the Code + Test link from the left navigation, Now you can able to see the inbuilt code in the right side editor. You can modify the code as per your requirement and then can click on the save button, it will save the changes.

create an azure function using azure portal

Now you can test the function, if it is working as expected. Click on the Test/Run button to test the function.

Then on the Input window, select the POST method, you can change the name parameter value in the Body also and then click on the Run button.

Steps to create an azure function using azure portal

Now you can see, we got the output and the HTTP response code as expected.

Steps to create an azure function in azure portal

Now i have just changed the name parameter value from Azure to Raj and then click on the run button.

Steps to create an azure function in azure

Now you can see the expected output and response code as below.

Steps to create an azure functions

Now what we will do is we will test this function App in the Postman app. So click on the Get function URL button from the top.

How To Create Azure Function Apps in Azure

On the Get function URL popup, click on the Copy button to copy the function URL

Create Azure Functions in Azure

The URL will be like below

https://mynewdemofunctionapp.azurewebsites.net/api/HttpTrigger1?code=Sa3jSz9JrrapsN27yscWZm8wHsUO/GIMKg4V9aIhIm4CmXBiYFBgDw==

Now open the Postman app and paste the URL choose the POST operation and provide the JSON parameter value in the body and then click on the Send button. Now you can able to see the expected output with the proper response code.

create a function app in azure

Now, I have modified a little bit in the code in the function in the Azure Portal as below and clicked on the Save button to save the changes.

create a function app in azure Portal

Now, to check if it is working as expected, Run the Postman app again. Now you can see below we got the expected response based on our update in Azure Function.

How To Create Azure Function In The Azure Portal

This is How To Create Azure Function Apps In The Azure Portal by following the above mentioned steps.

You may also like following the below articles

Conclusion

Well, in this article, we discussed How To Create Azure Functions In Visual Studio, Creating an Azure Functions app in Visual Studio 2019, How To Create Azure Functions In Visual Studio 2019, Deploying the Azure Function using Visual Studio, Deploying the Azure Function using Visual Studio 2019 and finally we discussed How To Create Azure Function Apps In The Azure Portal, how to write a azure functions.

Leave a Comment