Get link from HTML code anchor tag

Task: Get Link from HTML code anchor <a> tag using Asp.net and C# code.

Description:  Sometime we need to retrieve link from HTML code <a> tag Or sometime we need to modify/append/alter that link.
So in this function the HTML code is use as input and then we can retrieve link in that html code <a> tag.

Code: 

public void getlinkfromhtml(string content)
{
  int index = 0;
  do
  {
    int newindex = index + 5;
    index = content.IndexOf("href=", newindex);
    if (index > 0)
    {
      int index2 = content.IndexOf('\'', index + 6);
      int index3 = content.IndexOf('\"', index + 6);

      if (index3 > 0)
      {
        if (index2 > index3 || index2 == (-1))
            index2 = index3;
      }
      if (index2 > 0)
      {
        string href = content.Substring(index+6,(index2-(index + 6))).ToLower();

// Save/Use or do anything with this link href. You Can replace also this with another link.

      }
    }
  }
  while (index > 1);
}

View Pdf on browser using asp.net

Task: View Pdf on browser using asp.net.

Description: Here I show how we can view the pdf file on browser using asp.net and c#.

using System.Net;
public void viewebook(string pdf_filepath)
{
    string FilePath = Server.MapPath(pdf_filepath);
    WebClient User = new WebClient();
    Byte[] FileBuffer = User.DownloadData(FilePath);
    if (FileBuffer != null)
    {
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-length", FileBuffer.Length.ToString());
        Response.BinaryWrite(FileBuffer);
    }

}

Facebook feed using graph api

Task: Get Facebook page feed using graph api.

Description: As facebook depreciated old feed url (https://www.facebook.com/feeds/page.php?format=rss20&id=page_id). So now we need to use its graph api for this.

Here I describe how to get facebook page feed using graph api using javascript code. You just need to update your access token ( use app token as access token from here https://developers.facebook.com/tools/accesstoken/ ). 

you can run below url on your browser for all fields and can use as your requirements. In below code limit is use for how many post will return.

https://graph.facebook.com/1399557183635849/feed?access_token=224210267619471|gtYtk8w5_qPHbZkSpJ9pwD7Qy-8

https://graph.facebook.com/page_id/feed?access_token=yourapptoken



<script src="http://code.jquery.com/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="https://connect.facebook.net/en/all.js" type="text/javascript"></script>
<script>
 FB.api('https://graph.facebook.com/page_id/feed?access_token=yourapptoken', { limit: 20 }, function (response) {

 if (response && !response.error) {
 var msg='';
            for (var i = 0, l = response.data.length; i < l; i++) {
                var post = response.data[i];
                var userid = post.from.id;
                if (post.message) {                       
                    msg += '<span style="word-break: break-all;">'+ post.message  + '<br/><a  rel="nofollow" href='+post.link+'><img src=' +  post.picture  +' /></a>' + '</span><br/><br/>';                       
                }
                document.getElementById("sFbFeeds").innerHTML=msg;
            }
            }
            else
            {
               // alert('Error Occure');
            }
        });

        </script>
<div id="fb-root"></div>
<div id="sFbFeeds"></div>

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;

}