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

Integrate Bing Maps With Geonames Database And ASP.NET

8. February 2011 03:11

API ASP.NET Microsoft Utils 

After Microsoft launched Bing Maps, there are few things which lead me not to use Google Maps:

  • Bing Maps are more accurate than Google Maps.
  • Bing Maps looks more pretty than Google Maps.
  • And the main reason I am using Bing Maps is because I am a Microsoft fan Cool

To locate a place on maps (Bing or Google), the best thing is to get the latitude and longitude of the location, this ensures that the place we are pinning on the map is accurate. But the big question is to where to get the latitude and longitude of the location. There might be a web service for getting the latitude and longitude of a location, but wouldn't it be nice if you just have to query a local database?

Get the Geonames data dump

Apart from providing free web services and API Geonames.org also provides their data dumps which gets updated regularly. the best things about the data dumps are that they are distributed country-wise, city-wise etc. If you wish to download the data country wise, then you can download the file(s) which are named according to the countries IATA codes. The one I am using for this example is the allCountries files from the dumps. Download this dump only if you want to have ALL the Geoname data.

 

Import data in SQL Server

The dump can be imported in the database using the Data import-Export wizard present in the SQL Server or you can write a custom tool to import the whole dump. The dump is in a TAB delimited format. Just in case if you are not aware, the file you downloaded is in UTF-8 encoding and therefore you need it to convert it to UTF-16 encoding before you actually import it into the database. There is a command line tool which will help you to convert the database dump to UTF-16 which I got from the Geoname forums.

 

This tool will convert the format of the dump file from UTF-8 to UTF-16. After the successfull conversion of the file, now comes the time to import the data in the database.

Create a database table:

CREATE TABLE GeoNames( 
geonameid int NOT NULL, 
name nvarchar(200) NULL, 
asciiname nvarchar(200) NULL, 
alternatenames nvarchar(max) NULL, 
latitude float NULL, 
longitude float NULL, 
feature_class char(2) NULL, 
feature_code nvarchar(10) NULL, 
country_code char(3) NULL, 
cc2 char(60) NULL, 
admin1_code nvarchar(20) NULL, 
admin2_code nvarchar(80) NULL, 
admin3_code nvarchar(20) NULL, 
admin4_code nvarchar(20) NULL, 
population bigint NULL, 
elevation int NULL, 
gtopo30 int NULL, 
timezone char(31) NULL, 
modification_date date NULL 
)

To import millions of records you can write a custom tool or you can use the SQL Server Data Import/Export Data wizard. I have wrote a custom tool to import, but you can use the T-SQL's BULK INSERT (because it is simple and easy) to import the dump.

BULK 
INSERT GeoNames 
FROM 'I:\Database\Dump.txt' 
WITH( 
DATAFILETYPE = 'widechar', 
FIELDTERMINATOR = '\t', 
ROWTERMINATOR = '\n' 
)

The parameters in the above SQL statement is self-explanatory and therefore I am not going to brief them. But before you can start locating places with ASP.NET make sure you have indexed the table, if not then you will receive a SQL Server timed-out error.

Working with Bing Maps

Our database is now ready and now we can start locating the places on the Bing maps. We have two pages in the project, one which we will be using to get the locations and their details on the basis of city name enter by the user and the other which will show the map with a push pin.

Default.aspx page:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="BingMap._Default" EnableViewState="true" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title>Bing Maps with ASP.NET and GeoNames Database</title>
    <link href="Style/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server" enableviewstate="true">
    Enter Place Name:  <asp:TextBox ID="txtPlaceName" runat="server" />
    <asp:Button ID="btnPlaceName" runat="server" Text="Get GeoData!" OnClick="btnPlaceName_Click" />
     <br />
    <br />
        <table id="GeoData" style="width: 55%;" enableviewstate="true">
            <tr>
                <td class="tdheader">
                      City Name
                </td>
                <td class="tdheader">
                      Lat./Log.
                </td>
                <td class="tdheader">
                     Country
                </td>
                <td>
                </td>
            </tr>
            <%for (int i = 0; i < RecCount; i++)
              {%>
            <tr>
                <td>
                     
                    <%=CityName[i]%>
                </td>
                <td>
                     
                    <%=Lat[i]%>
                    /
                    <%=Log[i]%>
                </td>
                <td class="country">
                     
                    <%=Country[i]%>
                </td>
                <td>
                    <a href="BingMap.aspx?lat=<%=Lat[i]%>&log=<%=Log[i]%>&place=<%=CityName[i]%>" target="_blank">Show on Map</a>
                </td>
            </tr>
            <%}%>
        </table>
    <br />
   <asp:Label ID="RecFound" Text="" runat="server" />
    </form>
</body>
</html>

The above page will get and show the details of the place. Click the Show on Map link to view the map.

 

Code Behind: Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BingMap.DBModel;


namespace BingMap
{
    public partial class _Default : System.Web.UI.Page
    {
        WorldEntities world = new WorldEntities();
        public List<string> CityName = new List<string>();
        public List<string> Country = new List<string>();
        public List<string> Lat = new List<string>();
        public List<string> Log = new List<string>();
        public int RecCount = 0;

        private void GetLocation(string CName)
        {
            try
            {
                var WorldLoc = from l in world.Geonames
                               where l.name == CName
                               select l;

                foreach (var item in WorldLoc)
                {
                    CityName.Add(item.name);
                    Country.Add(item.country_code);
                    Lat.Add(Convert.ToSingle(item.latitude));
                    Log.Add(Convert.ToSingle(item.longitude));
                    RecCount = RecCount + 1;
                }

                if (RecCount == 0)
                {
                    RecFound.Text = "No Record(s) Found!";
                }

                else
                {
                    RecFound.Text = Convert.ToString(RecCount) + " Record(s) Found!";
                }
            }
            catch (Exception x)
            {
                Response.Write(x.ToString());
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnPlaceName_Click(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
            {
                GetLocation(txtPlaceName.Text);
            }
        }
    }
}

There could be many places with the same name in different geographical locations. For example, if you query the database with San Francisco, you'll find out it is not the only place on the planet in U.S. The same is with the city in India called Hyderabad, one is in India and the other is in Pakistan. But the geographical location is different and thus we can place a push pin on the maps.

I have used a different web page for the map. From the page Default.aspx page I will pass the information (latitude, longitude and place name) in query string to pin the location on the map.

BingMap.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="BingMap.aspx.cs" Inherits="BingMap.BingMap" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Bing Map</title>
    <script type="text/javascript" src="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.3"></script>

    <script type="text/javascript">
        function LoadMap() {
            map = new VEMap('BingMap');
            var Latitude = '<%= LocLat %>';
            var Longitude = '<%= LocLog%>';
            var PlaceName = '<%=Place %>';
            if (Latitude.length == 0 || Longitude.length == 0) {
                var latlong = new VELatLong(28.63576, 77.22445);

                map.SetDashboardSize(VEDashboardSize.Large);
                map.LoadMap(latlong, 9, VEMapStyle.Road);

                //Add pushpin
                var pin = new VEShape(VEShapeType.Pushpin, latlong);
                pin.SetCustomIcon(null);
                pin.SetTitle("New Delhi");
                pin.SetDescription("Capital City Of India");
                map.AddShape(pin);
                map.ShowDashboard();
            }
            else {
                var latlong = new VELatLong(Latitude, Longitude);

                map.SetDashboardSize(VEDashboardSize.Large);
                map.LoadMap(latlong, 9, VEMapStyle.Road);

                //Add pushpin
                var pin = new VEShape(VEShapeType.Pushpin, latlong);
                pin.SetCustomIcon(null);
                pin.SetTitle(PlaceName);
                pin.SetDescription("<br/>" + "<strong>Latitude:</strong>" + '<%=LocLat%>' + "<br/>" + "<strong>Longitude:</strong>" + '<%=LocLog%>');
                map.AddShape(pin);
                map.ShowDashboard();
            }
        }
    </script>

</head>
<body onload="LoadMap();">
    <form id="BingForm" runat="server">
    <div id='BingMap' style="position: relative; width: 800px; height: 600px;">
    
    </div>
    </form>
</body>
</html>

The client-side script is used to load the map. I have used the version 6.3 of the Bing Maps but you can also use the version 7.0. Though you need some additional parameters to use the latest one like the Bing Maps developer API key. The map can be set in the script tag.

<script type="text/javascript" src="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.3"></script>

A funtion named LoadMap() will doing the rest of the job, like setting the latitude, longitude, adding push pin to the location on the map and customizing other details on the map.

var latlong = new VELatLong(28.63576, 77.22445);
map.SetDashboardSize(VEDashboardSize.Large);
map.LoadMap(latlong, 9, VEMapStyle.Road);

The first line in the above script will set the latitude and longitude. The LoadMap method should always be called after SetDashboardSize. I have set the VEDashboardSize enumeration to Large you can also use Small if you want the navigation controls of the map to appear small. LoadMap method will take 3 parameters, the first is the reference of the latitude and longitude of the location, second is the Zoom Level, which is 9 in my case, you can adjust this value according to your requirement and the third option VEMapStyle enumeration will let you set the style for the map. It can be Road, Aerial, BirdEye etc (Click on the links to know more about these enumerations). And this is it, this will load the map in the browser showing the place of your choice with specified latitude and longitude.

To be more precise an beautify the Bing Map, we can also add a push pin at the specified location and that too can also be done with the help of the client-side script.

var pin = new VEShape(VEShapeType.Pushpin, latlong);
pin.SetCustomIcon(null);
pin.SetTitle(PlaceName);
pin.SetDescription("<br/>" + "<strong>Latitude:</strong>" + '<%=LocLat%>' + "<br/>" + "<strong>Longitude:</strong>" + '<%=LocLog%>');
map.AddShape(pin);

To add a new push pin to our location we need to use VEShape class. SetCustomIcon method allows to set the custom icon for your push pin. SetTitle method will set the description for you push pin. SetDescription method sets the description of the push pin, here in the description I have set the other information like location's latitide and longitude. To add the push pin to the location the AddShape method of the map class will take pin as a parameter and set the push pin on the map.

For showing map I have used a different web page named BingMap.aspx which also includes the code behind (just a few lines) apart from client-side code:

BingMap.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BingMap
{
    public partial class BingMap : System.Web.UI.Page
    {
        public string LocLat = "";
        public string LocLog = "";
        public string Place = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString.AllKeys.Length > 0)
            {
                LocLat = Request.QueryString["lat"].ToString();
                LocLog = Request.QueryString["log"].ToString();
                Place = Request.QueryString["place"].ToString();
            }

            if (LocLat.Equals("") || LocLog.Equals(""))
            {

            }
        }
    }
}

In the code-behind I will check on page load if the count of the query string passed on to the page is greater than zero, if the condition is true then I will set the values in the public variables and set them on the client-side script which actually handles the loading, locating and adding push pin on the map. The URL on calling the BingMap.aspx page will look like this:

http://localhost:5543/BingMap.aspx?lat=28.35&log=79.41667&place=Bareilly

I have shown my home town on the map. You can also see a push pin and other details in a baloon.

 

And this is it, I can now locate any place on the Bing Maps which is present with me in Geonames database with the help of ASP.NET. The more can be done with the help of Geonames database like postcode lookup. I hope this tutorial will get you started with Bing Maps integrated with Geonames database with the help of ASP.NET.

Download: BingMap.zip (189.44 kb)

Download the UTF8ToUTF16 conversion tool

Related Links:

Currently rated 3.5 by 4 people

Reverse Those Short URLs

2. February 2011 02:58

ASP.NET Utils 

Bit.ly is one of the major short URL service provider. There are other also but Bit.ly is used by most of the users because of it's simplicity, API and statistics. But some notorious users create short URLs for the spam sites which doesn't make any sense to us. As you know by looking at the short URLs, they won't reveal anything. But there is a way to get the original/long URL through ASP.NET.

Below is the method which takes short URL as a parameter.

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

The Response.Uri will get the actual URL which is being requested.

 

Demo: http://demo.midnightprogrammer.net/ASPNET/ReverseURL/Default.aspx

Download: ReverseShortURL.zip (335.87 kb)

 No Rating