Error while getting public data from twitter - c#

String status;
IEnumerable<TwitterStatus> twitterStatus = twitterService.ListTweetsOnPublicTimeline();
foreach(String status in twitterStatus)
{
Console.WriteLine(twitterStatus);
}
Why it give can not convert string type error in foreach loop ?
this is my whole code
namespace TweetingTest
{
class Program
{
static void Main(string[] args)
{
TwitterClientInfo twitterClientInfo = new TwitterClientInfo();
twitterClientInfo.ConsumerKey = ConsumerKey; //Read ConsumerKey out of the app.config
twitterClientInfo.ConsumerSecret = ConsumerSecret; //Read the ConsumerSecret out the app.config
TwitterService twitterService = new TwitterService(twitterClientInfo);
if (string.IsNullOrEmpty(AccessToken) || string.IsNullOrEmpty(AccessTokenSecret))
{
//Now we need the Token and TokenSecret
//Firstly we need the RequestToken and the AuthorisationUrl
OAuthRequestToken requestToken = twitterService.GetRequestToken();
string authUrl = twitterService.GetAuthorizationUri(requestToken).ToString();
//authUrl is just a URL we can open IE and paste it in if we want
Console.WriteLine("Please Allow This App to send Tweets on your behalf");
//Process.Start(authUrl); //Launches a browser that'll go to the AuthUrl.
//Allow the App
Console.WriteLine("Enter the PIN from the Browser:");
string pin = Console.ReadLine();
OAuthAccessToken accessToken = twitterService.GetAccessToken(requestToken, pin);
string token = accessToken.Token; //Attach the Debugger and put a break point here
string tokenSecret = accessToken.TokenSecret; //And another Breakpoint here
Console.WriteLine("Write Down The AccessToken: " + token);
Console.WriteLine("Write Down the AccessTokenSecret: " + tokenSecret);
}
twitterService.AuthenticateWith(AccessToken, AccessTokenSecret);
//Console.WriteLine("Enter a Tweet");
//string tweetMessage;
//string data;
//string ListTweetsOnPublicTimeline;
//string TwitterUserStreamStatus = ListTweetsOnPublicTimeline();
//TwitterStatus=ListTweetsOnPublicTimeline();
//tweetMessage = Console.ReadLine();
//ListTweetsOnPublicTimeline = Console.ReadLine();
//TwitterStatus twitterStatus = twitterService.SendTweet(tweetMessage);
//TwitterStatus twitterStatus = twitterService.ListTweetsOnPublicTimeline();
//String status;
IEnumerable<TwitterStatus> tweets = twitterService.ListTweetsOnPublicTimeline();
foreach(var tweet in tweets)
{
Console.WriteLine(tweet);
//Console.WriteLine("{0} says '{1}'", tweet.User.ScreenName, tweet.Text);
}
//twitterStatus=Console.ReadLine();
}
This is my whole code on which I am working and facing just one error on foreach loop which is my lack of knowledge in C#

You will need something like this..
using TweetSharp;
TwitterService service = new TwitterService();
IEnumerable<TwitterStatus> tweets = service.ListTweetsOnPublicTimeline();
foreach (var tweet in tweets)
{
Console.WriteLine("{0} says '{1}'", tweet.User.ScreenName, tweet.Text);
}
Also try this code to see why it is failing.. try to debug response.StatusCode
using TweetSharp;
TwitterService service = new TwitterService();
IAsyncResult result = service.ListTweetsOnPublicTimeline(
(tweets, response) =>
{
if(response.StatusCode == HttpStatusCode.OK)
{
foreach (var tweet in tweets)
{
Console.WriteLine("{0} said '{1}'", tweet.User.ScreenName, tweet.Text);
}
}
});
More here : https://github.com/danielcrenna/tweetsharp

The object you are itterating through is of type "TwitterStatus", not string... so you are confusing it when you try to automatically cast a TwitterStatus object as a string.
Your question is very vague, so I'm going to assume your TitterStatus object has a "Text" property for the purposes of this answer.
foreach(TwitterStatus status in twitterStatus)
{
Console.WriteLine(status.Text);
}
(just replace the ".Text" with whatever property of TwitterStatus
holds the status text)

Related

Getting error in Twitterizer (update status or tweet) in c#

Actually i want to loop the twitterizer or update the tweet everytime when the loop iterate. When it starts the loop i=0 then everthing works fine.But when the loop iterate and i=1 then i am getting the below error in at enter image description here
An exception of type 'Twitterizer.TwitterizerException' occurred in Twitterizer2.dll but was not handled in user code
Additional information: The remote server returned an error: (401) Unauthorized.
string x;
var list2 = (List<string>)Session["title"];
if (list2 == null)
{
x = "No new Products Found";
}
else
{
x = string.Join(",", list2);
// x= list2[0];
}
//foreach (string x in list2)
//{
// Your code
for(int i=0;i<3;i++)
{
var oauth_consumer_key = "[REDACTED]";
var oauth_consumer_secret = "[REDACTED]";
if (Request["oauth_token"] == null)
{
OAuthTokenResponse reqToken = OAuthUtility.GetRequestToken(
oauth_consumer_key,
oauth_consumer_secret,
Request.Url.AbsoluteUri);
if(reqToken !=null)
{
Session["reqToken"] = reqToken;
}
string mx = Session["reqToken"].ToString();
Response.Redirect(string.Format("http://twitter.com/oauth/authorize?oauth_token={0}",
reqToken.Token));
}
else
{
string fx = Session["reqToken"].ToString();
string requestToken = Request["oauth_token"].ToString();
string pin = Request["oauth_verifier"].ToString();
var tokens = OAuthUtility.GetAccessToken(
oauth_consumer_key,
oauth_consumer_secret,
requestToken,
pin);
if(tokens!=null)
{
Session["tokens"] = tokens;
}
//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).");
Twitterizer.TwitterResponse<TwitterStatus> response = TwitterStatus.Update(accesstoken, x, new StatusUpdateOptions() { UseSSL = true, APIBaseAddress = "http://api.twitter.com/1.1/" });
if (response.Result == RequestResult.Success)
{
// Response.Redirect("https://twitter.com/");
}
else
{
// Response.Redirect("https://twitter.com/");
}
}
}
}
Please help me i spent many hours on that but i do not know where is the error.

Remove the twitter authorization during program running in C#

I am doing the tweets automatically from getting data from json url. But during the program execution after some seconds twitter always require to press the authorization button and then the program will continue. But now i want to place more than 10 urls in my program and it will create the heavy problem to press the authorization button all the time. Please help me in this regard to remove the authorization process every time. Below is the coding of the twitter by twitterizer.
[enter image description here][1]
public void twitter_function()
{
string x;
var list2 = (List<string>)Session["title"];
if (list2 == null)
{
x = "No new Products Found";
}
else
{
x = string.Join(",", list2);
// x= list2[0];
}
//foreach (string x in list2)
//{
// Your code
var oauth_consumer_key = "[REDACTED]";
var oauth_consumer_secret = "[REDACTED]";
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).");
Twitterizer.TwitterResponse<TwitterStatus> response = TwitterStatus.Update(accesstoken, x, new StatusUpdateOptions() { UseSSL = true, APIBaseAddress = "http://api.twitter.com/1.1/" });
if (response.Result == RequestResult.Success)
{
Response.Redirect("https://twitter.com/");
}
else
{
Response.Redirect("https://twitter.com/");
}
}
}
It is the coding for tweets and it requires "Authorize app" button every time. I want to remove it from program and want to run my program without any interruption. Thanks

RallyAPI - Change TestCase owner via API

I have the user object from the GetCurrentUser() call, and I have the Test Case as a DynamicJsonObject, but simply setting the TestCase["Owner"] to the current user doesn't work - anybody got a code sample where this works?
GAAH! I was so close, that I stumbled on the answer:
DynamicJsonObject owner = new DynamicJsonObject();
owner["Owner"] = restApi.GetCurrentUser()["_ref"].ToString();
restApi.Update(existingTestCase["_ref"], owner);
Works perfectly - thanks for the help.
Owner attribute is a reference to a User object. Here is a Java example when a test case is created and the owner is set:
public class CreateTCsetOwner {
public static void main(String[] args) throws URISyntaxException, IOException {
String host = "https://rally1.rallydev.com";
String username = "user#co.com";
String password = "secret";
String wsapiVersion = "v2.0";
String projectRef = "/project/222";
String workspaceRef = "/workspace/111";
String applicationName = "RestExample_createTCsetOwner";
RallyRestApi restApi = new RallyRestApi(
new URI(host),
username,
password);
restApi.setWsapiVersion(wsapiVersion);
restApi.setApplicationName(applicationName);
QueryRequest userRequest = new QueryRequest("User");
userRequest.setFetch(new Fetch("UserName", "DisplayName"));
userRequest.setQueryFilter(new QueryFilter("UserName", "=", "otheruser#co.com"));
QueryResponse userQueryResponse = restApi.query(userRequest);
String userRef = "";
for (int i=0; i<userQueryResponse.getResults().size();i++){
JsonObject userJsonObject = userQueryResponse.getResults().get(i).getAsJsonObject();
System.out.println("UserName: " + userJsonObject.get("UserName"));
userRef = userJsonObject.get("_ref").getAsString();
}
try {
for (int i=0; i<1; i++) {
System.out.println("Creating a test case...");
JsonObject newTC = new JsonObject();
newTC.addProperty("Name", "some test");
newTC.addProperty("Owner", userRef);
CreateRequest createRequest = new CreateRequest("testcase", newTC);
CreateResponse createResponse = restApi.create(createRequest);
if (createResponse.wasSuccessful()) {
System.out.println(String.format("Created %s", createResponse.getObject().get("_ref").getAsString()));
//Read TC
String ref = Ref.getRelativeRef(createResponse.getObject().get("_ref").getAsString());
System.out.println(String.format("\nReading testcase %s...", ref));
GetRequest getRequest = new GetRequest(ref);
} else {
String[] createErrors;
createErrors = createResponse.getErrors();
System.out.println("Error occurred creating a testcase: ");
for (int j=0; i<createErrors.length;j++) {
System.out.println(createErrors[j]);
}
}
}
} finally {
//Release all resources
restApi.close();
}
}
}

How to update status on twitter using C# and LINQ to Twitter library

I am writing an Metrol Style App to update status on my Twitter. I use LINQ to Twitter library. But I don't understand why my app throws exception 401 Unauthorized. Here is my code:
private void UpdateStatus()
{
// configure the OAuth object
var auth = new SingleUserAuthorizer
{
Credentials = new InMemoryCredentials
{
ConsumerKey = "ConsumerKey",
ConsumerSecret = "ConsumerSecret",
OAuthToken = "TwitterAccessToken",
AccessToken = "TwitterAccessTokenSecret"
}
};
using (var twitterCtx = new TwitterContext(auth, "https://api.twitter.com/1/", "https://search.twitter.com/"))
{
var tweet = twitterCtx.UpdateStatus("Hi everybody!"); // error here
viewTextBlock.Text = String.Empty;
viewTextBlock.Text = viewTextBlock.Text + "Status returned: " +
"(" + tweet.StatusID + ")" +
tweet.User.Name + ", " +
tweet.Text + "\n";
}
}
I just posted a blog entry on using OAuth in Windows 8 with LINQ to Twitter:
http://geekswithblogs.net/WinAZ/archive/2012/07/02/using-linq-to-twitter-oauth-with-windows-8.aspx
I also included a 401 FAQ in the LINQ to Twitter docs here:
http://linqtotwitter.codeplex.com/wikipage?title=LINQ%20to%20Twitter%20FAQ&referringTitle=Documentation
You can implement it using the Twitterizer assembly.
Firstly you can create a token which can be used to access Twitter and then using that particular token you can update TwitterStatus (Twitterizer.Core.TwitterObject.TwitterStatus).
Sample code is as follows.
public void CreateCachedAccessToken(string requestToken)
{
string ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"];
string ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"];
OAuthTokenResponse responseToken = OAuthUtility.GetAccessToken(ConsumerKey, ConsumerSecret, requestToken);
//Cache the UserId
Session["GetCachedUserId"] = responseToken.UserId;
OAuthTokens accessToken = new OAuthTokens();
accessToken.AccessToken = responseToken.Token;
accessToken.AccessTokenSecret = responseToken.TokenSecret;
accessToken.ConsumerKey = ConsumerKey;
accessToken.ConsumerSecret = ConsumerSecret;
Session["AccessToken"] = accessToken;
}
To update the TwitterStatus you can do as follows.
public OAuthTokens GetCachedAccessToken()
{
if (Session["AccessToken"] != null)
{
return (OAuthTokens)(Session["AccessToken"]);
}
else
{
return null;
}
}
TwitterStatus.Update(GetCachedAccessToken(), txtTweet.Trim());
The below mentioned method can be used to implement sign in.
protected string GetTwitterAuthorizationUrl()
{
string ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"];
string ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"];
OAuthTokenResponse reqToken = OAuthUtility.GetRequestToken(ConsumerKey, ConsumerSecret);
return "https://twitter.com/oauth/authorize?oauth_token=" + reqToken.Token;
}
Hope this helps.
If there are any clarifications please raise. Thanks

Accessing Google Docs with GData

Working Platform: ASP.NET 4.0 C# ( Framework Agnostic )
Google GData is my dependency
using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Documents;
I have two pages Auth and List.
Auth redirects to Google Server like this
public ActionResult Auth()
{
var target = Request.Url.ToString().ToLowerInvariant().Replace("auth", "list");
var scope = "https://docs.google.com/feeds/";
bool secure = false, session = true;
var authSubUrl = AuthSubUtil.getRequestUrl(target, scope, secure, session);
return new RedirectResult(authSubUrl);
}
Now it reaches the List Page if Authentication is successful.
public ActionResult List()
{
if (Request.QueryString["token"] != null)
{
String singleUseToken = Request.QueryString["token"];
string consumerKey = "www.blahblah.net";
string consumerSecret = "my_key";
string sessionToken = AuthSubUtil.exchangeForSessionToken(singleUseToken, null).ToString();
var authFactory = new GOAuthRequestFactory("writely", "qwd-asd-01");
authFactory.Token = sessionToken;
authFactory.ConsumerKey = consumerKey;
authFactory.ConsumerSecret = consumerSecret;
//authFactory.TokenSecret = "";
try
{
var service = new DocumentsService(authFactory.ApplicationName) { RequestFactory = authFactory };
var query = new DocumentsListQuery();
query.Title = "project";
var feed = service.Query(query);
var result = feed.Entries.ToList().ConvertAll(a => a.Title.Text);
return View(result);
}
catch (GDataRequestException gdre)
{
throw;
}
}
}
This fails at the line var feed = service.Query(query); with the error
Execution of request failed: https://docs.google.com/feeds/default/private/full?title=project
The HttpStatusCode recieved on the catch block is HttpStatusCode.Unauthorized
What is wrong with this code? Do I need to get TokenSecret? If so how?
You need to request a token from Google and use it to intialize your DocumentsService instance.
Here's an example using Google's ContactsService. It should be the same for the DocumentsService.
Service service = new ContactsService("My Contacts Application");
service.setUserCredentials("your_email_address_here#gmail.com", "yourpassword");
var token = service.QueryClientLoginToken();
service.SetAuthenticationToken(token);
But as you mentioned, you are using AuthSub. I jumped the gun a bit too fast.
I see that you are requesting a session token. According to the documentation of the API you must use the session token to authenticate requests to the service by placing the token in the Authorization header. After you've set the session token, you can use the Google Data APIs client library.
Here's a complete example (by Google) on how to use AuthSub with the .NET client library:
http://code.google.com/intl/nl-NL/apis/gdata/articles/authsub_dotnet.html
Let me include a shortened example:
GAuthSubRequestFactory authFactory =
new GAuthSubRequestFactory("cl", "TesterApp");
authFactory.Token = (String) Session["token"];
CalendarService service = new CalendarService(authFactory.ApplicationName);
service.RequestFactory = authFactory;
EventQuery query = new EventQuery();
query.Uri = new Uri("http://www.google.com/calendar/feeds/default/private/full");
EventFeed calFeed = service.Query(query);
foreach (Google.GData.Calendar.EventEntry entry in calFeed.Entries)
{
//...
}
And if I see correctly your example code pretty follows the same steps, except that you set the ConsumerKey and ConsumerSecret for the AuthFactory which is not done in the example by Google.
Used the 3-legged OAuth in the Google Data Protocol Client Libraries
Sample Code
string CONSUMER_KEY = "www.bherila.net";
string CONSUMER_SECRET = "RpKF7ykWt8C6At74TR4_wyIb";
string APPLICATION_NAME = "bwh-wssearch-01";
string SCOPE = "https://docs.google.com/feeds/";
public ActionResult Auth()
{
string callbackURL = String.Format("{0}{1}", Request.Url.ToString(), "List");
OAuthParameters parameters = new OAuthParameters()
{
ConsumerKey = CONSUMER_KEY,
ConsumerSecret = CONSUMER_SECRET,
Scope = SCOPE,
Callback = callbackURL,
SignatureMethod = "HMAC-SHA1"
};
OAuthUtil.GetUnauthorizedRequestToken(parameters);
string authorizationUrl = OAuthUtil.CreateUserAuthorizationUrl(parameters);
Session["parameters"] = parameters;
ViewBag.AuthUrl = authorizationUrl;
return View();
}
public ActionResult List()
{
if (Session["parameters"] != null)
{
OAuthParameters parameters = Session["parameters"] as OAuthParameters;
OAuthUtil.UpdateOAuthParametersFromCallback(Request.Url.Query, parameters);
try
{
OAuthUtil.GetAccessToken(parameters);
GOAuthRequestFactory authFactory = new GOAuthRequestFactory("writely", APPLICATION_NAME, parameters);
var service = new DocumentsService(authFactory.ApplicationName);
service.RequestFactory = authFactory;
var query = new DocumentsListQuery();
//query.Title = "recipe";
var feed = service.Query(query);
var docs = new List<string>();
foreach (DocumentEntry entry in feed.Entries)
{
docs.Add(entry.Title.Text);
}
//var result = feed.Entries.ToList().ConvertAll(a => a.Title.Text);
return View(docs);
}
catch (GDataRequestException gdre)
{
HttpWebResponse response = (HttpWebResponse)gdre.Response;
//bad auth token, clear session and refresh the page
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
Session.Clear();
Response.Write(gdre.Message);
}
else
{
Response.Write("Error processing request: " + gdre.ToString());
}
throw;
}
}
else
{
return RedirectToAction("Index");
}
}
This 2-legged sample never worked for me for google docs.

Categories

Resources