Error, missing TClient parameter - c#

I am following the google QuickStart google Drive .NET api video and I get an error at this point. I followed everything they said, I added all the required dlls. I am running windows 7 on a virutal machine, with Visual Studio 2012, could this be the issue?
After copy pasting their code, I cannot build it.
I get this error :
OAuth2.OAuth2Authenticator<TClient>' requires 1 type arguments
I could not find any info on google about this error , nor about the TClient
What is my missing TClient parameter?
The code
using System;
using System.Diagnostics;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Drive.v2;
using Google.Apis.Drive.v2.Data;
using Google.Apis.Util;
namespace GoogleDriveSamples
{
class DriveCommandLineSample
{
static void Main(string[] args)
{
String CLIENT_ID = "YOUR_CLIENT_ID";
String CLIENT_SECRET = "YOUR_CLIENT_SECRET";
// Register the authenticator and create the service
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET);
var auth = new OAuth2Authenticator(provider, GetAuthorization);
var service = new DriveService(auth);
File body = new File();
body.Title = "My document";
body.Description = "A test document";
body.MimeType = "text/plain";
byte[] byteArray = System.IO.File.ReadAllBytes("document.txt");
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "text/plain");
request.Upload();
File file = request.ResponseBody;
Console.WriteLine("File id: " + file.Id);
Console.WriteLine("Press Enter to end this process.");
Console.ReadLine();
}
private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
// Get the auth URL:
IAuthorizationState state = new AuthorizationState(new[] { DriveService.Scopes.Drive.GetStringValue() });
state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
Uri authUri = arg.RequestUserAuthorization(state);
// Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString());
Console.Write(" Authorization Code: ");
string authCode = Console.ReadLine();
Console.WriteLine();
// Retrieve the access token by using the authorization code:
return arg.ProcessUserAuthorization(authCode, state);
}
}
}

It looks like a setup or configuration issue in your solution. Try following the step-by-step instructions in the video recording of the Google Developers Live session where the .NET Drive quickstart is covered:
http://www.youtube.com/watch?v=uwrJSWqglTc

Related

How do I access SoftLayer object storage from a C# application for Android, developed in Visual Studio.

How do I access SoftLayer object storage from a C# application for Android, developed in Visual Studio. I am trying to add a Web Reference in VS so that I can use the storage API services. I have read http://sldn.softlayer.com/reference/objectstorageapi http://docs.openstack.org/developer/swift/api/object_api_v1_overview.html but still can't find how to do this.
Thanks, greatly appreciated - the next part of the task was to upload a file on the Android device to Object Storage. The code is a bit(!) messy and lacks error checking but hopefully will point anyone else trying to do this in the right direction.
var path = Android.OS.Environment.ExternalStorageDirectory ;
var filename = path + Java.IO.File.Separator + string.Format("{0}", prefix) + "mydata.txt";
string username = "SLOS1234567-1:SL1234567";
string apiKey = "1234567891234567891234567891234567891234567891234567891234567891";
string tokenval, URLval, URLcomp;
//Create a web request for authentication.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("https://syd01.objectstorage.softlayer.net/auth/v1.0");
//Get the headers associated with the request.
WebHeaderCollection myWebHeaderCollection = myHttpWebRequest.Headers;
//Add the X-Auth-User header (for OS user) in the request.
myWebHeaderCollection.Add("X-Auth-User", username);
//Add the X-Auth-Key header (for the API key) in the request.
myWebHeaderCollection.Add("X-Auth-Key",apiKey);
//Get the associated response - the auth token and storage URL.
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
tokenval = myHttpWebResponse.GetResponseHeader("X-Auth-Token");
URLval = myHttpWebResponse.GetResponseHeader("X-Storage-Url");
URLcomp = URLval + "/mycontainer/myDirectory/" + string.Format("{0}", prefix) + "mydata.txt";
//Upload the file
WebClient wc = new WebClient();
wc.Headers.Add("X-Auth-Token",tokenval);
wc.UploadFile(URLcomp, "PUT", filename);
For using C# for SoftLayer, there’s the next link available:
https://sldn.softlayer.com/article/C-Sharp
The next link provides Object Storage information for REST:
http://sldn.softlayer.com/blog/waelriac/managing-softlayer-object-storage-through-rest-apis
The next is an example of how C# can be used to interact with the SoftLayer API. The example follows the previous C# link.
using System;
using Newtonsoft.Json;
namespace GetHubNetworkStorage
{
class Program
{
static void Main(string[] args)
{
string username = "set me";
string apiKey = "set me";
authenticate authenticate = new authenticate();
authenticate.username = username;
authenticate.apiKey = apiKey;
SoftLayer_AccountService accountService = new SoftLayer_AccountService();
accountService.authenticateValue = authenticate;
try
{
// The result is an array of SoftLayer_Network_Storage objects and can be either iterated
// one by one to use the data or being displayed as a JSON value such in this example.
var hubNetworkStorages = accountService.getHubNetworkStorage();
string json = JsonConvert.SerializeObject(hubNetworkStorages, Formatting.Indented);
Console.WriteLine(json);
}
catch (Exception e)
{
Console.WriteLine("Can't retrieve SoftLayer_Network_Storage information: " + e.Message);
}
Console.ReadKey();
}
}
}
The next link also might help you if you decide to manage the object-storage-rest-api through curl but wrapped into C# code:
Making a cURL call in C#

using the exmple of google drive sdk for read spreadsheet

I am trying to use the google drive sdk exmple for read spread sheet.
when I am opening the example I am getting this error: "unhandled excption has occured......... returned unexpected result"404"
I am doing the following things:
1) in the login section I am entering my user name and password correctly (validate it a couple of times that it is correct)
2) go to tab :"Selected SpreadSheet". then the error comes up
The problem you are experiencing is similar to this question: Google drive API to C#
You can no longer log into Google Spreadsheets with the old user credentials (username/password only). You need to use OAuth 2.0 now (which requires you to create an app and credentials at console.developers.google.com).
You can use the example below for the authentication logic, and use the logic in the logic found in this question to actually manipulate the file:
Accessing Google Spreadsheets with C# using Google Data API
Here is my answer to the linked question in case it gets deleted in the future:
This example requires you to use the following nuget packages and their dependencies:
Google.GData.Spreadsheets
Also, you must go to https://console.developers.google.com and register your application and create credentials for it so you can enter your CLIENT_ID and CLIENT_SECRET.
This is the documentation I used to put together this example: https://developers.google.com/google-apps/spreadsheets/
using System;
using System.Windows.Forms;
using Google.GData.Client;
using Google.GData.Spreadsheets;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
string CLIENT_ID = "YOUR_CLIENT_ID";
string CLIENT_SECRET = "YOUR_CLIENT_SECRET";
string SCOPE = "https://spreadsheets.google.com/feeds https://docs.google.com/feeds";
string REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
OAuth2Parameters parameters = new OAuth2Parameters();
parameters.ClientId = CLIENT_ID;
parameters.ClientSecret = CLIENT_SECRET;
parameters.RedirectUri = REDIRECT_URI;
parameters.Scope = SCOPE;
string authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
MessageBox.Show(authorizationUrl);
Console.WriteLine("Please visit the URL in the message box to authorize your OAuth "
+ "request token. Once that is complete, type in your access code to "
+ "continue...");
parameters.AccessCode = Console.ReadLine();
OAuthUtil.GetAccessToken(parameters);
string accessToken = parameters.AccessToken;
Console.WriteLine("OAuth Access Token: " + accessToken);
GOAuth2RequestFactory requestFactory =
new GOAuth2RequestFactory(null, "MySpreadsheetIntegration-v1", parameters);
SpreadsheetsService service = new SpreadsheetsService("MySpreadsheetIntegration-v1");
service.RequestFactory = requestFactory;
SpreadsheetQuery query = new SpreadsheetQuery();
SpreadsheetFeed feed = service.Query(query);
// Iterate through all of the spreadsheets returned
foreach (SpreadsheetEntry entry in feed.Entries)
{
// Print the title of this spreadsheet to the screen
Console.WriteLine(entry.Title.Text);
}
Console.ReadLine();
}
}
}

How to create google-drive spreadsheet from .csv file?

I`d like to create spreadsheet from .csv file.
Code:
static void Main()
{
String CLIENT_ID = "<MY ID>";
String CLIENT_SECRET = "<MY SECRET>";
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET);
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
var service = new DriveService(auth);
File body = new File();
body.Title = "My spread";
body.Description = "A test spread";
body.MimeType = "application/vnd.google-apps.spreadsheet";
byte[] byteArray = System.IO.File.ReadAllBytes("spread.csv");
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
service.Files.Insert(body, stream, "application/vnd.google-apps.spreadsheet").Upload();
}
private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
string[] scopes = new string[] { "https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/userinfo.profile" };
IAuthorizationState state = new AuthorizationState(scopes);
state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
Uri authUri = arg.RequestUserAuthorization(state);
// Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString());
Console.Write(" Authorization Code: ");
string authCode = Console.ReadLine();
Console.WriteLine();
// Retrieve the access token by using the authorization code:
return arg.ProcessUserAuthorization(authCode, state);
}
After inserting file and clicking on it on google-drive page(logged as owner) I get message
"We're sorry.
The spreadsheet at this URL could not be found. Make sure that you have the right URL and that the owner of the spreadsheet hasn't deleted it"
When I change MimeType to "text/csv" and insert file, after clicking on it, I get message
"No preview available
This item was created with (MyApp'sName), a Google Drive app.
Download this file or use one of the apps you have installed to open it."
I can also right click on this file(that one created with "text/csv" MimeType) and choose option "Export to Google Docs" and this gives me result that I'd like to reach - spreadsheet file with my .csv's file content. But such indirect method doesn`t fully satify me. Is there any method to make spreadsheet file on google drive, with content from .csv file direct from my application?
I don't know c#, but on the basis it mirrors Java, within the line
service.Files.Insert(body, stream,
"application/vnd.google-apps.spreadsheet").Upload();
you need to insert the equivalent of
.setConvert(true)
also ...
the mimetype should be "text/csv"
I've found the answer :)
How to programmatically convert a file into an appropriate Google Documents format:
var service = new DriveService(new BaseClientService.Initializer
{
...
});
...
FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, _mimeType);
request.Convert = true;
request.Upload();

how to post to facebook page wall from .NET

I've created Facebook page.
I have no application secret and no access token.
I want to post to this page from my .NET desktop application.
How can I do it? Can anyone help please, where can I get access token for this?
Should I create a new Facebook Application? If yes, how can I grant permissions to this application to post on page's wall?
UPD1:
I have no website.
I need to post company's news from .NET desktop application to company's Facebook page.
All I have is Login/Password for Facebook Page Account.
UPD2:
I've created Facebook Application. With AppID/SecretKey. I can get access token. But...
How can I grant permissions to post to page's wall?
(OAuthException) (#200) The user hasn't authorized the application to perform this action
I have created a video tutorial showing how to do this at this location:
http://www.markhagan.me/Samples/Grant-Access-And-Post-As-Facebook-User-ASPNet
You will notice that, in my example, I am asking for both "publish_stream" and "manage_pages". This let's you also post on pages of which that users is an admin. Here is the full code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Facebook;
namespace FBO
{
public partial class facebooksync : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CheckAuthorization();
}
private void CheckAuthorization()
{
string app_id = "374961455917802";
string app_secret = "9153b340ee604f7917fd57c7ab08b3fa";
string scope = "publish_stream,manage_pages";
if (Request["code"] == null)
{
Response.Redirect(string.Format(
"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope));
}
else
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
//meh.aspx?token1=steve&token2=jake&...
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
client.Post("/me/feed", new { message = "markhagan.me video tutorial" });
}
}
}
}
You need to ask the user for the publish_stream permission. In order to do this you need to add publish_stream to the scope in the oAuth request you send to Facebook. The easiest way to do all of this is to use the facebooksdk for .net which you can grab from codeplex. There are some examples there of how to do this with a desktop app.
Once you ask for that permission and the user grants it you will receive an access token which you can use to post to your page's wall. If you need to store this permission you can store the access token although you might need to ask for offline_access permission in your scope in order to have an access token that doesn't expire.
You can use
https://www.nuget.org/packages/Microsoft.Owin.Security.Facebook/ to obtain users login and permission and
https://www.nuget.org/packages/Facebook.Client/
to post to feeds.
Below example is for ASP.NET MVC 5:
public void ConfigureAuth(IAppBuilder app)
{
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Facebook
var facebookOptions = new FacebookAuthenticationOptions
{
AppId = "{get_it_from_dev_console}",
AppSecret = "{get_it_from_dev_console}",
BackchannelHttpHandler = new FacebookBackChannelHandler(),
UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=id,name,email,first_name,last_name,location",
Provider = new FacebookAuthenticationProvider
{
OnAuthenticated = context =>
{
context.Identity.AddClaim(new Claim("FacebookAccessToken", context.AccessToken)); // user acces token needed for posting on the wall
return Task.FromResult(true);
}
}
};
facebookOptions.Scope.Add("email");
facebookOptions.Scope.Add("publish_actions"); // permission needed for posting on the wall
facebookOptions.Scope.Add("publish_pages"); // permission needed for posting on the page
app.UseFacebookAuthentication(facebookOptions);
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
}
}
On the callback you get user access token:
public ActionResult callback()
{
// Here we skip all the error handling and null checking
var auth = HttpContext.GetOwinContext().Authentication;
var loginInfo = auth.GetExternalLoginInfo();
var identityInfo = auth.GetExternalIdentity(DefaultAuthenticationTypes.ExternalCookie);
var email = loginInfo.Email // klaatuveratanecto#gmail.com
var name = loginInfo.ExternalIdentity.Name // Klaatu Verata Necto
var provider = loginInfo.Login.LoginProvider // Facebook | Google
var fb_access_token = loginInfo.identityInfo.FindFirstValue("FacebookAccessToken");
// Save this token to database, for the purpose of this example we will save it to Session.
Session['fb_access_token'] = fb_access_token;
// ...
}
Which then you can use to post to user's feed or page
public class postcontroller : basecontroller
{
public ActionResult wall()
{
var client = new FacebookClient( Session['fb_access_token'] as string);
var args = new Dictionary<string, object>();
args["message"] = "Klaatu Verata N......(caugh, caugh)";
try
{
client.Post("/me/feed", args); // post to users wall (feed)
client.Post("/{page-id}/feed", args); // post to page feed
}
catch (Exception ex)
{
// Log if anything goes wrong
}
}
}
You need to grant the permission "publish_stream".
Possibly the easiest way to do this is via Facebook PowerShell Module, http://facebookpsmodule.codeplex.com. This allows the same sort of operations as FacebookSDK, but via an IT-Admin scripting interface rather than a developer-oriented interface.
AFAIK there is still a limitation of Facebook Graph API that you will not be able to post references to other pages (e.g. #Microsoft) using the Facebook Graph API. This will apply to FacebookSDK, FacebookPSModule, and anything else built over Facebook Graph API.
You will get information on how to create a facebook app or link your website to facebook on https://developers.facebook.com/?ref=pf.
You will be able to download facebook sdk at http://facebooksdk.codeplex.com/. There are some good example given in the document section of the site.
public void PostImageOnPage()
{
string filename=string.Empty;
if(ModelState.IsValid)
{
//-------- save image in image/
if (System.Web.HttpContext.Current.Request.Files.Count > 0)
{
var file = System.Web.HttpContext.Current.Request.Files[0];
// fetching image
filename = Path.GetFileName(file.FileName);
filename = DateTime.Now.ToString("yyyyMMdd") + "_" + filename;
file.SaveAs(Server.MapPath("~/images/Advertisement/") + filename);
}
}
string Picture_Path = Server.MapPath("~/Images/" + "image3.jpg");
string message = "my message";
try
{
string PageAccessToken = "EAACEdEose0cBAAoWM3X";
// ————————create the FacebookClient object
FacebookClient facebookClient = new FacebookClient(PageAccessToken);
// ————————set the parameters
dynamic parameters = new ExpandoObject();
parameters.message = message;
parameters.Subject = "";
parameters.source = new FacebookMediaObject
{
ContentType = "image/jpeg",
FileName = Path.GetFileName(Picture_Path)
}.SetValue(System.IO.File.ReadAllBytes(Picture_Path));
// facebookClient.Post("/" + PageID + "/photos", parameters);// working for notification on user page
facebookClient.Post("me/photos", parameters);// woring using bingoapp access token not page in(image album) Post the image/picture to User wall
}
catch (Exception ex)
{
}
}

Post twitter update with Twitterizer

I have this piece of code:
var settings = WebConfigurationManager.AppSettings;
var consumerKey = settings["Twitter.ConsumerKey"];
var consumerSecret = settings["Twitter.ConsumerSecret"];
var authToken = settings["Twitter.OAuthToken"];
var authVerifier = settings["Twitter.OAuthVerifier"];
//var accessToken = GetAccessToken(
// consumerKey, consumerSecret, authToken, string.Empty);
var tokens = new OAuthTokens()
{
AccessToken = authToken,
AccessTokenSecret = authVerifier,
ConsumerKey = consumerKey,
ConsumerSecret = consumerSecret
};
TwitterStatus.Update(tokens, txtComment.Text);
All I need it to to is update my twitter status. Unfortunately it is not working. It only worked once when I initially logged in to twitter to grant the application access. I then stored the authToken and authVerifier so I can reuse them for future updates.
Any idea what is wrong?
UPDATE: I just changed the code to :
TwitterResponse<TwitterStatus> tweetResponse = TwitterStatus.Update(tokens, txtComment.Text);
if (tweetResponse.Result == RequestResult.Success)
lblMessage.Text = "Twitter status successfully posted.";
else
lblMessage.Text = string.Format("Twitter status update failed with Error: '{0}'",
tweetResponse.ErrorMessage);
and I get an error message: "Invalid / expired token".
You are storing the wrong values. The authToken and verifier values need to be quickly exchanged for an access token using OAuthUtility.GetAccessToken(...). The access token that is returned from that method is what should be stored and supplied to Twitterizer.
-Ricky
The Twitterizer Author
I wanted to be able to make a simple status update from C#/.NET, but didn't want to embed a big library.
So I wrote a small OAuth.Manager class that does this stuff.
It's described here:
OAuth with Verification in .NET
Sample code to update status:
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;
var url = "http://api.twitter.com/1/statuses/update.xml?status=Hello+World";
var authzHeader = oauth.GenerateAuthzHeader(url, "POST");
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
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 +
Environment.NewLine +
Environment.NewLine +
"You will have to tweet manually." +
Environment.NewLine);
}
For the first time through, you need to get an access token and secret. This is done in a multi-step process, starting with this code:
var oauth = new OAuth.Manager();
oauth["consumer_key"] = MY_APP_SPECIFIC_KEY;
oauth["consumer_secret"] = MY_APP_SPECIFIC_SECRET;
oauth.AcquireRequestToken("https://api.twitter.com/oauth/request_token", "POST");
Step 2 is to tell the user** to visit https://api.twitter.com/oauth/authorize?oauth_token=XXXX where xxxx is replaced with the actual token received, accessible in this case by oauth["token"]. Step 3 is to tell the user to grab (ctrl-c) the PIN from the webpage and paste it into your app, where you use the pin to get another type of token.
A better way is to automate that web UI sequence by using a Windows Form with an embedded WebBrowser control. When you set the Url property of that control to the appropriate value, it will show that webpage for you, inside the main form of your own app. You can also automate the part where you retrieve the PIN. This reduces context switches for your user and makes things simpler to understand.
Anyway, with the pin you do, step 4:
oauth.AcquireAccessToken("https://api.twitter.com/oauth/access_token",
"POST",
pin);
...which sends out another HTTP REST request, and when it returns you will have an accesss token and secret, available in oauth["token"] and oauth["token_secret"].
This authorization stuff with the web UI needs to happen only once; after you get the access token and secret once, you can store them and re-use them. They never expire, says Twitter.
You can then proceed to sending the status update...
var url = "http://api.twitter.com/1/statuses/update.xml?status=Hello+World";
var authzHeader = oauth.GenerateAuthzHeader(url, "POST");
...
...as above.
I know I am late to the game, but I created an end-to-end video tutorial showing exactly how to do this: I create an application on dev.twitter.com, install twitterizer using nuget, write the code to handle the oauth and finally write the code to use the access tokens received from twitter to make a tweet.
Video: http://www.youtube.com/watch?v=TGEA1sgMMqU
Tutorial: http://www.markhagan.me/Samples/Grant-Access-And-Tweet-As-Twitter-User-ASPNet
Code (in case you don't wan to leave this page):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Twitterizer;
namespace PostFansTwitter
{
public partial class twconnect : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var oauth_consumer_key = "YOUR_CONSUMER_KEY_HERE";
var oauth_consumer_secret = "YOUR_CONSUMER_SECRET_KEY_HERE";
if (Request["oauth_token"] == null)
{
OAuthTokenResponse reqToken = OAuthUtility.GetRequestToken(
oauth_consumer_key,
oauth_consumer_secret,
Request.Url.AbsoluteUri);
Response.Redirect(string.Format("http://twitter.com/oauth/authorize?oauth_token={0}",
reqToken.Token));
}
else
{
string requestToken = Request["oauth_token"].ToString();
string pin = Request["oauth_verifier"].ToString();
var tokens = OAuthUtility.GetAccessToken(
oauth_consumer_key,
oauth_consumer_secret,
requestToken,
pin);
OAuthTokens accesstoken = new OAuthTokens()
{
AccessToken = tokens.Token,
AccessTokenSecret = tokens.TokenSecret,
ConsumerKey = oauth_consumer_key,
ConsumerSecret = oauth_consumer_secret
};
TwitterResponse<TwitterStatus> response = TwitterStatus.Update(
accesstoken,
"Testing!! It works (hopefully).");
if (response.Result == RequestResult.Success)
{
Response.Write("we did it!");
}
else
{
Response.Write("it's all bad.");
}
}
}
}
}

Categories