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 with Continuous Deployment

A quick guide to setting up continuous deployment for Azure functions.

Continuous Deployment or Continuous Delivery allows us to deploy our application / code into the production or test based on each check in to our source control, this allows us to focus our craft and not on deployments.

Setting up CD for Azure functions is really a simple process.

Source code can be found here

Create a function

First we need some functions. I've created a simple GET function. I'm assuming you have setup functions and seen them in action already. If not check out my blog posts on Azure functions

Create a folder for your azure function.

Add a host.json file - Leave this empty for now.

{}

By default the host.json needs to have {} this leaves it empty, leaving it blank will stop the function from starting.

Create a folder for your first function. Each function should have a folder.

In this folder create 3 files.

  • project.json
{
    "frameworks": 
    {  
     "net46":
     { 
      "dependencies":
      {
        "Newtonsoft.Json": "10.0.3"
      }
     }
   }
}
  • function.json
{
    "disabled": false,
    "bindings": [
      {
        "authLevel": "anonymous",
        "name": "req",
        "type": "httpTrigger",
        "direction": "in"
      },
      {
        "name": "$return",
        "type": "http",
        "direction": "out"
      }
    ]
}

Note: I've created this function as a GET with anonymous authentication so we can call it with no keys.

  • run.csx
using System.Net;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");
    
    return req.CreateResponse(HttpStatusCode.OK, "Hello there");
}

Go ahead and commit the function to your source control.

Create a function

Back onto the Azure portal. Create a new function app.

Once created head to the "Platform Features" Tab

Azure-Function-platform

Select Deployment options and select "Setup"

azure-deployment-setup-2

Configure sources

Azure functions allows you to deploy from different sources.

azure-function-sources

Follow the steps to select the source you want. I am going with Github.

Once setup follow the steps to add your functions source. Then click sync or make a change and push to your source control.

Azure-Functions-Sync

That's it go ahead and test the function.

Azure-Functions-Test

When I run the test I get the hello response.

Azure makes it really easy to deploy from source control. There is the ability to add tests aswell, I'll cover that in another post.

A quick guide to setting up continuous deployment for Azure functions. Continuous Deployment or Continuous Delivery allows us to deploy our application / code into the production or test based on each check in to our source control, this allows us to focus our craft and not on deployments. Setting up…

Read More

Azure Functions Routes and Proxies

Azure Function Proxies allow you to create a single unifed API surface for your Azure functions. The Microsoft Azure stack allows you to use different technologies so you can use the right tool for the job.

Azure functions can also have routes. Unlike a Proxy a route will only effect the azure function it is on.

A proxy allows us to create a single clean set of endpoints and Azure handles all the routing to the right place.

Getting Started

I've created two simple Azure functions both are HTTP Trigger functions.

Source code here

GET - HTTPDEMOGET

We have a GET Function that will return an object from a pretend database.

POST - HTTPDEMOPOST

We have a POST function that will save an object somewhere.

Source for our functions is here

Azure function Routes

First we will look into the routing in azure functions.

POST Function

First lets set our routing on our POST function.

When we create a function we get a default route that looks something like this

https://serversncodefunctiondemo.azurewebsites.net/api/HttpDemoPost?code=SJ47E3DDWAMeWw2sRU9aKhFYJPFacCTdtA/K7qu5GH86U2JNdKD6jA==

Changing the route on our function is simple. In our function.json we have to add a property for route for example,

{
  "bindings": [
    {
      "authLevel": "function",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "route": "serversncodedemo"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    }
  ],
  "disabled": false
}

I've modified my function to now have "route": "serversncodedemo"

This changes my URL to replace the httpdemopost part with serversncodedemo.

https://serversncodefunctiondemo.azurewebsites.net/api/serversncodedemo?code=SJ47E3DDWAMeWw2sRU9aKhFYJPFacCTdtA/K7qu5GH86U2JNdKD6jA==

Now when we use that URL and pass our Json payload. We have changed our functions route.

GET Function

For this demo our get function will take an ID and return the record from our magic database.

To set a function as a GET function is done in the function.json.

In the bindings, I've set my function to

route: "serversncodedemo/{id}"

So my function.json looks like this

    "bindings": [
      {
        "authLevel": "anonymous",
        "name": "req",
        "type": "httpTrigger",
        "direction": "in",
        "route": "serversncodedemo/{id}"
      },

Changing the authlevel is not required but I've done it for this demo.

Setting the route is what changes it to a GET, we're telling the function to expect id as part of the route to the function.

In our run.csx we have to add string id as a parameter into our function

public static async Task <HttpResponseMessage> Run(HttpRequestMessage req, string id, TraceWriter log)

We can now see it in a route like this

https://serversncodefunctiondemo.azurewebsites.net/api/serversncodedemo/{id}

We replace {id} with what ever we want and we will get a response.

We have now set the routes in our functions and these routes are the same serversncodefunctiondemo.azurewebsites.net/api/serversncodedemo/ we then have small changes for our POST and GET functions.

Azure Function Proxies

Proxies give us more control over all our functions or just selected methods instead of having to set the route in the function.json on each of our functions. Also if your using a custom domain it's used in Proxies. These are in Preview as of the creating of this post.

So lets create a proxy.

Create-Azure-Function-Proxy

On our Azure function create a new Azure function.

Define-Azure-Function-Proxy

I've created a Proxy called get,

We set a route template as person/{id} and then selected methods for the GET.

The backend URL is optional but in this case I set it to the same as the GET Function we created earlier.

https://serversncodefunctiondemo.azurewebsites.net/api/serversncodedemo/{id}

Click create and our Proxy is now created and ready.

Proxy-Detail

We have now created a proxy for our GET Function instead of having to use

https://serversncodefunctiondemo.azurewebsites.net/api/serversncodedemo/{id}

We can use

https://serversncodefunctiondemo.azurewebsites.net/person/{id}

Proxies and Routing provide a powerful and flexible layer on top of Azure functions to help organize your API.

A quick note on custom domains you can add a custom domain to Azure functions in the same way sas for Azure App service. But as of the writing of this post there are restrictions. I couldn't set it to a route domain but had to use a subdomain.

Source code here

Azure Function Proxies allow you to create a single unifed API surface for your Azure functions. The Microsoft Azure stack allows you to use different technologies so you can use the right tool for the job. Azure functions can also have routes. Unlike a Proxy a route will only effect…

Read More

Azure Functions with Table Storage

Using a HTTP Trigger Azure Function and storing the data into an Azure Table storage account. Azure Table storage is a service that stores structured NoSQL data in the cloud, providing a key/attribute store with a schemaless design.

You can find the code for this here

This post builds on some other posts I've done,

I've covered getting started on Azure Table Storage in an other post Azure Table Storage

I've also covered creating a HTTP Trigger Azure Function

So let's get too it.

Adding Table Storage

In the project.json file we need to add the nuget reference for "WindowsAzure.Storage" as of writing this post the current version is 8.4.0. Our project.json will look something like this.

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

        "WindowsAzure.Storage": "8.4.0"
      }
     }
   }
}

I've also got "Newtonsoft.Json" there because I want to use the Deserialize on the payload.

HTTP Trigger Function

Now over to our function in the run.csx and first we need our classes I have two. Our function will look something like this

using System.Net;
using Newtonsoft.Json;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");    

    dynamic body = await req.Content.ReadAsStringAsync();
    var e = JsonConvert.DeserializeObject<Person>(body as string);

    // Define the row,
    string sRow = e.email + e.lastname;

    // Create the Entity and set the partition to signup, 
    PersonEntity _person = new PersonEntity("signup", sRow);

    _person.First_Name_VC = e.firstname;
    _person.Last_Name_VC = e.lastname;
    _person.Email_VC = e.email;

    // Connect to the Storage account.
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse("XXX");

    CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

    CloudTable table = tableClient.GetTableReference("personitems");

    table.CreateIfNotExists();

    TableOperation insertOperation = TableOperation.Insert(_person);

    table.Execute(insertOperation);

    return req.CreateResponse(HttpStatusCode.OK, "Ok");
}

public class Person{
    public string firstname {get;set;}
    public string lastname {get;set;}
    public string email {get;set;}
}

public class PersonEntity : TableEntity
{
    public PersonEntity(string skey, string srow)
    {
        this.PartitionKey = skey;
        this.RowKey = srow;
    }

    public PersonEntity() { }

    public string First_Name_VC { get; set; }
    public string Last_Name_VC { get; set; }
    public string Email_VC { get; set;}
}

So lets break it down and take a look

Person Class and PersonEntity

At the bottom of our Function we add our classes we want to use.

public class Person{
    public string firstname {get;set;}
    public string lastname {get;set;}
    public string email {get;set;}
}

This person class is for the payload.

public class PersonEntity : TableEntity
{
    public PersonEntity(string skey, string srow)
    {
        this.PartitionKey = skey;
        this.RowKey = srow
    }

    public PersonEntity() { }
    public string First_Name_VC { get; set; }
    public string Last_Name_VC { get; set; }
    public string Email_VC { get; set;}
}

This is our Table storage entity.

References

Next at the top we need to add our references

using System.Net;
using Newtonsoft.Json;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;

From HTTP Trigger to Table Storage

Now that's the house keeping done, lets walk through our function and save our information into Azure table storage.

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");    

    dynamic body = await req.Content.ReadAsStringAsync();
    var e = JsonConvert.DeserializeObject<Person>(body as string);

    // Define the row,
    string sRow = e.email + e.lastname;

    // Create the Entity and set the partition to signup, 
    PersonEntity _person = new PersonEntity("signup", sRow);

    _person.First_Name_VC = e.firstname;
    _person.Last_Name_VC = e.lastname;
    _person.Email_VC = e.email;

    // Connect to the Storage account.
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse("XXX");

    CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

    CloudTable table = tableClient.GetTableReference("personitems");

    table.CreateIfNotExists();

    TableOperation insertOperation = TableOperation.Insert(_person);

    table.Execute(insertOperation);

    return req.CreateResponse(HttpStatusCode.OK, "Ok");
}

First up we want to Deserialise our payload and turn it into an object.


    dynamic body = await req.Content.ReadAsStringAsync();
    var e = JsonConvert.DeserializeObject<Person>(body as string);

dynamic body reads the Content of the HttpRequestMessage req.
We tehn pass that into the JsonConvert as a string. JsonConvert DeserializeOject turns that into an object we can use.

Next we create our table entity.

    // Define the row,
    string sRow = e.email + e.lastname;

    // Create the Entity and set the partition to signup, 
    PersonEntity _person = new PersonEntity("signup", sRow);

    _person.First_Name_VC = e.firstname;
    _person.Last_Name_VC = e.lastname;
    _person.Email_VC = e.email;

Table Storage uses a partition key and row key for each object. That's up to you to set. In this case I have set the partition to signup. The RowKey should be unique to the partition. I've set by combining the email and last name. In a real world I would only allow the email in my Table storage once, so I would validate I had no new ones. So email could a rowkey you can set it according to your use case.

Next we setup our Person object and set the properties.

    // Connect to the Storage account.
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse("XXX");

    CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

    CloudTable table = tableClient.GetTableReference("personitems");

    table.CreateIfNotExists();

    TableOperation insertOperation = TableOperation.Insert(_person);

    table.Execute(insertOperation);

We connect to our storage account, load our table of "personitems" I've added a check to create if not exists.

We then call the tableOperation and insert our new record to the database.

Wrap up

To end I have the function return OK, in the real world you might want more information here.

    return req.CreateResponse(HttpStatusCode.OK, "Ok");

We now have a function that takes a HTTP payload and stores it into an Azure function.

Expanding Functions

One of the great things about functions is you can create bindings on other things. So you could have another function that runs when an entry is made in Azure Table Storage. That trigger would do another job with the new person that has just signed up.

That's it for this one for more on Azure Functions and serverless check out the series of posts I've created here

Using a HTTP Trigger Azure Function and storing the data into an Azure Table storage account. Azure Table storage is a service that stores structured NoSQL data in the cloud, providing a key/attribute store with a schemaless design. You can find the code for this here This post builds…

Read More

Azure Functions Entity Framework - Part 2

In this post we will look at using Entity Frameworks Entity models and using our DbContext to create mappings and use these mappings in our Azure function. Azure functions use Code First approaches to Entity Framework.

Source code for this demo can be found here

For Azure Functions Entity framework - Part 1 covers the basics of adding Entity Framework to our Azure Function.

Getting Started

project.json

{
 "frameworks": 
 {  
  "net46":
  { 
   "dependencies":
   {
     "Newtonsoft.Json": "10.0.3",
     "EntityFramework": "6.1.3",
     "System.Data.Common": "4.3.0"
   }
  }
 }
}

Our run.csx will look something like this.

#r "System.Data"

using System.Net;
using System.Data;
using System.Data.SqlClient;
using Newtonsoft.Json;
using System.Linq;
using System.Data.Entity;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    dynamic body = await req.Content.ReadAsStringAsync();
    var e = JsonConvert.DeserializeObject<Person>(body as string);
    e.Created_DT = System.DateTime.Now;
    
    try
    {        
        using (PeopleContext context = new PeopleContext())
        {
            context.Persons.Add(e); 
            context.SaveChanges();            
        }
    }
    catch(System.Data.Entity.Infrastructure.DbUpdateException ex)
    {
        log.Info(string.Format("Failure with database update {0}.", ex.Message));        
    }      

    return req.CreateResponse(HttpStatusCode.OK, "Ok");
}

public class PeopleContext : DbContext
{
    public PeopleContext()
        : base("XXXX")
    { }

  public DbSet<Person> Persons { get; set; }
}

public class Person{
    public int Id { get; set; }
    public string FirstName_VC {get;set;}
    public string LastName_VC {get;set;}
    public string Email_VC {get;set;}
    public DateTime Created_DT {get;set;}
}

So lets go through what we're doing here. We'll start on our code from the bottom up.

Entity Model

public class Person{
    public int Id { get; set; }
    public string FirstName_VC {get;set;}
    public string LastName_VC {get;set;}
    public string Email_VC {get;set;}
    public DateTime Created_DT {get;set;}
}

We have our Person Class, this the entity we're going to use. We have a table in the database called "Person"

Note: Azure functions use a code first approach to EF. So if the person table doesn't exist it gets created the first time you try to insert data.

DbContext

With Entity framework we create a Dbcontext and create the mapping for our classes to the database.

public class PeopleContext : DbContext
{
    public PeopleContext()
        : base("XXXX")
    { }

  public DbSet<Person> Persons { get; set; }
}

We create a PeopleContext and pull in the DbContext. We then set the connection string as we want.

public DbSet<Person> Persons { get; set; }

Sets up our entity we can use Persons in our code now to get the table.

Wire the function

    dynamic body = await req.Content.ReadAsStringAsync();
    var e = JsonConvert.DeserializeObject<Person>(body as string);
    e.Created_DT = System.DateTime.Now;

Will take the Json Payload from the request and Deserialize it into an object of type Person for e.

We take e and open a context to our database.

    try
    {        
        using (PeopleContext context = new PeopleContext())
        {
            context.Persons.Add(e);
            context.SaveChanges();            
        }
    }
    catch(System.Data.Entity.Infrastructure.DbUpdateException ex)
    {
        log.Info(string.Format("Failure with database update {0}.", ex.Message));        
    }   

We add e to our persons entity and then save our changes.

This will result in a new record in the table.

Sample Payload.

{
 "FirstName_VC": "serversncode",
 "LastName_VC": "Entity",
 "Email_VC": "test@test.com"
}

That's it, in a single run.csx file we can build on our EF models to create a database connection. Remember functions are short lived things and "You had one job" kind of things so keeping our models simple and clear is important when it comes to functions.

I've made the sample as narrow as I could, for more on Serverless in Azure check out our series on Azure Functions

In this post we will look at using Entity Frameworks Entity models and using our DbContext to create mappings and use these mappings in our Azure function. Azure functions use Code First approaches to Entity Framework. Source code for this demo can be found here For Azure Functions Entity framework…

Read More