Node.js for .NET Developers

Introduction

You can pick up the solution from https://github.com/johnconraddomingo/NodeJs.AspnetNodejs

This whole post is a good introduction to Node.js from a .NET Developer’s perspective. By the end of this document, you should

  • Be familiar with Node.js
  • Get your hands wet with Node.js JavaScript
  • Be abel to build a very basic HTML Hello World website
  • Be able to build an API

We will not build anything too pretty because as i’d like to limit the scope of this post, but we will be able to create a HTML Website and a WebAPI.

It is assumed that

  • You know your way around Visual Studio
  • You know the basics of a website
  • You have an idea what MVC is

What is it?

The official definition is Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. To explain that further:

  • You write Server-side codes that run on Chrome’s V8 engine. That said, js codes are actually compiled, and only expressed as Javascript. This is in contrast to the Javascript that you would write in a browser, which is interpreted script.
  • You most likely write Client-Side scripts on Javascript, and so you will most likely be dealing with Javascript and JSON both Server-Side and Client-Side
  • Non-blocking IO simply means Asynchronous operations, that is, when you make a request to the server, it doesn’t block any other incoming requests.
  • V8 provides a predictable environment for developers. Unlike Javascript that you write on a browser, Node.js runs on a platform with not much variables that will affect its dependencies.

I am primarily a .NET Developer, and so majority of what will be discussed here is (a) how Node.js compares with ASP.NET and (b) using Visual Studio to code.

Comparing Node.js and ASP.NET

For starters, they both have a dot in their names… Does that count?

  • Asynchronous Operations: Although ASP.NET allows for this, Node.js provides this functionality out of the box
  • Language used: ASP.NET can be expressed using C# or VB, and whatever language is available for .NET, including F#. On the other hand, Node.js is expressed in Javascript.
  • Compilation: Just because Node.js is expressed in Javascript, it means that it’s not compiled and that it’s slower compared to ASP.NET which is compiled into assemblies. Node.js is compiled. Javascript is merely the language used.
  • Power: Node.js, by definition is fast and efficient. However, it is not used for more intensive stuff that require much processing power.
  • Package Manager: While .NET as a whole has Nuget (https://www.nuget.org/), Node has NPM (https://www.npmjs.com/) or Node Package Manager.
  • Engine: ASP.NET uses the .NET Framework as the engine while Node.js uses V8.
  • Views: ASP.NET Provides View Engines with either ASPX or Razor available out of the box. They’re pretty much the same with very little difference in syntax. In Node.js, we work with View Engines that we can get from NPM. Since you’re reading a blog for .NET Developers, it’s best to use Vash, being a Razor clone.

Let’s start!

Starting Node.js

Getting Node.js

Downloading for Usage

We can download Node.js from https://nodejs.org/en. It will detect your machine for you. You can go ahead and download what link is available, or go to https://nodejs.org/en/download/ for more options.

Preparing your development from Visual Studio

From Visual Studio, create a New Project and you’ll find Node.js Web Application from the Templates list under JavaScript. This should get you started with a Web Server running.

NodeNewProject

Note: Please make sure you download the package from https://nodejs.org/en, otherwise Visual Studio will hang up when you create a new Project.

What you’re getting

Now, let’s see what Visual Studio created for you.

‘use strict’;
var
http = require(‘http’);
var
port = process.env.PORT || 1337;
http.createServer(function (req, res) {
res.writeHead(
200, { ‘Content-Type’: ‘text/plain’ });
   
res.end(‘Hello World\n’);
}).listen(port);

You get a port that Nodejs opens for you and a createServer method that accepts self-executing method.

It writes Hello World in the Response as a plain text, which you can easily replace with an application/json if you’re doing a WebAPI.

Let’s go through them in the next sub sections

Running from the Console

You’ll notice that a console is running everything: It’s just opening a port an accepting a request and returning something. If you’re running on production , there are a few solutions out there that will allow you to install it as a service, like os-service (https://www.npmjs.com/package/os-service) and node-windows (https://github.com/coreybutler/node-windows)

You’ll also notice that it’s starting up from server.js: You can find that this file is set in the package.json file located in the root folder of your project

“name”: “node-js.aspnet-nodejs”,
“version”: “0.0.0”,
“description”: “NodeJs.AspnetNodejs”,
“main”: “server.js”,
“author”: {
   
“name”: “John”
}

Dependencies

Now, dependencies. In .NET (and most other frameworks out there), it is the framework that handles the dependencies by looking at the folder structure and going through each file and looking at the classes available.

Node.js is quite different in that it expects you to point to it where the dependencies are, sort of like how C++ works. Here, it’s via the require keyword and in the sample above it’s using the http module.

How to Point to your Dependencies

Here’s an introduction on how to use the require/exports keyword to link them all up. Here’s what my project looks like

NodeJsProject

I created a folder named modules. That’s where I want to put all my custom methods. I can group files that are relevant to each other based on what they do, and even put them in the root folder. But for the purpose of this blog, I used a straightforward name.

Under it, I created a numberSquared and a personInfo file. They’re javascript files, as opposed to cs or vb if you’re coming from .NET. We will call these exposed objects from our server.js.

Fields

I want my personInfo to return a static value, and so I’m going to use the exports keyword and return an anonymous class to a named field that i’m going to call person.

module.exports.person = { id: 0, firstName: “John Conrad”, lastName: “Domingo” };

Back at server.js, I say

// Require: Field
var staticPersonInfo = require(‘./modules/personInfo.js’);
console.log(‘Test >> Default Person is ‘ + JSON.stringify(staticPersonInfo.person));

Where I just call .person like a normal field.

Method

It’s pretty much the same concept for methods, but this time I’m going to tell the exports keyword to take a self-executing anonymous method and say that squared will return the number * number.

module.exports = function (number) {
   
return { squared: function () {
      
return number * number;
      
}
    }
;
}

Back at server.js I do the same thing by requiring a numberSquared and this time, I will get 25 by calling the squared() method.

// Require: Method
var simpleMath = require(‘./modules/numberSquared.js’);
console.log(‘Test >> The square of 5 is ‘ + simpleMath(5).squared());

Method Structure

You will find that the default method structure of self-executing methods come in the form of request/response: And that’s because of the asynchronous nature of Node.js. It doesn’t hang around to wait for things to finish. It lets go of control and executes the callback once it does its job.

Packages

This section will use the package express (https://www.npmjs.com/package/express) as an example. Express is a web framework that we will be using later on.

Getting Packages

You can pick up Packages from npm where the command options get installed along with Node.js. You can visit the site on https://www.npmjs.com/. You can easily access the Package Manager from the command prompt. This is the .NET equivalent of Nuget where you can download Packages via Powershell.

To install from Visual Studio using the Command Prompt, Right-click on your project and choose Open Command Prompt here. Or you can just go to the Command Prompt yourself and manually go your project folder. and type

npm install express –save

where express is the name of the package that you want to install and –save says that you want to add express as a dependency to the package.json file, allowing it to automatically be downloaded.

You can also do it via Visual Studio. From the npm node in Solution Explorer, right-click and choose Install New npm Packages.

Either method you choose, you will find that a folder named node_modules will be populated by the package that you installed as well as its dependencies.

Using Packages

To use a package, simply refer to it via the require keyword. Easy! Node.js should already know all about your dependencies since it’s already in your package.json file. Visual Studio even lists your packages from the NPM package properties under Solution Explorer.

var express = require(‘express’);

At this point, even Visual Studio offered express to me via Intellisense

Web API

Now, we’re going to make an API. You know that an API is merely a Controller and that if we want to build a website out of that, we’ll basically reuse this method and chuck in a View and Controllers

Refer to the codes below. I once again used the require keyword and pulled in express. Express has functions that corresponds to HTTP verbs, like get, post and delete. And from there, we add in self-executing methods that returns either a HTML string for a website or json (plus xml, potentially).

This set how your calls to the server is routed. You should be very familiar with this as we have it either in RouteConfig in MVC or as attribute on top of the HTTP methods inside your controller.

var http = require(‘http’);
var
express = require(‘express’);
var
app = express();

// Default
app.get(‘/’, function (req, res) {
    res.send(
‘<html><head></head><body><h1>Hello World</h1></body></html>’);
});

// Api
app.get(‘/api/defaultPerson’, function (req, res) {
   
var staticPersonInfo = require(‘./modules/personInfo.js’);
   
res.set(“Content-Type”, “application/json”);
   
res.send(staticPersonInfo.person);
});

var server = http.createServer(app);
server.listen(1337, function () {
    console.log(
“Express is running on port 1337”);
});

you will notice that from the default get, I passed in HTML. You can in theory build a website out of this, although things would just get silly if you do anything more than a hello world. What you want to do is get a View Engine later on.

NodejsEdge

Now let’s look at the API. I go to api/default and it’s giving me back a json with the person object I pulled in from personInfo.js. Have a look at the header that I added in.

NodejsPostman

If we have a look at the header, it is indeed giving us an application/json as we have defined.

nodejsPostman2

There isn’t much parsing either, because Node.js is already talking json in the backend!

Conclusion

That folks, has been your introduction to Node.js. If you are a .NET developer, this post should be very straightforward to you. If you would like to learn more, it would really help if you do further reading on

  • How Node.js handles the MVC pattern
  • How View Engines get integrated (see: Vash)
  • How Node.js links to static resources
  • How Node.js handles data management (see: MongoDB)

Responsive Web Design Basics

Definition

Quick and Dirty definition: Responsive Web Design allows your website to look good on whatever device you’re viewing it from whether it be your computer, tablet or phone. It is usually done using (but not limited to) HTML and CSS.

3 Useful Tricks

We’ll refer to the sample below

<meta name="viewport" 
 content="width=device-width, initial-scale=1.0">
<html>
  <style>
    #divHello{ font-size:20vh;}
    #divWorld{ font-size:25px;} 
      
    @media only screen and (max-width: 600px){
    /* For phones */
    
    #divWorld{
      text-align:center;
      width: 100%
     }
   }
  </style>
  <body>
   <div id="divHello">Hello</div>
   <div id="divWorld">World</div>
  </body>
</html>

Here are some useful tricks that you can do, obviously on top of the usual width = 100%, min-width, max-width and strategically placing your components.

The Viewport meta tag

Viewport tells the browser how to control the page’s dimensions. 10px looks much much smaller on your phone than on your computer. The Viewport tag tells your browser to scale the page based on how wide your device is.

  • A <meta> viewport element gives the browser instructions on how to control the page’s dimensions and scaling.
  • The width=device-width part sets the width of the page to follow the screen-width of the device (which will vary depending on the device).
  • The initial-scale=1.0 part sets the initial zoom level when the page is first loaded by the browser.

Vh, Vw and Vmin and Vmax

These units scale to the size of your viewport.

  • vw: 1/100th viewport width
  • vh: 1/100th viewport height
  • vmin: 1/100th of the smallest side
  • vmax: 1/100th of the largest side

Looking at the sample above, line divHello tells you to scale to the height. Running this HTML and resizing your browser height will resize the font size on the fly. Resizing your browser’s width will do nothing.

If you choose vmin, it will choose the smaller of the viewport width and height. Vmax will choose the larger.

Media Queries

CSS3 Media Queries defines which CSS to change or add when the device falls on the defined min-width or max-with. In the sample above, you’ll notice that making the browser’s width smaller forces divWorld to 100% width.

Take note that you can add in multiple queries. For instance, you can have a CSS based on a specific device in mind. Here’s a reference

/* Smartphones (portrait and landscape) ----------- */
@media only screen
and (min-width : 320px)
and (max-width : 480px) {
/* Styles */
}
 
/* Smartphones (landscape) ----------- */
@media only screen
and (min-width : 321px) {
/* Styles */
}
 
/* Smartphones (portrait) ----------- */
@media only screen
and (max-width : 320px) {
/* Styles */
}
 
/* iPads (portrait and landscape) ----------- */
@media only screen
and (min-width : 768px)
and (max-width : 1024px) {
/* Styles */
}
 
/* iPads (landscape) ----------- */
@media only screen
and (min-width : 768px)
and (max-width : 1024px)
and (orientation : landscape) {
/* Styles */
}
 
/* iPads (portrait) ----------- */
@media only screen
and (min-width : 768px)
and (max-width : 1024px)
and (orientation : portrait) {
/* Styles */
}
 
/* Desktops and laptops ----------- */
@media only screen
and (min-width : 1224px) {
/* Styles */
}
 
/* Large screens ----------- */
@media only screen
and (min-width : 1824px) {
/* Styles */
}
 
/* iPhone 4 ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */
}

 

Added References:

https://en.wikipedia.org/wiki/Responsive_web_design
http://www.w3schools.com/css/css_rwd_viewport.asp
https://paulund.co.uk/understanding-the-viewport-meta-tag

Loading Screen on your Website

Make a loading screen by attaching a GIF on your DIV
Place this on your Head Tag

<style type="text/css">

    /*this is what we want the div to look like when it is not showing*/

    div.loading-invisible {

        /*make invisible*/

        display: none;

    }

 

    /*this is what we want the div to look like when it IS showing*/

    div.loading-visible {

        /*make visible*/

        display: block;

        /*position it 200px down the screen*/

        position: absolute;

        top: 200px;

        left: 0;

        width: 100%;

        text-align: center;

        /*in supporting browsers, make it a little transparent*/

        background: #fff;

        filter: alpha(opacity=75); /* internet explorer */

        -khtml-opacity: 0.75; /* khtml, old safari */

        -moz-opacity: 0.75; /* mozilla, netscape */

        opacity: 0.75; /* fx, safari, opera */

        border-top: 1px solid #ddd;

        border-bottom: 1px solid #ddd;

    }

</style>

Source
http://andrewpeace.com/javascript-css-loading-screen.html

Mobile Site

Want to make a Mobile site? You know, the one that looks good in modern mobile browsers. Top your HTML with this

<head runat="server">

 <meta name="viewport" content="width=device-width,user-scalable=no,minimum-scale=1.0, maximum-scale=1.0"" />

 <meta name="apple-mobile-web-app-capable" content="yes"/>

 <title></title>

</head>