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.
Related
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
I am trying to create a login method and I need to get a password from the corresponding user. This is my database layer code:
public int loginUser(string userName, string pass)
{
int result = 0;
var credentials = MongoCredential.CreateMongoCRCredential("SearchForKnowledge", userName, pass);
var settings = new MongoClientSettings
{
Credentials = new[] { credentials }
};
try
{
var mongoClient = new MongoClient(settings);
var database = mongoClient.GetDatabase("SearchForKnowledge");
var coll = database.GetCollection<BsonDocument>("Users");
var filter = Builders<BsonDocument>.Filter.Eq("userName", userName);
var query = coll.Find(filter);
//??????????
}
catch (Exception ex) {
result = 0;
}
return result;
}
as you can see if the login is success im trying to return 1 and if it fails, 0 (for redirecting purposes). I am struggling to check if the username matches password set to it. At the moment I just made a filter, passed it to the method Find and im dead stuck at this point. How do I return that user's password from mongodb and compare it to the one passed as a parameter?
Try something like this:
public int loginUser(string userName, string pass)
{
int result = 0;
//Here you use credentials for the connection, not the one passed
//to the method:
var credentials = MongoCredential.CreateMongoCRCredential("SearchForKnowledge", connectionUsername, connectionPass);
var settings = new MongoClientSettings
{
Credentials = new[] { credentials }
};
try
{
var mongoClient = new MongoClient(settings);
var database = mongoClient.GetDatabase("SearchForKnowledge");
var coll = database.GetCollection<BsonDocument>("Users");
var filter = Builders<BsonDocument>.Filter.Eq("userName", userName);
var result = await coll.Find(filter).ToListAsync().First();
if(result["Password"] == pass)
{
result = 1;
}
}
catch (Exception ex) {
result = 0;
}
return result;
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.
Here, I am using user id generated by facebook in place of appid . Am I correct here??
As I wanted to get access token with the help of user name and password for my application designed in windows forms. I am using below code to fetch it. Please, give me any better solution to fetch access token.
string appId = userid.ToString();
string[] extendedPermissions = new[] { "publish_stream", "offline_access" };
var oauth = new FacebookOAuthClient { ClientId = appId };
var parameters = new Dictionary<string, object> {
{ "response_type", "token" }, { "display", "popup" } };
if (extendedPermissions != null && extendedPermissions.Length > 0)
{
var scope = new StringBuilder();
scope.Append(string.Join(",", extendedPermissions));
parameters["scope"] = scope.ToString();
}
var loginUrl = oauth.GetLoginUrl(parameters);
wbTestWindow.Navigate(loginUrl);
// this webBrowser's related navigated function
private void wbTestWindow_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
FacebookOAuthResult result;
if (FacebookOAuthResult.TryParse(e.Url, out result))
{
if (result.IsSuccess)
{
var accesstoken = result.AccessToken;
}
else
{
var errorDescription = result.ErrorDescription;
var errorReason = result.ErrorReason;
}
}
}
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.