Quantcast
Channel: Tweetinvi a friendly Twitter C# library
Viewing all articles
Browse latest Browse all 4126

Edited Unassigned: NullCredentialsException even when using setCredentials [2628]

$
0
0
Hello,

I'm implementing a code for users to login and being able to use several functions such as:
*Send a Tweet
*Send a Direct Message
*Retrieve Direct Messages (sent/received)
*Retrieve their mentions
*Retrieve hashtags

For that, once they login, I apply a "setCredentials" with all parameters needed. The access Tokens are the ones obtained after the login. However, sometimes (want to remark the SOMETIMES, because not always happens), even when the "ApplicationCredentials" derived from the "SetCredentials" contain the information, I get an error saying that the credentials are null and that I must use the "setCredentials" method. Here is the code, using Tweetinvi 9.8.2. I hope you can help me since I don't find the explanation (since it happens sometimes, and it can happen with any of the functions described above). This is just one part of the code so you don't have to read many lines. The code is implemented in an ASP, the comments in spanish just describe what the Tweeinvi documentations says, but in spanish. I attach the frontend, it just has a button for login and, when appCredentials are null, all the functions buttons are disabled (to avoid the error), when appCredentials have something, the functions buttons are enabled. The tokens are saved on the webconfig, and the verifications of the "if" in the page_load is so that, if the user is already logged in, it doesn't take him back to the authorization twitter page.

const string
consumerKey = "QIwJdW0s4fCgVRIK4JxXkU8wo",
consumerSecret = "HIdySxqpsG8K9flePKxuAOrkOjhjsckAOSYCv4BO5MwJ3CENCl";

string accessToken = string.Empty, accessSecret = string.Empty,
callbackURL = "http://localhost:25942/DemoFuncional/TwitterDefault.aspx";

protected void Page_Load(object sender, EventArgs e)
{
//Para evitar problemas de longitud (Restricción de Twitter)
TxtTweet.MaxLength = maxLongitudCar;
TxtMenDir.MaxLength = maxLongitudCar;
TxtHashtagQuery.MaxLength = maxLongitudCar;

//Revisamos si ya estamos autenticados o hay que autenticarnos
//Después de autenticarte, cuando te regresa (callbackURL) le agrega el
//parámetro "oauth_token" a la URL, que sirve para sacar los accessTokens
string authorizationKey = Request.QueryString["oauth_token"];
if (authorizationKey != null && TwitterCredentials.ApplicationCredentials == null)
{
//Esta es la segunda (y última fase) del Login
//Generaremos los access Tokens y tendremos las credenciales necesarias
//Para ejecutar cuaquier método sin problemas.
//https://github.com/linvi/tweetinvi/wiki/Authentication
//https://tweetinvi.codeplex.com/workitem/2618?FocusElement=CommentTextBox
//https://twittercommunity.com/t/how-to-check-whether-an-access-token-is-expired-or-not/783

string authorizationURL = Request.Url.AbsoluteUri;
var appCredentials = CredentialsCreator.GenerateApplicationCredentials(consumerKey, consumerSecret);

//Valores que se respaldaron de la fase 1 (Botón de Login)
appCredentials.AuthorizationKey = WebConfigurationManager.AppSettings["AuthorizationKey"];
appCredentials.AuthorizationSecret = WebConfigurationManager.AppSettings["AuthorizationSecret"];

//Se consiguen todas las credenciales necesarias
var newCredentials = CredentialsCreator.GetCredentialsFromCallbackURL(authorizationURL, appCredentials);

//Ya que se obtuvieron todos los valores necesarios, se asignan las credenciales
//Para poder ejecutar cualquier operación (Tweets, mensajes directos, etc...)
TwitterCredentials.SetCredentials(
newCredentials.AccessToken,
newCredentials.AccessTokenSecret,
newCredentials.ConsumerKey,
newCredentials.ConsumerSecret);
}

if (TwitterCredentials.ApplicationCredentials == null)
{
setEstadoBtns(false);
LabelLogin.Text = "Primero ingresa con tu cuenta de Twitter";
BtnLogin.Visible = true;
BtnLogin.Enabled = true;
}
else
{
setEstadoBtns(true);
LabelLogin.Text = "";
BtnLogin.Enabled = false;
BtnLogin.Visible = false;
accessToken = TwitterCredentials.ApplicationCredentials.AccessToken;
accessSecret = TwitterCredentials.ApplicationCredentials.AccessTokenSecret;
}

}

protected void setEstadoBtns(bool estado)
{
//Esta función es para poder habilitar/deshabilitar rápidamente
//Todos los botones de acciones de Twitter (excepto el Login).

BtnEnviarTweet.Enabled = estado;
BtnEnviarMenDir.Enabled = estado;
BtnMenDirEnviados.Enabled = estado;
BtnMenDirRecibidos.Enabled = estado;
BtnObtenerMenciones.Enabled = estado;
BtnObtenerHashtags.Enabled = estado;

}

//Fase uno del Login
protected void BtnLogin_Click(object sender, EventArgs e)
{
//Fase 1 para el Login
//Conseguiremos la ruta (callbackURL con el parámetro oauth_token y verifier
//Para ir a twitter y autenticarnos. Luego se ejecutará la fase 2
//Que se encuentra en LoadPage. La fase 2 sólo se ejecutará una vez.
//https://github.com/linvi/tweetinvi/wiki/Authentication
//https://tweetinvi.codeplex.com/workitem/2618?FocusElement=CommentTextBox
//https://twittercommunity.com/t/how-to-check-whether-an-access-token-is-expired-or-not/783

//Revisamos que el Login no se haya realizado previamente
string authorizationKey = Request.QueryString["oauth_token"];
if (authorizationKey == null )
{

//Se prepará la url para ir a twitter
var appCredentials = CredentialsCreator.GenerateApplicationCredentials(consumerKey, consumerSecret);
var url = CredentialsCreator.GetAuthorizationURLForCallback(appCredentials, callbackURL);

//Se requieren respaldar estos valores para más adelante (fase 2)
WebConfigurationManager.AppSettings["AuthorizationKey"] = appCredentials.AuthorizationKey;
WebConfigurationManager.AppSettings["AuthorizationSecret"] = appCredentials.AuthorizationSecret;

//Redireccionamos a Twitter
Response.Redirect(url);
}
}

/************************* Código de Tweets *************************************/
protected void BtnEnviarTweet_Click(object sender, EventArgs e)
{
Tweet.PublishTweet(TxtTweet.Text);
}
protected void BtnBorrarTxtTweet_Click(object sender, EventArgs e)
{
TxtTweet.Text = String.Empty;
}

Viewing all articles
Browse latest Browse all 4126

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>