In my previous post, I touched on how to create a simple Azure Function and invoke it through a web request.
In this post, I want to do something more interesting that has not yet been covered in any of the template provided.
My objective is to insert a record into Sql Azure Database every time I receive a request.
For this post, we are going to assume you already have Azure Sql database up and running and already have a function app created.
Prerequisites:
- create an Azure Sql Database from the portal.
- create a table called LogRequest with two columns (Id [PK, int, identity] , Log [nvarchar(max)]
I used visual studio 2015 community to connect to sql database can created the new table.
Function Code and Database Configuration:
- Click on “New Function“, then select “HttpTrigger – C#“, Name your function “HttpTriggerSqlDatabase” to make it easy to locate
- Once you get the default code view, find the small link down the bottom of the code text box called “View files“
- Click on the “+” sign to add new file, name the file “project.json” we are going to use this file to add all required nuget packages.
copy and paste the json content bellow and hit save.
{ "frameworks": { "net46":{ "dependencies": { "Dapper": "1.42.0", "System.Data.SqlClient":"4.1.0", "Microsoft.WindowsAzure.ConfigurationManager":"3.2.1" } } } }
you should start seeing the logs restoring all missing nuget packages, then compile the code. - Associate your database connection string to the Function App. To do that, click on the top link “Function app settings” then click the button “Go to App Service Settings”
It will open your Function App settings page, then click on Data Contentions, Add
once you successfully added a connection called “SqlConnection“, close the views and navigate back to your function using the breadcrumbs. - Click on your function named “HttpTriggerSqlDatabase”, copy the snippet bellow.
using System.Net; using Dapper; using System.Data.SqlClient; using System.Configuration; public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log) { log.Info($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}"); var successful =true; try { var cnnString = ConfigurationManager.ConnectionStrings["SqlConnection"].ConnectionString; using(var connection = new SqlConnection(cnnString)) { connection.Open(); var rLog = await req.Content.ReadAsAsync<LogRequest>(); // insert a log to the database // NOTE: Execute is an extension method from Dapper library connection.Execute("INSERT INTO [dbo].[LogRequest] ([Log]) VALUES (@Log)", rLog); log.Info("Log added to database successfully!"); } } catch { successful=false; } return !successful ? req.CreateResponse(HttpStatusCode.BadRequest, "Unable to process your request!") : req.CreateResponse(HttpStatusCode.OK, "Data saved successfully!"); } public class LogRequest { public int Id{get;set;} public string Log{get;set;} }
Now save the code and ensure the logs shows the function compiled successfully.
Testing the Function
Scrolling down the page to the Run section, you can invoke your API
I used LinqPad to retrieve the record from the database to verify that my data was actually saved successfully.
Conclusion
It was relatively easy to have my Azure Function connect to a database and insert a record triggered by a web request.
Using nuget to download packages and reference them in the function is extremely useful, given that most of .Net framework and 3rd party are available as packages.
This scenario gives us the opportunity to design solutions that store request’s data into a relational database which is a step closer to real business application’s requirement.
In feature posts, we will take this a step further and emit events to trigger other Functions to perform other actions meaningful to the data received.
can i use azure function for automatic processing of azure analysis services which is exist in azure virtual machine ?
please help me