Node.js is an exciting platform that has been increasing in popularity for the past few years. It offers a server side JavaScript programming model ideal for building highly scalable and performant network applications whether on premise or in the cloud. In this talk we will take a look at various options for building and deploying Node applications on Microsoft Azure. This session is how to useAzure SQL Databse and Azure Storage with Node.js
1. Cherno More Hotel
12 July 2014
Boris Simandoff, Product Manager @ Chaos Group
Mihail Mateev, Senior Technical Evangelist, TL @ Infragistics Inc.
Node.js and Open Source Software Development
on Microsoft Azure
2. How this talk has started….
Боби, хайде да направим
една презентация за
Microsoft Azure
3. How this talk has started….
Ами… щом е за облачни
технолологии
няма да откажа…
но нека да е с Node.js
4. How this talk has started….
А защо да не е за
open source
технологии в
Microsoft Azure ?
Да включим и други
технологии ?
5. How this talk has started….
Ето така се
правят
презентации…
6. How this talk has started….
Момчета, това е
една интересна
тема за Varna Conf
7. Mihail Mateev
• About…
Mihail Mateev is a Senior Technical Evangelist, Team
Lead at Infragistics Inc., Community Lead for Europe,
Microsoft Azure MVP
Mihail works in various areas related to Microsoft
technologies : Silverlight, WPF, WP, LightSwitch, WCF,
ASP.Net MVC, MS SQL Server and Microsoft Azure
8. Contents
• Why Node.js
• Comparing Node.js to .NET
• Introduction to Node.js on Windows
• Using Azure SQL Database with Node.js
• Accessing Azure Storage with Node.js
• Building a Web Site with Node.js
• Deploying a Node.js Application
• Node.js & Edge.js
• Microsoft Azure Mobile Services and Node.js
• Resources
9. What is Node.js
• Node.js is a simple but powerful tool for asynchronous
network programming
• By utilizing your existing knowledge of JavaScript, you can get
up and running Apps quickly
• Node.js is based on V8 JS engine
10. What is Node.js
• Practically no installation required
• Very lightweight (one 7MB static exe)
• Node.js encourages good software practices out of the box
like async programming and inversion of control
11. Why Node.js?
• Node.js uses JavaScript syntax.
• There are more than 100 000 000 WEB developers!
• The realistic reason:
Cross platform applications with JS will be faster and easier
12. Why Node.js?
• The good parts of JavaScript are really awesome
•
• One language for the browser and the server
• Async by default
• Over 1M concurrent requests
13. Node.js Timeline
2009 2010 2011 2012 2013 2014
Jan 2009
Created
Ryan Dahl
April 2010
Heroku
launches
node
support
Nov 2011
Windows Azure
support
EBay releases API
built on node
Cloud9IDE azure
support
Oct 2011
node.js
overtakes Ruby
as most popular
repo on gitHub
Walmart
Launch mobile
site on node.js
Feb 2012
App
Harbour
support
July 2011
LinkedIn adopts
node for mobile
platform
port to Windows
IISNode
July 2010
Yammer
adopts
node.js
Nov
2010
Cloud9I
DE
launches
April 2014
Visual Studio
support
Node.js for
VS 2012 & 2013
Beta 1.0
Nov 2013
Visual Studio
support
Node.js for
VS 2012 & 2013
Alpha 1.0
14. Comparing Node.js to .NET
• Traditional Web Server Model
Client Server
Request
Response
Dedicated Thread
to service request
15. Comparing Node.js to .NET
• Traditional Web Server Model
Request 1
thread 1 processes the request
and blocks till completion
Response 1
thread 1000 processes the request
and blocks till completion
Web Server (with 1000 threads)
Request 1000
Response 1000
Request 1001
Request 1002
Request 1003
Requests queue up
as blocked threads
wait on server
16. Comparing Node.js to .NET
• Async Web Server Model
Client Server
Request
Response
Thread is free to
service other requests
Return from Async
Do Async Work
Once event or async
operation is complete
thread completes the
request
17. Comparing Node.js to .NET
• Async Web Server Model
Web Server
Request 1
Request 99999 Single threaded
event Loop
• Listen for requests
• Starts any I/O operations by
specifying a call back to execute
on completion
• Continue to listen for requests
Response 5
Response 1
“With node.js everything runs in parallel
Except your code ! ”
Response 99999
18. Comparing Node.js to .NET
• Mapping the Nomenclature
IIS Node.js
C# / VB JavaScript
EF / SQL Server Mongoose/MongoDB or other
Database
ASP.NET Web Forms Express + EJS
ASP.NET MVC/Razor Express + Jade/Razor
ASP.NET Web API Express/Hapi
SignalR WS / Socket.IO
AngularJS / KnockoutJS AngularJS / KnockoutJS
22. Introduction to Node.js on Windows
• How Node.js works?
• Asynchronous I/O
• Event Loop with Pool of Threads
• Dead-Lock Free (no concurrency issues)
24. Introduction to Node.js on Windows
• Why Node.js
• The good parts of JavaScript are really awesome
• One language for the browser and the server
• Async by default
• Over 1M concurrent requests
25. Introduction to Node.js on Windows
• Enabling a Node.js Server-Side App on Microsoft
Azure (PaaS)
• Web Role - all requests are received by
Microsoft IIS 7 and passed to a native IIS module
called iisnode
• Worker roles are much more like the basic node
application in that they directly run node.exe for
Server.js when the role instance starts.
26. Introduction to Node.js on Windows
• Enabling a Node.js Server-Side App on Windows
Azure (PaaS)
27. Introduction to Node.js on Windows
• Node.js in Azure Websites
• The architecture for running Node.js within Azure Websites
is identical to that used when hosting within a Web role
28. Introduction to Node.js on Windows
• Integrating Node with IIS / Benefits of using IISNode:
• Run your Node application across multiple CPU cores
• Serve static content from IIS, dynamic content from node
• Integrated, browser-based debugging with node-inspector
• Monitor the node executable plus changes to your code
• Configuration flexibility with XML + YAML overrides
• View console logs from the browser
• All the other existing IIS benefits, including output caching
29. MS SQLServer and Node.js
• Node.js Modules for SQLServer
#N % Node.js Module
#1 20.7% node-sqlserver
Microsoft Driver for Node.js for SQL Server
#2 18.0% tedious
A TDS driver, for connecting to MS SQLServer databases
#3 12.3% tds
TDS client for connecting to Microsoft SQL Server
#4 1.5% mssqlhelper
Microsoft SQL Server database helper
#5 0.4% mssqlx
NodeJs Microsoft SQL Server Command Line Interface
#6 0.2% msnodesql
Microsoft Driver for Node.js for SQL Server
#7 N/A node-sqlserver-unofficial
Microsoft Driver for Node.js for SQL Server – unofficial distribution
30. MS SQLServer and Node.js
• node-sqlserver & msnodesql
• Microsoft Driver for Node.js for SQL Server
and Azure SQL Database: Node.js module,
based on SQL Server Native Client 11.0 -
available as Microsoft SQL Server 2012
Native Client found in the
SQL Server 2012 Feature Pack
• The same repository, different npm
packages
31. MS SQLServer and Node.js
• node-sqlserver-unofficial
This is an unofficial binary distribution of that driver.
• No need to compile from source (which requires
Visual Studio and totally confuses people).
• It runs on both x86 and x64 and with node versions
0.8 and 0.10.
• No workarounds needed to run on Azure web sites.
node-sqlserver-unofficial npm page
32. MS SQLServer and Node.js
• node-sqlserver-unofficial
This is an unofficial binary distribution of that driver.
• No need to compile from source (which requires
Visual Studio and totally confuses people).
• It runs on both x86 and x64 and with node versions
0.8 and 0.10.
• No workarounds needed to run on Azure web sites.
node-sqlserver-unofficial npm page
33. MS SQLServer and Node.js
• tedious
• A TDS driver, for connecting to MS SQLServer databases.
• Tedious is an implementation of the TDS protocol, which
is used to interact with instances of Microsoft's SQL
Server. It is intended to be a fairly slim implementation of
the protocol, with not too much additional functionality.
• Tedious is implemented only with JavaScript
34. MS SQLServer and Node.js
• node-tds
• This is a module that allows you to access Microsoft SQL
Server 2005 and later.
• It is a pure JS implementation of the TDS protocol hosted
on GitHub.
• node-tds is similar to tedious
35. MS SQLServer and Node.js
• node-tds mssqlhelper
• Microsoft SQL Server Helper nodejs
• mssqlx
• NodeJs Microsoft SQL Server Command Line Interface
36. MS SQLServer and Node.js
• Pros and Cons
driver pros cons
tedious,
tds
Lightweight ,
JS implementation,
no dependencies
Limited functionalities,
Cannot use integrated
authentication
msnodesql,
node-sqlserver
More features Many dependencies,
No actual builds
Require custom build
node-sqlserver-
unofficial
Same like msnodesql, node-sqlserver,
fixed issues with the official distributions
No official support
Ende.js and Edge-sql can run any SQL expression, can connect
using integrated security
Requires .Net 4.5
Can run only on Windows
37. MS SQLServer and Node.js
• JSON to SQL Type Mappings
JSON Value T-SQL Type
Numeric values (integer,
decimal, floating point)
Float(53)
Boolean Bit
DateTime DateTimeOffset(3)
String Nvarchar(max)
38. Microsoft Azure and Node.js
• Using Azure SQL Database with Node.js
• Default Microsoft Driver for Node.JS for SQL Server
• Open First – hosted on Github
https://github.com/Azure/node-sqlserver
• Simplicity by Design – keeps the simple API
• Use in Windows Azure Web Sites
39. Azure SQL Database with Node.js
• Using Azure SQL Database with Node.js
• Connecting to SQL Server Database with Node.JS – node-
sqlserver
var sql = require('node-sqlserver');
var conn_str =
"Driver={SQL Server Native Client 11.0};" +
"Server=tcp:[databasename].database.windows.net,1433;" +
"Database=TaskList;Uid=[username];" +
"Pwd=[password];Encrypt=yes;Connection Timeout=30“
40. Azure SQL Database with Node.js
• Connecting to SQL Server Database with Node.JS
sql.open(conn_str, function (err, conn) {
err && throw err;
conn.queryRaw(query, function (err, results) {
err && throw err;
for (var i = 0; i < results.rows.length; i++) {
res.write( "Description: " + results.rows[i][0] + "n");
}
res.end();
});
}); // sql.open
41. Azure SQL Database with Node.js
• Using Azure SQL Database with Node.js
• Connecting to SQL Server Database with Node.JS + tedious
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
var config = {
server: 'ic509d6puu.database.windows.net',
userName: '[user]@[db-server].database.windows.net',
password: [password],
database: ' [database] ' ,
encrypt: true // for Azure users
}
42. Azure SQL Database with Node.js
• Using Azure SQL Database with Node.js
• Connecting to SQL Server Database with Node.JS + tedious
function executeStatement() {
request = new Request( "select 42,
'hello world'", function(err, rowCount) {
if (err) {
console.log(err);
} else {
console.log(rowCount + ' rows');
}
connection.close();
});
request.on('done',
function(rowCount, more) {
console.log(rowCount +
' rows returned‘ );
});
connection.execSql(request);
}
43. Azure SQL Database with Node.js
• Using Azure SQL Database with Node.js
• Connecting to SQL Server Database with Node.JS + tedious
var connection = new Connection(config);
connection.on('connect' , function(err) {
// If no error, then good to go...
executeStatement();
}
);
44. Azure SQL Database with Node.js
• Using Azure SQL Database with Node.js
• Connecting to SQL Server Database with Node.JS + tedious
– Insert Query
connection.on('connect', function(err){
var request = new Request("INSERT INTO MyTable (uniqueIdCol, intCol,
nVarCharCol) VALUES (@uniqueIdVal, @intVal, @nVarCharVal)",
function(err){
if(err){
console.log(err);
};
});
request.addParameter('uniqueIdVal',
TYPES.UniqueIdentifierN,'ba46b824-487b-4e7d-8fb9-703acdf954e5');
request.addParameter('intVal', TYPES.Int, 435);
request.addParameter('nVarCharVal', TYPES.NVarChar, 'hello world');
connection.execSql(request);
});
45. Azure SQL Database with Node.js
• Using Azure SQL Database with Node.js
• Connecting to SQL Server Database with Node.JS +
node-sqlserver-unofficial
var sql = require('node-sqlserver-unofficial');
sql.query(conn_str, "SELECT TOP 10 FirstName, LastName FROM Person.Person", function (err, results) {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.write( "Got error :-( " + err);
res.end( "" );
return;
}
res.writeHead(200, { 'Content-Type': 'text/plain' });
for (var i = 0; i < results.length; i++) {
res.write( "FirstName: " + results[i].FirstName + " LastName: " + results[i].LastName );
}
res.end( "; Done." );
});
49. Building a Web Site with Node.js
• Node Options in the Gallery
50. Building a Web Site with Node.js
• DEMO
• Creating Azure Web Site with Node.js, tedious and
Azure SQL Database
• Creating Azure Web Site with Node.js, node-
sqlserver-unofficial and Azure SQL Database
• Creating Web App with Edge and Azure SQL
Database
51. Building a Web Site with Node.js
• DEMO
• Creating Azure Web Site with Node.js,
azure-table-node and Azure Table Storage
• Creating Azure Web Site with Node.js,
azure and Azure Blob Storage
53. Node.js and C# with Edge.js
• Edge.js
• Native binding to .Net world
var edge = require('edge')
var hello = edge.func(function() {/*
async (input) => {
return ".NET welcomes " + input.ToString();
}
*/})
hello('Node.js', function(error, result) {
error && throw error
console.log(result)
})
54. Node.js and C# with Edge.js
• Edge.js and SQL Server / Azure SQL Database
• The Edge.js module for Node.js allows in-process interop beween
Node.js and .NET code
• The Edge-sql extension of Edge.js enables executing T-SQL scripts
embedded within a Node.js application using asynchronous ADO.NET
running in-process with Node.js code.
• The Edge-sql extension currently supports the four basic CRUD
operations: select, insert, update, and delete.
55. Node.js and C# with Edge.js
• Edge.js and SQL Server / Azure SQL Database
• Connection string / using environment variables
SETX EDGE_SQL_CONNECTION_STRING "Data Source=localhost;Initial
Catalog=node-test;Integrated Security=True "
56. Node.js and C# with Edge.js
• Edge.js and SQL Server / Azure SQL Database
• Query SQL Server directly using Edge.js
var getTopUsers = edge.func('sql', function () { /*
SELECT TOP 5 * FROM SampleUsers ORDER BY CreateDate DESC
*/ });
57. Node.js and C# with Edge.js
• Edge.js, Edge-sql and SQL Server / Azure SQL Database
• Query SQL Server directly using Edge.js /
code to set the ConnectionString in node.js
var params = {
connectionString: "Data Source=IGBGSOFEV06SQLEXPRESS;Initial
Catalog=NodeJS;Integrated Security=True“ ,
source: "SELECT TOP 5 * FROM SampleUsers ORDER BY CreateDate DESC"
};
var getTopUsers = edge.func( 'sql‘ , params);
58. Node.js and C# with Edge.js
• Edge.js , Edge-sql and SQL Server / Azure SQL Database
• Query SQL Server directly using Edge.js
getTopUsers(null, function (error, result) {
if (error) { logError(error, res); return; }
if (result) {
res.write( "<ul>" );
result.forEach(function(user) {
res.write( "<li>" + user.FirstName + " " +
user.LastName + ": " + user.Email + "</li>" );
});
res.end( "</ul>" );
}
else {
}
});
59. Node.js and C# with Edge.js
• Edge.js , Edge-sql and SQL Server / Azure SQL Database
• Execute .NET code to query SQL Server
• Create a .NET class library
• Import the .Net assembly and use it’s API in Node.js +
Edge application
60. Node.js and C# with Edge.js
• Edge.js , Edge-sql and SQL Server / Azure SQL Database
• Create a .Net Class Library
public class Sample1
{
public async Task<object> Invoke(object input)
{
....
}
public async Task<List<SampleUser>> QueryUsers(int
pageNumber, int pageSize)
{
....
}
}
61. Node.js and C# with Edge.js
• Edge.js , Edge-sql and SQL Server / Azure SQL Database
• Create a .Net Class Library
public class SampleUser
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public DateTime CreateDate { get; set; }
}
62. Node.js and C# with Edge.js
• Edge.js , Edge-sql and SQL Server / Azure SQL Database
• Using a .Net Library from Node.js + Edje.js app
// Set up the assembly to call from Node.js
var querySample = edge.func({
assemblyFile: 'EdgeSampleLibrary.dll',
typeName: 'EdgeSampleLibrary.Sample1',
methodName: 'Invoke'
});
63. Node.js and C# with Edge.js
• Edge.js , Edge-sql and SQL Server / Azure SQL Database
• Using a .Net Library from Node.js + Edje.js app
// This is the data we will pass to .NET
var data = { pageNumber: 2, pageSize: 3 }
// Invoke the .NET function
querySample(data, function (error, result) {
....
});
64. Node.js and C# with Edge.js
• Edge.js, Edge-sql and SQL Server / Azure SQL Database
• DEMO
65. Mobile Services & Node.js
• Azure Mobile Services Review
Data Authentication Notifications Scripts & Svcs
66. Mobile Services & Node.js
• Microsoft Azure Mobile Services Architecture
72. Mobile Services & Node.js
• Push Notifications
Insert, Update, Delete, Read on a Table
Automatic or Manual Server Script
An Event
Script Runs in the Azure Mobile Service
Windows
Phone 8
iOS AndroidWindows 8
73. Mobile Services & Node.js
• Node Modules
• Extensibility through numerous included modules
75. Resources:
• Node.js - http://nodejs.org/
• Node.js for Visual Studio - https://nodejstools.codeplex.com/
• Scott Hanselman blog - http://www.hanselman.com/blog/
• Microsoft Azure – Node.js Developer Center -
http://azure.microsoft.com/en-us/develop/nodejs/
• Azure SDK for Node.js in GitHub -
https://github.com/Azure/azure-sdk-for-node