Archivo de la categoría: SomeCode

From PCD – The future of C# and Visual Basic

No pierdas la oportunidad de concer el futuro, explicado directamente por Anders Hejlsberg!
Si quieres conocer las nuevas caracteristicas como «Async» y como el futuro rompera la caja negra del compilador convirtiendola en un servicio mas… eso si, necesitaras disponer de al menos 1 hora para prestar la atención que se merece.

Haz clic en : The future of C# and Visual Basic

Que lo disfruteis!,
Pep Lluis,

Lambdas EN VB

Como ya sabéis, una de las características que se han añadido son las expresiones Lambda, A pesar de existir cantidad de ejemplos, algunos me estáis pidiendo que os deje un par de ejemplos al estilo del blog.

Ahí van los típicos :

Module Module1

    Sub Main()
        Dim Numeros = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}

        Dim Pares = Numeros.Count(Function(n)
                                      Return (n Mod 2 = 0)
                                  End Function)
        Console.WriteLine("Numeros Pares : {0}", Pares)

        Dim esPar = Function(n)
                        If n Mod 2 = 0 Then Return "Si" Else Return "No"
                    End Function
        Console.WriteLine(esPar(2))

        Array.ForEach(Numeros, Sub(n)
                                   If (n Mod 2 = 0) Then Console.WriteLine(n)
                               End Sub)

        Console.ReadLine()
    End Sub

End Module

Saludos,

Actualizar dos tablas vinculadas en una vista Maestro-Detalle

Una de las consultas comúnmente solicitadas a través del Blog, tiene que ver con la actualización de datos de dos tablas relacionadas en una BD de SQL, o sea actualizar una vista maestro-detalle vinculadas a sendas tablas.

Aunque por obvio y sencillo, las explicaciones acostumbran a ser de lo más diversas y finalmente te das cuenta que la mayoría de ejemplos se inician con un «desparrame» de jergas incomprensivas para la mayoría. Me decido postearos el ejemplo más básico posible, para que a partir de este punto podáis hacerlo crecer a vuestra necesidad.

Espero que os sea útil y despeje vuestras jaquecas cuando se trata de lidiar con diversas tablas.
PepLluis,

 (Para ejecutar el ejemplo, iniciar Visual Studio y crear un nuevo proyecto ‘Winform’, añadir dos DataGridView y un Button, copiar / pegar codigo y por supuesto F5)

Imports System.Data.SqlClient

Public Class Form1

    Private Maestro As SqlDataAdapter
    Private Detalle As SqlDataAdapter
    Private ConjuntoDeDatos As DataSet

    Private Sub Form1_Load() Handles MyBase.Load

        Dim miConexion As New SqlConnection("Data Source=.\SQLExpress;Initial Catalog=MaestroDetalle;Integrated Security=True")

        Maestro = New SqlDataAdapter("Select * From Maestro", miConexion)
        Dim MaestroCmdBuilder As New SqlCommandBuilder(Maestro)

        Detalle = New SqlDataAdapter("Select * From Detalle", miConexion)
        Dim DetalleCmdBuilder As New SqlCommandBuilder(Detalle)

        ConjuntoDeDatos = New DataSet
        Maestro.Fill(ConjuntoDeDatos, "Maestro")
        Me.DataGridView1.DataSource = ConjuntoDeDatos
        Me.DataGridView1.DataMember = "Maestro"

        Detalle.Fill(ConjuntoDeDatos, "Detalle")
        Me.DataGridView2.DataSource = ConjuntoDeDatos

        ConjuntoDeDatos.Relations.Add("Fk", ConjuntoDeDatos.Tables("Maestro").Columns("IdMaestro"),
                                            ConjuntoDeDatos.Tables("Detalle").Columns("IdDetalle"))

        Me.DataGridView2.DataMember = "Maestro.Fk"
    End Sub

    Private Sub Actualizar() Handles Button1.Click
        If ConjuntoDeDatos.HasChanges Then
            Maestro.Update(ConjuntoDeDatos, "Maestro")
            Detalle.Update(ConjuntoDeDatos, "Detalle")
        End If
    End Sub
End Class

Linq – ParallelQuery

Discutiendo sobre la proliferación de núcleos en los procesadores y como sacarle más provecho, os introduzco a la inicialización de colecciones con ‘Query’s’ en Linq utilizando el pragma ‘asParallel’  de esa forma podemos añadir ese atractivo «Extra» a funciones que normalmente dejan que decir por la falta de agilidad al ejecutarse.

 

' Ejemplo de inicializacion de Query's paralelas
' En este caso usando una coleccion de respuestas sobre una peticion de ping.
' Pep Lluis 2010

Module Module1

    Sub Main()
        'Si el sistema dispone de mas de un nucleo
        If System.Environment.ProcessorCount > 1 Then
            'Definir una lista de IP's... por ejemplo :
            Dim Ips = {"localhost""192.168.1.2""192.168.1.3"}

            'Construccion de la Linq parallel query
            Dim PingP = From ip In Ips.AsParallel
                        Select New System.Net.NetworkInformation.Ping().Send(ip)
            Dim asParallel As DateTime = DateTime.Now   'Tomar tiempo de incio proceso
            'Procesar las respuestas
            ProcessPings(PingP)
            'Mostrar el tiempo empleado (Desde el inicio hasta el proceso de respuestas)
            Console.WriteLine("Tiempo empleado, usando 'AsParallel' : {0}"DateTime.Now - asParallel)

            'Query sin 'asParallel'
            Dim PingS = From ip In Ips
                        Select New System.Net.NetworkInformation.Ping().Send(ip)
            Dim noParallel As DateTime = DateTime.Now   'Tomar Tiempo de Inicio
            ProcessPings(PingS)
            Console.WriteLine("Tiempo Empleado sin Parallel Query   : {0}"DateTime.Now - noParallel)
        Else
            Console.WriteLine("No se puede realizar el test con un solo nucleo.")
        End If
        Console.ReadLine()
    End Sub

    'Procesar respuestas
    Sub ProcessPings(ByVal Pings)
        For Each ping In Pings
            Console.WriteLine("{0} : {1}", ping.Status, ping.Address)
        Next
    End Sub
End Module
Espero vuestas opiniones,
Pep Lluis,
I have this post in English version, no doubt in contact with me if needed.

De un DGV a una MDB

Debido a la insistencia de algunos lectores de este blog, me complace retomar un antiguo ejemplo donde rellenamos un DGV con los datos de una hoja XLS y posteriormente creamos una BD con la tabla correspondiente y en formato MDB. Por lo tanto seguro que con las nuevas herramientas podremos realizar tareas similares con mucho menos código, por eso matizo que se trata de un ejemplo reanimado de 2005 al 2010 J

Las versiones tanto de la XLS como la MDB corresponden al 97-2003. Para poder ejecutar este ejemplo necesitas crear un nuevo proyecto ‘Winforms’ en VB y simplemente copiar y pegar el código en el ‘form1’.

Tenéis que tener en cuenta para que funcione necesitas guardar tu hoja en la carpeta del proyecto ‘Bin/Debug’ (o reléase) según estés compilando y con el nombre ‘Libro1.xls’.

No dudéis en contactar conmigo para aclarar cualquier duda, además si necesitas el proyecto el completo estaré encantado de facilitártelo (Lo tengo para Visual Studio 2010).

Espero vuestras valoraciones.
Happy reentrada!
Pep Lluis,

' --------------------------------------------------------------------------------------------
' * AVISO IMPORTANTE * Este programa es propiedad (c)2010 Pep Lluis Bano.
' * AVISO IMPORTANTE * Se autoriza su uso, solo con fines formativos.
' 
' EL USO DE ESTA APLICACION IMPLICA LA ACEPTACION DE LAS CONDICIONES DE USO QUE SE APLICAN
' AL PROGRAMARIO "Open Source", ESTE PROGRAMA SE PROPORCIONA "COMO ESTA", NO OBLIGANDO AL 
' AUTOR A CONTRAER COMPROMISO ALGUNO PARA CON QUIENES LO UTILICEN, ASI COMO DECLINANDO 
' CUALQUIER REPONSABILIDAD DIRECTA O INDIRECTA, CONTRAIDA POR LOS MISMOS EN SU UTILIZACION 
' FUERA DE LOS PROPOSITOS PARA EL QUE FUE ESCRITO Y DISEÑADO.
'
' CUALQUIER MODIFICACIÓN Y DISTRIBUCION DEL MISMO DEBERA CONTENER Y CITAR SU FUENTE Y ORIGEN.
'
' ASI MISMO EL AUTOR AGRADECERA CUALQUIER COMENTARIO o CORRECCION QUE LOS LECTORES CONSIDEREN
' CONTRIBUYENDO ESTOS ULTIMOS A MEJORAR LA APLICACION CON FINES FORMATIVOS.
' CONSIDEREN ENVIAR SUS COMENTARIOS ulizando la opcion [Contact]
' --------------------------------------------------------------------------------------------

Imports
 ADOX
Imports System.Data.OleDb
Imports System.Text.RegularExpressions

Public Class Form1
    'Definir conexion,adaptador y Dataset
    Private MiXlsConexion As OleDbConnection
    Private MiXlsAdaptador As OleDbDataAdapter
    Private MiXlsDataSet As New DataSet()
    Private MiXlsDGV As New DataGridView

    Private MiMdbConexion As New OleDbConnection
    Private MiMdbAdaptador As New OleDbDataAdapter
    Private MiMdbDataSet As New DataSet()

    Private Mienlazador As New BindingSource
    Private MiMdbDGV As New DataGridView

    Private Sub Form1_FormClosing(ByVal sender As ObjectByVal e As System.Windows.Forms.FormClosingEventArgsHandles Me.FormClosing
        MiMdbConexion.Close()
    End Sub

    Private Sub Form1_Load() Handles MyBase.Load
        Dim MiXlsEtiqueta As New Label
        MiXlsEtiqueta.Text = "Contenido de la Hoja Excel"
        MiXlsEtiqueta.TextAlign = ContentAlignment.MiddleCenter
        MiXlsEtiqueta.BorderStyle = BorderStyle.Fixed3D
        MiXlsEtiqueta.BackColor = Color.Green
        MiXlsEtiqueta.ForeColor = Color.White
        MiXlsEtiqueta.Dock = DockStyle.Top

        Dim MiXlsDGBPanel As New Panel
        MiXlsDGBPanel.AutoSize = True
        MiXlsDGV.Dock = DockStyle.Top
        MiXlsDGBPanel.Controls.AddRange(New Control() {MiXlsDGV, MiXlsEtiqueta})


        Dim MiMdbEtiqueta As New Label
        MiMdbEtiqueta.Text = "Contenido de la BD resultante"
        MiMdbEtiqueta.TextAlign = ContentAlignment.MiddleCenter
        MiMdbEtiqueta.BorderStyle = BorderStyle.Fixed3D
        MiMdbEtiqueta.BackColor = Color.Maroon
        MiMdbEtiqueta.ForeColor = Color.White
        MiMdbEtiqueta.Dock = DockStyle.Top

        Dim MiMdbDGBPanel As New Panel
        MiMdbDGBPanel.AutoSize = True
        MiMdbDGV.Dock = DockStyle.Top
        MiMdbDGBPanel.Controls.AddRange(New Control() {MiMdbDGV, MiMdbEtiqueta})

        Dim BotonDeActualizar As New Button
        BotonDeActualizar.Dock = DockStyle.Bottom
        BotonDeActualizar.Text = "Generar Archivo MDB"

        Me.AutoSize = True
        Me.Text = "De XLS a MDB"
        MiXlsDGBPanel.Dock = DockStyle.Top
        MiMdbDGBPanel.Dock = DockStyle.Top
        Me.Controls.AddRange(New Control() {MiMdbDGBPanel, MiXlsDGBPanel, BotonDeActualizar})
        AddHandler BotonDeActualizar.Click, AddressOf GenerarMdb

        LeerXls()
    End Sub

    Private Sub LeerXls()
        'Abrir y llenar el DGV con la hoja de excel
        MiXlsConexion = New OleDbConnection _
        ("Provider=Microsoft.Jet.OLEDB.4.0;" + _
         "Extended Properties = 'Excel 8.0';" + _
         "Data Source=|DataDirectory|\libro1.xls;")
        MiXlsAdaptador = New OleDbDataAdapter("SELECT * FROM [Hoja1$]", MiXlsConexion)
        MiXlsConexion.Open()
        MiXlsAdaptador.Fill(MiXlsDataSet)
        MiXlsDGV.DataSource = MiXlsDataSet.Tables(0)
    End Sub

    Private Sub GenerarMdb()
        'Eliminar la BD1 si existe
        If My.Computer.FileSystem.FileExists("Bd1.mdb"Then
            My.Computer.FileSystem.DeleteFile("Bd1.mdb")
        End If
        '
        Dim Nombrede_MiBd = "Bd1.mdb"
        Dim NombreDe_MiTabla = "Detalles"
        ' Para crear una nueva BD de Access, me viene a la
        ' memoria la funcion Catalog del ADOX.DLL
        Dim Catalogo As New ADOX.Catalog()
        Catalogo.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Nombrede_MiBd)
        '
        ' Una vez creado el nuevo catalogo añadiremos 
        ' la tabla utilizando el suministrador OLEDB
        MiXlsConexion = New OleDb.OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source =" & Nombrede_MiBd)
        '
        ' Obtenendremos el esquema de la nueva BD
        MiXlsConexion.Open()
        Dim MiEsquema As DataTable = MiXlsConexion.GetOleDbSchemaTable(OleDb.OleDbSchemaGuid.Tables, _
                New Object() {NothingNothing, NombreDe_MiTabla, "Detalles"})
        '
        ' El ultimo paso sera crear la estructura en funcion a las columnas de la hoja
        Dim Campos As String = "Create Table [" + NombreDe_MiTabla + "] ("
        For Each col As DataGridViewTextBoxColumn In MiXlsDGV.Columns
            If Campos.EndsWith(")"Or Campos.EndsWith("Key"Then Campos += ", "
            Campos += "[" + Regex.Replace(col.DataPropertyName, " ""_") + "] Text(50)"
        Next
        Campos += ")"
        Dim MiMandato As New OleDbCommand(Campos, MiXlsConexion)
        MiMandato.ExecuteNonQuery()
        MiXlsConexion.Close()
        '
        ' Añadir todos las filas como registros a la BD
        MiMdbConexion = New OleDb.OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source =" & Nombrede_MiBd)
        MiMdbAdaptador = New OleDbDataAdapter("SELECT * FROM Detalles", MiMdbConexion)
        Dim commandbuilder As New OleDb.OleDbCommandBuilder(Me.MiMdbAdaptador)
        MiMdbConexion.Open()
        MiMdbAdaptador.Fill(MiMdbDataSet)

        Dim Registro As DataRow
        For Each row As DataGridViewRow In MiXlsDGV.Rows
            If row.Index < MiXlsDGV.RowCount - 1 Then
                Registro = MiMdbDataSet.Tables(0).NewRow
                For Each col As DataGridViewColumn In MiXlsDGV.Columns
                    'Añadir una entrada por celda
                    Registro(col.Index) = row.Cells(col.Index).Value
                Next
                'Añadir una linea por fila
                MiMdbDataSet.Tables(0).Rows.Add(Registro)
            End If
        Next
        MiMdbAdaptador.Update(MiMdbDataSet)
        MiMdbDGV.DataSource = MiMdbDataSet.Tables(0)
        MiMdbConexion.Close()
    End Sub
End Class

Flag’s Enumerations

        

// Utilizar VStudio 2010.

‘// El propósito de este código es mostrar el uso 
‘// de los indicadores de enumeraciones utilizando
‘// conversiones hexadecimales (por ejemplo!).
‘//
‘// (c)(r) 🙂 PepLluis 2010

‘// Para entender este ejemplo, imagina que
‘// necesitas controlar algún dispositivo, ya sea
‘// a través de Ethernet, USB o Puerto Serie, para
‘// Supervisar or controlar las operaciones de
‘// paro o marcha, trabando solo con dos bytes…
‘// el primero de ellos mapeando los bits de
‘// salida y el segundo los de entrada, después
‘// de esto solo necesitaras enviar el byte de
‘// salida al dispositivo o supervisar la entrada
‘// cuando se produzca un cambio en su valor.

‘// Este ejemplo además muestra el uso de
‘// la continuación implícita de línea y los
‘// inicializadores para poder añadir todos los
‘// Controles necesarios en el form, en un solo
‘// golpe.
.

‘// Los comentarios y el código están en Ingles
‘// por tema de difusión, no dudes en pedírmelos
‘// en Castellano, si lo consideras oportuno

‘// Test this code with Visual Studio 2010.

‘// the purpose of this code is just show and play ‘// with flag’s enumerations and play using
‘// hexadecimals conversions.
‘//
‘// (C)(R) 🙂 PepLluis 2010

‘// To understand this sample… imagine you need
‘// control some devices using Ethernet, USB or
‘// Serial Ports to supervise and set/reset their
‘// status with start/stop operations, just two
‘// bytes… the first one to map input bits
‘// and the second to map output bits, after
‘// this you only need send output byte to device
‘// or supervise received byte when value change.

‘// this sample also show how use implicit line
‘// continuation and initializers to add controls
‘// in one shot in load event (for example).

 

 

Y aqui el Codigo…

‘Define input channel
<FlagsAttribute()> Public Enum InputChannel
    PowerAlarm = 1
    LowVoltage = 2
    HighVoltage = 4
    OverCurrent = 8
    PowerGood = 16
    ShortCircuit = 32
    WithoutLoad = 64
    OutOfService = 128
End Enum

» Define output channel
<FlagsAttribute()> Public Enum OutputChannel
    Engine_Axis1 = 1
    Engine_Axis2 = 2
    Engine_Axis3 = 4
    Smoke_Vent = 8
    Refrigerator = 16
    Blast_Furnace = 32
    TransPort_Belt = 64
    Emergency_Stop = 128
End Enum

‘// You can add dynamically items to enum and no changes are needed inside code… just rebuild

Public Class FlagsEnumerationSample
    Private Sub When_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ‘Title
        Me.Text = «Playing with Flag’s Enum’s»
        ‘Add all labels and textbox in one shot
        Me.Controls.AddRange({New Label With {.Name = «lblHexcaptn»,
                                              .AutoSize = True,
                                              .Location = New Point(5, 10),
                                              .Text = «Output Value:»},
                              New Label With {.Name = «lblHexValue»,
                                              .AutoSize = True,
                                              .Location = New Point(75, 10),
                                              .Text = «0x00», .Height = 20},
                              New Label With {.Name = «lblInputVal»,
                                              .AutoSize = True,
                                              .Location = New Point(140, 10),
                                              .Text = «Input Value : 0x»},
                              New TextBox With {.Name = «txtInputVal»,
                                                .MaxLength = 2,
                                                .Width = 20,
                                                .Location = New Point(220, 8),
                                                .Text = «00»}
                            })

        ‘Add one customized button for every item in enumeration
        Dim NextPos As Integer = 30                                             ‘Point for this button (30=initial top pos)
        For Each elem In [Enum].GetValues(GetType(OutputChannel))               ‘iterate output enum
            Me.Controls.Add(New CustomButton(New Point(20, NextPos), elem))     ‘add new button with new point position for elem
            AddHandler Me.Controls(elem.ToString).Click, AddressOf OutPutOnOff  ‘When button is click put output on/off
            NextPos += Me.Controls(elem.ToString).Height                        ‘Calculate next point location for next elem
        Next

        NextPos = 30                                                            ‘Initial top pos for first element
        For Each elem In [Enum].GetValues(GetType(InputChannel))                ‘Iterate input enum
            Me.Controls.Add(New CustomLabel(New Point(160, NextPos), elem))     ‘Add customized label for any bit input in enum
            NextPos += Me.Controls(elem.ToString).Height                        ‘Calculate location for next label
        Next
        ‘Simulate input value… refresh labels when textbox value change
        AddHandler Me.Controls(«txtInputVal»).TextChanged, AddressOf InputsOnOff

        Me.Height = NextPos + 50                                                ‘Fix form height, after last control + 50
    End Sub

    Private Outputs As Byte = 0                                                 ‘Output channel (Byte)
   
    ‘Change On/Off output bit status of sender
    ‘remark : TAG property of button is used as bit weight
    Sub OutPutOnOff(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If Outputs And CType(sender, Button).Tag Then                           ‘Flic /Flac output bit
            Outputs = Outputs Xor CType(sender, Button).Tag                     ‘Set Off if On
            sender.BackColor = Color.GreenYellow                                ‘GreenYellow if Off
        Else
            Outputs = Outputs Or CType(sender, Button).Tag                      ‘Set On if Off
            sender.BackColor = Color.Red                                        ‘Reed if On
        End If
        Me.Controls(«lblHexValue»).Text = «0x» + Hex(Outputs)
    End Sub

    Private Inputs As Byte? = 0                                                 ‘Input channel (Byte)
    ‘Change color of label when bit is On or Off
    ‘remark : TAG property of label is used as bit weight
    Sub InputsOnOff()
        Try
            Inputs = «&h0» + Me.Controls(«txtInputVal»).Text                    ‘Read & convert text as Hex value
        Catch ex As Exception
            Me.Controls(«txtInputVal»).Text = «»                                ‘Wrong format… clear textbox
        End Try

        For Each Elem In [Enum].GetNames(GetType(InputChannel))                 ‘for each item in enum
            If Inputs And CType(Me.Controls(Elem), Label).Tag Then              ‘Red Color if bit is On, Green if off
                Me.Controls(Elem).BackColor = Color.Red
            Else
                Me.Controls(Elem).BackColor = Color.GreenYellow
            End If
        Next
    End Sub
End
Class


‘ Just My customizes Button to select and display outputs
Class CustomButton
    Inherits Button
   
    ‘ Create using
       _location inside form
       _elem     particular item of enumeration
    Sub New(ByVal _location As Point, ByVal _elem As [Enum])
        Me.Tag = CType(_elem, OutputChannel)                    ‘My Bit weight
        Me.Name = _elem.ToString                                ‘My Name
        Me.Text = Me.Name                                       ‘Name to Show
        Me.Width = 100                                          ‘Wide
        Me.Location = _location                                 ‘Set Position
        Me.BackColor = Color.GreenYellow                        ‘Initial Color
    End Sub
End
Class


‘ Just My customized Label to display Inputs
Class CustomLabel
    Inherits Label
   
    ‘ Create using
       _location pos inside form
       _elem     particular item of enumeration
    Sub New(ByVal _location As Point, ByVal _elem As [Enum])
        Me.Tag = CType(_elem, InputChannel)                     ‘My Bit weight
        Me.Name = _elem.ToString                                ‘My Name
        Me.Text = Me.Name                                       ‘Name to Show
        Me.Width = 100                                          ‘Wide
        Me.Location = _location                                 ‘Position
        Me.TextAlign = ContentAlignment.MiddleCenter            ‘Align
        Me.BackColor = Color.GreenYellow                        ‘Initial color
        Me.BorderStyle = Windows.Forms.BorderStyle.FixedSingle  ‘Set Border
    End Sub
End
Class

Salud,
Pep Lluis,

El Llenguatge dels ordinadors (Proximo evento en Vic)

El Llenguatge dels ordinadors


Dijous de 11 de Febrer del 2010 a les 20h (Durada aproximada 1:30min)

1ra Part – Introducció

Informació general
Dedicarem aquesta primera sessió a fer un recorregut entorn a l’evolució dels sistemes operatius i els llenguatges de programació tot posant especial èmfasis en la part mes filosòfica del desenvolupament d’aplicacions.

Entorn: Sistemes Operatius i Llenguatges
Audiència : Públic en General 
Lloc


Biblioteca Joan Triadú
Arquebisbe Alemany 5

08500 VIC
 

Conduit :

 


Pep Lluis Bano

Spain.Net Leader
INETA Regional Speaker
MVP– Visual Developer

 

Enviar un correo electrónico con MailMessage

Son muchas las cuestiones que recibo acerca de cómo enviar un correo electrónico utilizando código y en concreto con .NET y VB.

Este tipo de facilidades acostumbran a ser muy utilices sobre todo en aplicaciones que puntualmente deben enviar alertas reportando situaciones en las que se requiere llamar la atención o notificar acontecimientos a personas distantes del lugar donde se producen.

Os dejo este corto, como siempre con la estructura más básica, pero practica de como enviar un correo, eso si no dudéis en continuar esta conversación si queréis ampliar el tema.

No olvidéis que necesitáis incluir los espacios de nombres : System.Net / System.Net.Mail, con los imports al inicio del proyecto.

    Sub EnviarMail_Demo()

        Dim Correo As New MailMessage

        Correo.From = New MailAddress(«MiCorreo@Proveedor.com»)

        Correo.To.Add(New MailAddress(«TuCorreo@Proveedor.com»))

        Correo.Subject = «Motivo del correo»

        Correo.Body = «Detalle y texto que vas ha recibir en Tu Correo»

        Dim Cartero As New SmtpClient(«smtp.TuServidor.com»)

        Cartero.Credentials = New NetworkCredential(«miCuenta@DeCorreo.com», «ClaveDeAcceso»)

        Cartero.Send(Correo)

    End Sub

Espero que esto os ayude como punto de inicio de este espacio de nombres.

Saludos,
Pep Lluis,

Descargar archivos desde un FTP en .NET – How to Download files from FTP using .NET

FtpClient

        

Existe una inquietud por parte de muchas personas desde la aparición de .NET, en tanto a como descargar archivos utilizando una aplicación de escritorio desde un servidor FTP.

El propósito de este ejemplo es demostrar como descargar simultáneamente archivos de un directorio raíz en un ftp, evidentemente con algunas limitaciones como por ejemplo navegar en los directorios del mismo. Me gustara compartir esta aplicación para que la ejecutéis según os interese, intentare adaptar todas las sugerencias que me hagáis llegar y finalmente poder publicar el proyecto (o eso espero) para compartirlo con todos vosotros.

Podéis descomprimir y ejecutar él ‘.exe’ en cualquier maquina con Vista o 7, si necesitáis el instalador no dudéis en solicitármelo, pero con en principio cualquier equipo con el Framework 3.5 sirve.

Espero vuestros comentarios.
(C) Pep Lluis 2009 🙂
 


Always receive some comments from people asking ‘How to Download files from FTP using .NET”,  the best way to answer this, is develop a very easy & simple sample using last version of framework, first I will share this app to free run and I will adapt all yours suggestions, finally share the project with source code (… or I hope so).

You can run with no setup in windows vista or 7, please ask if you need setup for deployment.

Please don’t forget run and send your suggestions.
Best!!
Pep Lluis,

 

Puedes descargarte el ejecutable haciendo clic en : FTPClient

Advertencia y Aclaración.
Está claro que os facilito este articulo por vuestra insistencia, esta aplicación solo utiliza dos librerías : 
System.Net, System.IO y no almacena ningún tipo de información introducida por nombres o credenciales intercambiadas por el usuario,  debo rechazar categóricamente cualquier responsabilidad por el uso de la información así como la aplicación aquí contenida, cualquier uso de la misma o de la información de este artículo y su alcance es estrictamente responsabilidad del lector, aunque como siempre estaré encantado de recibir vuestros comentarios.

Warning:  It is clear that this article is delivered for the insistence of some readers, this application uses only two libraries: System.NET, System.IO, does not store any information introduced by names or exchanged by the user credentials, I categorically reject any responsibility for the use of information as well as the application contained here, any use of it or the information in this article and its scope is strictly responsibility of the reader, although as I am always happy to receive your comments.