06Feb

Azure Function : A quick start with database

Azure Function is a solution for running small piece of code or a "Function" in cloud. You can write just the code need for the problem without worrying about the infrastructure or the application to run it. Function can make your development more productive and you can choose your development language of choice such as C#, F#, node.js, java or PHP.

Pay only for the time your code runs. Azure Function lets you develop Serverless application on Microsoft Azure.

Feature of Azure Function:

  • Choice of Language
  • Pay-per-use pricing model
  • Bring your own dependencies
  • Integrated Security
  • Simplified integration
  • Flexible Development
  • Open Source

Function is great solution for processing data, integration system and working with internet-of-things(IoT) and building simple APIs and Microservices.

Function provide templates to get you started with key scenarios.

  • Http Triggers
  • Timer Triggers
  • GitHub Webhook
  • Generic Webhook
  • CosmosDB Trigger
  • Blob Trigger
  • Queue Trigger
  • Event Hub Trigger
  • Service bus Queue Trigger
  • Service bus Topic Trigger

Here i'm going to explain how to create simple Azure Function in Azure Portal.

Go to Azure Portal, click on New then search for Function App.

1

Select the Function app in Result shown. Then click on Create Button.

2

Provide Required details and click on Create

3

App will be created and the app details will be shown.

4

Hover cursor on Functions and click on + icon and choose webhook+Api and language C# click on Create this function button5

You will see the following screen containing a Function. Notice that Get function URL on the right  top corner of the screen.

6

Click on that and copy the URL in your browser address bar and hit Enter. You will see the following message. "Please pass a name on the query string or in the request body" 

Now append this &name=Azure at the end of the URL and hit enter. You will see the following message. "Hello azure".

Now create a database in Azure

Go to:  Resource Groups >> Add >>

Select SQL Database

Click on "Create" Button

Provide all the required details and click on create button.

Once the database is created go to that database, click on show connection string and copy the connection string, it will be required.

7

8

Provide your username and password which you have given while creating SQL Database.

Connect to your database using SQL Server or Visual studio. Create table using following script.

CREATE TABLE [dbo].[LogRequest]( [ID] [int] IDENTITY(1,1) NOT NULL, [Log] [varchar](max) NULL)

Now go to your function app. Click on [+ New Function ] at the top.

9

Select "Http Trigger" function and language C#. Provide function name as "HttpTriggerDatabase" then click on create.

10

Once the function is created, Go to that function and Click on "View Files" on the Right side Blade. To create a file, Click on [+ Add] Button. Give a file name as "Project.json" and Hit Enter [ ↵ ] Paste the following in that file.

{
 "frameworks": {
	    "net46":{
	      "dependencies": {
	        "Dapper": "1.42.0",
	        "System.Data.SqlClient":"4.1.0",
	        "Microsoft.WindowsAzure.ConfigurationManager":"3.2.1"
	      }
	    }
	   }
	}

Click "Save" Button. Now open your function and paste the following code.

 

 


	using Microsoft.Azure.WebJobs.Host;
	using System.Configuration;
	using System.Data.SqlClient;
	using System.Net;
	using System.Net.Http;
	using System.Threading.Tasks;
	using Dapper;
	
	        public static async Task 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 (SqlConnection connection = new SqlConnection(cnnString))
	                {
	                    var rLog = await req.Content.ReadAsAsync();
	
	                    // insert a log to the database
	                    string query = "INSERT INTO [dbo].[LogRequest] ([Log])  VALUES (@Log)";
	                    using (SqlCommand cmd = new SqlCommand(query, connection))
	                    {
	                        cmd.Parameters.AddWithValue("@Log", "Log1");
	                        connection.Open();
	                        cmd.ExecuteNonQuery();
	                        connection.Close();
	                    }	
	                }
	            }
	            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 configure your database connection for your azure function.

11

 

Go to Application Setting. Scroll down up to "Connection String"

13

Give connection name as "SqlConnection" and paste your copied connection string in the value field. Select "SQL Azure" form the dropdown. Click save.

Go to your function and Click on Run button. You can see the output "Data saved successfully"

12

You can copy the URL from Get function URL  and browse, you will see the same output on the screen.

Thank you.

 

Related

Roles in DevOps Mobile App Development

DevOps can be defined as an approach to enable seamless application delivery from inception to produ...

Read More >

What is DevOps and why Enterprises are serious about it?

The term DevOps is becoming increasingly familiar as more and more companies are interested in imple...

Read More >

Azure Blob Storage: The PowerShell Way!

Hi folks!Great to see you again.This blog post is purely based on Azure Blob Storage: The PowerShell...

Read More >

Create a Windows Server 2012 R2 VM using ARM in Azure PowerShell

Hi Folks,In this Blog Post we will learn how to create an Azure ARM Virtual Machine using Azure Powe...

Read More >

Continuous Integration/ Continuous Deployment VSTS

Following the below steps you can build and deploy your ASP.NET  app to Azure from either Visua...

Read More >

How to Sync On-premise AD with Windows Azure AD using Azure AD Connect tool

 Azure AD is a service that provides identity and access management capabilities in the cloud. ...

Read More >

Creating a Point-to-Site Connectivity using Azure Resource Manager

Configure a Point-to-Site connectivity to a VNet using PowerShell (ARM Mode)Task 1: Create a Self-Si...

Read More >

How to Create an Azure Virtual Network by using a Deployment Template

Hello Folks!In this Blog post, we will try to learn how to create an Azure V-Net using an ARM templa...

Read More >

Locking VMs and Resources Groups with Azure Resource Manager using Azure PowerShell

Hello Folks!In this blog post we will be talking about locking down your Azure Resources with Azure ...

Read More >

Microsoft Azure: Implementing Internet Facing Load Balancers using Azure Resource Manager

Howdy Folks!I was exploring Network Load Balancer in Azure Resource Manager and found out that you c...

Read More >

Share

Post a Comment

  • Recent
  • Popular
  • Tag
Tags
Monthly Archive
Subscribe
Name

Contact Us
  • *
  • *