TypeScript – Introduction

It is time to start learning the language of the future: TypeScript

There are a lot of online resources to learn the language, here I just share a small piece of code with the basics of the language:

//---------------
// 1 Basic types
//---------------
var myBooleanVar: boolean = false;
var myNumberVar: number = 29;
var myStringVar: string = "Juan Carlos";

// 1.1 Arrays
var myArrayVar: number[] = [1, 2, 3];
var myArrayVar: Array<number> = [1, 2, 3];

// 1.2 Enumerations
enum Direction { Up, Down, Left, Right };
var myDirectionVar: Direction = Direction.Up;

// 1.3 Any
var myAnyTypeVar: any = "I am a text";
myAnyTypeVar = false; // before it was string, now a boolean

// 1.4 Void
function log(msg: string): void {
	console.log(msg);
	// this functions returns nothing
}

//---------------
// 2 Interfaces
//---------------
interface IPerson {
	name: string;
	age?: number; // optional parameter
}

function sayHello(person: IPerson) {
	console.log(person.name);
	if (person.age) {
		console.log("Your age is " + person.age)
	}
}

// myVar has no type but has all the fields that a 
// Person should have. Therefore is a Person (duck typing)
var myVar = { name: "Juan Carlos" };
sayHello(myVar);

// 2.1 Interfaces extends
interface IStudent extends IPerson {
	studentId: number;
}

// 2.2 Interfaces indexes
interface Friends {
	[index: number]: IPerson;
	length: number;
}

// 2.3 Interfaces with functions/methods
interface PeopleService {
	getPersonId(person: IPerson): number;
	// a function that has a Person has parameter and return a boolean
	(newFriend: IPerson): boolean;
}

//---------------
// 3 Classes
//---------------

// 3.1 Interfaces implementation
interface IVehicle {
	move(direction: Direction);
	registrationNumber: number;
}

class Vehicle implements IVehicle {
	registrationNumber: number;

    constructor(id: number) {
		this.registrationNumber = id;
	}

	move(direction: Direction) {
		console.log("Moving" + direction);
	}
}

// 3.2 Classes Extends
class Car extends Vehicle {
	// by default all public
	private numberOfWheels: number = 4;
	speed: number = 120;
	
	// method override
	move(direction: Direction) {
		console.log("Speed = " + this.speed);
		// call base
		super.move(direction);
	}
}

var myCar: IVehicle = new Car(1234);
myCar.move(Direction.Up);

// 3.3 Classes, define class fields in constructor 
// add public or private to the parameter
class Motorbike implements IVehicle {
	private numberOfWheels: number = 2;
	
	// the constructor defines a public field 'registrationNumber'
    constructor(
		public registrationNumber: number,
		// define a private field with the value passed as parameter
		// if no value specified, the field as the value 90
		private speed: number = 90) {
	}

	move(direction: Direction) {
		console.log("Moving the motorbike" + direction);
	}
}

// 3.4 Accesors and static fields
class Plane implements IVehicle {
	// Static field
	static minSpeed: number = 100;
	static speedCorrectionFactor: number = 0.8;
	
	constructor(
		public registrationNumber: number,
		private _speed: number = 300) {
	}

	// speed getter
	get getSpeed(): number {
		// for some reason the public speed is 80%
		// of the realone
        return this._speed * Plane.speedCorrectionFactor;
    }

	// speed setter
    set setSpeed(newSpeed: number) {
		if (newSpeed > Plane.minSpeed) {
			this._speed = newSpeed;
		}
	}

	move(direction: Direction) {
		console.log("Flying! " + direction);
	}
}

Resources:
http://www.typescriptlang.org/Handbook

AngularJS and SignalR

The goal of this post is to connect and use SignalR from AngularJS. All the code is available in GitHub.

All code is available here: GitHub Link

The application used in this post allows to add tasks to a collaborative list of tasks to do. The application displays a list with all the tasks pending to do and also allows to remove them from the list. SignalR will push the notification “newTask” and “taskDone” to all connected users.

Feel free to get the code from github and run the application in more than one place (different tabs in your explorer) to see how SignalR synchronizes all of them.

The simplicity of the application allows to focus on the goal of this post: SignalR and AngularJS.

This is a screenshot of the running application.

Screenshot of the signalR and angularJS app.

SignalR Hub

The first thing that we need is to configure the OWIN startup, we need this class in our project:

[assembly: OwinStartup(typeof(Startup))]
namespace AngularJS_SignalR
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // SignalR
            app.MapSignalR();
        }
    }
}

The signalR hub type is “INotesCallbacks”, this interface defines the callbacks that the hub can make to the connected clients.

    // Client callbacks
    public interface INotesCallbacks
    {
        // Notify note added
        Task BroadcastNewNote(Note newNote);
        // Notify note removed
        Task BroadcastRemoveNote(int noteId);
    }

The hub also implement the interface “INotesCalls” this interfaces defines the hub methods that clients can call.

    // Client calls
    public interface INotesCalls
    {
        // Add note
        Task AddNote(string note);
        // Get all notes
        IEnumerable<Note> GetAllNotes();
        // Remove note
        Task RemoveNote(int roomId);
    }

This is the implementation of the hub:
Continue reading

JavaScript – first steps for a c# developer

The goal of this post is to compare some basics features of JavaScript with C#.

Objects Initialization

The initialization of JavaScript objects is similar to c# anonymous initialization.

// c# Anonymous initialization
var car = new
{
  Name = "myCar",
  PlateNumber = 12435
};
// JavaScript Initialization
var car =
{
  Name: "myCar",
  PlateNumber: 12435
};

Dynamic members

JavaScript objects can be dynamically expanded or updated. The behavior is like dynamic + ExpandoObjects in C#.

// c# Dynamic objects
dynamic car = new ExpandoObject();
car.Name = "myCar";
car.PlateNumber = 1234;
// JavaScript objects
var car = {}
car.Name = "myCar";
car.PlateNumber = 12435;

Classes and object oriented programming

JavaScript is a function oriented language. This means that classes in JavaScript are fairly different to classes in c#.

A class in JavaScript looks like a function. We need to use the keyword ‘this’ inside a function to define fields and methods of our class and the keyword ‘new’ to create instances. The function itself is the constructor of the class.

// c# class
Car myCar = new Car("myCar", "12345");

class Car
{
  public Car(string name, string plateNumber)
  {
    this.Name = name;
    this.PlateNumber = plateNumber;
  }

  public string Name { get; set; }
  public string PlateNumber { get; set; }

  public void Move(object position)
  {
    // move
  }

  private int Speed = 50;
}
// JavaScript class
var car = new Car("myCar", 12345);

function Car(name, plateNumber) {
  // public
  this.name = name;
  this.plateNumber = plateNumber;
  this.move = function (position) { /* move*/ }

  // private
  var speed = 50;
}

Properties

The previous javascript code is not creating properties because they have no getter and setter, if we need the getter and setter methods we need to use the following special syntax. This syntax also allows to define read-only properties.

// private backing field
var _name;
// property with public getter and setter
Object.defineProperty(this, "name", {
  get: function() { return _name; },
  set: function(value) { _name = value; }
});

Static methods and fields

Static members needs to be added dynamically to the class function:

// Define static field
Car.wheels = 4;
// Create instance
var myCar = new Car("myCar", 12345);
// Use static field
var test = myCar.wheels; // ERROR, static methods cannot be called from an instance
var test = Car.wheels; // OK

Prototype and inheritance

Prototype is an object contained by all classes. We can be extended dynamically this object (like all objects in JavaScript) with data and methods that will be accessible from our class.

Car.prototype.wheels = 4;
Car.prototype.move = function(position) { /* move*/ };

Inheritance in JavaScript is implemented changing the prototype of the child class. Let’s create a class “Car” that should have “Vehicle” class as base class:

function Vehicle(...) {
...
}
function Car(...){
...
}
Ferrari.prototype = new Vehicle();