Get Twitter, Facebook And Feed Readers Count In ASP.NET

2. September 2011 03:40

API ASP.NET Code Snippets Web 

I am working on some web stuff these days and surfing around to look at some of the best web developer's work around the web. As I was surfing I came across one of the most popular and reputed web tutorials site Nettus+. I am not going talking about any tutorial or article published on this site, but one thing that attracts my attention was the way they are displaying their followers count on twitter, facebook likes and RSS readers.
This looks pretty cool and just out of curiosity I viewed the page source, hoping to find some script or API call which gets the count. But eventually I can't found anything. For Twitter and Facebook I know that there is an API and therefore I can get the twitter followers and facebook like count but don't know anything about the feed readers count. So I search the web get myself aware of the feedburner API. So let's take a look at the code.
 
Get Twitter Followers Count

To get your twitter followers count, I am making a REST API call. This call will return XML string and then I am going to parse the received XML using LINQ. You just need to pass your twitter user name to get the followers count.
public string GetTwitterFollowersCount(string UserName)
{
            XDocument xdoc = XDocument.Load("http://api.twitter.com/1/users/show.xml?screen_name=" + UserName + "&include_entities=false");
            return (from item in xdoc.Descendants("user")
                    select item.Element("followers_count").Value).SingleOrDefault();
}
Get Facebook Likes Count

To get total Facebook likes count you need to remember that you have to use the URL of your page for e.g. http://www.facebook.com/audi or http://www.facebook.com/nettutsplus and not just the name of your page. Check out the code:
public string GetFacebookLikes(string FaceBookURL)
{
         string URL = "https://api.facebook.com/method/fql.query?query=select%20%20like_count,%20total_count,%20share_count,%20click_count%20from%20link_stat%20where%20url=%22" + FaceBookURL + "%22";
         XElement xdoc = null;
         XElement counts = null;
         xdoc = XElement.Load(URL);

         IEnumerable<XElement> total_Like_count =
             from elem in xdoc.Descendants()
             where elem.Name.LocalName == "like_count"
             select elem;

         counts = total_Like_count.First();
         string FBLikes = Convert.ToString(counts.Value);
         return FBLikes;
}
Get RSS Feed Readers Count

To get the RSS feed readers count you need to pass the complete URL of your feed URL for e.g. http://feeds.feedburner.com/MidnightProgrammer
public string GetFeedReadersCount(string url)
{
            XDocument xdoc = XDocument.Load("http://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=" + url);
            return (from item in xdoc.Descendants("entry")
                    select item.Attribute("circulation").Value).SingleOrDefault();
}

This is it, now it all depends on the designer or developer how to get the stats and present it in a more attractive way. I am not a designer and this is why I am not putting any effort to do something like this to show you this thing in action. At present I am working on JQuery version of the above code, so people who are willing to show stats on their blogs or website which are different platforms. Till that time, try the above code with ASP.NET and let me know of this helps you out.

Currently rated 3.9 by 7 people

Using ReCaptcha In ASP.NET WebForms And MVC

31. July 2011 14:58

API ASP.NET ASP.NET MVC 

ReCaptcha is now being used widely by many websites especially where there is a possibility of spamming the website, blog or a forum. Here I will show you on how you can use ReCaptcha in ASP.NET and MVC. Get a ReCaptcha Gobal Key and ASP.NET ReCaptcha DLL. Once you get the global key we are ready to go.
 
ReCaptcha in WebForms
 
Fire Visual Studio and create a new ASP.NET web forms project. First add a ReCaptcha DLL in the project and as we are talking about a user control we will have to register the control. On the top of the page use the register directive to register the ReCaptcha control.
<%@ register tagprefix="recaptcha" namespace="Recaptcha" assembly="Recaptcha" %>
Now on the page, we will use the control.
<recaptcha:recaptchacontrol id="recaptcha" runat="server" publickey="public key"  privatekey="private key" />
You will get the public key and the private key when you register for the ReCaptcha global key. This will render the ReCaptcha control on the page.
Notice that I have also placed a button and the label (with no text) on the page along with the ReCaptcha control. On the submit button we will check the Page.IsValid method. If the ReCaptcha text entered by the user is correct then the Page.IsValid method will return true else it will return false. Therefore the code on the submit button will be as follows:
if (Page.IsValid)
{
      lblStatus.Text = "Captcha Validated!";
}
else
{
      lblStatus.Text = "Invalid Captcha!";
}
This is it, hit F5 and try it out. We are now done implementing ReCaptcha in web forms and now we will see it in action in MVC.
 
ReCaptcha in MVC
 
Create a new MVC project in Visual Studio and I am using MVC 3 with RAZOR View Engine. To implement ReCaptcha in MVC, we will be using Microsoft Web Helpers. I assume you are aware of NuGet. Just in case if you are not aware of the Microsoft Web Helpers read my post on Working With Microsoft Web Helpers In MVC 3 Razor View. Microsoft web helpers allow us to use ReCaptcha in a very easy way. In WebForms we have used a DLL to render the ReCaptcha control on the page, but with Microsoft web helpers we can render the control with a single line of code. As you have used NuGet to install Microsoft Web Helpers library, make sure that you also use the correct namespace on the top of the page.
@using Microsoft.Web.Helpers;

@using (Html.BeginForm("Submit", "Home", FormMethod.Post))
{
    @ReCaptcha.GetHtml(publicKey: "<public key>", theme: "red")
}
I have rendered the control inside the form because when the data gets submitted after user enters the text the Submit method of the Home controller gets fired and check the captcha text entered by the user. As you know we have two keys with us, one is a public key and the other is a private key. We have used the public key to render the control on the page and we will now use the private key to validate the captcha. Also make sure that in order to use the ReCaptcha class on server side code you need to add the Microsoft.Web.Helpers namespace.
[HttpPost]
public ActionResult Submit()
{
        if (ReCaptcha.Validate(privateKey: "<private key>"))
        {
             return Content("Valid Captcha");
        }
        else
       {
            return Content("InValid Captcha");
       }
}
The ReCaptcha class of the web helpers provides a method to validate the entered text by the user. The private key of the ReCaptcha is passed as a parameter in order to validate the captcha text.
Using ReCaptcha with ASP.NET WebForms or MVC is pretty simple and easy. Here are some of the links which I feel you might find useful.
Currently rated 5.0 by 1 person

Blog Analytics: Widget For BlogEngine.NET Powered By Google Analytics

19. March 2011 17:44

API ASP.NET BlogEngine.NET 

Finally, I got to know the way to show Google Analytics stats on my blog space. To know more about using Google Analytics API read their official article on using the API.

I have built a widget with the help of Analytics API to show the Google Analytics stats on my blog. The widget shows three stats at the moment (I don't want to make the widget look complex). Below is a screenshot for the widget in action on my blog:

 

The above widget shows the stats since I have started blogging. As you can see my blog is not as popular as yours or as popular comparative with other MSFT guys and other popular bloggers. As usual before you can use the widget you need to do some settings for the widget.

  

You should be aware by now that this widgets uses Google Analytics API, and I hope you all have Analytics account. The Username and Password will be the same as your Analytics account (and without @xyz.com). From Date and To Date specifies the date range which then populate the stats from Analytics service for the specified date range. I have provided an option that allows you to always use the To Date as the current date, you can do that by checking Always use Current Date (checking this will override To Date value). If you wish to show the stats ONLY for the current day then check Use From and To Date as Current Date (change the widget title from what you have to Today's Hit or whatever you wish!). I have settings as shown in the screenshot above for my blog and I am showing all my stats since I have started blogging.Last three options will allow you to toggle between the three statistics options you want to show on the widget or not.

I built this this in a lot of hurry, so if you find some bug or have some thoughts or you have made the widget more uselful, please feel free to write to me using the Contact form and let me know.

Download: BlogAnalytics - Widget.zip (107.28 kb)

Currently rated 5.0 by 3 people

Bit.ly API: Shorten URLs / Reverse Long URLs / Get QR Code Image

17. March 2011 16:03

.NET Framework API C# Utils 

If you have long URLs and other and want to create short URLs then Bit.ly API can help. I wrote a wrapper class which can let me create short URLs in jiffy. I was working on Bit.ly API to create my short URLs with a click of a button (that's for my personal use). Therefore, I ended up with a 'short' class to create shor URLs using Bit.ly API. What you need is a login and an apikey, which you can have one for yourself by signing up for a free account. You can find your apikey here after login. The class gives you two ways to make short URL, one with XML and the other with plain TEXT. I haven't write anything for JSON as it was not required at all to me in any ways. I am using plain TEXT for this example. You can read Bit.ly API official documentation for more information.

The below class can be used to create short URLs using Bit.ly API, reverse the short URLs and get the original URL. Also if you are not aware you can have a QR code of your short URL. Read more about QR Code here. If you are using Bit.ly or Goo.gl to shorten your URLs then you can have the QR code image by adding .qrcode in the end of the short URL (See in the code example below)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Net;
using System.IO;

namespace Bitly.API
{

    public class BitlyData
    {
        #region Properties

        public static string APIKEY { get; set; }
        public static string LoginName { get; set; }

        public static string StatusCode { get; set; }
        public static string StatusDesc { get; set; }
        public static string ShortURL { get; set; }
        public static string LongURL { get; set; }
        public static string HashCode { get; set; }
        public static string GlobalCode { get; set; }
        public static string NewHash { get; set; }

        #endregion
    }

    public class Bitly
    {

        #region Bit.Ly Variables

        private static string URL = "http://api.bit.ly/v3/shorten?login=";

        private static string BitResponse = "";

        #endregion

        #region Enums

        public enum Format
        {
            XML,
            JSON,
            TXT
        }

        #endregion

        #region Sample Response
        //        <?xml version="1.0" encoding="utf-8"?>
        //<response>
        //    <status_code>200</status_code>
        //    <status_txt>OK</status_txt>
        //    <data>
        //        <url>http://bit.ly/ekYLee</url>
        //        <hash>ekYLee</hash>
        //        <global_hash>gBH72m</global_hash>
        //        <long_url>http://midnightprogrammer.net/post/Windows-7-Development-Working-With-Task-Dialog-Class.aspx</long_url>
        //        <new_hash>1</new_hash>
        //    </data>
        //</response>

        #endregion

        public static string ShortURL(string LongURL, Format ReqFormat = Format.TXT)
        {
            string sURL = string.Empty;
            string BitLyURL = URL + BitlyData.LoginName + "&apikey=" + BitlyData.APIKEY + "&longUrl=" + LongURL + "&format=";

            if (ReqFormat == Format.JSON)
            {
                throw new NotImplementedException("This method is not implemented yet!");
            }

            if (ReqFormat == Format.XML)
            {
                BitResponse = new WebClient().DownloadString(BitLyURL + "xml");
                string Response = BitResponse;

                XmlDocument doc = new XmlDocument();
                doc.LoadXml(Response);
                XmlNodeList XlistResponse = doc.GetElementsByTagName("response");

                foreach (XmlNode XResnode in XlistResponse)
                {
                    XmlElement ResElm = (XmlElement)XResnode;

                    BitlyData.StatusCode = ResElm.GetElementsByTagName("status_code")[0].InnerText;

                    if (BitlyData.StatusCode != "200")
                    {
                        BitlyData.StatusDesc = ResElm.GetElementsByTagName("status_txt")[0].InnerText;
                        return BitlyData.StatusDesc;
                    }
                }

                if (BitlyData.StatusCode == "200")
                {

                    XmlNodeList XlistData = doc.GetElementsByTagName("data");

                    foreach (XmlNode XDatanode in XlistData)
                    {
                        XmlElement DataElm = (XmlElement)XDatanode;

                        BitlyData.ShortURL = DataElm.GetElementsByTagName("url")[0].InnerText;
                        BitlyData.LongURL = DataElm.GetElementsByTagName("long_url")[0].InnerText;
                        BitlyData.HashCode = DataElm.GetElementsByTagName("hash")[0].InnerText;
                        BitlyData.GlobalCode = DataElm.GetElementsByTagName("global_hash")[0].InnerText;
                        BitlyData.NewHash = DataElm.GetElementsByTagName("new_hash")[0].InnerText;
                    }
                }
            }

            if (ReqFormat == Format.TXT)
            {
                if (ReqFormat == Format.TXT)
                {
                    BitResponse = new WebClient().DownloadString(BitLyURL + "txt");
                    string Response = BitResponse;

                    BitlyData.ShortURL = Response;
                }
            }

            return sURL = BitlyData.ShortURL;
        }

        public static string ReverseShortURL(string ShortURL)
        {
            HttpWebRequest Webrequest = (HttpWebRequest)HttpWebRequest.Create(ShortURL);
            HttpWebResponse Webresponse = (HttpWebResponse)Webrequest.GetResponse();
            Uri uri = Webresponse.ResponseUri;
            return uri.AbsoluteUri;
        }

        public static string GetQRCodeURL(string ShortURL)
        {
            string QRCodeURL = string.Empty;
            QRCodeURL = ShortURL + ".qrcode";
            return QRCodeURL;
        }
    }
}

In the above class you can see that the second parameter is accepting TXT by default. So, if you call the method with or without the second parameter it will still work with the default parameter TXT. The enumeration called Format contains all the possible format of all the formats which is accepted by Bit.ly API. The second parameter in the class above should be removed if you plan to use the above code with the lower versions of .NET i.e. 3.x / 2.0

Sample Usage .NET 3.x / 2.0

Bitly.API.BitlyData.LoginName = "LOGIN NAME GOES HERE";
Bitly.API.BitlyData.APIKEY = "API KEY GOES HERE";
Console.WriteLine("Short URL: "+Bitly.API.Bitly.ShortURL("http://midnightprogrammer.net/post/9-Promises-Should-Be-Taken-Before-Choosing-IT-Profession.aspx", Bitly.API.Bitly.Format.TXT));
Console.WriteLine("Reverse URL: "+Bitly.API.Bitly.ReverseShortURL("http://bit.ly/eZ1kdb"));
Console.WriteLine("QRCode Image URL " + Bitly.API.Bitly.GetQRCodeURL("http://bit.ly/eZ1kdb"));

Sample usage .NET 4.0

Bitly.API.BitlyData.LoginName = "LOGIN NAME GOES HERE";
Bitly.API.BitlyData.APIKEY = "API KEY GOES HERE";
Console.WriteLine("Short URL: "+Bitly.API.Bitly.ShortURL("http://midnightprogrammer.net/post/9-Promises-Should-Be-Taken-Before-Choosing-IT-Profession.aspx", Bitly.API.Bitly.Format.TXT));
Console.WriteLine("Reverse URL: "+Bitly.API.Bitly.ReverseShortURL("http://bit.ly/eZ1kdb"));
Console.WriteLine("QRCode Image URL " + Bitly.API.Bitly.GetQRCodeURL("http://bit.ly/eZ1kdb"));

I have tested my code with Console Application, but you can test it with web or Windows form application. Note that the default parameters are only accepted if you are working with .NET 4.0 and not by the lower versions of .NET. If you wish to use the second parameter in .NET 4 then also it will work, but not using it with lower version will give you error.

I hope this class helps someone around the globe!

Currently rated 4.7 by 6 people

Working With Microsoft Web Helpers In MVC 3 Razor View

6. March 2011 10:58

API ASP.NET MVC Microsoft 

Building applications with ASP.NET MVC 3 and that too with RAZOR is easy. I believe most of the programmers out there found MVC 3 with RAZOR view engine found it easy. The best things I found in the new RAZOR view engine is the code is pretty much tidy no traditional code behinds and moreover you can work with the server-side code with the start of the @ symbol.
What is a Helper Class?
I am not going to copy and paste the definition from somewhere but I want to write my own thoughts on the helper class. Maybe this is not the best definition but this is how I would like to describe the Helper Class.
A class that minimize the effort incurred in the design, implementation of functionality on your application is called a helper class.
One of the best things that Microsoft incorporated in the framework is the use of the helper classes. Although this is not a new concept, previously also all the programmers are working on their own to create helper classes for the work they are doing to minimize the effort and time spend in writing the same lines of code again and again. Microsoft Web Helpers provides some of the best helper classes that can be used in almost every web application.
How to get Microsoft Web Helpers
To use Microsoft Web Helpers in your project use the below NuGet command:
If you are using Web Matrix then you can start using the helper class right away, but if you have created the application from Visual Studio then you still need the Web Matrix reference in you project. You can add the Web Matrix reference from C:\Program Files\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies. Once installed, you can now use it for majority of the complex tasks with ease and in less time. Some of the major use of this helper class is listed below:
Using Web Helpers
Gravatar: To show the gravatar on your web page use the Gravatar class Gethtml() and pass e-mail address as a parameter. If the e-mail id provided, has no Gravatar then the default Garavatar image will be displayed. To get the Gravatar with default Gravatar image:
@Gravatar.GetHtml("prashant@midnightrogrammer.net")
 
You can also have your own default image to replace the default Gravatar image. To show your own default image use the defaultImage: attribute
@Gravatar.GetHtml("prashant@midnightrogrammer.net", defaultImage: "http://midnightprogrammer.net/pics/default.gif")
Twitter: Twitter helper class can be used to show your tweets using the Profile method. This will display the same widget that you can get for youself from the Twitter website. Moreover you can also change the apperance of the widget. To display your tweets you can use your twitter profile name as a parameter in the Profile method.
@Twitter.Profile("prashantmx")
 
You can also search Twitter and display all the reactions. If I have to search about Windows Phone 7 then I will use the keyword #WP7.
@Twitter.Search("#wp7")
 
For Twitter follow button:
@TwitterGoodies.FollowButton("prashantmx")
Tweet Button: The tweet button will help you to tweet your website or blog content. But this time we will use the TwitterGoodies class TweetButton
@TwitterGoodies.TweetButton(TwitterGoodies.DataCount.Horizontal, "This is RAZOR Tweet", "http://midnightprogrammer.net", TwitterGoodies.Languages.English,"prashantmx")
 
You can set the align of tweet counts either vertically or horizontally or none. I have set it to horizontal.
Google / Yahoo Analytics: Insert tracking code in your website directly
@Analytics.GetGoogleHtml("UA-9087")
Same can be done for Yahoo. Just use GetYahooHtml instead of GetGoogleHtml
Facebook: Facebook integration is now much easier. To get the like button use:
@Facebook.LikeButton("http://midnightprogrammer.net")
To show the latest activity feed use the ActivityFeed method. I am going to see the latest activity from Microsoft
@Facebook.ActivityFeed("http://www.microsoft.com")
 
Microsoft Bing Search: If you want to have a search then the best option is to use Microsoft Bing (Because It's Not Google). There are two Bing search boxes that you can use, but the most popular is the Bing Advanced Search Box. Below are the two ways to use the Bing Search box
Normal Search Box
@{
    Bing.SiteTitle = "Midnight Programmer";
    Bing.SiteUrl = "http://midnightprogrammer.net";
}

@Bing.SearchBox()
 
Advanced Search Box
The same code will be used to show the advanced search box, just use the AdvancedSearchBox method instead of SearchBox as done previously
@{
    Bing.SiteTitle = "Midnight Programmer";
    Bing.SiteUrl = "http://midnightprogrammer.net";
}

@Bing.AdvancedSearchBox()
The main advantage of using the advanced search box for Bing is that it will let you search the whole website/blog without taking you to the Bing site and display the search content in the small container with two tabs showing the search result from the website/blog and the other one from the web.
Note: Bing team at Microsoft announced that they will be shutting down siteowner service on April 4th. This will prevent you to use the AdvancedSearchBox feature of Bing on your website/blog or web applications. Here is the quote from Bing's official blog:
As of April 4th, 2011 we will discontinue support for the bing.com/siteowner functionality. If you continue to leverage the feature after this date (April 4th, 2011), users who attempt to query in the search box will be redirected to a 404 page. This means that you will need to move to the Bing API in order to continue to receive web or site search results from us. We have decided to take this step for two reasons.
First, the tool has not been getting a lot of use and while we have some very loyal customers on it, we believe we can provide you better alternatives in the future as we free up resources.
Second, the functionality available through bing.com/siteowner can be replicated with the Bing search API and so it feels a bit redundant.
As has become customary, we will give you a window to migrate off and ask us any questions you may have about this change. We will also provide reminders as we get closer to April 4th. Thank you so much for your support.
 
So this is it. These are some of the helper classes in action that I have described in this post. There are lot of others and I hope that there would be other helper classes would be added in the later releases of Microsoft helper classes for web. You can read more here on web helpers from the below official Mirosoft resources.

Download: DBMatrix.zip (1.13 mb)

Currently rated 5.0 by 7 people