Showing posts with label nodejs. Show all posts
Showing posts with label nodejs. Show all posts

Reading Notes #342

Connector

Cloud


Programming

  • Writing a Blazor App (David Pine) - This tutorial shows how to build a simple blazor app...and it's NOT the hello-word or todo.

Miscellaneous



Reading Notes #341

IMG_20180815_181252Cloud


Programming


Integration


Miscellaneous


Books

  • VaporizedVaporized: Solid Strategies for Success in a Dematerialized World (Robert Tercek) - I really loved that book. In this world of digital transformation where everything goes so fast, this book explains why you should care. In fact, it asked so many good questions and related facts. I like to pretend I'm aware of the new technologies. That I'm on the edge, that I'm aware of the trending stuff... But guess what?! I got surprised, and even a bit scare at one point. This book is a must. Enjoy! ASIN: B01F9G31H8

Reading Notes #339

IMG_20180725_154113

Cloud



Programming



Data



Miscellaneous



~Enjoy!


Reading Notes #333

flag-28555_640Cloud


Programming


Data


Reading Notes #321

ester-eggs-2345859_640

Suggestion of the week



Cloud



Programming



Databases



Miscellaneous


Books



When: The Scientific Secrets of Perfect Timing (Daniel H. Pink)

A really amazing book packed of very interesting advice. Things that you kind of already knew, or at least had a feeling you maybe knew are clearly explained to you.

After reading (or listening) this book, you will know why, and you can decide to fight it or change the when... improve your performance and use your time and energy on something else.

ISBN: 0525589333






How to access an SQL Database from an Azure Function and Node.js

The other day, a friend asked me how he could add some functionality to an existing application without having access to the code. It the perfect case to demo some Azure Functions capability, so I jumped on the occasion. Because my friend is a Node.js developer on Linux, and I knew it was supported, I decided to try that combination. I know Node, but I'm definitely not and expert since I don't practice very often.

This post is my journey building that demo. I was out of my comfort zone, coding in Node and working on a Linux machine, but not that far... Because these days, you can "do some Azure" from anywhere.

The Goal


Coding an Azure Function that will connect to an SQL Database (it could be any data source). Using Node.js and tools available on Unbuntu.

Note: In this post, I will be using Visual Studio Code, but you could also create your function directly in the Azure Portal or from Visual Stusio.

Getting Started


If you are a regular reader of this blog, you know how I like Visual Studio Code. It's a great tool available on Mac Linux and Windows and gives you the opportunity to enjoy all its feature from anywhere feeling like if you were in your cozy and familiar environment. If VSCode is not already installed on your machine, go grap your free version on http://code.visualstudio.com.

Many extensions are available for VSCode, and one gives us the capability to code and deploy Azure Function. To install it, open VSCode and select the extension icon and search for Azure Function; it's the one with the yellow lighting and the blue angle brackets.

AzureFunctionExtension

Create the Azure Function


To get started let's great an Azure Function project. By sure to be in the folder where you wish to create your Function App. Open the Command Pallette (Ctrl + Shift + p) and type Azure Function. Select Azure Functions: Create New Project. That will add some configuration files for the Functions App.

Now Let's create a Function. You could reopen again the Command Palette and search for Azure Function: Create Function, but let's use the UI this time. At the bottom left of the Explorer section, you should see a new section called AZURE FUNCTIONS. Click on the little lighting to Create a new Function.

AzureFuncButton

After you specify the Function App name, the Azure subscription and other little essential, a new folder will be added in your folder structure, and the function is created. The code of our function is in the file Index.js. At the moment, of writing this post only Javascript is supported by the VSCode extension.

Open the file index.js and replace all its content by the following code.


var Connection = require('tedious').Connection;
var Request = require('tedious').Request
var TYPES = require('tedious').TYPES;

module.exports = function (context, myTimer) {

    var _currentData = {};

    var config = {
        userName: 'frankadmin',
        password: 'MyPassw0rd!',
        server: 'clouden5srv.database.windows.net',
        options: {encrypt: true, database: 'clouden5db'}
    };

    var connection = new Connection(config);
    connection.on('connect', function(err) {
        context.log("Connected");
        getPerformance();
    });

    function getPerformance() {

        request = new Request("SELECT 'Best' = MIN(FivekmTime), 'Average' = AVG(FivekmTime) FROM RunnerPerformance;", function(err) {
        if (err) {
            context.log(err);}
        });

        request.on('row', function(columns) {
            _currentData.Best = columns[0].value;
            _currentData.Average = columns[1].value;;
            context.log(_currentData);
        });

        request.on('requestCompleted', function () {
            saveStatistic();
        });
        connection.execSql(request);
    }


    function saveStatistic() {

        request = new Request("UPDATE Statistic SET BestTime=@best, AverageTime=@average;", function(err) {
         if (err) {
            context.log(err);}
        });
        request.addParameter('best', TYPES.Int, _currentData.Best);
        request.addParameter('average', TYPES.Int, _currentData.Average);
        request.on('row', function(columns) {
            columns.forEach(function(column) {
              if (column.value === null) {
                context.log('NULL');
              } else {
                context.log("Statistic Updated.");
              }
            });
        });

        connection.execSql(request);
    }

    context.done();
};

The code just to demonstrate how to connect to an SQL Database and do not represent the best practices. At the top, we have some declaration the used the package tedious; I will get back to that later. A that, I've created a connection using the configuration declared just before. Then we hook some function to some event. On connection connect the function getPerformance() is called to fetch the data.

On request row event we grab the data and do the "math", then finally on requestCompleted we call the second sub-function that will update the database with the new value. To get more information and see more example about tedious, check the GitHub repository.

Publish to Azure


All the code is ready; it's now time to publish our function to Azure. One more time you could to that by the Command Palette, or the Extension menu. Use the method of your choice and select Deploy to Function App. After a few seconds only our Function will be deployed in Azure.

Navigate to portal.azure.com and get to your Function App. If you try to Run the Function right now, you will get an error because tedious is not recognized.

Install the dependencies


We need to install the dependencies for the Function App, in this case tedious. A very simple way is to create a package.json file and to use the Kudu console ton install it. Create a package.json file with the following json in it:


{
    "name": "CloudEn5Minutes",
    "version": "1.0.0",
    "description": "Connect to Database",
    "repository": {
       "type": "git",
       "url": "git+https://github.com/fboucher/CloudEn5Minutes.git"
    },
    "author": "",
    "license": "ISC",
    "dependencies": {
        "tedious": "^2.1.1"
    }
}

Open the Kudu interface. You can reach it by clicking on the Function App then the tab Platform features and finally Advanced tools (Kudu). Kudu is also available directly by the URL [FunctionAppNAme].scm.azurewebsites.net (ex: https://clouden5minutes.scm.azurewebsites.net ). Select the Debug console CMD. Than in the top section navigate to the folder home\site\wwwroot. Drag & drop the package.json file. Once the file is uploaded, type the command npm install to download and install all the dependencies declared in our file. Once it all done you should restart the Function App.

Kudu

Wrapping up & my thoughts


There it is, if you go back now to your Function and try to execute it will work perfectly. It's true that I'm familiar with Azure Function and SQL Database. However, for a first experience using Ubuntu and Node.js in the mix, I was expecting more resistance. One more time VSCode was really useful and everything was done with ease.

For those of you that would like to test this exact function, here the SQL code to generate what will be required for the database side.


    CREATE TABLE RunnerPerformance(
        Id           INT IDENTITY(1,1)  PRIMARY KEY,
        FivekmTime   INT
    );

    CREATE TABLE Statistic(
        Id          INT IDENTITY(1,1)  PRIMARY KEY,
        BestTime    INT,
        AverageTime INT
    );

    INSERT Statistic (BestTime, AverageTime) VALUES (1, 1);

    DECLARE @cnt INT = 0;

    WHILE @cnt < 10
    BEGIN
    INSERT INTO RunnerPerformance (FivekmTime)
            SELECT  9+FLOOR((50-9+1)*RAND(CONVERT(VARBINARY,NEWID())));
    SET @cnt = @cnt + 1;
    END;

Video version



References


Reading Notes #303

logo-glyphSuggestion of the week

  • Writing tests in Postman (joyce) - With all the connected things and all the API in our system, this post shows a brilliant and simple way to test all those external calls.

Cloud


Programming


Data


Miscellaneous




Reading Notes #298

IMG_20170919_161146Cloud


Programming


Miscellaneous

  • #222: Patrick Lencioni—Getting Hiring Right (EntreLeadership Team) - It was my first episode of this podcast, but definitely not the last one. Very interesting speakers... nice books referenced... loved it.
  • Why Your Boss Makes You Punch a Time Clock (Suzanne Lucas Suzanne Lucas is a freelance writer who spent 10 years in corporate human resources, where she hired, fired, managed the numbers, and double-checked with t) - Most of us have to do timesheets... I'm sure that at one point, you asked yourself the reason about it. It's time read an answer, in this post.


Reading Notes #285

IMG_20170614_194330Cloud

Programming

Suggestion of the week

Miscellaneous



Reading Notes #280

IMG_20170511_082902Cloud


Miscellaneous


Reading Notes #276

roslynSuggestion of the week


Cloud


Programming


Miscellaneous

Reading Notes #260

shopping-cart-1275482_640Suggestion of the week


Cloud


Programming


Miscellaneous


Reading Notes #250

250Notes

 

Suggestion of the week


Cloud


Programming



Reading Notes #249

logicappSuggestion of the week


Cloud


Programming


Databases


Miscellaneous




Reading Notes #241

IMG_20160711_083348Cloud


Programming


Miscellaneous


Reading Notes #240

Cloud


Programming


Data


Miscellaneous


Reading Notes #224

Cloud


Programming


Miscellaneous


Reading Notes #222

hourglassSuggestion of the week


Cloud


Data



Reading Notes #219

AzureSDK2-8-2Suggestion of the week


Cloud


Programming


Books



Reading Notes #214

Suggestion of the week

  • Express - This is the perfect post to get started with node.js with Azure. This post starts with you step by step from a vanilla computer running OS X or Linux to your first App.

Cloud


Programming


Data


Miscellaneous