Cómo insertar un evento o cita en el calendario de Google Calendar, usando para ello el IDE y lenguaje de programación Microsoft Visual Studio .Net (Visual Basic .Net) 2010. Para poder insertar o añadir una cita en un calendario de Google Calendar será necesario usar el API de Google, también explicamos cómo descargarlo y cómo usarlo. Mostramos y publicamos la aplicación AjpdSoft Insertar Evento Google Calendar con código fuente gratuito como ejemplo de este artículo: inserta un evento, muestra los eventos de todos los calendarios de un intervalo de fechas, muestra todos los calendarios.
- Descargar e instalar Google Data API SDK.
- Crear aplicación con Visual Basic .Net 2010 que inserta un evento en Google Calendar usando Google Data API.
- Crear nuevo proyecto en Visual Studio 2010, agregar referencia a Google Data API SDK .
- Componentes necesarios para insertar cita en Google Calendar y para mostrar las citas de una fecha.
- El código fuente source code más importante, validar en Google, insertar evento Google Calendar, obtener calendarios y citas, insertar calendario.
- AjpdSoft Insertar Evento Google Calendar.
- Anexo.
Descargar e instalar Google Data API SDK
Para instalar Google Data API en un equipo con Microsoft Windows 7 abriremos un navegador web como Mozilla Firefox y accederemos a la URL:
http://code.google.com/p/google-gdata/downloads/list
Seleccionaremos Google Data API Setup (1.7.0.1).msi (21 MB):
Pulsaremos en el enlace Google Data API Setup (1.7.0.1).msi para iniciar la descarga:
Una vez descargado el fichero «Google Data API Setup (1.7.0.1).msi» haremos doble clic sobre él para iniciar la instalación:
Microsoft Windows 7 nos advertirá de que se va a ejecutar un archivo potencialmente peligroso (por tratarse de una descarga de Internet). Pulsaremos «Ejecutar» para continuar:
Se iniciará el asistente de instalación de Google Data API SDK, pulsaremos «Next» para continuar:
Indicaremos la carpeta de instalación, por defecto:
C:/Program Files (x86)/Google/Google Data API SDK
Pulsaermos «Next» para continuar:
Tras la instalación de Google Data API SDK, el asistente nos informará de que el proceso de instalación ha concluido, con el texto «Google Data API SDK has been successfully installed». Pulsaremos «Close»:
En realidad, el programa de instalación de Google Data API SDK extrae varios ficheros y carpetas. Los importantes son las librerías (dll) que serán usadas por nuestra aplicación para el acceso a los servicios de Google Calendar, se encuentran en la carpeta «redist»:
Crear aplicación con Visual Basic .Net 2010 que inserta un evento en Google Calendar usando Google Data API
Crear nuevo proyecto en Visual Studio 2010, agregar referencia a Google Data API SDK
Una vez instalado Google Data API SDK e instalado Microsoft Visual Studio .Net 2010, abriremos Microsoft Visual Studio y pulsaremos en el menú «Archivo» – «Nuevo proyecto…»:
Seleccionaremos, en la parte izquierda, en «Plantillas instaladas» la opción «Visual Basic» y en la parte derecha seleccionaremos «Aplicación de Windows Forms». Elegiremos .NET Framework 3.5, hay que tener en cuenta que el API actual de Google, en su versión 1.7.0.1, no soporta Framework 4.0, por lo que para el correcto funcionamiento seleccionaremos .NET Framework 3.5. En «Nombre» introduciremos el nombre de la solución, por ejemplo «AjpdSoftInsertarEventoGoogleCalendar». Pulsaremos «Aceptar» para continuar:
En el Explorador de soluciones , en la parte derecha, pulsaremos con el botón derecho sobre nuestra Solución y seleccionaremos «Agregar referencia…»:
En la pestaña «Examinar», accederemos a la carpeta de instalación de Google Data API SDK, a la subcarpeta «Redist», seleccionaremos las tres librerías necesarias de Google: Google.GData.Calendar.dll, Google.GData.Client.dll y Google.GData.Extensions.dll:
Pulsaremos a continuación en el menú «Ver» – «Código» (o la tecla rápida F7) y añadiremos los siguientes Imports (si no han sido añadidos automáticamente al agregar las referencias):
Imports Google.GData.Calendar
Imports Google.GData.Client
Imports Google.GData.Extensions
Componentes necesarios para insertar cita en Google Calendar y para mostrar las citas de una fecha
En el formulario principal de la aplicación, en nuestro caso «formEnviarCitaCalendar.vb» añadiremos los siguientes componentes (podremos añadir los que queramos y como queramos, en la imagen mostramos un ejemplo):
A continuación indicamos los componentes más importantes:
- TextBox (txtUsuario): nombre de usuario de Google con el que iniciaremos sesión.
- TextBox (txtContrasena): contraseña del usuario de Google con el que iniciaremos sesión.
- TabControl (Tab): donde colocaremos los componentes para insertar la cita en una pestaña y en otra pestaña los componentes para mostrar las citas (consulta).
- En el TabControl para insertar la cita introduciremos los siguientes componentes:
- ComboBox (lsCalendarios): donde obtendremos la lista de los calendarios del usuario que ha iniciado sesión en Google Calendar, para que seleccione en el que se insertará el evento.
- DateTimePiker (txtDesdeDia): fecha desde la que empezará la cita o evento de Google Calendar.
- MaskedTextBox (txtDesdeHora): hora desde la que empezará la cita o evento de Google Calendar.
- DateTimePiker (txtHastaDia): fecha en la que finalizará la cita o evento de Google Calendar.
- MaskedTextBox (txtHastaHora): hora en la que acabará la cita o evento de Google Calendar.
- TextBox (txtEvento): asunto del evento de Google Calendar.
- TextBox (txtLugar): lugar donde se producirá la cita o evento de Google Calendar.
- TextBox (txtDescripcion): descripción de la cita de Google Calendar.
- ComboBox (lsRecordatorio): lista con el tipo de recordatorio (SMS,
Correo electrónico,
Ventana emergente). - TextBox (txtInvitados): posibles invitados al evento o cita de Google Calendar.
- Button (btValidar): botón para probar el usuario y la contraseña, para validar en cuenta de google.
- Button (btListaCalendarios): botón para obtener y mostrar los calendarios del usuario de Google Calendar.
- Button (btEnviar): botón para enviar el evento o cita a Google Calendar.
- Button (btSalir): botón para salir y guardar los datos actuales en fichero INI.
- En el TabControl para mostrar las citas usaremos los siguientes componentes:
- ComboBox (lsCalendariosCitas): donde obtendremos la lista de los calendarios del usuario que ha iniciado sesión en Google Calendar, para que seleccione el calendario del que se obtendrán los eventos/citas.
- DateTimePiker (txtCitasDesde): fecha desde la que mostraremos las citas de Google Calendar.
- DateTimePiker (txtCitasHasta): fecha hasta la que mostraremos las citas de Google Calendar.
- NumericUpDown (txtNumeroMaximoCitas): para limitar el número máximo de eventos a obtener.
- ListView (lsCitas): campo donde mostraremos las citas de Google Calendar del período elegido.
- Button (btObtenerCitas): botón para obtener las citas del período elegido de Google Calendar.
- Button (btExportarCSV): botón para exportar las citas/eventos a fichero CSV separado por comas.
- En el TabControl para insertar la cita introduciremos los siguientes componentes:
- En el TabControl para mostrar los calendarios usaremos los siguientes componentes:
- Button (btObtenerCalendariosLista): botón para obtener todos los calendarios del usuario.
- CheckBox (opSoloPropietarioListaCalendarios): check para mostrar todos los calendarios del usuario o sólo los calendarios de los que sea propietario.
- ListView (lsListaCalendarios): lista para mostrar todos los calendarios.
- Otros componentes para añadir un nuevo calendario (TextBox, Button, CheckBox).
El código fuente source code más importante, validar en Google, insertar evento Google Calendar, obtener calendarios y citas, insertar calendario
A continuación mostramos los procedimientos y funciones más importantes de AjpdSoft Insertar Evento Google Calendar.
En primer lugar, para validar un usuario y contraseña de Google usaremos el siguiente código (correspondiente al botón «Probar validación» del formulario de la aplicación):
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 |
Private Sub btValidar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btValidar.Click Try System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor bePanel1.Text = "Validando credenciales en Google..." be.Refresh() 'Autenticación en Google con usuario y contraseña Dim servicioGoogle As New CalendarService("AjpdSoftCitaGoogleCalendar") Dim token As String servicioGoogle.setUserCredentials(txtUsuario.Text, txtContrasena.Text) token = servicioGoogle.QueryClientLoginToken() System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default MsgBox("Validación realizada correctamente con la " & _ "cuenta de Google indicada." & _ vbCrLf & vbCrLf + "Token: " & vbCrLf & token, MsgBoxStyle.Information + MsgBoxStyle.OkOnly) Catch ex As Exception System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default MsgBox("Se ha producido un error al intentar validar el usuario " & "y la contraseña en Google: " & _ vbCrLf & vbCrLf & ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation) End Try End Sub |
Para mostrar una lista de todos los calendarios dados de alta por el usuario de Google Calendar (correspondiente al botón «Calendarios» del formulario de la aplicación):
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 |
Private Sub btListaCalendarios_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btListaCalendarios.Click Dim titulo As String = "" Dim subtitulo As String = "" Try System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor bePanel1.Text = "Obteniendo lista de calendarios de Google Calendar..." be.Refresh() lsCalendarios.Items.Clear() obtenerCalendarios(opSoloPropietario.Checked) Dim i As Integer For i = 0 To calendariosT.Count - 1 lsCalendarios.Items.Add(calendariosT.Item(i).titulo) Next i If calendariosT.Count > 0 Then lsCalendarios.SelectedIndex = 0 End If bePanel1.Text = "Lista de calendarios obtenida correctamente" be.Refresh() System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default Catch ex As Exception bePanel1.Text = "Error al obtener lista de calendarios..." be.Refresh() System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default MsgBox("Se ha producido un error al intentar obtener la " & _ "lista de calendarios de Google Calendar: " & _ vbCrLf & vbCrLf & ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation) End Try End Sub |
El botón anterior usa el procedimiento «obtenerClanedarios» que mostramos a continuación:
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 |
'Obtiene los calendarios del usuario de Google Calendar Private Sub obtenerCalendarios(ByVal propietario As Boolean) Try 'Alta del servicio de Google y autenticación en Google Dim servicioGoogle As New CalendarService("AjpdSoftInsertarCitaGoogleCalendar") servicioGoogle.setUserCredentials(txtUsuario.Text, txtContrasena.Text) Dim consultaCalendar As CalendarQuery = New CalendarQuery() If propietario Then consultaCalendar.Uri = New Uri("https://www.google.com/calendar/feeds/default/owncalendars/full") Else consultaCalendar.Uri = New Uri("https://www.google.com/calendar/feeds/default/allcalendars/full") End If Dim resultadoFeed As CalendarFeed = servicioGoogle.Query(consultaCalendar) calendariosT.Clear() Dim creadoresCalendario As String Dim i As Integer For Each entradaActual As CalendarEntry In resultadoFeed.Entries Dim calendarios As New calendariosGoogleCalendar calendarios.titulo = entradaActual.Title.Text calendarios.uri = entradaActual.Id.AbsoluteUri.Substring(63) calendarios.descripcion = entradaActual.Summary.Text calendarios.soloLectura = resultadoFeed.ReadOnly creadoresCalendario = "" For i = 0 To resultadoFeed.Authors.Count - 1 If creadoresCalendario <> "" Then creadoresCalendario = creadoresCalendario & ", " & resultadoFeed.Authors.Item(i).Email Else creadoresCalendario = resultadoFeed.Authors.Item(i).Email End If Next calendarios.creadores = creadoresCalendario calendariosT.Add(calendarios) Next Catch ex As Exception MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation) End Try End Sub |
El código fuente source code VB.Net para insertar un evento o cita en Google Calendar (botón «Enviar evento»):
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 |
Private Sub btEnviar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btEnviar.Click If lsCalendarios.Text = "" Then MsgBox("Debe especificiar el calendario en el que se insertará el evento.", MsgBoxStyle.Information + MsgBoxStyle.OkOnly) lsCalendarios.Focus() Else Try System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor bePanel1.Text = "Enviando evento a Google Calendar..." be.Refresh() 'Alta del servicio de Google y autenticación en Google Dim servicioGoogle As New CalendarService("AjpdSoftInsertarCitaGoogleCalendar") servicioGoogle.setUserCredentials(txtUsuario.Text, txtContrasena.Text) Dim entradaCalendario As New EventEntry 'Asunto (título) del evento Google Calendar entradaCalendario.Title.Text = txtEvento.Text 'Descripción del evento Google Calendar entradaCalendario.Content.Content = txtDescripcion.Text 'Lugar del evento Google Calendar Dim ubicacionEvento = New Where() ubicacionEvento.ValueString = txtLugar.Text entradaCalendario.Locations.Add(ubicacionEvento) 'Fecha y hora inicio del evento, fecha y hora fin del evento Google Calendar Dim fechaInicioTxt As String = txtDesdeDia.Text & " " & txtDesdeHora.Text Dim fechaInicio As Date = Date.Parse(fechaInicioTxt, System.Globalization.CultureInfo.CurrentCulture) Dim fechaFinTxt As String = txtHastaDia.Text & " " & txtHastaHora.Text Dim fechaFin As Date = Date.Parse(fechaFinTxt, System.Globalization.CultureInfo.CurrentCulture) Dim desdeHastaCalendar As New [When](fechaInicio, fechaFin) entradaCalendario.Times.Add(desdeHastaCalendar) '** INICIO Activar tipo de Recordatorio Dim Recordatorio As New Reminder 'Unidad de tiempo (horas, minutos, días) If lsRecordatorioUnidadTiempo.Text = "minutos" Then Recordatorio.Minutes = CInt(txtRecordatorioTiempo.Text) End If If lsRecordatorioUnidadTiempo.Text = "horas" Then Recordatorio.Hours = CInt(txtRecordatorioTiempo.Text) End If If lsRecordatorioUnidadTiempo.Text = "días" Then Recordatorio.Days = CInt(txtRecordatorioTiempo.Text) End If 'tipo de recordatorio (SMS, correo electrónico, ventana emergente) If lsRecordatorio.Text = "SMS" Then Recordatorio.Method = Reminder.ReminderMethod.sms End If If lsRecordatorio.Text = "Correo electrónico" Then Recordatorio.Method = Reminder.ReminderMethod.email End If If lsRecordatorio.Text = "Ventana emergente" Then Recordatorio.Method = Reminder.ReminderMethod.alert End If entradaCalendario.Reminders.Add(Recordatorio) '** FIN Activar tipo de Recordatorio 'Inserta los invitados de la cita de Google Calendar If txtInvitados.Text <> "" Then Dim invintadosSeparados() As String Dim i As Integer invintadosSeparados = Split(txtInvitados.Text, ",") Dim invitado As Who For i = 0 To UBound(invintadosSeparados) invitado = New Who() invitado.Rel = Who.RelType.MESSAGE_TO invitado.Email = invintadosSeparados(i) entradaCalendario.Participants.Add(invitado) Next i End If 'Insertamos el evento creado en Google Calendar Dim uriDireccionGoogle As New Uri("https://www.google.com/calendar/feeds/" & calendariosT.Item(lsCalendarios.SelectedIndex).uri & "/private/full") Dim entradaEventoInsertar As AtomEntry = servicioGoogle.Insert(uriDireccionGoogle, entradaCalendario) MsgBox("Evento enviado correctamente a Google Calendar.", MsgBoxStyle.OkOnly + MsgBoxStyle.Information) bePanel1.Text = "Evento enviado correctamente a Google Calendar" be.Refresh() System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default Catch ex As Exception bePanel1.Text = "Error al enviar evento a Google Calendar..." be.Refresh() System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default MsgBox("Se ha producido un error al intentar insertar un " & _ "evento en Google Calendar: " & _ vbCrLf & vbCrLf & ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation) End Try End If End Sub |
El código fuente source code VB.Net para obtener las citas o eventos de Google Calendar (botón «Obtener citas») :
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 |
Private Sub btObtenerCitas_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btObtenerCitas.Click If lsCalendariosCitas.Text = "" Then MsgBox("Debe especificiar el calendario del que se obtendrán los eventos/citas.", MsgBoxStyle.Information + MsgBoxStyle.OkOnly) lsCalendariosCitas.Focus() Else Dim i As Integer System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor bePanel1.Text = "Obteniendo eventos/citas de Google Calendar..." be.Refresh() Try lsCitas.BeginUpdate() lsCitas.Columns.Clear() lsCitas.Items.Clear() lsCitas.View = View.Details lsCitas.Columns.Add(New ColHeader("Fecha inicio", 120, HorizontalAlignment.Left, True)) lsCitas.Columns.Add(New ColHeader("Fecha fin", 120, HorizontalAlignment.Left, True)) lsCitas.Columns.Add(New ColHeader("Asunto", 200, HorizontalAlignment.Left, True)) lsCitas.Columns.Add(New ColHeader("Lugar", 100, HorizontalAlignment.Left, True)) lsCitas.Columns.Add(New ColHeader("Descripción", 200, HorizontalAlignment.Left, True)) lsCitas.Columns.Add(New ColHeader("Participantes", 100, HorizontalAlignment.Left, True)) obtenerCitasGoogleCalendar(calendariosT.Item(lsCalendariosCitas.SelectedIndex).uri, txtNumeroMaximoCitas.Value) For i = 0 To citasT.Count - 1 Dim elementoLista As New ListViewItem elementoLista = New ListViewItem(CStr(citasT.Item(i).fechaInicio)) elementoLista.SubItems.Add(CStr(citasT.Item(i).fechaFin)) elementoLista.SubItems.Add(citasT.Item(i).titulo) elementoLista.SubItems.Add(citasT.Item(i).lugar) elementoLista.SubItems.Add(citasT.Item(i).contenido) elementoLista.SubItems.Add(citasT.Item(i).participantes) lsCitas.Items.Add(elementoLista) lInfoNumCitas.Text = "Obteniendo evento/cita: " & CStr(i + 1) lInfoNumCitas.Refresh() Next i lsCitas.EndUpdate() lInfoNumCitas.Text = "Número de citas/eventos: " & CStr(citasT.Count) lInfoNumCitas.Refresh() bePanel1.Text = "Obtenidas " & CStr(citasT.Count) & " citas" be.Refresh() System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default Catch ex As Exception bePanel1.Text = "Error al consultar citas/eventos de Google Calendar." be.Refresh() System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default MsgBox("Se ha producido un error al intentar obtener eventos de Google Calendar: " & _ vbCrLf & vbCrLf & ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation) End Try End If End |
El botón anterior usa el procedimiento obtenerCitasGoogleCalendar para obtener las citas en un array de structure, el procedimiento obtenerCitasGoogleCalendar:
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 |
'Obtiene las citas (eventos) del calendario indicado según el filtro indicado Private Sub obtenerCitasGoogleCalendar(ByVal calendario As String, ByVal numeroMaximoCitas As Integer) Dim lugarCita As String Dim participantesCita As String Dim i As Integer Try Dim servicioGoogle As Google.GData.Calendar.CalendarService = New Google.GData.Calendar.CalendarService("AjpdSoftInsertarCitaGoogleCalendar") servicioGoogle.setUserCredentials(txtUsuario.Text, txtContrasena.Text) Dim consultaCalendar As Google.GData.Calendar.EventQuery = New Google.GData.Calendar.EventQuery() ' consultaCalendar.Uri = New Uri("http://www.google.com/calendar/feeds/" + ' servicioGoogle.Credentials.Username + ' "/private/full?max-results=1000") 'Insertamos el evento creado en Google Calendar consultaCalendar.Uri = New Uri("https://www.google.com/calendar/feeds/" & calendario & "/private/full?max-results=" & CStr(numeroMaximoCitas)) consultaCalendar.StartTime = txtCitasDesde.Value consultaCalendar.EndTime = txtCitasHasta.Value Dim entradaFeed As Google.GData.Calendar.EventEntry Dim calendarioFeed As Google.GData.Calendar.EventFeed = servicioGoogle.Query(consultaCalendar) citasT.Clear() For Each entradaFeed In calendarioFeed.Entries Dim fechaEvento As New [When](entradaFeed.Times(0).StartTime, entradaFeed.Times(0).EndTime) Dim citasGoogle As New citasGoogleCalendar citasGoogle.contenido = entradaFeed.Content.Content citasGoogle.titulo = entradaFeed.Title.Text citasGoogle.fechaInicio = fechaEvento.StartTime citasGoogle.fechaFin = fechaEvento.EndTime lugarCita = "" For i = 0 To entradaFeed.Locations.Count - 1 If lugarCita <> "" Then lugarCita = lugarCita & ", " & entradaFeed.Locations.Item(i).ValueString Else lugarCita = entradaFeed.Locations.Item(i).ValueString End If Next citasGoogle.lugar = lugarCita participantesCita = "" For i = 0 To entradaFeed.Participants.Count - 1 If participantesCita <> "" Then participantesCita = participantesCita & ", " & entradaFeed.Participants.Item(i).ValueString Else participantesCita = entradaFeed.Participants.Item(i).ValueString End If Next citasGoogle.participantes = participantesCita citasT.Add(citasGoogle) Next Catch ex As Exception MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation) End Try End Sub |
El código fuente source code en VB .Net para exportar las citas del ListView a un fichero de texto plano con formato CSV (botón «Exportar citas a fichero CSV»):
1 2 3 4 5 6 7 8 9 10 11 12 |
Private Sub btExportarCSV_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btExportarCSV.Click dlGuardar.Filter = "Archivos CSV (*.csv)|*.csv|Todos los archivos (*.*)|*.*" dlGuardar.FilterIndex = 1 dlGuardar.DefaultExt = "csv" dlGuardar.FileName = "Eventos google calendar" dlGuardar.OverwritePrompt = True dlGuardar.Title = "Guardar eventos Google Calendar" If dlGuardar.ShowDialog Then exportarListViewCSV(lsCitas, dlGuardar.FileName) End If End Sub |
El botón anterior usa el procedimiento exportarListViewCSV para realizar la exportación:
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 |
'Exportar contenido ListView a formato CSV 'para abrir con Microsoft Office Excel, OppenOffice Calc o con Private Sub exportarListViewCSV(ByVal lstview As ListView, ByVal ficheroCSV As String) Dim lineasCSV As New System.Text.StringBuilder Dim lineaActual As String = String.Empty 'Escribir nombre de columnas y encabezados en la variable temporal For columnIndex As Int32 = 0 To lstview.Columns.Count - 1 lineaActual &= (String.Format(Chr(34) & "{0}" & Chr(34) & ";", lstview.Columns(columnIndex).Text)) Next 'Quitar la coma final lineasCSV.AppendLine(lineaActual.Substring(0, lineaActual.Length - 1)) lineaActual = String.Empty 'Escribir los datos del ListView en la variable temporal For Each item As ListViewItem In lstview.Items For Each subItem As ListViewItem.ListViewSubItem In item.SubItems lineaActual &= (String.Format(Chr(34) & "{0}" & Chr(34) & ";", subItem.Text)) Next 'Quitar coma final lineasCSV.AppendLine(lineaActual.Substring(0, lineaActual.Length - 1)) lineaActual = String.Empty Next 'Guardar datos variable temporal a fichero CSV Dim Sys As New System.IO.StreamWriter(ficheroCSV) Sys.WriteLine(lineasCSV.ToString) Sys.Flush() Sys.Dispose() End Sub |
El código fuente en Visual Basic .Net para obtener los calendarios del usuario de Google Calendar (botón «Obtener calendarios») :
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 |
Private Sub btObtenerCalendariosLista_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btObtenerCalendariosLista.Click Try System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor bePanel1.Text = "Obteniendo lista de calendarios de Google Calendar..." be.Refresh() lsListaCalendarios.Items.Clear() obtenerCalendarios(opSoloPropietarioListaCalendarios.Checked) lsListaCalendarios.BeginUpdate() lsListaCalendarios.Columns.Clear() lsListaCalendarios.Items.Clear() lsListaCalendarios.View = View.Details lsListaCalendarios.Columns.Add(New ColHeader("Título", 200, HorizontalAlignment.Left, True)) lsListaCalendarios.Columns.Add(New ColHeader("Descripción", 200, HorizontalAlignment.Left, True)) lsListaCalendarios.Columns.Add(New ColHeader("Creadores/Autores", 200, HorizontalAlignment.Left, True)) lsListaCalendarios.Columns.Add(New ColHeader("ID", 150, HorizontalAlignment.Left, True)) lsListaCalendarios.Columns.Add(New ColHeader("Sólo lectura", 100, HorizontalAlignment.Left, True)) Dim i As Integer For i = 0 To calendariosT.Count - 1 Dim elementoLista As New ListViewItem elementoLista = New ListViewItem(CStr(calendariosT.Item(i).titulo)) elementoLista.SubItems.Add(CStr(calendariosT.Item(i).descripcion)) elementoLista.SubItems.Add(CStr(calendariosT.Item(i).creadores)) elementoLista.SubItems.Add(calendariosT.Item(i).uri) elementoLista.SubItems.Add(CStr(calendariosT.Item(i).soloLectura)) lsListaCalendarios.Items.Add(elementoLista) Next i lsListaCalendarios.EndUpdate() bePanel1.Text = "Lista de calendarios obtenida correctamente" be.Refresh() System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default Catch ex As Exception bePanel1.Text = "Error al obtener lista de calendarios..." be.Refresh() System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default MsgBox("Se ha producido un error al intentar obtener la " & _ "lista de calendarios de Google Calendar: " & _ vbCrLf & vbCrLf & ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation) End Try End Sub |
El botón anterior usa el procedimiento «obtenerClanedarios» que ya hemos listado anteriormente.
Existen otros procedimientos aunque no tienen que ver con Google Calendar, como son:
Guardar datos de configuración en fichero INI:
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 |
Private Sub guardarDatosINI() Try Dim objFicherosINI As New FicherosINI( Path.Combine(Application.StartupPath, "configuracion.ini")) Dim objCifrarRSA As New encriptacionRSA() Dim ficheroDescripcion As String objFicherosINI.WriteString("Validación", "Usuario", txtUsuario.Text) objFicherosINI.WriteBoolean("Validación", "Guardar contraseña", opRecordarContrasena.Checked) objFicherosINI.WriteString("Evento", "Asunto", txtEvento.Text) objFicherosINI.WriteString("Evento", "Lugar", txtLugar.Text) objFicherosINI.WriteString("Evento", "Recordatorio - Tiempo", txtRecordatorioTiempo.Text) objFicherosINI.WriteString("Evento", "Recordatorio - Tipo", lsRecordatorio.Text) objFicherosINI.WriteString("Evento", "Recordatorio - Unidad", lsRecordatorioUnidadTiempo.Text) objFicherosINI.WriteString("Calendario", "Calendario actual", lsCalendarios.Text) objFicherosINI.WriteBoolean("Calendario", "Sólo propietario", opSoloPropietario.Checked) objFicherosINI.WriteString("Evento", "Invitados", txtInvitados.Text) If opRecordarContrasena.Checked = True Then ' Cifrar/Encriptar la contraseña y guardarla en el INI objFicherosINI.WriteString("Validación", "Contraseña", Trim(objCifrarRSA.encriptar128BitRijndael(txtContrasena.Text, "clave_ajpdsoft"))) Else objFicherosINI.WriteString("Validación", "Contraseña", "") End If 'Guardar descripción en fichero ficheroDescripcion = Path.Combine(Application.StartupPath, "descripcion.txt") Dim fichero As New StreamWriter(ficheroDescripcion) fichero.WriteLine(txtDescripcion.Text) fichero.Close() Catch ex As Exception MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation) End Try End Sub |
Y la clase «FicherosINI»:
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 |
Public Class FicherosINI ' Funciones del API de Windows para ficheros INI Private Declare Ansi Function GetPrivateProfileString _ Lib "kernel32.dll" Alias "GetPrivateProfileStringA" _ (ByVal lpApplicationName As String, _ ByVal lpKeyName As String, ByVal lpDefault As String, _ ByVal lpReturnedString As System.Text.StringBuilder, _ ByVal nSize As Integer, ByVal lpFileName As String) _ As Integer Private Declare Ansi Function WritePrivateProfileString _ Lib "kernel32.dll" Alias "WritePrivateProfileStringA" _ (ByVal lpApplicationName As String, _ ByVal lpKeyName As String, ByVal lpString As String, _ ByVal lpFileName As String) As Integer Private Declare Ansi Function GetPrivateProfileInt _ Lib "kernel32.dll" Alias "GetPrivateProfileIntA" _ (ByVal lpApplicationName As String, _ ByVal lpKeyName As String, ByVal nDefault As Integer, _ ByVal lpFileName As String) As Integer Private Declare Ansi Function FlushPrivateProfileString _ Lib "kernel32.dll" Alias "WritePrivateProfileStringA" _ (ByVal lpApplicationName As Integer, _ ByVal lpKeyName As Integer, ByVal lpString As Integer, _ ByVal lpFileName As String) As Integer Dim strFilename As String ' Constructor, para aceptar el fichero INI Public Sub New(ByVal Filename As String) strFilename = Filename End Sub 'Propiedad sólo lectura con nombre de fichero ReadOnly Property FileName() As String Get Return strFilename End Get End Property 'Función para leer cadena de texto (string) de fichero INI Public Function GetString(ByVal Section As String, _ ByVal Key As String, ByVal [Default] As String) As String Dim intCharCount As Integer Dim objResult As New System.Text.StringBuilder(256) intCharCount = GetPrivateProfileString(Section, Key, _ [Default], objResult, objResult.Capacity, strFilename) If intCharCount > 0 Then GetString = Left(objResult.ToString, intCharCount) Else GetString = "" End If End Function 'Función para leer un valor numérico del fichero INI Public Function GetInteger(ByVal Section As String, _ ByVal Key As String, ByVal [Default] As Integer) As Integer Return GetPrivateProfileInt(Section, Key, _ [Default], strFilename) End Function 'Función para leer un valor booleano de fichero INI Public Function GetBoolean(ByVal Section As String, _ ByVal Key As String, ByVal [Default] As Boolean) As Boolean Return (GetPrivateProfileInt(Section, Key, _ CInt([Default]), strFilename) = 1) End Function 'Función para escribir valor de cadena (string) en fichero INI Public Sub WriteString(ByVal Section As String, _ ByVal Key As String, ByVal Value As String) WritePrivateProfileString(Section, Key, Value, strFilename) Flush() End Sub 'Función para escribir valor numérico en fichero INI Public Sub WriteInteger(ByVal Section As String, _ ByVal Key As String, ByVal Value As Integer) ' Writes an integer to your INI file WriteString(Section, Key, CStr(Value)) Flush() End Sub 'Función para escribir valor booleano en fichero INI Public Sub WriteBoolean(ByVal Section As String, _ ByVal Key As String, ByVal Value As Boolean) ' Writes a boolean to your INI file WriteString(Section, Key, CStr(Math.Abs(CInt(Value)))) Flush() End Sub 'Guarda los cambios de la caché en fichero INI Private Sub Flush() FlushPrivateProfileString(0, 0, 0, strFilename) End Sub End Class |
Para la encriptación de la contraseña del usuario (si decide guardarla):
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 |
Public Class encriptacionRSA Public Function encriptar128BitRijndael( ByVal textoEncriptar As String, ByVal claveEncriptacion As String) As String Dim bytValue() As Byte Dim bytKey() As Byte Dim bytEncoded() As Byte = New Byte() {} Dim bytIV() As Byte = {121, 241, 10, 1, 132, 74, 11, 39, 255, 91, 45, 78, 14, 211, 22, 62} Dim intLength As Integer Dim intRemaining As Integer Dim objMemoryStream As New MemoryStream() Dim objCryptoStream As CryptoStream Dim objRijndaelManaged As RijndaelManaged 'Quitar nulos en cadena de texto a encriptar textoEncriptar = quitarNullCadena(textoEncriptar) If textoEncriptar = "" Then Return "" End If bytValue = Encoding.ASCII.GetBytes(textoEncriptar.ToCharArray) intLength = Len(claveEncriptacion) 'La clave de cifrado debe ser de 256 bits de longitud (32 bytes) 'Si tiene más de 32 bytes se truncará 'Si es menor de 32 bytes se rellenará con X If intLength >= 32 Then claveEncriptacion = Strings.Left(claveEncriptacion, 32) Else intLength = Len(claveEncriptacion) intRemaining = 32 - intLength claveEncriptacion = claveEncriptacion & Strings.StrDup(intRemaining, "X") End If bytKey = Encoding.ASCII.GetBytes(claveEncriptacion.ToCharArray) objRijndaelManaged = New RijndaelManaged() Try 'Crear objeto Encryptor y escribir su valor 'después de que se convierta en array de bytes objCryptoStream = New CryptoStream(objMemoryStream, _ objRijndaelManaged.CreateEncryptor(bytKey, bytIV), _ CryptoStreamMode.Write) objCryptoStream.Write(bytValue, 0, bytValue.Length) objCryptoStream.FlushFinalBlock() bytEncoded = objMemoryStream.ToArray objMemoryStream.Close() objCryptoStream.Close() Catch ex As Exception MsgBox("Error al encriptar cadena de texto: " & ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation) End Try 'Devolver el valor del texto encriptado 'convertido de array de bytes a texto en base64 Return Convert.ToBase64String(bytEncoded) End Function Public Function desencriptar128BitRijndael( ByVal textoEncriptado As String, ByVal claveDesencriptacion As String) As String Dim bytDataToBeDecrypted() As Byte Dim bytTemp() As Byte Dim bytIV() As Byte = {121, 241, 10, 1, 132, 74, 11, 39, 255, 91, 45, 78, 14, 211, 22, 62} Dim objRijndaelManaged As New RijndaelManaged() Dim objMemoryStream As MemoryStream Dim objCryptoStream As CryptoStream Dim bytDecryptionKey() As Byte Dim intLength As Integer Dim intRemaining As Integer Dim strReturnString As String = String.Empty If textoEncriptado = "" Then Return "" End If 'Convertir el valor encriptado base64 a array de bytes bytDataToBeDecrypted = Convert.FromBase64String(textoEncriptado) 'La clave de desencriptación debe ser de 256 bits de longitud (32 bytes) 'Si tiene más de 32 bytes se truncará 'Si es menor de 32 bytes se rellenará con A intLength = Len(claveDesencriptacion) If intLength >= 32 Then claveDesencriptacion = Strings.Left(claveDesencriptacion, 32) Else intLength = Len(claveDesencriptacion) intRemaining = 32 - intLength claveDesencriptacion = claveDesencriptacion & Strings.StrDup(intRemaining, "X") End If bytDecryptionKey = Encoding.ASCII.GetBytes(claveDesencriptacion.ToCharArray) ReDim bytTemp(bytDataToBeDecrypted.Length) objMemoryStream = New MemoryStream(bytDataToBeDecrypted) Try 'Crear objeto Dencryptor y escribir su valor 'después de que se convierta en array de bytes objCryptoStream = New CryptoStream(objMemoryStream, _ objRijndaelManaged.CreateDecryptor(bytDecryptionKey, bytIV), _ CryptoStreamMode.Read) objCryptoStream.Read(bytTemp, 0, bytTemp.Length) 'objCryptoStream.FlushFinalBlock() objMemoryStream.Close() objCryptoStream.Close() Catch ex As Exception MsgBox("Error al desencriptar cadena de texto: " & ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation) End Try 'Devolver la cadena de texto desencriptada 'convertida de array de bytes a cadena de texto ASCII Return quitarNullCadena(Encoding.ASCII.GetString(bytTemp)) End Function 'Quita nulos de una cadena de texto Public Function quitarNullCadena( ByVal texto As String) As String Dim posicionNull As Integer Dim textoSinNull As String posicionNull = 1 textoSinNull = texto Do While posicionNull > 0 posicionNull = InStr(posicionNull, texto, vbNullChar) If posicionNull > 0 Then textoSinNull = Left$(textoSinNull, posicionNull - 1) & _ Right$(textoSinNull, Len(textoSinNull) - posicionNull) End If If posicionNull > textoSinNull.Length Then Exit Do End If Loop Return textoSinNull End Function End Class |
AjpdSoft Insertar Evento Google Calendar
Si eres desarrollador de software y quieres descargar gratuitamente el código fuente source code completo en Microsoft Visual Basic .Net (Microsoft Visual Studio 2010) sólo tendrás que registrarte en nuestra web (de forma completamente gratuita) y acceder a la descarga:
A continuación os mostramos la aplicación en funcionamiento:
En primer lugar introduciremos usuario y contraseña de nuestra cuenta de Google, si queremos comprobar si los datos son correctos pulsaremos «Probar validación»:
Si el usuario y contraseña pertenecen a una cuenta de Google mostrará el siguiente mensaje indicando «Validación realizada correctamente con la cuenta de Google indicada. Token …»:
Para insertar o añadir un nuevo evento en un calendario del usuario, en primer lugar pulsaremos en el botón «Calendarios» en la pestaña «Insertar cita» para obtener la lista de todos los calendarios del usuario, a continuación seleccionaremos el calendario en el que queramos insertar el evento, introduciremos los datos (fecha desde, fecha hasta, evento, lugar, descripción, tipo de recordatorio, invitados y pulsaremos «Enviar evento»:
Si todo es correcto la aplicación mostrará el mensaje «Evento enviado correctamente a Google Calendar»:
Ahora podremos comprobar que, efectivamente, el evento ha sido añadido abriendo un navegador web y accediendo a nuestra cuenta de Google Calendar (Gmail):
Pulsando en el evento podremos ver todos los datos insertados con nuestra aplicación:
Desde la pestaña «Mostrar citas» podremos consultar todas las citas o eventos de cualquier calendario de nuestro usuario de Google Calendar, podremos acotar el resultado seleccionando una fecha desde y una fecha hasta. Como en la ventana de inserción de cita, en este caso también pulsaremos en «Calendarios» para obtener la lista de los calendarios del usuario, seleccionaremos el calendario del que queramos consultar los eventos, la fecha desde, fecha hasta y número máximo de eventos a consultar y pulsaremos en «Obtener citas». Si todo es correcto la aplicación obtendrá todos los eventos entre las fechas indicadas del calendario seleccionado: fecha de inicio, fecha de fin, asunto, lugar, descripción y participantes (invitados):
Además, en la ventana anterior, permite exportar las citas/eventos obtenidos a un fichero de texto CSV, para ello será suficiente con pulsar en el botón «Exportar citas a fichero CSV».
Desde la pestaña «Calendarios» podremos obtener la lista de todos los calendarios del usuario de Google Calendar e insertar un nuevo calendario:
Anexo
- Código fuente source code completo en Microsoft Visual Basic .Net 2010 VB.Net (fichero «formEnviarCitaCalendar.vb«):
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 |
Imports Google.GData.Calendar Imports Google.GData.Client Imports Google.GData.Extensions Imports System.IO Public Class formEnviarCitaCalendar 'Para obtener las citas de un calendario Google Calendar Public Structure citasGoogleCalendar Public id As String Public titulo As String Public fechaInicio As Date Public fechaFin As Date Public contenido As String Public lugar As String Public participantes As String End Structure Dim citasT As New List(Of citasGoogleCalendar) 'Para obtener los calendarios de Google Calendar Public Structure calendariosGoogleCalendar Public titulo As String Public uri As String Public descripcion As String Public soloLectura As Boolean Public creadores As String End Structure Dim calendariosT As New List(Of calendariosGoogleCalendar) ' Clase ColHeader es un objeto ColumnHeader con una propiedad ' adicional para determinar un orden ascendente o descendente ' True especifica orden ascendente, false descendente Public Class ColHeader Inherits ColumnHeader Public ascending As Boolean Public Sub New(ByVal [text] As String, ByVal width As Integer, ByVal align As HorizontalAlignment, ByVal asc As Boolean) Me.Text = [text] Me.Width = width Me.TextAlign = align Me.ascending = asc End Sub End Class 'Exportar contenido ListView a formato CSV 'para abrir con Microsoft Office Excel, OppenOffice Calc o con Private Sub exportarListViewCSV(ByVal lstview As ListView, ByVal ficheroCSV As String) Dim lineasCSV As New System.Text.StringBuilder Dim lineaActual As String = String.Empty 'Escribir nombre de columnas y encabezados en la variable temporal For columnIndex As Int32 = 0 To lstview.Columns.Count - 1 lineaActual &= (String.Format(Chr(34) & "{0}" & Chr(34) & ";", lstview.Columns(columnIndex).Text)) Next 'Quitar la coma final lineasCSV.AppendLine(lineaActual.Substring(0, lineaActual.Length - 1)) lineaActual = String.Empty 'Escribir los datos del ListView en la variable temporal For Each item As ListViewItem In lstview.Items For Each subItem As ListViewItem.ListViewSubItem In item.SubItems lineaActual &= (String.Format(Chr(34) & "{0}" & Chr(34) & ";", subItem.Text)) Next 'Quitar coma final lineasCSV.AppendLine(lineaActual.Substring(0, lineaActual.Length - 1)) lineaActual = String.Empty Next 'Guardar datos variable temporal a fichero CSV Dim Sys As New System.IO.StreamWriter(ficheroCSV) Sys.WriteLine(lineasCSV.ToString) Sys.Flush() Sys.Dispose() End Sub Private Sub btValidar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btValidar.Click Try System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor bePanel1.Text = "Validando credenciales en Google..." be.Refresh() 'Autenticación en Google con usuario y contraseña Dim servicioGoogle As New CalendarService("AjpdSoftCitaGoogleCalendar") Dim token As String servicioGoogle.setUserCredentials(txtUsuario.Text, txtContrasena.Text) token = servicioGoogle.QueryClientLoginToken() System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default MsgBox("Validación realizada correctamente con la " & _ "cuenta de Google indicada." & _ vbCrLf & vbCrLf + "Token: " & vbCrLf & token, MsgBoxStyle.Information + MsgBoxStyle.OkOnly) Catch ex As Exception System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default MsgBox("Se ha producido un error al intentar validar el usuario " & "y la contraseña en Google: " & _ vbCrLf & vbCrLf & ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation) End Try End Sub Function obtenerHoraMinuto(ByVal fecha As Date) As String Dim horaMinuto As String = "00:00" Dim hora As String = "00" Dim minuto As String = "00" If Len(Trim(Str(fecha.Hour))) = 1 Then hora = "0" & fecha.Hour Else hora = fecha.Hour End If If Len(Trim(Str(fecha.Minute))) = 1 Then minuto = "0" & fecha.Minute Else minuto = fecha.Minute End If horaMinuto = hora & ":" & minuto obtenerHoraMinuto = horaMinuto End Function Private Sub guardarDatosINI() Try Dim objFicherosINI As New FicherosINI( Path.Combine(Application.StartupPath, "configuracion.ini")) Dim objCifrarRSA As New encriptacionRSA() Dim ficheroDescripcion As String objFicherosINI.WriteString("Validación", "Usuario", txtUsuario.Text) objFicherosINI.WriteBoolean("Validación", "Guardar contraseña", opRecordarContrasena.Checked) objFicherosINI.WriteString("Evento", "Asunto", txtEvento.Text) objFicherosINI.WriteString("Evento", "Lugar", txtLugar.Text) objFicherosINI.WriteString("Evento", "Recordatorio - Tiempo", txtRecordatorioTiempo.Text) objFicherosINI.WriteString("Evento", "Recordatorio - Tipo", lsRecordatorio.Text) objFicherosINI.WriteString("Evento", "Recordatorio - Unidad", lsRecordatorioUnidadTiempo.Text) objFicherosINI.WriteString("Calendario", "Calendario actual", lsCalendarios.Text) objFicherosINI.WriteBoolean("Calendario", "Sólo propietario", opSoloPropietario.Checked) objFicherosINI.WriteString("Evento", "Invitados", txtInvitados.Text) If opRecordarContrasena.Checked = True Then ' Cifrar/Encriptar la contraseña y guardarla en el INI objFicherosINI.WriteString("Validación", "Contraseña", Trim(objCifrarRSA.encriptar128BitRijndael(txtContrasena.Text, "clave_ajpdsoft"))) Else objFicherosINI.WriteString("Validación", "Contraseña", "") End If 'Guardar descripción en fichero ficheroDescripcion = Path.Combine(Application.StartupPath, "descripcion.txt") Dim fichero As New StreamWriter(ficheroDescripcion) fichero.WriteLine(txtDescripcion.Text) fichero.Close() Catch ex As Exception MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation) End Try End Sub Private Sub formEnviarCitaCalendar_Load( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim objFicherosINI As New FicherosINI( Path.Combine(Application.StartupPath, "configuracion.ini")) Dim objCifrarRSA As New encriptacionRSA() Dim fecha As Date = Now() Dim ficheroDescripcion As String Dim calendarioActual As String Try 'Establecemos la fecha y hora de inicio y de fin fecha = DateTime.Now txtDesdeDia.Value = fecha txtHastaDia.Value = fecha txtDesdeHora.Text = obtenerHoraMinuto(fecha) fecha = fecha.AddMinutes(30) txtHastaHora.Text = obtenerHoraMinuto(fecha) 'Cargamos los valores del fichero de configuracion.ini opRecordarContrasena.Checked = objFicherosINI.GetBoolean("Validación", "Guardar contraseña", False) txtUsuario.Text = objFicherosINI.GetString("Validación", "Usuario", "") txtEvento.Text = objFicherosINI.GetString("Evento", "Asunto", "") txtLugar.Text = objFicherosINI.GetString("Evento", "Lugar", "") txtRecordatorioTiempo.Text = objFicherosINI.GetString("Evento", "Recordatorio - Tiempo", "") lsRecordatorio.Text = objFicherosINI.GetString("Evento", "Recordatorio - Tipo", "") lsRecordatorioUnidadTiempo.Text = objFicherosINI.GetString("Evento", "Recordatorio - Unidad", "") txtInvitados.Text = objFicherosINI.GetString("Evento", "Invitados", "") calendarioActual = objFicherosINI.GetString("Calendario", "Calendario actual", "") lsCalendarios.Items.Add(calendarioActual) lsCalendarios.Text = calendarioActual opSoloPropietario.Checked = objFicherosINI.GetBoolean("Calendario", "Sólo propietario", False) opRecordarContrasena.Checked = objFicherosINI.GetBoolean("Validación", "Guardar contraseña", False) 'Desencriptar/descifrar la contraseña y mostrarla txtContrasena.Text = objCifrarRSA.desencriptar128BitRijndael( objFicherosINI.GetString("Validación", "Contraseña", ""), "clave_ajpdsoft") ficheroDescripcion = Path.Combine(Application.StartupPath, "descripcion.txt") If File.Exists(ficheroDescripcion) = True Then Dim Reader As StreamReader = File.OpenText(ficheroDescripcion) Dim fichero As String = Reader.ReadToEnd() Reader.Close() txtDescripcion.Text = fichero End If Catch ex As Exception MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation) End Try End Sub Private Sub btSalinSinGuardar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) End End Sub Private Sub ValidarUsuarioToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) btValidar_Click(sender, e) End Sub Private Sub ObtenerCalendariosToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) btListaCalendarios_Click(sender, e) End Sub Private Sub EnviarEventocitaToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) btEnviar_Click(sender, e) End Sub Private Sub LimpiarDatosActualesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) btLimpiar_Click(sender, e) End Sub Private Sub SalirYGuardarDatosToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) btSalir_Click(sender, e) End Sub 'Obtiene los calendarios del usuario de Google Calendar Private Sub obtenerCalendarios(ByVal propietario As Boolean) Try 'Alta del servicio de Google y autenticación en Google Dim servicioGoogle As New CalendarService("AjpdSoftInsertarCitaGoogleCalendar") servicioGoogle.setUserCredentials(txtUsuario.Text, txtContrasena.Text) Dim consultaCalendar As CalendarQuery = New CalendarQuery() If propietario Then consultaCalendar.Uri = New Uri("https://www.google.com/calendar/feeds/default/owncalendars/full") Else consultaCalendar.Uri = New Uri("https://www.google.com/calendar/feeds/default/allcalendars/full") End If Dim resultadoFeed As CalendarFeed = servicioGoogle.Query(consultaCalendar) calendariosT.Clear() Dim creadoresCalendario As String Dim i As Integer For Each entradaActual As CalendarEntry In resultadoFeed.Entries Dim calendarios As New calendariosGoogleCalendar calendarios.titulo = entradaActual.Title.Text calendarios.uri = entradaActual.Id.AbsoluteUri.Substring(63) calendarios.descripcion = entradaActual.Summary.Text calendarios.soloLectura = resultadoFeed.ReadOnly creadoresCalendario = "" For i = 0 To resultadoFeed.Authors.Count - 1 If creadoresCalendario <> "" Then creadoresCalendario = creadoresCalendario & ", " & resultadoFeed.Authors.Item(i).Email Else creadoresCalendario = resultadoFeed.Authors.Item(i).Email End If Next calendarios.creadores = creadoresCalendario calendariosT.Add(calendarios) Next Catch ex As Exception MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation) End Try End Sub 'Obtiene las citas (eventos) del calendario indicado según el filtro indicado Private Sub obtenerCitasGoogleCalendar(ByVal calendario As String, ByVal numeroMaximoCitas As Integer) Dim lugarCita As String Dim participantesCita As String Dim i As Integer Try Dim servicioGoogle As Google.GData.Calendar.CalendarService = New Google.GData.Calendar.CalendarService("AjpdSoftInsertarCitaGoogleCalendar") servicioGoogle.setUserCredentials(txtUsuario.Text, txtContrasena.Text) Dim consultaCalendar As Google.GData.Calendar.EventQuery = New Google.GData.Calendar.EventQuery() ' consultaCalendar.Uri = New Uri("http://www.google.com/calendar/feeds/" + ' servicioGoogle.Credentials.Username + ' "/private/full?max-results=1000") 'Insertamos el evento creado en Google Calendar consultaCalendar.Uri = New Uri("https://www.google.com/calendar/feeds/" & calendario & "/private/full?max-results=" & CStr(numeroMaximoCitas)) consultaCalendar.StartTime = txtCitasDesde.Value consultaCalendar.EndTime = txtCitasHasta.Value Dim entradaFeed As Google.GData.Calendar.EventEntry Dim calendarioFeed As Google.GData.Calendar.EventFeed = servicioGoogle.Query(consultaCalendar) citasT.Clear() For Each entradaFeed In calendarioFeed.Entries Dim fechaEvento As New [When](entradaFeed.Times(0).StartTime, entradaFeed.Times(0).EndTime) Dim citasGoogle As New citasGoogleCalendar citasGoogle.contenido = entradaFeed.Content.Content citasGoogle.titulo = entradaFeed.Title.Text citasGoogle.fechaInicio = fechaEvento.StartTime citasGoogle.fechaFin = fechaEvento.EndTime lugarCita = "" For i = 0 To entradaFeed.Locations.Count - 1 If lugarCita <> "" Then lugarCita = lugarCita & ", " & entradaFeed.Locations.Item(i).ValueString Else lugarCita = entradaFeed.Locations.Item(i).ValueString End If Next citasGoogle.lugar = lugarCita participantesCita = "" For i = 0 To entradaFeed.Participants.Count - 1 If participantesCita <> "" Then participantesCita = participantesCita & ", " & entradaFeed.Participants.Item(i).ValueString Else participantesCita = entradaFeed.Participants.Item(i).ValueString End If Next citasGoogle.participantes = participantesCita citasT.Add(citasGoogle) Next Catch ex As Exception MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation) End Try End Sub Private Sub btObtenerCitas_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btObtenerCitas.Click If lsCalendariosCitas.Text = "" Then MsgBox("Debe especificiar el calendario del que se obtendrán los eventos/citas.", MsgBoxStyle.Information + MsgBoxStyle.OkOnly) lsCalendariosCitas.Focus() Else Dim i As Integer System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor bePanel1.Text = "Obteniendo eventos/citas de Google Calendar..." be.Refresh() Try lsCitas.BeginUpdate() lsCitas.Columns.Clear() lsCitas.Items.Clear() lsCitas.View = View.Details lsCitas.Columns.Add(New ColHeader("Fecha inicio", 120, HorizontalAlignment.Left, True)) lsCitas.Columns.Add(New ColHeader("Fecha fin", 120, HorizontalAlignment.Left, True)) lsCitas.Columns.Add(New ColHeader("Asunto", 200, HorizontalAlignment.Left, True)) lsCitas.Columns.Add(New ColHeader("Lugar", 100, HorizontalAlignment.Left, True)) lsCitas.Columns.Add(New ColHeader("Descripción", 200, HorizontalAlignment.Left, True)) lsCitas.Columns.Add(New ColHeader("Participantes", 100, HorizontalAlignment.Left, True)) obtenerCitasGoogleCalendar(calendariosT.Item(lsCalendariosCitas.SelectedIndex).uri, txtNumeroMaximoCitas.Value) For i = 0 To citasT.Count - 1 Dim elementoLista As New ListViewItem elementoLista = New ListViewItem(CStr(citasT.Item(i).fechaInicio)) elementoLista.SubItems.Add(CStr(citasT.Item(i).fechaFin)) elementoLista.SubItems.Add(citasT.Item(i).titulo) elementoLista.SubItems.Add(citasT.Item(i).lugar) elementoLista.SubItems.Add(citasT.Item(i).contenido) elementoLista.SubItems.Add(citasT.Item(i).participantes) lsCitas.Items.Add(elementoLista) lInfoNumCitas.Text = "Obteniendo evento/cita: " & CStr(i + 1) lInfoNumCitas.Refresh() Next i lsCitas.EndUpdate() lInfoNumCitas.Text = "Número de citas/eventos: " & CStr(citasT.Count) lInfoNumCitas.Refresh() bePanel1.Text = "Obtenidas " & CStr(citasT.Count) & " citas" be.Refresh() System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default Catch ex As Exception bePanel1.Text = "Error al consultar citas/eventos de Google Calendar." be.Refresh() System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default MsgBox("Se ha producido un error al intentar obtener eventos de Google Calendar: " & _ vbCrLf & vbCrLf & ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation) End Try End If End Sub Private Sub btEnviar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btEnviar.Click If lsCalendarios.Text = "" Then MsgBox("Debe especificiar el calendario en el que se insertará el evento.", MsgBoxStyle.Information + MsgBoxStyle.OkOnly) lsCalendarios.Focus() Else Try System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor bePanel1.Text = "Enviando evento a Google Calendar..." be.Refresh() 'Alta del servicio de Google y autenticación en Google Dim servicioGoogle As New CalendarService("AjpdSoftInsertarCitaGoogleCalendar") servicioGoogle.setUserCredentials(txtUsuario.Text, txtContrasena.Text) Dim entradaCalendario As New EventEntry 'Asunto (título) del evento Google Calendar entradaCalendario.Title.Text = txtEvento.Text 'Descripción del evento Google Calendar entradaCalendario.Content.Content = txtDescripcion.Text 'Lugar del evento Google Calendar Dim ubicacionEvento = New Where() ubicacionEvento.ValueString = txtLugar.Text entradaCalendario.Locations.Add(ubicacionEvento) 'Fecha y hora inicio del evento, fecha y hora fin del evento Google Calendar Dim fechaInicioTxt As String = txtDesdeDia.Text & " " & txtDesdeHora.Text Dim fechaInicio As Date = Date.Parse(fechaInicioTxt, System.Globalization.CultureInfo.CurrentCulture) Dim fechaFinTxt As String = txtHastaDia.Text & " " & txtHastaHora.Text Dim fechaFin As Date = Date.Parse(fechaFinTxt, System.Globalization.CultureInfo.CurrentCulture) Dim desdeHastaCalendar As New [When](fechaInicio, fechaFin) entradaCalendario.Times.Add(desdeHastaCalendar) '** INICIO Activar tipo de Recordatorio Dim Recordatorio As New Reminder 'Unidad de tiempo (horas, minutos, días) If lsRecordatorioUnidadTiempo.Text = "minutos" Then Recordatorio.Minutes = CInt(txtRecordatorioTiempo.Text) End If If lsRecordatorioUnidadTiempo.Text = "horas" Then Recordatorio.Hours = CInt(txtRecordatorioTiempo.Text) End If If lsRecordatorioUnidadTiempo.Text = "días" Then Recordatorio.Days = CInt(txtRecordatorioTiempo.Text) End If 'tipo de recordatorio (SMS, correo electrónico, ventana emergente) If lsRecordatorio.Text = "SMS" Then Recordatorio.Method = Reminder.ReminderMethod.sms End If If lsRecordatorio.Text = "Correo electrónico" Then Recordatorio.Method = Reminder.ReminderMethod.email End If If lsRecordatorio.Text = "Ventana emergente" Then Recordatorio.Method = Reminder.ReminderMethod.alert End If entradaCalendario.Reminders.Add(Recordatorio) '** FIN Activar tipo de Recordatorio 'Inserta los invitados de la cita de Google Calendar If txtInvitados.Text <> "" Then Dim invintadosSeparados() As String Dim i As Integer invintadosSeparados = Split(txtInvitados.Text, ",") Dim invitado As Who For i = 0 To UBound(invintadosSeparados) invitado = New Who() invitado.Rel = Who.RelType.MESSAGE_TO invitado.Email = invintadosSeparados(i) entradaCalendario.Participants.Add(invitado) Next i End If 'Insertamos el evento creado en Google Calendar Dim uriDireccionGoogle As New Uri("https://www.google.com/calendar/feeds/" & calendariosT.Item(lsCalendarios.SelectedIndex).uri & "/private/full") Dim entradaEventoInsertar As AtomEntry = servicioGoogle.Insert(uriDireccionGoogle, entradaCalendario) MsgBox("Evento enviado correctamente a Google Calendar.", MsgBoxStyle.OkOnly + MsgBoxStyle.Information) bePanel1.Text = "Evento enviado correctamente a Google Calendar" be.Refresh() System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default Catch ex As Exception bePanel1.Text = "Error al enviar evento a Google Calendar..." be.Refresh() System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default MsgBox("Se ha producido un error al intentar insertar un " & _ "evento en Google Calendar: " & _ vbCrLf & vbCrLf & ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation) End Try End If End Sub Private Sub btListaCalendarios_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btListaCalendarios.Click Dim titulo As String = "" Dim subtitulo As String = "" Try System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor bePanel1.Text = "Obteniendo lista de calendarios de Google Calendar..." be.Refresh() lsCalendarios.Items.Clear() obtenerCalendarios(opSoloPropietario.Checked) Dim i As Integer For i = 0 To calendariosT.Count - 1 lsCalendarios.Items.Add(calendariosT.Item(i).titulo) Next i If calendariosT.Count > 0 Then lsCalendarios.SelectedIndex = 0 End If bePanel1.Text = "Lista de calendarios obtenida correctamente" be.Refresh() System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default Catch ex As Exception bePanel1.Text = "Error al obtener lista de calendarios..." be.Refresh() System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default MsgBox("Se ha producido un error al intentar obtener la " & _ "lista de calendarios de Google Calendar: " & _ vbCrLf & vbCrLf & ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation) End Try End Sub Private Sub btLimpiar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btLimpiar.Click txtEvento.Text = "" txtLugar.Text = "" txtDescripcion.Text = "" txtInvitados.Text = "" End Sub Private Sub btSalir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btSalir.Click guardarDatosINI() End End Sub Private Sub btSalinSinGuardar_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btSalinSinGuardar.Click End End Sub Private Sub btCalendarioColor_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btCalendarioColor.Click If dlColor.ShowDialog Then txtNuevoCalendarioColor.Text = "#" & CStr(Hex$(dlColor.Color.ToArgb)) End If End Sub Private Sub btInsertarCalendario_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btInsertarCalendario.Click Try 'Alta del servicio de Google y autenticación en Google Dim servicioGoogle As New CalendarService("AjpdSoftInsertarCitaGoogleCalendar") servicioGoogle.setUserCredentials(txtUsuario.Text, txtContrasena.Text) Dim entradaCalendario As New CalendarEntry entradaCalendario.Title.Text = txtNuevoCalendarioNombre.Text entradaCalendario.Summary.Text = txtNuevoCalendarioDescripcion.Text entradaCalendario.TimeZone = System.TimeZone.CurrentTimeZone.StandardName entradaCalendario.Hidden = opNuevoCalendarioOculto.Checked entradaCalendario.Color = txtNuevoCalendarioColor.Text entradaCalendario.Location = New Where("", "", txtNuevoCalendarioUbicacion.Text) entradaCalendario.Selected = opNuevoCalendarioSeleccionado.Checked Dim uriDireccionGoogle As New Uri("https://www.google.com/calendar/feeds/default/owncalendars/full") servicioGoogle.Insert(uriDireccionGoogle, entradaCalendario) Dim nuevoCalendario As CalendarEntry = servicioGoogle.Insert(uriDireccionGoogle, entradaCalendario) MsgBox("Calendario añadido correctamente.", MsgBoxStyle.Information + MsgBoxStyle.OkOnly) Catch ex As Exception MsgBox("Se ha producido un error al intentar añadir un calendario: " & _ vbCrLf & vbCrLf & ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation) End Try End Sub Private Sub btExportarCSV_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btExportarCSV.Click dlGuardar.Filter = "Archivos CSV (*.csv)|*.csv|Todos los archivos (*.*)|*.*" dlGuardar.FilterIndex = 1 dlGuardar.DefaultExt = "csv" dlGuardar.FileName = "Eventos google calendar" dlGuardar.OverwritePrompt = True dlGuardar.Title = "Guardar eventos Google Calendar" If dlGuardar.ShowDialog Then exportarListViewCSV(lsCitas, dlGuardar.FileName) End If End Sub Private Sub btObtenerCalendariosMostrarCitas_Click(ByVal sender As System.Object, <br> ByVal e As System.EventArgs) Handles btObtenerCalendariosMostrarCitas.Click Try System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor bePanel1.Text = "Obteniendo lista de calendarios de Google Calendar..." be.Refresh() lsCalendariosCitas.Items.Clear() obtenerCalendarios(opSoloPropietarioCitas.Checked) Dim i As Integer For i = 0 To calendariosT.Count - 1 lsCalendariosCitas.Items.Add(calendariosT.Item(i).titulo) Next i If calendariosT.Count > 0 Then lsCalendariosCitas.SelectedIndex = 0 End If bePanel1.Text = "Lista de calendarios obtenida correctamente" be.Refresh() System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default Catch ex As Exception bePanel1.Text = "Error al obtener lista de calendarios..." be.Refresh() System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default MsgBox("Se ha producido un error al intentar obtener la " & _ "lista de calendarios de Google Calendar: " & _ vbCrLf & vbCrLf & ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation) End Try End Sub Private Sub btObtenerCalendariosLista_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) <br> Handles btObtenerCalendariosLista.Click Try System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor bePanel1.Text = "Obteniendo lista de calendarios de Google Calendar..." be.Refresh() lsListaCalendarios.Items.Clear() obtenerCalendarios(opSoloPropietarioListaCalendarios.Checked) lsListaCalendarios.BeginUpdate() lsListaCalendarios.Columns.Clear() lsListaCalendarios.Items.Clear() lsListaCalendarios.View = View.Details lsListaCalendarios.Columns.Add(New ColHeader("Título", 200, HorizontalAlignment.Left, True)) lsListaCalendarios.Columns.Add(New ColHeader("Descripción", 200, HorizontalAlignment.Left, True)) lsListaCalendarios.Columns.Add(New ColHeader("Creadores/Autores", 200, HorizontalAlignment.Left, True)) lsListaCalendarios.Columns.Add(New ColHeader("ID", 150, HorizontalAlignment.Left, True)) lsListaCalendarios.Columns.Add(New ColHeader("Sólo lectura", 100, HorizontalAlignment.Left, True)) Dim i As Integer For i = 0 To calendariosT.Count - 1 Dim elementoLista As New ListViewItem elementoLista = New ListViewItem(CStr(calendariosT.Item(i).titulo)) elementoLista.SubItems.Add(CStr(calendariosT.Item(i).descripcion)) elementoLista.SubItems.Add(CStr(calendariosT.Item(i).creadores)) elementoLista.SubItems.Add(calendariosT.Item(i).uri) elementoLista.SubItems.Add(CStr(calendariosT.Item(i).soloLectura)) lsListaCalendarios.Items.Add(elementoLista) Next i lsListaCalendarios.EndUpdate() bePanel1.Text = "Lista de calendarios obtenida correctamente" be.Refresh() System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default Catch ex As Exception bePanel1.Text = "Error al obtener lista de calendarios..." be.Refresh() System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default MsgBox("Se ha producido un error al intentar obtener la " & _ "lista de calendarios de Google Calendar: " & _ vbCrLf & vbCrLf & ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation) End Try End Sub End Class |
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 |
Imports System.Security.Cryptography Imports System.Text Imports System.IO Public Class encriptacionRSA Public Function encriptar128BitRijndael( ByVal textoEncriptar As String, ByVal claveEncriptacion As String) As String Dim bytValue() As Byte Dim bytKey() As Byte Dim bytEncoded() As Byte = New Byte() {} Dim bytIV() As Byte = {121, 241, 10, 1, 132, 74, 11, 39, 255, 91, 45, 78, 14, 211, 22, 62} Dim intLength As Integer Dim intRemaining As Integer Dim objMemoryStream As New MemoryStream() Dim objCryptoStream As CryptoStream Dim objRijndaelManaged As RijndaelManaged 'Quitar nulos en cadena de texto a encriptar textoEncriptar = quitarNullCadena(textoEncriptar) If textoEncriptar = "" Then Return "" End If bytValue = Encoding.ASCII.GetBytes(textoEncriptar.ToCharArray) intLength = Len(claveEncriptacion) 'La clave de cifrado debe ser de 256 bits de longitud (32 bytes) 'Si tiene más de 32 bytes se truncará 'Si es menor de 32 bytes se rellenará con X If intLength >= 32 Then claveEncriptacion = Strings.Left(claveEncriptacion, 32) Else intLength = Len(claveEncriptacion) intRemaining = 32 - intLength claveEncriptacion = claveEncriptacion & Strings.StrDup(intRemaining, "X") End If bytKey = Encoding.ASCII.GetBytes(claveEncriptacion.ToCharArray) objRijndaelManaged = New RijndaelManaged() Try 'Crear objeto Encryptor y escribir su valor 'después de que se convierta en array de bytes objCryptoStream = New CryptoStream(objMemoryStream, _ objRijndaelManaged.CreateEncryptor(bytKey, bytIV), _ CryptoStreamMode.Write) objCryptoStream.Write(bytValue, 0, bytValue.Length) objCryptoStream.FlushFinalBlock() bytEncoded = objMemoryStream.ToArray objMemoryStream.Close() objCryptoStream.Close() Catch ex As Exception MsgBox("Error al encriptar cadena de texto: " & ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation) End Try 'Devolver el valor del texto encriptado 'convertido de array de bytes a texto en base64 Return Convert.ToBase64String(bytEncoded) End Function Public Function desencriptar128BitRijndael( ByVal textoEncriptado As String, ByVal claveDesencriptacion As String) As String Dim bytDataToBeDecrypted() As Byte Dim bytTemp() As Byte Dim bytIV() As Byte = {121, 241, 10, 1, 132, 74, 11, 39, 255, 91, 45, 78, 14, 211, 22, 62} Dim objRijndaelManaged As New RijndaelManaged() Dim objMemoryStream As MemoryStream Dim objCryptoStream As CryptoStream Dim bytDecryptionKey() As Byte Dim intLength As Integer Dim intRemaining As Integer Dim strReturnString As String = String.Empty If textoEncriptado = "" Then Return "" End If 'Convertir el valor encriptado base64 a array de bytes bytDataToBeDecrypted = Convert.FromBase64String(textoEncriptado) 'La clave de desencriptación debe ser de 256 bits de longitud (32 bytes) 'Si tiene más de 32 bytes se truncará 'Si es menor de 32 bytes se rellenará con A intLength = Len(claveDesencriptacion) If intLength >= 32 Then claveDesencriptacion = Strings.Left(claveDesencriptacion, 32) Else intLength = Len(claveDesencriptacion) intRemaining = 32 - intLength claveDesencriptacion = claveDesencriptacion & Strings.StrDup(intRemaining, "X") End If bytDecryptionKey = Encoding.ASCII.GetBytes(claveDesencriptacion.ToCharArray) ReDim bytTemp(bytDataToBeDecrypted.Length) objMemoryStream = New MemoryStream(bytDataToBeDecrypted) Try 'Crear objeto Dencryptor y escribir su valor 'después de que se convierta en array de bytes objCryptoStream = New CryptoStream(objMemoryStream, _ objRijndaelManaged.CreateDecryptor(bytDecryptionKey, bytIV), _ CryptoStreamMode.Read) objCryptoStream.Read(bytTemp, 0, bytTemp.Length) 'objCryptoStream.FlushFinalBlock() objMemoryStream.Close() objCryptoStream.Close() Catch ex As Exception MsgBox("Error al desencriptar cadena de texto: " & ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation) End Try 'Devolver la cadena de texto desencriptada 'convertida de array de bytes a cadena de texto ASCII Return quitarNullCadena(Encoding.ASCII.GetString(bytTemp)) End Function 'Quita nulos de una cadena de texto Public Function quitarNullCadena( ByVal texto As String) As String Dim posicionNull As Integer Dim textoSinNull As String posicionNull = 1 textoSinNull = texto Do While posicionNull > 0 posicionNull = InStr(posicionNull, texto, vbNullChar) If posicionNull > 0 Then textoSinNull = Left$(textoSinNull, posicionNull - 1) & _ Right$(textoSinNull, Len(textoSinNull) - posicionNull) End If If posicionNull > textoSinNull.Length Then Exit Do End If Loop Return textoSinNull End Function End Class |
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 |
Public Class FicherosINI ' Funciones del API de Windows para ficheros INI Private Declare Ansi Function GetPrivateProfileString _ Lib "kernel32.dll" Alias "GetPrivateProfileStringA" _ (ByVal lpApplicationName As String, _ ByVal lpKeyName As String, ByVal lpDefault As String, _ ByVal lpReturnedString As System.Text.StringBuilder, _ ByVal nSize As Integer, ByVal lpFileName As String) _ As Integer Private Declare Ansi Function WritePrivateProfileString _ Lib "kernel32.dll" Alias "WritePrivateProfileStringA" _ (ByVal lpApplicationName As String, _ ByVal lpKeyName As String, ByVal lpString As String, _ ByVal lpFileName As String) As Integer Private Declare Ansi Function GetPrivateProfileInt _ Lib "kernel32.dll" Alias "GetPrivateProfileIntA" _ (ByVal lpApplicationName As String, _ ByVal lpKeyName As String, ByVal nDefault As Integer, _ ByVal lpFileName As String) As Integer Private Declare Ansi Function FlushPrivateProfileString _ Lib "kernel32.dll" Alias "WritePrivateProfileStringA" _ (ByVal lpApplicationName As Integer, _ ByVal lpKeyName As Integer, ByVal lpString As Integer, _ ByVal lpFileName As String) As Integer Dim strFilename As String ' Constructor, para aceptar el fichero INI Public Sub New(ByVal Filename As String) strFilename = Filename End Sub 'Propiedad sólo lectura con nombre de fichero ReadOnly Property FileName() As String Get Return strFilename End Get End Property 'Función para leer cadena de texto (string) de fichero INI Public Function GetString(ByVal Section As String, _ ByVal Key As String, ByVal [Default] As String) As String Dim intCharCount As Integer Dim objResult As New System.Text.StringBuilder(256) intCharCount = GetPrivateProfileString(Section, Key, _ [Default], objResult, objResult.Capacity, strFilename) If intCharCount > 0 Then GetString = Left(objResult.ToString, intCharCount) Else GetString = "" End If End Function 'Función para leer un valor numérico del fichero INI Public Function GetInteger(ByVal Section As String, _ ByVal Key As String, ByVal [Default] As Integer) As Integer Return GetPrivateProfileInt(Section, Key, _ [Default], strFilename) End Function 'Función para leer un valor booleano de fichero INI Public Function GetBoolean(ByVal Section As String, _ ByVal Key As String, ByVal [Default] As Boolean) As Boolean Return (GetPrivateProfileInt(Section, Key, _ CInt([Default]), strFilename) = 1) End Function 'Función para escribir valor de cadena (string) en fichero INI Public Sub WriteString(ByVal Section As String, _ ByVal Key As String, ByVal Value As String) WritePrivateProfileString(Section, Key, Value, strFilename) Flush() End Sub 'Función para escribir valor numérico en fichero INI Public Sub WriteInteger(ByVal Section As String, _ ByVal Key As String, ByVal Value As Integer) ' Writes an integer to your INI file WriteString(Section, Key, CStr(Value)) Flush() End Sub 'Función para escribir valor booleano en fichero INI Public Sub WriteBoolean(ByVal Section As String, _ ByVal Key As String, ByVal Value As Boolean) ' Writes a boolean to your INI file WriteString(Section, Key, CStr(Math.Abs(CInt(Value)))) Flush() End Sub 'Guarda los cambios de la caché en fichero INI Private Sub Flush() FlushPrivateProfileString(0, 0, 0, strFilename) End Sub End Class |