Cómo usar el API de Twitter para desarrollar una aplicación en C# C Sharp .Net que nos permita interactuar con nuestra cuenta de Twitter. Para ello desarrollamos la aplicación gratuita con código fuente AjpdSoft Gestión Seguidores Twitter. Con el API de Twitter podremos leer los tweets, tweets retwitteados, menciones, Timeline, seguir a usuarios, dejar de seguir, visitar perfil, enviar tweet, mostrar los últimos 20 seguidores, amigos, mensajes directos, etc. También podremos realizar tareas automáticas como: enviar mensaje directo a quien nos sigue, añadir mención a quien nos sigue, seguir a quien nos sigue (todo ello de forma automática). También podremos, de forma automática, dejar de seguir a aquellos amigos (que seguimos) que no nos siguen.
- Alta de aplicación en Twitter Developers.
- API para acceso a Twitter con Visual Studio .Net C# C Sharp.
- Acceso a Twitter con aplicación C# .Net y API Twitter Spring.NET Social Extension.
- AjpdSoft Gestión Seguidores Twitter en funcionamiento.
- Código fuente source code C# AjpdSoft Gestión Seguidores Twitter.
Alta de aplicación en Twitter Developers
Para que nuestra aplicación desarrollada en C# .Net (Visual Stuio .Net) pueda conectar utilizar el API de Twitter deberemos registrarla en Twitter. Deberemos disponer de un usuario de Twitter, si aún no lo tenemos nos daremos de alta en su web oficial. Una vez que tengamos el usuario accederemos a la sección Developers de Twitter en la URL:
https://developer.twitter.com/en/apps
Nos mostrará la lista de aplicaciones de Twitter que tengamos dadas de alta, para añadir una nueva pulsaremos en «Create new application»:
Introduciremos los datos de la aplicación, como el nombre, descripción, sitio web, etc., en nuestro caso desarrollaremos AjpdSoft Gestión Seguidores Twitter:
Una vez introducidos los datos, leídos los términos de licencia y aceptados (marcando «Yes, I agree») introduciremos los datos del capcha y pulsaremos en «Create your Twitter application»:
Nos mostrará la nueva aplicación creada en Twitter, en la pestaña «Details» podremos consultar las asignaciones de Consumer key y un Consumer secret y otros datos que necesitaremos para desarrollar la aplicación en C# o en otros lenguajes: Request token URL, Authorize URL, Access token URL, etc.:
En la pestaña «Settings» podremos modificar el nombre, la descripción, el sitio web, podremos añadir un icono para la aplicación y lo más importante, deberemos establecer el tipo de permiso que requerirá la aplicación en «Application Type», con las posibilidades de «Read only», «Read and Write», «Read, Write and Access direct messages». Dependiendo de las tareas que queramos que realice nuestra aplicación indicaremos el tipo de acceso, normalmente con «Read only» suele ser suficiente. Estos permisos se mostrarán al usuario cuando utilice nuestra aplicación por lo que debemos escoger la opción estrictamente necesaria, a ser posible «Read only»:
En la pestaña «OAuth tool» podremos consultar el Consumer Key, Consumer Secret, Access token y Access token secret de nuestra aplicación. También el método de petición de información: GET, POST, DELETE, PUT, HEAD. Normalmente se suele usar GET:
Con estos sencillos pasos ya tendremos nuestra aplicación dada de alta en Twitter con los datos de acceso necesarios para su posterior desarrollo en C# C Sharp como explicaremos a continuación.
API para acceso a Twitter con Visual Studio .Net C# C Sharp
Una vez dada de alta la aplicación en Twitter, lo siguiente que necesitaremos será el API de Twitter, que son un conjunto de librerías DLL con los métodos necesarios para realizar diversas operaciones en una cuenta de Twitter desde C# C Sharp. Existen varios proyectos que han desarrollado las librerías DLL necesarias para acceder a Twitter desde una aplicación Visual Studio .Net C# C Sharp, algunos de ellos:
- LINQ2Twitter by @joemayo.
- Spring.NET Social extension for Twitter by SpringSource.
- TweetSharp by @danielcrenna.
- Tweetinvi maintained by Linvi.
- Crafted,Twitter by @martbrow.
Usaremos Spring.NET Social Extension for Twitter, por lo tanto realizaremos la descarga de estos ficheros desde:
https://github.com/spring-projects/spring-net-social-twitter/tree/master/lib/net/4.0
O bien usando Maven o Gradle (como se recomienda en la web oficial de Spring.NET Social Extension).
Acceso a Twitter con aplicación C# .Net y API Twitter Spring.NET Social Extension
Descomprimiremos el fichero Spring.Social.Twitter-2.0.0-M1.zip descargado, usaremos los ficheros ubicados en:
…/Spring.Social.Twitter-2.0.0-M1/bin/net/4.0/Debug
Usaremos:
- Spring.Rest.dll
- Spring.Social.Core.dll
- Spring.Social.Twitter.dll
Abriremos Microsoft Visual Studio .Net, pulsaremos en «Archivo» – «Nuevo proyecto»:
Seleccionaremos en la parte izquierda «Otros lenguajes» – «Visual C#», en la parte derecha seleccionaremos «.NET Framework 4» y «Aplicación de Windows Forms». Introduciremos el nombre para el proyecto
A continuación agregaremos las referencias al API de Twitter en Visual Studio .Net, para ello pulsaremos en «Proyecto» – «Agregar referencia»:
En la pestaña «Examniar» seleccionaremos los ficheros DLL del API de Twitter: Spring.Rest.dll, Spring.Social.Core.dll, Spring.Social.Twitter.dll:
De esta forma se agregarán las referencias al API de Twitter en nuestro proyecto C# C Sharp:
- Spring.Rest
- Spring.Social.Core
- Spring.Social.Twitter
Agregaremos ahora una nueva clase a nuestro proyecto donde implementaremos todas las tareas que queramos realizar con el API de Twitter, para ello pulsaremos con el botón derecho del ratón sobre el proyecto en el Explorador de soluciones, seleccionaremos «Agregar» – «Clase»:
Introduciremos el nombre para la clase, por ejemplo «TareasTwitter.cs«, pulsaremos «Aceptar»:
Añadiremos en esta clase los import correspondientes para usar el API de Twitter:
using Spring.IO;
using Spring.Social.OAuth1;
using Spring.Social.Twitter.Api;
using Spring.Social.Twitter.Api.Impl;
using Spring.Social.Twitter.Connect;
En esta clase añadiremos como constantes privadas las claves Consumer Key y Consumer Secret obtenidas en este paso:
El código fuente completo de esta clase puede consultarse aquí.
De la misma forma añadiremos también otra clase para encriptar y desencriptar texto, que nos servirá para guardar la contraseña de acceso a la base de datos, la llamaremos «Encriptar.cs«:
El código fuente completo de esta clase puede consultarse aquí.
Añadiremos la clase para guardar la configuración de la aplicación, la llamaremos «GuardarConfiguracion.cs«:
El código fuente completo de esta clase puede consultarse aquí.
Añadiremos la clase para guardar la configuración de la aplicación, la llamaremos «BDSQLite.cs«:
El código fuente completo de esta clase puede consultarse aquí.
El formulario principal de la aplicación «formTwitter.cs» contendrá los siguientes componentes:
El código fuente completo del formulario principal puede consultarse aquí.
AjpdSoft Gestión Seguidores Twitter en funcionamiento
La aplicación AjpdSoft Gestión Seguidores Twitter muestra los tweets, tweets retwitteados, menciones, timeline, permite seguir, dejar de seguir, visitar pefiles, enviar tweet, muestra los últimos 20 seguidores, amigos, mensajes directos, etc. Además, lo más interesante de esta aplicación gratuita es que permite realizar tareas automáticas como: enviar mensaje directo a quien nos sigue, añadir mención a quien nos sigue, seguir a quien nos sigue (todo ello de forma automática). También permite, de forma automática, dejar de seguir a aquellos amigos (que seguimos) que no nos siguen.
A continuación mostramos un videotutorial sobre el funcionamiento de AjpdSoft Gestión Seguidores Twitter:
Ejecutaremos la aplicación, en primer lugar en «Usuario» introduciremos el nombre de usuario de Twitter, pulsaremos en «Conectar con Twitter»:
La aplicación abrirá el navegador por defecto, accederemos a nuestra cuenta de Twitter en el navegador y autorizaremos el acceso de la aplicación, Twitter generará un PIN:
Deberemos introducir dicho PIN en la aplicación:
Una vez conectados, desde la pestaña «Mensajes directos» podremos obtener los 20 últimos mensajes directos, desde donde podremos responder a un mensaje directo o eliminarlo:
En la pestaña «Seguidores» podremos consultar los últimos 20 seguidores de nuestra cuenta de Twitter, podremos dejar de seguir a un amigo, seguir a un usuario o visitar su perfil:
En la pestaña «Siguiendo» podremos consultar los últimos 20 amigos a los que hemos seguido, podremos dejar de seguir a un amigo, seguir a un usuario o visitar su pefil (id, nick, nombre, seguidores, siguiendo, fecha antigüedad, descripción, url del perfil, ubicación, idioma):
Desde la pestaña «Tweet» podremos enviar un Tweet, en la pestaña «Tweets TimeLine» podremos ver los últimos 20 mensajes de la línea de tiempo:
En la pestaña «Mis tweets» podremos consultar los últimos 20 tweets enviados con el ID de tweet, el id de usuario, el nick de usuario, la fecha, el texto del tweet y el número de retweets:
En la pestaña «Menciones» podremos consultar las últimas 20 menciones que nos hayan hecho (id, id usuario, fecha, tweet, número retweets):
En la pestaña «Tweet favoritos» podremos consultar los últimos 20 tweets marcados como favoritos:
En la pestaña «Mis tweets retwitteados» podremos consultar los últimos 20 tweets retwitteados:
En la pestaña «Tareas automáticas» podremos establecer y activar tres acciones automáticas que permite la aplicación:
- Enviar mensaje directo a nuevos seguidores.
- Añadir mención a nuevo seguidor.
- Seguir a nuevo seguidor.
Podremos elegir qué acción realizará la aplicación de forma automática en el intervalo de segundos especificado. La aplicación comprobará en el intervalo indicado si hay nuevos seguidores, de haberlos y de forma automática, realizará las acciones indicadas (mensaje directo, mención, seguir):
Para que la opción anterior de tareas automáticas funcione deberemos configurar la base de datos SQLite local, para ello pulsaremos en la pestaña «Configuración»:
- Fichero BD SQLite: indicaremos una carpeta y nombre de fichero donde se creará la base de datos local SQLite que usará la aplicación internamente, en esta base de datos guardará los nuevos usuarios a los que le haya enviado mensaje directo para no enviar mensajes directos varias veces al mismo usuario.
- Una vez especificada la ubicación y fichero de la base de datos pulsaremos en «Crear BD y tablas para Twitter» para crear la base de datos. Si la base de datos ya existe con datos NO deberemos volver a crearla, será suficiente con seleccionarla en «Fichero BD SQLite».
Una vez creada la base de datos y especificadas acciones automáticas, para activarlas, en la pestaña «Tareas automáticas» pulsaremos en «Activar tareas automáticas»:
Minimizando la aplicación quedará en el área de notificación:
La aplicación también permite dejar de seguir a quien no nos sigue de forma automática. Para ello pulsaremos en la pestaña «Dejar de seguir a quien no te sigue», pulsaremos en el botón «Obtener amigos que no te siguen», la aplicación obtendrá los amigos a los que seguimos, los seguidores y mostrará en la parte derecha los amigos que no nos siguen, pulsando en «Dejar de seguir a todos los que no te siguen» de forma automática dejará de seguir a los que no nos siguen:
Nota: esta versión de la aplicación tiene la limitación de sólo permitir esta tarea automática si no tenemos más de 5000 amigos.
IMPORTANTE: no debemos abusar de las técnicas indicadas en este tutorial puesto que Twitter podría penalizar nuestra cuenta, no debe abusarse, sobre todo, de las menciones.
Código fuente source code C# C Sharp AjpdSoft Gestión Seguidores Twitter
A continuación mostramos listado del código fuente (source code) de la aplicación AjpdSoft Gestión Seguidores Twitter:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Spring.Social.OAuth1; using Spring.Social.Twitter.Api; using Spring.Social.Twitter.Api.Impl; using Spring.Social.Twitter.Connect; namespace AjpdSoftGestiónSeguidoresTwitter { //datos perfil usuario Twitter public struct PerfilUsuario { public string nombre; public string nick; public long id; public string descripcion; public int seguidores; public int siguiendo; public DateTime? fechaAlta; public string ubicacion; public string idioma; public string urlPerfil; public bool notificaciones; public bool traductor; public bool verificado; public bool protegido; public bool loSigo; } //datos mensaje directo Twitter public struct MensajeDirecto { public long id; public long idUsuario; public string nick; public string usuario; public string mensaje; public DateTime? fecha; } //datos seguidor Twitter public struct Seguidor { public PerfilUsuario perfilUsuario; public string meSigue; } //Datos amigo Twitter public struct Amigo { public PerfilUsuario perfilUsuario; public string meSigue; } //Tweet Twitter (TimeLine, Retweet, menciones) public struct DatosTweet { public long id; public long idUsuario; public string usuario; public DateTime? fecha; public string tweet; public long NumeroRetweet; } class TareasTwitter { //ConsumerKey y ConsumerSecret de nuestra aplicación dada de alta en Twitter private const string TwitterConsumerKey = "4azv2Q xxx"; private const string TwitterConsumerSecret = "DsFUOA xxx"; ITwitter twitter; //Conectar con API de Twitter mediante PIN para obtener token de acceso //devuelve true si la conexión se ha realizado correctamente public bool obtenerTokenTwitter(ref string resultado) { try { TwitterServiceProvider twitterServiceProvider = new TwitterServiceProvider(TwitterConsumerKey, TwitterConsumerSecret); // Autenticación en Twitter usando código PIN OAuthToken oauthToken = twitterServiceProvider.OAuthOperations.FetchRequestTokenAsync("oob", null).Result; string authenticateUrl = twitterServiceProvider.OAuthOperations.BuildAuthorizeUrl(oauthToken.Value, null); System.Diagnostics.Process.Start(authenticateUrl); string pinCode = ""; InputBox.solicitarTexto("Código PIN", "Introduzca el código PIN obtenido de Twitter:", ref pinCode); AuthorizedRequestToken requestToken = new AuthorizedRequestToken(oauthToken, pinCode); OAuthToken oauthAccessToken = twitterServiceProvider.OAuthOperations.ExchangeForAccessTokenAsync(requestToken, null).Result; twitter = twitterServiceProvider.GetApi(oauthAccessToken.Value, oauthAccessToken.Secret); resultado = System.DateTime.Now + " " + "Conectado a API de twitter correctamente con PIN"; return true; } catch (Exception error) { resultado = System.DateTime.Now + " " + "Error al obtener token acceso Twitter: " + error.Message; return false; } } //Obtener los datos del perfil del usuario de Twitter //que ha iniciado sesión de autenticación con PIN public void obtenerDatosPerfilPIN (string usuario, ref PerfilUsuario datosPerfilUsuario, ref string resultado) { try { datosPerfilUsuario.nick = twitter.UserOperations.GetUserProfileAsync(usuario).Result.ScreenName; datosPerfilUsuario.nombre = twitter.UserOperations.GetUserProfileAsync(usuario).Result.Name; datosPerfilUsuario.descripcion = twitter.UserOperations.GetUserProfileAsync(usuario).Result.Description; datosPerfilUsuario.siguiendo = twitter.UserOperations.GetUserProfileAsync(usuario).Result.FriendsCount; datosPerfilUsuario.seguidores = twitter.UserOperations.GetUserProfileAsync(usuario).Result.FollowersCount; datosPerfilUsuario.fechaAlta = twitter.UserOperations.GetUserProfileAsync(usuario).Result.CreatedDate; datosPerfilUsuario.ubicacion = twitter.UserOperations.GetUserProfileAsync(usuario).Result.Location; datosPerfilUsuario.id = twitter.UserOperations.GetUserProfileAsync(usuario).Result.ID; datosPerfilUsuario.idioma = twitter.UserOperations.GetUserProfileAsync(usuario).Result.Language; datosPerfilUsuario.urlPerfil = twitter.UserOperations.GetUserProfileAsync(usuario).Result.ProfileUrl; datosPerfilUsuario.verificado = twitter.UserOperations.GetUserProfileAsync(usuario).Result.IsVerified; datosPerfilUsuario.traductor = twitter.UserOperations.GetUserProfileAsync(usuario).Result.IsTranslator; datosPerfilUsuario.protegido = twitter.UserOperations.GetUserProfileAsync(usuario).Result.IsProtected; resultado = System.DateTime.Now + " " + "Datos del perfil [" + usuario + "] obtenidos correctamente"; } catch (Exception error) { resultado = System.DateTime.Now + " " + "Error al obtener datos del perfil [" + usuario + "]: " + error.Message; } } //obtener datos perfil de usuario por ID public void obtenerPerfilUsuario (long id, ref PerfilUsuario perfilUsuario, ref string resultado) { try { TwitterProfile perfilUsuarioTwitter = twitter.UserOperations.GetUserProfileAsync(id).Result; PerfilUsuario perfil = new PerfilUsuario(); perfil.descripcion = perfilUsuarioTwitter.Description; perfil.fechaAlta = perfilUsuarioTwitter.CreatedDate; perfil.id = perfilUsuarioTwitter.ID; perfil.idioma = perfilUsuarioTwitter.Language; perfil.nick = perfilUsuarioTwitter.ScreenName; perfil.nombre = perfilUsuarioTwitter.Name; perfil.verificado = perfilUsuarioTwitter.IsVerified; perfil.traductor = perfilUsuarioTwitter.IsTranslator; perfil.protegido = perfilUsuarioTwitter.IsProtected; perfil.loSigo = perfilUsuarioTwitter.IsFollowing; perfil.seguidores = perfilUsuarioTwitter.FriendsCount; perfil.siguiendo = perfilUsuarioTwitter.FriendsCount; perfil.ubicacion = perfilUsuarioTwitter.Location; perfil.urlPerfil = perfilUsuarioTwitter.ProfileUrl; perfilUsuario = perfil; resultado = "Obtenido perfil usuario " + Convert.ToString(id); } catch (Exception error) { resultado = System.DateTime.Now + " " + "Error al obtener datos del perfil [" + Convert.ToString(id) + "]: " + error.Message; } } //Enviar mensaje directo a usuario Twitter //debe ser seguido por el usuario que ha iniciado sesión public void enviarMensajeDirectoTwitter(string mensaje, long idUsuario, ref string resultado) { if (mensaje != "") { try { DirectMessage mensajeDirectoTwiiter = twitter.DirectMessageOperations.SendDirectMessageAsync(idUsuario, mensaje).Result; resultado = System.DateTime.Now + " " + "Mensaje directo [" + mensaje + "] enviado a [" + Convert.ToString(idUsuario) + "]"; } catch (Exception error) { resultado = System.DateTime.Now + " " + "Error al enviar mensaje directo: " + error.Message; } } } //Obtener últimos 20 mensajes directos Twitter public List obtenerUltimos20MensajesDirectos(ref string resultado) { try { List mensajes = new List(); IList mensajesTwiiter = twitter.DirectMessageOperations.GetDirectMessagesReceivedAsync().Result; foreach (DirectMessage mensajeTwitter in mensajesTwiiter) { MensajeDirecto mensajeDirecto = new MensajeDirecto(); mensajeDirecto.id = mensajeTwitter.ID; mensajeDirecto.idUsuario = mensajeTwitter.Sender.ID; mensajeDirecto.nick = mensajeTwitter.Sender.ScreenName; mensajeDirecto.usuario = mensajeTwitter.Sender.Name; mensajeDirecto.mensaje = mensajeTwitter.Text; mensajeDirecto.fecha = mensajeTwitter.CreatedAt; mensajes.Add(mensajeDirecto); resultado = System.DateTime.Now + " " + "Obteniendo mensaje [" + Convert.ToString(mensajeTwitter.ID) + "]" + Environment.NewLine + resultado; } resultado = System.DateTime.Now + " " + "Últimos 20 mensajes directos obtenidos"; return mensajes; } catch (Exception error) { resultado = System.DateTime.Now + " " + "Error al obtener mensajes directos: " + error.Message; return null; } } //Elimina un mensaje directo de Twitter que nos hayan enviado public void eliminarMensajeDirecto(long idMensaje, ref string resultado) { try { DirectMessage mensaje; mensaje = twitter.DirectMessageOperations.DeleteDirectMessageAsync(idMensaje).Result; resultado = System.DateTime.Now + " " + "Mensaje directo [" + idMensaje + "] eliminado correctamente"; } catch (Exception error) { resultado = System.DateTime.Now + " " + "Error al eliminar mensaje directo [" + Convert.ToString(idMensaje) + "]: " + error.Message; } } //Obtener últimos 20 usuarios que nos han seguido en Twitter public List obtenerUltimos20Seguidores (ref string resultado) { try { List seguidores = new List(); CursoredList seguidoresTwitter = twitter.FriendOperations.GetFollowersAsync().Result; foreach (TwitterProfile seguidorTwitter in seguidoresTwitter) { Seguidor seguidor = new Seguidor(); seguidor.perfilUsuario.id = seguidorTwitter.ID; seguidor.perfilUsuario.nick = seguidorTwitter.ScreenName; seguidor.perfilUsuario.nombre = seguidorTwitter.Name; if (seguidorTwitter.IsFollowing) seguidor.meSigue = "Sí"; else seguidor.meSigue = "No"; seguidor.perfilUsuario.seguidores = seguidorTwitter.FollowersCount; seguidor.perfilUsuario.siguiendo = seguidorTwitter.FriendsCount; seguidor.perfilUsuario.fechaAlta = seguidorTwitter.CreatedDate; seguidor.perfilUsuario.descripcion = seguidorTwitter.Description; seguidor.perfilUsuario.urlPerfil = seguidorTwitter.ProfileUrl; seguidor.perfilUsuario.ubicacion = seguidorTwitter.Location; seguidor.perfilUsuario.idioma = seguidorTwitter.Language; seguidores.Add(seguidor); resultado = "Obteniendo seguidor [" + Convert.ToString(seguidorTwitter.ID) + "]" + Environment.NewLine + resultado; } resultado = System.DateTime.Now + " " + "Últimos 20 seguidores obtenidos" + Environment.NewLine + resultado; return seguidores; } catch (Exception error) { resultado = System.DateTime.Now + " " + "Error al obtener seguidores: " + error.Message; return null; } } //Obtener últimos 20 usuarios a los que seguimos (amigos) en Twitter public List obtenerUltimos20Amigos(ref string resultado) { try { List amigos = new List(); CursoredList amigosTwitter = twitter.FriendOperations.GetFriendsAsync().Result; foreach (TwitterProfile amigoTwitter in amigosTwitter) { Amigo amigo = new Amigo(); amigo.perfilUsuario.id = amigoTwitter.ID; amigo.perfilUsuario.nick = amigoTwitter.ScreenName; amigo.perfilUsuario.nombre = amigoTwitter.Name; if (amigoTwitter.IsFollowing) amigo.meSigue = "Sí"; else amigo.meSigue = "No"; amigo.perfilUsuario.seguidores = amigoTwitter.FollowersCount; amigo.perfilUsuario.siguiendo = amigoTwitter.FriendsCount; amigo.perfilUsuario.fechaAlta = amigoTwitter.CreatedDate; amigo.perfilUsuario.descripcion = amigoTwitter.Description; amigo.perfilUsuario.urlPerfil = amigoTwitter.ProfileUrl; amigo.perfilUsuario.ubicacion = amigoTwitter.Location; amigo.perfilUsuario.idioma = amigoTwitter.Language; amigos.Add(amigo); resultado = "Obteniendo amigo [" + Convert.ToString(amigoTwitter.ID) + "]" + Environment.NewLine + resultado; } resultado = System.DateTime.Now + " " + "Últimos 20 amigos obtenidos" + Environment.NewLine + resultado; return amigos; } catch (Exception error) { resultado = System.DateTime.Now + " " + "Error al obtener amigos: " + error.Message; return null; } } //Dejar de seguir a usuario que seguimos (amigo) por nick public void dejarDeSeguirAmigo(string usuario, ref string resultado) { try { TwitterProfile amigo = twitter.FriendOperations.UnfollowAsync(usuario).Result; resultado = System.DateTime.Now + " " + "Dejado de seguir a [" + usuario + "]"; } catch (Exception error) { resultado = System.DateTime.Now + " " + "Error al dejar de seguir a [" + usuario + "]: " + error.Message; } } //Dejar de seguir a usuario que seguimos (amigo) por ID public void dejarDeSeguirAmigo(long usuario, ref string resultado) { try { TwitterProfile amigo = twitter.FriendOperations.UnfollowAsync(usuario).Result; resultado = System.DateTime.Now + " " + "Dejado de seguir a [" + usuario + "]"; } catch (Exception error) { resultado = System.DateTime.Now + " " + "Error al dejar de seguir a [" + Convert.ToString(usuario) + "]: " + error.Message; } } public void seguirUsuario(string usuario, ref string resultado) { try { TwitterProfile amigo = twitter.FriendOperations.FollowAsync(usuario).Result; resultado = System.DateTime.Now + " " + "Siguiendo a [" + usuario + "]"; } catch (Exception error) { resultado = System.DateTime.Now + " " + "Error al seguir a [" + usuario + "]: " + error.Message; } } //Obtener los 20 últimos tweets de mi línea de tiempo (HomeTimeLine) //últimos de mis tweets, menciones y mis tweets retwitteados public List obtener20UltimosTweet(string tipo, ref string resultado) { try { List tweets = new List(); IList lineaTiempo; lineaTiempo = twitter.TimelineOperations.GetHomeTimelineAsync().Result; if (tipo == "UserTimeLine") { lineaTiempo = twitter.TimelineOperations.GetUserTimelineAsync().Result; } if (tipo == "Menciones") { lineaTiempo = twitter.TimelineOperations.GetMentionsAsync().Result; } if (tipo == "Favoritos") { lineaTiempo = twitter.TimelineOperations.GetFavoritesAsync().Result; } if (tipo == "Retweets") { lineaTiempo = twitter.TimelineOperations.GetRetweetsOfMeAsync().Result; } foreach (Tweet tweetTwitter in lineaTiempo) { DatosTweet datoTweet = new DatosTweet(); datoTweet.id = tweetTwitter.ID; datoTweet.idUsuario = tweetTwitter.User.ID; datoTweet.usuario = tweetTwitter.User.ScreenName; datoTweet.fecha = tweetTwitter.CreatedAt; datoTweet.tweet = tweetTwitter.Text; datoTweet.NumeroRetweet = tweetTwitter.RetweetCount; tweets.Add(datoTweet); resultado = System.DateTime.Now + " " + "Obteniendo tweet [" + Convert.ToString(tweetTwitter.ID) + "]" + Environment.NewLine + resultado; } resultado = System.DateTime.Now + " " + "Tweets TimeLine obtenidos" + Environment.NewLine + resultado; return tweets; } catch (Exception error) { resultado = System.DateTime.Now + " " + "Error al obtener tweets de TimeLine: " + error.Message; return null; } } //Enviar tweet public void enviarTweet(string texto, ref string resultado) { try { Tweet tweet = twitter.TimelineOperations.UpdateStatusAsync(texto).Result; resultado = System.DateTime.Now + " " + "Tweet enviado correctamente [" + texto + "]"; } catch (Exception error) { resultado = System.DateTime.Now + " " + "Error al enviar tweet: " + error.Message; } /* Tweet tweet = twitter.TimelineOperations.UpdateStatusAsync( txtTweet.Text, new AssemblyResource("c:imagen.png", typeof(Program))).Result; */ } //Obtener últimos 5000 usuarios a los que seguimos (amigos) en Twitter //cursor = -1 obtendrá los 5000 amigos del usuario con el que hemos iniciado sesión public List obtenerUltimos5000Amigos(long cursor, ref string resultado) { try { CursoredList amigosTwitter = twitter.FriendOperations.GetFriendIdsInCursorAsync(cursor).Result; resultado = System.DateTime.Now + " " + "Últimos 5000 amigos obtenidos" + Environment.NewLine + resultado; return amigosTwitter; } catch (Exception error) { resultado = System.DateTime.Now + " " + "Error al obtener 5000 últimos amigos: " + error.Message; return null; } } //Obtener últimos 5000 usuarios que nos siguen (seguidores) en Twitter //cursor = -1 obtendrá los 5000 seguidores del usuario con el que hemos iniciado sesión public List obtenerUltimos5000Seguidores(long cursor, ref string resultado) { try { CursoredList seguidoresTwitter = twitter.FriendOperations.GetFollowerIdsInCursorAsync(cursor).Result; resultado = System.DateTime.Now + " " + "Últimos 5000 seguidores obtenidos" + Environment.NewLine + resultado; return seguidoresTwitter; } catch (Exception error) { resultado = System.DateTime.Now + " " + "Error al obtener 5000 últimos seguidores: " + error.Message; return null; } } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
using System; using System.Security.Cryptography; using System.Text; using System.IO; namespace AjpdSoftGestiónSeguidoresTwitter { class Encriptar { public string cifrarTextoAES (string textoCifrar, string palabraPaso, string valorRGBSalt, string algoritmoEncriptacionHASH, int iteraciones, string vectorInicial, int tamanoClave) { try { byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(vectorInicial); byte[] saltValueBytes = Encoding.ASCII.GetBytes(valorRGBSalt); byte[] plainTextBytes = Encoding.UTF8.GetBytes(textoCifrar); PasswordDeriveBytes password = new PasswordDeriveBytes(palabraPaso, saltValueBytes, algoritmoEncriptacionHASH, iteraciones); byte[] keyBytes = password.GetBytes(tamanoClave / 8); RijndaelManaged symmetricKey = new RijndaelManaged(); symmetricKey.Mode = CipherMode.CBC; ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, InitialVectorBytes); MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write); cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); byte[] cipherTextBytes = memoryStream.ToArray(); memoryStream.Close(); cryptoStream.Close(); string textoCifradoFinal = Convert.ToBase64String(cipherTextBytes); return textoCifradoFinal; } catch { return null; } } public string descifrarTextoAES (string textoCifrado, string palabraPaso, string valorRGBSalt, string algoritmoEncriptacionHASH, int iteraciones, string vectorInicial, int tamanoClave) { try { byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(vectorInicial); byte[] saltValueBytes = Encoding.ASCII.GetBytes(valorRGBSalt); byte[] cipherTextBytes = Convert.FromBase64String(textoCifrado); PasswordDeriveBytes password = new PasswordDeriveBytes(palabraPaso, saltValueBytes, algoritmoEncriptacionHASH, iteraciones); byte[] keyBytes = password.GetBytes(tamanoClave / 8); RijndaelManaged symmetricKey = new RijndaelManaged(); symmetricKey.Mode = CipherMode.CBC; ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, InitialVectorBytes); MemoryStream memoryStream = new MemoryStream(cipherTextBytes); CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read); byte[] plainTextBytes = new byte[cipherTextBytes.Length]; int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); memoryStream.Close(); cryptoStream.Close(); string textoDescifradoFinal = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount); return textoDescifradoFinal; } catch { return null; } } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SQLite; using System.Data.SqlClient; using System.Data; namespace AjpdSoftGestiónSeguidoresTwitter { class BDSQLite { public SQLiteConnection conexionSQLite; //crear la BD SQLite y las tablas para guardar datos de Twitter public void crearBDSQLite (string fichero, string contrasena, ref string resultado) { try { //creamos la BD SQLite SQLiteConnection.CreateFile(fichero); if (contrasena != "") { //establecemos la contraseña conexionSQLite.ChangePassword(contrasena); } //si existe el fichero de BD creamos las tablas if (System.IO.File.Exists(fichero)) { //conectamos con la BD SQLite para crear las tablas string resultadoConexion = ""; if (conectarBDSQLite(fichero, contrasena, ref resultadoConexion)) { //crear las tablas de SQLite para guardar datos de Twitter //tabla seguidores string consultaSQL = "create table seguidores (" + "id long not null primary key, fecha datetime)"; SQLiteCommand comandoSQL = new SQLiteCommand(consultaSQL, conexionSQLite); comandoSQL.CommandType = CommandType.Text; comandoSQL.ExecuteNonQuery(); //tabla amigos consultaSQL = "create table amigos (" + "id long not null primary key, fecha datetime)"; comandoSQL = new SQLiteCommand(consultaSQL, conexionSQLite); comandoSQL.CommandType = CommandType.Text; comandoSQL.ExecuteNonQuery(); //tabla mensajes directos consultaSQL = "create table mensaje (" + "id not null primary key, idusuario long)"; comandoSQL = new SQLiteCommand(consultaSQL, conexionSQLite); comandoSQL.CommandType = CommandType.Text; comandoSQL.ExecuteNonQuery(); resultado = System.DateTime.Now + " " + "BD SQLite creada correctamente."; } } } catch (Exception error) { resultado = System.DateTime.Now + " " + "Error al abrir la BD SQLite: " + error.Message; } } //conectar con la base de datos SQLite public bool conectarBDSQLite (string fichero, string contrasena, ref string resultado) { //si existe la BD SQLite if (System.IO.File.Exists(fichero)) { string stringConexionSQLite = String.Format("Data Source={0}", fichero); try { conexionSQLite = new SQLiteConnection(stringConexionSQLite); if (contrasena != "") conexionSQLite.SetPassword(contrasena); conexionSQLite.Open(); resultado = System.DateTime.Now + " " + "Conectado a la BD SQLite correctamente"; return true; } catch (Exception error) { resultado = System.DateTime.Now + " " + "Error al abrir BD SQLite: " + error.Message; return false; } } else { resultado = System.DateTime.Now + " " + "Error al abrir BD SQLite: no existe el fichero " + fichero; return false; } } //comprobar si existe seguidor en la bd SQLite (por el ID de Twitter) public bool existeSeguidor(long idSeguidor, ref string resultado) { string consultaSQL = "select count(*) from seguidores where id = " + Convert.ToString(idSeguidor); SQLiteCommand comandoSQL = new SQLiteCommand(consultaSQL, conexionSQLite); comandoSQL.CommandType = CommandType.Text; try { long numRegistros = (long)comandoSQL.ExecuteScalar(); comandoSQL.Dispose(); resultado = System.DateTime.Now + " " + "Ejecutada consulta SQL en SQLite para existe seguidor: " + Convert.ToString(numRegistros); return (numRegistros > 0); } catch (Exception error) { resultado = System.DateTime.Now + " " + "Error SQLite existe seguidor: " + error.Message; return false; } } //insertar nuevo seguidor en BD SQLite public void insertarSeguidor(long idSeguidor, ref string resultado) { string consultaSQL = "insert into seguidores (id, fecha) values (@idSeguidor, @fecha)"; try { SQLiteParameter parametroFecha = new SQLiteParameter(); parametroFecha.ParameterName = "@fecha"; parametroFecha.DbType = DbType.DateTime; parametroFecha.Value = System.DateTime.Now; SQLiteParameter parametroidSeguidor = new SQLiteParameter(); parametroidSeguidor.ParameterName = "@idSeguidor"; parametroidSeguidor.DbType = DbType.String; parametroidSeguidor.Value = Convert.ToString(idSeguidor); SQLiteCommand comandoSQL = new SQLiteCommand(consultaSQL, conexionSQLite); comandoSQL.CommandType = CommandType.Text; comandoSQL.Parameters.Add(parametroFecha); comandoSQL.Parameters.Add(parametroidSeguidor); comandoSQL.ExecuteNonQuery(); resultado = System.DateTime.Now + " " + "Insertado nuevo seguidor en BD SQLite [" + Convert.ToString(idSeguidor) + "]"; } catch (Exception error) { resultado = System.DateTime.Now + " " + "Error SQLite insertar seguidor: " + error.Message; } } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace AjpdSoftGestiónSeguidoresTwitter { public partial class formTwitter : Form { TareasTwitter tareasTwitter = new TareasTwitter(); BDSQLite bdSQLite = new BDSQLite(); Int32 numMensajesDirectosSesion = 0; private void cerrarAplicacion() { Application.Exit(); } public formTwitter() { InitializeComponent(); } private void btEliminarMensajeDirecto_Click(object sender, EventArgs e) { try { long idMensaje; idMensaje = Convert.ToInt64(lsMensajes.Items[lsMensajes.FocusedItem.Index].Text); if (MessageBox.Show("¿Está seguro que desea eliminar el mensaje directo [" + Convert.ToString(idMensaje) + "]?", "Eliminar mensaje directo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes) { string resultado = ""; tareasTwitter.eliminarMensajeDirecto(idMensaje, ref resultado); txtLog.Text = resultado + Environment.NewLine + txtLog.Text; } } catch (Exception error) { txtLog.Text = System.DateTime.Now + " " + "Error al eliminar mensaje directo: " + error.Message + Environment.NewLine + txtLog.Text; } } private void btResponderMensajeDirecto_Click(object sender, EventArgs e) { try { long idUsuario; idUsuario = Convert.ToInt64(lsMensajes.Items[lsMensajes.FocusedItem.Index].SubItems[1].Text); string resultado = ""; string mensaje = ""; InputBox.solicitarTexto("Mensaje", "Introduzca mensaje directo a enviar:", ref mensaje); tareasTwitter.enviarMensajeDirectoTwitter(mensaje, idUsuario, ref resultado); txtLog.Text = resultado + Environment.NewLine + txtLog.Text; } catch (Exception error) { txtLog.Text = System.DateTime.Now + " " + "Error al responder mensaje directo: " + error.Message + Environment.NewLine + txtLog.Text; } } private void btConectarTwitter_Click(object sender, EventArgs e) { string resultado = ""; if (tareasTwitter.obtenerTokenTwitter(ref resultado)) { btObtenerDatosPerfil.Enabled = true; btPerfilVisitarURL.Enabled = true; tab.Enabled = true; btObtenerDatosPerfil.Text = "Obtener datos del perfil @" + txtUsuarioAccesoTwitter.Text; } else { btObtenerDatosPerfil.Enabled = false; btPerfilVisitarURL.Enabled = false; tab.Enabled = false; } txtLog.Text = resultado; } private void btObtenerSeguidores_Click(object sender, EventArgs e) { //preparamos el ListView lsSeguidores.Clear(); lsSeguidores.View = View.Details; lsSeguidores.GridLines = true; lsSeguidores.FullRowSelect = true; lsSeguidores.Columns.Add("ID", 70); lsSeguidores.Columns.Add("Nick", 80); lsSeguidores.Columns.Add("Nombre", 95); lsSeguidores.Columns.Add("Lo sigo", 40); lsSeguidores.Columns.Add("Seguidores", 60); lsSeguidores.Columns.Add("Siguiendo", 60); lsSeguidores.Columns.Add("Fecha alta", 60); lsSeguidores.Columns.Add("Descripción", 100); lsSeguidores.Columns.Add("URL Perfil", 60); lsSeguidores.Columns.Add("Ubicación", 40); lsSeguidores.Columns.Add("Idioma", 40); //Añadimos los elementos (filas) al ListView string[] elementosFila = new string[11]; ListViewItem elementoListView; string resultado = ""; List seguidores = new List(); seguidores = tareasTwitter.obtenerUltimos20Seguidores(ref resultado); //Añadimos los elementos (filas) al ListView //con los seguidores twitter obtenidos foreach (Seguidor seguidor in seguidores) { elementosFila[0] = Convert.ToString(seguidor.perfilUsuario.id); elementosFila[1] = Convert.ToString(seguidor.perfilUsuario.nick); elementosFila[2] = seguidor.perfilUsuario.nombre; elementosFila[3] = seguidor.meSigue; elementosFila[4] = Convert.ToString(seguidor.perfilUsuario.seguidores); elementosFila[5] = Convert.ToString(seguidor.perfilUsuario.siguiendo); elementosFila[6] = Convert.ToString(seguidor.perfilUsuario.fechaAlta); elementosFila[7] = seguidor.perfilUsuario.descripcion; elementosFila[8] = seguidor.perfilUsuario.urlPerfil; elementosFila[9] = seguidor.perfilUsuario.ubicacion; elementosFila[10] = seguidor.perfilUsuario.idioma; elementoListView = new ListViewItem(elementosFila); lsSeguidores.Items.Add(elementoListView); } txtLog.Text = resultado + Environment.NewLine + txtLog.Text; } private void btVisitarPerfilSeguidor_Click(object sender, EventArgs e) { string urlPerfilTwitter = ""; try { urlPerfilTwitter = lsSeguidores.Items[lsSeguidores.FocusedItem.Index].SubItems[8].Text; System.Diagnostics.Process.Start(urlPerfilTwitter); txtLog.Text = System.DateTime.Now + " " + "Visitado perfil [" + urlPerfilTwitter + "]" + Environment.NewLine + txtLog.Text; } catch (Exception error) { txtLog.Text = System.DateTime.Now + " " + "Error al visitar perfil Twitter [" + urlPerfilTwitter + "]: " + error.Message + Environment.NewLine + txtLog.Text; } } private void btDejardeSeguir_Click(object sender, EventArgs e) { try { string seguidorNick; seguidorNick = lsSeguidores.Items[lsSeguidores.FocusedItem.Index].SubItems[1].Text; string resultado = ""; tareasTwitter.dejarDeSeguirAmigo(seguidorNick, ref resultado); txtLog.Text = resultado + Environment.NewLine + txtLog.Text; } catch (Exception error) { txtLog.Text = System.DateTime.Now + " " + "Error al dejar de seguir a seguidor: " + error.Message + Environment.NewLine + txtLog.Text; } } private void btSeguirSeguidor_Click(object sender, EventArgs e) { try { string seguidorNick; seguidorNick = lsSeguidores.Items[lsSeguidores.FocusedItem.Index].SubItems[1].Text; string resultado = ""; tareasTwitter.seguirUsuario(seguidorNick, ref resultado); txtLog.Text = resultado + Environment.NewLine + txtLog.Text; } catch (Exception error) { txtLog.Text = System.DateTime.Now + " " + "Error al seguir a seguidor: " + error.Message + Environment.NewLine + txtLog.Text; } } private void btObtenerUltimosAmigos_Click(object sender, EventArgs e) { //preparamos el ListView lsAmigos.Clear(); lsAmigos.View = View.Details; lsAmigos.GridLines = true; lsAmigos.FullRowSelect = true; lsAmigos.Columns.Add("ID", 70); lsAmigos.Columns.Add("Nick", 80); lsAmigos.Columns.Add("Nombre", 95); lsAmigos.Columns.Add("Seguidores", 60); lsAmigos.Columns.Add("Siguiendo", 60); lsAmigos.Columns.Add("Fecha alta", 60); lsAmigos.Columns.Add("Descripción", 100); lsAmigos.Columns.Add("URL Perfil", 60); lsAmigos.Columns.Add("Ubicación", 40); lsAmigos.Columns.Add("Idioma", 40); //Añadimos los elementos (filas) al ListView string[] elementosFila = new string[10]; ListViewItem elementoListView; string resultado = ""; List amigos = new List(); amigos = tareasTwitter.obtenerUltimos20Amigos(ref resultado); //Añadimos los elementos (filas) al ListView //con los seguidores twitter obtenidos foreach (Amigo amigo in amigos) { elementosFila[0] = Convert.ToString(amigo.perfilUsuario.id); elementosFila[1] = Convert.ToString(amigo.perfilUsuario.nick); elementosFila[2] = amigo.perfilUsuario.nombre; elementosFila[3] = Convert.ToString(amigo.perfilUsuario.seguidores); elementosFila[4] = Convert.ToString(amigo.perfilUsuario.siguiendo); elementosFila[5] = Convert.ToString(amigo.perfilUsuario.fechaAlta); elementosFila[6] = amigo.perfilUsuario.descripcion; elementosFila[7] = amigo.perfilUsuario.urlPerfil; elementosFila[8] = amigo.perfilUsuario.ubicacion; elementosFila[9] = amigo.perfilUsuario.idioma; elementoListView = new ListViewItem(elementosFila); lsAmigos.Items.Add(elementoListView); } txtLog.Text = resultado + Environment.NewLine + txtLog.Text; } private void btDejarSeguirAmigo_Click(object sender, EventArgs e) { try { string seguidorNick; seguidorNick = lsAmigos.Items[lsAmigos.FocusedItem.Index].SubItems[1].Text; string resultado = ""; tareasTwitter.dejarDeSeguirAmigo(seguidorNick, ref resultado); txtLog.Text = resultado + Environment.NewLine + txtLog.Text; } catch (Exception error) { txtLog.Text = System.DateTime.Now + " " + "Error al dejar de seguir a amigo: " + error.Message + Environment.NewLine + txtLog.Text; } } private void btSeguirAmigo_Click(object sender, EventArgs e) { try { string seguidorNick; seguidorNick = lsAmigos.Items[lsAmigos.FocusedItem.Index].SubItems[1].Text; string resultado = ""; tareasTwitter.seguirUsuario(seguidorNick, ref resultado); txtLog.Text = resultado + Environment.NewLine + txtLog.Text; } catch (Exception error) { txtLog.Text = System.DateTime.Now + " " + "Error al seguir a amigo: " + error.Message + Environment.NewLine + txtLog.Text; } } private void btEnviarTweet_Click(object sender, EventArgs e) { string resultado = ""; tareasTwitter.enviarTweet(txtTweet.Text, ref resultado); txtLog.Text = resultado + Environment.NewLine + txtLog.Text; } private void btObtenerUltimosMensajesDirectos_Click(object sender, EventArgs e) { //establecemos las propiedades del ListView lsMensajes.Clear(); lsMensajes.View = View.Details; lsMensajes.GridLines = true; lsMensajes.FullRowSelect = true; //añadimos las columnas al ListView lsMensajes.Columns.Add("ID", 90); lsMensajes.Columns.Add("ID Usuario", 70); lsMensajes.Columns.Add("Nick", 70); lsMensajes.Columns.Add("Usuario", 90); lsMensajes.Columns.Add("Mensaje", 600); lsMensajes.Columns.Add("Fecha", 90); string[] elementosFila = new string[6]; ListViewItem elementoListView; string resultado = ""; List mensajes = new List(); mensajes = tareasTwitter.obtenerUltimos20MensajesDirectos(ref resultado); //Añadimos los elementos (filas) al ListView con los mensajes twitter obtenidos foreach (MensajeDirecto mensaje in mensajes) { elementosFila[0] = Convert.ToString(mensaje.id); elementosFila[1] = Convert.ToString(mensaje.idUsuario); elementosFila[2] = mensaje.nick; elementosFila[3] = mensaje.usuario; elementosFila[4] = mensaje.mensaje; elementosFila[5] = Convert.ToString(mensaje.fecha); elementoListView = new ListViewItem(elementosFila); lsMensajes.Items.Add(elementoListView); } txtLog.Text = resultado + Environment.NewLine + txtLog.Text; } private void btObtenerUltimosTweetsTimeLine_Click(object sender, EventArgs e) { //Establecemos las propiedades del ListView lsTweets.Clear(); lsTweets.View = View.Details; lsTweets.GridLines = true; lsTweets.FullRowSelect = true; //Añadimos las columnas al ListView lsTweets.Columns.Add("ID", 90); lsTweets.Columns.Add("ID Usuario", 70); lsTweets.Columns.Add("Usuario", 70); lsTweets.Columns.Add("Fecha", 90); lsTweets.Columns.Add("Tweet", 500); lsTweets.Columns.Add("Nº retweets", 90); //Añadimos los elementos (filas) al ListView string[] elementosFila = new string[6]; ListViewItem elementoListView; string resultado = ""; List tweets = new List(); tweets = tareasTwitter.obtener20UltimosTweet("HomeTimeLine", ref resultado); foreach (DatosTweet tweet in tweets) { //Añadimos una primera fila al ListView elementosFila[0] = Convert.ToString(tweet.id); elementosFila[1] = Convert.ToString(tweet.idUsuario); elementosFila[2] = tweet.usuario; elementosFila[3] = Convert.ToString(tweet.fecha); elementosFila[4] = tweet.tweet; elementosFila[5] = Convert.ToString(tweet.NumeroRetweet); elementoListView = new ListViewItem(elementosFila); lsTweets.Items.Add(elementoListView); } txtLog.Text = resultado + Environment.NewLine + txtLog.Text; } private void btObtenerUltimosTweetsMios_Click(object sender, EventArgs e) { //Establecemos las propiedades del ListView lsTweetsMios.Clear(); lsTweetsMios.View = View.Details; lsTweetsMios.GridLines = true; lsTweetsMios.FullRowSelect = true; //Añadimos las columnas al ListView lsTweetsMios.Columns.Add("ID", 90); lsTweetsMios.Columns.Add("ID Usuario", 70); lsTweetsMios.Columns.Add("Usuario", 70); lsTweetsMios.Columns.Add("Fecha", 90); lsTweetsMios.Columns.Add("Tweet", 500); lsTweetsMios.Columns.Add("Nº retweets", 90); //Añadimos los elementos (filas) al ListView string[] elementosFila = new string[6]; ListViewItem elementoListView; string resultado = ""; List tweets = new List(); tweets = tareasTwitter.obtener20UltimosTweet("UserTimeLine", ref resultado); foreach (DatosTweet tweet in tweets) { //Añadimos una primera fila al ListView elementosFila[0] = Convert.ToString(tweet.id); elementosFila[1] = Convert.ToString(tweet.idUsuario); elementosFila[2] = tweet.usuario; elementosFila[3] = Convert.ToString(tweet.fecha); elementosFila[4] = tweet.tweet; elementosFila[5] = Convert.ToString(tweet.NumeroRetweet); elementoListView = new ListViewItem(elementosFila); lsTweetsMios.Items.Add(elementoListView); } txtLog.Text = resultado + Environment.NewLine + txtLog.Text; } private void btObtenerTweetsMenciones_Click(object sender, EventArgs e) { //Establecemos las propiedades del ListView lsTweetMenciones.Clear(); lsTweetMenciones.View = View.Details; lsTweetMenciones.GridLines = true; lsTweetMenciones.FullRowSelect = true; //Añadimos las columnas al ListView lsTweetMenciones.Columns.Add("ID", 90); lsTweetMenciones.Columns.Add("ID Usuario", 70); lsTweetMenciones.Columns.Add("Usuario", 70); lsTweetMenciones.Columns.Add("Fecha", 90); lsTweetMenciones.Columns.Add("Tweet", 500); lsTweetMenciones.Columns.Add("Nº retweets", 90); //Añadimos los elementos (filas) al ListView string[] elementosFila = new string[6]; ListViewItem elementoListView; string resultado = ""; List tweets = new List(); tweets = tareasTwitter.obtener20UltimosTweet("Menciones", ref resultado); foreach (DatosTweet tweet in tweets) { //Añadimos una primera fila al ListView elementosFila[0] = Convert.ToString(tweet.id); elementosFila[1] = Convert.ToString(tweet.idUsuario); elementosFila[2] = tweet.usuario; elementosFila[3] = Convert.ToString(tweet.fecha); elementosFila[4] = tweet.tweet; elementosFila[5] = Convert.ToString(tweet.NumeroRetweet); elementoListView = new ListViewItem(elementosFila); lsTweetMenciones.Items.Add(elementoListView); } txtLog.Text = resultado + Environment.NewLine + txtLog.Text; } private void btObtenerTweetsFavoritos_Click(object sender, EventArgs e) { //Establecemos las propiedades del ListView lsTweetsFavoritos.Clear(); lsTweetsFavoritos.View = View.Details; lsTweetsFavoritos.GridLines = true; lsTweetsFavoritos.FullRowSelect = true; //Añadimos las columnas al ListView lsTweetsFavoritos.Columns.Add("ID", 90); lsTweetsFavoritos.Columns.Add("ID Usuario", 70); lsTweetsFavoritos.Columns.Add("Usuario", 70); lsTweetsFavoritos.Columns.Add("Fecha", 90); lsTweetsFavoritos.Columns.Add("Tweet", 500); lsTweetsFavoritos.Columns.Add("Nº retweets", 90); //Añadimos los elementos (filas) al ListView string[] elementosFila = new string[6]; ListViewItem elementoListView; string resultado = ""; List tweets = new List(); tweets = tareasTwitter.obtener20UltimosTweet("Favoritos", ref resultado); foreach (DatosTweet tweet in tweets) { //Añadimos una primera fila al ListView elementosFila[0] = Convert.ToString(tweet.id); elementosFila[1] = Convert.ToString(tweet.idUsuario); elementosFila[2] = tweet.usuario; elementosFila[3] = Convert.ToString(tweet.fecha); elementosFila[4] = tweet.tweet; elementosFila[5] = Convert.ToString(tweet.NumeroRetweet); elementoListView = new ListViewItem(elementosFila); lsTweetsFavoritos.Items.Add(elementoListView); } txtLog.Text = resultado + Environment.NewLine + txtLog.Text; } private void btObtenerTweetsMisRetwees_Click(object sender, EventArgs e) { //Establecemos las propiedades del ListView lsTweetsMisRetweets.Clear(); lsTweetsMisRetweets.View = View.Details; lsTweetsMisRetweets.GridLines = true; lsTweetsMisRetweets.FullRowSelect = true; //Añadimos las columnas al ListView lsTweetsMisRetweets.Columns.Add("ID", 90); lsTweetsMisRetweets.Columns.Add("ID Usuario", 70); lsTweetsMisRetweets.Columns.Add("Usuario", 70); lsTweetsMisRetweets.Columns.Add("Fecha", 90); lsTweetsMisRetweets.Columns.Add("Tweet", 500); lsTweetsMisRetweets.Columns.Add("Nº retweets", 90); //Añadimos los elementos (filas) al ListView string[] elementosFila = new string[6]; ListViewItem elementoListView; string resultado = ""; List tweets = new List(); tweets = tareasTwitter.obtener20UltimosTweet("Retweets", ref resultado); foreach (DatosTweet tweet in tweets) { //Añadimos una primera fila al ListView elementosFila[0] = Convert.ToString(tweet.id); elementosFila[1] = Convert.ToString(tweet.idUsuario); elementosFila[2] = tweet.usuario; elementosFila[3] = Convert.ToString(tweet.fecha); elementosFila[4] = tweet.tweet; elementosFila[5] = Convert.ToString(tweet.NumeroRetweet); elementoListView = new ListViewItem(elementosFila); lsTweetsMisRetweets.Items.Add(elementoListView); } txtLog.Text = resultado + Environment.NewLine + txtLog.Text; } private void temporizador_Tick(object sender, EventArgs e) { string resultado = ""; try { //obtenemos últimos 20 seguidores List seguidores = new List(); seguidores = tareasTwitter.obtenerUltimos20Seguidores(ref resultado); txtLog.Text = resultado + Environment.NewLine + txtLog.Text; //recorremos seguidor a seguidor para tareas automáticas foreach (Seguidor seguidor in seguidores) { //si el seguidor es nuevo lo añadimos a la BD SQLite if (!bdSQLite.existeSeguidor(seguidor.perfilUsuario.id, ref resultado)) { txtLog.Text = resultado + Environment.NewLine + txtLog.Text; bdSQLite.insertarSeguidor(seguidor.perfilUsuario.id, ref resultado); txtLog.Text = resultado + Environment.NewLine + txtLog.Text; //Es un nuevo seguidor, le enviamos automáticamente un mensaje directo if (txtTareaAutoMensajeDirectoSeguidores.Text != "" & opTareaAutoEnviarMensajeDirectoSeguidores.Checked) { tareasTwitter.enviarMensajeDirectoTwitter( txtTareaAutoMensajeDirectoSeguidores.Text, seguidor.perfilUsuario.id, ref resultado); txtLog.Text = resultado + Environment.NewLine + txtLog.Text; numMensajesDirectosSesion = numMensajesDirectosSesion + 1; bePNumMensajesDirectos.Text = "Nº mensajes directos: " + Convert.ToString(numMensajesDirectosSesion); if (iconizarApp.Visible) iconizarApp.Text = Application.ProductName + " @" + txtUsuarioAccesoTwitter.Text + " [" + Convert.ToString(numMensajesDirectosSesion) + "]"; } //añadi mención nuevo seguidor if (opTareaAutoMencion.Checked) { if (seguidor.perfilUsuario.nick != "" & txtTareaAutoMencion.Text != "") { string textoMencion = ""; textoMencion = txtTareaAutoMencion.Text; textoMencion = textoMencion.Replace("##nick##", "@" + seguidor.perfilUsuario.nick); tareasTwitter.enviarTweet(textoMencion, ref resultado); txtLog.Text = resultado + Environment.NewLine + txtLog.Text; } } //Es un nuevo seguidor, lo seguimos if (opTareaAutoSeguirSeguidor.Checked) { tareasTwitter.seguirUsuario(seguidor.perfilUsuario.nick, ref resultado); txtLog.Text = resultado + Environment.NewLine + txtLog.Text; //numSeguidos = +1; //bePNumMensajesDirectos.Text = "Nº mensajes directos: " + // Convert.ToString(numMensajesDirectosSesion); } } else txtLog.Text = System.DateTime.Now + " " + "El seguidor [" + Convert.ToString(seguidor.perfilUsuario.id) + "] ya existe en la BD" + Environment.NewLine + txtLog.Text; } } catch (Exception error) { txtLog.Text = System.DateTime.Now + " " + "Error al iniciar temporizador: " + error.Message + Environment.NewLine + txtLog.Text; } } private void btCrearBDSQLite_Click(object sender, EventArgs e) { //crear la BD SQLite con las tablas necesarias si no existe if (!System.IO.File.Exists(txtBDSQLite.Text)) { string resultado = ""; bdSQLite.crearBDSQLite(txtBDSQLite.Text, txtBDSQLiteContrasena.Text, ref resultado); txtLog.Text = resultado + Environment.NewLine + txtLog.Text; } else { MessageBox.Show("La BD SQLite ya existe, si desea " + "reemplazarla debe eliminarla o moverla manualmente.", "BD SQlite", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } private void bSelFicBDSQLite_Click(object sender, EventArgs e) { dlAbrirFichero.CheckFileExists = false; dlAbrirFichero.CheckPathExists = true; dlAbrirFichero.Multiselect = false; dlAbrirFichero.DefaultExt = "sqlite"; dlAbrirFichero.FileName = ""; dlAbrirFichero.Filter = "Archivos SQLite (*.sqlite)|*.sqlite|" + "Todos los archivos (*.*)|*.*"; dlAbrirFichero.Title = "Seleccionar fichero BD SQLite"; if (dlAbrirFichero.ShowDialog() == DialogResult.OK) { txtBDSQLite.Text = dlAbrirFichero.FileName; } } private void btActivarTareasAutomaticas_Click(object sender, EventArgs e) { try { temporizador.Enabled = false; if (txtTareaAutomaticaIntervalo.Text != "") temporizador.Interval = Convert.ToInt32(txtTareaAutomaticaIntervalo.Text) * 1000; else temporizador.Interval = 300000; //si no se especifica intervalo: 5 minutos if (System.IO.File.Exists(txtBDSQLite.Text)) { string resultado = ""; if (bdSQLite.conectarBDSQLite(txtBDSQLite.Text, txtBDSQLiteContrasena.Text, ref resultado)) { txtLog.Text = resultado + Environment.NewLine + txtLog.Text; temporizador.Enabled = true; btActivarTareasAutomaticas.Enabled = false; btDetenerTareasAutomaticas.Enabled = true; mnuDesactivarTareasAutomaticas.Enabled = true; mnuActivarTareasAutomaticas.Enabled = false; } else txtLog.Text = resultado + Environment.NewLine + txtLog.Text; } else { tab.SelectedTab = tabConfiguracion; bSelFicBDSQLite.Focus(); MessageBox.Show("Para activar las tareas automáticas debe " + "crear la BD SQLite previamente.", "Tareas automáticas Twitter", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } } catch (Exception error) { txtLog.Text = System.DateTime.Now + " " + "Error al iniciar tareas automáticas: " + error.Message + Environment.NewLine + txtLog.Text; } } private void btObtenerDatosPerfil_Click(object sender, EventArgs e) { string resultado = ""; PerfilUsuario datosPerfilUsuario = new PerfilUsuario(); tareasTwitter.obtenerDatosPerfilPIN(txtUsuarioAccesoTwitter.Text, ref datosPerfilUsuario, ref resultado); txtPerfilNick.Text = datosPerfilUsuario.nick; txtPerfilNombre.Text = datosPerfilUsuario.nombre; txtPerfilBiografia.Text = datosPerfilUsuario.descripcion; txtPerfilSiguiendo.Text = Convert.ToString(datosPerfilUsuario.siguiendo); txtPerfilSeguidores.Text = Convert.ToString(datosPerfilUsuario.seguidores); txtPerfilFechaAlta.Text = Convert.ToString(datosPerfilUsuario.fechaAlta); txtPerfilUbicacion.Text = datosPerfilUsuario.ubicacion; txtPerfilID.Text = Convert.ToString(datosPerfilUsuario.id); txtPerfilIdioma.Text = datosPerfilUsuario.idioma; txtPerfilURL.Text = datosPerfilUsuario.urlPerfil; opPerfilRestringido.Checked = datosPerfilUsuario.protegido; opPerfilTraductor.Checked = datosPerfilUsuario.traductor; txtLog.Text = resultado + Environment.NewLine + txtLog.Text; } private void btVisitarPerfilTweetTimeLine_Click(object sender, EventArgs e) { string urlPerfilTwitter = ""; string usuario = ""; try { usuario = lsTweets.Items[lsTweets.FocusedItem.Index].SubItems[2].Text; string resultado = ""; PerfilUsuario perfilUsuario = new PerfilUsuario(); tareasTwitter.obtenerDatosPerfilPIN(usuario, ref perfilUsuario, ref resultado); txtLog.Text = resultado + Environment.NewLine + txtLog.Text; urlPerfilTwitter = perfilUsuario.urlPerfil; if (urlPerfilTwitter != null) { System.Diagnostics.Process.Start(urlPerfilTwitter); txtLog.Text = System.DateTime.Now + " " + "Visitado perfil [" + urlPerfilTwitter + "]" + Environment.NewLine + txtLog.Text; } else txtLog.Text = System.DateTime.Now + " No se ha podido obtener la URL del perfil del usuario"; } catch (Exception error) { txtLog.Text = System.DateTime.Now + " " + "Error al visitar perfil Twitter [" + urlPerfilTwitter + "]: " + error.Message + Environment.NewLine + txtLog.Text; } } private void btVisitarPefilAmigo_Click(object sender, EventArgs e) { string urlPerfilTwitter = ""; try { urlPerfilTwitter = lsAmigos.Items[lsAmigos.FocusedItem.Index].SubItems[7].Text; System.Diagnostics.Process.Start(urlPerfilTwitter); txtLog.Text = System.DateTime.Now + " " + "Visitado perfil [" + urlPerfilTwitter + "]" + Environment.NewLine + txtLog.Text; } catch (Exception error) { txtLog.Text = System.DateTime.Now + " " + "Error al visitar perfil Twitter [" + urlPerfilTwitter + "]: " + error.Message + Environment.NewLine + txtLog.Text; } } private void btDejarSeguirTimeLine_Click(object sender, EventArgs e) { try { string seguidorNick; seguidorNick = lsTweets.Items[lsTweets.FocusedItem.Index].SubItems[2].Text; string resultado = ""; tareasTwitter.dejarDeSeguirAmigo(seguidorNick, ref resultado); txtLog.Text = resultado + Environment.NewLine + txtLog.Text; } catch (Exception error) { txtLog.Text = System.DateTime.Now + " " + "Error al dejar de seguir a usuario: " + error.Message + Environment.NewLine + txtLog.Text; } } private void btSeguirTimeLine_Click(object sender, EventArgs e) { try { string seguidorNick; seguidorNick = lsTweets.Items[lsTweets.FocusedItem.Index].SubItems[2].Text; string resultado = ""; tareasTwitter.seguirUsuario(seguidorNick, ref resultado); txtLog.Text = resultado + Environment.NewLine + txtLog.Text; } catch (Exception error) { txtLog.Text = System.DateTime.Now + " " + "Error al seguir a usuario: " + error.Message + Environment.NewLine + txtLog.Text; } } private void btVisitarPerfilMisTweets_Click(object sender, EventArgs e) { string urlPerfilTwitter = ""; string usuario = ""; try { usuario = lsTweetsMios.Items[lsTweetsMios.FocusedItem.Index].SubItems[2].Text; string resultado = ""; PerfilUsuario perfilUsuario = new PerfilUsuario(); tareasTwitter.obtenerDatosPerfilPIN(usuario, ref perfilUsuario, ref resultado); txtLog.Text = resultado + Environment.NewLine + txtLog.Text; urlPerfilTwitter = perfilUsuario.urlPerfil; if (urlPerfilTwitter != null) { System.Diagnostics.Process.Start(urlPerfilTwitter); txtLog.Text = System.DateTime.Now + " " + "Visitado perfil [" + urlPerfilTwitter + "]" + Environment.NewLine + txtLog.Text; } else txtLog.Text = System.DateTime.Now + " No se ha podido obtener la URL del perfil del usuario"; } catch (Exception error) { txtLog.Text = System.DateTime.Now + " " + "Error al visitar perfil Twitter [" + urlPerfilTwitter + "]: " + error.Message + Environment.NewLine + txtLog.Text; } } private void btDejarSeguirMenciones_Click(object sender, EventArgs e) { try { string seguidorNick; seguidorNick = lsTweetMenciones.Items[lsTweetMenciones.FocusedItem.Index].SubItems[2].Text; string resultado = ""; tareasTwitter.dejarDeSeguirAmigo(seguidorNick, ref resultado); txtLog.Text = resultado + Environment.NewLine + txtLog.Text; } catch (Exception error) { txtLog.Text = System.DateTime.Now + " " + "Error al dejar de seguir a usuario: " + error.Message + Environment.NewLine + txtLog.Text; } } private void btSeguirMenciones_Click(object sender, EventArgs e) { try { string seguidorNick; seguidorNick = lsTweetMenciones.Items[lsTweetMenciones.FocusedItem.Index].SubItems[2].Text; string resultado = ""; tareasTwitter.seguirUsuario(seguidorNick, ref resultado); txtLog.Text = resultado + Environment.NewLine + txtLog.Text; } catch (Exception error) { txtLog.Text = System.DateTime.Now + " " + "Error al seguir a usuario: " + error.Message + Environment.NewLine + txtLog.Text; } } private void button4_Click(object sender, EventArgs e) { string urlPerfilTwitter = ""; string usuario = ""; try { usuario = lsTweetMenciones.Items[lsTweetMenciones.FocusedItem.Index].SubItems[2].Text; string resultado = ""; PerfilUsuario perfilUsuario = new PerfilUsuario(); tareasTwitter.obtenerDatosPerfilPIN(usuario, ref perfilUsuario, ref resultado); txtLog.Text = resultado + Environment.NewLine + txtLog.Text; urlPerfilTwitter = perfilUsuario.urlPerfil; if (urlPerfilTwitter != null) { System.Diagnostics.Process.Start(urlPerfilTwitter); txtLog.Text = System.DateTime.Now + " " + "Visitado perfil [" + urlPerfilTwitter + "]" + Environment.NewLine + txtLog.Text; } else txtLog.Text = System.DateTime.Now + " No se ha podido obtener la URL del perfil del usuario"; } catch (Exception error) { txtLog.Text = System.DateTime.Now + " " + "Error al visitar perfil Twitter [" + urlPerfilTwitter + "]: " + error.Message + Environment.NewLine + txtLog.Text; } } private void btDetenerTareasAutomaticas_Click(object sender, EventArgs e) { temporizador.Enabled = false; btActivarTareasAutomaticas.Enabled = true; btDetenerTareasAutomaticas.Enabled = false; mnuDesactivarTareasAutomaticas.Enabled = false; mnuActivarTareasAutomaticas.Enabled = true; } private void lbEnlaceURL_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { System.Diagnostics.Process.Start("https://www.proyectoa.com"); } private void formTwitter_FormClosed(object sender, FormClosedEventArgs e) { GuardarConfiguracion guardarConfig = new GuardarConfiguracion(); guardarConfig.guardarValorConfiguracion("TA.Intervalo", Convert.ToString(txtTareaAutomaticaIntervalo.Value)); if (opTareaAutoEnviarMensajeDirectoSeguidores.Checked) guardarConfig.guardarValorConfiguracion("TA.Mensaje.Activar", "Sí"); else guardarConfig.guardarValorConfiguracion("TA.Mensaje.Activar", "No"); guardarConfig.guardarValorConfiguracion("TA.Mensaje.Mensaje", txtTareaAutoMensajeDirectoSeguidores.Text); if (opTareaAutoMencion.Checked) guardarConfig.guardarValorConfiguracion("TA.Mencion.Activar", "Sí"); else guardarConfig.guardarValorConfiguracion("TA.Mencion.Activar", "No"); guardarConfig.guardarValorConfiguracion("TA.Mencion.Mensaje", txtTareaAutoMencion.Text); if (opTareaAutoSeguirSeguidor.Checked) guardarConfig.guardarValorConfiguracion("TA.Seguir.Activar", "Sí"); else guardarConfig.guardarValorConfiguracion("TA.Seguir.Activar", "No"); guardarConfig.guardarValorConfiguracion("BD.Fichero", txtBDSQLite.Text); Encriptar encriptar = new Encriptar(); guardarConfig.guardarValorConfiguracion("BD.Contraseña", encriptar.cifrarTextoAES(txtBDSQLite.Text, "AjpdSoft_Frase_Encriptado", "AjpdSoft_Frase_Encriptado", "MD5", 22, "1234567891234567", 128)); guardarConfig.guardarValorConfiguracion("Tweet.Tweet", txtTweet.Text); guardarConfig.guardarValorConfiguracion("Twitter.Usuario", txtUsuarioAccesoTwitter.Text); } private void formTwitter_Load(object sender, EventArgs e) { if (System.IO.File.Exists( System.IO.Path.Combine( AppDomain.CurrentDomain.BaseDirectory, AppDomain.CurrentDomain.FriendlyName + ".config"))) { GuardarConfiguracion guardarConfig = new GuardarConfiguracion(); string intervalo = ""; txtUsuarioAccesoTwitter.Text = guardarConfig.leerValorConfiguracion("Twitter.Usuario"); intervalo = guardarConfig.leerValorConfiguracion("TA.Intervalo"); if (intervalo != "") txtTareaAutomaticaIntervalo.Value = Convert.ToDecimal(intervalo); string op = ""; op = guardarConfig.leerValorConfiguracion("TA.Mensaje.Activar"); if (op == "Sí") opTareaAutoEnviarMensajeDirectoSeguidores.Checked = true; else opTareaAutoEnviarMensajeDirectoSeguidores.Checked = false; txtTareaAutoMensajeDirectoSeguidores.Text = guardarConfig.leerValorConfiguracion("TA.Mensaje.Mensaje"); op = guardarConfig.leerValorConfiguracion("TA.Mencion.Activar"); if (op == "Sí") opTareaAutoMencion.Checked = true; else opTareaAutoMencion.Checked = false; txtTareaAutoMencion.Text = guardarConfig.leerValorConfiguracion("TA.Mencion.Mensaje"); op = guardarConfig.leerValorConfiguracion("TA.Seguir.Activar"); if (op == "Sí") opTareaAutoSeguirSeguidor.Checked = true; else opTareaAutoSeguirSeguidor.Checked = false; txtBDSQLite.Text = guardarConfig.leerValorConfiguracion("BD.Fichero"); Encriptar encriptar = new Encriptar(); txtBDSQLite.Text = encriptar.descifrarTextoAES( guardarConfig.leerValorConfiguracion("BD.Contraseña"), "AjpdSoft_Frase_Encriptado", "AjpdSoft_Frase_Encriptado", "MD5", 22, "1234567891234567", 128); txtTweet.Text = guardarConfig.leerValorConfiguracion("Tweet.Tweet"); } } //Buscar un elemento en un ListView private bool existeElementoListView(ListView lista, string elementoBuscar) { foreach (ListViewItem elementoLista in lista.Items) { if (elementoLista.Text == elementoBuscar) return true; } return false; } private void btTest_Click(object sender, EventArgs e) { string resultado = ""; //últimos 5000 amigos List listaAmigos = new List(); listaAmigos = tareasTwitter.obtenerUltimos5000Amigos(-1, ref resultado); txtLog.Text = resultado + Environment.NewLine + txtLog.Text; lsAmigosTodos.Clear(); lsAmigosTodos.View = View.Details; lsAmigosTodos.GridLines = true; lsAmigosTodos.FullRowSelect = true; //Añadimos los elementos (filas) al ListView string[] elementosFila = new string[1]; ListViewItem elementoListView; lsAmigosTodos.Columns.Add("ID", 70); foreach (long amigo in listaAmigos) { elementosFila[0] = Convert.ToString(amigo); elementoListView = new ListViewItem(elementosFila); lsAmigosTodos.Items.Add(elementoListView); } lInfoAmigos.Text = "Amigos (siguiendo) [" + Convert.ToString(lsAmigosTodos.Items.Count) + "]"; //últimos 5000 seguidores List listaSeguidores = new List(); listaSeguidores = tareasTwitter.obtenerUltimos5000Seguidores(-1, ref resultado); txtLog.Text = resultado + Environment.NewLine + txtLog.Text; lsSeguidoresTodos.Clear(); lsSeguidoresTodos.View = View.Details; lsSeguidoresTodos.GridLines = true; lsSeguidoresTodos.FullRowSelect = true; //Añadimos los elementos (filas) al ListView string[] elementosFilaSeguidores = new string[1]; ListViewItem elementoListViewSeguidores; lsSeguidoresTodos.Columns.Add("ID", 70); foreach (long seguidor in listaSeguidores) { elementosFilaSeguidores[0] = Convert.ToString(seguidor); elementoListViewSeguidores = new ListViewItem(elementosFilaSeguidores); lsSeguidoresTodos.Items.Add(elementoListViewSeguidores); } lInfoSeguidores.Text = "Seguidores [" + Convert.ToString(lsSeguidoresTodos.Items.Count) + "]"; //comparamos cada elemento del listview de amigos con los del listview de seguidores //para mostrar los amigos que no nos siguen lsAmigosNoTeSiguen.Clear(); lsAmigosNoTeSiguen.View = View.Details; lsAmigosNoTeSiguen.GridLines = true; lsAmigosNoTeSiguen.FullRowSelect = true; //Añadimos los elementos (filas) al ListView string[] elementosFilaAmigosNoteSiguen = new string[1]; ListViewItem elementoListViewAmigosNoteSiguen; lsAmigosNoTeSiguen.Columns.Add("ID", 70); foreach (ListViewItem elementoLista in lsAmigosTodos.Items) { if (!existeElementoListView(lsSeguidoresTodos, elementoLista.Text)) { elementosFilaAmigosNoteSiguen[0] = elementoLista.Text; elementoListViewAmigosNoteSiguen = new ListViewItem(elementosFilaAmigosNoteSiguen); lsAmigosNoTeSiguen.Items.Add(elementoListViewAmigosNoteSiguen); } } lInfoAmigosNoTeSiguen.Text = "Amigos que no te siguen [" + Convert.ToString(lsAmigosNoTeSiguen.Items.Count) + "]"; /* List listaAmigos = new List(); string resultado = ""; listaAmigos = tareasTwitter.obtenerUltimos5000Amigos(-1, ref resultado); txtLog.Text = resultado + Environment.NewLine + txtLog.Text; lsSeguidoresTodos.Clear(); lsSeguidoresTodos.View = View.Details; lsSeguidoresTodos.GridLines = true; lsSeguidoresTodos.FullRowSelect = true; //Añadimos los elementos (filas) al ListView string[] elementosFila = new string[15]; ListViewItem elementoListView; lsSeguidoresTodos.Columns.Add("ID", 70); lsSeguidoresTodos.Columns.Add("Nick", 70); lsSeguidoresTodos.Columns.Add("Nombre", 85); lsSeguidoresTodos.Columns.Add("Lo sigo", 30); lsSeguidoresTodos.Columns.Add("Seguidores", 50); lsSeguidoresTodos.Columns.Add("Siguiendo", 50); lsSeguidoresTodos.Columns.Add("Fecha alta", 50); lsSeguidoresTodos.Columns.Add("Descripción", 100); lsSeguidoresTodos.Columns.Add("URL Perfil", 30); lsSeguidoresTodos.Columns.Add("Ubicación", 30); lsSeguidoresTodos.Columns.Add("Idioma", 30); lsSeguidoresTodos.Columns.Add("Verificado", 30); lsSeguidoresTodos.Columns.Add("Protegido", 30); lsSeguidoresTodos.Columns.Add("Notificaciones", 30); lsSeguidoresTodos.Columns.Add("Traductor", 30); foreach (long amigo in listaAmigos) { elementosFila[0] = Convert.ToString(amigo); PerfilUsuario perfilUsusuario = new PerfilUsuario(); tareasTwitter.obtenerPerfilUsuario(amigo, ref perfilUsusuario, ref resultado); txtLog.Text = resultado + Environment.NewLine + txtLog.Text; elementosFila[0] = Convert.ToString(perfilUsusuario.id); elementosFila[1] = Convert.ToString(perfilUsusuario.nick); elementosFila[2] = perfilUsusuario.nombre; if (perfilUsusuario.loSigo) elementosFila[3] = "Sí"; else elementosFila[3] = "No"; elementosFila[4] = Convert.ToString(perfilUsusuario.seguidores); elementosFila[5] = Convert.ToString(perfilUsusuario.siguiendo); elementosFila[6] = Convert.ToString(perfilUsusuario.fechaAlta); elementosFila[7] = perfilUsusuario.descripcion; elementosFila[8] = perfilUsusuario.urlPerfil; elementosFila[9] = perfilUsusuario.ubicacion; elementosFila[10] = perfilUsusuario.idioma; if (perfilUsusuario.verificado) elementosFila[11] = "Sí"; else elementosFila[11] = "No"; if (perfilUsusuario.protegido) elementosFila[12] = "Sí"; else elementosFila[12] = "No"; if (perfilUsusuario.notificaciones) elementosFila[13] = "Sí"; else elementosFila[13] = "No"; if (perfilUsusuario.traductor) elementosFila[14] = "Sí"; else elementosFila[14] = "No"; elementoListView = new ListViewItem(elementosFila); lsSeguidores.Items.Add(elementoListView); elementoListView = new ListViewItem(elementosFila); lsSeguidoresTodos.Items.Add(elementoListView); } //preparamos el ListView /* lsSeguidoresTodos.Clear(); lsSeguidores.View = View.Details; lsSeguidores.GridLines = true; lsSeguidores.FullRowSelect = true; lsSeguidores.Columns.Add("ID", 70); lsSeguidores.Columns.Add("Nick", 80); lsSeguidores.Columns.Add("Nombre", 95); lsSeguidores.Columns.Add("Lo sigo", 40); lsSeguidores.Columns.Add("Seguidores", 60); lsSeguidores.Columns.Add("Siguiendo", 60); lsSeguidores.Columns.Add("Fecha alta", 60); lsSeguidores.Columns.Add("Descripción", 100); lsSeguidores.Columns.Add("URL Perfil", 60); lsSeguidores.Columns.Add("Ubicación", 40); lsSeguidores.Columns.Add("Idioma", 40); //Añadimos los elementos (filas) al ListView string[] elementosFila = new string[11]; ListViewItem elementoListView; string resultado = ""; List seguidores = new List(); seguidores = tareasTwitter.obtenerUltimos20Seguidores(ref resultado); //Añadimos los elementos (filas) al ListView //con los seguidores twitter obtenidos foreach (Seguidor seguidor in seguidores) { elementosFila[0] = Convert.ToString(seguidor.perfilUsuario.id); elementosFila[1] = Convert.ToString(seguidor.perfilUsuario.nick); elementosFila[2] = seguidor.perfilUsuario.nombre; elementosFila[3] = seguidor.meSigue; elementosFila[4] = Convert.ToString(seguidor.perfilUsuario.seguidores); elementosFila[5] = Convert.ToString(seguidor.perfilUsuario.siguiendo); elementosFila[6] = Convert.ToString(seguidor.perfilUsuario.fechaAlta); elementosFila[7] = seguidor.perfilUsuario.descripcion; elementosFila[8] = seguidor.perfilUsuario.urlPerfil; elementosFila[9] = seguidor.perfilUsuario.ubicacion; elementosFila[10] = seguidor.perfilUsuario.idioma; elementoListView = new ListViewItem(elementosFila); lsSeguidores.Items.Add(elementoListView); } txtLog.Text = resultado + Environment.NewLine + txtLog.Text; */ } private void btMinimizar_Click(object sender, EventArgs e) { iconizarApp.Icon = this.Icon; iconizarApp.ContextMenuStrip = this.mnuContextual; iconizarApp.Text = Application.ProductName + " @" + txtUsuarioAccesoTwitter.Text; iconizarApp.Visible = true; this.Visible = false; } private void mnuMostrarAplicacion_Click(object sender, EventArgs e) { Show(); WindowState = FormWindowState.Normal; Activate(); iconizarApp.Visible = false; } private void mnuActivarTareasAutomaticas_Click(object sender, EventArgs e) { btActivarTareasAutomaticas_Click(sender, e); } private void mnuDesactivarTareasAutomaticas_Click(object sender, EventArgs e) { btDetenerTareasAutomaticas_Click(sender, e); } private void formTwitter_Resize(object sender, EventArgs e) { if (this.WindowState == FormWindowState.Minimized) { btMinimizar_Click(sender, e); //Tipo de icono a mostrar el el globo informativo (Info, Error, None, Warning) iconizarApp.BalloonTipIcon = ToolTipIcon.Info; //Título del balón informativo (el nombre de la aplicación) iconizarApp.BalloonTipTitle = Application.ProductName + " @" + txtUsuarioAccesoTwitter.Text; //Texto del balón informativo iconizarApp.BalloonTipText = "La aplicación ha quedado ocultada " + "en el área de notificación. Para mostrarla haga " + "doble clic sobre el icono"; //Tiempo que aparecerá hasta ocultarse automáticamente iconizarApp.ShowBalloonTip(8); } } private void iconizarApp_BalloonTipClicked(object sender, EventArgs e) { mnuMostrarAplicacion_Click(sender, e); } private void mnuCerrar_Click(object sender, EventArgs e) { cerrarAplicacion(); } private void txtUsuarioAccesoTwitter_TextChanged(object sender, EventArgs e) { this.Text = Application.ProductName + " @" + txtUsuarioAccesoTwitter.Text; } private void txtTweet_TextChanged(object sender, EventArgs e) { try { lInfoTweet.Text = "Caracteres restantes " + Convert.ToString(140 - txtTweet.Text.Length); } catch { } } private void txtTareaAutoMencion_TextChanged(object sender, EventArgs e) { string textoMencion = ""; textoMencion = txtTareaAutoMencion.Text; textoMencion = textoMencion.Replace("##nick##", "@" + txtUsuarioAccesoTwitter.Text); lMencionResultado.Text = textoMencion; } private void btDejarSeguirTodos_Click(object sender, EventArgs e) { if (lsAmigosTodos.Items.Count == 5000 || lsSeguidoresTodos.Items.Count == 5000) { MessageBox.Show("Este procedimiento sólo funcionará si tiene menos de 5.000 " + "amigos o seguidores. En futuras versiones ampliaremos este límite.", "El proceso no puede realizarse", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { if (MessageBox.Show("¿Está seguro que desea dejar de seguir a " + Convert.ToString(lsAmigosNoTeSiguen.Items.Count) + " amigos? Recuerde " + "que Twitter puede penalizar el uso abusivo de esta técnica." + Environment.NewLine + Environment.NewLine + "El proceso puede tardar varios minutos en función del número " + "de amigos a dejar de seguir.", "Dejar de seguir a amigos", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes) { foreach (ListViewItem elemento in lsAmigosNoTeSiguen.Items) { string resultado = ""; long idUsuario = 0; try { if (elemento.Text != "") { idUsuario = Convert.ToInt64(elemento.Text); tareasTwitter.dejarDeSeguirAmigo(idUsuario, ref resultado); txtLog.Text = resultado + Environment.NewLine + txtLog.Text; } } catch (Exception error) { txtLog.Text = System.DateTime.Now + " " + "Error al dejar de seguir a [" + Convert.ToString(idUsuario) + "]: " + error.Message + Environment.NewLine + txtLog.Text; } } } } } private void btPerfilVisitarURL_Click(object sender, EventArgs e) { string urlPerfilTwitter = ""; try { urlPerfilTwitter = txtPerfilURL.Text; System.Diagnostics.Process.Start(urlPerfilTwitter); txtLog.Text = System.DateTime.Now + " " + "Visitado perfil [" + urlPerfilTwitter + "]" + Environment.NewLine + txtLog.Text; } catch (Exception error) { txtLog.Text = System.DateTime.Now + " " + "Error al visitar perfil Twitter [" + urlPerfilTwitter + "]: " + error.Message + Environment.NewLine + txtLog.Text; } } private void btVisitarPerfilAmigosNoSiguen_Click(object sender, EventArgs e) { string urlPerfilTwitter = ""; long usuario = 0; try { usuario = Convert.ToInt64(lsAmigosNoTeSiguen.Items[lsAmigosNoTeSiguen.FocusedItem.Index].SubItems[0].Text); string resultado = ""; PerfilUsuario perfilUsuario = new PerfilUsuario(); tareasTwitter.obtenerPerfilUsuario(usuario, ref perfilUsuario, ref resultado); txtLog.Text = resultado + Environment.NewLine + txtLog.Text; urlPerfilTwitter = perfilUsuario.urlPerfil; if (urlPerfilTwitter != null) { System.Diagnostics.Process.Start(urlPerfilTwitter); txtLog.Text = System.DateTime.Now + " " + "Visitado perfil [" + urlPerfilTwitter + "]" + Environment.NewLine + txtLog.Text; } else txtLog.Text = System.DateTime.Now + " No se ha podido obtener la URL del perfil del usuario"; } catch (Exception error) { txtLog.Text = System.DateTime.Now + " " + "Error al visitar perfil Twitter [" + urlPerfilTwitter + "]: " + error.Message + Environment.NewLine + txtLog.Text; } } private void btProbarInsercionRegistroBD_Click(object sender, EventArgs e) { string resultado = ""; string valorID = ""; InputBox.solicitarTexto("ID Seguidor (número)", "11111111", ref valorID); try { bdSQLite.insertarSeguidor(Convert.ToInt64(valorID), ref resultado); MessageBox.Show("Resultado ejecución SQL inserción: " + Environment.NewLine + Environment.NewLine + resultado, "Insertar seguidor en BD", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception error) { MessageBox.Show(error.Message, "Insertar seguidor en BD", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void btComprobarExisteSeguidorBD_Click(object sender, EventArgs e) { string resultado = ""; string valorID = ""; InputBox.solicitarTexto("ID Seguidor (número)", "11111111", ref valorID); try { if (bdSQLite.existeSeguidor(Convert.ToInt64(valorID), ref resultado)) MessageBox.Show("El ID de seguidor ya existe en la BD." + Environment.NewLine + Environment.NewLine + resultado, "Existe seguidor", MessageBoxButtons.OK, MessageBoxIcon.Information); else MessageBox.Show("El ID de seguidor no existe en la BD." + Environment.NewLine + Environment.NewLine + resultado, "Existe seguidor", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception error) { MessageBox.Show(error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void btConectarBD_Click(object sender, EventArgs e) { string resultado = ""; if (bdSQLite.conectarBDSQLite(txtBDSQLite.Text, txtBDSQLiteContrasena.Text, ref resultado)) MessageBox.Show("Conexión establecida con la BD SQLite." + Environment.NewLine + Environment.NewLine + resultado, "Conexión BD", MessageBoxButtons.OK, MessageBoxIcon.Information); else MessageBox.Show("Error al conectar con la BD SQLite." + Environment.NewLine + Environment.NewLine + resultado, "Conexión BD", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; using System.Windows.Forms; namespace AjpdSoftGestiónSeguidoresTwitter { class GuardarConfiguracion { //leer valor de configuración del fichero app.config public string leerValorConfiguracion (string clave) { try { string resultado = ConfigurationManager.AppSettings[clave].ToString(); return resultado; } catch { return ""; } } //escribir valor de configuración en fichero app.config public void guardarValorConfiguracion(string clave, string valor) { try { Configuration ficheroConfXML = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath); //eliminamos la clave actual (si existe), si no la eliminamos //los valores se irán acumulando separados por coma ficheroConfXML.AppSettings.Settings.Remove(clave); //asignamos el valor en la clave indicada ficheroConfXML.AppSettings.Settings.Add(clave, valor); //guardamos los cambios definitivamente en el fichero de configuración ficheroConfXML.Save(ConfigurationSaveMode.Modified); } catch { /* MessageBox.Show("Error al guardar valor de configuración: " + System.Environment.NewLine + System.Environment.NewLine + ex.GetType().ToString() + System.Environment.NewLine + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);*/ } } } } |