UNIR PDFs usando iTextSharp

'unir documentos usando iTextDoNEt --> http://sourceforge.net/projects/itextdotnet/
'función llamada

  public void combinarPDFs(string basePath, string filePDF1, string filePDF2, string newFilePDF)
{
    PdfMerge newPDF = new PdfMerge();


    newPDF.AddDocument(Path.Combine(basePath, filePDF1));
    newPDF.AddDocument(Path.Combine(basePath, filePDF2));
    newPDF.Merge(basePath + newFilePDF);
}
'Clase
using System;
using System.Collections.Generic;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
public class PdfMerge
{
    private BaseFont baseFont;
    private bool enablePagination = false;
    private readonly List documents;
    private int totalPages;
    public BaseFont BaseFont
    {
        get { return baseFont; }
        set { baseFont = value; }
    }
    public bool EnablePagination
    {
        get { return enablePagination; }
        set
        {
            enablePagination = value;
            if (value && baseFont == null)
                baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        }
    }
    public List Documents
    {
        get { return documents; }
    }
    public void AddDocument(string filename)
    {
        documents.Add(new PdfReader(filename));
    }
    public void AddDocument(Stream pdfStream)
    {
        documents.Add(new PdfReader(pdfStream));
    }
    public void AddDocument(byte[] pdfContents)
    {
        documents.Add(new PdfReader(pdfContents));
    }
    public void AddDocument(PdfReader pdfDocument)
    {
        documents.Add(pdfDocument);
    }
    public void Merge(string outputFilename)
    {
        Merge(new FileStream(outputFilename, FileMode.Create));
    }
    public void Merge(Stream outputStream)
    {
        if (outputStream == null || !outputStream.CanWrite)
            throw new Exception("OutputStream es nulo o no se puede escribir en éste.");

        Document newDocument = null;
        try
        {
            newDocument = new Document();
            PdfWriter pdfWriter = PdfWriter.GetInstance(newDocument, outputStream);
            newDocument.Open();
            PdfContentByte pdfContentByte = pdfWriter.DirectContent;
            if (EnablePagination)
                documents.ForEach(delegate(PdfReader doc)
                                  {
                                      totalPages += doc.NumberOfPages;
                                  });
            int currentPage = 1;
            foreach (PdfReader pdfReader in documents)
            {
                for (int page = 1; page <= pdfReader.NumberOfPages; page++)
                {
                    newDocument.NewPage();
                    PdfImportedPage importedPage = pdfWriter.GetImportedPage(pdfReader, page);
                    pdfContentByte.AddTemplate(importedPage, 0, 0);
                    if (EnablePagination)
                    {
                        pdfContentByte.BeginText();
                        pdfContentByte.SetFontAndSize(baseFont, 9);
                        pdfContentByte.ShowTextAligned(PdfContentByte.ALIGN_CENTER,string.Format("{0} de {1}", currentPage++, totalPages), 520, 5, 0);
                        pdfContentByte.EndText();
                    }
                }
            }
        }
        finally
        {
            outputStream.Flush();
            if (newDocument != null)
                newDocument.Close();
            outputStream.Close();
        }
    }
    public PdfMerge()
    {
        documents = new List();
    }
}

IMPRIMIR FICHERO


Public Sub impresionaDoc(RutaFichero As String, NombreFichero as String, impresora As String)
        Try
            Dim intProcessID As Integer
            intProcessID = Shell(RutaFichero  & " """ & NombreFichero & """" & " """ & impresora & """", AppWinStyle.NormalFocus, False)


        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
End Sub

DESCARGAR FICHERO


Dim U As String = "http://www.webdescargadelfichero.com/ficheroparadescarga.pdf"  'url descarga
Dim F As String = "ficherodescargado.pdf"  'nombre fichero.extensión


If Not System.IO.File.Exists(F) then

 'Opción 1
 My.Computer.Network.DownloadFile(U ,F )

 'Opcion 2
 'con webClient
 Dim fileReader As New System.IO.WebClient()
 fileReader.DownloadFile(U, F)

end if

PASO DE DATOS DEL NAVEGADOR AL SERVIDOR y viceversa


Desde el cliente (código html):
         ...  a href='contactfile.aspx?idCliente=12569&nif=79589632J'  ...
Recepción de los datos en servidor
     Request.QueryString("idCliente").ToString
    Request.QueryString("nif").ToString


Desde el servidor al cliente:
Dim scriptHeader As String = variableTextoHtml


Dim csnameHeader As [String] = "ContactoHeader"
Dim cstypeHeader As Type = Me.[GetType]()


Dim csHeader As ClientScriptManager = Page.ClientScript


If Not csHeader.IsStartupScriptRegistered(cstypeHeader, csnameHeader) Then
           csHeader.RegisterStartupScript(cstypeHeader, csnameHeader, scriptHeader)
End If

ENCRIPTACIÓN SHA-1 (C#)



using System.Security;
using System.Security.Cryptography; 

public string HashString(string str) 
{
     SHA1 sha1 = SHA1Managed.Create();
     ASCIIEncoding encoding = new ASCIIEncoding();
     byte[] stream = null;
     StringBuilder sb = new StringBuilder();
     stream = sha1.ComputeHash(encoding.GetBytes(str));
     for (int i = 0; i < stream.Length; i++) sb.AppendFormat("{0:x2}", stream[i]);


     return sb.ToString(); 
}

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