Remove the twitter authorization during program running in C# - 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

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.

LinqToTwitter status update only works sometimes

I'm trying to send a tweet using LinqToTwitter. My problem is that it almost never works. I've gotten it to work maybe three times out of thirty, and usually that's when I try to debug. I'm thinking it might have something to do with timing and authentication, but I don't know how to do it. The code runs without errors, but no tweet is generated.
public static async Task SendTweetAsync(string text)
{
// Get the authorization credentials
var auth = GetCredentials();
// Create the twitter context
var ctx = new TwitterContext(auth);
try
{
Status responseTweet = await ctx.TweetAsync(text);
}
catch (Exception e) {
throw e;
}
}
private static AspNetAuthorizer GetCredentials()
{
return new AspNetAuthorizer
{
CredentialStore = new InMemoryCredentialStore()
{
ConsumerSecret = "##########",
ConsumerKey = "##########",
OAuthToken = "##########",
OAuthTokenSecret = "##########",
UserID = ##########
}
};
}
I don't know what happened to the answer that was here before, by #JoeMayo, but the thing that worked for me was to change the AspNetAuthorizer to SingleUserAuthorizer.
private static SingleUserAuthorizer GetCredentials()
{
return new SingleUserAuthorizer
{
CredentialStore = new InMemoryCredentialStore()
{
ConsumerSecret = "##########",
ConsumerKey = "##########",
OAuthToken = "##########",
OAuthTokenSecret = "##########",
UserID = ##########
}
};
}
Also, I added await auth.AuthorizeAsync();
var auth = GetCredentials();
await auth.AuthorizeAsync();
As I said, the credit should really go to #JoeMayo, but his answer is gone.

Unable Post tweet From C# Aaplication

i'm using oauth and twitterizer in my C# apps, and after trying for several times. and it won't get any exception, error. but it's doesn't want to post it to twitter.
here is my code
protected void Page_Load(object sender, EventArgs e)
{
BLTgUser objBLTgUser = new BLTgUser();
if (!objBLTgUser.IsLogin) objBLTgUser.GoToLoginPage(HttpContext.Current.Request.Url.AbsoluteUri);
m_strIdGods = objBLTgUser.IdGods;
BLGodsProfile objGods = new BLGodsProfile();
tbmgodsprofile objGodsProfile = objGods.GetGodsByIdGods(m_strIdGods);
string reqToken = Request.QueryString["oauth_token"].ToString();
string pin = Request.QueryString["oauth_verifier"].ToString();
var oauth_consumerKey = System.Configuration.ConfigurationManager.AppSettings["TwitterConsumerKey"];
var oauth_consumerSecret = System.Configuration.ConfigurationManager.AppSettings["TwitterConsumerSecret"];
var tokens = OAuthUtility.GetAccessToken(
oauth_consumerKey,
oauth_consumerSecret,
reqToken,
pin);
string accessToken = tokens.Token;
string accessTokenSecret = tokens.TokenSecret;
objGodsProfile.twittertoken = accessToken;
objGodsProfile.twitterpin = accessTokenSecret;
objGodsProfile.twitterstatus = "1";
objGods.UpdateGodsProfile(objGodsProfile);
}
i'm trying store the token and tokensecret to Database, it's for the next uses.
string v_str = "";
BLEnumHelper m_BLEnumHelper = new BLEnumHelper();
BLGodsProfile userprofile = new BLGodsProfile();
tbmgodsprofile godsAccessToken = userprofile.GetGodsByIdGods(m_strIdGods);
string reqToken = godsAccessToken.twittertoken;
string reqTokenAccess = godsAccessToken.twitterpin;
var oauth_consumerKey = System.Configuration.ConfigurationManager.AppSettings["TwitterConsumerKey"];
var oauth_consumerSecret = System.Configuration.ConfigurationManager.AppSettings["TwitterConsumerSecret"];
OAuthTokens accesstoken = new OAuthTokens()
{
AccessToken = reqToken,
AccessTokenSecret = reqTokenAccess ,
ConsumerKey = oauth_consumerKey,
ConsumerSecret = oauth_consumerSecret
};
TwitterResponse<TwitterStatus> response = TwitterStatus.Update(accesstoken,p_strMessage);
if (response.Result == RequestResult.Success)
{
Response.Write("we did it!");
}
else
{
Response.Write("it's all bad.");
}
and after the 2nd code be called, it wont' post to twitter.
Twitterizer is no longer maintained.
https://github.com/Twitterizer/Twitterizer/blob/develop/README.mediawiki
Twitterizer not supporting Twitter's new API version 1.1, you can't use it for development.
As an alternative, I recommend CoreTweet for you.

Error while getting public data from twitter

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)

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