Fluent API Libraries for Azure .NET SDK

Just as Microsoft is constantly working to update, upgrade and add to the overall Microsoft Azure platform, they are also working to keep updating and improving the development tools to match. The current Azure .NET SDK has been around for quite some time now. While it’s stable, there may be some room for improvement to the overall Azure developer experience. Microsoft recently announced they are working on a newer set of Azure API libraries for use with the .NET Framework that are based on Fluent Interfaces. This article describes both what a “Fluent Interface” is, as well as what the new fluent Azure SDK for .NET has to offer and how it can be used.

What is a Fluent Interface?

The term “Fluent Interface” is relatively new, but Fluent Interfaces are not new to the software industry. In fact fluent interfaces have their origins all the way back to the 1970s in the Smalltalk language and its invention of method cascading. However, like many other programming constructs and patterns, it has taken some time to finally get more broadly adopted. As a result, the term “Fluent Interface” wasn’t coined until 2005 (by Eric Evans and Martin Fowler) when the use of this code pattern finally started gaining traction in other programming languages.

The purpose of Fluent Interfaces is to implement APIs that enable code to be written that’s much easier to read. The idea is that when code is easier to read, it’s also easier to edit and maintain.

With “traditional” code for an object oriented API, the method calls are written and executed step-by-step, line-by-line in a progressive style. Here’s a simple example of this progressive style:

var obj = new DomainObject();
obj.SetValueOne(42);
obj.SetValueTwo(2063);
obj.PerformAction();
obj.Apply()

As you can see, with a “traditional” / progressive coding style to an API, the different method calls are run on a new line per method call.

Fluent Interfaces on the other hand enable the code using the API to be written such that methods can be chained together, one after the other, by passing back a reference to the object as the return value of each method call. Here’s a simple example of using a similar API that implements a Fluent Interface:


// 1 line

var obj = new DomainObject().SetValueOne(42).SetValueTwo(2063).PerformAction().Apply();

// multiple lines

var obj = new DomainObject()

    .SetValueOne(42)

    .SetValueTwo(2063)

    .PerformAction()

    .Apply();

The way a Fluent Interface is implemented is by returning the object itself as the return value from each method call so that another method call on that object can be called immediately on the same line of code.

To help clarify the way an API implementing a Fluent Interface works, here’s a simple example of what the source code of the “DomainObject” in the above Fluent Interface usage example could be:

public class DomainObject
{
    public DomainObject() {
        // ... constructor logic here ...
    }

    public DomainObject SetValueOne(int val)
    {
        // ... code goes here ...

        return this;
    }

    public DomainObject SetValueTwo(int val)
    {
        // ... code goes here ...

        return this;
    }

    public DomainObject PerformAction()
    {
        // ... code goes here ...

        return this;
    }

    public DomainObject Apply()
    {
        // ... code goes here...

        return this;
    }
}

One of the things that is different from an API that implements a Fluent Interface is that all property setters are implemented as regular methods so they can return a reference to the object itself. The reason for this is that traditional, progressive Properties in Object Oriented programming aren’t able to return a value.

The above example is a really simple example of a Fluent Interface. Full APIs could be a bit more advanced in the way Fluent Interfaces are used by implementing methods that can return and accept parameters of other Fluent objects. This allows for sort of a “nested” Fluent Interface API to be implemented. There really is a lot of flexibility to the way Fluent Interfaces are implemented to meet the specific needs of a particular API implementation.

Azure Fluent API

The new, Simple Azure Management Libraries for .NET allow for MANY common Azure .NET code scenarios to be implemented in ways that can be done with only a single line of code. If you’re familiar with the older Azure .NET SDK, then you’ll know it can be a bit cumbersome by requiring multiple lines of code to perform pretty much any action.

It’s nice to be able to code and automate tasks using a code API, but there are times when something different could be a better way. The new Azure Management Libraries for .NET that bring along a Fluent Interface style API to Azure .NET SDK coding really does bring a better, easier way to writing Azure code with C# and other .NET Framework languages.

Instead of giving some descriptions of how the new APIs work and how to use them, I’ll just list a few code samples to demonstrate exactly how to use these new Azure Management Libraries for .NET.

Authenticate with an Azure Subscription

Here’s an example of how you can now authentication with an Azure Subscription with only a single line of code:


var az = Azure.Authenticate(credFile).WithDefaultSubscription();

Create / Provision a new Virtual Machine (VM)

Here’s an example using the Fluent Interface API to create and provision a new Virtual Machine in Azure:


var windowsVM = az.VirtualMachines.Define("myWinVM")
    .WithRegion(Region.US_EAST)
    .WithNewResourceGroup(resourceGroupName)
    .WithNewPrimaryNetwork("10.0.0.0/28")
    .WithPrimaryPrivateIpAddressDynamic()
    .WithNewPrimaryPublicIpAddress("mywindowsvmdns")
    .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER)
    .WithAdminUserName("serveradmin")
    .WithPassword(pwd)
    .WithSize(VirtualMachineSizeTypes.StandardD3V2)
    .Create();

This example create a new Windows VM in Azure using the Windows Server 2012 R2 Datacenter image form the Azure Marketplace with an Instance Size of the Standard D3V2. It also specifies the Resource Group to create it in, as well as IP Address information, and the administrator credentials for the server.

Create a Network Security Group

Here’s a little more advanced example that sets up a Network Security Group with a couple rules assigned to it:

var frontEndNSG = azure.NetworkSecurityGroups.Define(frontEndNSGName)
    .WithRegion(Region.US_EAST)
    .WithNewResourceGroup(rgName)
    .DefineRule("ALLOW-SSH")
        .AllowInbound()
        .FromAnyAddress()
        .FromAnyPort()
        .ToAnyAddress()
        .ToPort(22)
        .WithProtocol(SecurityRuleProtocol.Tcp)
        .WithPriority(100)
        .WithDescription("Allow SSH")
        .Attach()
    .DefineRule("ALLOW-HTTP")
        .AllowInbound()
        .FromAnyAddress()
        .FromAnyPort()
        .ToAnyAddress()
        .ToPort(80)
        .WithProtocol(SecurityRuleProtocol.Tcp)
        .WithPriority(101)
        .WithDescription("Allow HTTP")
        .Attach()
    .Create();

Storage Account Management

Here’s how you can create a new Azure Storage Account:

var storageAccount = az.StorageAccounts.Define(storageAccountName)
    .WithRegion(Region.US_EAST)
    .WithNewResourceGroup(resourceGroupName)
    .Create();

Where to Download

The new Microsoft Azure SDK for .NET that implements the Fluent Interface pattern is Open Source and hosted on Github at https://github.com/Azure/azure-sdk-for-net/tree/Fluent

Currently it’s in Beta (v1.0.0-beta3) at the time this article was written. This Beta is a developer preview that supports major parts of Azure VMs, VM Scale Sets, Storage, Networking, Resource Manager, Key Vault, and Batch. It doesn’t support everything just yet, but it is an active work in progress with more releases to come over the next few months adding more features.

With the project being Open Source, the community can contribute to it. This means that anyone could start adding support for other Azure services not yet in the Fluent API and contribute that back as Pull Requests to the project. OSS FTW!

3 thoughts on “Fluent API Libraries for Azure .NET SDK

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s