The Facebook team launched a Facebook API client in c#, but this library doesn’t give any functionality to Receive the access token for the API which is required to request authenticated information of a user. So, c# developers of Facebook API can use this library only for public information retrieval and need to implement their ways to retrieve the access token before requesting authenticated information. To make this process a little easier for beginners in the Facebook platform, I am going to illustrate an easy way to retrieve the Facebook c# API access token here with code examples and step-by-step instructions:
When do We Need this Access Token?
I am assuming that you already know about registering a new Facebook application. After registering you will receive a few codes named ‘App ID’,’API Key’ and ‘App Secret. With these, you will be able to start using Facebook API and make calls to Facebook API for any kind of public data. You will need to get the access token only when you intend to access some private data for a user. Then, the user will have to allow your application for usage, which will give you access to his private data, the access token is the key to that door.
Optional Customized Facebook Class:
Here I am going to make use of my two custom classes. One is MYWebRequest, which I have discussed before while showing the way of creating http request using c sharp; Another is MyFB, a simple class that utilizes Facebook C# API library and meet my custom needs 🙂
You can get the code snippet of MyWebRequest class from the related post linked above, and here is the code sample for the MyFB class, which you can also use by enhancing/extending for your custom needs:
publicclassMyFB{
private FacebookAPI myFBAPI;
private string appId;
private string apiKey;
private string appSecret;
#region Application Settings Properties/// <summary>/// Get And Set Application ID/// </summary>public String ApplicationID
{
get
{
return appId;
}
set
{
appId = value;
}
}
/// <summary>/// Get And Set API Key/// </summary>public String APIKey
{
get
{
return apiKey;
}
set
{
apiKey = value;
}
}
/// <summary>/// Get And Set Application Secret/// </summary>public String ApplicationSecret
{
get
{
return appSecret;
}
set
{
appSecret = value;
}
}
/// <summary>/// Get And Set Access Token/// </summary>public String AccessToken
{
get
{
return myFBAPI.AccessToken;
}
set
{
myFBAPI.AccessToken = value;
}
}
#endregion//Constructorpublic MyFB()
{
myFBAPI = new FacebookAPI();
}
public String GetMyName()
{
try
{
JSONObject me = myFBAPI.Get("/me");
return me.Dictionary["name"].String;
}
catch(FacebookAPIException err)
{
return err.Message;
}
}
public String GetAccessToken(string code)
{
//create the constructor with post type and few data
MyWebRequest myRequest = new MyWebRequest("https://graph.facebook.com/oauth/access_token", "GET", "client_id=" + this.ApplicationID + "&client_secret=" + this.ApplicationSecret + "&code=" + code + "&redirect_uri=http:%2F%2Flocalhost:5176%2F");
string accessToken = myRequest.GetResponse().Split('&')[0];
accessToken = accessToken.Split('=')[1];
return accessToken;
}
}Code language:PHP(php)
Redirect to Facebook to allow access:
To allow access, Facebook requires you to redirect the user to the Facebook page(given Facebook API documentation) where the user is asked to allow his private information access to the application. And then return to the application with a reply code, which is later can be used to retrieve the access token.
(My code is from a sample asp.net MVC application’s controller function. Make the tweak to fit yours if you are using another type of application. Also, I have tested the application on my local visual studio asp.net server, for which I am using a local host as my application domain; you should change that to your domain.)
Here, on the above code sample, the structure of MySettings class is being created from the idea of my other article on storing application settings using c#, so either go through that to get a clear idea and use the best practice, or you can hard code the setting’s value for now for testing quickly. First, we are checking for the ‘code’ variable value from the URI string as after returning from Facebook authentication, it redirects to our given URL with added the code as part of the URL. Initially, when the application starts to launch it’s empty, so the ‘code’ value will be null and the if condition will become true, and then the application will redirect the user to the Facebook OAuth URL for permission to grant access.
Last One More Internal Request To Facebook:
After the user accepts and allows the application to access private data, the application will redirect including the code value. This time that value will be valid non-null and the “else” block will be executed. There all settings are served to the MyFB class instance and the ‘GetAccessToken’ method is being called, which in turn creates a GET Request to Facebook along with the code value for an access token, then facebook returns a string containing the access token and its expiation duration. By parsing that string the method returns the access token(it can also be set directly to the class’s access token variable instead of returning, do it if you are interested in using it with some other class’s also). After it, we are set up completely to make the authenticated requests. Here I have used the simple ‘/me’ request and from the result, the user’s name is shown.
Note For Desktop Application Developers:
If you are creating a .NET desktop application using Facebook API, you will have to do things a little differently. Please, read the official Facebook notes for desktop application authentication. Also, you will have to be familiar with a web browser For WPF or WebBrowser For Windows Forms, depending on which desktop-type application you are creating. You will need to pass 2 more parameters in the URL when pop-up the URL in your application with web browser control, which is “type=user_agent&display=popup” that will directly send the access token back without the need for another extra request that is needed in the web application.
I hope this tutorial will help you to get started; let me know by commenting if you have any questions. Also, to know more about Facebook c#, please read my other article about getting started with facebook graph api in c# . Happy coding 🙂
Can you please share your line of code that you are using while making the mywebrequest class please? Was it seen as a valid url while debugging? Also, have you tried that url directly in the browser what it returns? For valid url, the returned respose should include a valid access token and expiration timestamp.
Your post is really great help. i have created new test asp.net web application. In my test application i have added reference of FacebookAPI.dll, created one class file ‘MyFB’. in this class file i have pasted your code given in this article.
i am getting build error “FacebookAPI is a ‘namespace’ but used like a ‘type'” i am pasting starting few lines of code of my class ‘MyFB.cs’
using System.Web;
using FacebookAPI;
using FacebookAPI.Managers;
using FacebookAPI.Objects;
using FacebookAPI.FacebookProperties;
1:namespace test
2:{
3: public class MyFB
4: {
5: private FacebookAPI myFBAPI;
6: private string appId;
7: private string apiKey;
8: private string appSecret;
…..
……
…….
}//class end
}//namespace end
at line no 5 i am getting error… i am not getting where i am missing something.
Hi Rana. Thanks for putting together this article. I’ve researched a few ways to integrate Facebook within my web site, and I feel that going that going with the Facebook C# API is the way to go.
Unfortunately, I’ve come across a problem that I haven’t been able to figure out.
I’ve implemented your MyWebRequest class and when I hit the line
dataStream = request.GetRequestStream();
I receive a ProtocolViolationException with the message “Cannot send a content-body with this verb-type”.
I’m not receiving the ProtocolViolationException error any more, but I am receiving a 400 error from Facebook’s server. I think that’s an improvement, but not 100% sure yet.
One thing to note is that the redirect_uri parameter has a port number in it (http://localhost:57260/), but this matches my Site URL in
the Facebook app settings.
In your example “Redirect to Facebook to Allow Access”, you note the redirect path to be: “https://graph.facebook.com/…” It should be https://WWW.facebook.com. Otherwise it you receive an webpage cannot be found error.
I found a complete tutorial on developing facebook application with facebook Graph API with OAuth 2.0 here .. May be of help to someone .. Must visit .. http://www.facebooksdk.blogspot.com/
I am wondering if the following is possible or not! hope someone can help!
From a particular website page I would like to offer a log in with your facebook account. After the ‘allowing’ I would like to redirect that person to the webpage where he came from (read this can be from hundreds of different pages). Would it be possible to redirect to the starting webpage after the authentification?
I want to create a service using c# for getting access token social login provider like facebook, twitter etc and i want to check login status of every login provider by service every 5 minutes. Plz tell me solution for this.
I am facing several problems trying to implement the facebook access code. I am allowed access to my app, but I can’t get passed the fb.getaccesstoken function. It gives me this error:
Cannot send a content-body with this verb-type.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type.
Source Error:
Line 62:
Line 63: // Get the request stream.
Line 64: dataStream = request.GetRequestStream();
Line 65:
Line 66: // Write the data to the request stream.
@Fernando Linhares
you have the code that fb sends you but using that you are not able to get the access token. is that the case? if so, the following might help you.
//catch the code sent by fb
var fb_code = Request.QueryString[“code”];
i have this error:
Server Error in ‘/’ Application.
Cannot send a content-body with this verb-type.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type.
Source Error:
Line 56: request.ContentType = “application/x-www-form-urlencoded”;
Line 57: request.ContentLength = byteArray.Length;
Line 58: dataStream = request.GetRequestStream();
Line 59:
Line 60:
could you tell me what is the problem??
Hi, seems like, your issue is related to this tutorial: https://codesamplez.com/programming/http-request-c-sharp . Please comment there if so and also share your details code(better to use some code sharing site) and let me know so that I can suggest further. Thanks.
but now i having another issue that fb = new MyFB(); cannot be execute straight away redirect…..i havd already write the code….how about you add me at wcien90@hotmail.com…
this is the code of webrequest..i had alreadt written it…
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using Facebook;
using System.Net;
using System.IO;
using System.Text;
namespace SocialLikeGraphSharp
{
public class MyWebRequest
{
private WebRequest request;
private Stream dataStream;
private string status;
public String Status
{
get
{
return status;
}
set
{
status = value;
}
}
public MyWebRequest(string url)
{
request = WebRequest.Create(url);
}
public MyWebRequest(string url, string method)
: this(url)
{
if (method.Equals(“GET”) || method.Equals(“POST”))
{
request.Method = method;
}
else
{
throw new Exception(“Invalid Method Type”);
}
}
public MyWebRequest(string url, string method, string data)
: this(url, method)
{
string postData = data;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.Method = “POST”;
Hi, to achieve this, you will just have to get extended permission, which doesn’t have any expiration time. This will give you access even when user is offline. Please refer to “For how long you want user to authenticate” section on my another article regarding guidelines on facebook authentication . Hope it helps. Thanks.
Hi, I didn’t work on any desktop application based on facebook sdk. But, I already given hints on my last paragraph on this tutorial. Hope that helps. Also, open source project facebook sdk for c# has also few samples on desktop application as well. Hope that helps. Thanks.
Sure, we can. we can get all info which are public and supported by api. Read about user profile query . You can read my another article on facebook c# graph api as a starting reference. Thanks.
I saw “user profile query” by using that we can get username,mail id,etc… but they had not mentioned anything about phone number can you pls make it clear how to get that phone number too.
thanks for your reply in advance.
Hello ferose, I did mention, “supported by api”- which means, if it is mentioned in api, it surely can be, if not, it can’t be. However, I did checked and found that, at the time of my writing of this tutorial and some other, it was supported, but facebook authority kept it disabled for a while. For which reason, you can’t see them on API reference. Read this announcement from facebook: http://developers.facebook.com/blog/post/447/ , where they mentioned to keep the address/phone number no longer accessible. So, I guess, you will have to live without it for now until they are enabled again, mate. Thanks.
I’m trying to show a user facebook status updates on my website. I have seen the client script provided by fb suits the purpose. But my site was hosted on internet, and some of client machines may have fb blocked. so i’m trying with sdk code u r discussing. but reg authentication, offline access is not available at present. pls let me know how i overcome this authentication.
Help. When I do this, I put in a redirect uri of http://txttoad.com/facebookapp.aspx – and I do get the redirect uri but it looks like this.. with a # instead of the ? – what am I doing wrong
Please tell me what is code. I am using in dekstop application. I just want to access token. all things are going right. app id, sceret id, redirect url. I dont what is code and where from i get this. please any body help me please
However, if I do a get from my app the same url I do not get anything in the data object
var request = WebRequest.Create(URL);
request.ContentType = “application/json; charset=utf-8”;
string text;
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
//Response.End();
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize(text);
long messages = result[“data”].Length;
Response.Write(“Messages:” + messages);
Messages:0 is the result
I am pretty sure this code used to work – I dont think I changed anything??
Can anyone enlighten me?
Can your code work in a vb.net application if I convert the code from c# to vb.net?
Does your code require that a user be asked to log into Facebook in order to access the correct Facebook account?
I haven’t got your code to work as yet , but you have nicely described the process. Thanks.
As per .NET nature, it should work. And yes, it will basically redirect user to facebook site to authorize the app. If the user is not logged in, they will be asked to do so. However, as you can see, the code is almost four years old and I am not aware of latest facebook api much, so I will suggest to check the official documentation for verifying.
var JetpackInstantSearchOptions=JSON.parse(decodeURIComponent("%7B%22overlayOptions%22%3A%7B%22colorTheme%22%3A%22light%22%2C%22enableInfScroll%22%3Atrue%2C%22enableFilteringOpensOverlay%22%3Atrue%2C%22enablePostDate%22%3Atrue%2C%22enableSort%22%3Atrue%2C%22highlightColor%22%3A%22%23FFC%22%2C%22overlayTrigger%22%3A%22submit%22%2C%22resultFormat%22%3A%22expanded%22%2C%22showPoweredBy%22%3Atrue%2C%22defaultSort%22%3A%22relevance%22%2C%22excludedPostTypes%22%3A%5B%5D%7D%2C%22homeUrl%22%3A%22https%3A%5C%2F%5C%2Fcodesamplez.com%22%2C%22locale%22%3A%22en-US%22%2C%22postsPerPage%22%3A5%2C%22siteId%22%3A18994550%2C%22postTypes%22%3A%7B%22post%22%3A%7B%22singular_name%22%3A%22Post%22%2C%22name%22%3A%22Posts%22%7D%2C%22page%22%3A%7B%22singular_name%22%3A%22Page%22%2C%22name%22%3A%22Pages%22%7D%2C%22attachment%22%3A%7B%22singular_name%22%3A%22Media%22%2C%22name%22%3A%22Media%22%7D%7D%2C%22webpackPublicPath%22%3A%22https%3A%5C%2F%5C%2Fcodesamplez.com%5C%2Fwp-content%5C%2Fplugins%5C%2Fjetpack%5C%2Fjetpack_vendor%5C%2Fautomattic%5C%2Fjetpack-search%5C%2Fbuild%5C%2Finstant-search%5C%2F%22%2C%22isPhotonEnabled%22%3Afalse%2C%22isFreePlan%22%3Atrue%2C%22apiRoot%22%3A%22https%3A%5C%2F%5C%2Fcodesamplez.com%5C%2Fwp-json%5C%2F%22%2C%22apiNonce%22%3A%22155bc22a78%22%2C%22isPrivateSite%22%3Afalse%2C%22isWpcom%22%3Afalse%2C%22hasOverlayWidgets%22%3Afalse%2C%22widgets%22%3A%5B%5D%2C%22widgetsOutsideOverlay%22%3A%5B%5D%2C%22hasNonSearchWidgets%22%3Afalse%2C%22preventTrackingCookiesReset%22%3Afalse%7D"));
aqua says
Thanks.. very helpful article.
Rana says
Can you please share your line of code that you are using while making the mywebrequest class please? Was it seen as a valid url while debugging? Also, have you tried that url directly in the browser what it returns? For valid url, the returned respose should include a valid access token and expiration timestamp.
Bindiya Luhar says
hi ali,
Your post is really great help. i have created new test asp.net web application. In my test application i have added reference of FacebookAPI.dll, created one class file ‘MyFB’. in this class file i have pasted your code given in this article.
i am getting build error “FacebookAPI is a ‘namespace’ but used like a ‘type'” i am pasting starting few lines of code of my class ‘MyFB.cs’
using System.Web;
using FacebookAPI;
using FacebookAPI.Managers;
using FacebookAPI.Objects;
using FacebookAPI.FacebookProperties;
1:namespace test
2:{
3: public class MyFB
4: {
5: private FacebookAPI myFBAPI;
6: private string appId;
7: private string apiKey;
8: private string appSecret;
…..
……
…….
}//class end
}//namespace end
at line no 5 i am getting error… i am not getting where i am missing something.
ProudGeekDad says
Hi Rana. Thanks for putting together this article. I’ve researched a few ways to integrate Facebook within my web site, and I feel that going that going with the Facebook C# API is the way to go.
Unfortunately, I’ve come across a problem that I haven’t been able to figure out.
I’ve implemented your MyWebRequest class and when I hit the line
dataStream = request.GetRequestStream();
I receive a ProtocolViolationException with the message “Cannot send a content-body with this verb-type”.
Any ideas?
ProudGeekDad says
I ended up changing this line:
dataStream = request.GetRequestStream();
to this:
dataStream = request.GetResponse().GetResponseStream();
I’m not receiving the ProtocolViolationException error any more, but I am receiving a 400 error from Facebook’s server. I think that’s an improvement, but not 100% sure yet.
Rana says
In that case. I am positive that, something is really wrong with your url that you are using to request the access token.
ProudGeekDad says
I’m pretty sure it’s the URL also, but I can’t figure out what would be wrong with it!
This is the URL that I’m using. I’ve changed all numbers to be zero (0), lower case letters to be “a”, and uppercase letters to be “A”.
https://graph.facebook.com/oauth/access_token?client_id=000000000000000&redirect_uri=http%3a%2f%2flocalhost%3a57260%2f&client_secret=00000aa0a000a0a000000aaaa0000a00&code=0.aAaAaa_aaAaaaAAaAaA_aa__.0000.0000000000-0000000000|aAAa0AAaa0AA0aAAAAaAA0Aa0a0
One thing to note is that the redirect_uri parameter has a port number in it (http://localhost:57260/), but this matches my Site URL in
the Facebook app settings.
Laurie says
Change the Method of your WebRequest (line 92 of the MyFB class above) from GET to POST and that should fix it.
PS >> Excellent post RANA, Thanks. I’m having a bash at my first FB app in c# tonight 🙂
suppu says
i am trying your solution but System.Net.WebException: The operation has timed out error is coming how to solve that.
Rana says
Debug what url is generating for making the web request. try that on your browser whether that shows a access token and expiration time info.
Tudor says
Hello,
Where can I find a list of parameters? For instance, I call
JSONObject f = faceApi.Get(“/me/friends”);
to retrieve my friends, but what about if I want my statuses? or my friend’s statuses? Is there any available list of commands?
Tudor
Rana says
Hi, you can find these all on facebook api documentation. Such as, for all kind of informations that facebook api provides about the user, can be found at http://developers.facebook.com/docs/reference/api/user/. Also, If you are beginner, you should consider reading my another article on getting started with facebook graph api
Enoch says
In your example “Redirect to Facebook to Allow Access”, you note the redirect path to be: “https://graph.facebook.com/…” It should be https://WWW.facebook.com. Otherwise it you receive an webpage cannot be found error.
Balaji Birajdar says
The path is correct..
You will have to connect to https://graph.facebook.com/… to communicate with facebook via its API.
Steven Hassenberg says
I found a complete tutorial on developing facebook application with facebook Graph API with OAuth 2.0 here .. May be of help to someone .. Must visit .. http://www.facebooksdk.blogspot.com/
Balaji Birajdar says
Thanks
The code sample you provided proved to be extremely helpful. I used it in my application and it works great.
The complete login procedure can be seen here http://facebooksdk.blogspot.com/2011/03/facebookloginhelper.html
Inge says
I am wondering if the following is possible or not! hope someone can help!
From a particular website page I would like to offer a log in with your facebook account. After the ‘allowing’ I would like to redirect that person to the webpage where he came from (read this can be from hundreds of different pages). Would it be possible to redirect to the starting webpage after the authentification?
Hope someone has an awnser!
Thnx !!!
Kundan says
Hi I am having a problem.
I have added Facebook.dll api along with facebook.web.dll, facebook.web.mvc.dll
but for FacebookAPI it is missing the reference and also for FacebookAPI(); JSONObject, FacebookAPIException
So how can u add up reference to these ???
leading concepts says
Switched the GET to POST, but getting 400 error?
cd says
can you suggest the java code to retrieve all my facebook friends names and email addresses………….?
Rana says
Sorry, I haven’t tried facebook application with java code..
Martin says
Great article!
I would like to know where is the code snippet for FacebookAPI, because I do not see it!
Thanks
Rana says
The variable “myFBAPI” is of “FacebookAPI” type. You can search by control+f on browser. Thanks.
chira says
How we can call method below you described.
public String GetAccessToken(string code)
{}
I want to know what string code should we pass..please give example.
devin says
the “code” is a long string sent by FB after a user successfully authorizes your app.
you will find detailed information here:
https://developers.facebook.com/docs/authentication/#redirect-uris
let me know if you need further help
Khumesh Kumawat says
Hi…
I want to create a service using c# for getting access token social login provider like facebook, twitter etc and i want to check login status of every login provider by service every 5 minutes. Plz tell me solution for this.
Thanks
Khumesh Kumawat
Fernando Linhares says
I am facing several problems trying to implement the facebook access code. I am allowed access to my app, but I can’t get passed the fb.getaccesstoken function. It gives me this error:
Cannot send a content-body with this verb-type.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type.
Source Error:
Line 62:
Line 63: // Get the request stream.
Line 64: dataStream = request.GetRequestStream();
Line 65:
Line 66: // Write the data to the request stream.
devin says
@author
thanks a ton mate!
@Fernando Linhares
you have the code that fb sends you but using that you are not able to get the access token. is that the case? if so, the following might help you.
//catch the code sent by fb
var fb_code = Request.QueryString[“code”];
if (fb_code != null)
{
string GraphURL = “https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL& client_secret=YOUR_APP_SECRET&code=” + fb_code;
WebRequest request = WebRequest.Create(GraphURL);
request.Method = “GET”;
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
}
now, the responseFromServer will contain the access token. you can split it and fetch it!
Ninh says
Hi Rana,
Can you public this demo code.
Thanks!
Rodrigo says
Everytime I want to get a user info, I have to do the request?
Otherthing, how do you handle the access_token expiration?
By the way, good post you got there!
Rana says
hi, you can set the expiration time yourself, even to infinity. Checkout the facebook official api page references for details. Thanks.
en says
i have this error:
Server Error in ‘/’ Application.
Cannot send a content-body with this verb-type.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type.
Source Error:
Line 56: request.ContentType = “application/x-www-form-urlencoded”;
Line 57: request.ContentLength = byteArray.Length;
Line 58: dataStream = request.GetRequestStream();
Line 59:
Line 60:
could you tell me what is the problem??
Rana says
Hi, seems like, your issue is related to this tutorial: https://codesamplez.com/programming/http-request-c-sharp . Please comment there if so and also share your details code(better to use some code sharing site) and let me know so that I can suggest further. Thanks.
en says
but now i having another issue that fb = new MyFB(); cannot be execute straight away redirect…..i havd already write the code….how about you add me at wcien90@hotmail.com…
en says
this is the code of webrequest..i had alreadt written it…
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using Facebook;
using System.Net;
using System.IO;
using System.Text;
namespace SocialLikeGraphSharp
{
public class MyWebRequest
{
private WebRequest request;
private Stream dataStream;
private string status;
public String Status
{
get
{
return status;
}
set
{
status = value;
}
}
public MyWebRequest(string url)
{
request = WebRequest.Create(url);
}
public MyWebRequest(string url, string method)
: this(url)
{
if (method.Equals(“GET”) || method.Equals(“POST”))
{
request.Method = method;
}
else
{
throw new Exception(“Invalid Method Type”);
}
}
public MyWebRequest(string url, string method, string data)
: this(url, method)
{
string postData = data;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.Method = “POST”;
request.ContentType = “application/x-www-form-urlencoded”;
request.ContentLength = byteArray.Length;
dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
}
public string GetResponse()
{
//request.Credentials = CredentialCache.DefaultCredentials;
WebResponse response = request.GetResponse();
this.Status = ((HttpWebResponse)response).StatusDescription;
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
en says
do you have any relevant source code for offline access token c#???
Rana says
Hi, to achieve this, you will just have to get extended permission, which doesn’t have any expiration time. This will give you access even when user is offline. Please refer to “For how long you want user to authenticate” section on my another article regarding guidelines on facebook authentication . Hope it helps. Thanks.
varsha says
do u have any relevant source code for wpf or window application. if u have send me, thanks
Rana says
Hi, I didn’t work on any desktop application based on facebook sdk. But, I already given hints on my last paragraph on this tutorial. Hope that helps. Also, open source project facebook sdk for c# has also few samples on desktop application as well. Hope that helps. Thanks.
ferose says
can we get phone number,username,mail Id, of a fb user
Md Ali Ahsan Rana says
Sure, we can. we can get all info which are public and supported by api. Read about user profile query . You can read my another article on facebook c# graph api as a starting reference. Thanks.
ferose says
I saw “user profile query” by using that we can get username,mail id,etc… but they had not mentioned anything about phone number can you pls make it clear how to get that phone number too.
thanks for your reply in advance.
Md Ali Ahsan Rana says
Hello ferose, I did mention, “supported by api”- which means, if it is mentioned in api, it surely can be, if not, it can’t be. However, I did checked and found that, at the time of my writing of this tutorial and some other, it was supported, but facebook authority kept it disabled for a while. For which reason, you can’t see them on API reference. Read this announcement from facebook: http://developers.facebook.com/blog/post/447/ , where they mentioned to keep the address/phone number no longer accessible. So, I guess, you will have to live without it for now until they are enabled again, mate. Thanks.
bergetburk says
Hi,
Where to find and download the FacebookAPI, and how do you implement that in your own code?
Md Ali Ahsan Rana says
You can find it here: https://github.com/facebook-csharp-sdk/facebook-csharp-sdk/
anupavan says
I’m trying to show a user facebook status updates on my website. I have seen the client script provided by fb suits the purpose. But my site was hosted on internet, and some of client machines may have fb blocked. so i’m trying with sdk code u r discussing. but reg authentication, offline access is not available at present. pls let me know how i overcome this authentication.
Michelle Sollicito says
Help. When I do this, I put in a redirect uri of http://txttoad.com/facebookapp.aspx – and I do get the redirect uri but it looks like this.. with a # instead of the ? – what am I doing wrong
tanweer says
Please tell me what is code. I am using in dekstop application. I just want to access token. all things are going right. app id, sceret id, redirect url. I dont what is code and where from i get this. please any body help me please
Michelle Sollicito says
If I copy this url into the browser it works great – I get back the stream from my group
https://graph.facebook.com/171486003058541/feed?access_token=%5Blong term app token]
the response starts like this..
{
“data”: [
{
“id”: “171486003058541_172666886273786”,
“from”: {
“name”: “Michelle Sollicito”,
“id”: “100000449886864”
},
“to”: {
“data”: [
{
“name”: “TxtToAd”,
“id”: “171486003058541”
}
]
},
However, if I do a get from my app the same url I do not get anything in the data object
var request = WebRequest.Create(URL);
request.ContentType = “application/json; charset=utf-8”;
string text;
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
//Response.End();
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize(text);
long messages = result[“data”].Length;
Response.Write(“Messages:” + messages);
Messages:0 is the result
I am pretty sure this code used to work – I dont think I changed anything??
Can anyone enlighten me?
Ross Gallagher says
Can your code work in a vb.net application if I convert the code from c# to vb.net?
Does your code require that a user be asked to log into Facebook in order to access the correct Facebook account?
I haven’t got your code to work as yet , but you have nicely described the process. Thanks.
Md Ali Ahsan Rana says
As per .NET nature, it should work. And yes, it will basically redirect user to facebook site to authorize the app. If the user is not logged in, they will be asked to do so. However, as you can see, the code is almost four years old and I am not aware of latest facebook api much, so I will suggest to check the official documentation for verifying.
Hemant Sharma says
Can you please tell me where do i get FacebookAPI reference myFBAPI variable.
prathima says
hello,
can you please show how to access friends list after user login through facebook in asp.net C# coding .
thanks
Jenny says
I’m constantly getting one error i.e, “FacebookApi is a namespace but is used as a type” . What should i do to resolve this problem?
shashank says
how to access email id ??
Yogesh says
How to post on facebook page on behalf of that page using jquery??? Please help me