List of favorites using tweet sharp - c#

I am having trouble implementing a function to get the list of favorite tweets for a given user using tweetsharp. Does anyone have suggestion on how i should go about doing this? Thanks!
[HttpGet]
public JsonResult GetTwitterFavoritesList(string oauth_token, string oauth_verifier, string screen_name)
{
try
{
var requestToken = new OAuthRequestToken { Token = oauth_token };
TwitterService service = new TwitterService(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET);
OAuthAccessToken accessToken = service.GetAccessToken(requestToken, oauth_verifier);
service.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);
ListFavoriteTweetsOptions options = new ListFavoriteTweetsOptions();
options.ScreenName = screen_name;
options.MaxId = 100;
IEnumerable<TwitterStatus> favoritesList = service.ListFavoriteTweets(options);
return Json(favoritesList, JsonRequestBehavior.AllowGet);
}
catch(Exception)
{
return Json(false);
}
}

Your problem is probably the MaxId = 100. That property is used for "paging" and setting it to 100 means no tweet with an id of more than 100 will be returned. Given all current tweets are in the billions, the query won't return anything.
If you were trying to restrict the number of tweets returned, you want to use the Count property, if one exists for that method.

I resolved this issue by using the access token and access secret i got from the initial authorization. So to get favorites i did not need to do a second authorization. i saved the access token and secret and just used them again in this line
service.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);

Related

async and await with Twitter direct_messages/events using LinqToTwitter

I'm really stuck in this for days. I'm using LinqToTwitter with ASP.Net C#
I'm trying to get the new DirectMessages work, I followed the examples but with no luck.
I want the function to work on Button click, so what I tried is:
BtnClick:
`
protected void Btn1_Click(object sender, EventArgs e)
{
string x = MyTest().Result;
}
`
MyTest:
`
static async Task<string> mytest()
{
AspNetAuthorizer auth = DoAuthorization();
var twitterCtx = new TwitterContext(auth);
List<DMEvent> AllDmEvents = new List<DMEvent>();
string Cursor;
DirectMessageEvents dmResponse =
await
(from dm in twitterCtx.DirectMessageEvents
where dm.Type == DirectMessageEventsType.List &&
dm.Count == 10
select dm)
.SingleOrDefaultAsync(); //In debugging mode, after this line is executed, it will go away and keep loading forever and never come back
AllDmEvents.AddRange(dmResponse.Value.DMEvents);
Cursor = dmResponse.Value.NextCursor;
string xxx = (JsonConvert.SerializeObject(AllDmEvents, Formatting.None));
return xxx;
}
`
DoAuthorization:
`
static AspNetAuthorizer DoAuthorization()
{
AspNetAuthorizer auth = new AspNetAuthorizer();
auth = new AspNetAuthorizer
{
CredentialStore = new SessionStateCredentialStore
{
ConsumerKey = "MyConsumerKey",
ConsumerSecret = "MyConsumerSecret ",
OAuthToken = "MyOAuthToken ",
OAuthTokenSecret = "MyOAuthTokenSecret ",
ScreenName = "MyUserName",
UserID = 12345678
}
};
return auth;
}`
Any help would be SO much appreciated!
The DoAuthorization() in your code looks like it came from the Console sample and that won't work with ASP.NET. The reason is that ASP.NET is stateless and the OAuth process brings you to the Twitter site and back. So, you have to break up the authorization into two pieces: Begin and Complete.
I'm guessing that you're using ASP.NET MVC, but the concept is similar (but different) if you're using WebForms). Here's the Begin part:
public class OAuthController : AsyncController
{
public ActionResult Index()
{
return View();
}
public async Task<ActionResult> BeginAsync()
{
var auth = new MvcAuthorizer
{
CredentialStore = new SessionStateCredentialStore
{
ConsumerKey = ConfigurationManager.AppSettings["consumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"]
}
};
Notice that it uses an MvcAuthorizer, populating credentials. Once you have the MvcAuthorizer instance, redirect the user to Twitter for authorization, like this:
string twitterCallbackUrl = Request.Url.ToString().Replace("Begin", "Complete");
return await auth.BeginAuthorizationAsync(new Uri(twitterCallbackUrl));
}
That send the user to the Twitter authorization page, where they give your app permission to operate on their behalf. Twitter will redirect the user back to twitterCallback, which is why the code above modified the URL to replace the Begin with Complete in your URL. So, Twitter redirect the user back to your app, which calls the CompleteAsync() action below:
public async Task<ActionResult> CompleteAsync()
{
var auth = new MvcAuthorizer
{
CredentialStore = new SessionStateCredentialStore()
};
await auth.CompleteAuthorizeAsync(Request.Url);
// This is how you access credentials after authorization.
// The oauthToken and oauthTokenSecret do not expire.
// You can use the userID to associate the credentials with the user.
// You can save credentials any way you want - database,
// isolated storage, etc. - it's up to you.
// You can retrieve and load all 4 credentials on subsequent
// queries to avoid the need to re-authorize.
// When you've loaded all 4 credentials, LINQ to Twitter will let
// you make queries without re-authorizing.
//
//var credentials = auth.CredentialStore;
//string oauthToken = credentials.OAuthToken;
//string oauthTokenSecret = credentials.OAuthTokenSecret;
//string screenName = credentials.ScreenName;
//ulong userID = credentials.UserID;
//
return RedirectToAction("Index", "Home");
}
Now that your app has the user's permissions, grab their tokens and hold them for subsequent queries so you don't have to continue the OAuth process every time the user wants to use your app. Please see the notes in the code on how to get those credentials.
Now, when you want to perform a query, instantiate an MvcAuthorizer, like this:
static async Task<string> mytest()
{
var auth = new MvcAuthorizer
{
CredentialStore = new SessionStateCredentialStore()
};
var twitterCtx = new TwitterContext(auth);
List<DMEvent> AllDmEvents = new List<DMEvent>();
string Cursor;
DirectMessageEvents dmResponse =
await
(from dm in twitterCtx.DirectMessageEvents
where dm.Type == DirectMessageEventsType.List &&
dm.Count == 10
select dm)
.SingleOrDefaultAsync(); //In debugging mode, after this line is executed, it will go away and keep loading forever and never come back
AllDmEvents.AddRange(dmResponse.Value.DMEvents);
Cursor = dmResponse.Value.NextCursor;
string xxx = (JsonConvert.SerializeObject(AllDmEvents, Formatting.None));
return xxx;
}
You can see how the first statement of your modified myTest() method instantiates MvcAuthorizer with SessionStateCredentialStore, holding your credentials.
Finally, at the point in time where you want the user to authorize your app with Twitter (log in, on first query, or any other timing of your choice), check to see whether they're already authorized and re-direct if not, like this:
public ActionResult Index()
{
if (!new SessionStateCredentialStore().HasAllCredentials())
return RedirectToAction("Index", "OAuth");
return View();
}
Notice how the code above calls HasAllCredentials() on a SessionStateCredentialStore instance. I assume that you'll be adding your own logic to determine when to load the user's credentials, but wanted you to be aware of the HasAllCredentials() helper method to make it easier to know when the user must be authorized.
For more info, visit the LINQ to Twitter OAuth docs. The LINQ to Twitter source code also has Samples on how to use OAuth.

How to get sms records by subaccount

I know about using the class MessageListRequest to ask for a list of SMS messages from the Twilio server. There is no Subaccount filter as a parameter when defining the request. Does anyone know how to get the message list for only those messages associated with a specific subaccount? Thanks.
I have used the subaccount credentials to get the list of messages but the result of the Twilio request is a list object with zero entries . I know there are messages in the sub account because I can see them in the Twilio dashboard for the subaccount. Can you please tell me what I am doing wrong in this code?
var aRequest = new MessageListRequest();
aRequest.From = null;
aRequest.To = null;
aRequest.DateSent = null;
GetSubAccounts();
if (mySubAccountSid != null)
{
TwilioRestClient aTwilio = new TwilioRestClient(mySubAccountSid,
mySubAccountToken);
var aResult = aTwilio.ListMessages(aRequest);
if (aResult != null)
{
foreach (var aMessage in aResult.Messages)
{
mySQLManager.UpdateSMSLogTable(aMessage, myVesselID);
Methods.WriteLog(aMessage.Sid + " " + aMessage.To + " " + aMessage.Body);
}
}
return aList;
}
The simple way, which is likely what you mean, is even if you use
your master credentials for auth, but a subaccount SID in the URL
provided for Message List Resource,
/2010-04-01/Accounts/{AccountSid}/Messages, you get the resources
for that subaccount.
The C# library has a GetAccount method that takes an account
SID and returns the Account object (representing the subaccount) for
which you should then be able to make API calls as normal.
var account = twilio.GetAccount("SUBACCOUNT_SID");
Eventually if you want to track things in a more sophisticated
manner, you may decide to use UsageRecords.
Using UsageRecords combined with Subaccounts will allow you
to build usage reports and set triggers based upon some behavior.
The two links provided above will show you how to work with each in
more detail but an example of grabbing a list of all-time usage for
sms would like this in C#:
// Download the twilio-csharp library from twilio.com/docs/csharp/install
using System;
using Twilio;
class Example
{
static void Main(string[] args)
{
// Find your Account Sid and Auth Token at twilio.com/user/account
string AccountSid = "ACCOUNT_SID";
string AuthToken = "AUTH_TOKEN";
var twilio = new TwilioRestClient(AccountSid, AuthToken);
var records = twilio.ListUsage("sms", null, null, null, null, null);
foreach (var record in records.UsageRecords)
{
Console.WriteLine(record.Count);
}
}
}

How can I get the picture of a Facebook event using server side code?

I'm writing a web app that pulls events data from Facebook, and I can get a lot of the information using an app token, but not the picture, which requires a client token, as documented here: https://developers.facebook.com/docs/graph-api/reference/v2.2/event/picture
I want the code that grabs the event data to run automatically on a server at regular intervals, without requiring a user to log in to their Facebook account.
Is there a way I can get a client token without user intervention? If not, is there another way I can get the event picture?
This is the code I am using to get the event data, using C# and JSON.Net (This gets a list of events created by the specified user - ResortStudios):
var fb = new FacebookClient();
dynamic result = fb.Get( "oauth/access_token", new
{
client_id = "XXXXXXXXXXX",
client_secret = "XXXXXXXXXXXXXXXXXXXXXXXXX",
grant_type = "client_credentials"
} );
var apptoken = result.access_token;
fb = new FacebookClient(apptoken);
result = fb.Get("ResortStudios/events");
JObject events = JObject.Parse(result.ToString());
JArray aEvents = (JArray)events["data"];
string s = aEvents.ToString();
List<fbEvent> lEvents = JsonConvert.DeserializeObject<List<fbEvent>>(s);
I've not tried this but something occurred to me that might work for you. Have you considered something like storing it a non-persistent data store like session state? Then, using the Facebook SDK for .NET, you create an ActionResult for UserInfo, like below. (I know this isn't directly applicable but I hoped it might get you thinking.)
//http://facebooksdk.net/docs/web/ajax-requests/
public ActionResult UserInfo()
{
var accessToken = Session["AccessToken"].ToString();
var client = new FacebookClient(accessToken);
dynamic result = client.Get("me", new { fields = "name,id" });
return Json(new
{
id = result.id,
name = result.name,
});
}

Retrieve instagram access token on page load

I want to show my user feed on my website and what I intend to do is to authenticate my own user account each time a user visits the page, and in that way buypass that the user have to log in to his instagram account.
My problem is that I'm having a hard time retrieving the instagram access token through a HttpWebRequest..
See the following NON working code sample:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.instagram.com/oauth/authorize?client_id=xxxxxxxxxxxxxxxxxxxxxx&redirect_uri=http://mywebsite.com&response_type=token");
request.Method = "POST";
request.AllowAutoRedirect = false;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string redirectUrl = response.ResponseUri.ToString();
HttpContext.Current.Response.Write(redirectUrl);
HttpContext.Current.Response.End();
If I paste the url in my browser I get a redirect to http://mysite.com/#access_token=xxxxxxxxxxxxxx and everything seems fine, but when I try to execute the code above, I can't retrieve the correct uri due to some in between redirects before the final url.
Any help would be much appriciated..
I recommend you to use Instasharp library. InstaSharp is a C# library that wraps the Instagram API and makes it easy to write applications with Instagram data. It has a very easy method to get access token for a user. Check its API.
Unfortunately the documentation for Instasharp currently provided has a few errors. I.e. The documentation says OAuthInfo, when such a class does not exist.
Here is some code that works for me.
Notice you don't seem to need to pass a User Object at all (not sure why you would need to anyway)
Also note, that the authenticated and non authenticated methods allow you pass different params, count being the most important one. I've noticed that regardless of the count you pass, an arbitrary number of results is returned, e.g. 33 for authenticated and 13 for authenticated for the same search term. InstagramResult is my wrapper class for the object and Config holds the InstagramAuthorisationModel and InstagramAuthorisationModel holds the static keys created when signing up for a developer account.
public class InstagramService : IInstagramService
...
public InstagramConfig Config
{
get{return new InstagramConfig("https://api.instagram.com/v1", "https://api.instagram.com/oauth", InstagramAuthorisationModel.ApplicationId, InstagramAuthorisationModel.Secret, InstagramAuthorisationModel.RedirectUri);}
}
private AuthInfo UserAuthInfo()
{
return new AuthInfo()
{
// User =new UserInfo(){},
Access_Token = GetInstagramAccessToken()
};
}
public string GetInstagramAccessToken()
{
return _socialMediaRepository.GetInstagramAccessToken(_userApiKey);
}
public List<InstagramResult> Search(string searchTag, int count)
{
var auth = UserAuthInfo();
var tags = new InstaSharp.Endpoints.Tags.Authenticated(Config, auth);
var searchresult = tags.Recent(searchTag);
return searchresult.Data.Select(media => new InstagramResult()
{
Media = media,
image = media.Images.LowResolution.Url
})
.ToList();
}
..

401 when attempting to Tweet with Linq to Twitter

So I've looked at all the of the suggestions from the Linq to Twitter documentation regarding 401 statuses with Oauth and I honestly don't know what I'm doing wrong.
var auth = new PinAuthorizer
{
Credentials = new InMemoryCredentials
{
ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"],
//OAuthToken = ConfigurationManager.AppSettings["twitterOAuthToken"], //don't include this
//AccessToken = ConfigurationManager.AppSettings["twitterAccessToken"] //or this for new users.
},
//
UseCompression = true,
GoToTwitterAuthorization = pageLink => Process.Start(pageLink),
GetPin = () =>
{
Console.WriteLine("/nAfter twitter authorizes your application you will be returned here or something/n");
Console.Write("Enter Pin here:");
return Console.ReadLine();
}
};
auth.Authorize();
using (var twitterCtx = new TwitterContext(auth, "https://api.twitter.com/1/",
"https://search.twitter.com/"))
{
try
{
twitterCtx.Log = Console.Out;
Console.WriteLine("Please provide tweet text");
string tweet = Console.ReadLine();
twitterCtx.UpdateStatus(tweet);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
I've ran this using the Pin Authentication method as well as the single user method (providing the oauth keys with config file). I'm able to query tweets but I can't update my status or send direct messages (I receive a 403 forbidden when I try to DM). I've provided a callback URL (albeit fake) so I can't think of why this isn't working. Any help would be appreciated.
PS this runs in Main, not sure if that matters
All you need is this overload of the TwitterContext ctor and it will use the proper base URLs:
new TwitterContext(auth)
The example you're using is for v1.0 URLs and LINQ to Twitter is on Twitter API v1.1 now. It will default to the proper base URLs.
If you're querying okay, but getting errors on update and DM, double check to make sure you aren't trying to tweet the same text. That's why I append a DateTime.Now to the end of test tweets - to guarantee uniqueness.

Categories

Resources