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();

Single Page Application (SPA) using AngularJS and WebAPI – Architecture

The goal of this post is to clarify an architecture of a single page application using the following technologies:

  • ASP MVC
  • AngularJS
  • WebAPI
  • Entity Framework

The next diagram shows at the left the client side and at the right the server side:

Single Page Application (SPA) using AngularJS and WebAPI – Architecture

 

 The first row is the communication between the different used technologies.

The middle row represent the logic of our application and the last the data containers used on these classes.

Using the previous diagram is easy to see which data each layer uses.

e.g:

  1. The Angular controller can only work with the Angular context.
  2. The WebAPI controller send and receive data in JSON format. The JSON objects are automatically translated to C# view models. The WebAPI controllers are also able to map the view-models to domain objects to use the domain services. WebAPI controllers can also request domain objects to the domain services and translate it to ViewModels c# before sending it back to the client-side in JSON format.

Data containers and layers:

  • AngularJS Context: The context is populated by the angular repository. HTML templates bind to it.
  • ViewModels Json: The data is sent from client to server side and vice versa in JSON format. The WebAPI controller send automatically by default the data in this format. The send and received data in JSON format is mapped automatically to the expected object.
  • ViewModels C#: The data the WebAPI controller send and receive as parameter. The conversion between Json and C# view models is done automatically by the WebAPI controller. This class is a subset of our entity domain objects plus some calculated properties that our views may need. It can be used for example to keep some server-side data hidden on the client-side.
  • Entities: Entity Framework entities or domain specific classes. All the data related to the domain. Theses classes are completely independent of the view. The domain services or application logic must use theses classes. The mapping from and to Entities to c# view models can be done automatically or Auto-mapper.

AngularJS AJAX calls

AngularJS is a JavaScript framework that allows us to create Single Page Applications (SPA). If we use AngularJS we can bind from our HTML views to JavaScript files (controllers). Controllers will offer the data to the view. Typically this data is retrieved from REST services using Ajax calls.

The goal of this post is to show how to make AJAX calls using AngularJS. I will illustrate two different ways to do it, the first one helps to understand how the asynchronous call works, the second one is an easier way to do it using a higher-level service.

Using $http and $q

One way to make AJAX calls using AngularJS is using the services $http and $q:

  • The $http service allows us to make the GET and POST calls.
  • The $q service is used to wait asynchronously for the response, basically it is a deferred result, it returns a “promise” that will response after some time. After some time the deferred can be “resolved” or “rejected”.   The method using this deferred can add two call-backs to it one to execute when it is resolved and one when it is rejected.

Let say we have a controller that needs to populate some data asynchronously. I like to dedicate the controller to define the binds for our views. The AJAX call will be executed in a different file, a repository.

AngularJS – Controller: The module will call a repository and add set the response in the scope when the deferred is resolved.

angular js controller

AngularJS – Repository: The repository make an AJAX Get request to a ASP.NET WebAPI Controller.

angular js repository

We can write the same repository with less lines using shortcut methods:

angular js repository

This solution works but there is an easier way to do AJAX calls…

Using $resource

This service lets us interact with RESTful server-side data sources with a higher-level than the $http service. The $resource service is defined in the module ‘ngResource’ and this module is in the file angular-resource.js.

The first thing that we need to do is to reference the angular-resource.js file and add this module as a dependency of our module:

ngResource reference

ngResource reference

Using the $resource we can write our controller and repository easier because we don’t have to deal directly with deferred objects.

This is now the implementation of our controller and repository using the Angular service $resource , really easy!

angular js repository and controller

ASP MVC – Template Overview

When a new MVC Web Application is created in Visual Studio a lot of files are added to the solution. The goal of this post is to provide a small overview of all these files, this overview should make easier to understand the MVC solution structure.

The files described here are the files created by default when you add a web project using the MVC template.

Create a a Web project:

New Web Project

Use the MVC Template:

MVC Template

This is the generated project:

MVC Template Project

ASP MVC Template Overview

Let’s start enumerating some created folders:

  • Content: CSS files with view styles. (Bootstrap)
  • Fonts: Some fonts required by the CSS files.
  • Scripts: JavaScript files. (JQuery)
  • Controllers: C# files with the code that is going to be run at the server side.

Now the rest of files and folders with some more details:

Views

This folder contains *.cshtml files. The Razor engine generates the views of our web application out of these files. Typically we will have a view or a group of views for each controller. This folder also contains a Web.config don’t confuse this one with the Web.config at the root of the solution. Razor engine is configured here.

Continue reading

Adaptive HTML5 + CSS3 Page design

En este post voy a explicar un modo muy sencillo de hacer el diseño de una página adaptativo.

Un diseño adaptativo es aquel en el que la distribución y los elementos que aparecen en la página cambian dependiendo del tamaño de la pantalla de visualización.

Hoy en día esto es imprescindible debido a la gran variedad de dispositivos capaces de acceder a una página web: PCs, Móviles, Tablets, Televisiones, etc.

El objetivo es que la página web tenga 3 diseños:

  • Dispositivos con pantalla grande, más de 980px
  • Dispositivos con pantalla pequeña, entre 480px y 980px
  • Dispositivos con pantalla mini, menos de 480px

Continue reading

Selectores CSS avanzados

Después de ver algunos de los selectores CSS más básicos, en este post muestro un resumen de algunos selectores más avanzados.

Referencia: http://www.w3schools.com/cssref/css_selectors.asp

HTML de ejemplo:

<html>
<head>
    <meta charset="utf-8" />
    <title>CSS Selectors tests</title>
    <link href="css/selectoresAvanzados.css" rel="stylesheet" />
</head>
<body>
 <ul id="lista1">
 <li>Descendiente directo de ul con id="lista"</li>
 </ul>

<p class="contiguo" />
 <p>Elemento inmediatamente contiguo a p con class="new"</p>

<ul id="lista2">
 <li>Primero (rojo)</li>
 <li>Segundo</li>
 <li class="last">Ultimo (azul)</li>
 </ul>

<p class="linea">CSS Selectores <br />avanzados</p>

<a href="www.google.es" id="buscador-google" title="Buscador">Google</a>
<a href="www.facebook.es" id="redsocial-facebook" title="Red Social">Facebook</a>
<a href="www.yahoo.es" id="buscador-yahoo" title="Buscador">Yahoo</a>

<p lang="es">Hola CSS!</p>
 <p lang="en">Hello CSS!</p>
</body>
</html>

CSS con algunos selectores avanzados:

Continue reading

Selectores CSS

Etiqueta: Se aplican a todas las labels del tipo indicado.

p {...}

.Clase: Se aplican a todoas las etiquetas.

<span class="myClase"></span>
.myClase{...}

Etiqueta.Clase: Se aplican a todas las etiquetas del tipo y clase indicados. (Elementos que aparecen varias veces en el HTML).

<span class="myClase"></span>
span.myClase{...}

#Identificador: Se aplica al elemento con el identificador dado. (Debería ser único en el HTML).

<span id="myId"></span>
#myId{...}

Etiqueta#Identificador: Se aplica a la etiqueta con el identificador dado.

<span id="mySpan"></span>
span#mySpan{...}

Etiquetas anidadas: Se aplica a las etiquetas que se encuentren anidadas dentro de otras. Por ejemplo, todos los enlaces, etiquetas <a> que se encuentren dentro de etiquetas <span>.

<span>
<a href.../>
</span>
span a{...}

Los selectores por clase e identificadores pueden combinarse con los selectores anidados, de este modo podemos aplicar un estilo a etiquetas anidadas dentro de otras que tienen un identificador o clase dados:

.box span{...}
#box span{...}

Selectores por estado: Se aplica a identificadores con que se encuentran en un estado determinado. Por ejemplo, un enlace podría encontrarse en estado visitado o no visitado.

/* No visitado */
a:link{...}
/* Visitado */
a:visited{...}
/* Ratón encima */
a:hover{...}
/* Pulsado (por ejemplo en menús) */
a:active{...}
/* Con el foco (por ejemplo en etiquetas <input type="text" />)*/
:focus{...}

Agrupación de selectores: La agrupación permite aplicar el mismo estilo a varios selectores.

#myDiv, #mySpan {...}



Más información: