Facebook & .NET

Date posted: 20/09/2014

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.

Introduction

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.

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.

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.

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.

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 != "")

GetPersonalInfo(access_token);

else

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.

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

reader.Close();

dataStream.Close();

response.Close();

return responseFromServer;

}

So we create a GET request to Facebook and we get as a result something like this

access_token=CAAV6Q......&expires=5126953

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.

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 classPersonalInfo

{

public string id { get; set; }

public string first_name { get; set; }

public string last_name { get; set; }

public string gender { get; set; }

public string link { get; set; }

public string locale { get; set; }

public string name { get; set; }

public int timezone { get; set; }

public DateTime updated_time { get; set; }

public bool verified { get; set; }

}

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.

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.

Summary

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.