Azure Timer Functions

A quick getting started guide for Azure Timer functions. Timer triggers give us alot more options to automate things. With Azure timer functions we don't have to take care of the timer Azure handles that. We can focus on the code and what our function should do.

CRON Expressions

Azure timer functions use a CRON expression for the schedule. CRON Expressions can be a bit confusing at first but with some time they make sense and really easy to configure and use.

A CRON Expression contains six fields.

{second} {minute} {hour} {day} {month} {day-of-week}

Each field is separated by a space. The value of the fields can vary and this is where I think alot of people get lost.

Examples of values:

A specific value:

"0 */5 * * * *"  - Every 5 Minutes.

"0 0 */6 * * *" - Once every 6 hours.

Note the */X this sets the trigger to every X.

"0 0 * * * *" - At the top of every hour.

"0 30 8 * * *" - At 8:30 AM every day

"0 30 11 * * 1-5" - At 11:30 AM every week day. (Monday - Friday)

To specify months or days you can use numeric values, names, or abbreviations of names:

  • For days, the numeric values are 0 to 6 where 0 starts with Sunday.
  • Names are in English. For example: Monday, January.
  • Names are case-insensitive.
  • Names can be abbreviated. Three letters is the recommended abbreviation length.  For example: Mon, Jan.

The default time zone used with the CRON expressions is Coordinated Universal Time (UTC). Azure Timer functions can run in other time zones to change the time zone you need to add a setting in the Function.json

WEBSITE_TIME_ZONE - "Eastern Standard Time"

For a full list of Azure Time zones see here

Creating a function

In our Azure Portal Go to our functions. If you haven't checked them out, see my getting started guide. For all my Azure function posts.

Create a new Function, on the wizard select the "Timer Trigger" function.

Create an Azure Timer Function

We then need to name our new function.

We can also set a schedule by default. The Timer function I just created uses a every 5 minutes expression: "0 */5 * * * *"

Create our new Timer function. 

Now that we have created a function. The default code will write to the log every 5 minutes.

Default Function will write to it's log.

So that's it, we can now code up our function as we want and Automate all the things.

To change the timer on the function just head to the function.json file

{
  "bindings": [
    {
      "name": "myTimer",
      "type": "timerTrigger",
      "direction": "in",
      "schedule": "0 */5 * * * *"
    }
  ],
  "disabled": false
}

You can see the schedule settings here. Changing it and resaving it will update the triggers timer.

A quick getting started guide for Azure Timer functions. Timer triggers give us alot more options to automate things. With Azure timer functions we don't have to take care of the timer Azure handles that. We can focus on the code and what our function should do.CRON ExpressionsAzure timer…

Read More

Azure Functions Nuget Packages and the dot Net Framework

Using Nuget and the .NET Framework in our Azure Functions is easy and straight forward. We can give our Azure functions alot of power and functionality.

Using the .NET Framework

For framework assemblies, add references by using the #r "AssemblyName" directive.

For example if we want to use System.Data.SqlClient we would need to add a #r directive to the top of our code like this


#r "System.Data"

using System.Data.SqlClient;

This will allow us to use the SQLClient libarary of the .net framework.

Adding Nuget

If you are wondering where to get started check out our Azure Functions Getting Started

In our Function we need to add a "project.json" file. Go to View Files and add a new file and name it project.json

Azure Function Add Project json

In our Project.json we want to add the following


{
  "frameworks": 
    {  
      "net46":
      { 
        "dependencies":
        {
          "Newtonsoft.Json": "10.0.3"
        }
      }
    }
}


This will load the nuget package of Newtonsoft Json into our function.

Then in our code we just reference


using Newtonsoft.Json;

And now we can use our Nuget package in our Azure Function.

Using Nuget and the .NET Framework in our Azure Functions is easy and straight forward. We can give our Azure functions alot of power and functionality. Using the .NET Framework For framework assemblies, add references by using the #r "AssemblyName" directive. For example if we want to use…

Read More

Azure Functions Triggers

Azure Functions come with a number of triggers, from HTTP, Timers, service bus, blob and many more. In this post we go over the different types of triggers available out of the box for Azure Functions.

Last week I covered the creating of functions and getting up and running, Azure Functions Getting Started

Azure Function Triggers

Azure functions have a number of quick start templates for different triggers in C#, F# and Javascript. These are out of the box and have some default code.

Azure Function Triggers

  • HTTP Trigger

When a HTTP request is made to the function, the functions code will be executed. It provides a REST API endpoint that can be called with a HTTP post request.

  • Timer Trigger

This is a trigger that is based on a schedule. You can define the schedule and it will execute the code in the function.

To create a schedule you use the CRON Expression

A timer trigger is made up of

{second} {minute} {hour} {day} {month} {day-of-week}

Examples

Once every 5 minutes

0 */5 * * * *

Trigger once every two hours

0 0 */2 * * *

Trigger once every hour from 9 AM to 5 PM

0 0 9-17 * * *

Trigger At 9:30 AM every weekday

0 30 9 * * 1-5

  • Queue Trigger

This is a trigger that will execute the code whenever a message is added to a selected Azure Queue Storage

  • Blob Trigger

When an item is added to a specified Blob Storage container the code will be executed.

  • EventHub Trigger

When an event is added to the selected event hub the code in the function will execute.

  • Servicebus Queue Trigger

When a message is added to a selected Service Bus queue, this function will be executed.

  • Servicebus Topic Trigger

When a message is added to a specified Service Bus topic, then this function will be triggered.

With these triggers we have alot of flexibility to create a very flexible application.

Azure Functions come with a number of triggers, from HTTP, Timers, service bus, blob and many more. In this post we go over the different types of triggers available out of the box for Azure Functions. Last week I covered the creating of functions and getting up and running, Azure…

Read More

Azure Functions Getting Started

Function as a Service or FAAS we do love our abbreviations. FAAS is a set of functions that are short lived and single responsibility and have the ability to scale well. The big part of Functions as a service is they are part of serverless, this doesn't mean there isn't a server it just means the server is not your problem.

Some of the properties of Function as a service are

  • Short lived functions - AWS Lambda has a timeout of 1 second.
  • Single Responsibility - A Function should only do 1 thing.
  • Event Driven - A function can respond to a HTTP Trigger like a Webhook, a schedule and timer or a Service bus message.
  • Scale easily with traffic spikes

This is the first post in a series on FAAS in general but starting with Azure Functions.

Azure Functions

Azure functions are Microsofts FAAS offering and what we will start to explore.

With Azure Functions you can write functions in C#, F#, Node.js, Python, PHP, Batch, Bash and an executable. Functions have full support for Nuget and NPM. Easily integrate to other Azure services.

Pricing

Azure functions have two price plans, app service plan so it would be tied to your existing plans or consumption and you only pay for what you use.

With Functions you pay per second X number of executions.

Getting Started

Lets get creating some azure functions. Open the Azure Portal

Click on New and in the market place type in Function App (it's filed under Compute in the marketplace if you just want to click it)

Getting Started with Azure Function App

Once you select this we can create our first function app. This isn't the functions it's a host for our functions. Think of it like setting up an Azure App Service.

Create Azure Function App

Now we create our function app. We give it a name, select the Resource Group and Subscription as we do with most things in Azure.

Hosting Plan we have two choices,

  • Consumption Plan
  • App Service Plan

With an App service plan our function is tied to the currently running app services.

Consumption plan is just what it sounds like you pay for what you use. Per Second per request. I won't go into the details here if you go to the Azure Pricing Calculator you can find out more.

All Azure functions need a storage account and they can be integrated to Application Insights.

Hit create and deploy our new Azure Function.

Next we need to add the menu item to the side bar on our portal. It's not there by default.

Click "More Services" on the bottom of the side bar

Azure More Services

Search for "Azure Functions" and click the Star to add it onto the side bar and then you can move it where you want.

Azure Function Apps sidebar option

Once our Function app has deployed we can start creating functions.

Azure Function App Ready

Let's create a quick function and see it all in action.

Along side functions Hit the plus to create a function

Azure Function New

For your first Function you will see the Azure Function quick start panel.

Azure Function Quick Start

We'll create a web hook Function, this is a HTTP Trigger function, I'll cover the triggers in another post.

Create this function.

Azure Function Code

Ok we now have a function, our screen in the portal is in 3 sections

  • We our editor which by default is loading the code for our function.
  • Below this we have our logging output.
  • Next to this on the left we have "Files" and "Test"

The file "run.csx" is our code. Azure functions are scripts. In this case I have a csharp script.

Select "Test" on the left side to open the test panel.

Test Azure Function

This makes a POST request and sends a request body with "Name": "Azure" this is the default test.

Below that you can select Run and the output will show "Hello Azure"

You can also test it from an API testing tool like postman (for more on postman and api testing check out my post API Testing with Postman)

Click on "</> Get Function URL"

Azure Function Get URL

Copy this url and open Postman or any API testing tool

Azure Function Test

Set the web method to POST and enter the URL from the function.

Select Body and go to RAW, set the application content type to "JSON(Application/json)"

And then enter the RAW body of

{
"name": "James"
}

Click send and then we will get a response of "Hello James"

That's it you have created your first function.

This is the first post in a series on FAAS, focusing at first on Azure Functions.

Over the course of these posts we will cover

  • Different triggers.
  • Passing more information.
  • Nuget Packages.
  • Working with Visual Studio.
  • Connecting to other services including SQL and Azure tables.

Function as a Service or FAAS we do love our abbreviations. FAAS is a set of functions that are short lived and single responsibility and have the ability to scale well. The big part of Functions as a service is they are part of serverless, this doesn't mean there isn't…

Read More

ASP Web API with Azure Table Storage

Using ASP Web API with Azure table storage

We've already covered the basics of creating an ASP Web API project and the basics for Azure Table Storage

ASP WEB API intro

Azure Table Storage

For the sample code for this check out our GitHub

Now we're going to get into using both of these. Creating a simple ASP Web API to create data into an Azure Table storage and to get that data back out. We'll do some testing of the API with Postman

As earlier we're using Visual Studio 2015.

Lets get going

Create a Web API project

Create Web API Project

Add Azure Storage from nuget.

We'll create a new controller building on our last post on Azure Table storage. We'll go for a "PlayerController"

Create API Controller

Select "Web API 2 Controller" from the Add scaffold option.

In the model create an entity for Table Storage "PlayerEntity". The player entity will look the same as we had in our last post.

Player Entity

Now back to our controller, we want to create two methods a POST method to create a player and a Get method to get players for a sport.

    public List<PlayerEntity> Get(string sport)
    {
        List<PlayerEntity> _records = new List<PlayerEntity>();

        //Create a storage account object.
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_connectionString);

        // Create the table client.
        CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

        // Retrieve a reference to the table.
        CloudTable table = tableClient.GetTableReference("player");

        // Create the table if it doesn't exist.
        table.CreateIfNotExists();

        // Get All Players for a sport
        TableQuery<PlayerEntity> query = new TableQuery<PlayerEntity>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, sport));
        
        foreach (PlayerEntity entity in table.ExecuteQuery(query))
        {
            _records.Add(entity);
        }

        return _records;
    }

This is the same as we used in our last post on Azure table storage.

We create a storage account with a connection string.

The table client is created and this we check for the table "Player" if it doesn't exist we create it.

Azure Table storage is a partitioned database. For this demo we create a partition based on Sport. So we can create players for "Soccer", "Rugby" and "Hurling" and so on. The get method will then only return the players for the sport we want.

For the Post there are a few ways to pass parameters we'll keep it simple for now. We'll pass the parameters into the POST method.

    // POST api/Player
    public string Post(string sSport, string sRow, string sFirstName, string sLastName, string sClub, string sPostition)
    {
        string sResponse = "";

        // Create our player

        // Create the entity with a partition key for sport and a row
        // Row should be unique within that partition
        PlayerEntity _record = new PlayerEntity(sSport, sRow);

        _record.Sport_VC = sSport;
        _record.First_Name_VC = sFirstName;
        _record.Last_Name_VC = sLastName;
        _record.Club_VC = sClub;
        _record.Position_VC = sPostition;

        //Create a storage account object.
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_connectionString);

        // Create the table client.
        CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

        // Retrieve a reference to the table.
        CloudTable table = tableClient.GetTableReference("player");

        // Create the TableOperation object that inserts the customer entity.
        TableOperation insertOperation = TableOperation.Insert(_record);

        try
        {
            // Execute the insert operation.
            table.Execute(insertOperation);

            sResponse = "OK";
        }
        catch (Exception ex)
        {
            sResponse = "Failed: " + ex.ToString();
        }
        return sResponse;
    }

With this Post method, we can take the parameters passed in and then create a player in our Table storage.

Testing with PostMan

We will use Postman to do the testing if you don't have it go get it and check out this post on using Postman

Our Get method is simple it takes a parameter of sport and then will return all the players in that sport.

In post man we create a GET Request to

http://*LOCALHOST*/api/Player?sport=soccer

This will return a list of all players in Soccer.

To test the POST method change the method in Postman to "POST"

http://*LOCALHOST*/api/Player?sSport=soccer&sRow=52&sFirstName=Chris&sLastName=Smalling&sClub=Man Utd&sPostition=CB

That's it, since we kept our POST simple we just need to pass the parameters and we can add the player to the Azure table.

Coming soon we'll start to work on our POST method and passing the parameters in different ways.

For the sample code for this check out our GitHub

Using ASP Web API with Azure table storage We've already covered the basics of creating an ASP Web API project and the basics for Azure Table Storage ASP WEB API intro Azure Table Storage For the sample code for this check out our GitHub Now we're going to get into…

Read More