Develop And Deploy Azure Function Using Visual Studio

Introduction

 
In my last article, we have seen how to develop Azure Functions using the Azure portal. That is good for experimenting but in a real scenario, we need to develop the functions in the local environment. Once it’s ready for production, we need to deploy it. In this article, I’m going to explain how to develop and deploy the Azure Functions using Visual Studio tooling.

Prerequisites
  • Visual Studio 2017 with Azure Development workload 
  • Azure Subscription 
  • Latest Azure Function tools
  • Basic knowledge of Azure Storage Service

What we will learn

  • Creating an Azure Functions app in Visual Studio
  • Deploying the Azure Functions using Visual Studio

Creating an Azure Functions app in Visual Studio


Step 1
 
Open Visual Studio, select New->Project from the file menu.

Step 2
 
In the "New Project" window, from the "Installed" section, click on Cloud >> Azure Functions template and name it. In my case, I named it as MyAzureFunction, as shown in the below figure.
 
 
 
Step 3
 
In the next window, we need to choose the trigger for our Azure Function. In my case, I have selected HTTP Trigger. For Storage Account, let it be Storage Emulator. Later, while deploying or doing bindings, we need to provide the Azure Storage Account connection string.

We can provide the access right to Function level or else, we can make it anonyms. By default, the access right will be at the Function level.
 
 
Once it is done, click OK to create a project.

Step 4
 
The project contains the class file and the local setting file named local.setting.json will contain a Key and value pair of Azure Storage connection string.
  1. {  
  2.     "IsEncrypted"false,  
  3.     "Values": {  
  4.         "AzureWebJobsStorage""UseDevelopmentStorage=true",  
  5.         "AzureWebJobsDashboard""UseDevelopmentStorage=true"  
  6.     }  
  7. }  

Right now, we are using Development Storage. The class file contains a predefined function with code.

  1. [FunctionName("MyFunctionDemo")]  
  2.     public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, TraceWriter log)  
  3.     {  
  4.         log.Info("C# HTTP trigger function processed a request.");  
  5.   
  6.         // parse query parameter  
  7.         string name = req.GetQueryNameValuePairs()  
  8.             .FirstOrDefault(q => string.Compare(q.Key, "name"true) == 0)  
  9.             .Value;  
  10.   
  11.         if (name == null)  
  12.         {  
  13.             // Get request body  
  14.             dynamic data = await req.Content.ReadAsAsync<object>();  
  15.             name = data?.name;  
  16.         }  
  17.   
  18.   
  19.         return name == null  
  20.             ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")  
  21.             : req.CreateResponse(HttpStatusCode.OK, "Hello " + name);  
  22.     }  
  23. }  
The above function will accept both get and post requests. If the request is GET type, it will get the value from the query string with the key as name and for POST, it will get a value of key name from the request body. Finally, it will respond with a string “Hello <name value>” to the user.
 
Let’s run the app and test it in Postman. 
 
 
 
Run the endpoint http://localhost:7071/api/MyFunctionDemo in the Postman tool.  
 
 
 
Yes, we got a response as expected. Let’s update the code by binding the Azure Queue. If you are new to Azure Queue Storage, please click here to learn about Azure Queue Storage.
 
I’m going to use my existing Storage Account. Let's update the connection string of the storage account in the local.setting.json file.
  1. {  
  2.     "IsEncrypted"false,  
  3.   "Values": {  
  4.     "AzureWebJobsStorage""<Give Your Storage Account Connection String>",  
  5.     "AzureWebJobsDashboard""UseDevelopmentStorage=true"  
  6.   }  
  7. }   

Let’s create a class called Order.cs.

  1. public class Order  
  2.  {  
  3.   
  4.      public string OrderId { getset; }  
  5.      public string ProductId { getset; }  
  6.      public string UserEmail { getset; }  
  7.      public decimal Price { getset; }  
  8.  }  
Now, go to MyFunctionDemo and update the code as given below.
  1. public static class MyFunctionDemo  
  2.     {  
  3.         [FunctionName("MyFunctionDemo")]  
  4.         public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, TraceWriter log,  
  5.             [Queue("orders", Connection = "AzureWebJobsStorage")] IAsyncCollector<Order> outputQueue)  
  6.         {  
  7.             string jsonContent = await req.Content.ReadAsStringAsync();  
  8.             var myOrder = JsonConvert.DeserializeObject<Order>(jsonContent);  
  9.             log.Info($"Order {myOrder.OrderId} received from {myOrder.UserEmail} for product{myOrder.ProductId}");  
  10.             await outputQueue.AddAsync(myOrder);  
  11.             
  12.             //return req.CreateResponse(HttpStatusCode.OK,new {message = $"Your Order is Placed, Thank you" });   
  13.             return  req.CreateResponse($"Your Order is Placed with Order Id {myOrder.OrderId}, Thank you");  
  14.         }  
  15.     }  

We have added one more parameter to the function which is for Queue, where we need to provide the Queue name and connection string key. And, I used a strongly-typed Collector. Basically, this function will deserialize the JSON payload which is sent through the request, add the message to the queue, and respond back to the user with some text message.
 
Let’s test the function in POSTMAN.
 
 
 
Yes, we received the response as expected. Let’s check the message in the Queue using the Azure Storage Explorer.
 
 
 
From the above figure, you can see the message in the queue with name orders.
 

Deploying the Azure Function using Visual Studio

 
Step 1
 
Right-click on the project from Solution Explorer and select "Publish". 
 
 
Step 2
 
In the "Create App Service" window, provide an app name which is unique. Provide your Azure subscription, then choose the existing resource group and Azure Storage. Else, you can create a new one; in my case, I have chosen the existing one.
 
 
 
Once all done, click on "Create". The Azure Functions app deployment will be started

Step 3
 
You can update the application setting from the "Publish" window.
 
 

Click on "Manage Application Settings".
 
 
 
In this "Application Settings" window, you can update the both, local and remote, Azure Storage connection strings.

Step 4
 
Once the deployment is completed, check the service in the portal and get the endpoint.
 
 
 
https://myazurefunctiondemo.azurewebsites.net/api/MyFunctionDemo?code=G4RH366GQQWmj9RiXXcYS7Dfe/XKuPmQTUkbkLiLYk3UraXQnPoKpA==
 
Since we configured the Access rights as a function, we will get a code in a URL for authentication.
 
Step 5
 
Let's test the function using the POSTMAN tool.
 
 
 
Yes, we have got a response as expected.
 

Conclusion


We have seen how to create an Azure Functions app in Visual Studio and how to bind Azure Queue Storage service with the Functions app and finally, we deployed it on Azure using Visual Studio.


Similar Articles