Get Latest Twitter Feed in our website

Task: Get Latest Twitter Feed to our website.

Description: Now a days the social networking is vary popular and important for our online presence. All Online business also need to use it properly to make benefit from them. So just time to get twitter feed to your website. Here I describe the code for getting twitter latest feed for your website.


Code: 

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



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 ])(?<url>(www|ftp)\.[^ ,""\s<]*)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
    arg = urlregex.Replace(arg, " <a href=\"http://${url}\" target=\"_blank\">${url}</a>");
    Regex httpurlregex = new Regex(@"(^|[\n ])(?<url>(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;

}
 

Dynamically resize image with maintain its ratio in asp.net

Task: Dynamically Re-size Image with maintain its ration using Asp.net and C# code.

Description: Many times we need to store different size images for a specific images as used in e-commerce website. for that we re-size the image and save multiple images as one small, medium and a full size image. But If we have issue regarding space and having good performance server then we can use dynamically re-sizing of image just save single big image and then when need to use re-size it at run time as you want.

For achieving this task I write a code which response the re-size image. I use it for jpg and png images not for gif.



Call the page where you code for image merging :

Image1.ImageUrl = "dynamicimage.aspx";



Dynamic Code for image generation and merging (dynamicimage.aspx/dynamicimage.aspx.cs)


using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

protected void Page_Load(object sender, EventArgs e)
{
  string testimage = Server.MapPath(@"images/hemant_image.jpg");
  getimage(testimage, 400, 400); 
  // can set imageurl, max-width and max-height using query string...
}

public void getimage(string ThumbnailPath, int maxwidth, int maxheight)
{
    System.Drawing.Image image = System.Drawing.Image.FromFile(ThumbnailPath);
    Size ThumbNailSize = setimagesize(maxwidth, maxheight, image.Width, image.Height);

    System.Drawing.Image ImgThnail = new Bitmap(ThumbNailSize.Width, ThumbNailSize.Height);
    System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(ImgThnail);

    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
    graphics.SmoothingMode = SmoothingMode.HighQuality;
    graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
    graphics.CompositingQuality = CompositingQuality.HighQuality;
    graphics.DrawImage(image, 0, 0, ThumbNailSize.Width, ThumbNailSize.Height);

    ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();
    EncoderParameters encoderParameters;
    encoderParameters = new EncoderParameters(1);
    encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);

    string sExt = System.IO.Path.GetExtension(ThumbnailPath);

    if (sExt.ToString() == ".png")
    {
        Response.ContentType = "image/png";
        ImgThnail.Save(Response.OutputStream, image.RawFormat);
    }
    else
    {
        Response.ContentType = "image/jpeg";
        ImgThnail.Save(Response.OutputStream, info[1], encoderParameters);
    }
    image.Dispose();
}

// below code is my old one for calculating height and width with maintain image ratio.

public Size setimagesize(int maxwidth, int maxheight, int OriginalWidth, int OriginalHeight)
{
    Size NewSize = new Size();
    int sNewWidth = OriginalWidth;
    int sNewHeight = OriginalHeight;
    int tempheight = 0;
    int tempwidht = 0;
    if (OriginalWidth >= OriginalHeight)
    {
        if (OriginalWidth >= maxwidth)
        {
            sNewWidth = maxwidth;
            sNewHeight = OriginalHeight * maxwidth / OriginalWidth;
        }
        if (sNewHeight > maxheight)
        {
            tempheight = sNewHeight;
            sNewHeight = maxheight;
            sNewWidth = sNewWidth * maxheight / tempheight;
        }
    }
    else
    {
        if (OriginalHeight >= maxheight)
        {
            sNewHeight = maxheight;
            sNewWidth = OriginalWidth * maxheight / OriginalHeight;
        }
        if (sNewWidth > maxwidth)
        {
            tempwidht = sNewWidth;
            sNewWidth = maxwidth;
            sNewHeight = sNewHeight * maxwidth / tempwidht;
        }
    }
    NewSize = new Size(sNewWidth, sNewHeight);
    return NewSize;
}



Show image with watermark dynamic using code

Task: Show Image With Watermark dynamically using Asp.net and C# code.

Description: Sometime we need to add watermark with image on website so that no one can copy and reuse it. So that we can do it by a vary simple way using our back-end code. Here I write a code for achieving this task.
Here we can use image URL to that page URL where we write a code for merging these two images. And in code file I make a function for it we can call it in page_load event. In this function we have to pass both image URL, our image and watermark (watermark should be less then of image size - I will work later for resolve this issue also) and two points x and y for watermark position on that image (these points should be appropriate I also resolve this issue in my next post).
Watermark image should be "PNG" for better result.

Here I show the repetitive watermark on image, You can use it single or anyway as you w...
  

Call the page where you code for image merging :

Image1.ImageUrl = "dynamicimage.aspx";
 

Dynamic Code for image generation and merging (dynamicimage.aspx.cs)

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;


protected void Page_Load(object sender, EventArgs e)
{

string ThumbnailPath = Server.MapPath(@"images/testimage.jpg");
string watermark =Server.MapPath(@"images/watermark.png");
drawimagewm(ThumbnailPath, watermark, 50, 50);


}
public void drawimage(string imageurl, string watermark, int startx, int starty)
{
    string ThumbnailPath = imageurl;
    string Thumb_WMPath = watermark;

    System.Drawing.Image image = System.Drawing.Image.FromFile(ThumbnailPath);
    System.Drawing.Image img_WM = System.Drawing.Image.FromFile(Thumb_WMPath);

    int width = image.Width;
    int height = image.Height;

    int width2 = img_WM.Width;
    int height2 = img_WM.Height;

    System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(image);

    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
    graphics.SmoothingMode = SmoothingMode.HighQuality;
    graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
    graphics.CompositingQuality = CompositingQuality.HighQuality;

    if (startx > (width - width2) || starty > (height - (height2)))
    {
        graphics.DrawImage(image2, new Point(startx, starty));
    }
// I use 50 for gapping between two watermark...
    for (int i = startx; i < (width - (width2)); i = i + width2 + 50)
    {
        for (int j = starty; j < (height - (height2)); j = j + height2 + 50)
        {
            graphics.DrawImage(img_WM, new Point(i, j));
        }
    }
    ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();
    EncoderParameters encoderParameters;
    encoderParameters = new EncoderParameters(1);
    encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);

    string sExt = System.IO.Path.GetExtension(ThumbnailPath);
    Response.ContentType = "image/jpeg";

    if (sExt.ToString() == ".jpg" || sExt.ToString() == ".jpeg")
    {
        image.Save(Response.OutputStream, info[1], encoderParameters);
    }
    else
    {
        image.Save(Response.OutputStream, image.RawFormat);
    }
    image.Dispose();
    img_WM.Dispose();
}

Get Blogger Post - Rss Feed in our website

Task: Get Blogger RSS Feed/Post to our website (Show blogger post to our website).

Description: Sometime we need to show blogger post(RSS Feed) to our website. Using below code we can read all blog post from blogger(blogspot) Or we can also modify the code for reading other RSS feed(XML). The basic behind the reading RSS is read XML response. The blogger provides us a Rss link, from where we can read the XML.
I also used the string trimming with removing html tag Method As I used previously : Remove Html Tag
Here I used two methods for achieving this.

Method 1 : Using XML...

// Code Start //

using System.Xml;

using System.Text.RegularExpressions;

public string blogdetail = "";
private void ReadRssFeed()
{
    string blog = "";
    string RssFeedUrl = "http://hemantrautela.blogspot.com/feeds/posts/default?alt=rss";
    XDocument xDoc = new XDocument();
    xDoc = XDocument.Load(RssFeedUrl);
    var items = (from x in xDoc.Descendants("item")
                 select new
                 {
                     title = x.Element("title").Value,
                     link = x.Element("link").Value,
                     pubDate = x.Element("pubDate").Value,
                     description = x.Element("description").Value
                 });
    if (items != null)
    {
        foreach (var i in items)
        {
            String result = Regex.Replace(i.description, @"<[^>]*>", String.Empty);
            if (result.Length > 300)
            {
                result = result.Substring(0, 300);
                result = result.Substring(0, result.LastIndexOf(" ")) + "...";

            }
            blog += "<a href='" + i.link + "' rel='nofollow'>" + i.title + "</a><br/>" +
                    result + "<br/><br/>";
        }
        blogdetail = blog;
    }

}

// Code End//


Method 2 : Using by System.ServiceModel.Syndication

// Code Start //

    
    using System.Text.RegularExpressions;

    public string blogdetail = "";
    public void ReadRssFeed()
    {
        string rssFeedUrl = "http://hemantrautela.blogspot.com/feeds/posts/default?alt=rss";
        var syndicationFeed = System.ServiceModel.Syndication.SyndicationFeed.Load(XmlReader.Create(rssFeedUrl));
        string blog = "";
        foreach (var item in syndicationFeed.Items)
        {
            String result = Regex.Replace(item.Summary.Text, @"<[^>]*>", String.Empty);
            if (result.Length > 300)
            {
                result = result.Substring(0, 300);
                result = result.Substring(0, result.LastIndexOf(" ")) + "...";
            }
            blog += "<a href='" + item.Links[0].Uri + "' rel='nofollow'>" + item.Title.Text + "</a><br/>" +
                    result + "<br/><br/>";
        }
        blogdetail = blog;

    }

// Code End//