Facebook Application

viraginitysplashInternet and Web Development

Nov 10, 2013 (3 years and 7 months ago)

99 views

Facebook
Application

Ranjan Kumar Singh

Talentica Software Pvt. Ltd.

Agenda


The Opportunity


Why is the Internet increasingly obsessed with Facebook?


The Facebook Platform


Introduction to Facebook and the Facebook Platform


The Framework


Core components


Tools


The Anatomy of a Facebook App


How are Facebook Applications built?


Application Architecture


Integration points


Demo


Creating a Platform Application step by step

Facebook Chases Google and Yahoo. Twitter Left
Behind


Facebook : General Growth


More than 350 million active users


50% of the active users log on to Facebook in
any given day


More than 3.5 billion pieces of content (web links,
news stories, blog posts, notes, photo albums,
etc.) shared each week


More than 1.6 million active Pages on Facebook


More than 700,000 local businesses have active
Pages on Facebook


Pages have created more than 5.3 billion fans

Facebook : User Engagement


"We're not trying to help you make new friends online. We're just trying to help you
digitally map out the relationships you already have."
-

Zuckerberg



Average user has 130 friends on the site


Average user sends 8 friend requests per month


Average user spends more than 55 minutes per day on
Facebook


Average user clicks the Like button on 9 pieces of
content each month


Average user writes 25 comments on Facebook content
each month


Average user becomes a fan of 2 Pages each month


Average user is invited to 3 events per month


Average user is a member of 12 groups

Discovering Facebook


Canvas


Publisher


Request, Invitation, Notification


News Feed


Comment, Like, Share


Profile


Profile Box


Info Tab


Application Tab


Application Menu


Application Directory


Application Profile Page


Business/Fan Page


www.facebook.com

Discovering Facebook : News Feed


Your own personalized news channel


something like a FNN
(Friends News Network), Contains a live list of announcements or
stories about


profile changes, upcoming events, birthdays, changes in relationship status, and
conversations with other users


activity of your network of friends on Facebook


whom they befriended, what apps they added, what their Status is.


Facebook compiles this list of news stories based on several
factors
-

all mixed together into a behind
-
the
-
scenes, super
-
secret
algorithm.


who posted the content, and what type of content it is


your preferences of story types,


frequency settings on specific friends,


the privacy levels of your friends,


a user’s opinion on the quality of a story


how many friends are commenting on a certain piece of content,


Facebook ultimately retains control over what is placed on
the News Feed.


Discovering Facebook : Facebook Pages


A Facebook Page is a customizable presence for an
organization, product, or public personality to join the
conversation with Facebook users.


Looks and behaves like user profiles, anybody can visit


By leveraging the real connections between friends on
Facebook, a Page lets Fans become brand advocates.


Posts by the Page appear in News Feed, giving Pages a
stronger voice to reach their Fans.


Pages have the flexibility of multiple customizable tabs
previously exclusive to user profiles.


There are thousands of Facebook Platform applications built
by 3rd party developers available for use on Page.


Example



http://www.facebook.com/nytimes


http://www.facebook.com/pages/Ranjan/132466815687


Social Sites: While Everyone Falls, Facebook Rises


Discovering the Pulse of Facebook:

The Social Graph


The social graph can be defined as the
interconnections that exist among family,
friends, and acquaintances that every person
has.



Facebook's stated mission is to model the social
graph in digital form as accurately and
completely as possible.



The social graph enables social distribution



The net effect of the social graph is that groups
and application can achieve exponential growth

Introducing the Facebook Platform


People are already building social apps, but
they have to reconstruct the social graph all by
themselves.


Facebook launched Facebook Applications
Platform in May 2007


The Facebook platform exposes the social
graph to everybody with an idea, enabling rapid
social distribution of new application.


The Facebook platform is optimized for building
applications in Facebook, and with more value
for people to develop on its base.



The Opportunity


Earn money with Facebook applications.



A lot of people in the past few years have earned a lot through Facebook
applications by just using some simple strategies.


Develop a viral application and make it popular amongst Facebook users.


Virality is inbuilt into the system, you just need to harness it.


Cheap and exponential growth


Once your application attracts a crowd you will be able to either display ads on it
or simply sell it to big names who are looking for buying applications that are
popular.


Wealth of Data


Relationship Status


Education & Employment Data


Geographic Data


Interests & Affinities


Not their contact information though!

Top Applications

Name

Developer

MAU

Daily
Growth Rate

1.

FarmVille

Zynga

72,015,037

0.00

2.

Café World

Zynga

32,058,162

0.00

3.

Causes

Causes

30,889,550

0.00

4.

Happy Aquarium (BETA)

CrowdStar

27,431,252

0.00

5.

Mafia Wars

Zynga

27,036,835

0.00

6.

FishVille

Zynga

25,983,286

0.00

7.

Birthday Cards

RockYou!

22,927,753

0.00

8.

Pet Society

Playfish

21,404,273

0.00

9.

Texas HoldEm Poker

Zynga

20,071,134

0.26

10.

Facebook for iPhone

Facebook

19,289,530

0.48

Facebook Platform :
Statistics


More than one million developers and entrepreneurs from
more than 180 countries


Every month, more than 70% of Facebook users engage
with Platform applications


More than 350,000 active applications currently on
Facebook Platform


More than 250 applications have more than one million
monthly active users


More than 80,000 websites have implemented Facebook
Connect since its general availability in December 2008


More than 60 million Facebook users engage with Facebook
Connect on external websites every month


Two
-
thirds of comScore’s U.S. Top 100 websites and half of
comScore’s Global Top 100 websites have implemented
Facebook Connect

Platform Core Components


The server API (REST)


Methods that let you add social context to your
applications.


FBML, Facebook Markup Language


Allows you to integrate your application into
Facebook.


FQL, Facebook Query Language


Query for Facebook user data with a
SQL
-
style
interface

without using the API


FBJS, Facebook JavaScript


developers who want to use JavaScript in their
Facebook applications.

RESTful API


With the API, you can add social context to
your application by utilizing profile, friend,
Page, group, photo, and event data.


The Facebook API is a REST (Representational
State Transfer)
-
based interface.


Method calls are made over the internet by sending
HTTP GET or POST requests to the Facebook API REST
server.


Nearly any computer language can be used to
communicate over HTTP with the REST server.


When you call a Facebook API method, your results
normally come back in either XML (the default) or JSON
format.


http://developers.facebook.com/tools.php


Facebook API client libraries



You can develop your Facebook application in whichever
development environment you prefer. Facebook and other
third party application developers have created client
libraries for these environments.


Facebook provides official support for


PHP5, JavaScript, Facebook Connect for iPhone,


ActionScript 3.0 (officially supported with Adobe),


Microsoft SDK for Facebook Platform (officially supported
with Microsoft)


The Facebook Platform developer community maintains the
following client libraries :


Android, ColdFusion, C++, C#, Google Web Toolkit,
Java, Perl, Python, Ruby, Ruby on Rails, Smalltalk,
VB.NET, Windows Mobile/Facebook Development with
the .NET Compact Framework


http://wiki.developers.facebook.com/index.php/User:Client_Libraries

API Methods


Administrative Methods


admin.getAppProperties


admin.getMetrics


Login/Auth Methods


auth.getSession


Data Retrieval Methods


fql.query


friends.get


friends.getAppUsers


users.getInfo


users.getLoggedInUser


Publishing Methods


stream.publish


comments.add


http://wiki.developers.facebook.com/index.php/API


http://developers.facebook.com/tools.php


FBML, Facebook Markup
Language


FBML is an evolved subset of HTML with some elements
removed, and others which have been added that are
specific to Facebook.


ability to easily place social tags within HTML.


awareness of who is viewing the page.


If the logged in user is blocked from viewing the particular
info, nothing renders at all.


Facebook server processes FBML and displays the output in
HTML for rendering in a browser.


On the whole, most HTML tags in the Facebook
environment will render the same as normal HTML


Facebook parses a few HTML tags differently than your normal
HTML.


The form tag renders a form in HTML, adding five additional
hidden input fields

the fb_sig_profile, fb_sig_user,
fb_sig_session_key, fb_sig_time, and fb_sig

FBML : Social Data Tags


Social data is the core of FBML and the primary attraction to developers.


<fb:name uid="1160" capitalize="true" />


<fb:profile
-
pic uid="12345" linked="true" />


<fb:eventlink eid="21150032416" />


<fb:grouplink gid="2541896821" />


<fb:user
-
table cols="3"><fb:user
-
item uid="12345" />
</fb:user
-
table>


<fb:user
-
status uid="12345" linked="true"/>



Visibility on Profile


fb:visible
-
to
-
owner


fb:visible
-
to
-
friends


fb:visible
-
to
-
app
-
users


fb:18
-
plus


fb:21
-
plus



http://developers.facebook.com/tools.php


FBML : Design and Component tags

Social Widgets and
Tools


fb:board


fb:comments


fb:feed


fb:friend
-
selector


fb:multi
-
friend
-
input


fb:live
-
stream


fb:wall


fb:wallpost


fb:wallpost
-
action

Page Navigation


fb:dashboard


fb:action


fb:help


fb:mediaheader


fb:header
-
title


fb:owner
-
action


fb:tabs


fb:tab
-
item

Embedded Media


fb:iframe


fb:photo


fb:mp3


fb:silverlight

Notifications and Requests


fb:req
-
choice


fb:request
-
form


fb:multi
-
friend
-
selector


fb:multi
-
friend
-
selector (condensed)


fb:request
-
form
-
submit


fb:prompt
-
permission

http://wiki.developers.facebook.com/index.php/FBML

http://developers.facebook.com/tools.php

FQL, Facebook Query
Language


fql.query : returns results in XML or JSON format


Many of the Facebook API calls are just pre
-
packaged FQL queries


Key Advantage


Condensed XML
reduces bandwidth and parsing costs
.


More complex requests can
reduce the number of requests
necessary
.


Provides a single
consistent
,
unified interface

for all of your data
.


Facebook manages the database connections for
you, you do not need to open and close database
connections as part of your application.

FQL : Syntax


If you already know SQL, it should be pretty straightforward.


SELECT [fields] FROM [table] WHERE [conditions]


You can also optionally add on ORDER BY and LIMIT clauses that work like
they do in MySQL


Get pids in range (1,42) from $user_id's albums, sorted by created date:



SELECT pid FROM photo



WHERE aid IN ( SELECT aid FROM album WHERE owner=''$user_id'' )



ORDER BY created DESC LIMIT 1,42


FQL introduces a way of dealing with columns which are themselves
structures or arrays


"current_location" column of the user table is a
location

structure
consisting city, state, zip and country.


You can reference the structures as a whole (SELECT current_location ) or
you can filter them down to only a single field within the structure using
dots (SELECT current_location.zip)


Developer tool
http://developers.facebook.com/tools.php

FQL : Tables


album


application


comment


event


event_member


family


friend


friend_request


group


group_member


link


link_stat


mailbox_folder


message


metrics


note


notification


page


page_admin


page_fan


permissions


photo


photo_tag


profile


standard_friend_info


standard_user_info


status


stream


stream_filter


user

FQL != SQL


SELECT * is not allowed. You need to specify all
the fields by name in which you want to include
in the result set.


The FROM clause can only include a single table.


At least one field in the WHERE clause must be
classified as indexable.


JOIN is not supported (though
IN

subqueries
are).


The GROUPBY and COUNT keywords are not
supported.


The BETWEEN and LIKE operators are not
supported.


Because you have read
-
only access, you
obviously cannot use keywords like UPDATE,
DELETE, INSERT INTO, or CREATE TABLE.

FBJS, Facebook JavaScript


Facebook expose certain scripting functionality through a
collection of JavaScript objects that allow you to modify
your content on Facebook.


FBJS objects are made to mimic the functionality of
JavaScript as closely as possible, but it may take some
getting used to for people who are already adept with
JavaScript.


The JavaScript syntax you've come to know and love (or
hate) is exactly the same. You can create objects, use
anonymous functions, create timeouts and almost any
other thing you can think of. Modifying the DOM tree is
slightly different, however.


Facebook pre
-
processes the script by parsing through the
code and prepending your application ID to the names of
your functions and variables.


This creates a virtual scope for every application that runs
within Facebook.

FBJS : The Basics


Placing your FBJS



<script> <!
--

//
--
> </script>


<script src="http://foo.com/bar.js"></script>



FBJS DOM Objects


A handle to an FBJS DOM object can be retrieved by either
calling
document.getElementById
, or

document.createElement
.


FBJS DOM objects implement most of the same methods
regular JavaScript objects implement including: appendChild,
insertBefore, removeChild, and cloneNode.


Properties like parentNode, nextSibling, src, href (and many
many others) have been redefined as a couplet of getters and
setters.

FBJS: Setting Style and Content


Manipulating Styles



obj.setStyle({color: 'black', background: 'white'});


You need to transform hyphenated style property names into lower
camel case


obj.setStyle(‘marginRight', ’10px')


FBJS allows you to programmatically work with class styles that you
have already defined in your code. :


addClassName(className), removeClassName(className)



toggleClassName(className),

hasClassName(className)



Setting Content



innerHTML isn't implemented for security reasons. Three alternatives
exist.


obj.setTextValue(newText)

can be used to set a literal text value
inside of your DOM object (no HTML or FBML accepted).


obj.setInnerFBML(fbJsStringVar)

can be used to put HTML or
FBML inside of your DOM object. Note that you need to create a Fb:js
-
string object first and pass it in as passing a string literal will result in
an error.

<fb:js
-
string var="welcomeMsg">


<div>Welcome to Poolster</div>

</fb:js
-
string>




obj.setInnerXHTML(string)

is a beta feature that allows you to
place a string of XHTML directly into the document. The XHTML is
sanitized in JavaScript before being rendered.

FBJS : Using AJAX and Dialog


FBJS supplies a very powerful AJAX object for developers.


Facebook proxies all AJAX requests and optionally runs useful
post
-
processing on the data returned, such as JSON, or FBML
parsing.




var ajax = new Ajax();


ajax.responseType = Ajax.JSON;


ajax.ondone = function(data) { }


ajax.onerror = function() { }


ajax.requireLogin = 1;



var load = { "UserName": ‘
Ranjan
', "Category":
’2’
};


ajax.post(
‘http://www.poolster.com/handler.aspx’
, load);


Dialogs


showMessage(title, content, button_confirm = 'Okay')




showChoice(title, content, button_confirm = 'Okay', button_cancel =
'Cancel')




var d = new Dialog();


d.oncancel = function() { }


d.onconfirm = function() {

}


d.showChoice("Poolster", "Are you sure you want to
quit

?", 'Yes', 'No');

Facebook App Types


Desktop App


Web App


FBML


Facebook User


Fan Page


Both


IFrame


Facebook Connect App


Mobile App

Facebook Connect


Facebook Connect lets users bring their identity and connections
everywhere. Developers can access a user's:


Identity:

name, photos, events, and more.


Social Graph:

friends and connections.


Stream:

activity, distribution, and integration points within Facebook, like
stream stories and Publishers.



Create more engaging experiences on your website.


Traffic


Enable over 300 million Facebook users to share your content with their friends on
Facebook. Let users publish a story, invite their friends, or send an event. Their friends
then click back to your site.


Engagement


Users can immediately find their friends and engage. More friends leads to more activity
and more pageviews. Connected users create 15
-
60% more content than users who
have not connected with Facebook Connect.


Registration


Allow login using Facebook connect


Personalization


Present relevant and targeted information based on a user's profile information.


Social Context


Highlight friend content and across site. Filter information by friends or people
-
in
-
your
network's usage and recommendations.


Social Experiences


Create new experiences and lightweight actions that allow users to interact with each
other and their friends (for example, like, publishing stories, gifting).


http://www.joost.com/


http://www.facebook.com/connectnews?v=app_7146470109

Facebook Connect : Features

Goal

Feature

Suggestion

Time
Invest.

Results*

Traffic

Share

Add Facebook Share
button to any piece
of content.

< 1 hour



2
-
4% users share


3
-
10 clicks/share

Traffic

Facebook
Page/Fan Box

Create Facebook
Pages and post, use
Fan Box on site to
drive fans.

1
-
2 hours



5
-
10% fans click through per post

Engagement

Live
Conversation

Add Live Stream
Box next to every
live video stream.

1
-
2 hours



+15
-
20% time on site for users who
engage


+5
-
15% traffic

Engagement

Social
Comments

Add social
comments to every
piece of content.

1
-
2 hours



+15
-
20% comments


+15
-
20% registered users

Registration

Single sign
-
on

Allow Facebook
users to register for
your site and set up a
profile using their
Facebook account.

1
-
6 weeks



15% increase in registrations

*Based on interviews with current Facebook Connect sites

Facebook FBML Application Architecture

IFrame application

Choosing between an FBML or IFrame Application


FBML



Lets you quickly start building an application from scratch, which is
good for a new Facebook developer.


Is likely to be faster on first page loads


paradigm is closer to that of the traditional Web


Gives you easy access to lots of Facebook elements


Lets your application pages have nice URLs


Has a sensible authorization mechanism


IFrames



Are easier and faster if you have an existing application, widget, or
website if the application utilizes XFBML


Are likely to lead to a faster experience for users over the long run


Let you use the JavaScript, HTML, and CSS that you are used to


Are faster if you are doing a lot of AJAX in your application, since the
requests don't need to go through Facebook proxy


Debugging regular HTML and JavaScript is easier than for FBML and
FBJS given the tools available today


Allow you to use popular JavaScript libraries like jQuery in your code,
but you'd have to modify the library to use it in FBJS, and some things
just might not work


Facebook App : Integration Points


Application Directory


Application Profile


Canvas Page


Profile


Applications Menu


Bookmarks


Application Tabs


Publisher


Feed Forms


News Feed


Requests


User Dashboard


Interacting with Users


Notification, Email

Facebook Apps

Finding the right concept


Build something interesting


since nestled in a social networking context, apps must be
social.


If its social it will be viral


Leverage The System


each user brings with them a network of friends that can be
involved


Engage the user


Provide the opportunity to interact and share elements with
each other


completely free attention to a Facebook application is very
rare.


“One Action Applications” is a proved concept!

Facebook App : Virality


Metrics for virality


For every new user how many new user they convert



> 1.4 is exponential growth


Viral Channels


Request & Invitations


News Feed


Stream


Publisher


Sharing


Notifications


Email


Friend Linking


Messages


Chats


Comments

Facebook App : Other Considerations


Scalability


Don’t scale until you need to “… unless you’re on Facebook.”


Object Caching


Memcached


Debugging Tools


Firebug


Fiddler


Developer Roadmap


http://wiki.developers.facebook.com/index.php/Developer_Roadmap





Demo


Demo Step 1 : Hello Facebook User


Create Poolster demo web app


Add references to client APIs


Configure the ASP.NET app


<appSettings>



<add key="APIKey" value=""/>



<add key="Secret" value=""/>



<add key="Callback" value="http://125.18.50.44:3001/poolster/"/>



<add key="Suffix" value="poolster"/>



<add key="PoolsterServiceUrl"

value="http://172.19.6.17/poolsterservice/service.svc"/>


</appSettings>


Create Poolster demo Facebook app


Configure the Facebook App


Demonstrate fb:name tag


Run the App

Demo Step 2 : Inviting Friends,
Getting Permissions, Page Navigation


Add master page


Add Home, My games and Create pages


Demonstrate using fb:dashboard, fb:action,
fb:create
-
button
, fb:help,
fb:bookmark

<fb:dashboard>


<fb:create
-
button href="CreateGame.aspx">Create a new pool game</fb:create
-
button>


<fb:action href="CreateGame.aspx">Create a new pool game</fb:action>


<fb:action href="InviteFriends.aspx">Invite Friends</fb:action>


<fb:help href="MyGames.aspx">Poolster Help!</fb:help>

</fb:dashboard>


Demonstrate using fb:tab and fb:tab
-
item

<fb:tabs>


<fb:tab
-
item title="Home" href="Home.aspx" Selected="<% =Convert.ToInt32(selected=="home") %>">



</fb:tab
-
item>


</fb:tabs>



Demonstrate Invite Friends

<fb:request
-
form action="home.aspx" method="POST" invite="true" type="Poolster"


content="Want to play pool games? Join me! <fb:req
-
choice url='http://apps.facebook.com/poolster/home.aspx'
label='Accept'/>">

<fb:multi
-
friend
-
selector showborder="false" actiontext="Invite your friends to Poolster">

</fb:request
-
form>


Demonstrate getting special permissions

<form id="settingForm" runat="server" promptpermission="read_stream,publish_stream,offline_access,email">


Would you like poolster to read from and post to your News Feed? &nbsp;&nbsp;&nbsp;


<asp:Button ID="btn
Allow
" runat="server" CssClass="inputsubmit" Text="Allow" />


</form>

<fb:prompt
-
permission perms="email">Would you like to receive email updates from poolster?</fb:prompt
-
permission>


Run the app

Demo Step 3 : FBJS, AJAX


Add and configure Poolster client, Add base page and login page


Add game list control with bet button and AJAX handling of bet action


function ShowMessage(title, msg) {


var dialog = new Dialog();


dialog.showMessage(title, msg, button_confirm = 'Ok');


}


function PlaceBet(gameId, gameOptionId) {


var d = new Dialog();


d.oncancel = function() { }


d.onconfirm = function() { OnConfirmPlaceBet(gameId, gameOptionId); }


d.showChoice("Poolster", "Are you sure you want to play ?", 'Yes', 'No');


}


function OnConfirmPlaceBet(gameId, gameOptionId) {


var ajax = new Ajax();


ajax.responseType = Ajax.JSON;


ajax.ondone = function(response) { HandlePlaceBetResponse(response, gameId, gameOptionId); }


ajax.onerror = function() { ShowMessage("Poolster", "Unknown Error ! Please try again after some time."); }


ajax.requireLogin = 1;


var load = { "GameId": gameId, "GameOptionId": gameOptionId };


ajax.post('<%=callback + "Handlers/PlaceBetHandler.aspx" %>', load);

}


function HandlePlaceBetResponse(response, gameId, gameOptionId) {


ShowMessage("Poolster", response.Message);


if (response.Success) {


var selectedOptionId = parseInt(document.getElementById("Game" + gameId +
"SelectedOption").getValue());


var element = document.getElementById("Option" + selectedOptionId);


if (element != null) {


element.setClassName("ListItem");


}


document.getElementById("Option" + gameOptionId).setClassName("selectedListItem");


document.getElementById("Game" + gameId + "SelectedOption").setValue(gameOptionId);


}


}



server side handling of bet action (BetHandler.aspx), send notification (on bet action)


Add the control to home page and Run the demo

Demo Step 4 : Application Tab


Add a page for displaying pool game


Link the game title to this page


Demonstrate
fb:share
-
button


<fb:share
-
button class="meta" >


<meta name="title" content=" <%# Eval("Title") %>"/>


<meta name="description" content="<%# Eval("Title") %>"/>


<link rel="target_url" href="<%#"http://apps.facebook.com/" + BasePage.suffix


+ "/Game.aspx?gameid=" + Eval("Id") %>"/>


</fb:share
-
button>


Add a page for displaying active games


Configure Facebook app to display this
page in profile tab


Run the demo

Demo Step 5: Stream, Email, Notifications


Add create page


Provide UI for creating pool game


Demonstrate various publishing methods


function ShowPublishDialog() {


var attachment = { 'name': '<%=GameTitle %>', 'href': '<%=GameLink %>', 'description': '' };


var actions = [{ 'text': 'play', 'href': '<%=GameLink %>'}];


Facebook.streamPublish('Created new Poolster game', attachment, actions);


}


private void PublishGame()


{


//attachment at = new attachment();




//List<action_link> actionlink = new List<action_link>();


//action_link al1 = new action_link { href = GameLink, text = "Play" };


//actionlink.Add(al1);


//string msg = string.Format("created new pool game
\
"{0}
\
"", GameTitle);


//Api.Stream.Publish(msg, at, actionlink, LoggedInUser.ToString(), LoggedInUser);



//depricated
, Developers will be able to ask users to share their primary email addresses


//List<long> fbusers = Api.Friends.Get().ToList();


//Api.Notifications.SendEmail(fbusers, "New Pool Game", GameTitle, GameLink);





//
Api.Notifications.Send(fbusers, “
Created new pool game

" + GameTitle

+ “ “ +
GameLink
,



//
"user_to_user");


if (!ClientScript.IsClientScriptBlockRegistered("ShowPublishPoolsterDialog"))


{


string script = "ShowPublishDialog();";


ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowPublishPoolsterDialog", script, true);


}


}


Display the games authored


Add option to “Mark Winning”


Run the app

Demo Step 6 : Publisher


Add a publisher


Add a control for displaying publisher


Add handlers


Configure the publisher


Run the demo


View Complete demo at



http://apps.facebook.com/poolster/home.aspx