Current Article
Industry Buzz
Social Networking
Featured Articles
Browse Content >
Back to Home

How to Retrieve User Data from Facebook Connect in ASP.NET

Bill Konrad
In this article, we will bridge the gap between Facebook Connect and retrieving user data using the Facebook Developer toolkit. A useful class is included for download that simplifies the process and reduces the work to just five lines of code!

Introduction & Prerequisites

In previous articles we have focused on integrating with Facebook Connect and authenticating using the most recent version of the Facebook Developer Toolkit, version 2.0. Please review the following two articles before continuing if you are unclear on either of these processes.

How to Integrate with Facebook Connect - Bill Konrad
How to Use the Facebook Developer Toolkit 2.0 - Bill Konrad

Assuming that you have read/understand both, this article is the next logical step. We are going to examine how to connect to the Facebook API using the Facebook Developer Toolkit 2.0 when a user successfully authenticates with Facebook Connect from your 3rd party site. While the process is not complicated, it does require a bit of trickery. So let's dive right in!

Getting Started

We are going to use the barebones project we created in How to Integrate with Facebook Connect for the basis of this project. Listed below is Default.aspx which will serve as our only .aspx page.

Default.aspx

<%@ page language="C#" autoeventwireup="true" codefile="Default.aspx.cs" inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head runat="server">
    <title>Facebook Connect & Facebook Developer Toolkit 2.0</title>
</head>
<body>

    <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php"
        type="text/javascript"></script>

    <form id="form1" runat="server">
    <div>
        <fb:login-button length="long" onlogin="window.location.reload()">
        </fb:login-button>
        <br />
        <br />
        Name captured from Facebook Connect:
        <asp:label id="lblName" runat="server" text="Not authenticated."></asp:label>
    </div>
    </form>

    <script type="text/javascript">
        FB.init("8a4e7b49b58938fdda19230224389297", "xd_receiver.htm");
    </script>

</body>
</html>
        

There are only two items here that have changed since the original Facebook Connect tutorial.

First, I have hooked in to the onlogin event with a quick JavaScript call to "window.location.reload()". What this essentiallyl states is "when a Facebook Connect user successfully authenticates, reload the current page." We do this so that our code behind file can capture the result and use that data to connect to the Facebook API using the Facebook Developer Toolkit. We'll see more on this later in the article.

The second is the asp:Label that I have added to display the full name of the successfully authenticated user.

Capturing the Facebook Connect Authentication Results

The key to this article is understanding the next few steps. When a user authenticates through Facebook Connect, a collection of cookies are set in the browser of the client. They are as follows.

APIKEY_user
The user ID of the currently logged in user.
APIKEY_session_key
The current session. This is used to make API requests.
APIKEY_expires
When the current session expires. This is usually an hour or two after it's granted. If it's 0, then it means the session does not expire.
APIKEY_ss
The session secret. This prevents someone who knows your session key from using the session.
APIKEY (with nothing after it)
The signature, which will be generated from all other parameters.
fbsetting_APIKEY
The last cookie is not related to the signature validation (which is why it does not start with the APIKEY prefix). It is used to cache the login state between page loads, so that the XFBML rendering does not have to wait for a round trip to Facebook before starting.


The first two cookies listed here, APIKEY_user and APIKEY_session_key are the two we will primarily concern ourselves with. Let's take a look at the class ConnectAuthentication which I created to automate the process. Note, this class is based on ideas sourced from around the web in addition to my own ingenuity!

public class ConnectAuthentication
{
    public ConnectAuthentication()
    {

    }

    public static bool isConnected()
    {
        return (SessionKey != null && UserID != -1);
    }

    public static string ApiKey
    {
        get
        {
            return ConfigurationManager.AppSettings["APIKey"];
        }
    }

    public static string SecretKey
    {
        get
        {
            return ConfigurationManager.AppSettings["Secret"];
        }
    }

    public static string SessionKey
    {
        get
        {
            return GetFacebookCookie("session_key");
        }
    }

    public static int UserID
    {
        get
        {
            int userID = -1;
            int.TryParse(GetFacebookCookie("user"), out userID);
            return userID;
        }
    }

    private static string GetFacebookCookie(string cookieName)
    {
        string retString = null;
        string fullCookie = ApiKey + "_" + cookieName;

        if (HttpContext.Current.Request.Cookies[fullCookie] != null)
            retString = HttpContext.Current.Request.Cookies[fullCookie].Value;

        return retString;
    }
}
    

Rather than go into the nitty gritty details of how this works, let's take a look at how this class gets used to create the link between Facebook Connect and the Facebook Developer Toolkit. Below is a complete listing of Default.aspx.cs which contains the magic.

using System;
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 facebook.web;

public partial class _Default: System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (ConnectAuthentication.isConnected())
        {
            API api = new API();
            
            api.ApplicationKey = ConnectAuthentication.ApiKey;
            api.SessionKey = ConnectAuthentication.SessionKey;
            api.Secret = ConnectAuthentication.SecretKey;
            api.uid = ConnectAuthentication.UserID;
            
            //Display user data captured from the Facebook API.
            
            facebook.Schema.user user = api.users.getInfo();
            string fullName = user.first_name + " " + user.last_name;

            lblName.Text = fullName;
        }
        else
        {
            //Facebook Connect not authenticated, proceed as usual.
        }
    }
}
    

Just like a normal ASP.NET page lifecycle, we tap into the Page_Load event handler. By calling ConnectAuthentication.isConnected() we quickly check to see if a Facebook Connect user is currently authenticated. Then, taking a page out of How to Use the Facebook Developer Toolkit 2.0 we set a collection of attributes on the API object to let the Facebook API know who we are. We are now fully connected! Not too bad, huh?

The rest is just to demonstrate to ourselves that we have actually connected to the API. A quick call to api.users.getInfo() pulls down some profile data. We set our asp:Label's text value to the full name of the authenticated user, and we are done.

As is relatively self explanatory, the else statement here should contain any standard Page_Load processing not pertaining to the Facebook API.

Conclusion & Next Steps

At this point, we have retrieved user data from the Facebook API based on user and session data from a successful Facebook Connect authentication. There is no limit to what can be accessed using the Facebook Developer Toolkit, so we essentially have a full blown Facebook app in our third party site.

There is one piece of this that we are missing, and that is verifying the incoming signature. While this is not particularly difficult, it gets a bit technical, and is better suited to a new article. I'll follow up on this topic soon, and we'll lock out the bad guys in style. Until then, go nuts, and enjoy your newly socially leveraged web app!

Share Article

User Comments

Gravatar
Bill Konrad
3/1/2009
Readers:

We wrote this article as a means of diving into the large and wonderful world of Facebook Connect + Facebook Developer Toolkit. Where do you want to go from here? Give us some feedback to guide new content!

Thanks,

Bill Konrad
Gravatar
Marat
3/3/2009
Hi Bill,

Great article! When is the article about verifying incoming signature is going to be posted?

Thanks,

Marat
Gravatar
Mike Pesch
3/3/2009
I second Marat's comment and question. These instructions are great, but it's difficult to proceed without verifying the incoming signature, and I can't find anything built into the .net developer toolkit to handle it.
Gravatar
tariq Sheikh
3/4/2009
i did manually setting ur toolkit not apper in vs2008 sp1
Gravatar
M.Sunil Kumar
3/18/2009
Hi, I developed this application using Vs.Net 2005. I m unable to connect to FaceBook Apis through this interface.
Gravatar
Jamie
3/18/2009
Nice work, but is there any way to avoid putting the api key and secret in the web.config?

I'm hsoting various websites, and I want to give my users the option with the modules I'm developing to use their own application details.
Gravatar
Bill Konrad
3/20/2009
Jamie,

Yes, there is an easy way in fact. If you look at my ConnectAuthentication class under the two parameters ApiKey and SecretKey, you will see that they are being pulled from ConfigurationManager.AppSettings. If you modify these get methods to pull the ApiKey and SecretKey from your own personal location, then you can let your users specify these parameters.

Let me know if that confuses you.

Bill
Gravatar
Marat
3/21/2009
Bill,

can you show some sample code on how to publish to user news feed using the .net facebook API?

thanks
Gravatar
jan
3/22/2009
Bill thanks for these great articles!

As Marat, I'd also be very interested in finding out how to publish to user's wall and news feed from the toolkit :-)
Gravatar
Ross
3/23/2009
As a .net developer I can't thank you enough for your articles. They have been hands down the most helpful resource I have found so far.

It looks to me like fb has deliberately designed the login process so you can't store a fb username and password in your own database in order to authenticate a user automatically. Is this the case?

Ideally I would prefer to allow users to link their fb account to the one on my site & automatically authenticate fb when appropriate, rather than having to ask each time.
Gravatar
Bill Konrad
3/23/2009
Ross,

First, thanks for the positive feedback. It's great to know that my writing is helping your apps get launched.

You are absolutely correct that Facebook designed it that way. They don't want to jeopardize that sensitive data. It makes sense, really.

Unfortunately, the upshot is that as far as I know, you can't automatically authenticate with FB upon login on your side. Facebook envisions it more as your users logging in with their Facebook account and then you automatically authenticating them with -your- system.

Let me know if that clarifies it for you.

Bill
Gravatar
Ross
3/23/2009
It does make sense & we may actually restructure our fb integration concept because of this.

I did however find that you can request "offline access" which creates an unlimited session. I believe that this could be used to achieve the account linking experience we were visualizing originally.

It is explained at the very bottom of the page here:

http://wiki.developers.facebook.com/index.php/Authenticating_Users_with_Facebook_Connect
Gravatar
Bill Konrad
3/23/2009
The user would have to sign off on this linking occurring, and as they note, it's not generally recommended. I'm not sure what the outcome would be, but in my opinion it's not a good approach.

Just my two cents.
Gravatar
Ross
3/24/2009
Off Topic:

Is it possible to set up visual studio to debug facebook connect apps locally? From what I can gather facebook authentication callback url's dont support the built in webserver for visual studio.

I can get my apps working on our public server but it would be enormously advantageous if I could debug prior to posting.
Gravatar
Bill Konrad
3/25/2009
Ross,

As far as I know, it's not possible/easy to get Facebook to interact with the localhost server. It's definitely a pain, but again, I'm sure it's for security reasons.

What I would recommend is that you set up an app at something like test.yourdomain.com and then run a second copy of your app behind some simple authentication. Facebook should allow you to use that address since the root domain is yourdomain.com

Have you tried this approach? Does it sound reasonable?
Gravatar
Alex
3/27/2009
I was able to get up visual studio to debug facebook connect apps by pointing the domain i was using to my local computer in the hosts file.

That way the cookies were set for both domains.

It seems to be working....
Gravatar
Ivan Camilo Vásquez
3/27/2009
Great article! we're planning to use facebook connect across all our websites, and this is a great start point.

As far as Alex comment, are you referring to the C:\WINDOWS\system32\drivers\etc\hosts file?
Gravatar
James Andrews
4/9/2009
You should say "where APIKEY is your facebook application APIKEY" It took about 15 minutes before the fog cleared and I understood what was going on.
Gravatar
zxed
4/18/2009
easy to follow...

Q: FB connect states that you a benefit of using connect is that you can be sure that the user has a valid email address... how do you pull that over? i didnt see the email address in the user schema... any idea?
Gravatar
Candi
4/25/2009
Bill - thanks so much for these posts. They've been extremely helpful. I'd like to see how to post to the user's wall and the friends wall.
Gravatar
Anup Marwadi
5/2/2009
Hello,
I was trying to figure out if there is a way we can use Facebook Connect and tie that in with the Membership Provider on ASP.net.

I have seen the OpenId implementations and don't know if the Facebook Connect can infact be used on the Membership API using the same approach. I may be wrong, but if you have any insights, I would highly appreciate them!

Here's what I think:
1. User logs in using Facebook Connect
2. We obtain user Id, check if a mapping exists for that user in the database.
3. If mapping doesn't exist, we use the personal information to create a new Membership Account (but we don't have email, password; password can be set to a random value since the user will ideally only login from Facebook?) Don't know how to deal with the Email.
4. If mapping exists, we just use it and then call the FormAuth.Setcookie method.

The issue is with Step 3.
Gravatar
mark
5/26/2009
A tutorial with an overview of how Facebook connect(.NET) and the Facebook API(php, javascript) are meant to be working together would be very helpful. Just the basic mechanics really.
Gravatar
Aruna
6/3/2009
Hi

We are trying to implement facebook connect to our website. Our website is implemented with asp.net 2.0 I couldn't find dll's for 2.0, these dll's are for 3.5 only. Could any oneplease tell me. Is it possible to implement facebook connect with asp.net 2.0.

Thanks in advance.
Gravatar
Arun
6/10/2009
API api = new API();
To create a object of API what namespace I need to add. I am using facebook 2.0 dll. but i am getting an error namespace API couldnot be added message. I am trying to use fb:Connect in ASP.NET. I am not getting how to retrieve facebook friends and group information in my application.
Gravatar
Andy
6/15/2009
Great article! Very useful.

when i call api.users.getInfo() it retrieves the basic data, but fields like birthdate and proxied_emails aren't coming back. Any ideas?

Gravatar
pxpilot
6/15/2009
Funny as it sounds everything works wonderfully for me except I can't get the user to logoff. I think it has to do with cookie cache, this is what i got so far, still no good. HELP!

string FbApiKey = ConfigurationManager.AppSettings["FacebookApiKey"];
string[] CookiesKeys = HttpContext.Current.Request.Cookies.AllKeys;
foreach (string CookieKey in CookiesKeys)
{
if (CookieKey.IndexOf(FbApiKey) > -1)
{
Response.Cookies[CookieKey].Expires = DateTime.Now.AddDays(-1);
}
}
API api = new API();
api.LogOff();
Gravatar
yudi
6/24/2009
hi thanks for the article. I'm still trying to figure out how would you authenticate a user using his facebook account against the asp .net membership provider authentication. creating fb connect cookies doesn't mean anything to the asp .net authentication system. anyone has any idea? we cannot create a user account to the membership provider since we don't have the email address. Is the only solution not using .net membership provider???
Gravatar
boss
6/28/2009
nice
Gravatar
Adam Creeger
6/30/2009
Hey Bill, Your wonderful article inspired me to create a tiny .NET component that takes care of this for you, and validates the signature too. Have a look at:

http://fbconnectauth.codeplex.com/

Hope someone finds it useful!
Gravatar
serv
7/4/2009
u rock mannnnnnnn
Gravatar
Hung.Nguyen
7/21/2009
I have tried your demo on my environment but I have some problems. When I click on the "Connect with Facebook" button, then login into with my Facebook account, I get a popup which says "
Under Construction
DNNFBLogin is under construction.
Note to application developers:
To fix this error, please set your Connect URL in the application settings editor. Once it has been set, users will be redirected to that URL instead of this page after logging in."

I checked the cookie and see that the cookies (APIKEY_session_key , APIKEY_user ...) don't exist on my browser.

I'm absolutely sure that I have replaced the API Key, Application Secret, Canvas Callback URL exactly and my browser works properly (allowing cookie too).I've been reading your tutorials very carefully but I don't understand why.

I've been googled and see that there're many developers encounter the same problem but without any solutions.
Please help me
Thanks in advanced

Gravatar
Hung.Nguyen
7/21/2009
I've tried to do all my development on my live site too, the Canvas Callback URL is "http://vietnam.krestondts.com.au", everyone can browse to the site from anywhere on the world, it's not just a local site.
It's weird that when I browse the site directly from local IIS, the site works well - login to the Facebook successfully, but it doesn't automatically reload (onlogin="window.location.reload()"). And then when I browse the page again , the site will be refresh and fill all the logined user's information exactly.
But the site doesn't work when I browse it from a browser (not reload and the cookies don't exists).
Gravatar
Hung.Nguyen
7/21/2009
Sorry all, I have mistaken between the Canvas Callback URL and the Connect URL. The Connect URL must be filled.
The sample has worked well. That's great.
Thanks a lot
Gravatar
Minh.Ha
7/22/2009
I want to login to Facebook from my web application but doesn't use the Facebook login button. For example login to Facebook by a backgound request URL. Is there anyone can tell me a solution ?
Thanks in advanced
Gravatar
Abhishek Gupta
7/27/2009
Hello,

I m getting error related to security exception on given below line.

facebook.Schema.user user = api.users.getInfo();

Here is error which comes:

Security Exception

Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.

Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Net.WebPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

I have windows 2008 server and running from http://XX.XX.XX.XX

If you have any idea then Please let me know.

Thanks In Advance.
Gravatar
puneet
7/28/2009
Bill,
Hi.

I tried to create the same example on my server and running into a problem. When i click on the facebook connect button, i get facebook login prompt in a popup window. The window does not close after i enter my facebook credentials into the window. it reloads the same page with fbconnect button in the popup window. what am i doing wrong?

Q: The fbapp needs to be fbml or iframe?

thanks
puneet
Gravatar
sean
7/31/2009
The isConnected() method will not be able to detect invalid session keys. The way I implemented it was to actually try using it. I have described a modification to it in http://my6solutions.com/post/2009/07/31/Facebook-Connect-Invalid-Session-Key-issue.aspx
Gravatar
Rajnikant
8/8/2009
Hello

Nice Article. It helps me to connect to facebook.
But I got problem when i try to get userinfo.

I tries this

API api = new API();
api.ApplicationKey = ConnectAuthentication.ApiKey;
api.SessionKey = ConnectAuthentication.SessionKey;
api.Secret = ConnectAuthentication.SecretKey;
api.uid = ConnectAuthentication.UserID;
//Display user data captured from the Facebook API.

facebook.Schema.user user = api.users.getInfo();

string fullName = user.first_name + " " + user.last_name;

I got this error

ystem.Security.SecurityException: Request for the permission of type 'System.Net.WebPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

Please help me.

Thanks in Advance

Rajnikant Rajwadi
Gravatar
Tuan Anh
8/12/2009
Thank you for your article! It's very helpful for me.
Gravatar
Massimo Barbieri
8/19/2009
Hi,
very nice job.

I got an error for some facebook users because UserID should be a long, non an integer, so some userIds are "unparsable" as integer because are too big.

I solved simply changing the property UserID to long.

I hope this help you and other readers too, bye and thank you.

Massimo Barbieri

--
www.massimobarbieri.it
Gravatar
Rich
8/25/2009
I am a noob. I still get the default text: Name captured from Facebook Connect: Not authenticated which means it's not connecting.

I've completed all three articles, but in the second one I left out the part where specified to remove the HTML markup and add the following to the codebehind:

protected void Page_PreInit(object sender, EventArgs e)
{
base.RequireLogin = true;
}


However, I did modify the web config and add the bin to the project.

Any help would be appreciated.
Gravatar
Josh
8/26/2009
With recent changes to the UserId length in Facebook, I needed to change the following function to:

public static long UserID
{
get
{
long userID = -1;
long.TryParse(GetFacebookCookie("user"), out userID);
return userID;
}
}

This fixed issues we were experiencing with new users with longer user ids.

Hope this helps,
Josh
Gravatar
Chacha DeJava
8/27/2009
Thanks again!
Gravatar
senthil
8/28/2009
hi Bill Konrad,

i am developing asp.net website there i am generating pdf and saved it in specified location,i want to publish that pdf link to facebook using facebook connect

how to achive this???????????????
Gravatar
mohamed batawy
8/30/2009
Hello Facebook admins.
I'm glad to e-mail you.
Please, i'm having a problem with my account.
Breifly, yesterday i was opening my account .... then after i wrote my e-mail & password, i had the message says that my account has been disabled.... Read More
And then i received an e-mail on my mail from Facebook saying that my account was disabled because of a missuse from me !!!!
I NEVER missused this account ... i just using it like everybody else on Facebook ... adding some apps , joininng groups , adding friends , confirming from friends , .... etc etc.
- I want to know why it was disabled ??
- How will i get it back ??
Please reply ASAP

Note:

I made my account on Facebook with this mail
undertaker_kane_210@yahoo.com
Gravatar
come on
9/6/2009
Totally fucking worthless article. Does not work. Thanks for nothing
Gravatar
Love Chopra
9/11/2009
Hi,
I am integrating Facebook Connect to my website but I am facing a problem here, please have a look on to it:-

- When I am logging in to my FB integrated website using facebook login id of application developer then I am able to get user info like first name, last name etc. but when I am logging in using facebook login id of user which is not the developer of application then I get user id as 0 from cookies however I get other info like session key, application id and secret key but not able to get user id and in this case when I am calling users.getInfo() method from my code it always return null.

Kindly help me on this regard as soon as possible.
I am awaiting for your response.

Gravatar
Sohail
9/18/2009
I have successfully connected and auth with facebook. But now i have to get the logedin user information like country, state, zip etc...
i am using

string country= user.hometown_location.country;
string postal = user.current_location.zip;
string gender = user.sex;
string dob = user.birthday_date.ToShortDateString();

But its giving me OBJECT REFRENCE IS NULL error, Please let me know how can i get rid of this??????????

please send me solution if possible on rmsohaila@hotmail.com

I shall be very greatful to you guys.
Gravatar
Harish singh
9/30/2009
change the property UserID to:-
public static long UserID
{
get
{
int userID = -1;

string uid = (GetFacebookCookie("user"));
long LngString = Int64.Parse(uid);
return LngString;

}
}
Gravatar
Chris
11/4/2009
I get a pop-up asking for facebook credentials, but the pop-up doesn't go away. It refreshes to my website. How do I close the pop-up and refresh my parent site?
Gravatar
Robert Wafle
11/28/2009
This is JUST the information I was looking for! Thanks!
Gravatar
pontaj
12/6/2009
When users login at my web site with fb connect, does some info of the user or a new user account (like a copy of the user's fb account) need to be stored in the database of my site? Or is this done by myself by fetching the user info and stuff during their first login and store it in my own defined db-tables?
Gravatar
Mohammad Ishak
12/17/2009
I have used this Coding for my project. But I got HttpContext.Current.Request.Cookies[fullCookie] is NULL only. So It could not create the link between Facebook Connect and the Facebook Developer Toolkit. Please Provide the Solution Imediatly.
Gravatar
Nishant Gauttam
1/11/2010
article is pretty good and helpful. but need to ask you one thing.I can get name, birthdate ,profile pic of user from userinfo but how can i get user's email..?
Gravatar
shahzad
1/11/2010
hi,
do anybody know how can i get email of facebook user on my asp.net page.
Gravatar
JimBeam
1/18/2010
This article needs to updated for the 3.0 version of the toolkit. Otherwise it is completely useless.
Gravatar
Rohan Perera
2/4/2010
I just starting looking at the Microsoft Facebook SDK Kit. My question is quite general.

I would like to use the FaceBook.Rest{}
methods to get data. I am have Windows Form and I am trying to make a call to one of these functions like Friends.get which gets the list ids of friends.


Do you have an example that can illustrate how to make this call or point me to some other documentation

Thanks
Rohan
Gravatar
Daniele & Giacomo & Poppe
3/4/2010
Please change the "public static int UserID" property with this else facebook connect not works:

public static long UserID
{
get
{
long userID = -1;
long.TryParse(GetFacebookCookie("user"), out userID);
return userID;
}
}

Bye bye.
Poppe.
Gravatar
Daniele & Giacomo & Poppe
3/4/2010
Please change the "public static int UserID" property with this else facebook connect not works:

public static long UserID
{
get
{
long userID = -1;
long.TryParse(GetFacebookCookie("user"), out userID);
return userID;
}
}

Bye bye.
Poppe by italian developer.
www.teamdev.it
Gravatar
Dennis
3/16/2010
Hello,

Does anyone know what user data can be saved or cannot be saved on my website database if I use fbconnect?

I've been searching this on the net and I cant seem to find any info about it.

Thanks!
Gravatar
Ravi Solanki
3/17/2010
Hi,
I try to use this code but getting a problem while I access this.
VS shows this error " The type or namespace name 'web' does not exist in the namespace 'facebook' (are you missing an assembly reference?)".

can you please help me?
Gravatar
Peter
3/22/2010
I get 2 error messages when using the above code:

If ConnectAuthentication.isConnected() Then
Dim api As New API()
ERROR: Type 'API' is not defined.

api.ApplicationKey = ConnectAuthentication.ApiKey
api.SessionKey = ConnectAuthentication.SessionKey
api.Secret = ConnectAuthentication.SecretKey
api.uid = ConnectAuthentication.UserID

'Display user data captured from the Facebook API.

Dim usr As Facebook.Schema.user = api.users.getInfo()
ERROR: 'user' is ambiguous in the namespace 'Facebook.Schema'.

Dim fullName As String = (usr.first_name & " ") + usr.last_name

lblName.Text = fullName
Else
'Facebook Connect not authenticated, proceed as usual.
End If


What can I do?
Gravatar
yagnesh
3/29/2010
Hi,

I want to post comment to Face-book users Photo Album and Photo.

I want to achieve this in ASP .Net.

I have downloaded all the tool kit and other required DLL. Please any one can provide me sample URL or Code that can help me for achieving this task.

Thanks
Gravatar
ss
7/11/2010
sdaf
Gravatar
nidhi
7/22/2010
hi
i want to fetch wall messages through facebook apis in c#....
is it possible .
please reply...
Gravatar
jameel
7/22/2010
hi
iam getting invalid signature
Facebook.Schema.user user = api.Users.GetInfo();
Gravatar
jameel
7/22/2010
hi bill

iam getting Incorrect signature
error in
Facebook.Schema.user user = api.Users.GetInfo();
Gravatar
Mihai
8/11/2010
I have a quick question ?
If I want to disconnect, how to I remove the facebook cookies ? I can't seem to be able to delete them.

Thanks
Gravatar
test
8/11/2010
sddsdsd
Gravatar
sreenivas
8/11/2010
I have a quick question ?
If I want to disconnect, how to I remove the facebook cookies ? I can't seem to be able to delete them.

Thanks
Gravatar
Prokopis
8/11/2010
Compiler Error Message: CS0246: The type or namespace name 'Api' could not be found (are you missing a using directive or an assembly reference?)

API api = new API();

on this line i get this error.what API i have to include?
Gravatar
Shashank
9/7/2010
HI,

It seems that many people are facing the same issue, I'm unable to run the application as it gives the error on following line...

API api = new API();

the error message says "The type or namespace name 'API' could not be found (are you missing a using directive or an assembly reference?)"

Please, its really urgent and killing me down.

Also if I remove the

<%@ Page Language="C#" .....

line, then its not possible to use the controls defined on aspx markup in code behind as there is no linking of the aspx page to its code behind cs file.

Please Help.
Gravatar
shahin
9/30/2010
Great!!!!!!
how i retrieve all photo from my facebook contact list?
Gravatar
Easton
10/15/2010
Is anyone supporting this forum anymore?

API api = new API();

doesn't exist anymore? Any updates?
Gravatar
GIO
10/25/2010
FGDSGDS
Gravatar
teguh
10/25/2010
pliss can you help me
Gravatar
Dofs
10/31/2010
Easton: look at the documentation and use this instead:

private ConnectSession _connectSession;

_connectSession = new ConnectSession(APPLICATION_KEY, SECRET_KEY);

Api _facebookAPI = new Api(_connectSession);
Gravatar
Vic
11/27/2010
Dofs:

If I use as you suggest
Api _facebookAPI = new Api(_connectSession);

I get following error

Compiler Error Message: CS0118: 'Facebook.Web.CanvasFBMLBasePage.Api' is a 'property' but is used like a 'type'

Gravatar
billy
12/1/2010
37. public static int UserID
38. {
39. get
40. {
41. int userID = -1;
42. int.TryParse(GetFacebookCookie("user"), out userID);
43. return userID;
44. }
45. }

If usrid is too long to conveted to int type,the user.getinfor() will return null,just change int to long.
Gravatar
Krishna
12/3/2010
Hi,

Its really useful and working article.
We can get all the basic information of facebook user by using api.users.getInfo() except email id? I need to use email id the register in my system? is there any way or do you have any idea how to get email id? please reply me back asap.

Thanks in advance.
-Krishna
Gravatar
Buy Facebook Apps
12/6/2010
Informative article for me--- And you define the process step by step.I hope all of them understand
Gravatar
wordpress programmer
12/28/2010
Hi..,

This is a really best post..

Thanks..,
Gravatar
Nayab Altaf
12/31/2010
yes i like it
Gravatar
Arun
1/5/2011
I may be a bit late here - Regarding the security exception which is being throws is a known bug in ASP.net 4.0. This happens when you call ConfigurationManager.GetSection("facebookSettings"); and the website is hosted on a shared location.

The workaround - create your own class which implements IFacebookSettings and use that during initialization of your FBApp object


Dim FBSettings = New FBSettings 'my own object
Dim FBApp As New Facebook.FacebookApp(FBSettings)
Gravatar
vipin
1/21/2011
Hello sir,

I want to display our site EmailAddress and phone number. How can do it this show emailaddress and phonenumber

Please help me
Gravatar
gabriel
2/16/2011
can this be done using yahoo or google?
Gravatar
sangeeta
2/20/2011
hi all..
well using the code suggested above the problem of session key has been resolved..

bt its causing one more problem..
when i first clicks on log in button it does not display the canvas page, its displays the page again with login button , now if i clicks the login button again this time it displays the login button..

on debugging i found that even though i m connected to facebook it gives session key and user and userid as null on first click..
whileon second time click it gives session n user id..

y so??
any solution?

i m using old fbconnect class and API..
Gravatar
Chad
2/21/2011
I also can't get the users email address and that is really the only thing stopping this from working great... Any way of doing this yet?

-Chad
www.datasprings.com
Gravatar
godwin
4/5/2011
Is it possible to save UID's in a database then retrieve user info, like photos and names, using these id's, then display it like a list of FB users who are registered n my website?
Gravatar
Sandeep
4/9/2011
can we pass FB username and password through facebook api and get logged in?

sandeep
www.swayamsoft.com
Gravatar
FUNDOO
4/18/2011
for more info about the topic visit http://freefundoo.com
Gravatar
Kritika
4/19/2011
Hey

thanx to share such a great post..

Gravatar
Lucas W
4/26/2011
Hi

I'm also experience the compilation error where the Api is a property but is used as a type error:

############################################################

Compiler Error Message: CS0118: 'Facebook.Web.CanvasFBMLBasePage.Api' is a 'property' but is used like a 'type'

Source Error:

Line 26: if (ConnectAuthentication.isConnected())
Line 27: {
Line 28: Api api = new Api();
Line 29:
Line 30: api.ApplicationKey = ConnectAuthentication.ApiKey;

############################################################

Anyone know why?
Gravatar
Ritesh
5/2/2011
Hi...
when i use this code... i got following error message... please help me...

API api = new API();
To create a object of API what namespace I need to add.i am getting an error namespace API couldnot be added message. I am trying to use fb:Connect in ASP.NET.
Gravatar
Jayesh
5/26/2011
API api = new API();

This line gives me missing directive or assembly reference error. The type or namespace could not be found.I have placed the binaries as well. Any idea??
Gravatar
Ankit
5/31/2011
API api = new API();

This line gives me missing directive or assembly reference error. The type or namespace could not be found.I have placed the binaries as well. Any idea??
Gravatar
bijesh
6/23/2011
API api = new API();

This line gives me missing directive or assembly reference error. The type or namespace could not be found.I have placed the binaries as well. Any idea??
Gravatar
purav
6/28/2011
hi,

i want to take username and password of the FB user and store in my Database.is it possible ??

please help me its too urgent.
Gravatar
Joe
7/7/2011
Would like to know how I can retrieve the email?
Thank u. Joe
Gravatar
Niand
7/13/2011
API api = new API();
To create a object of API what namespace I need to add. I am using facebook 2.0 dll. but i am getting an error namespace API couldnot be added message. I am trying to use fb:Connect in ASP.NET. I am not getting how to retrieve Facebook user email and group information in my application.
Gravatar
addypam
8/16/2011
nice post
http://www.eugenerics.com/
Gravatar
seotamana
8/22/2011
Tuscany Holidays
http://www.tuscanyholidayvilla.com/
We offer selective tuscan holiday homes and rental villas in tuscany which make your holidays in tuscany perfect and memorable.
Gravatar
seotamana
8/22/2011
Patio Furniture
https://www.jatifurnitureusa.com/
Outdoor &amp; Indoor Furniture - Free Shipping - Lowest Price &amp; Satisfaction Guaranteed - Chairs - Tables – Loungers – Dining Sets - Benches - Sofas - Teak | Wicker | Rattan.
Gravatar
kevin
8/23/2011
just not working
Gravatar
Johnny
9/5/2011
nice article... any thing for twitter as well ?

johnny
www.satuindonesia.com.au
Gravatar
rj
9/8/2011
21
Gravatar
Sandeep
9/8/2011
I am getting error while accessing users photo. Its working fine for old users. But not for new users.
Error is
Session has expired at unix time 1315504800. The current unix time is 1315540206.

Facebook not using Developers API key any more. and now API ID is numeric. and that causing problem, I think

Thanks.
Sandeep
Gravatar
TulasiRam
9/13/2011
It was Great.....

My Qustion Is...
is there any way to log out user account from facebook and how to get log in user mail ID?

thanks in advance
Gravatar
e- commerce
9/19/2011
Its really great post...I appreciate your post..thanks for discussing with us..!!About facebook..i used your structure...thanks alot
Gravatar
AHMAD ALI
9/21/2011
helap
Gravatar
AHMAD ALI
9/21/2011
hello
Gravatar
aniruddha
10/3/2011
i m using facebook.dll version 2.0 and able to retrive user name and photo through following code. but i m unable to retrive his mailid, mobile no. and current location. how to do this?

Code:

if (ConnectAuthentication.isConnected())
{
API api = new API();

api.ApplicationKey = ConnectAuthentication.ApiKey;
api.SessionKey = ConnectAuthentication.SessionKey;
api.Secret = ConnectAuthentication.SecretKey;
api.uid = ConnectAuthentication.UserID;

//Display user data captured from the Facebook API.

PanelRegister.Visible = true;

facebook.Schema.user user = api.users.getInfo();
string fullName = user.first_name + " " + user.last_name;

txtname.Text = fullName;
txtemail.Text = ""; ???
txtmobile.Text = ""; ???
txtlocation.Text = ""; ??
FBImage.ImageUrl = user.pic_square;
}
else
{
//Facebook Connect not authenticated, proceed as usual.
}
Gravatar
Subhash Solomon
10/8/2011
Thanks Bill. A special one to all those selfless developers who shared their tips and solutions in the comments following the article. Gratitude.
Gravatar
Carlos
10/9/2011
muito giro
Gravatar
Eng.Walaa
10/10/2011
thanks for your effort, but it works for one time with me and doesn't work again and works again when i move it to page only for it(means page contains only connect button) and never work with me in other page.
i need your opinion in this issue and why this happen and if you have solution for that
Gravatar
nr
10/22/2011
Great article...
Except that, I couldnt understand what this line of code is

API api = new API();

can anybody help/assist in this.

Thanks in advance
Gravatar
sparkklets
11/8/2011
i have written this code
protected void Button1_Click(object sender, EventArgs e)
{
// Label1.Text = FacebookLogin();

if (ConnectAuthentication.isConnected()==true)
{
Label3.Text = "the user is connected";
}
else
{
Label3.Text = "the user is not connected";
}
}

No matter the user is logged on or logged of it always go to else block
Gravatar
Mark
11/10/2011
This is a cool trick, i just tested it out, it works perfectly, thanks for this hope to see more tips!
http://www.youtube.com/watch?v=kYKYkwaqevY
Gravatar
Marcelo Cavalini
12/27/2011
Can I translate your post to portuguese and publish in my blog, http://cavas.com.br
with your credits?
Gravatar
yogesh
1/9/2012
API api = new API();

This line gives me missing directive or assembly reference error. The type or namespace could not be found.

please help me it's urgent
Thanks in advance
Gravatar
Matthew Oh
1/18/2012
To all who have API class issue:
You need to reference the correct dll files.
facebook.dll, facebook.web.dll, and Microsoft.Xml.Schema.Linq.dll. (facebook.dll file version was 2.0.0.0, the link to these dll were wrong in this webpage.) Note that facebook.dll is lower f not capital F. I could find the correct dlls from somewhere like demo & source.

Newer version of C# SDK 5.4.1 uses new Facebook.dll etc. (It doesn't use API anymore. I couldn't make it work at the moment. I will just use this old dll for a while)

VB.net source code will be like the following.

Dim fbConn As New ConnectAuthentication()
If fbConn.isConnected() Then
'Display user data captured from the Facebook API.
Dim _api As New API
With _api
.ApplicationKey = fbConn.ApiKey
.SessionKey = fbConn.SessionKey
.Secret = fbConn.SecretKey
.uid = fbConn.UserID
End With

Try

Dim _user As facebook.Schema.user = _api.users.getInfo()

tbShow.Text = "autheciated"
lblName.Text = "hi " + _user.first_name & " " & _user.last_name
lblFullCookie.Text = fbConn.ApiKey & ";" & fbConn.SecretKey & ";" & fbConn.UserID
imgProfilePic.ImageUrl = String.Format("https://graph.facebook.com/{0}/picture", fbConn.UserID)

Catch ex As Exception
lblName.Text = "user logout need to be considered!"
tbShow.Text = fbConn.SessionKey & ";" & fbConn.UserID
End Try
Else
'Facebook Connect not authenticated, proceed as usual.
End If
Gravatar
Sahil
1/23/2012
I want to display my Facebook' first 10 wall posts on asp page.I am trying asp repeater. Help me to work on this task.
Gravatar
Anonymous
2/28/2012
This code is old and useless.
Gravatar
Naveen Sharma
2/29/2012
Hey friends,

I want to use F-Connect on my website www.sexyGirlsRocking.com. But, I made that website in asp.net using vb.net 2008; please guide in the way.

Thank you so much in advance.

Naveen Sharma
Gravatar
ram
3/5/2012
i hot error at this line
plz explain Api api=new Api();
??????????????
Gravatar
bless
3/7/2012
Nice one
http://www.cheapseoservices.co.uk
Gravatar
Dharmesh
3/10/2012
Blah.. blah.. Blah...

Not working..Not working...Not working

Request you to reply on people question, please post sample code, if you think this code is working other wise remove this.

You are wasting people time
Gravatar
Rakesh
3/14/2012
i have done all the step you have described. but i am not able to get the simple first name of user after log in.

it showing me a FBConnect button when i click on this it ask for login if i m not logged in FB. when i login through that popup. it only refreshes the page.

the .IsConnected() method is always returning false value. it not creating sessionkey i my app.

i have written the code in asp.net using C# in VS2005.

Thanks in advance
Gravatar
Rakesh
3/14/2012
i have done all the step you have described. but i am not able to get the simple first name of user after log in.

it showing me a FBConnect button when i click on this it ask for login if i m not logged in FB. when i login through that popup. it only refreshes the page.

the .IsConnected() method is always returning false value. it not creating sessionkey i my app.

i have written the code in asp.net using C# in VS2005.

Thanks in advance
Gravatar
saqib
5/14/2012
how to get email Id and Contact information after log in
Gravatar
hcetiner
6/17/2012
would you mind updating this code for latest facebook SDK (v6) ?

because your example seems outdated.

Gravatar
german
6/20/2012
muy bueno!
Gravatar
deepesh
9/25/2012
how to import my all facebook friend's email id to my asp.net website. Please guid me. I did with profile image and name but could'nt with email ids. If you can give me entire code.
Gravatar
Nikhil
1/15/2013
hi i didn't recognise

API api = new API();

What is API in this

Please help


Regards,
Nikhil
Gravatar
mohit jain
5/8/2013
hello friend i am in big problem.i read many many tutorial of facebook login.
i do successfully login with facebook
.and shown photo with names.but are to unable to retrive userdata such as name,date of birth,emailid.
pls help me.
pls help me.
9812777864
Gravatar
sathis
7/8/2013
How do i get facebook feeds??
Please give a idea.....
Gravatar
mohit jain
8/17/2013
i successfull login with facebook login but problem with to store user data.
pls help me.
9811313652
Gravatar
jonathan_200975@yahoo.com
8/23/2013
thanks
Gravatar
jason
10/26/2013
Is it possible to authenticate (having enduser login/signup) on my site with fb but also request that they enter in there zip code. I want to be able to let the user log in via Facebook but also want to collect there zip code that they can manually put in.
Gravatar
assa
12/2/2013
sk;ljsdf
http://www.devasp.net/net/articles/display/1408.html
Gravatar
ahmed
1/16/2014
API ?? not defined
what is API ?
'API' couldn't be found ??
Gravatar
sitaram kumawat
5/27/2014
hello sir
Gravatar
sitaram
6/17/2014
hello sir good afternoon
Add a Comment

Name

Email Address

1 + 1 = ?

Comment










iphone application development konrad group
android application development konrad group
windows phone 7 development konrad group