Author : MD TAREQ HASSAN | Updated : 2020/10/27
The app we are gonna create
- The function app we are gonna create => will receive list of orders and save those order information to Azure Storage
- Azure storage type: table storage
- Trigger type: http
Prerequisites
- Install Visual Studio Azure worloads
- An Azure account with an active subscription => create an account
- Azure storage account (See: create Azure storage account
- Login to Visual Studio using credentials (account that has Azure subscription)
Dependency
Install-Package Microsoft.Azure.WebJobs.Extensions.Storage
Table storage
- Go to Azure portal resource group: https://portal.azure.com/#blade/HubsExtension/BrowseResourceGroups
- Select storage account and create table storage
- Use table name: ‘orderhistory’
Visual Studio project
- Create new project > Azure Functions
- Applications name: HoverFunctionApp > Create
- Select Http trigger
- Select storage account
- dropdown menu > browse
- select subscription and storage account
- Authorization level: Function > Create
Implement logic
- Open Package manager console in Visual Studio > Select target project
- you might have multiple projects in your solutio
- Package manager console: select function project
- Install Nuget package ‘
Microsoft.Azure.WebJobs.Extensions.Storage
’ (see dependency section)
Models
// OrderItem.cs
public class OrderItem
{
public string Id { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
public string Size { get; set; }
}
// Order.cs
public class Order
{
public List<OrderItem> Items { get; set; }
}
// TableOrderItem.cs
public class TableOrderItem : OrderItem
{
public TableOrderItem()
{}
public TableOrderItem(OrderItem item)
{
base.Id = item.Id;
base.Name = item.Name;
base.Size = item.Size;
base.Quantity = item.Quantity;
}
public string PartitionKey { get; set; }
public string RowKey { get; set; }
}
Rename file name to ‘OrderFunction’: OrderFunction.cs
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using System.Net.Http;
namespace HoverFunctionApp
{
public static class OrderFunction
{
[FunctionName("OrderFunction")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post",
Route = null)] HttpRequestMessage req,
[Table("orderhistory")]ICollector<TableOrderItem> items,
ILogger log)
{
log.LogInformation("Hover -> (HTTP trigger) function processed a request.");
string orderId = System.Guid.NewGuid().ToString();
Order order = await req.Content.ReadAsAsync<Order>();
foreach (var item in order.Items)
{
TableOrderItem toi = new TableOrderItem(item);
toi.PartitionKey = "history";
toi.RowKey = $"{orderId} - {item.Id}";
items.Add(toi);
}
return new OkResult();
}
}
}
Run locally and test
- Azure Functions Core tools (Installed with Visual Studio Azure workloads):
- let you run this project on your local development computer before you publish to Azure
- test your functions on your local computer from the command prompt or terminal
- local functions can connect to live Azure services, and you can debug your functions on your local computer
- Details of Azure Functions Core Tools: https://docs.microsoft.com/en-us/azure/azure-functions/functions-run-local
- Note: since we added Azure storage account during function project creation in visual studio, therefore it would able to access the Azure Table storage when running our function app locally.
- Download and install Postman
- Launch postman and Create Request (create collection or add to existing collection)
Azure storage explorer
- Download and install Azure storage explorer
- Launch and login to Azure storage explorer
Running function app
Send request to function app using postman
Request data:
{"Items": [
{"Id":"xyz-9b80-12b956b90de4", "Name":"ABC", "Quantity": 1, "Size":"M"},
{"Id":"xyz-4e1d-eb4f9fc8f907", "Name":"PQR", "Quantity": 3, "Size":"L"},
{"Id":"xyz-4e1d-e9ffc8bebb1e", "Name":"UVW", "Quantity": 6, "Size":"S"}
]}
Check storage explorer to see if order is created
Publish to Azure cloud and test
Create function app in Azure portal:
- Go to Azure portal and create function app: https://portal.azure.com/#create/Microsoft.FunctionApp
- Go to Azure portal > resource group
- check function app and associated storage account:
- Resource group link: https://portal.azure.com/#blade/HubsExtension/BrowseResourceGroups
Publish function app from visual studio:
- Visual Studio > Right click on the project > Publish
- Azure > Next
- Azure Function App (Windows) > Next
- Select subscription > View: Resource group > Expand resource group and select Function App
- Configure storage > Next > Next > Finish
- Publish
Check published function app in Azure portal:
- Go to Function app: https://portal.azure.com/#blade/HubsExtension/BrowseResource/resourceType/Microsoft.Web%2Fsites/kind/functionapp
- Select function app > OrederFunction > Functions in ‘Functions’ Section > Select OrederFunction
- Function keys > Show values > Copy key (save it to notepad to use in Postman)
- Get URL to trigger function app (save it to notepad to use in Postman):
- Copy site URL from Visual Studio Publish window
- Run the function locally to get the endpoint i.e.
/api/OrderFunction
- Full url (for the demo app):
http://myfoofunctionapp.azurewebsites.net/api/OrderFunction
Text using Postman:
- Open Postman > Set URL
- Set headers:
Content-Type
:application/json
x-functions-key
:<use key that was saved before>
- Set body
- Raw
- Type JSON
- Use request data (sample request data is below)
- Send request
- Open storage explorer and check data is saved in table storage
Request data:
{"Items": [
{"Id":"hovermind-12b956b90de4", "Name":"ABC", "Quantity": 1, "Size":"M"},
{"Id":"hovermind-eb4f9fc8f907", "Name":"PQR", "Quantity": 3, "Size":"L"},
{"Id":"hovermind-e9ffc8bebb1e", "Name":"UVW", "Quantity": 6, "Size":"S"}
]}