DotNetOpenAuth with Google Calendar Feed - c#

I have been racking my brain for a few days trying to get a list of calendars from Google using DotNetOpenAuth.
I can successfully get a list of contacts using the DotNetOpenAuth Samples. I have integrated it with my domain using the OpenId+OAuth. Everything works great to get a list of contacts.
So from there I modified the code to try to retrieve a list of Calendars and I keep getting a 401 Unauthorized error.
I know it is authorizing because I can get the contact list. Does anyone have a code example how they are retrieving calendars or calendar events using the DotNetOpenAuth with Google???
Thanks
Update:
Thanks for the response. I have read everything I can get my hands on. Here is what I have done so far
Step 1: I created a new GetCalendarEndPoint in the GoogleConsumer.cs
private static readonly MessageReceivingEndpoint GetCalendarEndpoint = new MessageReceivingEndpoint("https://www.google.com/calendar/feeds/default", HttpDeliveryMethods.GetRequest);
Step 2: Next I created a new method GetCalendars patterned after the GetContacts Method in GoogleConsumer.cs - (Rebuilt the dll etc.)
public static XDocument GetCalendars(ConsumerBase consumer, string accessToken, int maxResults/* = 25*/, int startIndex/* = 1*/) {
if (consumer == null)
{
throw new ArgumentNullException("consumer");
}
var request = consumer.PrepareAuthorizedRequest(GetCalendarEndpoint, accessToken);
var response = consumer.Channel.WebRequestHandler.GetResponse(request);
string body = response.GetResponseReader().ReadToEnd();
XDocument result = XDocument.Parse(body);
return result;
Step 3: In my Application I modified the ScopeURI to the the Calendar URI from GoogleConsumer as follows
private IAuthenticationRequest GetGoogleRequest()
{
Realm realm = Request.Url.Scheme + Uri.SchemeDelimiter + Global.GoogleTokenManager.ConsumerKey + "/";
IAuthenticationRequest authReq = relyingParty.CreateRequest(GoogleOPIdentifier, realm);
// Prepare the OAuth extension
string scope = GoogleConsumer.GetScopeUri(GoogleConsumer.Applications.Calendar);
Global.GoogleWebConsumer.AttachAuthorizationRequest(authReq, scope);
// We also want the user's email address
var fetch = new FetchRequest();
fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
authReq.AddExtension(fetch);
return authReq;
}
However, when I run the app I get 401 Unauthorized when I make the following call
var calendars = GoogleConsumer.GetCalendars(Global.GoogleWebConsumer, State.GoogleAccessToken, 25, 1);
I have also checked that the State.GoogleAccess token exists by simply displaying it on my screen before I trigger the method that makes this call.
Again, if I exectute
var calendars = GoogleConsumer.GetContacs(Global.GoogleWebConsumer, State.GoogleAccessToken, 25, 1);
then it works??????? Thanks for you help.

I've been suffering through exactly the same thing for most of the weekend.
I think that after much fiddling with Fiddler I've found the cause and have a solution which, although not pretty, seems to work. I found that I was able to access the calendar feed by copying and pasting the DNOA-generated Uri into a browser, but always got a 401 when attempting programmatic access. This is apparently because the default auto-redirect behavior of HttpWebRequest discards any cookies that the redirect is attempting to set. The Contacts feed doesn't set any cookies during the redirect, so it is immune.
The first time you request a calendar feed (even with a properly constructed and signed OAuth request), Google replies with a redirect containing a cookie. If you don't present that "calendar cookie" at the same time as your feed request you will get a 401 Unauthorized when you attempt to follow the redirect to the feed.
here's the cookie-setting header from Google:
HTTP/1.1 302 Moved Temporarily
Set-Cookie: S=calendar=y7AlfgbmcqYl0ugrF-Zt9A;Expires=Tue, 10-Jan-2012 03:54:20 GMT;Secure
Here's what I'm doing to make it work:
// wc: WebConsumer
var calRequest = wc.PrepareAuthorizedRequest(erp2, authTokenRsp.AccessToken);
// need to stop redirect to capture calendar cookie token:
calRequest.AllowAutoRedirect = false;
var calResponse = calRequest.GetResponse();
var redirectCookie = calResponse.Headers[System.Net.HttpResponseHeader.SetCookie];
var cookiedCalRequest = wc.PrepareAuthorizedRequest(erp2, authTokenRsp.AccessToken);
cookiedCalRequest.Headers[System.Net.HttpRequestHeader.Cookie] = redirectCookie;
var calFeedResponse = cookiedCalRequest.GetResponse();

Have you read the Google Calendar data API documentation to make sure you have the right endpoints programmed in? Have you also modified the code that acquires the access token to request access to Google Calendar in addition to Google Contacts? The access token in the sample only gets Contacts permissions unless you change it.

Related

Read Emails from Office 365 via c# using refresh token

So I'm able to login to Outlook via OAuth2 and get it to provide my app with access and refresh tokens.
However, I cannot seem to figure out how to get Outlook OAuth2 to give me another token using the provided refresh token. I've messed with this code quite a few times trying to get something to work using C# HttpClient(). Additionally, I've tried to follow this article and use the "native" "Experimental.IdentityModel.Clients.ActiveDirectory" library (what is this anyway?) to accomplish my task.
I could log in with this library and get an access code, but it wouldn't give me a refresh token. This particular library doesn't seem to provide access to refresh tokens, even if they are provided in the response.
Anyway, so here's the HttpClient code that I'm using to get an Access Token (this is from my callback Controller Method):
string authCode = Request.Params["code"];
var client = new HttpClient();
var clientId = ConfigurationManager.AppSettings["ida:ClientID"];
var clientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"];
var parameters = new Dictionary<string, string>
{
{"client_id", clientId},
{"client_secret", clientSecret},
{"code",authCode },
{"redirect_uri", Url.Action("Authorize", "Manage", null, Request.Url.Scheme)},
{"grant_type","authorization_code" }
};
var content = new FormUrlEncodedContent(parameters);
var response = await client.PostAsync("https://login.microsoftonline.com/common/oauth2/v2.0/token",content);
var tokens = await response.Content.ReadAsAsync<MicrosoftOAuthAuthenticationModel>();
var originalRefreshToken = tokens.refresh_token;
var originalAccessToken = tokens.access_token;
originalAccessToken gets generated as expected. Now here's the part I can't figure out:
var parameters2 = new Dictionary<string, string>
{
{"grant_type", "refresh_token"},
{"refresh_token", originalRefreshToken},
{"client_id", clientId},
{"client_secret", clientSecret},
{"resource","https://outlook.office365.com" }
};
var content2 = new FormUrlEncodedContent(parameters2);
var response2 = await client.PostAsync("https://login.microsoftonline.com/common/oauth2/token", content2);
var tokens2 = await response2.Content.ReadAsAsync<MicrosoftOAuthAuthenticationModel>();
var newRefreshtoken = tokens2.refresh_token;
var newAccessToken = tokens2.access_token;
I get a 400 error from the server that says "Authentication failed: Refresh Token is malformed or invalid". This seems weird because I'm literally grabbing the refresh token from the response and using it.
Does anyone have any information that might help? Alternatively, does anyone know who to contact for help? Last, the goal here is to simply be able to persistently read emails from an inbox on office 365 via the API so I can get the email id, conversation id, subject, content, from email address, etc. and process it. Is there an easier way to be doing this? This can't be a difficult or uncommon thing to do.
If you are using the ADAL library (Experimental.IdentityModel.Clients.ActiveDirectory), you don't need to save the refresh token. The library saves the token and manages refreshing as needed for you. You just always retrieve the token using the AcquireSilent... (don't remember the exact method name), and it will pull from cache as it can and refresh when needed.
In your code your likely seeing this problem because in the refresh you're not posting to the v2 endpoint. Change your endpoint URL to https://login.microsoftonline.com/common/oauth2/v2.0/token and see if that doesn't fix it. If it still doesn't work, you might compare with http://oauthplay.azurewebsites.net/.

OneDrive API with C#, get authentication code programmatic

I have to write an application, no matter what language (c#, Java, shell, python ...) that can connect to OneDrive and then uploads file.
Following the OneDrive API I found that i need in one step to go to the browser (manually and to post a url that combines client_id and client_security to get an authentication code so i can connect my client with it to get the access token. (oAuth2 protocol)
I need to get the access_token pragmatically, i don't need any manual step to be involved.
I tried in c# to use the WebBrowser component to navigate to the url and to get the access token, I found that the browser stays in the same url and not getting the final url that includes the auth_code!
My code looks like:
// Initialize a new Client (without an Access/Refresh tokens
var client = new Client(options);
// Get the OAuth Request Url
var authRequestUrl = client.GetAuthorizationRequestUrl(new[] { Scope.Basic, Scope.Signin, Scope.SkyDrive, Scope.SkyDriveUpdate });
// TODO: Navigate to authRequestUrl using the browser, and retrieve the Authorization Code from the response
WebBrowser wb = new WebBrowser();
wb.AllowNavigation = true;
wb.ScrollBarsEnabled = false;
wb.ScriptErrorsSuppressed = true;
wb.Navigate(authRequestUrl);
Console.WriteLine(wb.Version);
while (wb.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
wb.Document.InvokeScript("evt_Login_onload(event)");
Uri myUrl = wb.Url;
Anyone can help with fixing this, or maybe suggest other ideas please?
Thanks in Advance!
It looks like you're creating a Windows desktop app using C#. There's actually an example at https://msdn.microsoft.com/en-us/library/hh826529.aspx for using the WebBrowser class to get the authorization code, then the token, then make an API. In short, you'll first need to send a request to the following URL with your client_id and scopes.
https://login.live.com/oauth20_authorize.srf?client_id=YOUR_CLIENT_ID&scope=YOUR_SCOPE_STRING&response_type=code&redirect_uri=https://login.live.com/oauth20_desktop.srf
In the response, you'll get the authorization code which you'll need to use to send another request to with your client_id, client_secret, authorization code like the following.
https://login.live.com/oauth20_token.srf?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&redirect_uri=https://login.live.com/oauth20_desktop.srf&code=AUTHORIZATION_CODE&grant_type=authorization_code
When you finally receive the access token, you can make requests to the API using your access token similar to the following.
"https://apis.live.net/v5.0/me?access_token=ACCESS_TOKEN". The "me" can be changed to any other folder or directory.
I hope that helps.
dont u think the scope u provided are wrong, they should be wl.basic, wl.signin, and if ur using new onedrive api then it should be onedrive.readonly or onedrive.readwrite
if ur using liveconnect api for the purpose of using onedrive then scope should be wl.skydrive or wl.contacts_skydrive or wl.skydrive_update
depending upon ur uses (refer https://msdn.microsoft.com/en-us/library/hh243646.aspx)
and can u more elaborate how ur trying to get the access_token, from above it is quite confusing to me
Have you solved you issue?
Have you tried to use the LiveSDK to authenticate?
Have a look at my question there, it might help you :
Onedrive API vs LiveSDK
I have used the following code, after installing both the LiveSDK and the OneDrive SDK, and this does not require any login after the first authorization. However it "may" have to be a RT app (windows store or windows phone store)
var authClient = new LiveAuthClient();
var authResult = await authClient.LoginAsync(new string[] {
"wl.signin", "onedrive.readwrite", "onedrive.appfolder"});
if (authResult.Session == null)
throw new InvalidOperationException("You need to sign in and give consent to the app.");
var Connection = new ODConnection("https://api.onedrive.com/v1.0",
new MicrosoftAccountAuthenticationInfo() { TokenType = "Bearer",
AccessToken = odArgs.Session.AccessToken });
Toan-Nguyen's answer almost helps me. On the step 2 (when I should send a request with authorization code) I get the response with error "Public clients can't send client secret". This answer said it's neccessary to remove the attribute client_secret from url.

tweetsharp - app stops being able to tweet after a few hours

I have a asp.net 4.5 webforms site that allows users to link their account to twitter and tweet directly from my site.
My app is registered with twitter and I am able to successfully authorise my app for the user's account and initially can tweet fine, but after a few hours the tweets stop working. I am using tweetsharp to handle the authorisation.
my code is:
TwitterClientInfo twitterClientInfo = new TwitterClientInfo();
twitterClientInfo.ConsumerKey = ConsumerKey;
twitterClientInfo.ConsumerSecret = ConsumerSecret;
var requestToken = new OAuthRequestToken { Token = oauthtoken };
TwitterService twitterService = new TwitterService(ConsumerKey, ConsumerSecret);
OAuthAccessToken accessToken = twitterService.GetAccessToken(requestToken, oauthverifier);
twitterService.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);
TwitterUser user = twitterService.VerifyCredentials(new VerifyCredentialsOptions());
SendTweetOptions options = new SendTweetOptions();
options.Status = tweetText;
twitterService.SendTweet(options);
what i have noticed is that while the app is successfully tweeting, the accessToken.Token value that is being used to authenticate the user has a proper value (a long string of numbers and upper/lowercase characters) however when it stops tweeting the accessToken.Token value is just a single question mark "?".
Twitter says it doesn't expire tokens so i am at a loss to understand what is happening or how it can be resolved? if i went in to my twitter account and deauthorised my app and went through the authorisation again it would work fine for a few hours, but obviously that's not something i can ask my users to do.
can anyone suggest a resolution to this - either to stop the accessToken value becoming ? or to handle it and get a proper value if it does (without reauthorising the app)
Well, without beginning to understand the actual issue, I managed to fix it
Instead of retrieving the access token every time via:
var requestToken = new OAuthRequestToken { Token = oauthtoken };
OAuthAccessToken accessToken = twitterService.GetAccessToken(requestToken, oauthverifier);
twitterService.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);
i only do that once and store accessToken.Token and accessToken.TokenSecret in the database and retrieve them when tweeting and supply them
twitterService.AuthenticateWith(accessTokenFromDB, accessokenSecretFromDB);
I have seen somewhere that Twitter doesn't expire tokens, so this should work. Certainly it's been working for me all weekend whereas the original code would stop working after a few hours.
Thought this might help some others who have the same issue.

OAuth authentication without browser [duplicate]

I'm trying to create a .NET-based client app (in WPF - although for the time being I'm just doing it as a console app) to integrate with an OAuth-enabled application, specifically Mendeley (http://dev.mendeley.com), which apparently uses 3-legged OAuth.
This is my first time using OAuth, and I'm having a lot of difficulty getting started with it. I've found several .NET OAuth libraries or helpers, but they seem to be more complicated than I think I need. All I want to do is be able to issue REST requests to the Mendeley API and get responses back!
So far, I've tried:
DotNetOpenAuth
http://github.com/bittercoder/DevDefined.OAuth
http://oauth.googlecode.com/svn/code/csharp/
The first (DotNetOpenAuth) seems like it could possibly do what I needed if I spent hours and hours trying to work out how. The second and third, as best I can tell, don't support the verification codes that Mendeley is sending back -- although I could be wrong about this :)
I've got a consumer key and secret from Mendeley, and with DotNetOpenAuth I managed to get a browser launched with the Mendeley page providing a verification code for the user to enter into the application. However, at this point I got lost and couldn't work out how to sensibly provide that back to the application.
I'm very willing to admit that I have no idea where to start with this (although it seems like there's quite a steep learning curve) - if anyone can point me in the right direction I'd appreciate it!
I agree with you. The open-source OAuth support classes available for .NET apps are hard to understand, overly complicated (how many methods are exposed by DotNetOpenAuth?), poorly designed (look at the methods with 10 string parameters in the OAuthBase.cs module from that google link you provided - there's no state management at all), or otherwise unsatisfactory.
It doesn't need to be this complicated.
I'm not an expert on OAuth, but I have produced an OAuth client-side manager class, that I use successfully with Twitter and TwitPic. It's relatively simple to use. It's open source and available here: Oauth.cs
For review, in OAuth 1.0a...kinda funny, there's a special name and it looks like a "standard" but as far as I know the only service that implements "OAuth 1.0a" is Twitter. I guess that's standard enough. ok, anyway in OAuth 1.0a, the way it works for desktop apps is this:
You, the developer of the app, register the app and get a "consumer key" and "consumer secret". On Arstechnica, there's a well written analysis of why this model isn't the best, but as they say, it is what it is.
Your app runs. The first time it runs, it needs to get the user to explicitly grant approval for the app to make oauth-authenticated REST requests to Twitter and its sister services (like TwitPic). To do this you must go through an approval process, involving explicit approval by the user. This happens only the first time the app runs. Like this:
request a "request token". Aka temporary token.
pop a web page, passing that request token as a query param. This web page presents UI to the user, asking "do you want to grant access to this app?"
the user logs in to the twitter web page, and grants or denies access.
the response html page appears. If the user has granted access, there's a PIN displayed in a 48-pt font
the user now needs to cut/paste that pin into a windows form box, and click "Next" or something similar.
the desktop app then does an oauth-authenticated request for an "Access token". Another REST request.
the desktop app receives the "access token" and "access secret".
After the approval dance, the desktop app can just use the user-specific "access token" and "access secret" (along with the app-specific "consumer key" and "consumer secret") to do authenticated requests on behalf of the user to Twitter. These don't expire, although if the user de-authorizes the app, or if Twitter for some reason de-authorizes your app, or if you lose your access token and/or secret, you'd need to do the approval dance again.
If you're not clever, the UI flow can sort of mirror the multi-step OAuth message flow. There is a better way.
Use a WebBrowser control, and open the authorize web page within the desktop app. When the user clicks "Allow", grab the response text from that WebBrowser control, extract the PIN automatically, then get the access tokens. You send 5 or 6 HTTP requests but the user needs to see only a single Allow/Deny dialog. Simple.
Like this:
If you've got the UI sorted, the only challenge that remains is to produce oauth-signed requests. This trips up lots of people because the oauth signing requirements are sort of particular. That's what the simplified OAuth Manager class does.
Example code to request a token:
var oauth = new OAuth.Manager();
// the URL to obtain a temporary "request token"
var rtUrl = "https://api.twitter.com/oauth/request_token";
oauth["consumer_key"] = MY_APP_SPECIFIC_KEY;
oauth["consumer_secret"] = MY_APP_SPECIFIC_SECRET;
oauth.AcquireRequestToken(rtUrl, "POST");
THAT'S IT. Simple. As you can see from the code, the way to get to oauth parameters is via a string-based indexer, something like a dictionary. The AcquireRequestToken method sends an oauth-signed request to the URL of the service that grants request tokens, aka temporary tokens. For Twitter, this URL is "https://api.twitter.com/oauth/request_token". The oauth spec says you need to pack up the set of oauth parameters (token, token_secret, nonce, timestamp, consumer_key, version, and callback), in a certain way (url-encoded and joined by ampersands), and in a lexicographically-sorted order, generate a signature on that result, then pack up those same parameters along with the signature, stored in the new oauth_signature parameter, in a different way (joined by commas). The OAuth manager class does this for you automatically. It generates nonces and timestamps and versions and signatures automatically - your app doesn't need to care or be aware of that stuff. Just set the oauth parameter values and make a simple method call. the manager class sends out the request and parses the response for you.
Ok, then what? Once you get the request token, you pop the web browser UI in which the user will explicitly grant approval. If you do it right, you'll pop this in an embedded browser. For Twitter, the URL for this is "https://api.twitter.com/oauth/authorize?oauth_token=" with the oauth_token appended. Do this in code like so:
var url = SERVICE_SPECIFIC_AUTHORIZE_URL_STUB + oauth["token"];
webBrowser1.Url = new Uri(url);
(If you were doing this in an external browser you'd use System.Diagnostics.Process.Start(url).)
Setting the Url property causes the WebBrowser control to navigate to that page automatically.
When the user clicks the "Allow" button a new page will be loaded. It's an HTML form and it works the same as in a full browser. In your code, register a handler for the DocumentedCompleted event of the WebBrowser control, and in that handler, grab the pin:
var divMarker = "<div id=\"oauth_pin\">"; // the div for twitter's oauth pin
var index = webBrowser1.DocumentText.LastIndexOf(divMarker) + divMarker.Length;
var snip = web1.DocumentText.Substring(index);
var pin = RE.Regex.Replace(snip,"(?s)[^0-9]*([0-9]+).*", "$1").Trim();
That's a bit of HTML screen scraping.
After grabbing the pin, you don't need the web browser any more, so:
webBrowser1.Visible = false; // all done with the web UI
...and you might want to call Dispose() on it as well.
The next step is getting the access token, by sending another HTTP message along with that pin. This is another signed oauth call, constructed with the oauth ordering and formatting I described above. But once again this is really simple with the OAuth.Manager class:
oauth.AcquireAccessToken(URL_ACCESS_TOKEN,
"POST",
pin);
For Twitter, that URL is "https://api.twitter.com/oauth/access_token".
Now you have access tokens, and you can use them in signed HTTP requests. Like this:
var authzHeader = oauth.GenerateAuthzHeader(url, "POST");
...where url is the resource endpoint. To update the user's status, it would be "http://api.twitter.com/1/statuses/update.xml?status=Hello".
Then set that string into the HTTP Header named Authorization.
To interact with third-party services, like TwitPic, you need to construct a slightly different OAuth header, like this:
var authzHeader = oauth.GenerateCredsHeader(URL_VERIFY_CREDS,
"GET",
AUTHENTICATION_REALM);
For Twitter, the values for the verify creds url and realm are "https://api.twitter.com/1/account/verify_credentials.json", and "http://api.twitter.com/" respectively.
...and put that authorization string in an HTTP header called X-Verify-Credentials-Authorization. Then send that to your service, like TwitPic, along with whatever request you're sending.
That's it.
All together, the code to update twitter status might be something like this:
// the URL to obtain a temporary "request token"
var rtUrl = "https://api.twitter.com/oauth/request_token";
var oauth = new OAuth.Manager();
// The consumer_{key,secret} are obtained via registration
oauth["consumer_key"] = "~~~CONSUMER_KEY~~~~";
oauth["consumer_secret"] = "~~~CONSUMER_SECRET~~~";
oauth.AcquireRequestToken(rtUrl, "POST");
var authzUrl = "https://api.twitter.com/oauth/authorize?oauth_token=" + oauth["token"];
// here, should use a WebBrowser control.
System.Diagnostics.Process.Start(authzUrl); // example only!
// instruct the user to type in the PIN from that browser window
var pin = "...";
var atUrl = "https://api.twitter.com/oauth/access_token";
oauth.AcquireAccessToken(atUrl, "POST", pin);
// now, update twitter status using that access token
var appUrl = "http://api.twitter.com/1/statuses/update.xml?status=Hello";
var authzHeader = oauth.GenerateAuthzHeader(appUrl, "POST");
var request = (HttpWebRequest)WebRequest.Create(appUrl);
request.Method = "POST";
request.PreAuthenticate = true;
request.AllowWriteStreamBuffering = true;
request.Headers.Add("Authorization", authzHeader);
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
MessageBox.Show("There's been a problem trying to tweet:" +
Environment.NewLine +
response.StatusDescription);
}
OAuth 1.0a is sort of complicated under the covers, but using it doesn't need to be.
The OAuth.Manager handles the generation of outgoing oauth requests, and the receiving and processing of oauth content in the responses. When the Request_token request gives you an oauth_token, your app doesn't need to store it. The Oauth.Manager is smart enough to do that automatically. Likewise when the access_token request gets back an access token and secret, you don't need to explicitly store those. The OAuth.Manager handles that state for you.
In subsequent runs, when you already have the access token and secret, you can instantiate the OAuth.Manager like this:
var oauth = new OAuth.Manager();
oauth["consumer_key"] = CONSUMER_KEY;
oauth["consumer_secret"] = CONSUMER_SECRET;
oauth["token"] = your_stored_access_token;
oauth["token_secret"] = your_stored_access_secret;
...and then generate authorization headers as above.
// now, update twitter status using that access token
var appUrl = "http://api.twitter.com/1/statuses/update.xml?status=Hello";
var authzHeader = oauth.GenerateAuthzHeader(appUrl, "POST");
var request = (HttpWebRequest)WebRequest.Create(appUrl);
request.Method = "POST";
request.PreAuthenticate = true;
request.AllowWriteStreamBuffering = true;
request.Headers.Add("Authorization", authzHeader);
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
MessageBox.Show("There's been a problem trying to tweet:" +
Environment.NewLine +
response.StatusDescription);
}
You can download a DLL containing the OAuth.Manager class here. There is also a helpfile in that download. Or you can view the helpfile online.
See an example of a Windows Form that uses this manager here.
WORKING EXAMPLE
Download a working example of a command-line tool that uses the class and technique described here:

facebook c# sdk: deleting a request-id

I am using the latest facebook c# sdk (http://facebooksdk.codeplex.com/). After i have sent an apprequest, i want to delete the request id.
This is how i do it at the moment:
var app = new FacebookClient(appid, appsecret);
app.Delete(requestID);
But i am not sure if its get deleted or not. If i try to see if it still exist using the graph api i get:
{
"error": {
"type": "GraphMethodException",
"message": "Unsupported get request."
}
}
But the user still has the request in his notification area. So my question is> Is the request deleted, or did i miss something? Thanks
var url = "https://graph.facebook.com/{0}?access_token={1}";
fb.Delete((String.Format(url, fullRequestId, fb.AccessToken)));
First parameter is requestId and user id like -> fullRequestId = requestId + "_" + fbUser.id
Second parameter is Accesstoken
I'm just getting started on this myself, but I'm guessing that you need to instantiate the FacebookClient with the authorization code from the user, not with your application data. The way I understand it, the request is sent by the user not your application. Hence the need to use the users authorization code to get information about the requeset.
This is what's working for me (sorry it's VB.Net):
Dim fb As FacebookClient = New FacebookClient(Config.FacebookAppId,Config.FacebookAppSecret)
Dim result = fb.Delete(String.Format("{0}_{1}?access_token={2}", facebookRequestId, facebookUserId, fb.AccessToken))

Categories