Archive | April, 2009

Create a Visual Basic Dynamic-Link Library(dll) from the command line.

28 Apr

A Dynamic-Link Library is a non executable program made of one or more files, which contains classes, procedures, and/or other resources that other programs can use.  Because it is not an executable, it doesn’t need an entry point or the main() procedure  and it usually ends with .dll

Well, you can read more about Dynamic link libraries(dlls) on msdn or wikipedia.

In this post I’ll show you how to create a VB.Net DLL from the command line.

First you need to set up your system to use the vbc compiler. If you do not know how to do this, please read my previous post here.  So from now on I’ll assume you have set up your compiler and we are ready to go.

Steps:

  • Open notepad,  create a class, call it Person and save it as a VB file (Person.vb) . For this post we’ll create a simple Person class.  See the code for the class at the end of the post below.

>>CodeListing No.1 – The Person Class

  • Create a new folder in your main drive (in my case C:\) and call it PersonLibrary.  Save the above class in this folder.
  • Click Start > Run > type cmd  and click OK to open the command prompt.
  • Change to the PersonLibrary directory as shown in the image below.

changedirectory

How to Create a Dynamic-Link Library from the command line.

  1. There are two options. The first one is you create a library that has the same name as the source file.
  • To create a Dll that has the same name as the source file, at the command prompt type the following command.

vbc /target:library Person.vb

  • The command is vbc /target:library nameOfSourceFile.vb notice the space after vbc and the other space after library. Make sure you include them.
  • Browse to the PersonLibrary folder and you’ll see that the Person.dll dynamic-link library has been created. See the image below.

personlibrary1

2.  The other option is that you can provide your own name for the library.

  • To create a Dll that has your own desired name, at the command prompt type the following command.

vbc /target:library /out:PersonLibrary.dll Person.vb

  • The command is vbc /target:library /out:DesiredNameOfLibrary.dll nameOfSourceFile.vb
  • Now browse to the PersonLibrary folder and you’ll see the newly created dll with our custom name PersonLibrary.dll, as well as the old one, Person.dll

personlibrary2

And thats all there is to it. You are done and you have your libraries and you can distribute them now or use them from an application.

How to use the Library.

Before you use the library you simply have to import it into your project and add it as a reference using the command line when compiling.

  • Open Notepad and type in the following code
Imports System
Imports PersonLibrary

Module MainModule
    Sub Main()
        Dim p As New Person("Mike F", "Masao")
        p.Addresses(0) = "6032, Olacity, Arusha"
        p.Addresses(1) = "Tanzania"
        p.Citizenship = "Tanzanian"
        p.BirthDate = #8/21/1982#

        Console.WriteLine("Full Name: " & p.FullName("Mr."))
        Console.WriteLine("Address1: " & p.Addresses(0))
        Console.WriteLine("Address2: " & p.Addresses(1))
        Console.WriteLine("Citizenship: " & p.Citizenship)
        Console.WriteLine("Age: " & p.Age)

        Console.Read()
    End Sub

End Module
  • Save the file as MainProgram.vb under our PersonLibrary folder.
  • Now go back to the command prompt and issue the following command, which will add the library as a reference to the project and then compile the MainProgram code to an executable.

vbc /reference:PersonLibrary.dll MainProgram.vb

  • The command is vbc /reference:NameOfLibrary.dll NameOfMainProgram.vb
  • After the above steps, browse again to the PersonLibrary folder and you’ll see your libraries and your MainProgram.exe executable file as seen in the image below.

aftercompiling

  • Now double click the MainProgram.exe file and you should see the following output on your screen.

output

And we are done.

So now you can create your own libraries by using just notepad and the command prompt.

Hope this was helpful. Till next time, yours truly.

CodeListing No.1  – The Person Class

Public Class Person
    'Fields
    Public FirstName As String
    Public LastName As String
    Public m_BirthDate As Date
    'You can define up to 4 addresses for this person
    Public m_Addresses(3) As String
    Public Citizenship As String = ""

    Sub New(ByVal firstname As String, ByVal lastname As String)
        Me.FirstName = firstname
        Me.LastName = lastname
    End Sub
    Public Property BirthDate() As Date
        Get
            Return m_BirthDate
        End Get
        Set(ByVal value As Date)
            m_BirthDate = value
        End Set
    End Property

    Function FullName(Optional ByVal title As String = "") As String
        FullName = ""
        'use the title if provided
        If title <> "" Then FullName = title & " "
        'append first and last names
        FullName &= FirstName & " " & LastName
    End Function

    'Age is a ReadOnly property
    Public ReadOnly Property Age() As Integer
        Get
            Return Year(Now) - Year(m_BirthDate)
        End Get
    End Property

    Public Property Addresses(ByVal index As Integer) As String
        Get
            If index < 0 Or index > UBound(m_Addresses) Then
                Throw New IndexOutOfRangeException("Invalid address Index")
            End If
            Return m_Addresses(index)
        End Get
        Set(ByVal value As String)
            If index < 0 Or index > UBound(m_Addresses) Then
                Throw New IndexOutOfRangeException("Invalid address Index")
            End If
            m_Addresses(index) = value
        End Set
    End Property

End Class

Using the Timer object and Event Handlers to automatically control actions.

23 Apr

I know I haven’t been able to write for a long time now, and I’ll still be lagging up, but hopefully soon I’ll be back, with full speed, bringing you a new post every week.

Today I’ll show you how to use the System.Windows.Forms.Timer to control when to perform some action or call some procedures. A good example is when you maybe need to send a report to your boss,  say every day at 4pm.timers

In this case, you need a timer object, that calls an event handler which checks the time against your system time to see if it is 4pm or after and then call the procedure that sends the report. Let’s see how you can go about, doing that.

What we need.

  1. A Timer object.
  2. A method to serve as an event handler
  3. Your custom method that does whatever work you want done when it’s time.

We’ll make use of the AddHandler statement to hook up the Timer’s Tick event with our event handler. The AddHandler statement is used to associate an event with an event handler at run time.

See the full code below.

Imports System

Module Sample

Public Class Test

Private Shared myTimer As New System.Windows.Forms.Timer()

Public Shared Sub Main

	'hook up the event to the handler method

        AddHandler myTimer.Tick, AddressOf CheckTime

        ' Sets the timer interval to 1 second and start it.

        myTimer.Interval = 1000

        myTimer.Start()

	MsgBox("The timer is running now....")

	Console.Read()
   RemoveHandler myTimer.Tick, AddressOf CheckTime

End Sub

Public Shared Sub CheckTime(ByVal sender As System.Object, ByVal e As System.EventArgs)

        If DateTime.Parse(DateTime.Now.ToShortTimeString) > DateTime.Parse("11:00 AM") Then

            MsgBox("The time is : " & DateTime.Now.ToShortTimeString)

            'Call SendPendingInvoices()

        End If

    End Sub

End Class
End Module

As you can see above, we created a new Timer object, and in our main procedure, or start up procedure, we hooked up the Timer.Tick event to our CheckTime event handler method, so that it gets called every time the tick event of the timer is fired.  In our case that will be every 1 second.

To test the code, create a new blank console project and copy and paste the code above and simply click run. If your system time is greater than 11:00 AM then you should see a message box pop up every second showing you the current time from your system.

Hope this was helpful.

Till next time, yours truly.

A method for searching a ListView

1 Apr

Here is a simple method that will search a ListView and its subitems and select or highlight the ListViewItem or SubItem that begins with  the search criteria.

In this sample I make use of the ListView.FindItemWithText method which takes three parameters, the first a string specifying the item to find, second a boolen value to specify whether the subitems should be included and the third, the starting index in the listview items collection.

This is how the method works.

  1. The method takes two parameters, first the name of the ListView, and second the text to find.
  2. It starts the search at the first item and goes on until it finds a match. The found ListViewItem is then highlighted.
  3. If you click search again, its starts at the index of the last item and continues until it finds another match.
  4. If no match is found and you click search again, it starts from the beggining, at the first item’s index.

Using the code.

Create a listview object, load it with items and subitems. On your form, outside the method, create these 2 variables:

  • lastSearch, String - This will save your previous search text and compare it with the current text when you call the method again.
  • lastIndex - Integer – Set it to -1. - This will save the index of the found item so that the method starts from here when called again.

After this, call the method and pass the name of the listview you want to search and the text to find.

Here is the full code. You can use it as is, or you can modify it and add some changes as you see fit.

    Private lastSearch As String = ""
    Private lastIndex As Integer = -1

Private Sub SearchListView(ByVal listView As ListView, ByVal txtFind As String)

        Dim foundItem As ListViewItem = Nothing

        If lastSearch = txtFind Then
            If lastIndex < listView.Items.Count - 1 Then
                foundItem = listView.FindItemWithText(txtFind, True, lastIndex + 1)
            Else
                foundItem = listView.FindItemWithText(txtFind, True, 0)
            End If
        Else
            foundItem = listView.FindItemWithText(txtFind, True, 0)
        End If
        lastSearch = txtFind
        lastIndex = -1
        If Not (foundItem Is Nothing) Then
            lastIndex = foundItem.Index
            listView.Focus()
            listView.Items(foundItem.Index).Selected = True
        End If
    End Sub

I wrote this in .Net 2.0 but it should work with 3.0 and 3.5. The method is not perfect, its just an eye opener and the rest is up to the user to dig and improvise.

Till next time, yours truly.

Follow

Get every new post delivered to your Inbox.