Serializar un objeto a JSON en C#

En ocasiones nos interesa serializar un objeto en JSON, como por ejemplo al usar el AJAX de jQuery. Es tan fácil como esto:

static public string ToJSON(object obj)
{
    System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    return serializer.Serialize(obj);
}

Obtener un parámetro de la URL desde JavaScript

Función que nos permite obtener un parámetro de la URL pasado por GET desde JavaScript. En el caso de que el parámetro no exista nos devuelve un null.

// Helper function to get parameters from the query string.
function getUrlParam(paramName) {
    var reParam = new RegExp('(?:[\?&]|&)' + paramName + '=([^&]+)', 'i');
    var match = window.location.search.match(reParam);
    return (match && match.length > 1) ? match[1] : null;
}

Calculate the width of a text, and shorten it to a number of pixels given in JavaScript

In some cases we may need to calculate from JavaScript the width of a text on the screen.
To do this we will use a layer that will make us as a rule. This layer must have the same styles that the fate of the text that we want to measure, or assigning these styles whenever we are going to measure.

This is the HTML for the layer:

<span id="ruler"></span>

The layer has to be hidden with the following CSS:

#ruler {
	visibility: hidden;
	white-space: nowrap;
	position: absolute;
	top: -100;
	left: 0px;
}

And finally we will extend the string class in JavaScript with two methods that will allow us to calculate the width of a text in pixels and trim a text to a specified width.

// Calcula los pixeles de ancho que ocupa un texto
String.prototype.visualLength = function() {
    var ruler = document.getElementById("ruler");
    ruler.innerHTML = this;
    return ruler.offsetWidth;
}

// Recorta un texto al número de pixeles indicados, añadiendo un "..." en el caso de haber sido recortado
String.prototype.trimToPx = function(length)
{
    var tmp = this;
    var trimmed = this;
    if (tmp.visualLength() > length)
    {
        trimmed += "...";
        while (trimmed.visualLength() > length)
        {
            tmp = tmp.substring(0, tmp.length-1);
            trimmed = tmp + "...";
        }
    }

    return trimmed;
}

Check if an array contains an element in JavaScript

JavaScript is unfortunately not implemented all the methods we have available from C # or VB.NET. One is the method «Contains» from the lists. With this code you can extend the class «Array» of JavaScript to implement this method:

Array.prototype.contains = function(element) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == element) {
            return true;
        }
    }
    return false;
}