RECIBIR EMAIL (C#)

// Clase Pop3Exception -->


using System;
using System.Collections.Generic;
using System.Text;
using a = System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Collections;
using System.Net.Sockets;
using System.Diagnostics;

OpenPop.Pop3.Pop3Client objPOP3;

public class Pop3Exception : System.ApplicationException
{
    public Pop3Exception(string str)
        : base(str)
    {

    }
}

public class Pop3Message
{
    public long number;
    public long bytes;
    public bool retrieved;
    public string message;
}

public class Pop3 : System.Net.Sockets.TcpClient
{

    ArrayList retval;
    Pop3 obj; 

    public void Connect(string server, string username, string password)
    {
        string message;
        string response;
        Connect(server, 110);
        response = Response();
        if (response.Substring(0, 3) != "+OK")
        {
            throw new Pop3Exception(response);
        }
        message = "USER " + username + "\r\n";
        Write(message);
        response = Response();
        if (response.Substring(0, 3) != "+OK")
        {
            throw new Pop3Exception(response);
        }
        message = "PASS " + password + "\r\n";
        Write(message);
        response = Response();
        if (response.Substring(0, 3) != "+OK")
        {
            throw new Pop3Exception(response);
        }
    }
    public void Disconnect()
    {
        string message;
        string response;
        message = "QUIT\r\n";
        Write(message);
        response = Response();
        if (response.Substring(0, 3) != "+OK")
        {
            throw new Pop3Exception(response);
        }
    }

    public ArrayList returnList()
    {
        return retval;
    }

    public Pop3 returnPOP3()
    {
        return obj;
    }

    public ArrayList List()
    {
        string message;
        string response;

        retval = new ArrayList();

        message = "LIST\r\n";
        Write(message);
        response = Response();
        if (response.Substring(0, 3) != "+OK")
        {
            throw new Pop3Exception(response);
        }

        while (true)
        {
            response = Response();
            if (response == ".\r\n")
            {
                return retval;
            }
            else
            {
                Pop3Message msg = new Pop3Message();
                char[] seps = { ' ' };
                string[] values = response.Split(seps);
                msg.number = Int32.Parse(values[0]);
                msg.bytes = Int32.Parse(values[1]);
                msg.retrieved = false;
                retval.Add(msg);
                continue;
            }
        }
    }

    public Pop3Message Retrieve(Pop3Message rhs)
    {
        string message;
        string response;
        Pop3Message msg = new Pop3Message();
        msg.bytes = rhs.bytes;
        msg.number = rhs.number;
        message = "RETR " + rhs.number + "\r\n";
        Write(message);
        response = Response();
        if (response.Substring(0, 3) != "+OK")
        {
            throw new Pop3Exception(response);
        }
        msg.retrieved = true;
        while (true)
        {
            response = Response();
            if (response == ".\r\n")
            {
                break;
            }
            else
            {
                msg.message += response;
            }
        }
        return msg;
    }

    public void Delete(Pop3Message rhs)
    {
        string message;
        string response;
        message = "DELE " + rhs.number + "\r\n";
        Write(message);
        response = Response();
        if (response.Substring(0, 3) != "+OK")
        {
            throw new Pop3Exception(response);
        }
    }

    private void Write(string message)
    {

        System.Text.ASCIIEncoding en = new System.Text.ASCIIEncoding();

        byte[] WriteBuffer = new byte[1024];
        WriteBuffer = en.GetBytes(message);
        NetworkStream stream = GetStream();
        stream.Write(WriteBuffer, 0, WriteBuffer.Length);
        Debug.WriteLine("WRITE:" + message);
    }

    private string Response()
    {

        System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();

        byte[] serverbuff = new Byte[1024];
        NetworkStream stream = GetStream();
        int count = 0;
        while (true)
        {

            byte[] buff = new Byte[2];
            int bytes = stream.Read(buff, 0, 1);
            if (bytes == 1)
            {
                serverbuff[count] = buff[0];
                count++;
                if (buff[0] == '\n')
                {
                    break;
                }
            }
            else
            {
                break;
            };
        };

        string retval = enc.GetString(serverbuff, 0, count);
        Debug.WriteLine("READ:" + retval);
        return retval;
    }

}

// <--Clase Pop3Exception 

// Llamada a la descarga de correo -->

public int POP3connect(string server, string username, string password)
        {
          try
            {
                objPOP3 = new Pop3();
                objPOP3.Connect(server, username, password);
                ArrayList list = objPOP3.List();

                return objPOP3.List().Count;
               
            }
            catch (Pop3Exception E)
            {
                return 0;
            }

        }

public string POP3read(int n, ref string De, ref string Para, ref string Asunto, bool delete)
        {
            string Body="";

            try
            {

                ArrayList list = objPOP3.returnList();

                int i = 0;
                
                foreach (Pop3Message msg in list)
                {
                    if (i == n)
                    {
                        Pop3Message msg2 = objPOP3.Retrieve(msg);
                        String Mail = msg2.message;
                        //De
                        De = Mail.Substring(Mail.IndexOf("From: ", 1));
                        De = De.Substring(0, De.IndexOf("\r\n")).Replace("From: ", "");
                        //Para
                        Para = Mail.Substring(Mail.IndexOf("To: ", 1));
                        Para = Para.Substring(0, Para.IndexOf("\r\n")).Replace("To: ", "");
                        //Asunto
                        Asunto = Mail.Substring(Mail.IndexOf("Subject: ", 1));
                        Asunto = Asunto.Substring(0, Asunto.IndexOf("\r\n")).Replace("Subject: ", "");
                        //Body
                        Body = Mail.Substring(Mail.IndexOf("Content-Type: text/plain;", 1));
                        Body = Body.Substring(Body.IndexOf("\r\n\r\n") + 4);
                        Body = Body.Substring(0, Body.IndexOf("Content-Type: text/html;"));

                        if (delete ==true)
                        {
                            objPOP3.Delete(msg2);
                        }

                        break;
                    }
                    i = i + 1;
                   
                }
            }
            catch (Pop3Exception E)
            {
                
            }

            return Body;
}

public void POP3disconnect()
           {
             try
             {
                 objPOP3.Disconnect();
             }
              catch (Pop3Exception E)
             { 
             }
        }

// <-- Llamada a la descarga de correo

FECHAS - RECUPERAR 1ER Y ÚLTIMO DIA DE LA SEMANA / MES (Ej. MonthCalendar)

'1er día de la semana 
MonthCalendar.SelectionStart.Date.AddDays(1 - (MonthCalendar.SelectionStart.Date.DayOfWeek))
'Último día de la semana
MonthCalendar.SelectionStart.Date.AddDays(7 - (MonthCalendar.SelectionStart.Date.DayOfWeek))


'1er día del mes
Format(MonthCalendar.SelectionStart.Date.AddDays,"01/MM/yyyy")
'Último día del mes
MonthCalendar.SelectionStart.AddDays(Date.Today.DaysInMonth(Date.Today.Year, Date.Today.Month) - Date.Today.Day)

CREAR DIRECTORIO Y FICHERO EN DIRECTORIO DE LA APLICACIÓN ( Ej. log de Errores)

If Not Directory.Exists(System.AppDomain.CurrentDomain.BaseDirectory & "\LOGS") Then
      Directory.CreateDirectory(System.AppDomain.CurrentDomain.BaseDirectory & "\LOGS")
End If


Dim ficERR As String = System.AppDomain.CurrentDomain.BaseDirectory & "\LOGS\error" & errTipo & Format(Now, "yyyyMMdd") & ".log"
        
Dim sw As New System.IO.StreamWriter(ficERR, True)
       
sw.WriteLine(Format(Now, "hh:mm:ss") & "|" & errTipo & "|" & errTexto & vbCrLf)
sw.Close()
sw.Dispose()
sw = Nothing
      

EJECUTAR APLICACIÓN PASANDO PARÁMETROS AL EXE

Private Sub Inicio_Shown(sender As Object, e As System.EventArgs) Handles Me.Shown
        If Len(Command) Then
            If Trim(UCase(Command)) = "/F1" Then
                Function1()
            Else
                If Trim(UCase(Command)) = "/F2" Then
                    Function2()
                Else
                    If Trim(UCase(Command)) = "/F3" Then
                        Function3()
                    End If
                End If
            End If
        End If
  End Sub


* En acceso directo al ejecutable especificar el parametro en destino. Ej:"C:\MiPrograma\MiPRograma.exe" /F2

CREAR EVENTO PARA CONTROL DE USUARIO

'En Control de usuario
Public Event eventClick(ByVal sender As System.Object, ByVal clickeado As Boolean)



Private Sub alHacer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BT.Click, BT2.Click, Label1.Click
        RaiseEvent eventClick(Me, True)
End Sub


'En formulario
Private Sub BtTPV_eventClick(ByVal sender As Object, ByVal clickeado As Boolean) Handles BtTPV1.eventClick
 '...
End Sub

CARGAR RSS

Sub RSS() 
   RssUrl = textbox1.Text
   treeviewMENU.Nodes.Clear()


   Dim doc As New XmlDocument()
   doc.Load(RssUrl)
   Dim navigator As XPathNavigator = doc.CreateNavigator()
   Dim nodes As XPathNodeIterator = navigator.Select("/rss/channel/item/title")


   While nodes.MoveNext


       Dim node As XPathNavigator = nodes.Current
       Dim tmp As String = node.Value.Trim()
       tmp = tmp.Replace(ControlChars.CrLf, "")
       tmp = tmp.Replace(ControlChars.Lf, "")
       tmp = tmp.Replace(ControlChars.Cr, "")
       tmp = tmp.Replace(ControlChars.FormFeed, "")
       tmp = tmp.Replace(ControlChars.NewLine, "")


       treeviewMENU.Nodes.Add(tmp)


   End While


   Dim position As Integer = 0
   Dim nodesLink As XPathNodeIterator = navigator.Select("/rss/channel/item/link")


   While nodesLink.MoveNext


       Dim node As XPathNavigator = nodesLink.Current
       Dim tmp As String = node.Value.Trim()
       tmp = tmp.Replace(ControlChars.CrLf, "")
       tmp = tmp.Replace(ControlChars.Lf, "")
       tmp = tmp.Replace(ControlChars.Cr, "")
       tmp = tmp.Replace(ControlChars.FormFeed, "")
       tmp = tmp.Replace(ControlChars.NewLine, "")


       treeviewMENU.Nodes(position).Tag = tmp


       position += 1


  End While
end sub
            

Private Sub tvwRss_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles treeviewMENU.AfterSelect
        webBrowser1.Navigate(treeviewMENU.SelectedNode.tag)
End Sub


DESPLAZAR CONTROL EN TIEMPO DE EJECUCIÓN (mouse)

Private isDown As Boolean 





Private Sub move_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles move.MouseDown
      If e.Button = Windows.Forms.MouseButtons.Left Then
            isDown = True
      End If
End Sub


Private Sub move_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles move.MouseMove
      If isDown = True Then
            Panel1.Location = New Point(MousePosition.X , MousePosition.Y)
            Panel1.BringToFront()
      End If
End Sub


Private Sub move_MouseUp(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles move.MouseUp
      isDown = False
End Sub

LIBERAR MEMORIA


<DllImport("KERNEL32.DLL", EntryPoint:="SetProcessWorkingSetSize", SetLastError:=True, CallingConvention:=CallingConvention.StdCall)>
Function SetProcessWorkingSetSize(pProcess As IntPtr, dwMinimumWorkingSetSize As Integer, dwMaximumWorkingSetSize As Integer) As Boolean
End Function


<DllImport("KERNEL32.DLL", EntryPoint:="GetCurrentProcess", SetLastError:=True, CallingConvention:=CallingConvention.StdCall)>
Function GetCurrentProcess() As IntPtr
End Function

 'Funcion de liberacion de memoria
 Public Sub ClearMemory()
        Dim pHandle As IntPtr = GetCurrentProcess()
        SetProcessWorkingSetSize(pHandle, -1, -1)
 End Sub

DETECTAR IMPRESORAS

Imports System.Drawing.Printing
        
Dim Impresoras As String

'recorre las impresoras instaladas y añade el name a un combo
For Each Impresoras In PrinterSettings.InstalledPrinters
       cmbImp.Items.Add(Impresoras.ToString)
Next

CONVERTIR IMAGE A STRING / STRING A IMAGE


Public Function imageToByteArray(ByVal imageIn As System.Drawing.Image, ByVal pformato As System.Drawing.Imaging.ImageFormat) As Byte()
        Dim ms As New IO.MemoryStream
        Try
            imageIn.Save(ms, pformato)
        Catch ex As Exception
        End Try
        Return ms.ToArray()
    End Function

    Public Function byteArrayToImage(ByVal byteArrayIn As Byte()) As Image
        Dim returnImage As Image = Nothing
        Try
            Dim ms As New IO.MemoryStream(byteArrayIn)
            returnImage = Image.FromStream(ms)
        Catch ex As Exception
        End Try
        Return returnImage
    End Function



Private Function ArrayToString(ByVal bytes() As Byte, Optional ByVal format As String = Nothing) As String
        If bytes.Length = 0 Then Return String.Empty
        Dim sb As New System.Text.StringBuilder(bytes.Length * 4)
        For Each b As Byte In bytes
            sb.Append(b.ToString(format))
            sb.Append(","c)
        Next
        sb.Length -= 1
        Return sb.ToString()
    End Function


    Private Function StringToArray(ByVal s As String, Optional ByVal style As System.Globalization.NumberStyles = Nothing) As Byte()
        If s.Length = 0 Then Return New Byte() {}
        Dim values() As String = s.Split(","c)
        Dim bytes(values.Length - 1) As Byte
        For index As Integer = 0 To values.Length - 1
            bytes(index) = Byte.Parse(values(index), style)
        Next
        Return bytes
    End Function

'Ejemplo Imagen a String-->
dim strImage as string=""

strImage = ArrayToString(imageToByteArray(My.Resources.miImagen, System.Drawing.Imaging.ImageFormat.Png), Nothing)

FORMULARIO COLOR DEGRADADO

    Public Sub paintForm(ByVal e As System.Windows.Forms.PaintEventArgs, ByVal direccionGradiente As String, ByVal color1 As Color, ByVal color2 As Color, ByVal frm As Form)
        Dim y As Integer = 0
        Dim x As Integer = 0
        Dim ancho As Integer = frm.Width
        Dim alto As Integer = frm.Height
        Dim Y_ As Integer = 0, X_ As Integer = 0
        Dim _Y As Integer = 0, _X As Integer = 0


        Try


            Select Case UCase(direccionGradiente)
                Case "TOP-BOTTOM"
                    _Y = y + alto
                    _X = x
                    Y_ = y
                    X_ = x
                Case "LEFT-RIGHT"
                    _Y = y
                    _X = x + ancho
                    Y_ = y
                    X_ = x
                Case "BOTTOM-TOP"
                    _Y = y
                    _X = x
                    Y_ = y + alto
                    X_ = x
                Case "RIGHT-LEFT"
                    _Y = y
                    _X = x
                    Y_ = y
                    X_ = x + alto
                Case Else
                    _Y = y
                    _X = x
                    Y_ = y + alto
                    X_ = x


            End Select


        Dim colorear As New LinearGradientBrush(New Point(X_, Y_), New Point(_X, _Y), color1, color2)


        e.Graphics.FillRectangle(colorear, x, y, ancho, alto)


        Catch ex As Exception


        End Try
    End Sub


    'Degradar desde el centro del form
    Public Sub paintForm2(ByVal e As System.Windows.Forms.PaintEventArgs, ByVal color1 As Color, ByVal color2 As Color, ByVal frm As Form)


        Dim y As Integer = 0
        Dim x As Integer = 0
        Dim ancho As Integer = frm.Width
        Dim alto As Integer = frm.Height
        Dim _Y As Integer = 0, _X As Integer = 0


        Try
            _Y = y + alto
            _X = x


            Dim colorear As New LinearGradientBrush(New Point(0, 0), New Point(0, _Y / 2), color1, color2)
            Dim colorear2 As New LinearGradientBrush(New Point(0, _Y / 2 - 1), New Point(0, _Y), color2, color1)


            Dim MED As Integer = alto / 2


            e.Graphics.FillRectangle(colorear, x, y, ancho, MED)
            e.Graphics.FillRectangle(colorear2, x, MED, ancho, MED)
        Catch ex As Exception


        End Try
    End Sub

DETECTAR SI UN PUERTO ESTÁ ABIERTO

Imports System.Net.Sockets

Public Function IsPortOpen(ByVal Host As String, ByVal Port As Integer) As Boolean
    Dim m_sck As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
    Try
        m_sck.Connect(Host, Port)
        Return True
    Catch ex As SocketException
        'Código para manejar error del socket (cerrado, conexión rechazada)
    Catch ex As Exception
        'Código para manejar otra excepción
    End Try
    Return False
End Function


 http://www.elguille.info/colabora/2007/thepirat_HilosYpuertos.htm

RELLENAR FORMULARIO PDF (C#) CON itextsharp.dll

http://itextpdf.com/


'relCAMPOSxVALOR = nombrecampo&valorcampo|nombrecampo2&valorcampo2|...
public void writePDF(string relCAMPOSxVALOR, string PDForigen, string PDFfin)
        {
            string pdfTemplate = @PDForigen;
            string newFile = @PDFfin;
            string fileREL = @relCAMPOSxVALOR;


            try
            {
                System.IO.StreamReader sw = new System.IO.StreamReader(fileREL, Encoding.Default);
                relCAMPOSxVALOR = sw.ReadToEnd();
                sw.Close();
                System.IO.File.Delete(fileREL);
            }
            catch
            {
            }


            PdfReader pdfReader = new PdfReader(pdfTemplate);
            PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(
                            newFile, FileMode.Create));


            AcroFields pdfFormFields = pdfStamper.AcroFields;


            try
            {


                string CAMPO;
                string VALOR;


                relCAMPOSxVALOR = relCAMPOSxVALOR.Replace("\r\n", "");


                CAMPO = relCAMPOSxVALOR.Substring(0, relCAMPOSxVALOR.IndexOf("&", 1));
                relCAMPOSxVALOR = relCAMPOSxVALOR.Substring(relCAMPOSxVALOR.IndexOf("&", 1) + 1);
                VALOR = relCAMPOSxVALOR.Substring(0, relCAMPOSxVALOR.IndexOf("|", 1));
                relCAMPOSxVALOR = relCAMPOSxVALOR.Substring(relCAMPOSxVALOR.IndexOf("|", 1) + 1);


                pdfFormFields.SetField(CAMPO, VALOR);


                if (relCAMPOSxVALOR.Length != 0)
                {
                    writePDF_sub(relCAMPOSxVALOR, PDForigen, PDFfin, pdfStamper.AcroFields);
                }
            }
            catch (InvalidCastException e)
            {
                throw (e);    // Rethrowing exception e
            }
                     
            // flatten the form to remove editting options, set it to false
            // to leave the form open to subsequent manual edits
            pdfStamper.FormFlattening = false;


            // close the pdf
            pdfStamper.Close();
        }


        private void writePDF_sub(string relCAMPOSxVALOR, string PDForigen, string PDFfin, AcroFields pdfFormFields)
        {
            string pdfTemplate = @PDForigen;
            string newFile = @PDFfin;


            try
            {
                string CAMPO;
                string VALOR;


                if (relCAMPOSxVALOR.IndexOf("&") > 0 && relCAMPOSxVALOR.IndexOf("|") > 0)
                {
                    CAMPO = relCAMPOSxVALOR.Substring(0, relCAMPOSxVALOR.IndexOf("&", 1));
                    relCAMPOSxVALOR = relCAMPOSxVALOR.Substring(relCAMPOSxVALOR.IndexOf("&", 1) + 1);
                    VALOR = relCAMPOSxVALOR.Substring(0, relCAMPOSxVALOR.IndexOf("|", 1));
                    relCAMPOSxVALOR = relCAMPOSxVALOR.Substring(relCAMPOSxVALOR.IndexOf("|", 1) + 1);


                    pdfFormFields.SetField(CAMPO, VALOR);


                    if (relCAMPOSxVALOR.Length != 0)
                    {
                        writePDF_sub(relCAMPOSxVALOR, PDForigen, PDFfin, pdfFormFields);
                    }
                }
            }
            catch (InvalidCastException e)
            {
                throw (e);    // Rethrowing exception e
            }
            
        }





WinScp (Ejemplos de uso de la herramienta)

http://winscp.net


'Sincronizar directorio FTP con directorio local

 Dim Linea As String = " /command " & Chr(34) & "option batch on" & Chr(34) & " " & Chr(34) & "option confirm off" & Chr(34) & " " & Chr(34) & "reconnecttime 10" & Chr(34) & " " & Chr(34) & "open ftp://" & FTPuser & ":" & FTPpwd & "@" & FTP & Chr(34) & " " & Chr(34) & "synchronize both " & Chr(34) & Chr(34) & LOCALfolder & Chr(34) & Chr(34) & " " & FTPfolder & Chr(34)
       
Dim exe As New Process
exe.StartInfo = New ProcessStartInfo("winscp.exe", Linea)
exe.Start()

'Envío varíos archivos creando directorio en el sitio FTP
Dim T As String = ""
Dim Linea As String = ""


If Trim(RUTAARCHIVO1) <> "" Then T = T & " " & Chr(34) & "put " & Chr(34) & Chr(34) & RUTAARCHIVO1 & Chr(34)
If Trim(RUTAARCHIVO2) <> "" Then T = T & " " & Chr(34) & "put " & Chr(34) & Chr(34) & RUTAARCHIVO2 & Chr(34)
If Trim(RUTAARCHIVO3) <> "" Then T = T & " " & Chr(34) & "put " & Chr(34) & Chr(34) & RUTAARCHIVO3 & Chr(34)
If Trim(RUTAARCHIVO4) <> "" Then T = T & " " & Chr(34) & "put " & Chr(34) & Chr(34) & RUTAARCHIVO4 & Chr(34)
     
Linea = " /console /command " & Chr(34) & "option batch on" & Chr(34) & " " & Chr(34) & "option confirm off" & Chr(34) & " " & Chr(34) & "open ftp://" & FTPuser & ":" & FTPpwd & "@" & FTP & Chr(34) & " " & Chr(34) & "mkdir " & FTPdirectorio & " " & Chr(34) & "cd " & FTPdirectorio & Chr(34) & " " & Chr(34) & T & " " & Chr(34) & " exit" & Chr(34) & Chr(34) & Chr(34)
        
Dim exe As New Process
exe.StartInfo = New ProcessStartInfo("winscp.exe", Linea)
exe.Start()