Advertisement
Guest User

Untitled

a guest
Aug 3rd, 2018
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 75.01 KB | None | 0 0
  1. Imports iTextSharp.text
  2. Imports iTextSharp.text.api
  3. Imports iTextSharp.text.pdf
  4. Imports iTextSharp.text.pdf.parser
  5. Imports System.Text
  6. Imports System.IO
  7. Imports System
  8. Imports System.Data
  9. Imports System.Data.OleDb
  10. Imports System.Text.RegularExpressions
  11. Imports System.Data.SqlClient
  12. Imports Microsoft.VisualBasic.CompilerServices
  13. Imports System.Configuration
  14. Imports System.DirectoryServices.AccountManagement
  15.  
  16. Public Class Visure
  17.     'Il programma consente la lettura di una serie di file pdf inseriti in input contenenti le visure P.R.A.
  18.     'riporta i dati acquisiti all’interno del file excel del Cliente anch’esso richiesto in input.
  19.     'Il programma elaborerà ogni file pdf contenuto nella cartella indicata.
  20.     'Il pogramma esegue il caricamento dei dati elaborati sul Database specificato nel file .config
  21.     'N.B. Creare le tabelle: LOG_Operazioni, TB_Operatori, Testate_Excel, Anagrafica, Dettagli, VISURE_PDF se non presenti nel DB.
  22.     'La stringa per la creazioni delle sopracitate tabelle si troveranno nel file .config
  23.  
  24.     Public Shared CnSql As SqlConnection
  25.     Dim DirPdf As String
  26.     Dim fileExcel As String
  27.     Dim nProprietari As Integer
  28.     Dim Tab As String
  29.     Dim errors As Integer
  30.     Dim TempTab As String
  31.     Dim TempTabColName(100) As String
  32.     Dim DettagliDtTab As New System.Data.DataTable
  33.     Dim indexColTempTab As Integer
  34.     Dim G_USERFULLNAME As String
  35.     Dim G_ACCOUNTWINDOWS As String
  36.     Dim G_IDOPERATORE As String
  37.     Dim saveExcelDataGrid As System.Data.DataTable
  38.     Dim connectionString As String = My.Settings.ConnString
  39.  
  40.  
  41.     Private Sub Exec_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Exec.Click
  42.         'Inizia l'esecuzione del programma. Inserimento dei log relativi. Setup dei nomi delle tabelle presi dal file .config e controllo sui file di input
  43.         Try
  44.             'setup
  45.             errors = 0
  46.             RegistraLog("Elaborazione iniziata sul programma Visure_Pdf_Excel", "NULL")
  47.             Dim result As DialogResult = Windows.Forms.DialogResult.Yes
  48.             Tab = My.Settings.PDFtab
  49.             TempTab = My.Settings.TempTab
  50.             ProgressBar1.Step = 1
  51.  
  52.             'Controllo sui file di input
  53.             If fileExcel = "" Or DirPdf = "" Then
  54.                 MsgBox("Selezionare un file excel ed una cartella pdf prima di continuare.")
  55.                 Exit Sub
  56.             End If
  57.  
  58.             If Path.GetFileNameWithoutExtension(fileExcel).Contains("VISURE_PDF") Then
  59.                 result = MessageBox.Show("Un file excel già elaborato è stato selezionato, sei sicuro di voler continuare?", "Attenzione!", MessageBoxButtons.YesNo)
  60.             End If
  61.  
  62.             If result = DialogResult.Yes Then
  63.                 ProgressBar1.Visible = True
  64.                 ProgressBar1.Step = 10
  65.                 ProgressBar1.PerformStep()
  66.                 ProgressBar1.Value = 0
  67.                 TableDeleter(TempTab)
  68.                 CnSqlOpen(connectionString)
  69.                 LeggiRinominaPdfByTarga(DirPdf)
  70.             Else
  71.                 Exit Sub
  72.             End If
  73.         Catch ex As Exception
  74.             MsgBox("Un errore è stato rilvevato durante l'elaborazione dei file. Errore:" & vbLf & ex.Message)
  75.             Err.Clear()
  76.         End Try
  77.     End Sub
  78.  
  79.     Public Function LeggiRinominaPdfByTarga(ByVal sFolderPdfs As String) As Boolean
  80.         'Lettura dei pdf contenuti all'interno della cartella sFolderPdfs e creazione del file di testo relativo utilizzato in seguito per l'estrazione dei dati
  81.         ProgressBar1.Step = 1
  82.         Dim dir As DirectoryInfo
  83.         Dim file As FileInfo
  84.         Dim s As String
  85.         Dim sFileInput As String
  86.         Dim sFileTxt As String
  87.         Dim TableToExcel As New Data.DataTable
  88.         Dim counter As Integer = 0
  89.         Try
  90.             dir = New DirectoryInfo(sFolderPdfs)
  91.             'Inizio ciclo for per la scansione di ogni singolo file pdf.
  92.             'All'interno del ciclo verrà richiamato il metodo LeggiTargaEDateDaPdf per l'estrazione dei dati.
  93.             For Each file In dir.GetFiles("*.PDF", SearchOption.TopDirectoryOnly)
  94.  
  95.                 sFileInput = file.Directory.ToString + "\" + file.Name.ToString
  96.                 sFileTxt = file.Directory.ToString + "\" + file.Name.ToString.Replace("PDF", "txt")
  97.                 'Creazione del file txt sulla base del file pdf
  98.                 s = ParsePdfText(sFileInput)
  99.  
  100.                 My.Computer.FileSystem.WriteAllText(sFileTxt, s, False)
  101.  
  102.                 LeggiTargaEDateDaPdf(sFileTxt, sFileInput)
  103.  
  104.                 counter += 1
  105.                 If counter Mod 20 = 0 Then
  106.                     ProgressBar1.PerformStep()
  107.                 End If
  108.             Next file
  109.             'Fine della lettura dei file pdf e relativo inserimento dei dati nelle opportune tabelle.
  110.             'Eliminazione record duplicati all'interno della tabella VISURE_PDF.
  111.             CancellaDuplicatiIdTarga(Tab)
  112.  
  113.             'Inizio lettura del file excel
  114.             ExcelManagment(fileExcel)
  115.  
  116.             Return 0
  117.         Catch ex As Exception
  118.             Return 0
  119.         End Try
  120.  
  121.     End Function
  122.  
  123.     Public Shared Function ParsePdfText(ByVal sourcePDF As String, _
  124.                                    Optional ByVal fromPageNum As Integer = 0, _
  125.                                    Optional ByVal toPageNum As Integer = 0) As String
  126.         'Lettura del file pdf sourcePDF selezionato dal metodo LeggiRinominaPdfbyTarga e scrittura del file .txt utilizzto in seguito per la lettura dei dati.
  127.         Dim sb As New System.Text.StringBuilder
  128.         Try
  129.             Dim reader As New iTextSharp.text.pdf.PdfReader(sourcePDF)
  130.             Dim pageBytes() As Byte = Nothing
  131.             Dim token As iTextSharp.text.pdf.PRTokeniser = Nothing
  132.             Dim tknType As Integer = -1
  133.             Dim tknValue As String = String.Empty
  134.  
  135.             If fromPageNum = 0 Then
  136.                 fromPageNum = 1
  137.             End If
  138.             If toPageNum = 0 Then
  139.                 toPageNum = reader.NumberOfPages
  140.             End If
  141.  
  142.             If fromPageNum > toPageNum Then
  143.                 Throw New ApplicationException("Errore parametri")
  144.             End If
  145.  
  146.             For i As Integer = fromPageNum To toPageNum Step 1
  147.                 pageBytes = reader.GetPageContent(i)
  148.                 If Not IsNothing(pageBytes) Then
  149.  
  150.                     token = New iTextSharp.text.pdf.PRTokeniser(pageBytes)
  151.                     While token.NextToken()
  152.                         tknType = token.TokenType()
  153.                         tknValue = token.StringValue
  154.                         Select Case tknType
  155.  
  156.                             Case 1  ' iTextSharp.text.pdf.PRTokeniser.TK_NUMBER
  157.                                 Dim dValue As Double
  158.                                 Dim r As Double
  159.                                 If Double.TryParse(tknValue, dValue, Nothing, r) Then
  160.                                     If dValue < -8000 Then
  161.                                         sb.Append(r)
  162.                                     End If
  163.                                 End If
  164.  
  165.                             Case 2  ' iTextSharp.text.pdf.PRTokeniser.TK_STRING
  166.                                 sb.Append(token.StringValue)
  167.                             Case 3  ' iTextSharp.text.pdf.PRTokeniser.TK_NAME
  168.                                 '
  169.                             Case 4  ' iTextSharp.text.pdf.PRTokeniser.TK_COMMENT    
  170.                                 '
  171.                             Case 5  ' iTextSharp.text.pdf.PRTokeniser.TK_START_ARRAY
  172.                                 '
  173.                             Case 6  ' iTextSharp.text.pdf.PRTokeniser.TK_END_ARRAY
  174.                                 sb.Append(Environment.NewLine)
  175.                                 'sb.Append(" ")
  176.                             Case 7  ' iTextSharp.text.pdf.PRTokeniser.TK_START_DIC
  177.                                 '
  178.                             Case 8  ' iTextSharp.text.pdf.PRTokeniser.TK_END_DIC
  179.                                 '
  180.                             Case 9  ' iTextSharp.text.pdf.PRTokeniser.TK_REF
  181.                                 '
  182.  
  183.                             Case 10 ' iTextSharp.text.pdf.PRTokeniser.TK_OTHER
  184.                                 Select Case tknValue
  185.                                     Case "TJ"
  186.                                         sb.Append(" ")
  187.                                     Case "ET"      ', "TD", "Td" , "Tm" , "T*"
  188.                                         sb.Append(Environment.NewLine)
  189.                                 End Select
  190.  
  191.                         End Select
  192.  
  193.  
  194.                     End While
  195.                 End If
  196.             Next i
  197.             reader.Close()
  198.         Catch ex As Exception
  199.             MsgBox("Un errore è stato rilvevato in ParePdfText. Errore:" & vbLf & ex.Message)
  200.             Err.Clear()
  201.             Return String.Empty
  202.         End Try
  203.  
  204.         Return sb.ToString()
  205.  
  206.     End Function
  207.  
  208.     Public Sub LeggiTargaEDateDaPdf(ByVal sfileTxtInput As String, ByVal sfilePdfInput As String)
  209.         'Lettura del file txt sfileTxtInput prodotto dal pdf tramite il metodo ParsePdfText, estrazione e caricamento dei dati nella tabella VISURE_PDF
  210.         'Il seguente metodo viene richiamato all'interno di un ciclo FOR nel metodo LeggiRinominaPdfByTarga
  211.         Dim FilePdf As FileInfo
  212.         Dim sRiga As String
  213.         Dim sTarga As String
  214.         Dim sId As String
  215.         Dim FileTxt As FileInfo
  216.         FileTxt = New System.IO.FileInfo(sfileTxtInput)
  217.         Dim reader As StreamReader
  218.         Dim readerDate As StreamReader
  219.         sId = FileTxt.Name.Substring(0, FileTxt.Name.LastIndexOf(".").ToString)
  220.         FilePdf = New System.IO.FileInfo(sfilePdfInput)
  221.         Dim text As New StringBuilder()
  222.         reader = My.Computer.FileSystem.OpenTextFileReader(sfileTxtInput)
  223.         readerDate = My.Computer.FileSystem.OpenTextFileReader(sfileTxtInput)
  224.         Try
  225.             'Inizio lettura dati e creazione query di INSERT
  226.             Dim sqlIns As String = "INSERT INTO " & Tab & " VALUES(@Targa, "
  227.             Dim MyCmdIns As New SqlCommand(sqlIns, CnSql)
  228.             Dim DateTrovate As MatchCollection = Regex.Matches(text.ToString, "[0-9]*/[0-9]*/[0-9]{4}")
  229.             sRiga = reader.ReadLine.TrimStart
  230.             sTarga = Mid(sRiga, 22, 7)
  231.             MyCmdIns.Parameters.Add("@Targa", SqlDbType.NVarChar)
  232.             MyCmdIns.Parameters("@Targa").Value = sTarga
  233.  
  234.  
  235.  
  236.             'Lettura campi scelti e setup sqlCmd
  237.             Dim telaioInizio As Integer
  238.             Dim telaioFine As Integer
  239.             Dim telaio As String
  240.  
  241.             telaioInizio = sRiga.IndexOf("Telaio") + 6
  242.             telaioFine = sRiga.IndexOf("Fabbrica / Tipo")
  243.             telaio = sRiga.Substring(telaioInizio, telaioFine - telaioInizio)
  244.             sqlIns = sqlIns & "@Telaio, "
  245.             MyCmdIns.Parameters.Add("@Telaio", SqlDbType.NVarChar)
  246.             MyCmdIns.Parameters("@Telaio").Value = telaio
  247.  
  248.  
  249.  
  250.             Dim produttoreInizio As Integer
  251.             Dim produttoreFine As Integer
  252.             Dim produttore As String
  253.  
  254.             produttoreInizio = sRiga.IndexOf("Fabbrica / Tipo") + 15
  255.             produttoreFine = sRiga.IndexOf("Data Immatricolazione")
  256.             produttore = sRiga.Substring(produttoreInizio, produttoreFine - produttoreInizio)
  257.             sqlIns = sqlIns & "@Produttore, "
  258.             MyCmdIns.Parameters.Add("@Produttore", SqlDbType.NVarChar)
  259.             MyCmdIns.Parameters("@Produttore").Value = produttore
  260.  
  261.  
  262.  
  263.             Dim immatricolazioneInizio As Integer
  264.             Dim immatricolazione As String
  265.  
  266.             immatricolazioneInizio = sRiga.IndexOf("Data Immatricolazione") + Len("Data Immatricolazione")
  267.             immatricolazione = sRiga.Substring(immatricolazioneInizio, 10)
  268.             sqlIns = sqlIns & "@DataImmatricolazione, "
  269.             MyCmdIns.Parameters.Add("@DataImmatricolazione", SqlDbType.SmallDateTime)
  270.             MyCmdIns.Parameters("@DataImmatricolazione").Value = Convert.ToDateTime(immatricolazione.Replace("#", ""))
  271.  
  272.  
  273.  
  274.             Dim cartaInizio As Integer
  275.             Dim carta As String
  276.  
  277.             cartaInizio = sRiga.IndexOf("Data Aggiornamento Carta Circolazione") + Len("Data Aggiornamento Carta Circolazione")
  278.             carta = sRiga.Substring(cartaInizio, 10)
  279.             sqlIns = sqlIns & "@DataCartaCircolazione, "
  280.             MyCmdIns.Parameters.Add("@DataCartaCircolazione", SqlDbType.SmallDateTime)
  281.             MyCmdIns.Parameters("@DataCartaCircolazione").Value = Convert.ToDateTime(carta)
  282.  
  283.  
  284.  
  285.             Dim kwInizio As Integer
  286.             Dim kwFine As Integer
  287.             Dim kw As String
  288.  
  289.             kwInizio = sRiga.IndexOf("KW") + 2
  290.             kwFine = sRiga.IndexOf("Classe / Uso")
  291.             kw = sRiga.Substring(kwInizio, kwFine - kwInizio)
  292.             sqlIns = sqlIns & "@KW, "
  293.             MyCmdIns.Parameters.Add("@KW", SqlDbType.Decimal)
  294.             MyCmdIns.Parameters("@KW").Value = Convert.ToDecimal(kw.Replace(",", "."))
  295.  
  296.  
  297.  
  298.             Dim classeInizio As Integer
  299.             Dim classeFine As Integer
  300.             Dim classe As String
  301.  
  302.             classeInizio = sRiga.IndexOf("Classe / Uso") + 12
  303.             classeFine = sRiga.IndexOf("Carrozzeria")
  304.             classe = sRiga.Substring(classeInizio, classeFine - classeInizio)
  305.             sqlIns = sqlIns & "@Classe, "
  306.             MyCmdIns.Parameters.Add("@Classe", SqlDbType.NVarChar)
  307.             MyCmdIns.Parameters("@Classe").Value = classe
  308.  
  309.  
  310.  
  311.             Dim cilindrataInizio As Integer
  312.             Dim cilindrataFine As Integer
  313.             Dim cilindrata As String
  314.  
  315.             cilindrataInizio = sRiga.IndexOf("Cilindrata") + 10
  316.             cilindrataFine = sRiga.IndexOf("Alimentazione")
  317.             cilindrata = sRiga.Substring(cilindrataInizio, cilindrataFine - cilindrataInizio)
  318.             sqlIns = sqlIns & "@Cilindrata, "
  319.             MyCmdIns.Parameters.Add("@Cilindrata", SqlDbType.NVarChar)
  320.             MyCmdIns.Parameters("@Cilindrata").Value = cilindrata
  321.  
  322.  
  323.  
  324.             Dim alimentazioneInizio As Integer
  325.             Dim alimentazioneFine As Integer
  326.             Dim alimentazione As String
  327.             alimentazioneInizio = sRiga.IndexOf("Alimentazione") + 13
  328.             alimentazioneFine = sRiga.IndexOf("Tara")
  329.             alimentazione = sRiga.Substring(alimentazioneInizio, alimentazioneFine - alimentazioneInizio)
  330.             sqlIns = sqlIns & "@Alimentazione, "
  331.             MyCmdIns.Parameters.Add("@Alimentazione", SqlDbType.NVarChar)
  332.             MyCmdIns.Parameters("@Alimentazione").Value = alimentazione
  333.  
  334.  
  335.  
  336.             Dim taraInizio As Integer
  337.             Dim taraFine As Integer
  338.             Dim tara As String
  339.  
  340.             taraInizio = sRiga.IndexOf("Tara") + 4
  341.             taraFine = sRiga.IndexOf("Portata")
  342.             tara = sRiga.Substring(taraInizio, taraFine - taraInizio)
  343.             sqlIns = sqlIns & "@Tara, "
  344.             MyCmdIns.Parameters.Add("@Tara", SqlDbType.NVarChar)
  345.             MyCmdIns.Parameters("@Tara").Value = tara
  346.  
  347.  
  348.  
  349.             Dim postiInizio As Integer
  350.             Dim postiFine As Integer
  351.             Dim posti As String
  352.  
  353.             postiInizio = sRiga.IndexOf("Posti n.ro") + 10
  354.             postiFine = sRiga.IndexOf("Assi n.ro")
  355.             posti = sRiga.Substring(postiInizio, postiFine - postiInizio)
  356.             sqlIns = sqlIns & "@Posti, "
  357.             MyCmdIns.Parameters.Add("@Posti", SqlDbType.NVarChar)
  358.             MyCmdIns.Parameters("@Posti").Value = posti
  359.  
  360.  
  361.  
  362.             Dim assiInizio As Integer
  363.             Dim assiFine As Integer
  364.             Dim assi As String
  365.  
  366.             assiInizio = sRiga.IndexOf("Assi n.ro") + 9
  367.             assiFine = sRiga.IndexOf("Prima Formalita'")
  368.             assi = sRiga.Substring(assiInizio, assiFine - assiInizio)
  369.             sqlIns = sqlIns & "@Assi, "
  370.             MyCmdIns.Parameters.Add("@Assi", SqlDbType.NVarChar)
  371.             MyCmdIns.Parameters("@Assi").Value = assi
  372.  
  373.  
  374.  
  375.             Dim primaFormalitaInizio As Integer
  376.             Dim primaFormalitaFine As Integer
  377.             Dim primaFormalita As String
  378.  
  379.             primaFormalitaInizio = sRiga.IndexOf("Prima Formalita'") + 16
  380.             primaFormalitaFine = sRiga.IndexOf("Data Prima Formalita'")
  381.             primaFormalita = sRiga.Substring(primaFormalitaInizio, primaFormalitaFine - primaFormalitaInizio)
  382.             sqlIns = sqlIns & "@PrimaFomalita, "
  383.             MyCmdIns.Parameters.Add("@PrimaFomalita", SqlDbType.NVarChar)
  384.             MyCmdIns.Parameters("@PrimaFomalita").Value = primaFormalita
  385.  
  386.  
  387.  
  388.             Dim dataPrimaFormalitaInizio As Integer
  389.             Dim dataPrimaFormalita As String
  390.  
  391.             dataPrimaFormalitaInizio = sRiga.IndexOf("Data Prima Formalita'") + 21
  392.             dataPrimaFormalita = sRiga.Substring(dataPrimaFormalitaInizio, 10)
  393.             sqlIns = sqlIns & "@DataPrimaFormalita, "
  394.             MyCmdIns.Parameters.Add("@DataPrimaFormalita", SqlDbType.SmallDateTime)
  395.             MyCmdIns.Parameters("@DataPrimaFormalita").Value = Convert.ToDateTime(dataPrimaFormalita)
  396.  
  397.  
  398.  
  399.             Dim iultimaforminizio As Integer
  400.             Dim iultimaformfine As Integer
  401.             Dim sFormalita As String
  402.  
  403.             iultimaforminizio = sRiga.IndexOf("Ultima Formalita'") + 17
  404.             iultimaformfine = sRiga.IndexOf("Data Ultima Formalita'")
  405.             sFormalita = sRiga.Substring(iultimaforminizio, iultimaformfine - iultimaforminizio)
  406.             sqlIns = sqlIns & "@UltimaFormalita, "
  407.             MyCmdIns.Parameters.Add("@UltimaFormalita", SqlDbType.NVarChar)
  408.             MyCmdIns.Parameters("@UltimaFormalita").Value = sFormalita
  409.  
  410.  
  411.  
  412.             Dim sDataUltForm As String
  413.             Dim sDataUltFormInizio As Integer
  414.  
  415.             sDataUltFormInizio = sRiga.IndexOf("Data Ultima Formalita'") + 22
  416.             sDataUltForm = sRiga.Substring(sDataUltFormInizio, 10)
  417.             sqlIns = sqlIns & "@DataUltimaFormalita, "
  418.             MyCmdIns.Parameters.Add("@DataUltimaFormalita", SqlDbType.SmallDateTime)
  419.             MyCmdIns.Parameters("@DataUltimaFormalita").Value = Convert.ToDateTime(sDataUltForm)
  420.  
  421.  
  422.  
  423.             Dim attoInizio As Integer
  424.             Dim attoFine As Integer
  425.             Dim atto As String
  426.  
  427.             attoInizio = sRiga.IndexOf("Atto") + 4
  428.             attoFine = sRiga.IndexOf("Data Atto")
  429.             atto = sRiga.Substring(attoInizio, attoFine - attoInizio)
  430.             sqlIns = sqlIns & "@Atto, "
  431.             MyCmdIns.Parameters.Add("@Atto", SqlDbType.NVarChar)
  432.             MyCmdIns.Parameters("@Atto").Value = atto
  433.  
  434.  
  435.  
  436.             Dim dataAttoInizio As Integer
  437.             Dim dataAtto As String
  438.  
  439.             dataAttoInizio = sRiga.IndexOf("Data Atto") + 9
  440.             dataAtto = sRiga.Substring(dataAttoInizio, 10)
  441.             sqlIns = sqlIns & "@DataAtto, "
  442.             MyCmdIns.Parameters.Add("@DataAtto", SqlDbType.SmallDateTime)
  443.             MyCmdIns.Parameters("@DataAtto").Value = Convert.ToDateTime(dataAtto)
  444.  
  445.  
  446.  
  447.             Dim prezzoVeicoloInizio As Integer
  448.             Dim prezzoVeicoloFine As Integer
  449.             Dim prezzoVeicolo As String
  450.  
  451.             prezzoVeicoloInizio = sRiga.IndexOf("Prezzo del Veicolo") + 18
  452.             prezzoVeicoloFine = sRiga.IndexOf("Proprietario")
  453.             prezzoVeicolo = sRiga.Substring(prezzoVeicoloInizio, prezzoVeicoloFine - prezzoVeicoloInizio).Replace("*", "").Replace(".", "").Replace(",", ".").Replace(" ", "").ToUpper.Replace("EURO", "")
  454.             sqlIns = sqlIns & "@PrezzoVeicolo, "
  455.             MyCmdIns.Parameters.Add("@PrezzoVeicolo", SqlDbType.Decimal)
  456.             MyCmdIns.Parameters("@PrezzoVeicolo").Value = Convert.ToDecimal(prezzoVeicolo.Substring(0, prezzoVeicolo.Length - 3))
  457.  
  458.  
  459.  
  460.             'Completamento della stringa per la query di INSERT in VISURE_PDF.
  461.             sqlIns = sqlIns.Substring(0, sqlIns.Length - 2)
  462.             sqlIns = sqlIns & ")"
  463.             'Esecuzione Query di insert
  464.             MyCmdIns.CommandText = sqlIns
  465.             MyCmdIns.CommandTimeout = 0
  466.             MyCmdIns.CommandType = CommandType.Text
  467.             MyCmdIns.ExecuteNonQuery()
  468.  
  469.  
  470.             'Inizio gestione del blocco proprietari.
  471.             Dim counter As Integer = 0
  472.             MyCmdIns = New SqlCommand(sqlIns, CnSql)
  473.  
  474.             'Ridimensionamento sRiga al blocco proprietario.
  475.             sRiga = sRiga.Substring(sRiga.IndexOf("Proprietario"), sRiga.IndexOf("ANNOTAZIONI") - sRiga.IndexOf("Proprietario"))
  476.  
  477.             'Conto n proprietari.
  478.             For Each dato As Match In Regex.Matches(sRiga, "Proprietario")
  479.                 counter += 1
  480.             Next
  481.             nProprietari = counter
  482.  
  483.             'Dichiarazione array di indici blocco proprietario.
  484.             Dim indexProprietario(counter) As Integer
  485.             Dim indexTipo(counter) As Integer
  486.             Dim indexDataNascita(counter) As Integer
  487.             Dim indexComuneNascita(counter) As Integer
  488.             Dim indexComuneResidenza(counter) As Integer
  489.             Dim indexIndirizzo(counter) As Integer
  490.  
  491.             'Dichiarazione array blocco proprietario.
  492.             Dim proprietario(counter) As String
  493.             Dim tipo(counter) As String
  494.             Dim nascita(counter) As String
  495.             Dim comuneNascita(counter) As String
  496.             Dim residenza(counter) As String
  497.             Dim indirizzo(counter) As String
  498.             Dim arrCmd(counter) As String
  499.             Dim arrIns(counter) As String
  500.  
  501.             'Dichiarazione Parametri SQL
  502.             MyCmdIns.Parameters.Add("@Targa", SqlDbType.NVarChar)
  503.             MyCmdIns.Parameters.Add("@Proprietario", SqlDbType.NVarChar)
  504.             MyCmdIns.Parameters.Add("@Tipo", SqlDbType.NVarChar)
  505.             MyCmdIns.Parameters.Add("@DataNascita", SqlDbType.SmallDateTime)
  506.             MyCmdIns.Parameters.Add("@ComuneNascita", SqlDbType.NVarChar)
  507.             MyCmdIns.Parameters.Add("@ComuneResidenza", SqlDbType.NVarChar)
  508.             MyCmdIns.Parameters.Add("@Indirizzo", SqlDbType.NVarChar)
  509.  
  510.  
  511.             'Inizio salvataggio indici delle informazioni da estrarre relative al blocco proprietari
  512.             'Gli indici verranno utilizzati per indicare il punto di inizio e di fine del dato da estrarre
  513.             counter = 0
  514.             For Each dato As Match In Regex.Matches(sRiga, "Proprietario")
  515.                 indexProprietario(counter) = dato.Index
  516.                 counter += 1
  517.             Next
  518.             counter = 0
  519.  
  520.             'Sesso / Tipo Società
  521.             For Each dato As Match In Regex.Matches(sRiga, "Sesso / Tipo Societa'")
  522.                 indexTipo(counter) = dato.Index
  523.                 counter += 1
  524.             Next
  525.             counter = 0
  526.  
  527.             'Data di nascita
  528.             For Each dato As Match In Regex.Matches(sRiga, "Data di nascita")
  529.                 indexDataNascita(counter) = dato.Index
  530.                 counter += 1
  531.             Next
  532.             counter = 0
  533.  
  534.             'Comune di nascita
  535.             For Each dato As Match In Regex.Matches(sRiga, "Comune di nascita")
  536.                 indexComuneNascita(counter) = dato.Index
  537.                 counter += 1
  538.             Next
  539.             counter = 0
  540.  
  541.             'Comune di residenza
  542.             For Each dato As Match In Regex.Matches(sRiga, "Comune di residenza")
  543.                 indexComuneResidenza(counter) = dato.Index
  544.                 counter += 1
  545.             Next
  546.             counter = 0
  547.  
  548.             'Indirizzo
  549.             For Each dato As Match In Regex.Matches(sRiga, "Indirizzo")
  550.                 indexIndirizzo(counter) = dato.Index
  551.                 counter += 1
  552.             Next
  553.             counter = 0
  554.  
  555.             'Estrazione blocco proprietario da PDF utilizzando gli indici appena salvati.
  556.             'Creazione ed inizializzazione parametri sql per l'insert nella tabella Anagrafica
  557.             For Each dato As Match In Regex.Matches(sRiga, "Proprietario")
  558.                 sqlIns = "INSERT INTO Anagrafica VALUES(@Targa, "
  559.  
  560.                 'Targa_FK
  561.                 MyCmdIns.Parameters("@Targa").Value = sTarga
  562.  
  563.                 'Proprietario
  564.                 proprietario(counter) = sRiga.Substring(indexProprietario(counter) + Len("Proprietario"), indexTipo(counter) - (indexProprietario(counter) + Len("Proprietario")))
  565.                 arrCmd(counter) = "Proprietario nvarchar(100) NULL, "
  566.                 arrIns(counter) = "@Proprietario, "
  567.                 MyCmdIns.Parameters("@Proprietario").Value = proprietario(counter)
  568.                 sqlIns = sqlIns & arrIns(counter)
  569.  
  570.  
  571.                 'Sesso / Tipo Società
  572.                 tipo(counter) = sRiga.Substring(indexTipo(counter) + Len("Sesso / Tipo Societa'"), indexDataNascita(counter) - (indexTipo(counter) + Len("Sesso / Tipo Societa'")))
  573.                 arrCmd(counter) = "Tipo nvarchar(100) NULL, "
  574.                 arrIns(counter) = "@Tipo, "
  575.                 MyCmdIns.Parameters("@Tipo").Value = tipo(counter)
  576.                 sqlIns = sqlIns & arrIns(counter)
  577.  
  578.  
  579.                 'Data di Nascita
  580.                 nascita(counter) = sRiga.Substring(indexDataNascita(counter) + Len("Data di nascita"), 10)
  581.                 arrCmd(counter) = "DataNascita smalldatetime NULL, "
  582.                 arrIns(counter) = "@DataNascita, "
  583.                 MyCmdIns.Parameters("@DataNascita").Value = Convert.ToDateTime(nascita(counter))
  584.                 sqlIns = sqlIns & arrIns(counter)
  585.  
  586.  
  587.                 'Comune di Nascita
  588.                 comuneNascita(counter) = sRiga.Substring(indexComuneNascita(counter) + Len("Comune di nascita"), indexComuneResidenza(counter) - (indexComuneNascita(counter) + Len("Comune di nascita")))
  589.                 arrCmd(counter) = "ComuneNascita nvarchar(100) NULL, "
  590.                 arrIns(counter) = "@ComuneNascita, "
  591.                 MyCmdIns.Parameters("@ComuneNascita").Value = comuneNascita(counter)
  592.                 sqlIns = sqlIns & arrIns(counter)
  593.  
  594.  
  595.                 'Comune di Residenza
  596.                 residenza(counter) = sRiga.Substring(indexComuneResidenza(counter) + Len("Comune di residenza"), indexIndirizzo(counter) - (indexComuneResidenza(counter) + Len("Comune di residenza")))
  597.                 arrCmd(counter) = "ComuneResidenza nvarchar(100) NULL, "
  598.                 arrIns(counter) = "@ComuneResidenza, "
  599.                 MyCmdIns.Parameters("@ComuneResidenza").Value = residenza(counter)
  600.                 sqlIns = sqlIns & arrIns(counter)
  601.  
  602.  
  603.                 'Indirizzo
  604.                 If counter = 0 And nProprietari <> 1 Then
  605.                     indirizzo(counter) = sRiga.Substring(indexIndirizzo(counter) + Len("Indirizzo"), indexProprietario(counter + 1) - (indexIndirizzo(counter) + Len("Indirizzo")))
  606.                 Else
  607.                     indirizzo(counter) = sRiga.Substring(indexIndirizzo(counter) + Len("Indirizzo"), sRiga.Length() - (indexIndirizzo(counter) + Len("Indirizzo")))
  608.                 End If
  609.                 arrIns(counter) = "@Indirizzo, "
  610.                 MyCmdIns.Parameters("@Indirizzo").Value = indirizzo(counter)
  611.                 sqlIns = sqlIns & arrIns(counter)
  612.  
  613.  
  614.                 'Chiusura Select / Insert
  615.                 sqlIns = sqlIns.Substring(0, sqlIns.Length - 2) & ")"
  616.                 MyCmdIns.CommandText = sqlIns
  617.                 MyCmdIns.CommandTimeout = 0
  618.                 MyCmdIns.CommandType = CommandType.Text
  619.                 MyCmdIns.ExecuteNonQuery()
  620.                 counter += 1
  621.             Next
  622.  
  623.             'Cancellazione record duplicati dalla tabella Anagrafica
  624.             Dim sqlStr As String = "DELETE FROM Anagrafica WHERE ID NOT IN (SELECT MAX(ID) FROM Anagrafica GROUP BY Targa_FK, Proprietario HAVING MAX(ID) IS NOT NULL)"
  625.             Using myConn As New SqlConnection(connectionString)
  626.                 myConn.Open()
  627.                 Using myCmd As New SqlCommand(sqlStr, myConn)
  628.                     myCmd.ExecuteNonQuery()
  629.                 End Using
  630.                 myConn.Close()
  631.             End Using
  632.  
  633.             reader.Close()
  634.             readerDate.Close()
  635.  
  636.             'Elimina il file txt analizzato
  637.             FileTxt.Delete()
  638.         Catch ex As Exception
  639.             'Incremento valore errori e pulizia file txt utilizzato
  640.             errors += 1
  641.             reader.Close()
  642.             readerDate.Close()
  643.             FileTxt.Delete()
  644.             Err.Clear()
  645.         End Try
  646.  
  647.     End Sub
  648.  
  649.     Public Shared Function CnSqlOpen(ByVal connectionString As String) As Boolean
  650.         'Funzione utilizzata per l'apertura di una connessione con il DB. connectionString recuperata dal file .config
  651.         Try
  652.             If (CnSql Is Nothing) Then
  653.                 CnSql = New SqlConnection(connectionString)
  654.                 CnSql.Open()
  655.                 Return True
  656.             End If
  657.             If (CnSql.State = ConnectionState.Open) Then
  658.                 Return True
  659.             End If
  660.             CnSql = New SqlConnection(connectionString)
  661.             CnSql.Open()
  662.             Return True
  663.         Catch ex As Exception
  664.             MsgBox("Un errore è stato rilevato in CnSqlOpen. Errore:" & vbLf & ex.Message)
  665.         End Try
  666.     End Function
  667.  
  668.     Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  669.         'Caricamento del Programma. Inizializzazione variabili globali dell'operatore e registrazione degli annessi Log nella tabella LOG_Operazioni.
  670.         ProgressBar1.Visible = False
  671.         GetUserName()
  672.         User.Text = "Benvenuto " & G_ACCOUNTWINDOWS & "."
  673.         RegistraLog("Apertura programma Visure_Pdf_Excel", "NULL")
  674.         'Setup delle checkbox
  675.         Try
  676.             SaveExcelButton.Visible = False
  677.             Targa.Checked = True
  678.             SessoTipoSocieta.Enabled = False
  679.             DataNascita.Enabled = False
  680.             Comune.Enabled = False
  681.             Residenza.Enabled = False
  682.             Indirizzo.Enabled = False
  683.         Catch ex As Exception
  684.             MsgBox("Un errore è stato rilevato durante il caricamento del programma. Errore:" & vbLf & ex.Message)
  685.         End Try
  686.     End Sub
  687.  
  688.     Private Sub FormDisposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed
  689.         'Chiusura del programma, richiamo Garbage Collector per il rilascio di tutte le risorse utilizzate.
  690.         'Registrazione dei Log nella tabella LOG_Operazioni.
  691.         GC.Collect()
  692.         GC.WaitForPendingFinalizers()
  693.         RegistraLog("Chiusura programma Visure_Pdf_Excel", "NULL")
  694.     End Sub
  695.  
  696.     Private Sub UP_Excel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UP_Excel.Click
  697.         'Selezione del file Excel, Registrazione Log.
  698.         'Stampa feedback sulla maschera per notificare l'utente del corretto caricamento.
  699.         fileExcel = ""
  700.         'upload file
  701.         Try
  702.             Excel_Check.ForeColor = Color.Green
  703.             Excel_Check.Text = ""
  704.             OpenFileExcel.InitialDirectory = "C:\"
  705.             OpenFileExcel.Filter = "File Excel|*.xls; *.xlsx"
  706.  
  707.             If OpenFileExcel.ShowDialog = DialogResult.OK Then
  708.                 fileExcel = OpenFileExcel.FileName
  709.                 Excel_Check.Text = "File selezionato correttamente."
  710.                 Excel_TextBox.Text = fileExcel
  711.                 RegistraLog("Selezionato file Excel: " & Path.GetFileName(fileExcel), "NULL")
  712.             Else
  713.                 Excel_Check.ForeColor = Color.Red
  714.                 Excel_Check.Text = "Impossibile selezionare il file."
  715.                 Exit Sub
  716.             End If
  717.         Catch ex As Exception
  718.             MsgBox("Un errore è stato rilevato durante il caricamento del file Excel. Errore:" & vbLf & ex.Message)
  719.             Err.Clear()
  720.         End Try
  721.     End Sub
  722.  
  723.     Private Sub UP_Pdf_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UP_Pdf.Click
  724.         'Selezione del file Excel, Registrazione Log.
  725.         'Stampa feedback sulla maschera per notificare l'utente del corretto caricamento.
  726.         DirPdf = ""
  727.         'upload file
  728.         Try
  729.             Pdf_Check.ForeColor = Color.Green
  730.             Pdf_Check.Text = ""
  731.  
  732.             If OpenDirPdf.ShowDialog = DialogResult.OK Then
  733.                 DirPdf = OpenDirPdf.SelectedPath
  734.                 Pdf_Check.Text = "Cartella selezionata correttamente."
  735.                 PDF_TextBox.Text = DirPdf
  736.                 RegistraLog("Selezionata cartella PDF: " & Path.GetFileName(DirPdf), "NULL")
  737.             Else
  738.                 Pdf_Check.ForeColor = Color.Red
  739.                 Pdf_Check.Text = "Impossibile selezionare la cartella."
  740.                 Exit Sub
  741.             End If
  742.         Catch ex As Exception
  743.             MsgBox("Un errore è stato rilevato durante il caricamento del file PDF. Errore:" & vbLf & ex.Message)
  744.             Err.Clear()
  745.         End Try
  746.     End Sub
  747.  
  748.     Private Sub ExcelManagment(ByVal filePath As String)
  749.         'Lettura file Excel tramite il parametro filePath e salvataggio dei relativi dati nella data table DtTab
  750.         'Creazione SELECT per associare i dati estratti dal PDF contenuti nella tabella VISURE_PDF con le targhe presenti nella tabella TempTabXLS
  751.         'Oggetti DB utilizzati: VISURE_PDF, TempTabXLS, Anagrafica
  752.         Try
  753.             Dim sFileName As String = filePath
  754.             Dim MyConnection As OleDbConnection
  755.             Dim DtTab As New System.Data.DataTable
  756.             Dim sTipoFile As String
  757.             ProgressBar1.Step = 10
  758.  
  759.             'Individuo il tipo di file Excel scelto
  760.             If IO.Path.GetExtension(sFileName.ToUpper) = ".XLS" Then
  761.                 sTipoFile = "Excel 8.0"
  762.                 MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & sFileName & "';Extended Properties=" & sTipoFile & ";")
  763.             Else
  764.                 sTipoFile = "Excel 12.0"
  765.                 MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & sFileName & "';Extended Properties=" & sTipoFile & ";")
  766.             End If
  767.             ProgressBar1.PerformStep()
  768.  
  769.             ' Apre connessione con Excel
  770.             MyConnection.Open()
  771.  
  772.             'Popola data table
  773.             Dim myTableName = MyConnection.GetSchema("Tables").Rows(0)("TABLE_NAME")
  774.             Dim MyCommand As OleDbDataAdapter = New OleDbDataAdapter(String.Format("SELECT * FROM [{0}] ", myTableName), MyConnection)
  775.             MyCommand.TableMappings.Add("Table", "    ")
  776.             ProgressBar1.PerformStep()
  777.             MyCommand.Fill(DtTab)
  778.             MyConnection.Close()
  779.             'Creazione tabella temporanea TempTabXLS
  780.             CreateTable(TempTab, DtTab)
  781.             MsgBox("File excel elaborato correttamente. Inizio elaborazione file PDF.")
  782.  
  783.             'Caricamento DataTable in TempTabXLS
  784.             DataTableToSql(DtTab)
  785.  
  786.             'Creazione Select in base ai campi selzionati per l'associazione dati Excel/PDF.
  787.             'Creazione Insert dei dati nella tabella Dettagli.
  788.             'N.B. Tutti i dati saranno inseriti nella tabella Dettagli indifferentemente dai campi scelti.
  789.             'N.B. Tutti i dati estratti sono presenti sul DB. Solo i campi selezionati verranno estratti dalla query.
  790.             Dim sqlCmd As String = "SELECT "
  791.             Dim sqlDettagli As String = "SELECT " & TempTab & ".Targa, "
  792.             For i = 0 To indexColTempTab
  793.                 sqlCmd = sqlCmd & TempTab & "." & TempTabColName(i) & " as '" & TempTabColName(i).Replace("_", " ") & "', "
  794.             Next
  795.  
  796.  
  797.             If Telaio.Checked Then
  798.                 sqlCmd = sqlCmd & "Telaio, "
  799.             End If
  800.             sqlDettagli = sqlDettagli & "Telaio, "
  801.  
  802.  
  803.             If Produttore.Checked Then
  804.                 sqlCmd = sqlCmd & "Produttore, "
  805.             End If
  806.             sqlDettagli = sqlDettagli & "Produttore, "
  807.  
  808.  
  809.             If Immatricolazione.Checked Then
  810.                 sqlCmd = sqlCmd & "DataImmatricolazione as 'Data di Immatricolazione', "
  811.             End If
  812.             sqlDettagli = sqlDettagli & "DataImmatricolazione as 'Data di Immatricolazione', "
  813.  
  814.  
  815.             If CartaDiCircolazione.Checked Then
  816.                 sqlCmd = sqlCmd & "DataCartaCircolazione as 'Data Aggiornamento Carta di Circolazione', "
  817.             End If
  818.             sqlDettagli = sqlDettagli & "DataCartaCircolazione as 'Data Aggiornamento Carta di Circolazione', "
  819.  
  820.  
  821.             If KW.Checked Then
  822.                 sqlCmd = sqlCmd & "KW, "
  823.             End If
  824.             sqlDettagli = sqlDettagli & "KW, "
  825.  
  826.  
  827.             If Classe.Checked Then
  828.                 sqlCmd = sqlCmd & "Classe as 'Classe/Uso', "
  829.             End If
  830.             sqlDettagli = sqlDettagli & "Classe as 'Classe/Uso', "
  831.  
  832.  
  833.             If Cilindrata.Checked Then
  834.                 sqlCmd = sqlCmd & "Cilindrata, "
  835.             End If
  836.             sqlDettagli = sqlDettagli & "Cilindrata, "
  837.  
  838.  
  839.             If Alimentazione.Checked Then
  840.                 sqlCmd = sqlCmd & "Alimentazione, "
  841.             End If
  842.             sqlDettagli = sqlDettagli & "Alimentazione, "
  843.  
  844.  
  845.  
  846.             If Tara.Checked Then
  847.                 sqlCmd = sqlCmd & "Tara, "
  848.             End If
  849.             sqlDettagli = sqlDettagli & "Tara, "
  850.  
  851.  
  852.             If Posti.Checked Then
  853.                 sqlCmd = sqlCmd & "Posti as 'Posti n.ro', "
  854.             End If
  855.             sqlDettagli = sqlDettagli & "Posti as 'Posti n.ro', "
  856.  
  857.  
  858.             If Assi.Checked Then
  859.                 sqlCmd = sqlCmd & "Assi as 'Assi n.ro', "
  860.             End If
  861.             sqlDettagli = sqlDettagli & "Assi as 'Assi n.ro', "
  862.  
  863.  
  864.             If PrimaFormalita.Checked Then
  865.                 sqlCmd = sqlCmd & "PrimaFormalita as 'Prima Formalità', "
  866.             End If
  867.             sqlDettagli = sqlDettagli & "PrimaFormalita as 'Prima Formalità', "
  868.  
  869.  
  870.             If DataPrimaFormalita.Checked Then
  871.                 sqlCmd = sqlCmd & "DataPrimaFormalita as 'Data Prima Formalità', "
  872.             End If
  873.             sqlDettagli = sqlDettagli & "DataPrimaFormalita as 'Data Prima Formalità', "
  874.  
  875.  
  876.             If UltimaFormalita.Checked Then
  877.                 sqlCmd = sqlCmd & "UltimaFormalita as 'Ultima Formalità', "
  878.             End If
  879.             sqlDettagli = sqlDettagli & "UltimaFormalita as 'Ultima Formalità', "
  880.  
  881.  
  882.             If DataUltimaFormalita.Checked Then
  883.                 sqlCmd = sqlCmd & "DataUltimaFormalita as 'Data Ultima Formalità', "
  884.             End If
  885.             sqlDettagli = sqlDettagli & "DataUltimaFormalita as 'Data Ultima Formalità', "
  886.  
  887.  
  888.             If Atto.Checked Then
  889.                 sqlCmd = sqlCmd & "Atto, "
  890.             End If
  891.             sqlDettagli = sqlDettagli & "Atto, "
  892.  
  893.  
  894.             If DataAtto.Checked Then
  895.                 sqlCmd = sqlCmd & "DataAtto as 'Data Atto', "
  896.             End If
  897.             sqlDettagli = sqlDettagli & "DataAtto as 'Data Atto', "
  898.  
  899.  
  900.             If PrezzoVeicolo.Checked Then
  901.                 sqlCmd = sqlCmd & "PrezzoVeicolo as 'Prezzo del Veicolo', "
  902.             End If
  903.             sqlDettagli = sqlDettagli & "PrezzoVeicolo as 'Prezzo del Veicolo', "
  904.  
  905.  
  906.             If Proprietario.Checked Then
  907.                 sqlCmd = sqlCmd & "Proprietario, "
  908.             End If
  909.  
  910.             If SessoTipoSocieta.Checked Then
  911.                 sqlCmd = sqlCmd & "Tipo as 'Sesso/Tipo Società', "
  912.             End If
  913.  
  914.             If DataNascita.Checked Then
  915.                 sqlCmd = sqlCmd & "DataNascita as 'Data di Nascita', "
  916.             End If
  917.  
  918.             If Comune.Checked Then
  919.                 sqlCmd = sqlCmd & "ComuneNascita as 'Comune di Nascita', "
  920.             End If
  921.  
  922.             If Residenza.Checked Then
  923.                 sqlCmd = sqlCmd & "ComuneResidenza as 'Comune di Residenza', "
  924.             End If
  925.  
  926.             If Indirizzo.Checked Then
  927.                 sqlCmd = sqlCmd & "Indirizzo as 'Indirizzo di Residenza', "
  928.             End If
  929.  
  930.             'Chiusura delle Query.
  931.             sqlCmd = sqlCmd.Substring(0, sqlCmd.Length - 2) & " FROM " & TempTab & ", " & Tab & ", Anagrafica WHERE " & TempTab & ".Targa = " & Tab & ".Targa AND " & Tab & ".Targa = Anagrafica.Targa_FK"
  932.             sqlDettagli = sqlDettagli.Substring(0, sqlDettagli.Length - 2) & " FROM " & TempTab & ", " & Tab & " WHERE " & TempTab & ".Targa = " & Tab & ".Targa"
  933.             'Creazione DataTable
  934.             Dim RemoteDtTab As New System.Data.DataTable
  935.  
  936.             'Apertura connessione al DB
  937.             Using myConn As New SqlConnection(connectionString)
  938.                 myConn.Open()
  939.                 'Popolamento della DataTable contenente i dati da salvare su file Excel
  940.                 Using loader As New SqlDataAdapter(sqlCmd, myConn)
  941.                     loader.Fill(RemoteDtTab)
  942.                 End Using
  943.                 'Popolamento della DataTable contenente i dati da caricare nella tabella Dettagli.
  944.                 Using loaderDettagli As New SqlDataAdapter(sqlDettagli, myConn)
  945.                     loaderDettagli.Fill(DettagliDtTab)
  946.                 End Using
  947.                 myConn.Close()
  948.             End Using
  949.  
  950.             'Gestione degli errori, conto pdf mancanti.
  951.             Dim pdfMancanti As String = Convert.ToString(ErrorFinder().Rows.Count)
  952.             ProgressBar1.Value = 100
  953.             If ErrorFinder().Rows.Count > 0 Then
  954.                 Dim dt As System.Data.DataTable = ErrorFinder() 'Metodo per la ricerca degli errori tramite la discrepanza tra TempTabXLS e VISURE_PDF
  955.                 Dim errori As String = ""
  956.                 Dim rowIndex As Integer = 0
  957.                 For Each dr In dt.Rows
  958.                     errori = errori & Convert.ToString(dt.Rows(rowIndex)(0)) & vbLf 'Lista targhe con pdf mancante/corrotto
  959.                     rowIndex += 1
  960.                 Next
  961.                 'Feedback errori riscontrari e salvataggio dei Log
  962.                 MsgBox("Elaborazione PDF completata con " & errors & " errori. " & vbLf & vbLf & "PDF mancanti/corrotti: " & pdfMancanti & "." & vbLf & vbLf & "Targa PDF mancanti/corrotti: " & errori & vbLf & "Inizio salvataggio file Excel.")
  963.                 RegistraLog("PDF mancanti/corrotti: " & pdfMancanti, "NULL")
  964.                 RegistraLog("Targa PDF mancanti/corrotti: " & errori, "NULL")
  965.             Else
  966.                 MsgBox("Elaborazione PDF completata con " & errors & " errori. " & vbLf & vbLf & "PDF mancanti/corrotti: " & pdfMancanti & "." & vbLf & vbLf & "Inizio salvataggio file Excel.")
  967.             End If
  968.             ProgressBar1.Value = 0
  969.  
  970.             'Inizio scrittura dei dati sul file Excel del Cliente.
  971.             Dim strFilePath As String = filePath.Replace(Path.GetFileName(filePath), "")
  972.             ExcelExport(RemoteDtTab, strFilePath, True)
  973.  
  974.         Catch ex As Exception
  975.             MsgBox("Un errore è stato rilevato durante l'elaborazione dei dati. Errore:" & vbLf & ex.Message)
  976.             RegistraLog("Interruzione programma Visure_Pdf_Excel a causa di un errore.", "NULL")
  977.             ProgressBar1.Value = 0
  978.             Err.Clear()
  979.             Exit Sub
  980.         End Try
  981.     End Sub
  982.  
  983.     Private Sub ExcelExport(ByVal ExportDataTable As DataTable, ByVal filePath As String, ByVal ScegliExcel As Boolean)
  984.         'Scrittura dei dati estratti dal pdf sul file Excel del Cliente
  985.         'I dati estratti dal pdf sono contenuti in ExportDataTable.
  986.         'Il file Excel viene individuato dal metodo tramite il parametro filePath
  987.         Dim excel As New Microsoft.Office.Interop.Excel.Application
  988.         Dim wBook As Microsoft.Office.Interop.Excel.Workbook
  989.         Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet
  990.         Try
  991.             ProgressBar1.Value = 0
  992.             ProgressBar1.Step = 1
  993.             ProgressBar1.PerformStep()
  994.             'Dichiarazione variabili
  995.             If ScegliExcel Then
  996.                 wBook = excel.Workbooks.Open(fileExcel)
  997.             Else
  998.                 wBook = excel.Workbooks.Add()
  999.             End If
  1000.             wSheet = wBook.ActiveSheet()
  1001.             Dim dt As System.Data.DataTable = ExportDataTable
  1002.             Dim dc As System.Data.DataColumn
  1003.             Dim dr As System.Data.DataRow
  1004.             Dim colIndex As Integer = 0
  1005.             Dim rowIndex As Integer = 0
  1006.             Dim Counter As Integer = 0
  1007.             Dim indexProprietario As Integer
  1008.             Dim indexTipo As Integer
  1009.             Dim indexDataN As Integer
  1010.             Dim indexComuneN As Integer
  1011.             Dim indexComuneRes As Integer
  1012.             Dim indexIndirizzo As Integer
  1013.  
  1014.             'Scrittura header e salvataggio index blocco proprietari
  1015.             For Each dc In dt.Columns
  1016.                 colIndex = colIndex + 1
  1017.                 excel.Cells(1, colIndex) = dc.ColumnName
  1018.                 If dc.ColumnName = "Proprietario" Then
  1019.                     indexProprietario = colIndex
  1020.                 End If
  1021.                 If dc.ColumnName = "Sesso/Tipo Società" Then
  1022.                     indexTipo = colIndex
  1023.                 End If
  1024.                 If dc.ColumnName = "Data di Nascita" Then
  1025.                     indexDataN = colIndex
  1026.                 End If
  1027.                 If dc.ColumnName = "Comune di Nascita" Then
  1028.                     indexComuneN = colIndex
  1029.                 End If
  1030.                 If dc.ColumnName = "Comune di Residenza" Then
  1031.                     indexComuneRes = colIndex
  1032.                 End If
  1033.                 If dc.ColumnName = "Indirizzo di Residenza" Then
  1034.                     indexIndirizzo = colIndex
  1035.                 End If
  1036.             Next
  1037.             'Scrittura dei dati sul file Excel
  1038.             For Each dr In dt.Rows
  1039.                 rowIndex += 1
  1040.                 colIndex = 0
  1041.                 Counter += 1
  1042.                 If Counter Mod 10 = 0 Then
  1043.                     ProgressBar1.PerformStep()
  1044.                 End If
  1045.                 For Each dc In dt.Columns
  1046.                     colIndex += 1
  1047.                     excel.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
  1048.                 Next
  1049.             Next
  1050.             ProgressBar1.Step = 1
  1051.             Dim lastRow As Integer = wSheet.UsedRange.Columns.Count()
  1052.  
  1053.             'Unione proprietari multipli
  1054.             If Proprietario.Checked Then
  1055.                 'Eliminazione righe doppia ed aggiunta delle colonne necessarie per i proprietari multipli.
  1056.                 rowIndex = 0
  1057.                 Dim colCopyIndex As Integer
  1058.                 Dim proprColRange As Integer
  1059.                 For Each dr In dt.Rows
  1060.                     rowIndex += 1
  1061.                     colCopyIndex = indexProprietario
  1062.                     If wSheet.Cells(rowIndex, 1).Value = wSheet.Cells(rowIndex + 1, 1).Value Then
  1063.                         If rowIndex Mod 5 = 0 Then
  1064.                             ProgressBar1.PerformStep()
  1065.                         End If
  1066.                         proprColRange = lastRow - indexProprietario
  1067.                         For colIndex = lastRow + 1 To lastRow + proprColRange + 1
  1068.                             wSheet.Cells(rowIndex, colIndex).Value = wSheet.Cells(rowIndex + 1, colCopyIndex).Value
  1069.                             colCopyIndex += 1
  1070.                         Next
  1071.                         wSheet.Rows(rowIndex + 1).Delete()
  1072.                     End If
  1073.                 Next
  1074.             End If
  1075.  
  1076.             'Scrittura header secondo Proprietario
  1077.             Dim contaUltimaColonna As Integer
  1078.             contaUltimaColonna = lastRow
  1079.             If Proprietario.Checked Then
  1080.                 wSheet.Cells(1, contaUltimaColonna + 1).Value = "Secondo Proprietario"
  1081.                 contaUltimaColonna += 1
  1082.             End If
  1083.             If SessoTipoSocieta.Checked Then
  1084.                 wSheet.Cells(1, contaUltimaColonna + 1).Value = "Sesso/Tipo Scoietà S.P."
  1085.                 contaUltimaColonna += 1
  1086.             End If
  1087.             If DataNascita.Checked Then
  1088.                 wSheet.Cells(1, contaUltimaColonna + 1).Value = "Data di Nascita S.P."
  1089.                 contaUltimaColonna += 1
  1090.             End If
  1091.             If Comune.Checked Then
  1092.                 wSheet.Cells(1, contaUltimaColonna + 1).Value = "Comune di Residenza S.P."
  1093.                 contaUltimaColonna += 1
  1094.             End If
  1095.             If Residenza.Checked Then
  1096.                 wSheet.Cells(1, contaUltimaColonna + 1).Value = "Comune di Nascita S.P."
  1097.                 contaUltimaColonna += 1
  1098.             End If
  1099.             If Indirizzo.Checked Then
  1100.                 wSheet.Cells(1, contaUltimaColonna + 1).Value = "Indirizzo di Residenza S.P."
  1101.                 contaUltimaColonna += 1
  1102.             End If
  1103.  
  1104.             If ScegliExcel Then
  1105.                 'Formattazione dati aggiunti al file del Cliente per permettere una lettura del file facilitata.
  1106.                 wSheet.UsedRange.Borders.Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin
  1107.                 wSheet.UsedRange.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous
  1108.                 wSheet.UsedRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter
  1109.                 wSheet.Columns.AutoFit()
  1110.                 ProgressBar1.Step = 5
  1111.                 ProgressBar1.PerformStep()
  1112.  
  1113.                 'Controllo esistenza file ed eliminazione file vecchio.
  1114.                 Dim strFileName = filePath & Tab & ".xlsx"
  1115.                 If System.IO.File.Exists(strFileName) Then
  1116.                     ProgressBar1.PerformStep()
  1117.                     System.IO.File.Delete(strFileName)
  1118.                 End If
  1119.                 'Creazione percorso per il salvataggio del file.
  1120.                 CreaCartellaPercorso()
  1121.  
  1122.                 strFileName = fileExcel.Replace(Path.GetFileName(fileExcel), "VISURE_PDF.xlsx")
  1123.  
  1124.                 'Salvataggio file.
  1125.                 ProgressBar1.PerformStep()
  1126.                 wBook.SaveAs(strFileName)
  1127.                 wBook.Close()
  1128.                 ProgressBar1.PerformStep()
  1129.                 excel.Quit()
  1130.                 ProgressBar1.Value = 100
  1131.                 'Feedback salvataggio riuscito e registrazione Log.
  1132.                 MsgBox("File " & Path.GetFileName(strFileName) & " è stato salvato correttamente in " & strFileName)
  1133.                 ProgressBar1.Value = 0
  1134.                 ProgressBar1.Visible = False
  1135.                 InserisciTestata()
  1136.                 DettagliToSql(DettagliDtTab)
  1137.                 RegistraLog("Salvataggio file excel elaborato: " & Path.GetFileName(strFileName), "NULL")
  1138.                 'Richiesta nuova elaborazione
  1139.                 Dim result As DialogResult = Windows.Forms.DialogResult.No
  1140.                 GC.Collect()
  1141.                 GC.WaitForPendingFinalizers()
  1142.                 result = MessageBox.Show("Vuoi continuare con un'altra elaborazione?", "Leggi visure da pdf", MessageBoxButtons.YesNo)
  1143.                 If result = Windows.Forms.DialogResult.Yes Then
  1144.                     TableDeleter(TempTab)
  1145.                     Excel_Check.Visible = False
  1146.                     Pdf_Check.Visible = False
  1147.                     Excel_TextBox.Text = ""
  1148.                     PDF_TextBox.Text = ""
  1149.                 Else
  1150.                     TableDeleter(TempTab)
  1151.                     Me.Close()
  1152.                 End If
  1153.             Else
  1154.                 wSheet.UsedRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter
  1155.                 wSheet.Columns.AutoFit()
  1156.                 excel.Visible = True
  1157.             End If
  1158.             TableDeleter(TempTab)
  1159.             GC.Collect()
  1160.             GC.WaitForPendingFinalizers()
  1161.         Catch ex As Exception
  1162.             'Gestione degli errori. Eliminazione tabella temporanea e registrazione dei Log
  1163.             TableDeleter(TempTab)
  1164.             GC.Collect()
  1165.             GC.WaitForPendingFinalizers()
  1166.             MsgBox("Un errore è stato rilevato durante il salvataggio dei risultati. Errore:" & vbLf & ex.Message)
  1167.             RegistraLog("Interruzione programma Visure_Pdf_Excel a causa di un errore.", "NULL")
  1168.             excel.Quit()
  1169.             ProgressBar1.Value = 0
  1170.             Err.Clear()
  1171.         End Try
  1172.     End Sub
  1173.  
  1174.     Private Sub DataTableToSql(ByVal dt As DataTable)
  1175.         'Inserimento dei dati presenti sul file Excel del Cliente nella tabella temporanea.
  1176.         'I dati presenti sul file Excel del Cliente sono contenuti nella DataTable dt
  1177.         Try
  1178.             ProgressBar1.Step = 1
  1179.             Dim counter As Integer
  1180.             Dim progressBarCounter As Integer = 0
  1181.             Using myConn As New SqlConnection(connectionString)
  1182.                 myConn.Open()
  1183.  
  1184.                 'Creazione Insert
  1185.                 Dim sqlCmd As String = "INSERT INTO " & TempTab & " VALUES( "
  1186.                 For i = 0 To indexColTempTab
  1187.                     sqlCmd = sqlCmd & "@" & TempTabColName(i) & ", "
  1188.                 Next
  1189.                 sqlCmd = sqlCmd.Substring(0, Len(sqlCmd) - 2) & ")"
  1190.  
  1191.                 'Creazione Parametri SQL
  1192.                 Using myCmd As New SqlCommand(sqlCmd, myConn)
  1193.                     For i = 0 To indexColTempTab
  1194.                         myCmd.Parameters.Add("@" & TempTabColName(i), SqlDbType.NVarChar)
  1195.                     Next
  1196.  
  1197.                     'Inizializzazione Parametri ed esecuzioni query
  1198.                     For Each dr In dt.Rows
  1199.                         counter = 0
  1200.                         For Each dc In dt.Columns
  1201.                             myCmd.Parameters("@" & TempTabColName(counter)).Value = dr(dc.ColumnName)
  1202.                             counter += 1
  1203.                             If counter = indexColTempTab + 1 Then
  1204.                                 Exit For
  1205.                             End If
  1206.                             progressBarCounter += 1
  1207.                             If progressBarCounter Mod 20 = 0 Then
  1208.                                 ProgressBar1.PerformStep()
  1209.                             End If
  1210.                         Next
  1211.                         myCmd.ExecuteNonQuery()
  1212.                     Next
  1213.                 End Using
  1214.                 myConn.Close()
  1215.             End Using
  1216.  
  1217.             ProgressBar1.Value = 100
  1218.         Catch ex As Exception
  1219.             MsgBox("Un errore è stato rilevato nell'elaborazione del file Excel. Errore:" & vbLf & ex.Message)
  1220.             RegistraLog("Interruzione programma Visure_Pdf_Excel a causa di un errore.", "NULL")
  1221.             ProgressBar1.Value = 0
  1222.             Exit Sub
  1223.         End Try
  1224.     End Sub
  1225.  
  1226.     Private Sub TableDeleter(ByVal tablename As String)
  1227.         'Eliminazione della tabella scelta.
  1228.         'tablename contiene il nome della tabella.
  1229.         Try
  1230.             Using myConn As New SqlConnection(connectionString)
  1231.                 myConn.Open()
  1232.                 Using myCmd As New SqlCommand("DROP TABLE " & tablename, myConn)
  1233.                     myCmd.ExecuteNonQuery()
  1234.                 End Using
  1235.             End Using
  1236.         Catch ex As Exception
  1237.             Err.Clear()
  1238.         End Try
  1239.     End Sub
  1240.  
  1241.     Private Sub CreateTable(ByVal tableName As String, ByVal dt As DataTable)
  1242.         'Creazione della tabella temporanea TempTabXLS in modo dinamico in base al numero ed al nome di colonne del file Excel.
  1243.         'Unico vincolo la presenza della colonna Targa.
  1244.         'tableName contiene il nome della tabella temporanea (acquisito dal file .config)
  1245.         'DataTable contiene i dati contenuti nel file Excel del Cliente in modo da creare una tabella con lo stesso numero e stesso tipo di colonne.
  1246.         Try
  1247.             indexColTempTab = 0
  1248.             For Each dc In dt.Columns
  1249.                 TempTabColName(indexColTempTab) = Convert.ToString(dc.ColumnName).Replace(" ", "_").Replace("à", "a").Replace("è", "e").Replace("é", "e").Replace("ì", "i").Replace("ò", "o").Replace("ù", "u")
  1250.                 If TempTabColName(indexColTempTab).ToLower.Contains("targa") Then
  1251.                     TempTabColName(indexColTempTab) = "Targa"
  1252.                 End If
  1253.                 indexColTempTab += 1
  1254.             Next
  1255.             indexColTempTab -= 1
  1256.             Dim sqlStr As String = "Create Table " & TempTab & "( ID integer IDENTITY(1,1) PRIMARY KEY, "
  1257.             For i = 0 To indexColTempTab
  1258.                 sqlStr = sqlStr & TempTabColName(i) & " nvarchar(100) NULL, "
  1259.             Next
  1260.             sqlStr = sqlStr.Substring(0, Len(sqlStr) - 2) & ")"
  1261.             Using myConn As New SqlConnection(connectionString)
  1262.                 myConn.Open()
  1263.                 Using myCmd As New SqlCommand(sqlStr, myConn)
  1264.                     myCmd.ExecuteNonQuery()
  1265.                 End Using
  1266.             End Using
  1267.         Catch ex As Exception
  1268.             Err.Clear()
  1269.             Exit Sub
  1270.         End Try
  1271.     End Sub
  1272.  
  1273.     Private Sub Proprietario_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Proprietario.CheckedChanged
  1274.         'Disabilita tutti i campi legati al Proprietario finché il campo proprietario non è spuntato.
  1275.         If Proprietario.Checked Then
  1276.             SessoTipoSocieta.Enabled = True
  1277.             DataNascita.Enabled = True
  1278.             Comune.Enabled = True
  1279.             Residenza.Enabled = True
  1280.             Indirizzo.Enabled = True
  1281.  
  1282.         Else
  1283.             SessoTipoSocieta.Enabled = False
  1284.             DataNascita.Enabled = False
  1285.             Comune.Enabled = False
  1286.             Residenza.Enabled = False
  1287.             Indirizzo.Enabled = False
  1288.  
  1289.             SessoTipoSocieta.Checked = False
  1290.             DataNascita.Checked = False
  1291.             Comune.Checked = False
  1292.             Residenza.Checked = False
  1293.             Indirizzo.Checked = False
  1294.         End If
  1295.  
  1296.     End Sub
  1297.  
  1298.     Private Sub GetUserName()
  1299.         'Inizializza le variabili globali legati all'operatore.
  1300.         'Inserisce i dati nella tabella TB_OPERATORI in caso non fossero presenti.
  1301.         'Esegue una update del record relativo all'operatore nel caso i dati fossero mancanti.
  1302.         Try
  1303.             Dim userFullName As String = UserPrincipal.Current.DisplayName
  1304.             G_USERFULLNAME = userFullName
  1305.  
  1306.             If TypeOf My.User.CurrentPrincipal Is Security.Principal.WindowsPrincipal Then
  1307.                 Dim parts() As String = Split(My.User.Name, "\")
  1308.                 Dim username As String = parts(1)
  1309.                 G_ACCOUNTWINDOWS = username
  1310.                 Try
  1311.                     Using myConn As New SqlConnection(connectionString)
  1312.                         myConn.Open()
  1313.                         Dim sqlStr As String = "Select idOperatore From TB_OPERATORI WHERE AccountWindows = '" & username & "'"
  1314.                         Using myCmd As New SqlDataAdapter(sqlStr, myConn)
  1315.                             Dim dt As New System.Data.DataTable
  1316.                             myCmd.Fill(dt)
  1317.                             G_IDOPERATORE = Convert.ToString(dt.Rows(0)(0))
  1318.                         End Using 'End Select Using
  1319.  
  1320.                         sqlStr = "UPDATE TB_OPERATORI SET UserName = '" & username & "' WHERE AccountWindows = '" & username & "'"
  1321.                         Using myCmd As New SqlCommand(sqlStr, myConn)
  1322.                             myCmd.ExecuteNonQuery()
  1323.                         End Using 'End Update Using
  1324.                         myConn.Close()
  1325.                     End Using 'End myConn Using
  1326.  
  1327.                 Catch ex As Exception
  1328.                     Using myConn As New SqlConnection(connectionString)
  1329.                         myConn.Open()
  1330.                         Dim sqlStr As String = "INSERT INTO TB_OPERATORI VALUES(@Operatore, NULL, NULL, @Username, NULL, 0, 0, 0, NULL, @Username)"
  1331.                         Using myCmd As New SqlCommand(sqlStr, myConn)
  1332.  
  1333.                             myCmd.Parameters.Add("@Operatore", SqlDbType.VarChar)
  1334.                             myCmd.Parameters("@Operatore").Value = G_USERFULLNAME
  1335.  
  1336.                             myCmd.Parameters.Add("@Username", SqlDbType.VarChar)
  1337.                             myCmd.Parameters("@Username").Value = username
  1338.  
  1339.                             myCmd.ExecuteNonQuery()
  1340.                         End Using
  1341.  
  1342.                         sqlStr = "Select idOperatore From TB_OPERATORI WHERE AccountWindows = '" & username & "'"
  1343.                         Using myCmd As New SqlDataAdapter(sqlStr, myConn)
  1344.                             Dim dt As New System.Data.DataTable
  1345.                             myCmd.Fill(dt)
  1346.                             G_IDOPERATORE = Convert.ToString(dt.Rows(0)(0))
  1347.                         End Using 'End Select Using
  1348.                         myConn.Close()
  1349.                     End Using
  1350.                 End Try
  1351.             End If
  1352.         Catch ex As Exception
  1353.             MsgBox("Impossibile ottenere i dati dell'operatore. Errore: " & ex.Message)
  1354.             Err.Clear()
  1355.         End Try
  1356.  
  1357.     End Sub
  1358.  
  1359.     Private Sub RegistraLog(ByVal Operazione As String, ByVal Chiave As String)
  1360.         'Inserisce il Log all'interno della tabella LOG_Operazioni
  1361.         Try
  1362.             Dim cn As New SqlConnection(connectionString)
  1363.             Dim s As String
  1364.             s = "Insert into LOG_OPERAZIONI(IdOperatore, Data, Ora, Operazione, Chiave)" & _
  1365.                 " VALUES(@Operatore, @Data, @Ora, @Operazione, @Chiave)"
  1366.             Dim myCmd As New SqlCommand(s, cn)
  1367.             myCmd.Parameters.Add("@Operatore", SqlDbType.VarChar)
  1368.             myCmd.Parameters.Add("@Data", SqlDbType.DateTime)
  1369.             myCmd.Parameters.Add("@Ora", SqlDbType.NVarChar)
  1370.             myCmd.Parameters.Add("@Operazione", SqlDbType.VarChar)
  1371.             myCmd.Parameters.Add("@Chiave", SqlDbType.VarChar)
  1372.             myCmd.Parameters("@Operatore").Value = G_IDOPERATORE
  1373.             myCmd.Parameters("@Data").Value = Convert.ToDateTime(DateTime.Now.ToString("dd/MM/yyyy").Substring(0, 10))
  1374.             myCmd.Parameters("@Ora").Value = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss").Substring(Len("yyyy/MM/dd") + 1, 8)
  1375.             myCmd.Parameters("@Operazione").Value = Operazione
  1376.             myCmd.Parameters("@Chiave").Value = Chiave
  1377.             cn.Open()
  1378.             myCmd.ExecuteNonQuery()
  1379.             cn.Close()
  1380.         Catch ex As Exception
  1381.             MsgBox("Errore durante la scrittura dei log. Errore: " & ex.Message)
  1382.         End Try
  1383.     End Sub
  1384.  
  1385.     Private Sub CancellaDuplicatiIdTarga(ByVal tableName As String)
  1386.         'Elimina i record duplicati confrontandeo ID e Targa.
  1387.         'Elimina i record duplicati all'interno della tabella specificata tramite tableName
  1388.         Dim sqlStr As String = "DELETE FROM " & tableName & " WHERE ID NOT IN (SELECT MAX(ID) FROM " & tableName & " GROUP BY Targa HAVING MAX(ID) IS NOT NULL)"
  1389.         Using myConn As New SqlConnection(connectionString)
  1390.             myConn.Open()
  1391.             Using myCmd As New SqlCommand(sqlStr, myConn)
  1392.                 myCmd.ExecuteNonQuery()
  1393.             End Using
  1394.             myConn.Close()
  1395.         End Using
  1396.     End Sub
  1397.  
  1398.     Private Sub DettagliToSql(ByVal dt As DataTable)
  1399.         'Inserisce nella tabella Dettagli le targhe presenti nel file Excel con i relativi dati presenti nel PDF.
  1400.         'In caso di PDF mancante, corrotto o di errore nella lettura del PDF il metodo inserisce solamente la targa presente nel file Excel.
  1401.         'Il parametro dt contiene la targa estratta dal file Excel del Cliente associata ai dati presenti all'interno dei PDF
  1402.         Dim rowIndex As Integer = 0
  1403.         Dim colIndex As Integer = 0
  1404.         Dim sqlStr As String
  1405.         Dim ID_DataTable As New System.Data.DataTable
  1406.         Dim ID_Testata As Integer
  1407.         sqlStr = "Select ID from TestateExcel where IdOperatore = '" & G_IDOPERATORE & "' AND NomeFile = '" & Path.GetFileName(fileExcel) & "' AND PathExcel = '" & fileExcel & "' AND PathPDF = '" & DirPdf & "'"
  1408.         Using myConn As New SqlConnection(connectionString)
  1409.             myConn.Open()
  1410.             Using myCmd As New SqlDataAdapter(sqlStr, myConn)
  1411.                 myCmd.Fill(ID_DataTable)
  1412.             End Using
  1413.             myConn.Close()
  1414.         End Using
  1415.         sqlStr = ""
  1416.         ID_Testata = Convert.ToInt16(ID_DataTable.Rows(0)(0))
  1417.         'Inizio scrittura targhe senza pdf
  1418.         Dim errorDt As System.Data.DataTable = ErrorFinder()
  1419.         Try
  1420.             For Each dr In errorDt.Rows
  1421.                 sqlStr = "INSERT INTO Dettagli (Targa, ID_Testate) VALUES ('"
  1422.                 sqlStr = sqlStr & errorDt.Rows(rowIndex)(0) & "', " & ID_Testata & ")"
  1423.                 Using myConn As New SqlConnection(connectionString)
  1424.                     myConn.Open()
  1425.                     Using myCmd As New SqlCommand(sqlStr, myConn)
  1426.                         myCmd.ExecuteNonQuery()
  1427.                     End Using
  1428.                     myConn.Close()
  1429.                 End Using
  1430.                 rowIndex += 1
  1431.             Next
  1432.         Catch ex As Exception
  1433.             Err.Clear()
  1434.         End Try
  1435.  
  1436.         'Inizio inserimento Dettagli
  1437.         Try
  1438.             rowIndex = 0
  1439.             For Each dr In dt.Rows
  1440.                 colIndex = 0
  1441.                 sqlStr = "INSERT INTO Dettagli VALUES( "
  1442.                 For Each dc In dt.Columns
  1443.                     sqlStr = sqlStr & "'" & Convert.ToString(dt.Rows(rowIndex)(colIndex)).Replace("0.00.00", "").Replace(",", ".").Replace("'", "").Trim() & "', "
  1444.                     colIndex += 1
  1445.                 Next
  1446.                 sqlStr = sqlStr & ID_Testata & ", "
  1447.                 sqlStr = sqlStr.Substring(0, sqlStr.Length - 2) & ")"
  1448.                 Using myConn As New SqlConnection(connectionString)
  1449.                     myConn.Open()
  1450.                     Using myCmd As New SqlCommand(sqlStr, myConn)
  1451.                         myCmd.ExecuteNonQuery()
  1452.                     End Using
  1453.                     myConn.Close()
  1454.                 End Using
  1455.                 rowIndex += 1
  1456.             Next
  1457.         Catch ex As Exception
  1458.             MsgBox(ex.Message)
  1459.         Finally
  1460.             'CancellaDuplicatiIdTarga("Dettagli")
  1461.             RegistraLog("Inserimento targhe e dati relativi nella tabella dettagli.", "NULL")
  1462.         End Try
  1463.     End Sub
  1464.  
  1465.     Private Function ErrorFinder() As System.Data.DataTable
  1466.         'Trova gli errori tramite la discrepanza tra i dati contenuti nella tabella TempTabXLS e nella tabella VISURE_PDF
  1467.         Dim dt As New System.Data.DataTable
  1468.         Try
  1469.             Dim sqlStr As String = "Select Targa FROM TempTabXLS WHERE Targa NOT IN (Select Targa From VISURE_PDF)"
  1470.             Using myConn As New SqlConnection(connectionString)
  1471.                 myConn.Open()
  1472.                 Using myCmd As New SqlDataAdapter(sqlStr, myConn)
  1473.                     myCmd.Fill(dt)
  1474.                 End Using
  1475.                 myConn.Close()
  1476.             End Using
  1477.         Catch ex As Exception
  1478.             MsgBox(ex.Message)
  1479.         End Try
  1480.         Return dt
  1481.     End Function
  1482.  
  1483.     Private Sub CreaCartellaPercorso()
  1484.         'Crea il percorso di salvataggio dei dati e crea le cartelle opportune.
  1485.         'Copia dei file PDF analizzati e del file Excel del Cliente nel percorso stabilito dal file .config
  1486.         Dim pathXls As String = My.Settings.PathXLS
  1487.         Dim pathPdf As String = My.Settings.PathPDF
  1488.         Dim pathFilePdf As String
  1489.  
  1490.         Try
  1491.             'Creazione cartelle FILE_XLS / FILE_PDF
  1492.             If (Not System.IO.Directory.Exists(pathXls)) Then
  1493.                 System.IO.Directory.CreateDirectory(pathXls)
  1494.             End If
  1495.             If (Not System.IO.Directory.Exists(pathPdf)) Then
  1496.                 System.IO.Directory.CreateDirectory(pathPdf)
  1497.             End If
  1498.  
  1499.             'Creazione sottocartelle singola elaborazione
  1500.             pathXls = pathXls & "\" & DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss").ToLower.Replace("/", "").Replace(" ", "").Replace(".", "") & "_" & G_IDOPERATORE
  1501.             pathPdf = pathPdf & "\" & DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss").ToLower.Replace("/", "").Replace(" ", "").Replace(".", "") & "_" & G_IDOPERATORE
  1502.             System.IO.Directory.CreateDirectory(pathXls)
  1503.             System.IO.Directory.CreateDirectory(pathPdf)
  1504.             pathXls = pathXls & "\" & Path.GetFileName(fileExcel)
  1505.  
  1506.             'Copia file pdf nella sottocartella ed eliminazione file sorgente
  1507.             For Each x In My.Computer.FileSystem.GetFiles(DirPdf, FileIO.SearchOption.SearchTopLevelOnly)
  1508.                 If Path.GetFileName(x).EndsWith(".pdf") Or Path.GetFileName(x).EndsWith(".PDF") Then
  1509.                     pathFilePdf = pathPdf & "\" & Path.GetFileName(x)
  1510.                     IO.File.Copy(x, pathFilePdf, False)
  1511.                 End If
  1512.             Next
  1513.             IO.File.Copy(fileExcel, pathXls, False)
  1514.             DirPdf = pathPdf
  1515.             fileExcel = pathXls
  1516.         Catch ex As Exception
  1517.             MsgBox(ex.Message)
  1518.         End Try
  1519.     End Sub
  1520.  
  1521.     Private Sub InserisciTestata()
  1522.         'Inserisce i dati all'interno della tabella Testata
  1523.         'Dati inseriti: Nome del file Excel del Cliente, Id dell'operatore, data ed i path utilizzati per il salvataggio dei file
  1524.         Try
  1525.             Using myConn As New SqlConnection(connectionString)
  1526.                 Dim sqlStr As String = "INSERT INTO TestateExcel VALUES(@NomeFile, @IdOperatore, @Data, @PathExcel, @PathPdf)"
  1527.                 myConn.Open()
  1528.                 Using myCmd As New SqlCommand(sqlStr, myConn)
  1529.                     'Creazione Parametri
  1530.                     myCmd.Parameters.Add("@NomeFile", SqlDbType.NVarChar)
  1531.                     myCmd.Parameters.Add("@IdOperatore", SqlDbType.Int)
  1532.                     myCmd.Parameters.Add("@Data", SqlDbType.SmallDateTime)
  1533.                     myCmd.Parameters.Add("@PathExcel", SqlDbType.NVarChar)
  1534.                     myCmd.Parameters.Add("@PathPdf", SqlDbType.NVarChar)
  1535.                     'Inizializzazione Parametri
  1536.                     myCmd.Parameters("@NomeFile").Value = Path.GetFileName(fileExcel)
  1537.                     myCmd.Parameters("@IdOperatore").Value = Convert.ToInt16(G_IDOPERATORE)
  1538.                     myCmd.Parameters("@Data").Value = DateTime.Now()
  1539.                     myCmd.Parameters("@PathExcel").Value = fileExcel
  1540.                     myCmd.Parameters("@PathPdf").Value = DirPdf
  1541.                     'Inserimento dati
  1542.                     myCmd.ExecuteNonQuery()
  1543.                 End Using
  1544.             End Using
  1545.         Catch ex As Exception
  1546.             MsgBox(ex.Message)
  1547.         End Try
  1548.     End Sub
  1549.  
  1550.     Private Sub Srch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Srch.Click
  1551.         'Esegue la ricerca dei PDF legati alla targa richiesta in input tramite una query sulle tabelle Dettagli e Anagrafica.
  1552.         'Stampa i risultati sulla maschera tramite una DataGridView
  1553.         Dim targa As String
  1554.         Dim dt As New System.Data.DataTable
  1555.         Try
  1556.             targa = TextBoxTarga.Text.Trim.ToUpper
  1557.             CancellaDuplicatiIdTarga("Dettagli")
  1558.             Dim sqlStr As String = "SELECT Targa, Telaio, Produttore, DataImmatricolazione as 'Data di Immatricolazione', DataCartaCircolazione as 'Data Rilascio C. di C.', KW, Classe, Cilindrata, Alimentazione, Tara, Posti, Assi, PrimaFormalita as 'Prima Formalità', DataPrimaFormalita as 'Data Prima Formalità', UltimaFormalita as 'Ultima Formalità', DataUltimaFormalita as 'Data Ultima Formalità', Atto, DataAtto as 'Data Atto', PrezzoVeicolo as 'Prezzo del Veicolo', Proprietario, Tipo as 'Sesso / Tipo società', DataNascita as 'Data di Nascita', ComuneNascita as 'Comune di Nascita', ComuneResidenza as 'Comune di Residenza', Indirizzo FROM Dettagli, Anagrafica WHERE Dettagli.Targa = @Targa AND Anagrafica.Targa_FK = @Targa"
  1559.             Using myConn As New SqlConnection(connectionString)
  1560.                 myConn.Open()
  1561.                 Using myDataAdapter As New SqlDataAdapter(sqlStr, myConn)
  1562.                     myDataAdapter.SelectCommand.Parameters.Add("@Targa", SqlDbType.NVarChar)
  1563.                     myDataAdapter.SelectCommand.Parameters("@Targa").Value = targa
  1564.                     myDataAdapter.Fill(dt)
  1565.                 End Using
  1566.                 myConn.Close()
  1567.             End Using
  1568.             DataGridViewTarga.DataSource = dt
  1569.             saveExcelDataGrid = dt
  1570.             SaveExcelButton.Visible = True
  1571.         Catch ex As Exception
  1572.             MsgBox("Inserire una targa corretta prima di continuare.")
  1573.         End Try
  1574.     End Sub
  1575.  
  1576.     Private Sub CercaInsieme_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CercaInsieme.Click
  1577.         saveExcelDataGrid = DataTableToDataGrid(InsiemiToDataTable())
  1578.         SaveExcelButton.Visible = True
  1579.     End Sub
  1580.  
  1581.     Private Function DataTableToDataGrid(ByVal dt As System.Data.DataTable)
  1582.         Dim excelDataTable As New System.Data.DataTable
  1583.         CancellaDuplicatiIdTarga("Dettagli")
  1584.         Try
  1585.             Dim myConn As New SqlConnection(connectionString)
  1586.             Dim sqlStr As String = "SELECT Targa, Telaio, Produttore, DataImmatricolazione as 'Data di Immatricolazione', DataCartaCircolazione as 'Data Rilascio C. di C.', KW, Classe, Cilindrata, Alimentazione, Tara, Posti, Assi, PrimaFormalita as 'Prima Formalità', DataPrimaFormalita as 'Data Prima Formalità', UltimaFormalita as 'Ultima Formalità', DataUltimaFormalita as 'Data Ultima Formalità', Atto, DataAtto as 'Data Atto', PrezzoVeicolo as 'Prezzo del Veicolo', Proprietario, Tipo as 'Sesso / Tipo società', DataNascita as 'Data di Nascita', ComuneNascita as 'Comune di Nascita', ComuneResidenza as 'Comune di Residenza', Indirizzo FROM Dettagli, Anagrafica WHERE Dettagli.Targa = @Targa AND Anagrafica.Targa_FK = @Targa"
  1587.             Dim myDataAdapter As New SqlDataAdapter(sqlStr, myConn)
  1588.             myDataAdapter.SelectCommand.Parameters.Add("@Targa", SqlDbType.NVarChar)
  1589.             Dim j As Integer = 0
  1590.             myConn.Open()
  1591.             For Each dr In dt.Rows
  1592.                 myDataAdapter.SelectCommand.Parameters("@Targa").Value = dt.Rows(j).Item(0)
  1593.                 myDataAdapter.Fill(excelDataTable)
  1594.                 j += 1
  1595.             Next
  1596.             myConn.Close()
  1597.         Catch ex As Exception
  1598.             MsgBox("Un errore è avvenuto durante la ricerca.")
  1599.             Err.Clear()
  1600.         End Try
  1601.         DataGridViewTarga.DataSource = excelDataTable
  1602.         Return excelDataTable
  1603.     End Function
  1604.  
  1605.     Private Function InsiemiToDataTable()
  1606.         Dim fileInsieme
  1607.         InsiemiExcel.InitialDirectory = "C:\"
  1608.         InsiemiExcel.Filter = "File Excel|*.xls; *.xlsx"
  1609.         If InsiemiExcel.ShowDialog = DialogResult.OK Then
  1610.             fileInsieme = InsiemiExcel.FileName
  1611.             InsiemeTextBox.Text = fileInsieme
  1612.         Else
  1613.             fileInsieme = Nothing
  1614.         End If
  1615.  
  1616.         Dim dt As New System.Data.DataTable
  1617.         Try
  1618.             Dim MyConnection As OleDbConnection
  1619.             Dim fileExcelType As String
  1620.  
  1621.             'Individuo il tipo di file Excel scelto
  1622.             If IO.Path.GetExtension(fileInsieme.ToUpper) = ".XLS" Then
  1623.                 fileExcelType = "Excel 8.0"
  1624.                 MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & fileInsieme & "';Extended Properties=" & fileExcelType & ";")
  1625.             Else
  1626.                 fileExcelType = "Excel 12.0"
  1627.                 MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & fileInsieme & "';Extended Properties=" & fileExcelType & ";")
  1628.             End If
  1629.  
  1630.             ' Apre connessione con Excel
  1631.             MyConnection.Open()
  1632.  
  1633.             'Popola data table
  1634.             Dim myTableName = MyConnection.GetSchema("Tables").Rows(0)("TABLE_NAME")
  1635.             Dim MyCommand As OleDbDataAdapter = New OleDbDataAdapter(String.Format("SELECT * FROM [{0}] ", myTableName), MyConnection)
  1636.             MyCommand.TableMappings.Add("Table", "    ")
  1637.             MyCommand.Fill(dt)
  1638.             MyConnection.Close()
  1639.             saveExcelDataGrid = dt
  1640.         Catch ex As Exception
  1641.             MsgBox("Impossibile aprire il file excel!")
  1642.             Err.Clear()
  1643.         End Try
  1644.         Return dt
  1645.     End Function
  1646.  
  1647.     Private Sub SaveExcelButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveExcelButton.Click
  1648.         ExcelExport(saveExcelDataGrid, "", False)
  1649.         SaveExcelButton.Visible = False
  1650.     End Sub
  1651. End Class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement