How to get friends list from facebook? (Desktop application) - c#

As per this link code from stack overflow i have try this code for getting
friendslist but after login i got this error "requires valid signature"
string APIKey = ConfigurationManager.AppSettings["API_Key"];
string APISecret = ConfigurationManager.AppSettings["API_Secret"];
Facebook.Session.ConnectSession connectsession = new Facebook.Session.ConnectSession(APIKey, APISecret);
Facebook.Rest.Api api = new Facebook.Rest.Api(connectsession);
var friends = api.Friends.GetLists();
foreach (var friend in friends)
{
System.Console.WriteLine(friend.name);
}
guide me to find out the solution
Thanks
ash

If you are starting with a new application, you should definitely use the Graph API and not the old Rest API. The Rest API has been deprecated for quite a while now and there is no guarantee how much longer Facebook will support it.
For an example on using the Graph API try http://csharpsdk.org/docs/web/getting-started
You can obtain the friends list by making a request to me/friends
You can test other requests using the Graph API explorer.

Related

Google Ads Api Console Application

I want to develop a console application that pulls all campaigns under adwords accounts using Google Ads Api.
But I could not pass the authentication step.
I do not fully understand whether I should use the Service Account or Desktop Application Flow for this process.
GoogleAdsConfig config = new GoogleAdsConfig()
{
DeveloperToken = "Dev_token",
OAuth2Mode = Google.Ads.GoogleAds.Config.OAuth2Flow.APPLICATION,
OAuth2ClientId = "client_Id",
OAuth2ClientSecret = "secrret",
OAuth2RefreshToken = " refresh_token",
};
GoogleAdsClient client = new GoogleAdsClient(config);
GoogleAdsServiceClient googleAdsService = client.GetService(Google.Ads.GoogleAds.Services.V10.GoogleAdsService);
googleAdsService.SearchStream(AdwordsClientId, query,
delegate (SearchGoogleAdsStreamResponse resp)
{
foreach (GoogleAdsRow adsRow in resp.Results)
{
}
}
);
When I try as above, I get the following error
Google.Apis.Auth.OAuth2.Responses.TokenResponseException: Error:"unauthorized_client", Description:"Unauthorized", Uri:""
What paths should i follow?
Thank you.
unauthorized_client could have a couple of reasons. The most important ones that come to mind:
Did you make sure that your client ID and client secret match?
Have you activated the Google Ads API for the GCP project whose OAuth2 client you are using?

Facebook Retrive Data using Graph API using c#

i have created desktop Facebook application using c# .net. i want to retrieve users message,post and chat history. which is convenient way to retrieve users all information.i have started with Facebook Graph API but i am not getting any example.
can any one help me ?
A bit late to the party but anyway:
Add a reference to System.Net.Http and Newtonsoft.Json
string userToken = "theusertokentogiveyoumagicalpowers";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://graph.facebook.com");
HttpResponseMessage response = client.GetAsync($"me?fields=name,email&access_token={userToken}").Result;
response.EnsureSuccessStatusCode();
string result = response.Content.ReadAsStringAsync().Result;
var jsonRes = JsonConvert.DeserializeObject<dynamic>(result);
var email = jsonRes["email"].ToString();
}
Go to developer.facebook.com -> Tools & Support -> Select Graph API Explorer
Here U get FQL Query, Access Token
Then write code in C#.....
var client = new FacebookClient();
client.AccessToken = Your Access Token;
//show user's profile picture
dynamic me = client.Get("me?fields=picture");
pictureBoxProfile.Load(me.picture.data.url);
//show user's birthday
me = client.Get("me/?fields=birthday");
labelBirthday.Text = Convert.ToString(me.birthday);
http://www.codeproject.com/Articles/380635/Csharp-Application-Integration-with-Facebook-Twitt
I hope this will help you.!!!
you can check the Graph explorer tool on Developer.facebook.com , go to Tools and select graph explorer, its a nice tool which gives you exact idea about what you can fetch by sending "GET" and "POST" method on FB Graph APis
From what i see the app now only uses webhooks to post data to a data endpoint (in your app) at which point you can parse and use this. (FQL is deprecated). This is used for things like messaging.
A get request can be send to the API to get info - like the amt. of likes on your page.
The docs of FB explain the string you have to send pretty nicely. Sending requests can be done with the webclient, or your own webrequests.
https://msdn.microsoft.com/en-us/library/bay1b5dh(v=vs.110).aspx
Then once you have a string of the JSON formatted page you can parse this using JSON.NET library. It's available as a NUGEt package.

Get user email info from a Dotnet Google API

I'm have working two separate implementations of Oauth2 for both the gData and the Drive C# APIs, storing token information in an OAuth2Parameters and AuthorizationState respectively. I'm able to refresh the token and use them for the necessary API calls. I'm looking for a way to use this to get the user's information, mainly the email address or domain.
I tried following the demo for Retrieve OAuth 2.0 Credentials but I'm getting a compile error similar to rapsalands' issue here, saying it
can't convert from
'Google.Apis.Authentication.OAuth2.OAuth2Authenticator<
Google.Apis.Authenticatio‌​n.OAuth2.DotNetOpenAuth.NativeApplicationClient>'
to 'Google.Apis.Services.BaseClientService.Initializer'.
I just grabbed the most recent version of the Oauth2 api dlls so I don't think that's it.
All the other code samples I'm seeing around mention using the UserInfo API, but I can't find any kind of C#/dotnet api that I can use with it without simply doing straight GET/POST requests.
Is there a way to get this info using the tokens I already have with one of the C# apis without making a new HTTP request?
You need to use Oauth2Service to retrieve information about the user.
Oauth2Service userInfoService = new Oauth2Service(credentials);
Userinfo userInfo = userInfoService.Userinfo.Get().Fetch();
Oauth2Service is available on the following library: https://code.google.com/p/google-api-dotnet-client/wiki/APIs#Google_OAuth2_API
For #user990635's question above. Though the question is a little dated, the following may help someone. The code uses Google.Apis.Auth.OAuth2 version
var credentials =
await GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets {ClientId = clientID, ClientSecret = clientSecret},
new[] {"openid", "email"}, "user", CancellationToken.None);
if (credentials != null)
{
var oauthSerivce =
new Oauth2Service(new BaseClientService.Initializer {HttpClientInitializer = credentials});
UserInfo = await oauthSerivce.Userinfo.Get().ExecuteAsync();
}

Evernote AuthToken via OAuth

I have worked with OAuth before (working with Twitter and PHP) and it was simple. I am trying to get OAuth to work with the EverNote API sample https://github.com/evernote/evernote-sdk-csharp (because, as they say, "Real applications authenticate with Evernote using OAuth"). I looked at these:
Simple C# Evernote API OAuth example or guide?
https://github.com/sethhitch/csharp-oauth-sample
http://blog.stevienova.com/2008/04/19/oauth-getting-started-with-oauth-in-c-net/
But, I still don't know how to do this... This is my code:
// Real applications authenticate with Evernote using OAuth, but for the
// purpose of exploring the API, you can get a developer token that allows
// you to access your own Evernote account. To get a developer token, visit
// https://sandbox.evernote.com/api/DeveloperToken.action
String authToken = "myAuthCode";
if (authToken == "your developer token") {
Console.WriteLine("Please fill in your developer token");
Console.WriteLine("To get a developer token, visit https://sandbox.evernote.com/api/DeveloperToken.action");
return;
}
How can I add OAuth to this to get my authToken?
Thank you.
Check this sample project : http://discussion.evernote.com/topic/30584-here-is-a-net-oauth-assembly/ . I think this will help you to understand how oauth works.
For anyone trying to get this to work in MVC, I was playing around with Evernote, OpenAuth and C# this morning and managed to get it all working. I have put together a blog post / library explaining the experience and outlining how to do it with MVC here - http://www.shaunmccarthy.com/evernote-oauth-csharp/ - it uses the AsyncOAuth library: https://github.com/neuecc/AsyncOAuth
I wrote a wrapper around AsyncOAuth that you might find useful here: https://github.com/shaunmccarthy/AsyncOAuth.Evernote.Simple
One prickly thing to be aware of - the Evernote Endpoints (/oauth and /OAuth.action) are case sensitive
// Download the library from https://github.com/shaunmccarthy/AsyncOAuth.Evernote.Simple
// Configure the Authorizer with the URL of the Evernote service,
// your key, and your secret.
var EvernoteAuthorizer = new EvernoteAuthorizer(
"https://sandbox.evernote.com",
"slyrp-1234", // Not my real id / secret :)
"7acafe123456badb123");
// First of all, get a request token from Evernote - this causes a
// webrequest from your server to Evernote.
// The callBackUrl is the URL you want the user to return to once
// they validate the app
var requestToken = EvernoteAuthorizer.GetRequestToken(callBackUrl);
// Persist this token, as we are going to redirect the user to
// Evernote to Authorize this app
Session["RequestToken"] = requestToken;
// Generate the Evernote URL that we will redirect the user to in
// order to
var callForwardUrl = EvernoteAuthorizer.BuildAuthorizeUrl(requestToken);
// Redirect the user (e.g. MVC)
return Redirect(callForwardUrl);
// ... Once the user authroizes the app, they get redirected to callBackUrl
// where we parse the request parameter oauth_validator and finally get
// our credentials
// null = they didn't authorize us
var credentials = EvernoteAuthorizer.ParseAccessToken(
Request.QueryString["oauth_verifier"],
Session["RequestToken"] as RequestToken);
// Example of how to use the credential with Evernote SDK
var noteStoreUrl = EvernoteCredentials.NotebookUrl;
var noteStoreTransport = new THttpClient(new Uri(noteStoreUrl));
var noteStoreProtocol = new TBinaryProtocol(noteStoreTransport);
var noteStore = new NoteStore.Client(noteStoreProtocol);
List<Notebook> notebooks = client.listNotebooks(EvernoteCredentials.AuthToken);
You can also try the OAuth library found here : https://code.google.com/p/devdefined-tools/wiki/OAuth and follow the steps mentioned here.
The simple code to add is:
EvernoteOAuth oauth = new EvernoteOAuth(EvernoteOAuth.HostService.Sandbox, myConsumerKey, myConsumerSecret);
string errResponse = oauth.Authorize();
if (errResponse.Length == 0)
{
Console.WriteLine(string.Format("Token: {0}\r\n\r\nExpires: {1}\r\n\r\nNoteStoreUrl: {2}\r\n\r\nUserId: {3}\r\n\r\nWebApiUrlPrefix: {4}", oauth.Token, oauth.Expires, oauth.NoteStoreUrl, oauth.UserId, oauth.WebApiUrlPrefix));
}
else
{
Console.WriteLine("A problem has occurred in attempting to authorize the use of your Evernote account: " + errResponse);
}
You will need to use this assembly:
using EvernoteOAuthNet;
Available here:
http://www32.zippyshare.com/v/98249023/file.html

Facebook Graph API put Like issue.?

I am using Facebook Graph API and I wanted to put Like of any comment so I am doing like this.
FacebookGraphAPI obj = new FacebookGraphAPI(AccessToken);
obj.PutLike(item["id"].ToString().Replace("\"", ""));
It is not working even it will not give me error so how I can put the like.
Using the latest API, here's how to do a like (this assumes that there is a graph api like connection on the object being liked)
FacebookClient client = new FacebookClient(userAccessToken);
var result = client.Post(item["id"] + "/likes", null);
ProcessResult(result); // your code to determine how to handle the result being sent back from Facebook
The above code is from a current production working app of mine.
Happy coding!

Categories

Resources