vb.net Tips-II

Create Access Database at run time

We start off with a simple tip provided by Pradeep Shah. To create the access database at run time you have to use the ADOX objects. ADOX Object is a set of ADO objects to perform schema related activities. ADOX stands for ADO Extensions. ADOX is an object models that provides a set of objects that can be used perform activities pertaining to Data Definition.

To execute the below code run in your VB.NET application, from the Project Menu select Add References tab, choose the COM tab, and add a reference to Microsoft ADO Ext. 2.7 for DDL and Security. 

Add a Command Button to the Form. On the click of the Button add the following code.

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim db_create As New ADOX.Catalog
        Dim db_replay As Boolean
        Try
            Dim db_CreateString As String
            Dim db_path As String
            db_path = Application.StartupPath() & "\student.mdb"
            db_CreateString = _
            "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & db_path
            db_create.Create(db_CreateString)
            db_replay = True
        Catch ex As Exception
            db_replay = False
            MessageBox.Show("database already exists")
        Finally
            db_create = Nothing
        End Try
    End Sub
End Class

Finally run the application. Notice the student.mdb file in your default folder.

List All Logical Drives in VB.NET 

This tip will explain how to get the computer's logical drives from the local system. The code will work on flavors opf Visual Basic.
This program uses the Directory.GetLogicalDrives method to retrieves the names of the logical drives on this computer in the form "<drive letter>:\". All the drive letters will displayed them in a List Box.

’Add the name space before the class

Imports System.IO
Public Class Form1
    Inherits System.Windows.Forms.Form

  
' On form load add all the drives to the List box.

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

      
 For Each drive As String In Directory.GetLogicalDrives()
          ‘add all the drives to list box
            ListBox1.Items.Add(drive)
        Next drive
    End Sub
End Class

This is tip is also provided by Pradeep Shah.

Get the Size of the Disk Space and Free space available in VB.NET

To get the total disk space in VB.NET there is no class is available and even no class will allow us to access the disk properties directly. Such programs are useful when you write installer programs, where you need to measure available disk space. However, using two ways you can find the free space and other disk drive properties.

One option is to use InteropServices to call Windows APIs directly. InteropServices allow us to call un managed code and this can be used to call the Windows API "GetDiskFreeSpaceEx". This API returns couple of disk properties including available free space, total space and total free space.

The other option is PInvoke (Platform Invocation). Using this you can call the GetDiskFreeSpaceEx API function to get free and total space, in megabytes, on the given drive.

The following sample code demonstrates how to call the Windows API GetDiskFreeSpaceEx to retrieve these values.

GetDiskFreeSpaceEx function obtains the following information about the amount of space available on a disk volume. The total amount of space, the total amount of free space, and the amount of free space available to the user associated with the calling thread.

Follow these steps to find out total disk allocated and free space available in your drive. 

Public Class Form1

    Private Declare Function GetDiskFreeSpaceEx _
          Lib "kernel32" _
          Alias "GetDiskFreeSpaceExA" _
          (ByVal lpDirectoryName As String, _
          ByRef lpFreeBytesAvailableToCaller As Long, _
          ByRef lpTotalNumberOfBytes As Long, _
          ByRef lpTotalNumberOfFreeBytes As Long) As Long

   
Public Function GetFreeSpace(ByVal Drive As String) As Long
         'returns free space in MB, formatted to two decimal places
        'e.g., msgbox("Free Space on D: "& GetFreeSpace("D:\") & "MB")

       
Dim lBytesTotal, lFreeBytes, lFreeBytesAvailable As Long
        Dim a_counter As Long

       
a_counter = GetDiskFreeSpaceEx(Drive, lFreeBytesAvailable, _
             lBytesTotal, lFreeBytes)

       
If a_counter > 0 Then

           
Return BytesToMegabytes(lFreeBytes)

        Else

            Throw New Exception("Invalid or unreadable drive")

        End If

    End Function

     Public Function GetTotalSpace(ByVal Drive As String) As String
        'returns total space in MB, formatted to two decimal places
        'e.g., msgbox("Free Space on D: "& GetTotalSpace("D:\") & "MB")

       
Dim lBytesTotal, lFreeBytes, lFreeBytesAvailable As Long
        Dim a_counter As Long

       
a_counter = GetDiskFreeSpaceEx(Drive, lFreeBytesAvailable, _
             lBytesTotal, lFreeBytes)

       
If a_counter > 0 Then
            Return BytesToMegabytes(lBytesTotal)
        Else
            Throw New Exception("Invalid or unreadable drive")
        End If
    End Function

   
Private Function BytesToMegabytes(ByVal Bytes As Long) _
    As Long

       
Dim check_counter As Double
        check_counter = (Bytes / 1024) / 1024
        BytesToMegabytes = Format(check_counter, "###,###,##0.00")
      End Function

   
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        'when you click on the Button1 it will display the total space of the Drive in the message box
        MsgBox("Free Space on D: " & GetTotalSpace("D:\") & "MB")
   End Sub

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

       
'when you click on the Button2 it display only free space available in your Drive
       MsgBox("Free Space on D: " & GetFreeSpace("D:\") & "MB")

  
End Sub
End Class

Save the code and click on the buttons at runtime and check the difference. It will show you how much free space is available and how much space you have allotted to that particular drive.

Create and Delete Directories and Subdirectories in VB.NET

Using tip you can create and delete directories and subdirectories in your hard disk. It uses the DirectoryInfo Class. This class contains methods for creating, moving, and enumerating through directories and subdirectories and delete directories.

'declare the name space at the top of the class

Imports System.IO
Public Class Form1
    Public Function CreateDirectory(ByVal FullPath As String) _
       As Boolean
        'creating the new object of the type DirectoryInfo
        Dim D_Create As New DirectoryInfo(FullPath)
        Try
            D_Create.Create()
            Return True
        Catch
            Return False
        End Try
    End Function

   
Public Function DeleteDirectory(ByVal FullPath As String) _
          As Boolean
        Dim D_Create As New DirectoryInfo(FullPath)
        Try

           
' Delete the subdirectory. The true indicates that if subdirectories
            ' or files are in this directory, they are to be deleted as well.

            D_Create.Delete(True)
            Return True
        Catch
            Return False
        End Try
    End Function

   
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        CreateDirectory(TextBox1.Text)
        MsgBox("Directory successfully created")
End Sub

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

        DeleteDirectory(TextBox1.Text)
        MsgBox("Directory successfully Deleted")
    End Sub
End Class

List all the files in a given directory.

In this tip System.IO.Directory class provides information and performs operations on directories. The GetFile method will return all the names of all files in the specified directory.

Before Executing the Code you need to add a List box, Textbox and Command button to the form. Later add the code to the form class.

Public Class Form1
    Private Sub GetNames(ByVal dir As String)
        'clear listbox box
        listbox.Items.Clear()

       
'array to hold file names
        Dim files() As String
        'get files from the directory
        files = System.IO.Directory.GetFiles(dir)
        Dim tmp As Int16
        For tmp = 0 To files.GetUpperBound(0)
            'add filenames to list box
            listbox.Items.Add(files(tmp))
        Next
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'call the Getnames function when button clicked
        GetNames(TextBox1.Text)
    End Sub
End Class

Run the application and enter the absolute path in the text box. (Example. C:\cdrom) click the Command button to view the results in the List box. 

These tips have been provided by Malini S from Bangalore. 


The Following Tip is sent from Kunal Mukhargee.
This Vb.Net tip will show you how to hide your application in the System Tray and also attach a context menu with it.

First, drag two ContextMenu controls from the toolbox in the default form. (Whenever you create a project a form is provided by default. Here we will recognize that form as the "default form.")

Then, insert these menuitems as follows:
ContextMenu1:
Restore (MenuItem1)
Exit (MenuItem2)
ContextMenu2:
Hide (MenuItem3)
Exit (MenuItem4)

Second, add a NotifyIcon control from the toolbox in the form and use these properties as follows:

Icon-> Mention the icon file which you want to show in the systemtray when your application is hiding in the system tray.
Text-> Mention the text which you want to show when the mouse cursor moves over the icon in system tray.
ContextMenu-> Mention the contextmenu which you want to attach with the notify icon. Actually this is the context menu that will show up when you right click on the icon in the system tray.

Here we will be using the default form icon as that icon for the NotifyIcon control. For that we need to add the following code in the load event of the form.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
NotifyIcon1.Icon = Me.Icon
End Sub

Now we will add the codes for the menu items click events.

'Restore MenuItem (MenuItem1) of ContextMenu1
Private Sub MenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem1.Click
Me.Show()
Me.WindowState = FormWindowState.Normal
End Sub

'Exit MenuItem (MenuItem2) of ContextMenu1
Private Sub MenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem2.Click
Application.Exit()
End Sub

'Hide MenuItem (MenuItem3) of ContextMenu2
Private Sub MenuItem3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem3.Click
Me.Hide()
End Sub

'Exit MenuItem (MenuItem4) of ContextMenu2
Private Sub MenuItem4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem4.Click
Me.Close()
End Sub


Now when we have added code for handling the click events of the menuitems. Click on the NotifyIcon on the form and set the ContextMenu property to ContextMenu1.

Now we have seen that if we double click on the icon in system tray the form shows up. For that add the following code to your form, in the double click event of the NotifyIcon control.

Private Sub NotifyIcon1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles NotifyIcon1.DoubleClick
Me.Show()
Me.WindowState = FormWindowState.Normal
End Sub


Finally add the following code in the Form Resize event to hide the form when we click on the minimize button.

Private Sub Form1_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Resize
If Me.WindowState = FormWindowState.Minimized Then
Me.Hide()
End If
End Sub


Now run the application and check it out. Try exploring the other events of the NotifyIcon control.

That’s all for the month folks. We will have exclusive Dot Net tips the next two months, as we ramp up towards Whidbey.




Added on December 16, 2007 Comment

Comments

Post a comment

Your name:

Comment: