Facebook & .NET

Name: *
My email: *
Recipient email: *
Message: *
Fields marked as bold are compulsory.
You haven't filled in compulsory values. The email is not correct

It's been a few years since social networks have become a part of our life. Since people such as celebrity stars and politicians use them, it is no wonder that developers would choose to do so, in their own way. Let's choose Facebook to interact with. We are going to see how we can use .NET to communicate with Facebook API and use it to do things like getting users info or posting on Facebook.


To interact with Facebook we need to have a Facebook application of our own. You can create your own application (similar to my DotNetHints application) through the Facebook Developers portal. Creating the basics is not hard but in case you find yourself in trouble, doing some online research will be more than enough to help you.
After you have created your application you will notice you are given two IDs. That's the App ID and the App Secret. Note them down as we are going to use them later on in our example. One more interesting thing is the Site URL parameter. You should mark down the URL you are going to use. I have used my local URL since I am going to use my Visual Studio server.
Facebook application set up
That's all we need for now. We have created a functional Facebook application which we will need to communicate with the Facebook API.

Using the Facebook API

Supposing we want to create an example which displays the user's name. Here's what are we going to do.
First thing, we have to redirect to Facebook and ask for the user's permissions. The user will need to log in, in case he is not already (there is no point in getting a person's info if he is not a Facebook member, right?). Then Facebook will ask user if he wants to grant us permission to access his info. The permission message will be different, depending on the info we want to get, and will be asked the first time only. If he accepts, Facebook will response to our website and return a code.
We are then going to use this code to create a web request and in response get an access token, which is different depending on the user and the application and will only work for a short period of time. Once we get hold of this access token we can ask for anything we want, depending on the permission we have requested and the authorization we have been given.
That's pretty much all there is out there. If this is the first time you are dealing with the Facebook API you may be a bit confused right now, so let's do an example to clear things up.

Getting the code

We are going to create a simple example using C# which will do nothing more than getting the user's personal info. 
To do so, we will create a Web Form containing a button which will cause everything to happen when clicked and a literal where we will show our info.
<asp:Button runat="server" ID="btnShowPersonalInfo" Text="Show Personal Info" OnClick="btnShowPersonalInfo_Click" />
<asp:Literal runat="server" ID="PersonalInfo" />
We will check out the Page_Load method later on. Instead we will first see what happens when the button is clicked.
    protected void btnShowPersonalInfo_Click(object sender, EventArgs e)
        //Step 1
        //Button is clicked
        //Redirecting to Facebook and ask the user for authorization
        //Base url
        string facebookAuthorizationURL = authorizationURL;
        facebookAuthorizationURL += "?client_id=" + facebookAppID;
        //Redirection URL
        facebookAuthorizationURL += "&redirect_uri=" + GetRedirectURL();
        //Permission scope
        facebookAuthorizationURL += "&scope=user_about_me";
        Response.Redirect(facebookAuthorizationURL, true);
As we said, first thing to do is to get the code from Facebook. In order to get it, we have to redirect to Facebook. The URL's structure looks like this  
1) authorizationURL is a standard URL where we ask for Facebook authorization
    const string authorizationURL = "https://graph.facebook.com/oauth/authorize";
2) client_id is our ApplicationID
    const string facebookAppID = "1541805559......";
3)redirect_uri is the URI we want Facebook to return the user. This most probably will be the same page where we are right now. In our case we use a simple GetRedirectURL method to remove possible code appearance, which will happen when we finally get our code.
    private string GetRedirectURL()
        //Step 1.5
        //URL handling
        //This code is nothing more than a simplistic example of how to remove appearance of "code" in the query string 
        string redirectUri = Request.Url.AbsoluteUri;
        if (redirectUri.Contains("?code="))
            redirectUri = redirectUri.Remove(redirectUri.IndexOf("?code="));
        return redirectUri;
4)scope represents what kind of data we ask permission from the user. In our case the scope is "user_about_me". Other scopes include "publish_stream", "share_item" etc. In our case "user_about_me" will give as the personal info we want.
So we redirect to Facebook. What goes next? We said that if the user is not logged, he will need to do so.
Facebook login
After that, he will be asked to give us permission to get his data. At the moment, we are given permissions and Facebook knows about it, so we are not asked a second time. However if next time our application requires different permission scopes the user will need to confirm that permission as well. When permission is given, Facebook will redirect back to our website (redirect_uri) and the query string will contain some extra value, the code.
Facebook user grant permission
We can now get our code using 
string code = Request["code"];

Getting the access token

So far we got ourselves a code. Let's see what we can do with it. We are now getting a new request, this time the one Facebook has created for us. Now, it's time to see our Page_Load method.
    protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
            //Step 2
            //Getting the access token and our info
            if (Request["code"] != null)
                //We enter this part only when we are redirected from Facebook
                //In that case we have the user's code
                string code = Request["code"];
                //Now we need the access token
                string access_token = GetAccessToken(code);
                if (access_token != "")
                    PersonalInfo.Text = "Sorry, no access_token available.";
As we see in the Page_Load code, we are going to use a new method called GetAccessToken which does exactly what its name describes. The access token is what we need to access our user's info or post our own info to Facebook. Here's how we get it.
private string GetAccessToken(string code)
        //Step 3
        //Get the access token
        //Base URL
        string urlGetAccessToken = getTokenURL;
        //Facebook Application ID
        urlGetAccessToken += "?client_id=" + facebookAppID;
        //Facebook Application secret ID
        urlGetAccessToken += "&client_secret=" + facebookAppSecret;
        //Redirection URL
        urlGetAccessToken += "&redirect_uri=" + GetRedirectURL();
        //The code we got a moment ago
        urlGetAccessToken += "&code=" + code;
        string responseData = GetWebPageString(urlGetAccessToken);
        if (responseData != "")
            //Use System.Collections.Specialized;
            NameValueCollection col = HttpUtility.ParseQueryString(responseData);
            string access_token = col["access_token"] == null ? "" : col["access_token"];
            return access_token;
            return "";
All we have to do is create a GET request to Facebook. The request's URL should look like
1)getTokenURL is a standard URL where we ask for Facebook tokens
const string getTokenURL = "https://graph.facebook.com/oauth/access_token";
2)client_id is our ApplicationID
    const string facebookAppID = "1541805559......";
3)client_secret is our App Secret
   const string facebookAppSecret = "0ab63a35ffdd220df...............";
4)redirect_uri is the URI we want Facebook to return the user the same way we did previously. We are using the GetRedirectURL method once again.
5)code is the code we got from Facebook in the previous step.
To create the request we will use the GetWebPageString method introduced in a previous blog post
 private string GetWebPageString(string targetURL)
        //Step 3.5
        //Create a GET request to facebook 
        //Create a request to the referenced URL
        WebRequest request = WebRequest.Create(targetURL);
        //Get the response
        WebResponse response = request.GetResponse();
        //Create a Stream and StreamReader containing info from the server
        Stream dataStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(dataStream);
        //Get the info
        string responseFromServer = reader.ReadToEnd();
        //Release resources
        return responseFromServer;
So we create a GET request to Facebook and we get as a result something like this
which we will treat as a query string  to get the access token through a NameValueCollection.
Congratulations. You are now in possession of the access token. 

Go for it

We finally have the access token. From now on the code may depend on what we want to do. In our case, get the user's personal info. Back to the Page_Load you will notice that after we get the access token, we use the GetPersonalInfo method. Here's the method.
    private void GetPersonalInfo(string accessToken)
        //Step 4
        //Create a GET request to Facebook in order to get personal info
        //When data is returned we store it into a PersonalInfo object
        string personalInfoURL = "https://graph.facebook.com/me?access_token=" + accessToken;
        string jsonPersonalInfo = GetWebPageString(personalInfoURL);
        if (jsonPersonalInfo == "")
            PersonalInfo.Text = "Problem while requesting personal info.";
            //Use System.Web.Script.Serialization;
            PersonalInfo info = new JavaScriptSerializer().Deserialize<PersonalInfo>(jsonPersonalInfo);
            PersonalInfo.Text  = ShowPersonalInfo(info);
The personalInfoURL is quite important as it represents the type of data we want to get from Facebook. Actually the part of interest is the "me/". Using "me/friends/" instead, for example, would ask for the user's friends list. In the personalInfoURL we also have to add our access token.
Using it, we create one last GET request and then get JSON data in response.
The data in the case of personal info can be deserialized in a PersonalInfo class we create. 
public class PersonalInfo
    public string id { get; set; }
    public string first_name { getset; }
    public string last_name { getset; }
    public string gender { getset; }
    public string link { getset; }
    public string locale { getset; }
    public string name { getset; }
    public int timezone { getset; }
    public DateTime updated_time { getset; }
    public bool verified { getset; }
After desrializing, we have a PersonalInfo object. ShowPersonalInfo will handle that object and use reflection and a StringBuilder to create an HTML table showing the info we got.
 private string ShowPersonalInfo(object info)
        //Step 5 
        //Creating an HTML table to show data using reflection
        StringBuilder infoText = new StringBuilder("<table>");
        //Use System.Reflection;
        Type type = info.GetType();
        PropertyInfo[] properties = type.GetProperties();
        foreach (PropertyInfo property in properties)
            infoText.Append("<tr><td>" + property.Name + "</td><td>" + property.GetValue(info, null) + "</td></tr>");
        return infoText.ToString();
Finally, back to the GetPersonalInfo we show the return string using our literal.
PersonalInfo.Text  = ShowPersonalInfo(info);
That's all. You should now be able to see a picture like the one following.
Personal Info

What to do next

Facebook API offers much data to get depending on your permission scope and reference URLs. 
For example, using "email" in your permission scope and https://graph.facebook.com/me/ you can get JSON data similar to the ones we got earlier yet including user's email as well. 
In that case if we created a new class PersonalInfoAndEmail that inherits our PersonalInfo class but also contains the email attribute
public class PersonalInfoAndEmail : PersonalInfo
    public string email { get; set; }
and deserialize to a PersonalInfoAndEmail object, we would get the following results.
email personal info
Using "user_friends" in your permission scope and https://graph.facebook.com/me/friends you can get JSON data of the user's friends. 
In my case I get 
Using "publish_stream" permissions and creating a POST request (instead of the GET we created earlier) to https://graph.facebook.com/me/feed you can post on the user's wall.
You may read more concerning permissions here and reference URLs here
One last thing of importance has to do with Facebook permission policy. According to Facebook, "Apps requesting more than public_profile, email and the user_friends permission must be reviewed by Facebook before those permissions can be requested from people. Active apps created before April 30th, 2014 have one year before they are required to go through login review, including updates to existing apps. Facebook apps created after April 30th, 2014 must go through review."
So if you want to create an application in order to post in your users' walls, you have to get through Facebook control first. To do so you will need to select your type of extra requests and then upload photos and write a few paragraphs so the Facebook team will have clear understanding of how you are going to use the permissions you ask and then decide if you do need them or not.


Since Facebook is one of the most popular social networks it would be nice if we could use it to enhance our applications. First we need to create a Facebook application. Then we will use this application to get access to the users' info, first by getting a code, then the access token and finally our data. That is, of course, if the user allows us to do so. We can get most of the user's info, depending on the permission level Facebook has granted us.


Back to BlogPreviousNext


    Leave a comment