Thursday, September 12, 2013

MDB and ACCDB file searcher.

MDB and ACCDB file searcher.

Find all MS-Access files from a directory and display them on your screen. Here is a sample code in vb. At first, I might be pretty useless because Windows do have a file searcher but what if you want to do some operation over each file? That is why this sample code might be useful for you.
I also include a dynamic tooltip MouseMouve for the ListBox and very basic functions to make this program more enjoyable.
You could download the project sample at the end of this post.
MDB and ACCDB file searcher




Public Class Form1
    Private _ConnectionString As String = "Provider =Microsoft.ACE.OLEDB.12.0; Data Source = "
    Private _TableName As String
    Private _DA As Data.OleDb.OleDbDataAdapter
    Private _DS As Data.DataSet
    Private _BS As BindingSource
    Private _DT As DataTable
    Private _sPath As String
    Property _oOleDbConnection As System.Data.OleDb.OleDbConnection
    Private ttindex As Integer
    Private _Tooltips As ToolTip
    Private tSearch_MDB As Threading.Thread
    Private tSearch_ACCDB As Threading.Thread
    Structure Arg_tfindfiles
        Public Path As String
        Public Patern As String
    End Structure
#Region "Contructor and load functions"
    Public Sub New()
        InitializeComponent()
        _Tooltips = New ToolTip
    End Sub

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        'nothing here
    End Sub
    Private Sub ShutMe(sender As System.Object, e As System.EventArgs) Handles CloseToolStripMenuItem.Click
        Me.Close()
    End Sub
#End Region


    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        If FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            TextBox1.Text = FolderBrowserDialog1.SelectedPath
        End If
    End Sub

    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        Scan_for_Access_Files()
    End Sub

    Private Sub Scan_for_Access_Files()
        Me.ListBox1.Items.Clear()
        Dim oArg_mdb As Arg_tfindfiles
        Dim oArg_accdb As Arg_tfindfiles

        If tSearch_MDB IsNot Nothing Then tSearch_MDB = Nothing
        If tSearch_MDB Is Nothing Then tSearch_MDB = New Threading.Thread(AddressOf findfiles)
        tSearch_MDB.IsBackground = True
        oArg_mdb.Path = TextBox1.Text
        oArg_mdb.Patern = "*.mdb"
        tSearch_MDB.Start(oArg_mdb)

        If tSearch_ACCDB IsNot Nothing Then tSearch_ACCDB = Nothing
        If tSearch_ACCDB Is Nothing Then tSearch_ACCDB = New Threading.Thread(AddressOf findfiles)
        tSearch_ACCDB.IsBackground = True
        oArg_accdb.Path = TextBox1.Text
        oArg_accdb.Patern = "*.accdb"
        tSearch_ACCDB.Start(oArg_accdb)


        'findfiles(TextBox1.Text, "*.mdb") 'classic function
        'findfiles(TextBox1.Text, "*.accdb") 'classic function
    End Sub
    Private Sub findfiles(oArg As Arg_tfindfiles)
        Dim dirPath As String = oArg.Path 'need more verification
        Dim String_to_Search As String = oArg.Patern 'need more verification
        Dim Hash_Access_Temp As New HashSet(Of String)()
        Dim index1 As Integer
        Dim index2 As Integer
        Dim path_valid As Boolean
        Dim str_temp As String
        Dim wp As System.Security.Principal.WindowsPrincipal
        Dim IsAdmin As Boolean
        Dim oDirectorySecurity As System.Security.AccessControl.DirectorySecurity
        Dim oAuthorizationRuleCollection As System.Security.AccessControl.AuthorizationRuleCollection
        Dim oRule As System.Security.AccessControl.FileSystemAccessRule
        Dim Security_valid As Boolean
        Dim Is_Folder_shortcut As Boolean
        Dim IEDirectories As System.Collections.Generic.IEnumerable(Of String)
        Dim oFiles As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
        Dim oDirectories As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
        Try
            path_valid = True
            dirPath = Trim(dirPath)
            'check if sPath is not zero length
            If Len(dirPath) <= 0 Then
                path_valid = False
            End If

            'check for invalid char
            ' \ * | : ? < > / except the \ because is a directory seperator
            ' and * that means to ignore whatever inside the other chars. (optional)
            If InStr(dirPath, "|", CompareMethod.Binary) > 0 Then
                path_valid = False
            End If
            If InStr(dirPath, ">", CompareMethod.Binary) > 0 Then
                path_valid = False
            End If
            If InStr(dirPath, "<", CompareMethod.Binary) > 0 Then
                path_valid = False
            End If
            If InStr(dirPath, "?", CompareMethod.Binary) > 0 Then
                path_valid = False
            End If
            If InStr(dirPath, ":", CompareMethod.Binary) = 2 Then
                'very basic way to check if there is a ":" in the Path.
                str_temp = dirPath.Substring(2, Len(dirPath) - 2)
                If InStr(str_temp, ":", CompareMethod.Binary) > 0 Then
                    path_valid = False
                End If

            End If
            If InStr(dirPath, "*", CompareMethod.Binary) > 0 Then
                path_valid = False
            End If
            'be careful with non-english caracters


            '----------------------------------------------
            ' is administrator
            '----------------------------------------------
            IsAdmin = False
            wp = New System.Security.Principal.WindowsPrincipal(Security.Principal.WindowsIdentity.GetCurrent())
            If wp.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator) Then
                'Security_valid = True
                IsAdmin = True
            End If

            '----------------------------------------------
            ' SECURITY (Role)
            '----------------------------------------------



            Security_valid = False
            oDirectorySecurity = IO.Directory.GetAccessControl(dirPath)
            oAuthorizationRuleCollection = oDirectorySecurity.GetAccessRules(True, True, Type.GetType("System.Security.Principal.NTAccount"))

            For Each oRule In oAuthorizationRuleCollection

                If oRule.FileSystemRights = Security.AccessControl.FileSystemRights.FullControl Then
                    If InStr(oRule.IdentityReference.Value, My.User.Name) > 0 Then
                        Security_valid = True
                    End If

                    If InStr(oRule.IdentityReference.Value, "Admin") > 0 Then
                        If IsAdmin Then
                            Security_valid = True
                        End If
                    End If
                ElseIf oRule.FileSystemRights = Security.AccessControl.FileSystemRights.Read Then
                    If InStr(oRule.IdentityReference.Value, My.User.Name) > 0 Then
                        Security_valid = True
                    End If

                    If InStr(oRule.IdentityReference.Value, "Admin") > 0 Then
                        If IsAdmin Then
                            Security_valid = True
                        End If
                    End If
                ElseIf oRule.FileSystemRights = Security.AccessControl.FileSystemRights.ListDirectory Then
                    If InStr(oRule.IdentityReference.Value, My.User.Name) > 0 Then
                        Security_valid = True
                    End If

                    If InStr(oRule.IdentityReference.Value, "Admin") > 0 Then
                        If IsAdmin Then
                            Security_valid = True
                        End If
                    End If
                    If InStr(oRule.IdentityReference.Value, "Everyone") > 0 Then
                        If IsAdmin Then
                            Security_valid = True
                        End If
                    End If
                End If

            Next

            Security_valid = True
            '----------------------------------------------
            ' SECURITY (folder Shortcut)
            '----------------------------------------------

            'Is_Folder_shortcut = False
            If dirPath.StartsWith("c:\Documents and Settings", True, System.Globalization.CultureInfo.CurrentCulture) Then
                'very basic way to force you to be very carefull with that folder
                Is_Folder_shortcut = True
            End If


            Try
                IEDirectories = IO.Directory.EnumerateDirectories(dirPath)
            Catch ex As Exception
                If ex.Message.Contains("is denied") Then Exit Sub
            End Try
            '
            'Dim oAccess As System.Security.AccessControl.DirectorySecurity
            'Dim oAccess2 As System.Security.AccessControl.DirectorySecurity
            'oAccess = IO.Directory.GetAccessControl(params.Path)
            'oAccess2 = IO.Directory.GetAccessControl("C:\Program Files (x86)")
            '----------------------------------------------
            ' IF ALL OK, THEN DISPLAY THE RESULT
            '----------------------------------------------

            'oForm2.ListBox1.Items.Clear() ' recursive search file : don't clear the listBox
            If path_valid = True And Security_valid = True And Is_Folder_shortcut = False Then

                'la ligne Document and settings pose problème
                Try

                    'Recherche selon l'usager
                    oFiles = My.Computer.FileSystem.GetFiles( _
       dirPath, FileIO.SearchOption.SearchTopLevelOnly, String_to_Search)

                    Try
                        For index1 = 0 To oFiles.Count - 1 Step 1
                            Me.Invoke(New MethodInvoker(Sub() Me.ListBox1.Items.Add(oFiles(index1))))
                        Next
                    Catch ex As Exception
                        'MsgBox("index1" & oFiles(index1))
                    End Try

                Catch ex As Exception ': MsgBox(ex.StackTrace)


                Finally

                End Try

                Try

                    oDirectories = My.Computer.FileSystem.GetDirectories(dirPath, FileIO.SearchOption.SearchTopLevelOnly)
                    For index2 = 0 To oDirectories.Count - 1 Step 1

                        Dim error_directory As Boolean
                        error_directory = False
                        Try
                            IEDirectories = IO.Directory.EnumerateDirectories(oDirectories.Item(index2))
                        Catch ex As Exception
                            If ex.Message.Contains("is denied") Then error_directory = True
                        Finally
                            If Not error_directory Then
                                dirPath = oDirectories.Item(index2)
                                Dim oArg1 As Arg_tfindfiles
                                oArg1.Path = oDirectories(index2)
                                oArg1.Patern = String_to_Search
                                findfiles(oArg1) ''recursive search file : re-use "himself"
                            End If
                        End Try

                    Next
                Catch ex As Exception ': MsgBox(ex.StackTrace)

                End Try

            Else
                If Not Security_valid Then

                Else
                    'MsgBox("path_valid =" & path_valid & vbCrLf & "Security_valid =" & Security_valid)
                End If

            End If
        Catch e As System.Threading.ThreadAbortException
            Console.WriteLine("Thread - caught ThreadAbortException - resetting.")
            Console.WriteLine("Exception message: {0}", e.Message)
            Threading.Thread.ResetAbort()
        Catch ex As Exception


        End Try

    End Sub

    Private Sub CheckedListBox1_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs)
        If ttindex <> Me.ListBox1.IndexFromPoint(e.Location) Then
            ShowTooltips()
        End If
    End Sub


    Private Sub CheckedListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs)

    End Sub

    Private Sub ShowTooltips()
        ttindex = Me.ListBox1.IndexFromPoint(ListBox1.PointToClient(MousePosition))
        If ttindex >= 0 Then
            Dim p As Point = PointToClient(MousePosition)
            Me._Tooltips.Show(Me.ListBox1.Items(ttindex), Me, p.X, p.Y, 5000)
        End If
    End Sub

    Private Sub AboutToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles AboutToolStripMenuItem.Click
        Dim sString As String = ""
        sString = sString & "This is a sample" & vbCrLf
        sString = sString & "" & vbCrLf
        sString = sString & "Made by Check-Kay Wong" & vbCrLf

        MsgBox(sString, MsgBoxStyle.MsgBoxHelp, My.Application.Info.Title)

    End Sub


End Class



No comments:

Post a Comment