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

Devolver un código 301 (Moved Permanently) en C#

En algunos casos necesitamos informar a terceros que una página nuestra, o incluso un dominio entero ha sido movido a otro sitio.

Un ejemplo claro podría ser que teníamos el dominio www.newagedesign.com y ahora lo hemos movido a www.newagedesign.es. Lo ideal es avisar a todo el mundo que la dirección de nuestra web ha cambiado, pero esto a veces no es posible o puede llevar mucho tiempo. En estos casos lo ideal es redireccionar al visitante pero  indicándole que le redirigimos porque la web ha cambiado de lugar. Esto se consigue devolviéndole un error 301.

Todo esto comentado sobre un dominio también es aplicable a una página concreta.

En el caso de .NET esto se haría insertando el siguiente código en la página que queremos redirigir:

Response.Status = "301 Moved Permanently";
Response.AddHeader("Location","http://www.newagedesign.es/");
Response.End();

Obtención de la distancia entre dos coordenadas geográficas en C#

/// <summary>
        /// Obtiene la distancia entre dos coordenadas geográficas
        /// </summary>
        /// <param name="long1InDegrees">Longitud del punto 1 en grados</param>
        /// <param name="lat1InDegrees">Latitud del punto 1 en grados</param>
        /// <param name="long2InDegrees">Longitud del punto 2 en grados</param>
        /// <param name="lat2InDegrees">Latitud del punto 2 en grados</param>
        /// <returns>Distancia entre los dos puntos en metros</returns>
        private static double GetDistance(decimal long1InDegrees, decimal lat1InDegrees, decimal long2InDegrees, decimal lat2InDegrees)
        {
            double lats = (double)(lat1InDegrees - lat2InDegrees);
            double lngs = (double)(long1InDegrees - long2InDegrees);

            //Paso a metros
            double latm = lats * 60 * 1852;
            double lngm = (lngs * Math.Cos((double)lat1InDegrees * Math.PI / 180)) * 60 * 1852;
            double distInMeters = Math.Sqrt(Math.Pow(latm, 2) + Math.Pow(lngm, 2));
            return distInMeters;
        }

Cambiar proporción de una imágen en C#

public static string ChangeImageProportion(string strImgPath, string strImgOutputPath, int iWidth, int iHeight)
{
    try
    {
        //Comprueba la extensión
        //if (Path.GetExtension(strImgPath).ToLower() != ".jpg")
        //{
        //    throw new Exception("El fichero debe estar en formato JPG. (" + strImgPath + ")");
        //}

        //Lee el fichero en un stream
        Stream mystream = null;

        if (strImgPath.StartsWith("http"))
        {
            HttpWebRequest wreq = (HttpWebRequest)WebRequest.Create(strImgPath);
            HttpWebResponse wresp = (HttpWebResponse)wreq.GetResponse();
            mystream = wresp.GetResponseStream();
        }
        else
            mystream = File.OpenRead(strImgPath);

        // Cargo la imágen
        Bitmap source = new Bitmap(mystream);

        int _targetWidth = source.Width;
        int _targetHeight = source.Height;

        /*** Calculo de las proporciones finales ***/
        double _relation = ((double)source.Width) / ((double)source.Height);
        double _canvasRelation = ((double)iWidth) / ((double)iHeight);

        if (_relation > _canvasRelation)
        {
            // El ancho es el lado grande, hay que aumentar el alto
            _targetHeight = iHeight * source.Width / iWidth;
        }
        else if (_relation < _canvasRelation)
        {
            // El alto es el lado grande, hay que aumentar el ancho
            _targetWidth = iWidth * source.Height / iHeight;
        }

        // Ahora miro el desfase
        int iTop = (_targetHeight - source.Height) / 2;
        int iLeft = (_targetWidth - source.Width) / 2;

        // La nueva
        Bitmap target = new Bitmap(_targetWidth, _targetHeight);
        Graphics g = Graphics.FromImage(target);
        g.CompositingQuality = CompositingQuality.HighQuality;

        Color cW = Color.White;
        Brush brush = new SolidBrush(cW);
        g.FillRectangle(brush, 0, 0, _targetWidth, _targetHeight);
        g.DrawImage(source,
                    new Rectangle(iLeft, iTop, source.Width, source.Height),
                    0,
                    0,
                    source.Width,
                    source.Height,
                    GraphicsUnit.Pixel);

        // We will store the correct image codec in this object
        ImageCodecInfo ici = GetEncoderInfo("image/jpeg"); ;
        // This will specify the image quality to the encoder
        EncoderParameter epQuality = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 99L);
        // Store the quality parameter in the list of encoder parameters
        EncoderParameters eps = new EncoderParameters(1);
        eps.Param[0] = epQuality;

        // Genero un nuevo nombre de fichero
        //strImgPath = Path.Combine(Path.GetDirectoryName(strImgPath),Guid.NewGuid().ToString() + ".jpg");

        target.Save(strImgOutputPath, ici, eps);

        source.Dispose();
        target.Dispose();
        g.Dispose();

        return strImgPath;
    }
    catch
    {
        throw;
    }
}