Wednesday 15 October 2014

Example to create Facebook App to show list of friends using FQL(Facebook Query Language) and send Invite in C# (MVC)

To create such App firstly we need to create Facebook Developer account to get the Facebook Application Id.

Refer this link to create developer account and get FB App Id : 

Here we have used MVC  to develop this :

1. Create a controller of name PeopleController

2. Create an action

     public ActionResult InviteFBPeople()
        {
            return View();
        }

3. Create view for above action

@{
    ViewBag.Title = "Invite Facebook People";
}

<h2>Invite Facebook Friends</h2>

<div id="fb-root" style="display:inline; margin-left:20px;"></div>

<script language="javascript" type="text/javascript">
    //Facebook SDK initialize portion
    window.fbAsyncInit = function () {
        FB.init({
            appId: 'YourFBAppID',
            status: true, cookie: false, xfbml: true
        });
    };
    // All FB resources
    $(document).ready(function () {
        if (document.getElementById('fb-root') != undefined) {
            var e = document.createElement('script');
            e.type = 'text/javascript';
            e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
            e.async = true;
            document.getElementById('fb-root').appendChild(e);
        }
    });

</script>

<script>
    // This is to get the Access Token of FB
    $(document).ready(function () {
        setTimeout(function () {
            //something you want delayed
            FB.getLoginStatus(function (response) {
                if (response.status === 'connected') {
                    var fbAccessToken = response.authResponse.accessToken;
                    window.location = '@Url.Action("ListFacebookFriends", "People")' + "?id=" + fbAccessToken;

                }
            });

        }, 2000);

    });
</script>

4. In above script we have made to fetch the access token of logged in FB user and passed it to an action of name "ListFacebookFriends" in same People Controller, 

 public ActionResult ListFacebookFriends(string id)
        {
            //get current access token
            var accessToken = id;

            List<FacebookFriends> Friends = new List<FacebookFriends>();

            if (accessToken != "")
            {

                Friends = GetFriends(accessToken, false,"").ToList();

            }

            ViewBag.FbFriends = Friends;


            return View();
        }

5. Create Function of name GetFriends 

public IEnumerable<FacebookFriends> GetFriends(string accessToken, bool isUsing)
            {
                string strQuery = string.Empty;
                if (isUsing)
                {
                    strQuery = "SELECT uid, name, pic_square, email FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=me()) AND is_app_user";
                }
                else
                {
                    strQuery = "SELECT uid, name, pic_square, email FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=me()) AND NOT is_app_user";
                }

                FacebookClient objFQL = new FacebookClient(accessToken);

                dynamic parameters = new ExpandoObject();
                parameters.q = strQuery;

                dynamic objFNU = objFQL.Get("fql", parameters);

                List<FacebookFriends> friendsToReturn = new List<FacebookFriends>();

                if (objFQL != null)
                {
                    foreach (dynamic row in objFNU.data)
                    {
                        friendsToReturn.Add(new FacebookFriends()
                        {
                            FriendID = Convert.ToString(row.uid),
                            FriendName = row.name,
                            PicURLSquare = row.pic_square,
                            Email = row.email
                        }
                    );
                    }
                }

                return friendsToReturn;
            } //Get FB Friends not already using this app

6. Create class of name FacebookFriends.

    public class FacebookFriends
        {
            public string FriendID { get; set; }
            public string FriendName { get; set; }
            public string PicURLSquare { get; set; }
            public string ProfileLink { get; set; }
            public bool Follower { get; set; }
            public string Email { get; set; }
            public string UserName { get; set; }
}

7. Create view for action "ListFacebookFriends".

@{
    ViewBag.Title = "ListFacebookFriends";
}

<div id="main">

    <div >
        
        <div >
            <h2>List of Facebook Friends</h2>
            <div ></div>
            <div id="fb-root" style="display:inline; margin-left:20px;"></div>

            <script type="text/javascript">
                //Initialize facebook SDK
                window.fbAsyncInit = function () {
                    FB.init({
                        appId: '470021713099348',
                        status: true, cookie: false, xfbml: true, frictionlessRequests: true
                    });
                };

                // All FB resources
                $(document).ready(function () {
                    if (document.getElementById('fb-root') != undefined) {
                        var e = document.createElement('script');
                        e.type = 'text/javascript';
                        e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
                        e.async = true;
                        document.getElementById('fb-root').appendChild(e);
                    }
                });

                // Send Invite to friends
                function sendRequestToRecipients(targetid) {
                    FB.ui({
                        method: 'apprequests',
                        message: 'Try Talentcubed.com',
                        description: 'Play Games Get Hired',
                        to: targetid
                    }, requestCallback);

                    //    method: 'feed',

                }

                function requestCallback(response) {
                    // Handle callback here
                    var uid = response['to'];
                    var link = $('#inv_' + uid);
                    link.removeAttr('href');
                    $("#img_" + uid).fadeOut();
                }
                $(document).ready(function () {
                    $("#btnSearch").click(function () {
                        window.location = '@Url.Action("Search", "Wall")' + "?id=people";
                    });
                });
            </script>

            <div id="ListFbFriends">
                <div class="signupsearchTop" style="display:none;">
                    <input name="signupsearch" id="signupsearch" type="text" size="18" maxlength="150" placeholder="search for" class="signupfield" />
                    <input type="image" src="/images/btnsearch.jpg" name="image" class="signupsearchbtn" width="24" height="21">
                </div>

                <ul>
                    @foreach (var Friend in ViewBag.FbFriends)
                    {
                        <li>
                            <div ><img src='@Friend.PicURLSquare' alt='Friends' /></div>
                            <div ><p >@Friend.FriendName</p></div>
                            <div >
                                <a href="javascript:sendRequestToRecipients('@Friend.FriendID');" id="inv_@Friend.FriendID">Invite</a>
                            </div>
                        </li>
                    }
                </ul>
                
            </div>

        </div>

    </div>
    <!--row clearfix end -->
</div>

Enjoyyyyy...... !!!!!!




1 comments:

Unknown said...

getting error like this code is not working ..

Facebook.FacebookOAuthException was unhandled by user code
HResult=-2146233088
Message=(OAuthException - #12) (#12) fql is deprecated for versions v2.1 and higher
Source=Facebook
ErrorCode=12
ErrorSubcode=0
ErrorType=OAuthException
StackTrace:
at Facebook.FacebookClient.ProcessResponse(HttpHelper httpHelper, String responseString, Type resultType, Boolean containsEtag, IList`1 batchEtags)
at Facebook.FacebookClient.Api(HttpMethod httpMethod, String path, Object parameters, Type resultType)
at Facebook.FacebookClient.Get(String path, Object parameters, Type resultType)
at Facebook.FacebookClient.Get(String path, Object parameters)
at facebookLoginMVC.Controllers.PeopleController.GetFriends(String accessToken, Boolean isUsing) in d:\googleapi\Authentication\Authentication\fb\facebookLoginMVC\facebookLoginMVC\Controllers\HomeController.cs:line 161
at facebookLoginMVC.Controllers.PeopleController.ListFacebookFriends(String id) in d:\googleapi\Authentication\Authentication\fb\facebookLoginMVC\facebookLoginMVC\Controllers\HomeController.cs:line 134
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3d()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.b__3f()
InnerException:

Post a Comment


                                                            
 
Design by Abhinav Ranjan Sinha