Showing posts with label Facebook. Show all posts
Showing posts with label Facebook. Show all posts

Friday 30 September 2011

Getting Started with the Facebook C# SDK

Facebook recently announced the release of the Facebook C# SDK. The SDK allows .NET developers to create Facebook applications by directly calling their API. To get started with the SDK, follow these steps:
  1. Download the source and build the FacebookAPI project.
  2. Create your Facebook application from the Developer Section of your Facebook profile’s Application Settings.
  3. Coding your application to use the FacebookAPI.
In this example, I’ll demonstrate the creation of a simple .NET application that communicates with Facebook to pull my profile and friends list.

Building the FacebookAPI Project

First, download the source of the Facebook API project. Open the solution FacebookAPI.sln in Visual Studio and build the project. You will later use Facebook API assembly to interact with Facebook via .NET.

Creating the Application on Facebook

In order to successfully make calls to Facebook, you have to first register your application with Facebook and obtain authentication keys to be used with OAuth 2.0.
1. Go to http://developers.facebook.com/setup/ to begin registering your application. Make sure you use Internet Explorer. I ran into problems when attempting to register using Firefox (application would register, but a blank page was displayed).
2. Register the application using a site name and URL of the path relative to your authenticating logic. The redirect_url parameter you provide to the Facebook Graph API needs to match the path used to register the application.
create facebook application
In this example, I’ve registered the application as:
    Site Name: Dave Test
    Site URL: http://localhost/Facebook/oauth/
3. Once registered, you can view your application’s configuration settings and authentication keys. These details will be referenced in the example code to make requests to Facebook.
my application overview

Coding the Application

To accomplish the task of pulling my Facebook profile and friends list, I need to do the following:
  • Redirect from my local web application to Facebook with my application id and URL of my redirect handler
  • Construct the redirect URL handler to accept the access token provided by Facebook
  • Instantiate the FacebookAPI object with the access token above
  • Access my Profile via the FacebookAPI
1. Redirecting to Facebook
We need to send Facebook our application id and URL of the handler for Facebook’s redirect, containing our access token.
protected void btnAuthenticate_Click(object sender, EventArgs e)
{
    string clientId = "117342178314989";
    string redirectUrl = "http://localhost/Facebook/oauth/oauth-redirect.aspx";
 
    Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}", clientId, redirectUrl));
}
Notice that the variable clientId matches the field Application Id in my Facebook Application configuration settings and the relative path in the variable redirectUrl matches the path defined in the field Connect URL.
After redirecting, a response is sent back to http://localhost/Facebook/oauth/oauth-redirect.aspx containing a code in the query string parameters of the URL. Successfully making a call, results in the following URL:
http://localhost/Facebook/oauth/oauth-redirect.aspx?code=2.UwNcNB5FfO69d_l5S1j76Q__.3600.1280984400-1427490881%7CGE2JRQaeMDwAZHwZMkk0NUiMQD4.

Notice the parameter code. This value will be used to request an access token from Facebook’s Graph API.
2. Building the Handler for Facebook’s Redirect
In step 1, we’ve created the request to Facebook. In step 2, we need to build the handler to accept the access token provided by Facebook to successfully make API calls.
Currently, there’s nothing built into the API that requests the access token, so I had to build one. The code below calls the Facebook Graph API, requesting an access token.
private Dictionary<string, string> GetOauthTokens(string code)
{
    Dictionary<string, string> tokens = new Dictionary<string, string>();
 
    string clientId = "117342178314989";
    string redirectUrl = "http://localhost/Facebook/oauth/oauth-redirect.aspx";
    string clientSecret = "bc7996cfc4f0c66d0417b54eea73f4e7";
    string scope = "read_friendlists,user_status";
 
    string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}&scope={4}",
                    clientId, redirectUrl, clientSecret, code, scope);
 
    HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
    {
        StreamReader reader = new StreamReader(response.GetResponseStream());
        string retVal = reader.ReadToEnd();
 
        foreach (string token in retVal.Split('&'))
        {
            tokens.Add(token.Substring(0, token.IndexOf("=")),
                token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
        }
    }
 
    return tokens;
}
Variables clientId and clientSecret should match fields Application Id and Application Secret, respectively, in the Facebook Application Settings page.
Scope defines the scope of the request. These values are considered Extended Permissions which means requesting access to data not marked as public to everyone in a user’s Facebook profile.
3. Instantiate FacebookAPI with an Access Token
The method GetOauthTokens accepts a parameter code. We’ll pass in the code value obtained in the query string param of the response in step 1 and cache the response for the time defined by the expiration value in Facebook’s Graph API response.
protected void Page_Load(object sender, EventArgs e)
{
    if (Request.Params["code"] != null)
    {
        Facebook.FacebookAPI api = new Facebook.FacebookAPI(GetAccessToken());
        ...
    }
}
 
private string GetAccessToken()
{
    if (HttpRuntime.Cache["access_token"] == null)
    {
        Dictionary<string, string> args = GetOauthTokens(Request.Params["code"]);
        HttpRuntime.Cache.Insert("access_token", args["access_token"], null, DateTime.Now.AddMinutes(Convert.ToDouble(args["expires"])), TimeSpan.Zero);
    }
 
    return HttpRuntime.Cache["access_token"].ToString();
}
4. Access My Facebook Profile
Now that we have an active connection with Facebook, we can use the API in step 3 to request my profile information. Doing so is as easy as a few lines of code:
JSONObject me = api.Get("/me");
JSONObject meFriends = api.Get("/me/friends");
making Get requests to Facebook via the API returns JSON containing profile information. The first requests my profile while the second obtains my friends list.
Placing a watch on these objects gives us
a watch on me
a watch of variable meFriends As you can see, the variable me contains all of my public profile attributes. The variable meFriends has all 188 of my friends in an array of dictionary items. Each friend is stored in an id/name combo. If we wanted, we could take this another level deeper and get all friends profiles by requesting the id via the Graph API like so (1427490881 is my Facebook id):
JSONObject me = api.Get("/1427490881");

Full Source

/Default.aspx.cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
 
namespace Facebook
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void btnAuthenticate_Click(object sender, EventArgs e)
        {
            string clientId = "117342178314989";
            string redirectUrl = "http://localhost/Facebook/oauth/oauth-redirect.aspx";
 
            Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}", clientId, redirectUrl));
        }
    }
}

/oauth/oauth-redirect.aspx.cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Facebook;
using System.IO;
using System.Net;
using System.Collections.Generic;
 
namespace Facebook
{
    public partial class oauth_redirect : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Params["code"] != null)
            {
                Facebook.FacebookAPI api = new Facebook.FacebookAPI(GetAccessToken());
 
                JSONObject me = api.Get("/me");
                JSONObject meFriends = api.Get("/me/friends");
            }
        }
 
        private string GetAccessToken()
        {
            if (HttpRuntime.Cache["access_token"] == null)
            {
                Dictionary<string, string> args = GetOauthTokens(Request.Params["code"]);
                HttpRuntime.Cache.Insert("access_token", args["access_token"], null, DateTime.Now.AddMinutes(Convert.ToDouble(args["expires"])), TimeSpan.Zero);
            }
 
            return HttpRuntime.Cache["access_token"].ToString();
        }
 
        private Dictionary<string, string> GetOauthTokens(string code)
        {
            Dictionary<string, string> tokens = new Dictionary<string, string>();
 
            string clientId = "117342178314989";
            string redirectUrl = "http://localhost/Facebook/oauth/oauth-redirect.aspx";
            string clientSecret = "bc7996cfc4f0c66d0417b54eea73f4e7";
            string scope = "read_friendlists,user_status";
 
            string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}&scope={4}",
                            clientId, redirectUrl, clientSecret, code, scope);
 
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string retVal = reader.ReadToEnd();
 
                foreach (string token in retVal.Split('&'))
                {
                    tokens.Add(token.Substring(0, token.IndexOf("=")),
                        token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
                }
            }
 
            return tokens;
        }
    }
}

Facebook C# SDK - Writing your first Facebook Application

This is first tutorial on Facebook C# SDK. Over the upcoming days I will be blogging about how to use the Facebook C# SDK to create different types of Facebook Applications whether it is a Windows application, MVC application or even a Silverlight and Windows Phone applications.
We will start up with a simple winforms application which will include the authorization process and making requests to the Facebook server. Along the way I will also be explaining some of the Facebook and OAuth terminologies which I think will come as an added bonus if you are writing Facebook applications. (Even though this is a Windows application I highly recommend you to go through this particular tutorial whether you are developing a Facebook web application, Silverlight application or even Windows Phone application.)
So let’s get started.
Getting the Facebook C# SDK binaries:
You will need to get the latest Facebook C# SDK from http://facebooksdk.codeplex.com/releases or from nuget.
There are 3 NuGet packages for Facebook C# SDK – Facebook, FacebookWeb and FacebookWebMvc. You can see the list of available NuGet packages using the following command in the package manager console.
1
List-Package -Remote -Filter Facebook
I will be using v5.0.1 in this sample. To install the latest Facebook package execute the following command.
PM> Install-Package Facebook
Rather then going through all File>New Project, I will rather explain the core features that I have used in the sample to keep this post small before all you start getting bored. You can download the complete sample at the end of this post.
Summary of the Facebook App:
We will create a simple WinForm C# 4.0 application that contains the login button. When clicked it will ask the user to authorize the application with specified permissions. Once authorized it will display a message box saying “hi …”.
Authentication:
If you haven’t created a Facebook application you will need to do so at http://www.facebook.com/developers/createapp.php. (This Facebook application is also referred to as client in OAuth 2). For windows app you would require only require the application id (also referred to as client id).
Starting from v5 we have migrated all platforms (desktop,web, silverlight and wp7) to use the new Facebook OAuth Dialog.We have also migrated all the aouth related features from FacebookClient (FacebookApp) to FacebookOAuthClient.
Generating the Login Url:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
string appId = "xxx";
string[] extendedPermissions = new[] { "publish_stream", "offline_access" };
var oauth = new FacebookOAuthClient { ClientId = appId };
var parameters = new Dictionary<string, object>
{
{ "response_type", "token" },
{ "display", "popup" }
};
if (extendedPermissions != null && extendedPermissions.Length > 0)
{
var scope = new StringBuilder();
scope.Append(string.Join(",", extendedPermissions));
parameters["scope"] = scope.ToString();
}
var loginUrl = oauth.GetLoginUrl(parameters);
Whether it is a silverlight or windows phone app or desktop app, this is the unified standard way of generating the login url starting from v5. (Though you will require to change certain parameters like dispaly=touch for Windows phone to maximize user experience). By default the redirect_uri is set to http://www.facebook.com/connect/login_success.html which you can also change. For the current windows app the default redirect is more than enough.
Extended permissions are also known as scope in OAuth 2. You can read more about this at available Facebook permissions at http://developers.facebook.com/docs/authentication/permissions/
By default the display is set to page, we overwrite it to popup so that it consumes less space. More information about the display mode can me found at http://developers.facebook.com/docs/reference/dialogs/#display
Response Type is the result given by the Facebook Server on successful authorization. For native windows and windows phone app it is safe to set it as token. But if you are using web applications it is recommend to set it as code because when the Facebook Application redirect after authentication it appends the access_token to the redirect_uri. This means this url along with access token is stored in the browser’s history. (In case you are using a hosted browser control in Windows app, the url is not stored in the browser’s history. So it is safe to use token in desktop apps as compared to websites).
Using the browser user control you would then navigate to the generated login url.
1
webBrowser.Navigate(loginUrl);
Each time the page changes you would need to listen to it and check if the authorization process is completed.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
FacebookOAuthResult result;
if (FacebookOAuthResult.TryParse(e.Url, out result))
{
if (result.IsSuccess)
{
var accesstoken = result.AccessToken;
}
else
{
var errorDescription = result.ErrorDescription;
var errorReason = result.ErrorReason;
}
}
}
To ease the authentication process another helper class called FacebookOAuthResult has been added. TryParse returns true if it is recognized as a valid OAuth2 Authentication result. This means even if there was an OAuth 2 error such as user denied, it would still be able to parse it and return true. Thus there is another property called IsSuccess which is set to true if the oauth result was successful in the sense we have the access token or code. Scenario when the IsSuccess is false can be when the user clicks don’t allow. You can then access ErrorDescription and ErrorReason properties to show useful information to the user. So make sure to check it even if TryParse retruns true.
Making requests to Facebook server:
Now that you have the access token you can use that access token to make the request.
If you are using .net 3.5 (or any other platforms that doesn’t support dynamic keyword) then you can the cast it to IDictionary<string,object> and make a request. (If it is an array you can cast it to IList<object>)
1
2
3
4
5
6
var fb = new FacebookClient("access_token");
var result = (IDictionary<string, object>)fb.Get("/me");
var name = (string)result["name"];
MessageBox.Show("Hi " + name);
If you are using dynamic you could write it as:
1
2
3
4
5
6
var fb = new FacebookClient("access_token");
dynamic result = fb.Get("/me");
var name = result.name;
MessageBox.Show("Hi " + name);
Notice the dynamic keyword in “dynamic result”.
Hope this tutorial helps you get started with the Facebook C# SDK. I will be posting more tutorials in the upcoming days. Make sure to checkout this post on making requests to Facebook server. http://blog.prabir.me/post/Facebook-CSharp-SDK-Making-Requests.aspx
Here is the complete working sample. (make sure you put the appropriate application id before running the sample).

Facebook planning video chat integration with Skype

Seeing how Microsoft has a strong relation with Facebook, owning a good lead of shares and famously integrating its search engine Bing into the social network, a real integration between Skype and Facebook seemed like the logical next step in the social game. As such, Facebook is reportedly about to launch a new video chat product powered by Microsoft-owned Skype.
This comes just recently after Mark Zuckerberg’s comments last week, in which among other things claimed Facebook would have an “awesome” new feature to shout about on 6 July. Yes, it’s Skype video chat.
The alleged application that will link the two services, TechCrunch reports, will serve directly from within the browser. It will apparently also come loaded with a desktop component, all pointing at what TechCrunch describes as “deep integration” between Facebook and Skype.
The move comes hot on the heels of the year’s hottest tech acquisition of Luxembourg-based Skype by Microsoft for $8.5bn in May.This wouldn’t be the first time Skype has played the integration game with Facebook. In October 2010 it inked a deal with the company by slotting its “News Feed” and “Phonebook” features into its software.

Facebook has admitted its cookies could have been used to track people after they had logged out of the social-networking service


Facebook says it has fixed a problem with cookies that could be used to identify users when they visit other websites. Photo credit: Facebook 


On Wednesday, Facebook acknowledged the three cookies contained personally identifiable data, as revealed by Australian researcher Nik Cubrilovic in a blog post earlier in the week.
"Like every site on the internet that personalises content and tries to provide a secure experience for users, we place cookies on the computer of the user," the company said in a statement. "Three of these cookies on some users' computers inadvertently included unique identifiers when the user had logged out of Facebook."
"We fixed the cookies so that they won't include unique information in the future when people log out," it added.
As they stood, the cookies could have been used to identify other websites visited by its users. They gave rise to risks such as hackers gaining control of cookies through malicious cookie-harvesting, or Facebook itself deciding to use the information for commercial purposes.
Cubrilovic raised the issue after finding a number of persistent Facebook cookies that uniquely identified people who visited sites with Facebook 'Like' or 'Share' buttons, or with other Facebook-related widgets. He discovered the cookies by monitoring a Firefox browser session, and warned the company about the issue in November last year, he said.
There was no security or privacy breach—Facebook did not store or use any information it should not have.
– Facebook
"The most important of these [cookies] is a_user, which is the user's ID," Cubrilovic said in a blog post on Monday. While Facebook has not identified which cookies it has fixed, the researcher said the company has taken steps to destroy the a_user cookie on logout.
The 'datr' and 'lu' cookies could also be used to track logged-out Facebook users, Cubrilovic added. The 'datr' cookie tracks attempts to log in and to create multiple accounts (an anti-spammer measure). The 'lu' cookie is used to pre-fill the user's email address in the Facebook login form.
"These cookies, by the very purpose they serve, uniquely identify the browser being used — even after log-out," Cubrilovic said. "As a user, you have to take Facebook at their word that the purpose of these cookies is only for what is being described."
'No privacy breach'
In its statement on Wednesday, Facebook stressed that as it does not store the identifiers, it would not be able to use them for tracking. "There was no security or privacy breach—Facebook did not store or use any information it should not have," it said.

Changes to UK regulations in May mean that businesses must start getting the consent of users before putting tracking programs on their computers. They have until May 2012 to start complying with the new rules on the use of cookies.
The Information Commissioner's Office (ICO), which enforces data-protection regulations in the UK, said on Wednesday it has no immediate plans to look into Facebook's use of cookies.
"We'd need someone to raise it as an issue, or make a complaint," an ICO spokeswoman told ZDNet UK. "It isn't something we've been proactively looking into at this stage."
Instead, the ICO said it may raise the issue at a European level, through discussion in a group of privacy commissioners called the Article 29 Working Party.
"Privacy issues involving websites that are used by people across several countries tend to be raised at European level, as it makes more sense to offer an international view on the use of new practices and technologies," the data watchdog said in a statement.
In addition, the ICO said people should read Facebook's terms and conditions before signing up to make sure they are aware of how their information could be used.