Creating Facebook applications with NetAdvantage for jQuery, ASP.Net MVC3 and Facebook C # SDK – using jQuery Grid (Part 1)

[Infragistics] Mihail Mateev / Tuesday, October 11, 2011

Creating applications for Facebook is associated with the use of the API for the platform. With the release of Facebook C # SDK developers accepted this framework for developing Facebook applications under .Net based environments.

An interesting case is the development of Facebook applications with ASP.Net MVC3 and Razor. In a series of articles will show you how to develop Facebook applications with MVC3 Razor and NetAdvantage for jQuery. This article will show you how to develop applications for this social network using NetAdvantage jQuery Grid.

Sample application will display in the Infragistics igGrid current Facebook user friends. Application will have different views for all friends and for online friends.

To begin development, you must satisfy the following requirements

You should follow several steps when you create this application:

  • Create Facebook application and set application properties
  • Create ASP.Net MVC3 Razor application
  • Add references to NetAdvantage for jQuery and Facebook C# SDK
  • Create required controllers  and views and implement code to maintain user friends info

Create Facebook application.

Demo application  is designed to run within an iframe on a Facebook Canvas page. You could create a canvas application in http://developers.facebook.com/. In the current sample Facebook application is named jQueryGridDemo

You should add some settings in Basic and Advanced tabs.

Basic settings:

  • App Namespace : it is used to create the full application URL – in this case it will be jquerygriddemo and the whole URL will be : http://apps.facebook.com/jquerygriddemo
  • Canvas URL: it is an URL of the Facebook application outside of the Facebook. We will use http://localhost:10009/

Advanced settings:

  • Canvas Settings: Ensure that Canvas Width is “Fixed (760px)” and Canvas Height is “Fluid”.

Create ASP.Net MVC3 Razor application

Confirm that you want to create an Internet Application and select Razor as view engine.

Setting up the project

Add reference to Infragistics.Web.Mvc assembly:

When you create a new ASP.NET MVC 3 project it comes with Scripts and a Content folders where all the default JavaScript files and CSS contents are located respectively.

You should  use the same folder and insert the Infragistics Scripts & CSS from NetAdvantage for jQuery install folder.

More information how to set project to use  NetAdvantage for  jQuery components you could find in the article:
Using CRUD Operations with jQuery igGrid, Entity Framework and ASP.Net MVC3.

Add references to the Facebook C# SDK:

Facebook application implementation:

Controllers:

Add a new controller, named FacebookController. Create in  this controller two actions: Index (to get all Facebook friends of the current user) and OnlineIndex (to get all online Facebook friends of the current user).

Get all Facebook friends of the user.

   1: private const string SimpleExtendedPermissions = "user_about_me,publish_stream";
   2:  
   3:         [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
   4:         [CanvasAuthorize(Permissions = SimpleExtendedPermissions)]
   5:         public ActionResult Index()
   6:         {
   7:             var fb = new FacebookWebClient();
   8:             dynamic me = fb.Get("me");
   9:  
  10:             dynamic friendsData = fb.Get("/me/friends");
  11:  
  12:  
  13:             ViewBag.FriendsData = friendsData;
  14:  
  15:  
  16:             ViewBag.ProfilePictureUrl = string.Format("http://graph.facebok.com/{0}/picture", me.id);
  17:             ViewBag.Name = me.name;
  18:             ViewBag.FirstName = me.first_name;
  19:             ViewBag.LastName = me.last_name;
  20:  
  21:  
  22:             ViewBag.MessagePostSuccess = Request.QueryString.AllKeys.Contains("success") &&
  23:                                          Request.QueryString["success"] == "True";
  24:  
  25:             return View();
  26:  
  27:             
  28:         }

FacebookWebClient class is used in Facebook C# SDK to propose client API in C# for communication with Facebook web services.

Add in the Web.config file the code below, where you should change app_id and app_secret  with App ID and App Secret of the your Facebook application.

   1: <facebookSettings appId = "{app_id}" appSecret = "{app_secret}"
   2:    canvasPage = "http://apps.facebook.com/jquerygriddemo/"
   3:    canvasUrl = "http://localhost:10009/"
   4:    secureCanvasUrl = "https://localhost:44303/" />

That is all. Facebook C# SDK assemblies expect to have facebookSettings section in the your Web.config file and can read its attributes.

This application  could get an information about the current user with method FacebookWebClient.Get(“me”).

   1: var fb = new FacebookWebClient();
   2: dynamic me = fb.Get("me");
   3:  
   4: dynamic friendsData = fb.Get("/me/friends");

 

Information about current user friends you could receive via method: FacebookWebClient.Get(“/me/friends”). To be possible your application to receive this information from the current user it need additional “extended” permissions.  Permissions are string constants, described in the Facebook  Graph API.

In this case we need "user_about_me" permissions. We will use these permissions via attributes of the controller actions.

   1: private const string SimpleExtendedPermissions = "user_about_me";
   2: [CanvasAuthorize(Permissions = SimpleExtendedPermissions)]
   3: public ActionResult Index()
   4: {
   5: ..
   6: }

 

Method FacebookWebClient.Get(…) returns data like JsonArray. It is easier to handle it using C# dynamic type. Data will be used in the MVC views. You could save it in the ViewBag to be possible to access it from the views.

   1: dynamic friendsData = fb.Get("/me/friends");
   2:  
   3: ViewBag.FriendsData = friendsData;

To be possible to get photos you could use Facebook Graph API.

   1: ViewBag.ProfilePictureUrl = string.Format("http://graph.facebok.com/{0}/picture", me.id);

 

For friends photos you could use friend id instead id of the current user.

Get all online Facebook friends of the user.

When you use FacebookWebClient.Get(“/me/friends”)  in the result there is only data for id and name of each friend. It is not a good idea to call for each friend in the loop in this way:
FacebookWebClient.Get(“friend_id”). This will lead to a lot of requests for a short time and possible timeout for some requests.

In this case you have a great opportunity to use Facebook Query Language (FQL).  FQL enables you to use a SQL-style interface to query the data exposed by the Facebook Graph API.

You could receive data using FacebookWebClient.Query(“{query text}”);

   1: private const string ExtendedPermissions = "user_about_me,friends_location,user_location,friends_online_presence";
   2:  
   3: [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
   4: [CanvasAuthorize(Permissions = ExtendedPermissions)]
   5: public ActionResult OnlineIndex()
   6: {
   7:     var fb = new FacebookWebClient();
   8:     dynamic me = fb.Get("me");
   9:  
  10:     dynamic selectedFriends = fb.Query("SELECT uid, name, pic_square, ***, locale, online_presence, current_location FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) AND online_presence IN ('active', 'idle')");
  11:  
  12:     ViewBag.OnlineFriends = selectedFriends;
  13:  
  14:  
  15:     ViewBag.ProfilePictureUrl = string.Format("http://graph.facebok.com/{0}/picture", me.id);
  16:     ViewBag.Name = me.name;
  17:     ViewBag.FirstName = me.first_name;
  18:     ViewBag.LastName = me.last_name;
  19:  
  20:     return View();
  21:  
  22:  
  23: }

In the sample application FQL query get all friends with “active” and “idle” status, including data about gender, current location etc.

Views:

Application has two views, associated with  FacebookController: Index and OnlineIndex

Index View

The Index view shows all users in the Infragistics jQuery Grid.

To be possible to use filtering and paging without new server calls is used
Paging().Type(OpType.Local) and Filtering().Type(OpType.Local).

To be possible to use custom row templates is used jquery templating.

   1: @( Html.Infragistics().Grid<FacebookFriend>().ID("fbGrid").AutoGenerateColumns(true)
   2:     .Columns(column =>
   3:     {
   4:         column.For(x => x.PictureUrl).DataType("string").HeaderText("Picture").Width("100");
   5:         column.For(x => x.Name).DataType("string").HeaderText("Name").Width("300");
   6:     })
   7:     .Features(features =>
   8:     {
   9:         features.Paging().Type(OpType.Local).VisiblePageCount(5).ShowPageSizeDropDown(false).PageSize(10).PrevPageLabelText("Previous").NextPageLabelText("Next");
  10:  
  11:         features.Sorting().Mode(SortingMode.Single).ColumnSettings(settings =>
  12:         {
  13:             settings.ColumnSetting().ColumnKey("Name").AllowSorting(true);
  14:  
  15:         });
  16:  
  17:         features.Selection().MouseDragSelect(true).MultipleSelection(true).Mode(SelectionMode.Row);
  18:         features.Selection().MouseDragSelect(true).MultipleSelection(true).Mode(SelectionMode.Cell);
  19:  
  20:         features.Filtering().Type(OpType.Local).ColumnSettings(settings =>
  21:         {
  22:  
  23:             settings.ColumnSetting().ColumnKey("Name").AllowFiltering(true).FilterCondition("startsWith");
  24:         });
  25:  
  26:     })
  27:     .JQueryTemplating(true)
  28:     .RowTemplate("<tr><td class='tooltip-grid-image'> <img src='${PictureUrl}'></img> </td><td> ${Name} </td></tr>")
  29:     .DataSource(queryable)
  30:     .Width("450px")
  31:     .Height("420px")
  32:     .DataBind()
  33:     .Render()
  34: )

The whole code of the Index view:

   1: @inherits System.Web.Mvc.WebViewPage<IQueryable<CS_Canvas_AspNetMvc3_WithoutJsSdk.Models.FacebookFriend>>
   2: @using Infragistics.Web.Mvc;
   3: @using Facebook;
   4: @using Facebook.Web;
   5: @using Facebook.Web.Mvc;
   6: @using System.Collections.Generic;
   7: @using CS_Canvas_AspNetMvc3_WithoutJsSdk.Models;
   8:  
   9: @{
  10:     ViewBag.Title = "Index";
  11:     dynamic friendsData = ViewBag.FriendsData;
  12:  
  13:     var fb = new FacebookWebClient();
  14:  
  15:     List<FacebookFriend> myFriends = new List<FacebookFriend>();
  16:  
  17:  
  18:     foreach (dynamic friend in friendsData.data)
  19:     {
  20:         FacebookFriend rowList = new FacebookFriend();
  21:  
  22:         rowList.Id = friend.id;
  23:         rowList.Name = friend.name;
  24:         rowList.PictureUrl = string.Format("http://graph.facebok.com/{0}/picture", friend.id);
  25:     
  26:         myFriends.Add(rowList);
  27:  
  28:  
  29:     }
  30:  
  31:     var queryable = myFriends.AsQueryable();
  32:  
  33: }
  34: <!DOCTYPE html>
  35:  
  36: <html>
  37:  
  38: <head>
  39: <script type="text/javascript">
   1:  
   2:  
   3:     $(document).ready(function () {
   4:  
   5:         $('#homeButton').click(function () {
   6:             location.href = '/Home/Index';
   7:         });
   8:         $('#onlineButton').click(function () {
   9:             location.href = '/Facebook/OnlineIndex';
  10:         });
  11:     });
  12:  
</script>
  40: </head>
  41: <body>
  42: <h1>
  43:     Facebook C# SDK ASP.NET MVC3 Canvas Application</h1>
  44: <p>
  45:     This sample demonstrates the use of Facebook C# SDK ASP.NET MVC3 along with the
  46:     NetAdvantage jQuery igGrid</p>
  47: <strong>Hi @ViewBag.Name</strong><br />
  48: <img src="@ViewBag.ProfilePictureUrl"/>
  49: <table>
  50:     <tr>
  51:         <td>
  52:             First Name:
  53:         </td>
  54:         <td>@ViewBag.FirstName
  55:         </td>
  56:     </tr>
  57:     <tr>
  58:         <td>
  59:             Last Name:
  60:         </td>
  61:         <td>@ViewBag.LastName
  62:         </td>
  63:     </tr>
  64: </table>
  65: <br/>
  66:  
  67: <div>
  68:     <p><strong>Friends List </strong> </p>
  69:     @( Html.Infragistics().Grid<FacebookFriend>().ID("fbGrid").AutoGenerateColumns(true)
  70:         .Columns(column =>
  71:         {
  72:             column.For(x => x.PictureUrl).DataType("string").HeaderText("Picture").Width("100");
  73:             column.For(x => x.Name).DataType("string").HeaderText("Name").Width("300");
  74:         })
  75:         .Features(features =>
  76:         {
  77:             features.Paging().Type(OpType.Local).VisiblePageCount(5).ShowPageSizeDropDown(false).PageSize(10).PrevPageLabelText("Previous").NextPageLabelText("Next");
  78:  
  79:             features.Sorting().Mode(SortingMode.Single).ColumnSettings(settings =>
  80:             {
  81:                 settings.ColumnSetting().ColumnKey("Name").AllowSorting(true);
  82:  
  83:             });
  84:  
  85:             features.Selection().MouseDragSelect(true).MultipleSelection(true).Mode(SelectionMode.Row);
  86:             features.Selection().MouseDragSelect(true).MultipleSelection(true).Mode(SelectionMode.Cell);
  87:  
  88:             features.Filtering().Type(OpType.Local).ColumnSettings(settings =>
  89:             {
  90:  
  91:                 settings.ColumnSetting().ColumnKey("Name").AllowFiltering(true).FilterCondition("startsWith");
  92:             });
  93:  
  94:         })
  95:         .JQueryTemplating(true)
  96:                         .RowTemplate("<tr><td class='tooltip-grid-image'> <img src='${PictureUrl}'></img> </td><td> ${Name} </td></tr>")
  97:         .DataSource(queryable)
  98:         .Width("450px")
  99:         .Height("420px")
 100:         .DataBind()
 101:         .Render()
 102:     )
 103:        <table>
 104:         <tr>
 105:             <td>
 106:                 <input type='button' value='Home' id='homeButton'/>
 107:             </td>
 108:             <td>
 109:                 <input type='button' value='Online Friends' id='onlineButton'/>
 110:             </td>
 111:         </tr>
 112:     </table>
 113: </div>
 114: </body>
 115:  
 116: </html>

 

OnlineIndex View

Infragistics,Grid MVC Helper usage:

   1: @( Html.Infragistics().Grid<FacebookFriendInfo>().ID("fbGrid").AutoGenerateColumns(true)
   2:     .Columns(column =>
   3:     {
   4:         column.For(x => x.PictureUrl).DataType("string").HeaderText("Picture").Width("100");
   5:         column.For(x => x.Name).DataType("string").HeaderText("Name");
   6:         column.For(x => x.Gender).DataType("string").HeaderText("Gender").Width("100");
   7:         column.For(x => x.OnlinePresence).DataType("string").HeaderText("Status").Width("100");
   8:         column.For(x => x.CurrentLocation).DataType("string").HeaderText("Current Location");
   9:     })
  10:     .Features(features =>
  11:     {
  12:         features.Paging().Type(OpType.Local).VisiblePageCount(5).ShowPageSizeDropDown(false).PageSize(10).PrevPageLabelText("Previous").NextPageLabelText("Next");
  13:  
  14:         features.Sorting().Mode(SortingMode.Single).ColumnSettings(settings =>
  15:         {
  16:             settings.ColumnSetting().ColumnKey("Status").AllowSorting(true);
  17:  
  18:         });
  19:  
  20:         features.Selection().MouseDragSelect(true).MultipleSelection(true).Mode(SelectionMode.Row);
  21:         features.Selection().MouseDragSelect(true).MultipleSelection(true).Mode(SelectionMode.Cell);
  22:  
  23:         features.Filtering().Type(OpType.Local).ColumnSettings(settings =>
  24:         {
  25:             settings.ColumnSetting().ColumnKey("Name").AllowFiltering(true).FilterCondition("startsWith");
  26:         });
  27:  
  28:     })
  29:     .JQueryTemplating(true)
  30:     .RowTemplate("<tr><td class='tooltip-grid-image'> <img src='${PictureUrl}'></img> </td><td> ${Name} </td><td> ${Gender} </td><td> ${OnlinePresence} </td><td> ${CurrentLocation} </td></tr>")
  31:     .DataSource(queryable)
  32:     .Width("700px")
  33:     .Height("420px")
  34:     .DataBind()
  35:     .Render()

The whole code of the OnlineIndex view:

   1: @inherits System.Web.Mvc.WebViewPage<IQueryable<CS_Canvas_AspNetMvc3_WithoutJsSdk.Models.FacebookFriendInfo>>
   2: @using Infragistics.Web.Mvc;
   3: @using Facebook;
   4: @using Facebook.Web;
   5: @using Facebook.Web.Mvc;
   6: @using System.Collections.Generic;
   7: @using CS_Canvas_AspNetMvc3_WithoutJsSdk.Models;
   8:  
   9: @{
  10:     ViewBag.Title = "Online Index";   
  11:         
  12:      dynamic friendsData =     ViewBag.OnlineFriends;
  13:  
  14:     var fb = new FacebookWebClient();
  15:  
  16:     List<FacebookFriendInfo> myFriends = new List<FacebookFriendInfo>();
  17:  
  18:  
  19:     foreach (dynamic friend in friendsData)
  20:     {
  21:         FacebookFriendInfo rowList = new FacebookFriendInfo();
  22:  
  23:         rowList.Id = friend.id;
  24:         rowList.Name = friend.name;
  25:         rowList.Gender = friend.***;
  26:         if (friend.current_location != null)
  27:         {
  28:             rowList.CurrentLocation = friend.current_location.name;
  29:         }
  30:         
  31:         rowList.OnlinePresence = friend.online_presence;
  32:         rowList.PictureUrl = friend.pic_square;
  33:  
  34:         myFriends.Add(rowList);
  35:  
  36:  
  37:     }
  38:  
  39:     var queryable = myFriends.AsQueryable();
  40:  
  41: }
  42:  
  43: <!DOCTYPE html>
  44:  
  45: <html>
  46:  
  47: <head>
  48: <script type="text/javascript">
   1:  
   2:  
   3:     $(document).ready(function () {
   4:  
   5:         $('#homeButton').click(function () {
   6:             location.href = '/Home/Index';
   7:         });
   8:         $('#friendsButton').click(function () {
   9:             location.href = '/Facebook/Index';
  10:         });
  11:     });
  12:  
</script>
  49: </head>
  50:  
  51: <body>
  52: <h1>
  53:     Facebook C# SDK ASP.NET MVC3 Canvas Application</h1>
  54: <p>
  55:     This sample demonstrates the use of Facebook C# SDK ASP.NET MVC3 along with the
  56:     NetAdvantage jQuery igGrid displaying online friends</p>
  57: <strong>Hi @ViewBag.Name</strong><br />
  58: <img src="@ViewBag.ProfilePictureUrl"/>
  59: <table>
  60:     <tr>
  61:         <td>
  62:             First Name:
  63:         </td>
  64:         <td>@ViewBag.FirstName
  65:         </td>
  66:     </tr>
  67:     <tr>
  68:         <td>
  69:             Last Name:
  70:         </td>
  71:         <td>@ViewBag.LastName
  72:         </td>
  73:     </tr>
  74: </table>
  75: <br />
  76:  
  77:  
  78: <div>
  79:     <p><strong>Online Friends List</strong></p>
  80:     @( Html.Infragistics().Grid<FacebookFriendInfo>().ID("fbGrid").AutoGenerateColumns(true)
  81:         .Columns(column =>
  82:         {
  83:             column.For(x => x.PictureUrl).DataType("string").HeaderText("Picture").Width("100");
  84:             column.For(x => x.Name).DataType("string").HeaderText("Name");
  85:             column.For(x => x.Gender).DataType("string").HeaderText("Gender").Width("100");
  86:             column.For(x => x.OnlinePresence).DataType("string").HeaderText("Status").Width("100");
  87:             column.For(x => x.CurrentLocation).DataType("string").HeaderText("Current Location");
  88:         })
  89:         .Features(features =>
  90:         {
  91:             features.Paging().Type(OpType.Local).VisiblePageCount(5).ShowPageSizeDropDown(false).PageSize(10).PrevPageLabelText("Previous").NextPageLabelText("Next");
  92:  
  93:             features.Sorting().Mode(SortingMode.Single).ColumnSettings(settings =>
  94:             {
  95:                 settings.ColumnSetting().ColumnKey("Status").AllowSorting(true);
  96:  
  97:             });
  98:  
  99:             features.Selection().MouseDragSelect(true).MultipleSelection(true).Mode(SelectionMode.Row);
 100:             features.Selection().MouseDragSelect(true).MultipleSelection(true).Mode(SelectionMode.Cell);
 101:  
 102:             features.Filtering().Type(OpType.Local).ColumnSettings(settings =>
 103:             {
 104:                 settings.ColumnSetting().ColumnKey("Name").AllowFiltering(true).FilterCondition("startsWith");
 105:             });
 106:  
 107:         })
 108:         .JQueryTemplating(true)
 109:         .RowTemplate("<tr><td class='tooltip-grid-image'> <img src='${PictureUrl}'></img> </td><td> ${Name} </td><td> ${Gender} </td><td> ${OnlinePresence} </td><td> ${CurrentLocation} </td></tr>")
 110:         .DataSource(queryable)
 111:         .Width("700px")
 112:         .Height("420px")
 113:         .DataBind()
 114:         .Render()
 115:     )
 116:           <table>
 117:         <tr>
 118:             <td>
 119:                 <input type='button' value='Home' id='homeButton'/>
 120:             </td>
 121:             <td>
 122:                 <input type='button' value='All Friends' id='friendsButton'/>
 123:             </td>
 124:         </tr>
 125:     </table>
 126: </div>

 

Run the Application

On the main page you could select “Friends” or “Online Friends”

Select “Friends” and see the all Facebook friends in the igGrid.

Select “Online Friends” to see all Facebook friends with status “online” or “idle”

Enjoy! You have your first Facebook ASP.Net MVC3 application with Infragistics jQuery Grid.

Source code you could find here: