Computer Beacon  

Blog

FGT Update v3.1

Posted on 5/7/2012

This update fixes a few bugs and adds a few features reported / suggested by developers. You can grab the library at the FGT CodePlex project.

  • New user relationships are added, suggested by Tony Gravagno
  • Incorrect url when posting link attachments with urls that contain the '&' character, reported by Roberto Minoia
  • Incorrect IsAuthorized property, also reported by Roberto Minoia
  • GetGrantedPermissions() is now available on the Api class directly, not restricted to CanvasPage and TabPage class, suggested by Easton Harvey

Other updates include improved error handling when Facebook return "403 forbidden", fixed bug when posting unicode characters in posts and ships with JSON Toolkit v3.1 which offers additional speed up.

Thanks everyone for your support and positive feedbacks on this library, it has been doing very well. FGT v4 is currently at planning stage; its expected to implement Open Graph, a new and more flexible authorization model and hopefully expand to other platforms as well. If you have any suggestions for the future release you can post to our Facebook Page, send an email or comment below.

Comment on this post


Further optimizations in JSON Toolkit v3.1 update

Posted on 3/28/2012

About a month ago I released JSON Toolkit v3.0 which boosted the parsing speed up to 10x times. Today I just released v3.1 update which brings further performance improvement to the parsing operation. This time the speed-up is not that big though, about 5% to 10% (-:

Sample Data v3.1 v3.0 Speed-up
Serialized Java servlet 3700 ms 3943 ms 6.56%
Bing Api search response 1188 ms 1251 ms 5.27%
Facebook Graph object 567 ms 618 ms 8.85%

A new JsonException class has been added to better distinguish exceptions that are thrown by the toolkit.

There is no change to functionality, so there is no need to re-write any code. Just download the dll file from CodePlex and re-compile.

Comment on this post


How to write a Facebook Page Tab app in 10 minutes

Posted on 3/19/2012

In this article I'll show how simple it is to write a Facebook app for Page Tabs using Facebook Graph Toolkit (-:

First thing first go to https://developers.facebook.com and create a new app. Copy the AppID and Secret to web.config:

<configuration>
    <configSections>
        <section name="FacebookGraphToolkitConfiguration" type="Facebook_Graph_Toolkit.FacebookGraphToolkitConfiguration"/>
    </configSections>

    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
    <FacebookGraphToolkitConfiguration AppID="xxxxxxxxxx" AppSecret="xxxxxxxxxxxxxx">
    </FacebookGraphToolkitConfiguration>

</configuration>

Next, go to the app settings page on Facebook, and check the Page Tab function. Give your app a fancy name. Point the Page Tab URL and Secure Page Tab URL to an address that contains the aspx page you'll be creating. Localhost is also acceptable. Now here's the problem: Facebook requires apps to accept https connection. Normally enabling sandbox mode will temporarily allow normal http connection, but this doesn't work for Page Tabs (most probably Facebook bug). ScottGu's Blog has a nice article that explains how to create local SSL certificates for development purpose. When you deploy the application of course, you will need to purchase one for your server.

Here I'm going to create a very simple app called "Sum your name" - it basically just sums the ASCII (or unicode) values of the characters in your name and displays it. This is the same sample that is used for the Canvas and Page Tab demo at https://apps.facebook.com/aspdotnetsample/ .

To access the user's name we need the user to authorize our app. So let's put the below html into our .aspx page:

<div id="div_Authorized" runat="server">
    <p>Your name is: <asp:Label ID="Label_name" runat="server" /></p>
    <p>The sum of the ASCII values of your name is: <asp:Label ID="Label_Sum" runat="server" /></p>
</
div>
<
div id="div_NotAuthorized" runat="server">
    <p>You have not authorized the app.</p>
    <asp:Button runat="server" Text="Authorize" OnClick="AuthClick" />
</
div>

People often have questions about how to display different content for users who have and have not authorized the app. The simplest solution is render everything in a single .aspx page. After all, it's a server-side script, so all it matters is delivering the right html to the user. Do not use IframeRedirect, Response.Redirect or <a> links, because the information that is POSTed by Facebook will get lost in this process.

The C# code behind this page is quite straight forward:

public partial class PageTab : Facebook_Graph_Toolkit.TabPage {
    protected void Page_Load(object sender, EventArgs e) {
        if (Api == null) div_Authorized.Visible = false;
        else {
            div_NotAuthorized.Visible = false;
            Facebook_Graph_Toolkit.GraphApi.User u = new Facebook_Graph_Toolkit.GraphApi.User("me", Api.AccessToken);
            string name = u.Name;
            UInt64 sum = 0;
            foreach (char c in name) sum += c;
            Label_Sum.Text = sum.ToString();
            Label_name.Text = name;
        }
    }
    protected void AuthClick(object sender, EventArgs e) {
        RedirectToFacebookAuthorization();
    }
}

  1. Inherit TabPage instead of System.Web.UI.Page
  2. If the Api object is null, the user has not authorized our app.
  3. Call the RedirectToFacebookAuthorization() method as necessary. After authorization, the user will be redirected to this page again by Facebook.

Final thing, we need a mechanism that would allow Page administrators to add our app to their pages. This is achieved by redirecting the administrator to an address obtained by calling Dialog.GetAddPageTabUrl() method. You can do this at anywhere you like, it can be a website, it can be Canvas app, or a link in an email. Below is an example of how to achieve this in a canvas app:

FacebookAppConfig c = FacebookAppConfig.FromWebConfig;
string url = Dialog.GetAddPageTabUrl(c.AppID, c.CanvasAddress + "Default.aspx", DialogDisplayType.FullPage);
Facebook_Graph_Toolkit.Helpers.IframeHelper.IframeRedirect(url, false, true);

If it is just a normal ASP.NET webpage, you can put the link in an <a> tag or use Response.Redirect. If you get an error from Facebook saying that the url address must be owned by the app, simply go to the app settings and add your domain name there.

Finally, publish your app. And that's it!

Comment on this post


Facebook Graph Toolkit v3.0 update

Posted on 3/14/2012

First of all, thanks Verat Yuthavong for the heads up at our Computer Beacon Facebook Page. I have been busy working on Metro apps recently so I was not aware of the changes. Anyway, Facebook has been in the progress of changing its app authorization process (as it always is), and as a result some of the authorization procedures in FGT has been updated. I have been receiving some emails asking about putting their applications in a Page Tab, and that class has been updated too with simplified authorization settings and bug fixed. It is now possible to filter Graph Api connection data based on dates. Some variable names in the toolkit were found to be too long or misleading, so those were changed as well. It is likely that existing codes require slight modification to use FGT v3.0 .

Example codes and download

The sample application at https://apps.facebook.com/aspdotnetsample/ has been updated for v3.0. A new Page Tab demo is also added.

Note that in this example app, the Canvas part and the Page Tab part are requesting different permissions from the user on behalf of the same application, yet it still works.

As usual, the compiled libraries for .NET 4 and 3.5, example application and source code can be downloaded at http://fgt.codeplex.com/ .

New authorization model

With Facebook's updated authorization model, users are able to cancel some of the permissions yet still proceed to the app. The CheckExtendedPermissions field has been removed as it does not make sense anymore, and is being replaced by the GetGrantedPermissions() method. The ExtendedPermissions string field is changed to Permissions List<string> field.

public partial class Default : Facebook_Graph_Toolkit.CanvasPage{
    protected void Page_PreInit(object sender, EventArgs e){
        Permissions = "user_photos,read_stream,user_notes,user_events,manage_notifications,user_groups,user_likes".Split(',').ToList();
        RequireLogin = true;
    }
    protected void Page_Load(object sender, EventArgs e){
        List<string> GrantedPermissions = GetGrantedPermissions();
        if (GrantedPermissions.Count < Permissions.Count) {
            RedirectToFacebookAuthorization();
        }
    }
}

In FGT, most methods represent logic that connects to Facebook server, while properties extract information from variables. GetGrantedPermissions() performs a FQL query to check whether permissions are granted, so bear in mind the performance cost. Store the result in a varible if it is necessary to access it more than once.

The above code is essentially equal to the function of CheckExtendedPermissions field: the user will be forever redirected to the authorize dialog until all permissions are granted. However, developers can also check individual permissions one by one:

if (GrantedPermissions.Contains("publish_stream")) {
    //logic to post feed
}

Extend Access Token

"offline_access" will no longer be supported by Facebook very soon, although existing access tokens that have offline_access will continue to work. For new access tokens, it is necessary to renew it by calling an Api, which will extend its expire date to 60 days from the time it is renewed. Whether it is possible to repeatly renew the same access token every day is unclear (you may try it).

Facebook_Graph_Toolkit.FacebookAppConfig c = Facebook_Graph_Toolkit.FacebookAppConfig.FromWebConfig;
Facebook_Graph_Toolkit.GraphApi.Api _A = Api.ExtendAccessToken(c.AppID, c.AppSecret, Api.AccessToken);

The returned Api object contains the new access token as well as its expire date. The new access token may or may not be the same as the original one.

Filter Graph Api connections

All Graph Api connections in the library now accept an optional parameter having the type GraphApiFilter. GraphApiFilter has 4 properties: Offset, Limit, Since and Until. It is not required to specify all 4 properties.

Facebook_Graph_Toolkit.FacebookObjects.GraphApiFilter f = new Facebook_Graph_Toolkit.FacebookObjects.GraphApiFilter();
f.Limit = 10;
f.Until = new DateTime(2012, 3, 1);
IList<Post> Ps = Facebook_Graph_Toolkit.GraphApi.User.GetFeed("me", Api.AccessToken,f);
foreach (Post P in Ps) ......

To use Facebook's default settings, simply do not specify the third parameter.

IList<Post> Ps = Facebook_Graph_Toolkit.GraphApi.User.GetFeed("me", Api.AccessToken);

Renamed variables

All instances of FacebookAppConfig are now called FacebookAppInfo in CanvasPage, SocialPage and TabPage (previously they had different names). You can also conveniently retrieve the settings stored in web.config file by accessing the FacebookAppConfig.FromWebConfig static property.

Finally, here are the new settings for web.config:

<configuration>
  <configSections>
    <section name="FacebookGraphToolkitConfiguration" type="Facebook_Graph_Toolkit.FacebookGraphToolkitConfiguration"/>
  </configSections>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <FacebookGraphToolkitConfiguration AppID="123456789" AppSecret="xxxxxxxxxxxxxxxxxxx" CanvasAddress="http://apps.facebook.com/xxxxxxx/" PostAuthorizeRedirectURL="CanvasPage.aspx" WebTimeOut="8000">
  </FacebookGraphToolkitConfiguration>
</configuration>

They function the same as those in previous versions.

AddPageTab Dialog

The new Dialog.GetAddPageTabUrl method returns an url which prompts the user to add an application Page Tab to their administered pages. In this as well as other Dialog methods, the RedirectAddress parameter is no longer relative to the CanvasAddress. Developers have the flexibility to redirect the user to their own site instead. Note that the domain must be "owned" by the app: either it is relative to the CanvasAddress (i.e. apps.facebook.com/xxx/yyy.aspx ), or the domain of the website of the app.

Comment on this post


Optimized Json Toolkit: v3.0

Posted on 2/21/2012

Today I am proud to present to you the new Json Toolkit v3.0. This version brings significant performance improvement by using a completely redesigned parsing algorithm. The algorithm is much faster and has a speed up of more than 900% (i.e. 10 times faster) than the previous version.

Here are some of the performance comparisons between v2.1 and v3.0 using real JSON data. The running time is measured by looping the parse operation from 1000 to 100000 times (depending on length and complexity of the data).

Sample Data v2.1 v3.0 Speed up
Sample JSON from wiki 11684 ms 1654 ms 606%
Serialized Java servlet 84115 ms 10125 ms 731%
Bing Api object 29296 ms 3260 ms 798%
Facebook Graph object 8030 ms 793 ms 913%

The new algorithm removes unnecessary function calls and also take into consideration the fact that most data in real world scenarios are either string or integer data. Data from Facebook Graph Api are often wrapped in many layers of JSON objects and arrays, which explains why it has the highest speed up among all test data.

Json Toolkit v3.0 is available for download at CodePlex: http://jsontoolkit.codeplex.com/ . The library is fully compatible with the old version as no functionality has changed; simply replace the dll file and recompile the application. The new library is also tested against 50 different test cases with 100% pass.

Comment on this post