Get Latest Twitter Feed in our website

  Uncategorized

Step 1: Create a div element like below:-

<div id="twitter_feed"  runat="server"></div>

Step 2: Add the following method:-

using System.Text.RegularExpressions;
using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization;
using System.Net;
using System.Security.Cryptography;
using System.Globalization;

// use this in your page_load method or anywhere...
//twitter_feed.InnerHtml = GetTwitterFeeds();


// unique request
public static string GetTwitterFeeds()
{
    var oauth_token = "xxxxxxTOKEN-FROM-TWITTER-xxxxxxx";
    var oauth_token_secret = "xxxxxxTOKEN-SECRET-FROM-TWITTER-xxxxxxx";
    var oauth_consumer_key = "xxxxxxKEY-TWITTER-xxxxxxx";
    var oauth_consumer_secret = "xxxxxxSECRET-FROM-TWITTER-xxxxxxx";
    var screen_name = "TwitterScreenName";
    var count = 2; // set count how many feeds you want to show here

    // oauth implementation details
    var oauth_version = "1.0";
    var oauth_signature_method = "HMAC-SHA1";

    // unique request details
    var oauth_nonce = Convert.ToBase64String(
        new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
    var timeSpan = DateTime.UtcNow
        - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();

    // message api details
    var resource_url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
    // create oauth signature
    var baseFormat = "count=" + count + "&oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
                    "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&screen_name={6}";

    var baseString = string.Format(baseFormat,
                                oauth_consumer_key,
                                oauth_nonce,
                                oauth_signature_method,
                                oauth_timestamp,
                                oauth_token,
                                oauth_version,
                                 Uri.EscapeDataString(screen_name)
                                );

    baseString = string.Concat("GET&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString));

    var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
                            "&", Uri.EscapeDataString(oauth_token_secret));

    string oauth_signature;
    using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
    {
        oauth_signature = Convert.ToBase64String(
            hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
    }

    // create the request header
    var headerFormat = "OAuth oauth_nonce="{0}", oauth_signature_method="{1}", " +
                       "oauth_timestamp="{2}", oauth_consumer_key="{3}", " +
                       "oauth_token="{4}", oauth_signature="{5}", " +
                       "oauth_version="{6}"";

    var authHeader = string.Format(headerFormat,
                            Uri.EscapeDataString(oauth_nonce),
                            Uri.EscapeDataString(oauth_signature_method),
                            Uri.EscapeDataString(oauth_timestamp),
                            Uri.EscapeDataString(oauth_consumer_key),
                            Uri.EscapeDataString(oauth_token),
                            Uri.EscapeDataString(oauth_signature),
                            Uri.EscapeDataString(oauth_version)
                    );


    // make the request

    ServicePointManager.Expect100Continue = false;

    var postBody = "count=" + count + "&screen_name=" + Uri.EscapeDataString(screen_name);//
    resource_url += "?" + postBody;
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
    request.Headers.Add("Authorization", authHeader);
    request.Method = "GET";
    request.ContentType = "application/x-www-form-urlencoded";

    WebResponse response = request.GetResponse();
    string responseData = new StreamReader(response.GetResponseStream()).ReadToEnd();

    JavaScriptSerializer serializer = new JavaScriptSerializer();

    var result = serializer.Deserialize<Tw[]>(responseData);
    string str1 = "";

    str1 = "";
    foreach (var item in result)
    {
        str1 += "<div id="twitter-container" class='tfeed-text'>" + ReplaceLinks(item.text) + " ";
        DateTime d = DateTime.ParseExact(item.created_at, "ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture);
        str1 += "<br/><a target='_blank' rel='nofollow' href='http://twitter.com/" + Uri.EscapeDataString(screen_name) + "'>" + ToRelativeDate(d) + "</a></div><hr class='hrr3'>";


    }
    return str1;
}

public static string ToRelativeDate(DateTime dateTime)
{
    var timeSpan = DateTime.Now - dateTime;

    if (timeSpan <= TimeSpan.FromSeconds(60))
        return string.Format("{0} seconds ago", timeSpan.Seconds);

    if (timeSpan <= TimeSpan.FromMinutes(60))
        return timeSpan.Minutes > 1 ? String.Format(" {0} minutes ago", timeSpan.Minutes) : "about a minute ago";

    if (timeSpan <= TimeSpan.FromHours(24))
        return timeSpan.Hours > 1 ? String.Format(" {0} hours ago", timeSpan.Hours) : "about an hour ago";

    // if (timeSpan <= TimeSpan.FromDays(30))
    return timeSpan.Days > 1 ? String.Format(" {0} days ago", timeSpan.Days) : "1 day ago";

    /* if (timeSpan <= TimeSpan.FromDays(365))
         return timeSpan.Days > 30 ? String.Format("about {0} months ago", timeSpan.Days / 30) : "about a month ago";

     return timeSpan.Days > 365 ? String.Format("about {0} years ago", timeSpan.Days / 365) : "about a year ago";
 */
}
public class Tw
 {
   public string text;
   public string created_at;
 }

public static string ReplaceLinks(string arg)
//Replaces web and email addresses in text with hyperlinks
{
    Regex urlregex = new Regex(@"(^|[n ])(?(www|ftp).[^ ,""s<]*)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
    arg = urlregex.Replace(arg, " <a href="http://${url}" target="_blank">${url}</a>");
    Regex httpurlregex = new Regex(@"(^|[n ])(?(http://www.|http://|https://)[^ ,""s<]*)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
    arg = httpurlregex.Replace(arg, " <a href="${url}" target="_blank">${url}</a>");
    Regex emailregex = new Regex(@"(?<url>[a-zA-Z_0-9.-]+@[a-zA-Z_0-9.-]+.w+s)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
    arg = emailregex.Replace(arg, " <a href="mailto:${url}">${url}</a> ");
    return arg;

}
  

 

(Visited 6 times, 1 visits today)

LEAVE A COMMENT