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.
- {
- "IsEncrypted": false,
- "Values": {
- "AzureWebJobsStorage": "UseDevelopmentStorage=true",
- "AzureWebJobsDashboard": "UseDevelopmentStorage=true"
- }
- }
Right now, we are using Development Storage. The class file contains a predefined function with code.
- [FunctionName("MyFunctionDemo")]
- public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, TraceWriter log)
- {
- log.Info("C# HTTP trigger function processed a request.");
-
-
- string name = req.GetQueryNameValuePairs()
- .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
- .Value;
-
- if (name == null)
- {
-
- dynamic data = await req.Content.ReadAsAsync<object>();
- name = data?.name;
- }
-
-
- return name == null
- ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
- : req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
- }
- }
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.
- {
- "IsEncrypted": false,
- "Values": {
- "AzureWebJobsStorage": "<Give Your Storage Account Connection String>",
- "AzureWebJobsDashboard": "UseDevelopmentStorage=true"
- }
- }
Let’s create a class called Order.cs.
- public class Order
- {
-
- public string OrderId { get; set; }
- public string ProductId { get; set; }
- public string UserEmail { get; set; }
- public decimal Price { get; set; }
- }
Now, go to MyFunctionDemo and update the code as given below.
- public static class MyFunctionDemo
- {
- [FunctionName("MyFunctionDemo")]
- public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, TraceWriter log,
- [Queue("orders", Connection = "AzureWebJobsStorage")] IAsyncCollector<Order> outputQueue)
- {
- string jsonContent = await req.Content.ReadAsStringAsync();
- var myOrder = JsonConvert.DeserializeObject<Order>(jsonContent);
- log.Info($"Order {myOrder.OrderId} received from {myOrder.UserEmail} for product{myOrder.ProductId}");
- await outputQueue.AddAsync(myOrder);
-
-
- return req.CreateResponse($"Your Order is Placed with Order Id {myOrder.OrderId}, Thank you");
- }
- }
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.