Helpers y Componentes para implementar funcionalidad de Tweets.

Como se vé se está usando un helper GoogleUrlShortner, el cual permite consumir un servicio de google para convertir una url larga en corta. Veamos este helper el cual se encontró en la Web, ya que esta funcionalidad extendía la intención inicial de este post. Para ver el autor en el siguiente link

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Json;

namespace ReadDotNet.Web.Service
{

    public class GoogleUrlShortner
    {
        public static GoogleUrlReply Shorten(string longUrl)
        {
            string data = "{\"longUrl\":\"" + longUrl + "\"}";
            string gUrl = "https://www.googleapis.com/urlshortener/v1/url";

            string response = Post(gUrl, data);
            return FromJSON(response);
        }

        private static string Post(string url, string data)
        {
            WebRequest request = WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json";

            byte[] byteData = Encoding.UTF8.GetBytes(data);

            request.ContentLength = byteData.Length;

            using (Stream s = request.GetRequestStream())
            {
                s.Write(byteData, 0, byteData.Length);
                s.Close();
            }

            string replyData;

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (Stream dataStream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(dataStream))
                    {
                        replyData = reader.ReadToEnd();
                    }
                }
            }

            return replyData;
        }

        private static T FromJSON(string input)
        {
            MemoryStream stream = new MemoryStream();

            try
            {
                DataContractJsonSerializer jsSerializer = new DataContractJsonSerializer(typeof(T));
                stream = new MemoryStream(Encoding.UTF8.GetBytes(input));
                T obj = (T)jsSerializer.ReadObject(stream);

                return obj;
            }
            finally
            {
                stream.Close();
                stream.Dispose();
            }
        }
    }

    public class GoogleUrlReply
    {
        public string id { get; set; }
    }
}