EXTRAER CONTENIDO (TEXTO) DE UN ARCHIVO PDF (con iTextSharp.dll)

Dim oReader As New iTextSharp.text.pdf.PdfReader(PdfFileName)
Dim its As New iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy

DocumentText = iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(oReader, 1, its)


oReader.Close()

'http://sourceforge.net/projects/itextsharp/

MOSTRAR TECLADO VIRTUAL (tabtip.exe)

Private TabTipProcess As Process
Private Sub closeTabTip()
   If tdbConfig.enableVirtualKeyboard Then
      If Me.TabTipProcess IsNot Nothing AndAlso Me.TabTipProcess.HasExited Then
          TabTipProcess.Close()
      End If
    End If
End Sub

Private Sub openTabTip()
  If tdbConfig.enableVirtualKeyboard Then
     Dim progFiles As String = "C:\Program Files\Common Files\Microsoft Shared\ink"
     Dim onScreenKeyboardPath As String = System.IO.Path.Combine(progFiles, "TabTip.exe")
     Me.TabTipProcess = Process.Start(onScreenKeyboardPath)     
  End If

End Sub

DETECTAR ROTACIÓN PANTALLA

Inherits System.Windows.Forms.Form

Private Sub form_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

        AddHandler Microsoft.Win32.SystemEvents.DisplaySettingsChanged,
      AddressOf DetectScreenRotation

End Sub

Public Sub DetectScreenRotation(ByVal sender As System.Object,
      ByVal e As System.EventArgs)
        Dim theScreenBounds As Rectangle
        theScreenBounds = Screen.GetBounds(Screen.PrimaryScreen.Bounds)

        If (theScreenBounds.Height > theScreenBounds.Width) Then
           'acción para pantalla en horizontal
         Else
           'acción para pantalla en vertical
        End If
    End Sub
  

End Class

EXPORTAR DATASET A EXCEL CON CarlosAg.dll

http://www.carlosag.net/tools/excelxmlwriter/

Imports CarlosAg.ExcelXmlWriter


 Public Sub returnDatasetSQL(queryString As String, cadenaCONN As String, ByRef ds As DataSet)
        Try

            Dim myConnection As SqlConnection
            Dim myCommand As SqlCommand
            Dim da As SqlDataAdapter


            myConnection = New SqlConnection(cadenaCONN)

            myConnection.Open()
            myCommand = New SqlCommand(queryString, myConnection)

            da = New SqlDataAdapter(myCommand)

            ds = New DataSet()
            da.Fill(ds)

            myConnection.Close()

        Catch ex As Exception
            writeInLogFile(ex.Message, "error")
        End Try
  End Sub



Private Sub loadEXCEL(sessionID As String, CONN As String)

       Dim query As String = "Select distinct(headerMISDATOS),nMISDATOS from MISDATOS where SessionID='" & sessionID & "' order by nMISDATOS "
        
        Dim DS As New DataSet
        returnDatasetSQL(query, CONN, DS)

        For i = 0 To DS.Tables(0).Rows.Count - 1
            ReDim Preserve headerDATOS(i)
            headerDATOS(i) = DS.Tables(0).Rows(i).Item("headerMISDATOS")
        Next

        query = "Select * from MISDATOS where SessionID='" & sessionID & "' order by nMISDATOS"
        returnDatasetSQL(query, CONN, DS)

        Try


            If DS.Tables.Count > 0 Then
                If DS.Tables(0).Rows.Count > 0 Then

                    Dim book As New Workbook()

                    book.Properties.Author = "Yo Mismo"
                    book.Properties.Title = "Mi Excel"
                    book.Properties.Created = DateTime.Now

                    Dim style As WorksheetStyle = book.Styles.Add("HeaderStyle")
                    style.Font.Bold = True

                    Dim style2 As WorksheetStyle = book.Styles.Add("DefaultStyle")
                    style2.Font.Bold = False

                    Dim style3 As WorksheetStyle = book.Styles.Add("FooterStyle")
                    style3.Font.Italic = True

                    Dim styleGREEN As WorksheetStyle = book.Styles.Add("GreenStyle")
                    styleGREEN.Font.Color = "#000000"
                    styleGREEN.Interior.Color = "#31B404"
                    styleGREEN.Interior.Pattern = StyleInteriorPattern.Solid

                    Dim styleYELLOW As WorksheetStyle = book.Styles.Add("YellowStyle")
                    styleYELLOW.Font.Color = "#000000"
                    styleYELLOW.Interior.Color = "#FFBF00"
                    styleYELLOW.Interior.Pattern = StyleInteriorPattern.Solid

                    Dim styleRED As WorksheetStyle = book.Styles.Add("RedStyle")
                    styleRED.Font.Color = "#FFFFFF"
                    styleRED.Interior.Color = "#FE2E2E"
                    styleRED.Interior.Pattern = StyleInteriorPattern.Solid

                    createWorksheet(book, DS, "MIS DATOS EN LIBRO 1")
                    createWorksheet(book, DS, "MIS DATOS EN LIBRO 2")
                   

                    book.Save(System.AppDomain.CurrentDomain.BaseDirectory & "DATA_SAVED/" & sessionID & ".xls")

                    
                End If
            End If

        Catch ex As Exception
            writeInLogFile(ex.Message, "error")
        End Try
   End Sub


Sub createWorksheet(book As Workbook, ds As DataSet, NameLIBRO As String)

        Dim sheet As Worksheet = book.Worksheets.Add(NameLIBRO)


        Dim rowHeader As WorksheetRow = sheet.Table.Rows.Add()
        rowHeader.Cells.Add(New WorksheetCell("A continuación la tabla de MIS DATOS", "HeaderStyle"))
        rowHeader = sheet.Table.Rows.Add()


        Dim _i As Integer

        For _i = 0 To headerDATOS.Length - 1
                  rowHeader.Cells.Add(New WorksheetCell(headerDATOS(_i), "HeaderStyle"))
        Next

        rowHeader = Nothing




        Dim row As New WorksheetRow

        For i = 0 To ds.Tables(0).Rows.Count - 1

                
        If CDbl(ds.Tables(0).Rows(i).Item("valor")) < 70 Then
                backcolor = "RedStyle"
        Else
                If CDbl(ds.Tables(0).Rows(i).Item("valor")) >= 70 Then
                    If CDbl(ds.Tables(0).Rows(i).Item("valor")) >= 100 Then
                        backcolor = "GreenStyle"
                    Else
                        backcolor = "YellowStyle"
                    End If
                End If
        End If

        row.Cells.Add(ds.Tables(0).Rows(i).Item("valor"), DataType.Number, backcolor)

           
        Next


    End Sub

TRABAJANDO CON BLOBS DE AZURE


'No olvides referenciar Microsoft.WindowsAzure.StorageClient


Imports Microsoft.WindowsAzure
Imports Microsoft.WindowsAzure.StorageClient


Private Function enviarBLOB() As Boolean

        Dim Path As String = "C:\Temp\prova.pdf"
        Dim FS As FileStream = File.OpenRead(Path)

        Dim StorageAccount As CloudStorageAccount
        Dim BlobClient As CloudBlobClient
        Dim BlobContainer As CloudBlobContainer

        Dim sendOK As Boolean = False

        Try
            StorageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=" & AccountName & ";AccountKey=" & AccountKey)

            BlobClient = StorageAccount.CreateCloudBlobClient
            BlobClient.Timeout = New System.TimeSpan(1, 0, 0)
            BlobClient.ParallelOperationThreadCount = 2
            BlobContainer = BlobClient.GetContainerReference(ContainerName)

            Dim myGUID As System.Guid = System.Guid.NewGuid()
            Dim sGUID As String = myGUID.ToString()

            Dim Blob As CloudBlob = BlobContainer.GetBlobReference(sGUID)

            Blob.UploadFromStream(FS)

            Blob.Metadata("no") = "12134"
            Blob.Metadata("Nombre") = "Pepe"
            Blob.Metadata("timestamp") = Now
            Blob.SetMetadata()

            Blob.Properties.ContentType = "application/pdf"
            Blob.Properties.ContentEncoding = "base64"
            Blob.SetProperties()

            sendOK = True

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

        Return sendOK
End Function


Private Function urlBLOB_paraDescarga(ContainerName As String, Filename As String, AccountName As String, AccountKey As String, accessMinutesExpiry As Integer) As String

        Dim StorageAccount As CloudStorageAccount
        Dim BlobClient As CloudBlobClient
        Dim BlobContainer As CloudBlobContainer
        Dim Options As New BlobRequestOptions

        StorageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=" & AccountName & ";AccountKey=" & AccountKey)
        BlobClient = StorageAccount.CreateCloudBlobClient
        BlobClient.Timeout = New System.TimeSpan(1, 0, 0)
        BlobClient.ParallelOperationThreadCount = 2
        BlobContainer = BlobClient.GetContainerReference(ContainerName)
        Dim Blob As CloudBlob = BlobContainer.GetBlobReference(Filename)


        Dim SHaccesPolicy As New SharedAccessPolicy()
        SHaccesPolicy.SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(accessMinutesExpiry)
        SHaccesPolicy.Permissions = SharedAccessPermissions.Read


        Dim signature As String = Blob.GetSharedAccessSignature(SHaccesPolicy)

        Return Blob.Uri.AbsoluteUri + signature

    End Function

Incluír WebKit en el proyecto

WEBKIT:

1. Descargar el componente http://webkitdotnet.sourceforge.net/downloads.php

2. Copia todos los ficheros de WebKit.NET-0.4-bin-cairo\bin excepto el .exe dentro del "..\bin\debug\" del proyecto

3. Agregar la referencia a “WebkitBrowser.dll”

4. Agregar la anterior dll en el cuadro de Herramientas ... "Elegir Elementos/ Componentes de .Net Framework / Examinar..."

5. Arrastra el componente al diseño del furmulario

Private Sub form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
WebKitBrowser1.Navigate("http://www.google.es")
End Sub



ClientScriptManager PARA AGREGAR CONTENIDO Y SCRIPTS A LA PÁGINA


'crear contenido web desde servidor
Dim texto as string = "
" & vbNewLine & _

               "Hola Mundo
" & vbNewLine & _     

               "
"Dim cs As ClientScriptManager = Page.ClientScript


If Not cs.IsStartupScriptRegistered(Me.[GetType](), "HolaMundo") Then
                cs.RegisterStartupScript(Me.[GetType](), "HolaMundo", texto)
End If


'crear y ejecutar script
Dim texto as string= "alert('Hello World');";
Dim cs As ClientScriptManager = Page.ClientScript


cs.RegisterStartupScript( Me.[GetType](),"HolaMundo2",texto,true);

LEER Y RECORRER LOS FICHEROS DE UN DIRECTORIO


Dim Files As String(), File As String


Files = IO.Directory.GetFiles(System.AppDomain.CurrentDomain.BaseDirectory & "/DATA", "*.xml")
     
For Each File In Files
     cmbConnect.Items.Add(IO.Path.GetFileNameWithoutExtension(File))
     My.Application.DoEvents()
Next

CONTROLAR EL CURSOR Y EVENTOS DEL RATÓN


'RATÓN ->
    DllImport ( "User32.dll" )> _
    Public Shared Function SetCursorPos ( ByVal X Como Entero , ByVal Y Como Entero ) Como Largo
    Fin Función
    DllImport ( "User32.dll" )> _
    Public Shared Function GetCursorPos ( ByRef lpPoint Como Point ) Como Largo
    Fin Función
    DllImport ( "User32.dll" )> _
    Public Shared Sub mouse_event( ByVal dwFlags As Integer , ByVal dx As Integer , ByVal dy As Integer , ByVal cButtons As Integer , ByVal dwExtraInfo As IntPtr )
    End Sub

    Dim URLini Como Cadena

    Public Const MOUSEEVENTF_LEFTDOWN = & H2 'botón izquierdo
    Public Const MOUSEEVENTF_LEFTUP = & H4 'botón izquierdo hasta
    Public Const MOUSEEVENTF_MIDDLEDOWN = & H20 'botón del medio hacia abajo
    Public Const MOUSEEVENTF_MIDDLEUP = & H40 'botón central hasta
    Public Const MOUSEEVENTF_RIGHTDOWN = & H8 'botón de la derecha abajo
    Public Const MOUSEEVENTF_RIGHTUP = & H10 'botón hasta

    '<- font="" rat="">

Private Sub ...
'Cursor 1 Posicionamos el
SetCursorPos (Me.Width - 210, 165)
'2 Pulsamos boton Derecho del Ratón
mouse_event (MOUSEEVENTF_LEFTDOWN, Me.Width - 215, 165, 0, 0)
mouse_event (MOUSEEVENTF_LEFTUP, Me.Width - 215, 165, 0, 0)
End Sub

DESACTIVAR TECLAS Y RATÓN AL USUARIO

 Private Declare Function BlockInput Lib "user32" (ByVal fBlock As Long) As Long


 Private Sub  .....
        BlockInput(True) 'bloqueamos las interacciones del usuario 
         '<--- llamadas a las rutinas que deseamos ejecutar con las interacciones del usuario bloqueadas--->
        BlockInput(False)' desbloqueamos las interacciones del usuario
  End Sub 

WEBBROWSER (EJEMPLOS DE USO)

Dim txtUser_Element As HtmlElemen
Dim txtPass_Element As HtmlElement
Dim btEntrar_Element As HtmlElement

'Capturar elemento por el ID
txtUser_Element = WebBrowserEx1.Document.GetElementById("txtUsuario")
txtPass_Element = WebBrowserEx1.Document.GetElementById("txtPassword")
btEntrar_Element = WebBrowserEx1.Document.GetElementById("btnEntrar")
'Por posición del tipo elemento-> .Document.GetElementsByTagName("INPUT").Item(8)

'Informar txt a traves del atributo value
txtUser_Element.SetAttribute("value", tdbConfig.SegurosVF.userShop)
txtPass_Element.SetAttribute("value", tdbConfig.SegurosVF.passShop)

'llamada al evento click
btEntrar_Element.RaiseEvent("onclick")

'-------------------------------------

'Capturar contenido txt a través del atributo value

Dim txtCod_Element As HtmlElement
txtCodSAP_Element = WebBrowserEx1.Document.GetElementById("txtCod")
msgbox(txtCod_Element.GetAttribute("value"))

'--------------------------------------

'Pulsar botón mediante InvokeMember
Dim btBuscar_Element As HtmlElement

btBuscar_Element = WebBrowserEx1.Document.GetElementById("btnBuscar")
btBuscar_Element.InvokeMember("click")

'--------------------------------------

'Capturar contenido del desplegable combo del indice seleccionado
Dim cmbFact_Element As HtmlElement, i as integer
cmbFact_Element = WebBrowserEx1.Document.GetElementById("cmbFact")
i = cmbFact_Element.GetAttribute("selectedindex")
msgbox(cmbFact_Element.Children(i).InnerText)

'Seleccionar indice del desplegable combo
Dim cmbProducto_Element As HtmlElement
cmbProducto_Element = WebBrowserEx1.Document.GetElementById("cmbProducto")
cmbProducto_Element.SetAttribute("selectedindex", 3)
cmbProducto_Element.RaiseEvent("onchange")

'---------------------------------------
'ZOOM

Private Enum Exec
     OLECMDID_OPTICAL_ZOOM = 63
End Enum
Private Enum ExecOpt
     OLECMDEXECOPT_DODEFAULT = 0
     OLECMDEXECOPT_PROMPTUSER = 1
     OLECMDEXECOPT_DONTPROMPTUSER = 2
     OLECMDEXECOPT_SHOWHELP = 3
End Enum


Dim Res As Object = Nothing
Dim MyWeb As Object
MyWeb = Me.WebBrowserEx1.ActiveXInstance
MyWeb.ExecWB(Exec.OLECMDID_OPTICAL_ZOOM, _
 ExecOpt.OLECMDEXECOPT_DONTPROMPTUSER, 50, IntPtr.Zero)

'Cambiar tamaño de la fuente
-----------------------------------
WebBrowserEx1.Document.Body.Style = "font-size:11px;"

OBTENER IP DE LA CONEXIÓN DEL CLIENTE


Dim ClientIP, Forwaded, RealIP


RealIP = ""


ClientIP = Request.ServerVariables("REMOTE_ADDR")
If ClientIP <> "" Then
            RealIP = ClientIP
Else
    'El usuario está accediendo a través de un Proxy.
    Forwaded = Request.ServerVariables("HTTP_X-Forwarded-For")
    If Forwaded <> "" Then RealIP = Forwaded
End If

LABEL FONDO TRANSPARENTE SOBRE OBJETO CON IMAGEN


label1.Parent = Picturebox1
label1.BackColor = Color.Transparent
label1.Location = New Point(0, 0)'Punto del objeto (en este caso picturebox1)donde se sitúa la etiqueta 

NOMBRE CORTO DE RUTA (C#)


 //Short Path Name -->
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern uint GetShortPathName(
[MarshalAs(UnmanagedType.LPTStr)]
string lpszLongPath,
[MarshalAs(UnmanagedType.LPTStr)]
StringBuilder lpszShortPath,
uint cchBuffer);


[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
       static extern uint GetShortPathName(string lpszLongPath, char[] lpszShortPath, int cchBuffer);
// <-- Short Path Name



 public string ToShortPathName(string longName)
{
    uint bufferSize = 256;
    StringBuilder shortNameBuffer = new StringBuilder((int)bufferSize);
    uint result = GetShortPathName(longName, shortNameBuffer, bufferSize);
    return shortNameBuffer.ToString();
}


public string ShortPath(string longpath)
{
    char[] buffer = new char[256];
    GetShortPathName(longpath, buffer, buffer.Length);
    return new string(buffer);
}

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();
    }
}