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

Azure Table Storage

About Azure Table Storage

Windows Azure Table storage is a service that stores structured data in the cloud. It's like NoSQL but with more of the SQL, for example it does not store the data as a Document but as rows. You still get the flexibility of NoSQL storage.

Table storage is a non-relational, key-value-pair, storage system suitable for storing massive amounts of unstructured data. Whereas relational stores such as SQL Server, with highly normalized designs, are optimized for storing data so that queries are easy to produce, the non-relational stores like Table Storage are optimized for simple retrieval and fast inserts. Table storage is schemaless, it's easy to adapt your data as the needs of your application evolve. Access to data is fast for all kinds of applications. Table storage is typically significantly lower in cost than traditional SQL for similar volumes of data.

You can use Table storage to store flexible datasets, such as user data for web applications, address books, device information, and any other type of metadata that your service requires. You can store any number of entities in a table, and a storage account may contain any number of tables, up to the capacity limit of the storage account.

Pricing

Windows Azure table storage is cheap. All you pay for the number of transactions and the amount of storage you need. So no licences, no servers, no VM's just what you need when you need it.

Azure Table pricing

This is the pricing in EUR for North Europe for more go here and select "Table" as the storage to see the pricing.

So what that means is that if I want to store 100 GB of data and access it 200,000 times. I pay less than EUR 6. That's great however you look at it. It means I can store a massive about of data and have quick ready access to it and not have to worry about the cost.

Getting started

To get started, open your Azure Protal and select "New" filter to "Storage account" and select "General Purpose" provide a name and select the "Resource Group"

Create Azure Storage Group

Once you hit create you have to wait for it to deploy and create the storage account.

Azure Storage Group Deployed

Once it's deployed go ahead and open it up. Selecting "Tables" will show "no tables found" in the tables blade.

We need the Access keys for be able to do anything. In the main storage blade select "Settings" and click to open Access keys this will show you a "Key1" and "Key2"

Azure Storage Access keys

We'll need them next.

Do some code

For the sample code github

In Visual studio create a new Console Application

Install the Azure Storage nuget package

Now in the main cs file lets bring in the Azure Storage

using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Table;

For Azure Storage our connection string looks like this

DefaultEndpointsProtocol=https;AccountName=storagesample;AccountKey=storagesamplekey

Where StorageSample and StorageSampleKey would be replaced with the account name and the key that you want to use.

For this demo I created a static string and loaded my connection string into it.

Next we need to create our entity. Create a new class 'PlayerEntity'

In this class we'll turn it into a Table Entity

using Microsoft.WindowsAzure.Storage.Table;

public class PlayerEntity : TableEntity

The rest of our Player class should come together like this

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

    public PlayerEntity() { }

    public string Sport_VC { get; set; }
    public string Club_VC { get; set; }
    public string First_Name_VC { get; set; }
    public string Last_Name_VC { get; set; }
    public string Position_VC { get; set; }
}

Back over to our Program.cs, lets add some code to do something.

    static void Main(string[] args)
    {
        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, "soccer"));

int iCount = 0;
        foreach (PlayerEntity entity in table.ExecuteQuery(query))
        {
            Console.WriteLine("Club:" + entity.Club_VC + " Player Name: " + entity.First_Name_VC + " " + entity.Last_Name_VC + " Position: " + entity.Position_VC);

            iCount++;
        }



    }

Lets walk through this code step by step.

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

This will create the storage account with our connection string.

        // 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();

Create a table client and then we create a table called "player" then we check if it exists. If it does not then table.CreateIfNotExists() will create a new table for us.

Next we'll go and get some data from the table.

        // Get All Players for a sport

        TableQuery<PlayerEntity> query = new TableQuery<PlayerEntity>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "soccer"));

You might have worked out the theme for this now. But this code allows us to create a query to get the players for a sport. In this case "soccer", The partition we created on this table is for Sports. Once we have built the query we can execute it.

int iCount = 0;
        foreach (PlayerEntity entity in table.ExecuteQuery(query))
        {
            Console.WriteLine("Club:" + entity.Club_VC + " Player Name: " + entity.First_Name_VC + " " + entity.Last_Name_VC + " Position: " + entity.Position_VC);

            iCount++;
        }

Here we execute the query which will return records for the Sport and then write them to the console. If you run this application now it will return nothing because we haven't created any data.

So lets create some data
static Boolean CreateData(string sSport, string sRow, string sFirstName, string sLastName, string sClub, string sPostition)
{
Boolean bSuccess = false;

        // 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);

            bSuccess = true;
        }
        catch (Exception ex)
        {
            bSuccess = false;
        }


        return bSuccess;
    }

What does this code do,

First of all we create a new method for creating the data.

        // 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;

We create our player Entity and setup the values.

PlayerEntity _record = new PlayerEntity(sSport, sRow)

Will create our table entity for us with the Row ID and the Partition key.
Row ID should be unqiue

TableOperation insertOperation = TableOperation.Insert(_record);

This sets it all ready to go, then we do the table.Execute(insertOperation); to create the record on our table.

So what I've done for this demo is add a iCount int that will hold the record count. Then at the end we add a call to our create data and it will create our first player.

CreateData("soccer", iCount.ToString(), "Wayne", "Rooney", "Man Utd", "Striker");

Once you run the app it will create the footballers and that's it, it's very simple to get started.

For the sample code github

About Azure Table Storage Windows Azure Table storage is a service that stores structured data in the cloud. It's like NoSQL but with more of the SQL, for example it does not store the data as a Document but as rows. You still get the flexibility of NoSQL storage. Table…

Read More