Vainolo's Blog

Archive for the ‘C#’ tag

Azure Functions – Part 1: Getting Started

leave a comment

I love to write software. And because I’m not a software developer anymore I don’t get much time to do it, and it has always bugged me the incredible amount of work that is needed to configure, maintain, and in general, manage the infrastructures on which the software runs, which is what I really want to work on. So It’s no surprise that I’m a HUGE fan of server-less programming, as it is provided by Azure Functions (and others like Amazon Lambda or Google Cloud Functions). Since I get some free credits from Microsoft, I had to give this a try… and I’m loving it :-).

I assume that you have an Azure subscription, but if not, just go to https://signup.azure.com and get yours free. At the time of writing this, you even get a $200 credit valid for 30 days. Great to start playing.

The end goal of this tutorial is to have a full blown application for the analysis of financial data, all on top of a fully server-less infrastructure. Let’s see how far I can go. I’m very verbose in my tutorials because I’m a big consumer of them (both of other but also of mine :-)), and I hate it when they don’t show all the steps needed to perform something and you need to guess steps and many times end in an incorrect state that breaks the whole flow.

So let’s get started creating our first Azure Function! Navigate to https://portal.azure.com/, and after logging in you should be inside the Azure portal which looks something like this:

clip_image001[4]

To keep things organized, I have created a resource group to keep all of the resource associated with the tutorials in one place, and this is the tile shown in the dashboard (which I also created for these tutorials). A resource group is a logical container of resources in Azure, and helps maintain your subscription organized.

So let’s click on the nice blue "Create Resources" button, and see where we go:

clip_image001[6]

This screen is probably different for every person depending on what they have in their subscription, and I can’t see Azure Functions here, so I’ll do a search:

clip_image001[8]

And yes, there it is, the first result in the search. Clicking on the "Function App" row will open a new "blade" (yes, that’s how those vertical panes are called) that gives a short description of what is a Function App:

clip_image001[10]

This is what I came for, so I’ll click on the create button, which as expected opens a new "blade" (you can see that a new blade is created by looking at the horizontal scroll bar that keeps on growing on the bottom of the screen) where we can enter the details for the Function App we are creating:

clip_image001[12]

Let’s fill in the details for the App. First, the App name, must be unique over all azure websites (on top of which Azure Functions run), so let’s call it "vainolo-azfun" (as expected, it’s not taken :-)). I’m going to use my existing subscription to pay for this App and add it to the resource group from where I started this whole process (you can come to this screen from a different place and there you will have to chose the Resource Group). The Hosting Plan is how you pay for the App. There are two options: Consumption or App Service. Consumption is a "pay-as-you-go" charge where you are billed by the number of requests to the App, and App Service let’s you reserve compute resources to service your App. For tutorials and testing purposes, I’m assuming that Consumption plan is cheaper that App Service (need to check this!), and regardless of this it is also more straightforward so I chose Consumption. I leave the location as it is because I don’t really care, but when you are developing a serious service you need to have your Apps close to your clients, so this is important. Lastly, we need to create a Storage account, the place where Azure stores the code that is deployed in the function. I’ll just name this "vainoloazfun" (no dashed allowed here! And this also needs to be unique over all Storage services in Azure). I’m not going to enable Application Insights because this is not a real production App, but I’ll investigate its capabilities in the future.

Ok, this is what I have now:

image

I’ll go ahead an click on Create, and see what happens… Ah, the creation blade closes and after some time a message pops out of the little bell on the top right corner of the screen. When I click on it I see that the deployment of my Function App was successful:

clip_image001[16]

I’ll just go ahead and click on the "Go to Resource" button to navigate to my new, nice and shiny Function App, that looks like this:

clip_image001[18]

Great. But talk about overhead – to create a simple function I need a resource group, a storage account, a function app, and then only can I create a function. Man, we could do this way better. But let’s go on.

Let’s create our first function.. Click on the "Functions" text from the drop-down list from "vainolo-azfun" and you will get the Functions screen where a new Function can be created:

clip_image001[20]

I’ll go ahead and click on "+ New Function", getting the following screen:

clip_image001[22]

There are many options here and I will surely investigate them in the future, but for our first example we’ll create a simple Function and responds "Hello World" to an HTTP request. This is done using the "HTTP trigger" template. I’ll click on that option and a new blade opens asking me the name of the Function and the language in which I want to write it:

clip_image001[24]

I’ll select C# as I’m more familiar with it than JS (where is Java???), and I’ll call my function "HelloWorld". Once the language of the function is defined, a new option may suddenly appear in the blade (bad UX practice!) asking for the Authorization level. I’ll select Anonymous because it’s the simplest way to test the function:

clip_image001[26]

I now click "Create", and after a short wait this is what I get:

clip_image001[28]

Instead of getting a blank function (what I expected), Azure already fills my function with sample code that does much more than I wanted, by parsing the request and responding based on the query parameters. I think this is great because it gives you an idea of what you are doing :-). I’ll just delete everything except the first and last line of the function, change the return value to "Hello World":

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 World");
}

clip_image001[30]

That’s it. My function is ready! But does it work? It’s easy to check that! Clicking on "Save and Run" button, the function is compiled and a simple test is executed:

clip_image001[32]

And just as expected, my function returns "Hello World" as output.

But I’m a skeptic, and want to see this working outside of the Azure portal. To do this, I need to get the URL of the function, which is fetched by clicking on the "Get Function URL" link on the top of the editor, but it is also easy to create manually: https://vainolo-azfun.azurewebsites.com/api/HelloWorld (https://AppURL/api/FunctionName):

clip_image001[34]

I’ll open a new browser window and navigate to this URL, and Voila!

image

Not exactly what I expected… What is returned by the server is an XML message that contains "Hello World", and the reason for this is because the client (Chrome in this case) requests HTML or XML as response first (and other things later) and the server automagically decides to translates the text response to XML so that it can make the browser happy. So let’s try another way. Using a tool I found called https://www.hurl.it, I can test it again and here the response is once again as was shown in the Azure portal:

clip_image001[36]

And there you have it, my first Azure Function ;-).

In summary, we created in this tutorial a Function App, which is a container for multiple Azure Functions, and a simple Azure Function that returns "Hello World" when called. It’s a good place to start!

And I hope to get some time to play with this some more very soon.

Written by vainolo

February 6th, 2018 at 11:39 pm

C# for the Impatient, Lesson 1 – The Basics

leave a comment

To be able to follow this tutorial, I assume that you have a working Visual Studio environment (I’m using VS2013). I’m pretty sure there are other ways to create C# programs (mono for example) but for beginners VS does a lot of magic that saves time. Maybe later as I understand the basics, I’ll investigate other options for creating and building C# programs. I also assume that you already know how to program and are just searching for a fast way to get started on C# (just like what I am doing/did), so I’ll be skipping many details here. All code examples in this tutorial are located at github, so you don’t have to copy and paste all the time from the browser.

We’ll start by creating a simple console application in which we will learn the basics of the language. This is done by selecting “File–>New–>Project”. Select “Console Application” under The “Templates–>Visual C#–>Windows” tree on the left. You have three things to decide: the name of the project, the name of the solution, and where they are located. A few words on solutions and projects: A solution is a logical grouping of projects. A project MUST be contained inside a solution. A solution may contain more than one project, and also elements that are not part of a specific project, like build files, or configuration files. A project is usually a single application component (.exe, .dll, service role, etc.). I created a solution called “learning-csharp”, and my first project is called “lesson1”. VS works it’s magic and opens a new file “Program.cs” that I can start editing. So let’s do the typical example and print “hello world” to the console:

using System;

namespace lesson1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World");
        }
    }
}

Now hit F5 to run the program. You will see a console that opens and closes. What’s wrong here? nothing – VS opened a console, executed the app and when the app finished, closed the console. But we want to see that the program really worked! so let’s add something that leaves the console open. This is easy – ask the user for input:

using System;

namespace lesson1
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Hello World");
      Console.ReadLine();
    }
  }
}

Now if you hit F5, the console will print “Hello World” and will stay on top, waiting for the user to enter something and hit enter. So go ahead and hit enter. This will let the program finish and close the console window.

Great, we have our first program running. Now let’s do a quick run on the language basics, starting with variables. Variables are declared giving them a type and a name, and optionally an initial value. For example:

int i = 1;
bool b = true;
string s = "hello";

When you type this in VS, you probably saw something interesting: auto-complete proposes both string and String, or int and IntXX where XX can be 16, 32, and 64. From the “simple programmer” POV, they are the same (Int16 is short, Int32 is int, etc.). Under the hood, we have both primitive types (int, bool, string) and classes (Int32, String). Bear with me here, we’ll get to classes later), with a direct matching between a primitive type and an a class. The primitive type is probably stored in a smaller memory space and when used as an object it is Boxed, and when an object is set into a primitive type it is Unboxed. So use the ones you like, just know that using only class types may reduce your performance because of Boxing/unboxing.

So let’s extend our function to write some variables and their values (changes only in the main function). I also added a new trick that shows how to print multiple variables to the console:

static void Main(string[] args)
{
  Console.WriteLine("Hello World");
  int a = 1;
  bool b = true;
  String c = "Something";
  var d = 34.5;
  Console.WriteLine("a = {0} is an integer, b = {1} is a boolean, c = {2} is a string, d = {3} is a var", a, b, c, d);
  Console.ReadLine();
}

Oh, I missed another cool (IMHO) feature of C# – the var declaration. I won’t get into details here (mainly because I don’t know them), but the idea is that if the compiler can understand what is the type of the value of a variable, then you can declare it as var. This comes really handy when you have long type names – which are a good practice. To finish this basic section, let’s define a couple of arrays. The array definition is similar to C/C++/Java. As a Java programmer, I tried using int array[] but it doesn’t work. So don’t try it.

int[] arr1 = {1,3};
int[] arr2 = new int[5]; 

Now for some control structures. We have the usual suspects here: for, while, and do-while.

for (int i = 0; i < 5; i++)
{
    Console.WriteLine("i is {0}.", i);
}

int j = 5;
while (j >= 0)
{
    Console.WriteLine("j is {0}.", j);
    j--;
}

int k = 5;
do
{
    Console.WriteLine("k is {0}.", k);
    k--;
} while (k >= 0);

And the unusual one: foreach.

int[] l = { 1, 2, 3, 4, 5 };
foreach (var item in l)
{
    Console.WriteLine("item is {0}.", item);
}

So putting everything together, here’s the program we have:

using System;

namespace lesson1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World");

            // simple variables;
            int a = 1;
            bool b = true;
            String c = "Something";
            var d = 34.5;
            Console.WriteLine("a = {0} is an integer, b = {1} is a boolean, c = {2} is a string, d = {3} is a var", a, b, c, d);
            Console.ReadLine();

            // Arrays
            int[] arr1 = {1,3};
            int[] arr2 = new int[5];

            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("i is {0}.", i);
            }
            Console.ReadLine();

            int j = 5;
            while (j >= 0)
            {
                Console.WriteLine("j is {0}.", j);
                j--;
            }
            Console.ReadLine();

            int k = 5;
            do
            {
                Console.WriteLine("k is {0}.", k);
                k--;
            } while (k >= 0);
            Console.ReadLine();

            int[] l = { 1, 2, 3, 4, 5 };
            foreach (var item in l)
            {
                Console.WriteLine("item is {0}.", item);
            }
            Console.ReadLine();

        }
    }
}

I think this is enough for a first lesson. Before we finish, let’s talk a bit about conventions. As an experienced (and pedantic) programmer, I really like to follow language conventions, both in the formatting and in the naming of elements. This is because conventions makes it easier to read code by reducing how much the brain has to process, because it recognizes the convention as a pattern in the code (I just made up that explanation, but I’m sure I can prove it anecdotally). So these are the basics (based on this and this articles):

  • Names use camelCase. Variables with initial lowercase, classes with initial uppercase.
  • Every statement is in one line, including opening and closing braces (this REALLY bothers me).
  • 4 spaces indentation
  • Namespaces should follow the [Company].([Product]|[Technology]).[Feature].[Subnamespace] format.

Hope you enjoyed the tutorial. More will be coming (hopefully) soon.

Written by vainolo

May 14th, 2014 at 11:43 pm

%d bloggers like this: