Azure Functions Using C#

What do you mean by Azure functions?

Azure Functions are event-driven functions which are executed on some occurrence of events and can be used on-demand.

Using Azure Functions has several benefits, e.g. Coding and deployment in Azure Functions is comparatively easier than that  normal webapi and webapps.

You can use Azure functions where you code does not include any complex logic. Azure functions can be used for very small pieces of code which can be invoked via any triggered events.

Data processed by Azure Functions can be stored into various Azure data services such as Azure storage, Azure SQL DB and Document DB.

One can leverage Azure Functions to build HTTP-based API endpoints accessible by a wide range of applications, mobile etc. that too in variety of languages like JavaScript, C#, Python and PHP as well as scripting options like Bash, Batch and PowerShell. Azure Functions are scale-based and on-demand, so you pay only for the resources you consume.

Now let us see a small demo of how to create an Azure function and implement it using C#.

Pre-Requisites

You need to have the following software installed before proceeding.

  1. Visual Studio 2013 - If you don't have Visual Studio 2013 installed on your computer, you can download it from this URL.
  2. Windows Azure Subscription - you can also subscribe for a free trial of Windows Azure from URL.
  3. Windows Azure SDK 2.8.2 - To download latest sdk you can download it from this link.

Let us start with the actual demo of implementation of Azure functions provided above pre-requisites are met.

  1. Log on to Azure Preview Portal
  2. In the Azure Portal, click NEW > and search for “function App”. Select the Function App within the details blade and click on CREATE as shown in the below image.



  3. Once the function app is created locate your newly created function app by searching in the all resources tabs.



  4. Click on your newly created function app and click on WebHook + API option and choose the language as C# and your new HttpTriggerCSharp gets created.



    So basically this is how you create a function and a respective,

    HttpTrigger.

    Now let us try to insert a record in Azure SQL database with help of our function app.

  5. Create an Azure SQL database from the portal.
  6. Create a table called give it any name of your choice. I have created table called testtbl with the following script in azure sql database.
    1. Create TABLE testtbl  
    2. (  
    3.       Id int identity (1, 1) Primary key,   
    4.       logreq nvarchar (max)        
    5. )  
  7. Now click on HttpTriggerCSharp function which we created in step 4. I have created a function with name HttpTriggerCSharp2 as shown below.



  8. Once you have your view for HttpTriggerC# function find the small link down the bottom of the code text box called “View files“.





  9. 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 below and hit save.
    1. {  
    2.   "frameworks": {  
    3.     "net46":{  
    4.       "dependencies": {  
    5.         "Dapper""1.42.0",  
    6.         "System.Data.SqlClient":"4.1.0",  
    7.         "Microsoft.WindowsAzure.ConfigurationManager":"3.2.1"  
    8.       }  
    9.     }  
    10.    }  
    11. }  


    Once you add this file all the nuget packages get restored and then compile the code.

  10. Now you need to configure your azure sql database connection string with this function app. For that click on Function app settings at the bottom of the functionapp as shown below.



    Click on ‘Go to App Service Settings button’. It will open a new page as shown in the below image.



  11. Now Click on Data Connections and click on Add.





    Now select your database and say Ok.

    Once you have successfully added a connection whatever name you have given, in my case it is MS_TableConnectionString, close the views and navigate back to your function.

  12. Now click on your HttpTrigger function, in my case it is HttpTriggerCSharp2. Copy the below piece of code in your function with some changes like sql table name, appsetting name etc.


    1. using System.Net;  
    2. using Dapper;  
    3. using System.Data.SqlClient;  
    4. using System.Configuration;  
    5.   
    6. public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)  
    7. {  
    8.     log.Info($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}");  
    9.   
    10.     var successful =true;  
    11.     try  
    12.     {  
    13.         var cnnString  = ConfigurationManager.ConnectionStrings["MS_TableConnectionString"].ConnectionString;  
    14.           
    15.         using(var connection = new SqlConnection(cnnString))  
    16.         {  
    17.             connection.Open();  
    18.               
    19.             var rLog = await req.Content.ReadAsAsync<LogRequest>();  
    20.             connection.Execute("INSERT INTO [dbo].[testtbl] ([logreq]) VALUES (@Log)", rLog);  
    21.             log.Info("Log added to database successfully!");  
    22.         }  
    23.     }  
    24.     catch  
    25.     {  
    26.         successful=false;  
    27.     }  
    28.       
    29.     return !successful  
    30.         ? req.CreateResponse(HttpStatusCode.BadRequest, "Unable to process your request!")  
    31.         : req.CreateResponse(HttpStatusCode.OK, "Data saved successfully!");  
    32. }  
    33.   
    34. public class LogRequest  
    35. {  
    36.     public int Id {get;set;}  
    37.     public string Log {get;set;}  
    38. }  
  13. Now save the code and compile it -- make sure that the logs display the message function compiled successfully.


  14. Now run the code with i/p as below in the run text box:
    1. {  
    2.     "Log""This is my Log"  
    3. }  


    Now click on Run Button and you should get below message in the o/p window.



    To verify whether the data has been saved successfully I verified by connecting to Azure database through SQL Server Management Studio and firing the Select Query as shown below.


Summary - In the above article I have demonstrated the following things,

  1. What are Azure functions?
  2. How to use and implement Azure functions in C#?

Up Next
    Ebook Download
    View all
    Learn
    View all