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)

Entity Framework Code First

What is it?

Entity Framework is a relational mapper that allows you to create your database schema by starting with your models and telling the ORM how each component should be created as well as how they’re related to each other. It is primarily used as a facilitator of Domain-Driven Design, but more on that later. Maybe.

Why use Code First?

Based on my experience, it allows for

  • More control over your database and models: You can practically create your database in a very few lines
  • Not having to worry about creating your database. You just have to know where the server is and which rights you should give your solution. In the end it all comes down to ease of deployment
  • Not having to worry about your SQL Statements. You will mostly be using LINQ, which (I  hope) you’re already using anyway. Saving your changes is as easy as calling SaveChanges();

Why it’s not for you

  • Starting out can be a bit of a pain, as there’s a steep learning curve.  Like really, especially when creating your database. It throws out error messages that doesn’t even match what the issue is. You just have to overcome that initial struggle, then it’s smooth sailing.
  • Although it’s a good thing to not having to worry about SQL Statements, it can also work against you depending on your habits as a programmer but if you have proper unit tests, you should be fine.

Getting Started

We’re using a Patient Management System for a sample. All it does is take the name and time on a table with a constraint and display the same data just to prove that we can insert and read. Grab my sample code here: https://github.com/johnconraddomingo/EfCodeFirst.PatientManagement

This sample uses Entity Framework  6.1.3

Basic Components

Entities: The coded representation of database tables

We’re using Patient and Appointment.

public class Patient
{
  public Patient()
  {
       PatientAppointments = new List<Appointment>();
   }
   public int PatientId {get;set; }
   public string PatientName { get;set; }

   public virtual ICollection<Appointment> PatientAppointments{ get;set; }
}

Each patient can potentially contain multiple Appointments. And this relationship is defined by the ICollection in the parent. Notice the PatientAppointments in the Patient class.

public class Appointment
{
    public int AppointmentId { get; set; }
    public DateTime AppointmentDateTime { get; set; }
}

You’ll notice that the table looks like a regular class: And that’s the beauty of it all. We isolate the database part and just focus on our object. Now here’s where we

Entity Mapping

Now here’s where we tell EF the attributes of the fields such as

  • The Primary Keys
  • If they’re mandatory or optional fields
  • Max Length
public class PatientMap : EntityTypeConfiguration<Patient>
{
    public PatientMap()
    {
        // Key
        HasKey(k => k.PatientId);

        // Properties
        Property(p => p.PatientId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        Property(p => p.PatientName).IsRequired().HasMaxLength(50);

        // To Table
        ToTable("Patients");
    }
}

  • The table name that they correspond to
public class AppointmentMap : EntityTypeConfiguration<Appointment>
    {
        public AppointmentMap()
        {
            // Key

            HasKey(k => k.AppointmentId);

            // Properties
            Property(p => p.AppointmentId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            Property(p => p.AppointmentDateTime).IsRequired();

            // To Table
            ToTable("Appointments");
        }
    }

The DB Context

This is our representation of the Database. Here we define

  • The Database name
  • Which tables we want to include in our database
  • The mapping classes that we defined earlier
  • Other configs
public class PatientManagementDatabase : DbContext
{
    public PatientManagementDatabase() : base("PatientManagementContext")
    {
        Configuration.LazyLoadingEnabled = true;
        Configuration.ProxyCreationEnabled = false;
    }

    public DbSet<Patient> Patient { get; set; }
    public DbSet<Appointment> Appointment { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new AppointmentMap());
        modelBuilder.Configurations.Add(new PatientMap());
    }
}

Create Datasource

This is where we put everything together: We tell EF how to create the database. You decide where to call this method: Beginning of your application? App_Start?  Either way, it should be safe to call it anytime because within the initialiser you tell the framework when to create.

private static void CreateDatasource()
{
    Database.SetInitializer(new CreateDatabaseIfNotExists<PatientManagementDatabase>());

    var context = new PatientManagementDatabase();
    context.Patient.Create();
    context.Appointment.Create();

    context.SaveChanges();
}

That’s it! Now, we just play around with it by LINQ. This is a very simple example that you can build your more complex applications from.

You can download the sample from https://github.com/johnconraddomingo/EfCodeFirst.PatientManagement

Converting Data between Stream and Bytes

Stream to Array of Bytes

Private Function ConvertStreamToByteArray(ByVal input As Stream) As Byte()

        Dim data As Byte()

        Using br = New BinaryReader(input)

            data = br.ReadBytes(input.Length)

        End Using

        Return data

End Function

Array of Bytes to Stream

Private Function ConvertByteArrayToStream(ByVal bytFile As Byte()) As Stream

        Return New MemoryStream(bytFile)

End Function

Page_Load not getting fired when redirected to another page

My problem: My main page should always call Page_Load, because it retrieves the latest information given a certain time. Now, after my page has been loaded, i do some editting, and then i hit the update button: which in turn redirects me to a Success Page. I want to go back to the main page, but this time around, it does not go to Page_Load.

The solution: The cached data is persisting. What you need to do is to clear the cache on Page_Load

Response.Cache.SetCacheability(HttpCacheability.NoCache)

Reference: http://forums.asp.net/t/1317867.aspx/1

Saving Binary values to the Database

Saving native types like a string or an integer to the database is relatively simple. But for saving files or images, you need to convert them first to an array of byte. Here’s a snippet of how to get the blob. 

Private Function StreamFile(ByVal filename As String) As Byte()

  Dim ImageData As Byte() = Nothing

  Try 

    Dim fs As New FileStream(filename, FileMode.Open, FileAccess.Read)

    ImageData = New Byte(fs.Length – 1) {}

    fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length))

    fs.Close()

  Catch ex As Exception

    ‘ Do nothing

  End Try

  Return ImageData

End Function

How to: Create Versioned Assemblies for Precompiled Web Site Projects

I created a Website in order to create a Web User Control as a DLL. Something similar to this http://www.nathanblevins.com/2008/06/compile-a-web-user-control-into-a-dll-net-c/

The problem is that i can’t set the version of the assemblies, unlike a web application where i can just go to AssemblyInfo and change the version number. I need to be able to manage the version number as we intend to install the controls to the GAC.

Here’s a how-to page that will teach you how to do just that: http://msdn.microsoft.com/en-us/library/ms228042.aspx