DotNetOpenAuth OAuth2 for Basecamp API - c#

I'm having some difficulties getting the OAuth2 working for the Basecamp API with DotNetOpenAuth, here's what I have so far, this is a ASP.NET MVC 4 web app.
public ActionResult Basecamp()
{
var server = new DotNetOpenAuth.OAuth2.AuthorizationServerDescription();
server.AuthorizationEndpoint = new Uri("https://launchpad.37signals.com/authorization/new");
server.TokenEndpoint = new Uri("https://launchpad.37signals.com/authorization/token");
var client = new DotNetOpenAuth.OAuth2.WebServerClient(
server, "my-basecamp-id", "my-basecamp-secret");
client.RequestUserAuthorization(returnTo: new Uri("http://localhost:55321/settings/basecampauth"));
Response.End();
return null;
}
[HttpPost]
public ActionResult BasecampAuth()
{
var server = new DotNetOpenAuth.OAuth2.AuthorizationServerDescription();
server.AuthorizationEndpoint = new Uri("https://launchpad.37signals.com/authorization/new");
server.TokenEndpoint = new Uri("https://launchpad.37signals.com/authorization/token");
var client = new DotNetOpenAuth.OAuth2.WebServerClient(
server, "my-basecamp-id", "my-basecamp-secret");
var state = client.ProcessUserAuthorization(Request);
Response.Write(state.AccessToken);
Response.End();
return null;
}
The is the error I get from Basecamp:
---
:error: "Unsupported type: nil. We support user_agent and web_server."
I've tried to search and look around, and could not found much interesting. Any help / pointer would be appreciated.
Thanks

Change this:
server.AuthorizationEndpoint = new Uri("https://launchpad.37signals.com/authorization/new");
to this:
server.AuthorizationEndpoint = new Uri("https://launchpad.37signals.com/authorization/new?type=web_server");
Note: i added type=web_server to the end of the uri.
Take from these official docs.

Related

Twitter API 1 to 1.1 Rss to Json Conversion--WPF Application using C#

Since twitter is depreciating API version 1 soon I've decided to convert an older Application to allow it to work with the new 1.1 API. From what I know about 1.1 I know you have to authenticate before making a call and use JSON rather than RSS for serializing the data. The application is WPF coded using xmal and c#
I am able to successfully authenticate using the LINQ to Twitter Library but I am lost when it comes to using JSON. Here is my code that I used for API v1
else if (auth.IsAuthorized && i == 2)
{
SyndicationClient client = new SyndicationClient();
SyndicationFeed feed = await client.RetrieveFeedAsync(new Uri("https://api.twitter.com/1/statuses/user_timeline.rss?screen_name=ScreenName"));
{
_model.Tweets.Clear();
foreach (var item in feed.Items)
{
_model.Tweets.Add(new Tweet
{
Name = "#ExampleHandle",
Message = item.Title.Text,
Image = new BitmapImage(new Uri("ms-appx:Assets/test_image", UriKind.RelativeOrAbsolute)),
});
}
}
}
}
And here is the code for the tweet class
public class Tweet
{
public String Name { get; set; }
public String Message { get; set; }
public ImageSource Image { get; set; }
}
I was wondering if someone could point me in the right direction for writing the JSON equivalent of this. Thanks in advance!
For those you read this question later on I was able to solve this problem. Below are my answers depending on your situation.
If you simply want to use Json instead of RSS you can do it like this:
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(new Uri("https://api.twitter.com/1/statuses/user_timeline.json?screen_name=ScreenName"));
string ApiResponse = await response.Content.ReadAsStringAsync();
List<Tweet> tweets = await JsonConvert.DeserializeObjectAsync<List<Tweet>>(ApiResponse);
_model.Tweets.Clear();
foreach (var item in tweets)
{
_model.Tweets.Add(new Tweet
{
Name = "#UserName",
Message = item.Text,
Image = new BitmapImage(new Uri("ms-appx:Assets/sampleLocalImage", UriKind.RelativeOrAbsolute)),
});
However because of API 1.1 you must be authenticated before EACH call to the API for this is used Linq to Twitter. Here is the code for Authorization:
var auth = new SingleUserAuthorizer
{
Credentials = new InMemoryCredentials
{
ConsumerKey = TwitterSettings.ConsumerKey,
ConsumerSecret = TwitterSettings.ConsumerKeySecret,
OAuthToken = TwitterSettings.AccessToken,
AccessToken = TwitterSettings.AccessTokenSecret,
}
};
auth.Authorize();
And the Code to Perform a Search(This is the code you want to use if using Twitter API 1.1):
var twitterCtx = new TwitterContext(auth);
var statusTweets =
from tweet in twitterCtx.Status
where tweet.Type == StatusType.User
&& tweet.ScreenName == "ScreenName"
select tweet;
_model.Tweets.Clear();
foreach (var item in statusTweets)
{
_model.Tweets.Add(new Tweet
{
Name = item.User.Name,
Message = item.Text,
Image = new BitmapImage(new Uri(item.User.ProfileImageUrl)),
});
I'm not familiar with the Twitter API, but I would assume some combination of HttpClient (if you're on .NET 4.0, you can get it here) and Newtonsoft.Json would be appropriate.
Newtonsoft.Json is not authored by Microsoft, but it is the package that everyone uses (including Microsoft's default web templates). The old Microsoft JSON serialization stuff is pretty much dead at this point.

DotNetOpenAuth Twitter Authenticaion Returning 401 Unauthorized

I'm starting to tear my hair out with Twitter and trying to signin a user!!! I have Facebook, Google, OpenId all working fine, just Twitter being a PAIN.
I am constantly getting 401 Unauthorized when I try to run my code and for the life of me cannot figure out why.
I have created a twitter client and and I'm using it with the InMemoryTokenManager from the DotNetOpenAuth sample solution. My Twitter client is here
public class TwitterClient
{
private string UserName { get; set; }
private static readonly ServiceProviderDescription ServiceDescription =
new ServiceProviderDescription
{
RequestTokenEndpoint = new MessageReceivingEndpoint(
"https://api.twitter.com/oauth/request_token",
HttpDeliveryMethods.GetRequest |
HttpDeliveryMethods.AuthorizationHeaderRequest),
UserAuthorizationEndpoint = new MessageReceivingEndpoint(
"https://api.twitter.com/oauth/authorize",
HttpDeliveryMethods.GetRequest |
HttpDeliveryMethods.AuthorizationHeaderRequest),
AccessTokenEndpoint = new MessageReceivingEndpoint(
"https://api.twitter.com/oauth/access_token",
HttpDeliveryMethods.GetRequest |
HttpDeliveryMethods.AuthorizationHeaderRequest),
TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() },
};
IConsumerTokenManager _tokenManager;
public TwitterClient(IConsumerTokenManager tokenManager)
{
_tokenManager = tokenManager;
}
public void StartAuthentication()
{
var request = HttpContext.Current.Request;
using (var twitter = new WebConsumer(ServiceDescription, _tokenManager))
{
var callBackUrl = new Uri(request.Url.Scheme + "://" + request.Url.Authority + "/Members/TwitterCallback");
twitter.Channel.Send(
twitter.PrepareRequestUserAuthorization(callBackUrl, null, null)
);
}
}
public bool FinishAuthentication()
{
using (var twitter = new WebConsumer(ServiceDescription, _tokenManager))
{
var accessTokenResponse = twitter.ProcessUserAuthorization();
if (accessTokenResponse != null)
{
UserName = accessTokenResponse.ExtraData["screen_name"];
return true;
}
}
return false;
}
}
And I have the following in the constructor of my MembersController which is instantiating the InMemoryTokenManager with the correct credentials
_tokenManager = new InMemoryTokenManager(ConfigUtils.GetAppSetting("TwitterAppId"), ConfigUtils.GetAppSetting("TwitterAppSecret"));
And my two Actions are
public ActionResult LogonTwitter()
{
var client = new TwitterClient(_tokenManager);
client.StartAuthentication();
return null;
}
public ActionResult TwitterCallback()
{
var client = new TwitterClient(_tokenManager);
if (client.FinishAuthentication())
{
return new RedirectResult("/");
}
// show error
return View("LogOn");
}
The error appears in the StartAuthentication() in my TwitterClient. As soon as it calls this line
twitter.Channel.Send(
twitter.PrepareRequestUserAuthorization(callBackUrl, null, null)
);
I get the following error
Error occurred while sending a direct message or getting the response.
Inner Exception: The remote server returned an error: (401) Unauthorized.
Anyone got any advice? I have spent most of yesterday and this morning trying to sort this. All the online examples I have tried also seem to get 401 Unauthorized back? Is there a known issue with DotNetOpenAuth and Twitter?
Any help very much appreciated.
I can't remember the exact terminology but have you set up a callback URL in the twitter app (as well as in the code)? I've had similar problems recently, even when developing locally I believe you need to set that value, even if its just a placeholder

PayPal Express Checkout SOAP API: Refunds

I use the PayPal Express Checkout SOAP service. For example here's a trimmed down version of the code to redirect the user to PayPal Sandbox when checking out:
var client = new PayPalAPIAAInterfaceClient();
var credentials = new CustomSecurityHeaderType() {
Credentials = new UserIdPasswordType() { ... }
};
var paymentDetails = new PaymentDetailsType() {
OrderTotal = new BasicAmountType() {
Value = string.Format("{0:0.00}", 100m)
}
};
var request = new SetExpressCheckoutReq() {
SetExpressCheckoutRequest = new SetExpressCheckoutRequestType() {
SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType() {
PaymentDetails = new PaymentDetailsType[] { paymentDetails },
CancelURL = "http://www.mysite.com" + Url.Action("Cancelled", "PayPalCheckout"),
ReturnURL = "http://www.mysite.com" + Url.Action("Index", "PayPalCheckout")
},
Version = "60.0"
}
};
var response = client.SetExpressCheckout(ref credentials, request);
return Redirect(string.Format("{0}?cmd=_express-checkout&token={1}", "https://www.sandbox.paypal.com/cgi-bin/webscr", response.Token));
I then handle the data when the user is returned to the ReturnUrl. This was taken from some code I found on another website.
I now need to add a refund facility to my site. I was wondering if anyone else has done this? I've tried searching online but can't seem to find anything that helps. I also tried doing it myself but the API isn't very intuitive.
I'd appreciate the help. Thanks
It would just need to be a RefundTransaction API call that you would need to execute. Are you trying to have your return page issue a refund based on a condition, or are you trying to create a GUI type of interface to allow someone to issue a refund for a transaction? Have you looked at the code samples for this within the SDK's that PayPal offers? You should be able to use this code.

Facebook permission error

public Form1()
{
InitializeComponent();
// The application key of the Facebook application used
fbService.ApplicationKey = "XXXXXXXXXXX";
// Add all needed permissions
List<Enums.ExtendedPermissions> perms = new List<Enums.ExtendedPermissions>
{
Enums.ExtendedPermissions.none
};
fbService.ConnectToFacebook(perms); //error here (The given key was not present in the dictionary.)
}
I mention the error where I get the error , as am new to facebook api and specially new to c# any explained answer is appriciated
Thank you
Use the static method on FacebookClient like this:
FacebookClient.SetDefaultHttpWebRequestFactory(uri => {
var request = new HttpWebRequestWrapper((HttpWebRequest)WebRequest.Create(uri));
request.Proxy = ......; // normal .net IWebProxy
return request;
});
See this answer also: Facebook SDK Proxy setting C#

How to get the Twitter Usertimeline with Tweetsharp

I try to get the last 20 statuses of the Usertimeline. So I search in the internet and get
the follow code:
TwitterUser twitterUser = TwitterUser.Show("Username").ResponseObject;
if (twitterUser != null)
{
UserTimelineOptions userTimelineOptions = new UserTimelineOptions();
userTimelineOptions.UserId = twitterUser.Id;
return TwitterTimeline.UserTimeline(userTimelineOptions).ResponseObject;
}
return null;
When I test it, I get the follow exception:
Unexpected token when deserializing object: StartObject. Line 1, position 1795.
I have no idea what's wrong so I hope you can help me!
Since Twitterizer is discontinued, I assumed that you moved to TweetSharp:
TwitterService service = new TwitterService("consumerKey", "consumerSecret");
service.AuthenticateWith("accessToken", "accessTokenSecret");
var options = new ListTweetsOnHomeTimelineOptions();
options.ExcludeReplies = true;
var tweets = service.ListTweetsOnHomeTimeline(options);
For Twitterizer:
UserTimelineOptions options = new UserTimelineOptions();
options.ScreenName = "Username";
var tweets = TwitterTimeline.UserTimeline(options).ResponseObject;
Twitterizer uses the 1.0 API and TweetSharp has the required oAuth for the 1.1 twitter API:
https://dev.twitter.com/blog/changes-coming-to-twitter-api
Try this
var twitterService = new TwitterService("consumerKey", "consumerSecret");
twitterService.AuthenticateWith("token", "tokenSecret");
var tweets = twitterService.ListTweetsOnHomeTimeline();

Categories