Monday, May 22, 2006

BrainNet I - Handwriting Recognition In .NET

Contents


1. Overview

Solution Architect: "We have a new project. We need to develop a brain tumor recognition system. I hope you can do that?"

Dumb (And Lazy) Programmer: "No. Oh, probably yes - let me search whether I can I get a component or library for that"

The most important objective of this article series is to
  • Demonstrate some practical uses neural network programming
  • Give you a fair idea regarding neurons, neural networks and their applications
  • Introduce BrainNet library - an Artificial Neural Network library I developed - mainly using the .NET framework.

BrainNet, as it is now, is not a commercial standard library - it is just in its beta stage. However, I would like to put BrainNet in front of the open source community - mainly to

  • Create an awareness among programmers about Neural Network systems
  • Initialize some discussions about practical applications of Neural Networks in emerging systems

In the process, I will explain how to develop some cool Neural Network applications as well. For example, even in this introductory article, you are learning how to develop two Neural Network programs

  • DigitalNeuralGate - A Two input neural digital gate
  • PatternDetector - A simple handwriting/pattern detection program

Who knows, some times these articles can trigger some new concepts in you, and that may even change the whole way we look at the world right now - Anyway, Good luck, Happy Coding!!

1.1 Introduction To This Article Series

I am planning to write few articles, regarding Neural Networks and BrainNet Neural Network Library. In this article series, I will

  • Give you tips regarding how to use this neural network library in your own projects.
  • Explain in simple English what exactly is a neural network.
  • Explain the concept of a neuron, and a neural network.
  • Introduce and explain the programming model and design of the BrainNet library.
  • Introduce and explain Neural XML (NXML), an XML based programming language (which is a part of BrainNet library), for creating, training and running Neural Networks.

In short, after reading this article series, you will

  • Obtain a fair understanding regarding Neurons and neural networks
  • Gain a good concept regarding intelligent systems
  • Learn how to play with this neural network library to use it in your projects.
  • Understand how to develop some cool neural network programs

When we discuss the BrainNet library, we should analyze

  1. What we can do with this library
    • The answer to this question will give you proper understanding regarding how to use the library in your projects.
  2. What is inside the library or the actual implementation and design of the library
    • The answer to this question will give you proper understanding regarding how to extend the library yourself, and modify it to suit your needs.

1.2 Introduction To This Article

This is the first article in this series. This article tries to answer the first question - What we can do with this library. In this article,

  • I'll give you a very high level view regarding neural networks
  • I'll explain how to use BrainNet library in your projects to implement Neural Network logic.

Also, in this article, we will discuss how to develop two applications using BrainNet library,

  • DigitalNeuralGate - A Two input neural digital gate which can be trained to perform functions of various digital gates (like XOR, AND, OR etc)
  • PatternDetector - A simple handwriting/pattern detection program which can analyze an image to detect it.

The future articles will give you more details - Right now, my objective is to provide a good ground even for some one who don't know Neural Network programming at all. You can find the source code of all these projects in the related source code zip file.

1.3 Some Interesting Notes

Now, few words regarding the emerging trends and future computing.

These days Biologically inspired computing projects are getting very popular. They are used in various spheres, including learning and recognition systems, business prediction, data mining, pattern detection etc, to name a few.

This article is the first one in the series of articles related to biologically inspired computing. I am planning to discuss more topics like Genetic Algorithm, Conway's Game Of Life etc in my future articles. My most important objective is to create an awareness in the programming community regarding the possibilities of merging these diverse technologies and logics together - to invent better systems with more accuracy. For sure, the future is heading towards hybrid systems.

For me, the major inspiration in learning these topics is simply the 'natural' beauty in these topics. As we all know, nature is a misery, and we can learn a lot from nature, and when we can transform this knowledge about nature to application (using computers), a programmer is attaining the level of an artist. Just as an artist gets inspired by nature, I believe that a scientist and a programmer can also get intuitions in the same way. If you ask a poet, how he wrote a poem, he may say - "It came to me from a silent corner in my mind". Similarly - I believe - if you ask yourself how you got the most wonderful programming logic or idea you ever formulated in your life - you may utter the same words.

Tip: I heard a story long ago, about the great Albert Einstein. Einstein got the spark of Relativity theory from an intuition that came to his mind - i.e, One day he thought, what may happen if we travel with a light ray (in the same speed), and see it from there.

2. Introducing BrainNet Library - Developing A Simple Neural Digital Gate

You can use the library straight away in your projects- even with out understanding much regarding the actual theory behind neural networks. In this section

  • I will explain some basic facts about neural networks
  • We will develop a simple digital neural gate - i.e, a gate with two inputs and one output which can be trained to perform the functions of various gates like AND gate, OR gate, XOR gate etc.

2.1 Some Very Basic Facts

You should understand some basic facts about neural networks before we begin.

  • A Neural Network consists of various layers
  • Each layer can any number of neurons in it.

Here are some basic facts about the structure of a neural network

  • The first layer of the network is called an input layer, and it is here we apply the input
  • The last layer is called the output layer, and it is from here we take the output.
  • A neural network can have any number of hidden layers, between the input and output layer.
  • In most neural network models, a neuron in one layer is connected to all neurons in the next layer.

Fig: A 2-2-1 Network

For example, in the above network, N1 and N2 are neurons in input layer, N3 and N4 are neurons in hidden layer, and N5 is the neuron in output layer. We provide the inputs to N1 and N2. Each neuron in each layer is connected to all neurons in next layer. The above network can be called a 2-2-1 network, based on the number of neurons in each layer.

Now, some basic facts about training.

  • You can train a neural network by providing inputs and outputs.
  • The network will actually learn from the inputs and outputs -this is explained in detail later.
  • Once training is over, you can provide the inputs to obtain the outputs.

2.2 Using The BrainNet Library To Develop A 2-2-1 Network

Now we will see how you can use the BrainNet library to develop a neural network, which can be trained to perform digital gate functions. We are going to create a 2-2-1 network - which means, a network with two input neurons, two hidden layer neurons and one output neuron - exactly as shown in the picture above. Then, we will see how to train this network to perform the functions of various two input digital gates - like AND gate, OR gate, XOR gate etc.

The important point to note is that, we can train the same network to learn the functions of various gates. The network will learn which output to produce for a given input, from the truth table of a gate - after a number of training rounds.

Note: This project is included in the source code zip attached above with this article. Extract the zip, open the solution in from Visual Studio.NET, set the startup project as NeuralGate and run the project.

The DigitalNeuralGate Class

To use BrainNet library in your project, you should create a reference from your project to the BrainNet.NeuralFramework.Dll library file.

Let us see the code of DigitalNeuralGate class. In the constructor of the class, we are basically creating a Neural network with two neurons in first layer, two neurons in the hidden layer, and one neuron in the output layer. The Train function will pass a training data object (consists of inputs and outputs) to the TrainNetwork function of the library. The Run function will pass an array list as input to the RunNetwork function of the library.

'Let us import the BrainNet framework

Imports BrainNet.NeuralFramework

'<summary> Our simple digital neural gate class </summary>
Public Class DigitalNeuralGate

    'A variable to hold our network
    Private network As BrainNet.NeuralFramework.INeuralNetwork

    '<summary> This is the constructor. Here, we will create a 2-2-1 network </summary>
    Public Sub New()

        'Create the factory to create a Backward Propagation Neural Network
        'Backward Propagation neural network is a commonly used neural network model
        Dim factory As New BrainNet.NeuralFramework.BackPropNetworkFactory()

        'This is an array list which holds the number of neurons in each layer
        Dim layers As New ArrayList()

        'We need 2 neurons in first layer
        layers.Add(2)
        'We need 2 neurons in the second layer (the second layer is the first
        'hidden layer)
        layers.Add(2)
        'We need one neuron in the output layer
        layers.Add(1)

        'Provide the arraylist as the parameter, to create a network
        network = factory.CreateNetwork(layers)

        'Now, network holds a 2-2-1 neural network object in it.

    End Sub


    '<summary> This is the function for training the network using
    'the brainnet library </summary>
    Public Sub Train(ByVal input1 As Long, ByVal input2 As Long, ByVal output As Long)

        'Create a training data object
        Dim td As New TrainingData()

        'Add inputs to the training data object
        td.Inputs.Add(input1)
        td.Inputs.Add(input2)

        'Add expected output to the training data object
        td.Outputs.Add(output)

        'Train the network one time
        network.TrainNetwork(td)

    End Sub

    '<summary>This is the function for running the network using the
    'brainnet library </summary>
    Public Function Run(ByVal input1 As Long, ByVal input2 As Long) As Double

        'Declare an arraylist to provide as input to the Run method
        Dim inputs As New ArrayList()

        'Add the first input
        inputs.Add(input1)
        'Add the second input
        inputs.Add(input2)

        'Get the output, by calling the network's RunNetwork method
        Dim outputs As ArrayList = network.RunNetwork(inputs)

        'As we have only one neuron in the output layer,
        'let us return its output
        Return outputs(0)

    End Function



End Class

The code is self explanatory, and it is heavily commented. How ever, here are some more points.

  • Explanation of code inside Sub New() - Creating a neural network using BrainNet library

    You can create a network by creating an object of type BrainNet.NeuralFramework.BackPropNetworkFactory and by calling the CreateNetwork function of the factory object.

    • Kindly have a look at the constructor of the class, we used the CreateNetwork function of the factory object of type BrainNet.NeuralFramework.BackPropNetworkFactory to create our neural network object.
    • We provided the number of neurons in each layers as the input to the CreateNetwork function, using an ArrayList.
    • The CreateNetwork function will return an object of type BrainNet.NeuralFramework.INeuralNetwork.
    • If you need to understand more about factory pattern (and its use), reading my article regarding Design Patterns [Click Here] may help.

  • Explanation of code inside Train() function
    • Training can be done by calling the TrainNetwork function of the network. The input to the train network function is a TrainingData object. A TrainingData object consist of two array lists - Inputs and Outputs.
    • The number of elements in TrainingData.Inputs should match exactly with the number of neurons in your input layer.
    • The number of elements in TrainingData.Outputs should match exactly with the number of neurons in your output layer.

  • Explanation of code inside Run() function
    • You can call the RunNetwork function of the network, to run the network after training it. The input parameter to the Run function is an array list which consists of the inputs to the input layer. Again, the number of elements in this array list should match the number of neurons in input layer.
    • The Run function will return an array list which consists of the output values. The number of elements in this array list will be equal to the number of elements in the output layer.

A User Interface To Test Our DigitalNeuralGate Class

To test the digital neural gate, let us create a simple interface which can create a gate, read the inputs to train the gate, and obtain the output to display it.

Fig: User Interface To Test Our Gate

Here, we create a new object of our DigitalNeuralGate when the form loads (See the Form Load event in source code). Also, the user can create a new DigitalNeuralGate by clicking the 'Reset Gate' button. In the beginning, the Truth Table provided in the training text boxes are initialized to match the Truth Table of XOR gate (I hope you still remember simple Boolean Algebra). However, you can change the truth table by clicking the links, or you can provide custom truth table by entering directly in the text boxes. Run the project and see.

To begin with, Reset the Gate by clicking 'Reset Gate', and just click the 'Run Network' button and see the output. The output doesn't match the truth table output. Now, we can train the network using the values in the truth table. Click the 'Train 1000 Times' button and click the 'Run Network' button. You can see the output is getting closer to the expected output - that is, the network is learning. Do this a couple of times, and see the improvement in accuracy.

To try with a different truth table, Click 'Reset Gate', change the truth table, and repeat the above steps as required.

The source code is included in the zip file. Kindly open it and have a look at the project.

TrainOnce is a simple function which calls the Train function of the gate we just developed above.

   'Train the  network once, by using the inputs and output
    Sub TrainOnce()

        'Train the network using the training data, by passing
        'inputs and outputs to the train function of the gate

        'inp11, inp12, out1 etc are textbox names
        gate.Train(CLng(Me.inp11.Text), CLng(Me.inp12.Text), CLng(Me.out1.Text))
        gate.Train(CLng(Me.inp21.Text), CLng(Me.inp22.Text), CLng(Me.out2.Text))
        gate.Train(CLng(Me.inp31.Text), CLng(Me.inp32.Text), CLng(Me.out3.Text))
        gate.Train(CLng(Me.inp41.Text), CLng(Me.inp42.Text), CLng(Me.out4.Text))

    End Sub

This function handles the click event of 'Train 1000 times' button. It simply calls the above TrainOnce function 1000 times

    'Train the network 1000 times
    Private Sub cmdTrain1000_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles cmdTrain1000.Click
        Dim i As Integer
        Try
            'Call the TrainOnce function 1000 times
            For i = 0 To 1000
                TrainOnce()
            Next
        Catch ex As Exception
            MsgBox("Error. Check whether the input is valid - " + ex.Message)
        End Try
    End Sub

This function handles the click event of 'Run Network' button, to run the network by providing inputs and setting the outputs to the output text boxes

    'Run the network to get the output, and show it in the text boxes
    Private Sub cmdRun_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles cmdRun.Click
        Try
            'rout1, rinp11, rinp12 etc are textbox names
            rout1.Text = gate.Run(CLng(Me.rinp11.Text), CLng(Me.rinp12.Text))
            rout2.Text = gate.Run(CLng(Me.rinp21.Text), CLng(Me.rinp22.Text))
            rout3.Text = gate.Run(CLng(Me.rinp31.Text), CLng(Me.rinp32.Text))
            rout4.Text = gate.Run(CLng(Me.rinp41.Text), CLng(Me.rinp42.Text))
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub

Now, I hope, you have notices a very important fact. That is

  • You haven't changed any algorithm inside the DigitalNeuralGate, but DigitalNeuralGate is producing almost correct outputs when you teach it with various truth table. I.e, the logics, AND, OR, XOR etc can be implemented, by training the system externally with the logic, rather than changing the system internally.

Important: Just keep this sentence in your mind for your life time (though it can be misleading right now) - "A Neural Network is not programmed to produce outputs, instead it is trained to perform a particular task"

In this section, we just went through a very abstract overview regarding the capabilities, simplicity and flexibility of BrainNet neural network library.

2.3 Saving And Loading A Network

BrainNet offers built in support for persistence of neural networks. For example, in the above case, after training a Gate, you may need to save its state to load it later. For this, you can use the NetworkSerializer class in the BrainNet library.

To demonstrate this feature, let us add two functions to our DigitalNeuralGate class.

    '<summary>This is the function is for saving this gate to 
    'an xml file </summary>
    Public Sub Save(ByVal file As String)
        Dim ser As New BrainNet.NeuralFramework.NetworkSerializer()
        ser.SaveNetwork(file, network)
    End Sub

    '<summary>This is the function is for loading this gate 
    'from an xml file </summary>
    Public Sub Load(ByVal file As String)
        Dim ser As New BrainNet.NeuralFramework.NetworkSerializer()
        ser.LoadNetwork(file, network)
    End Sub

The SaveNetwork method with in NetworkSerializer class will save the network to a specified path, and the LoadNetwork function will load the network back.

3. Developing An Image/Pattern Detection System

In the above example, we developed a simple application - a two input gate that can be trained to perform the function of any digital gate - using Brian Net library. Now, it is time to go for something more exciting and powerful - a pattern/image detection program using BrainNet library. We provide a set of images as input to the network along with an ASCII character that corresponds to each input - and we will examine whether the network can predict a character when an arbitrary image is given.

Surprisingly, the project is pretty easy to develop. This is because, BrainNet library provides some functionalities to deal directly with images. This project will demonstrate

  • Built in support for image processing/detection and pattern processing in BrainNet library
  • Built in support for advanced training using Training Queues in BrainNet library.

Before going to the code and explanation, let us see what the application really does. You can find the application and source code in the attached zip file. Load the solution in Microsoft Visual Studio.NET, set the startup project as PatternDetector, and run the project.

3.1 Playing With The Pattern Detection Program

Run the program, and you will see the Pattern Detection dialog box. The pattern detection program can 'learn' the ASCII characters, corresponding to a bitmap (20 x 20 pixel size).

First of all, you need to train the network. To train the network, give some images and corresponding ASCII character value from the 'Train This Network' section.

Fig: Training - Adding images and corresponding character

To provide training data

  • Click 'Browse' to load an image to the picture box (You can find some images in the 'bin' folder of PatternDetector - Also, you can create 20 x 20 monochrome images in Paintbrush if you want).

  • Enter the ASCII character that corresponds to the image - for example, if you are loading image of character 'A', enter 'A' in the text box.

  • Click 'Add To Queue' button

To train the network

  • After adding the images to the training queue as explained earlier, click 'Start Training' button. Train the network at least 1000 times, for a below average accuracy. When you click the 'Start Training' button, training will start.

  • You will see a progress bar, indicating the training progress.

Detecting A Pattern

  • Once the training is completed, go to the 'Detect using Network' pane.

  • Load an image by clicking the browse button, and click 'Detect This Image Now' button to detect the pattern

  • If you trained the Network sufficient number of times, and if you provided enough samples, you will get the correct output.

Fig: Detecting The Image

3.2 Playing With The Source Code

The code of PatternDetector is pretty simple. If you can have a look at the code of frmMain.vb form, you will find three major functions

  • InitNetwork method to create/initialize the network
  • TrainPattern method to train the network
  • DetectPattern method to detect an image

The concept behind the program is pretty simple.

  • We are using a 400-400-8 network (400 neurons in input layer, 400 neurons in hidden layer, and 8 neurons in output layer) to perform the required operations
  • First of all, we will convert the 20 x 20 image (i.e, as you know a 20 x 20 image consists of 400 pixels) to an array of 1s and 0s. A white pixel is taken as 1 and a black pixel is taken as 0. This is fed to the input layer
  • As you know, we should give the output along with the input, during training phase. For this, the character's ASCII value's binary representation is fed to the output layer.

Fortunately, any of these tasks are not so complex at all. This can be easily achieved using the built-in functionality of BrainNet library. Just have a look at the major functions with in PatternDetector.

 'A private variable to hold our network.
    Private network As BrainNet.NeuralFramework.INeuralNetwork

    '<summary> Initialize our network </summary>
    Sub InitNetwork()

        'We are analyzing a 20x20 pixel picture, so let us take the number
        'of total inputs as 20 x 20 = 400 neurons

        'So let us initialize a 400-400-8 network. I.e, 400 neurons in
        'input layer, 400 neurons in hidden layer and 8 neurons in output layer
        'We've chosen 8 neurons in output because we need 8 bits to
        'represent an ASCII character

        'Create the factory to create a Backward Propagation Neural Network
        '(Backward Propagation neural network is a commonly used neural network model)
        Dim factory As New BrainNet.NeuralFramework.BackPropNetworkFactory()

        'This is an arralist which holds the number of neurons in each layer
        Dim layers As ArrayList = New ArrayList()

        'We need 400 neurons in first layer
        layers.Add(400)
        'We need 400 neurons in the second layer (the second layer is the first
        'hidden layer)
        layers.Add(400)
        'We need 8 neurons in the output layer
        layers.Add(8)

        'Provide the arraylist as the parameter, to create a network
        network = factory.CreateNetwork(layers)

    End Sub

    '<summary> Routine to train the network </summary>
    Sub TrainPattern()

        'This routine demonstrates how easily you can train
        'a network using a NetworkHelper object

        'Here, we are using a NetworkHelper object to train the 
        'network.

        'Create a helper object
        Dim helper As BrainNet.NeuralFramework.NetworkHelper
        helper = New BrainNet.NeuralFramework.NetworkHelper(network)

        'A helper object helps you to train the network more
        'efficiently. First of all, you add each training data to the
        'Training Queue using the helper. For this, you can use the
        'AddTrainingData method of the helper

        'Next, you can call the Train function of the helper to
        'randomize entries to the training queue and train the network more
        'efficiently

        'Step 1 - Add the training data from our list view box to the helper
        Dim item As ListViewItem

        For Each item In Me.lvMain.Items
            Dim img As Image = imlMain.Images(item.ImageIndex)
            Dim asciiVal As Long = Asc(item.Text)

            'The AddTrainingData method of Network helper helps you to
            'add an image and its corresponding ASCII value directly

 
            helper.AddTrainingData(img, asciiVal)
        Next

        'Step 2 - Train the network using the helper

        'Get the number of times
        Dim rounds As Long = Val(Me.txtTrainTimes.Text)



        'Add the handler of ShowProgress delegate, to get
        'the progress training progress
        StopTraining = False
        AddHandler helper.TrainingProgress, AddressOf ShowProgress
        'Start training
        helper.Train(rounds)
        RemoveHandler helper.TrainingProgress, AddressOf ShowProgress


    End Sub


    '<summary> Routine to detect an image </summary>
    Sub DetectPattern()



        'Step 1 : Convert the image to detect to an arraylist

        Dim imgHelper As New BrainNet.NeuralFramework.ImageProcessingHelper()
        Dim input As ArrayList

        input = imgHelper.ArrayListFromImage(Me.picImgDetect.Image)

        'Step 2: Run the network and obtain the output
        Dim output As ArrayList
        output = network.RunNetwork(input)

        'Step 3: Convert the output arraylist to long value
        'so that we will get the ascii character code

        Dim patternHelper As New BrainNet.NeuralFramework.PatternProcessingHelper()
        Dim character As String = Chr(patternHelper.NumberFromArraylist(output))
        Dim bitpattern As String = patternHelper.PatternFromArraylist(output)

        'Display the result
        Me.txtAsciiDetect.Text = character
        Me.txtPatternDetect.Text = bitpattern

    End Sub
 

The code is heavily commented, but here is some more explanation.

Training Using Network Helper

Examine the TrainPattern function. Instead of training the Network directly (as we did in the case of our Binary Neural Gate), we are using a Network Helper object to train the network. Using a network helper object, you can add images and the corresponding ASCII codes directly. AddTrainingData method of NetworkHelper class is gracefully overloaded, so that it can accept various parameters (more about this later).

Here, we are iterating each element in our list view (i.e, the training queue) - and add it to the helper. Then we initiate the training by calling the 'Train' method of the helper. The input to the 'Train' method is the number of rounds we need to train the network. For more details, have a look the help file of BrainNet library (included in the zip file).

PatternProcessingHelper and ImageProcessingHelper

Examine the DetectPattern function. Here, we should provide the input to the network, to obtain the output. To convert an image to an array of 1s and 0s, we use the ArrayListFromImage function inside the ImageProcessingHelper class. After obtaining the output from the network, we should convert this to the equivalent ASCII code to display the character in the textbox - for this, we use the NumberFromArrayList function in the PatternProcessingHelper class. Similarly, the PatternFromArrayList function converts an array list to a string (normally, a string of 1s and 0s).

Other than the above functions, the code for handling the user interface is also present in the PatternDetector project. Open the project, and have a look at the source code (it is commented heavily) for a better understanding.

4. Conclusion

That is it for the day. Congratulations for finishing the article with so much interest!!

I hope you enjoyed this article, and related projects. The attached zip file contains BrainNet Framework assembly file, BrainNet library Documentation in CHM format, and source code of the above two projects. Download and experiment.

In my future articles, I'll

  • Explain the concepts behind neurons and neural networks more theoretically
  • Explain the design and other internals of BrainNet library (Read my articles about Design patterns before this, that may help)
  • Release the source code of BrainNet Framework
  • Discuss how to create an XML based language for creating, training and running neural networks
  • Demonstrate how to use BrainNet Framework with web services to implement distant learning systems.

In the mean time, you can read more articles and get more source code from my website http://amazedsaint.blogspot.com/ and from my technical articles blog, at http://amazedsaint-articles.blogspot.com/. You can subscribe to the RSS feed of my technical articles blog, for tracking new posts. The Atom is here. If you come across any bugs, please report it to m.anoop@yahoo.com or post it here.

Contributions: Your contributions to the Amazed saint blog will help us to bring out more open source projects like BrainNet - among other well written articles, projects and tutorials - Hence, we request you to kindly consider a donation here.

Very soon, in my future articles we will discuss more cool topics regarding Neural Networks, Genetic Algorithms, Fuzzy Logic, Biologically Inspired Computing, Conway's Game Of Life etc - as I already discussed above. For now, have a great day, enjoy coding!!

Monday, May 01, 2006

Mastering the Dark Art - A little about hacking.

This article is a very basic introduction to hackers, exploits and hacking concepts.

Contents 


1. Introduction. 



Hacking is often used as a buzzword to indicate the activity of intruding into restricted areas by negotiating the security settings. Hacker is someone who is able to manipulate the inner workings of computers, information, and technology – by some means. The word "hacker" started out in the 14th century to mean somebody who was inexperienced or unskilled at a particular activity (such as a golf hacker). In the 1970s, computer enthusiasts to refer to them used the word “hacker”. This reflected the way enthusiasts approach computers - they eschew formal education and play around with the computer until they can get it to work. Later, this term became generalized for referring people who try several ways to manipulate information and technology, often by compromising safety measures. Since normal people have no clue as to how computers work, they often view hackers with suspicion and awe (as magicians and witches). This suspicion leads to the word "hacker" having the connotation of someone up to no good.

Serious hacking professionals have significant job opportunities as security analysts and specialists all around the world. At this point, it is important to mention that serious hacking experts are the ones who find pitfalls in security systems to strengthen them further, and not for destroying them. Any kind of hacking attempt with out a genuine reason is a serious offence by the standards of cyber law all around the world. 

However, these days, another type of hacking is also getting popular. This type of hacking refers to manipulating and modifying the code of open-source programs, to make them more reliable, mostly for the good of the public. For example, Linux Kernel is developed by a group of (second type of) hackers. This concept of hacking is somewhat different from the hacking concept we saw earlier. In this article, we will deal with the first type of hacking (or intrusion hacking), and ways to prevent such intrusion attempts. Learning (about) hacking techniques is a wonderful way to understand networking concepts and security issues.

Top ^

2. The World Of Hacking



The world of hacking consists of a wide rage of people – from security experts and programmers who develop reliable security systems, hackers who create tools to break in to these systems (often to prove the fickleness of them), and script kiddies who use (or misuse) these tools to break down the boxes (read ‘computers’) of their friends and enemies for no reason.

Real hackers break in to the systems using exploits of existing software or hardware. An exploit is a technique of breaking into a system, or a tool that implements the technique. An exploit takes advantage of a weakness or vulnerability in a system in order to hack it. Exploits are the key to hacker culture. Hackers gain fame by discovering exploits. Others gain fame by writing scripts (or programs) for them. Legions of script-kiddies apply the exploit to millions of systems, defacing web pages and gaining fame. Finding vulnerabilities is a big part of the hacker culture. Finding vulnerabilities is way of proving that a hacker is "elite". Often these elite hackers join to form groups. The world’s major hacking sites list such an elite group of hackers, and the most well known groups are ‘The Cult Of Dead Cow’ group and the ‘The Raven’.

Hackers break into systems mostly using the vulnerabilities of computer systems. In the security community, the word "vulnerability" describes a problem (such as a programming bug or common misconfiguration) that allows a system to be attacked or broken into. The buffer overflow exploit is such a vulnerability that is found in many systems. This causes mainly because programmers often forget to validate input. They (rightly) believe that a legal username is less than 32 characters long, and (wrongly) reserve more than enough memory for it, typically 200 characters. The assume that nobody will enter in a name longer than 200 characters, and don't verify this. Malicious hackers exploit this condition by purposely entering in user names 1000 characters long.

The average system on the Internet is vulnerable to various well-known buffer overflow attacks. For instance, Many Windows NT servers have IIS web services vulnerable to a buffer overflow in ".htr" handler, many Solaris servers have vulnerable RPC services like ‘cmsd’, ‘ToolTalk’, and ‘statd’; many Linux boxes have vulnerable IMAP4, POP3, or FTP services. Programs written in C are most vulnerable, and C++ is somewhat less vulnerable. The reason is that C requires the programmer to check buffer lengths himself.

Top ^

3. The Theory Of Hacking


In Internet, computers communicate between themselves by sending data packets, packed in a specific format. All data sent is broken up into packets, sent individually across the network, and reassembled back into the original data at the other end (using a protocol named TCP/IP). All computers in the Internet have a unique IP Internet address. A port is an extension of an Internet address that tells which program is to receive the data. Often, Internet ports are also termed as sockets. If a computer ‘A’ needs to contact ‘B’, then A should know the IP address of ‘B’, and also to which port it can send a request to ‘B’. If ‘B’ acknowledges the request from ‘A’, a connection is established. One or more ports in ‘B’ should be in listening mode to accept connection requests from computers like ‘A’. Then, according to the direction of control and data flow, one computer is called the server and the other one the client. Various Internet services have pre-defined ports. For example, most web servers run on 80th port. If we request a web page from Yahoo using our browser, then our computer will place a request to the 80th port of yahoo.com. The IP of yahoo.com is fetched from the so called ‘name servers’, or computers designed to keep the IP-URL tables. If the (yahoo) server acknowledges the connection, then another random port is opened in yahoo’s computer to connect it with ours. The listening socket in Yahoo server will continue listening for further connections.

Internet has various services like the World Wide Web (WWW), E-Mail, and Chat etc. Most of these services have pre-defined listening ports. A web server may have its 80th port in listening mode, while a chat server listens to the 6667th port. It is possible to access different ports at the same time, between different computers. For example, let us assume that there is a server with IP address 192.0.2.111. If we send data to IP 192.0.2.111, port 6667, then we are talking to the Internet Relay Chat (IRC) service. However, if we send something to port 80 on the same machine, then we are talking to the web server on that machine. Various programs are used to implement these services. For instance, Apache and Microsoft IIS as programs that can work as web servers (by listening and handle connection requests o the 80th port). Most hackers to intrude in to the target system use the vulnerabilities in such server programs. If an exploit is present in the web server that is running on the 80th port, then a hacker in the outer world may use these exploits to intrude in to the system, to deface the website or to run arbitrary code.

Other than using such exploits in servers, hackers may use Trojan viruses to intrude in to the system. The word ‘Trojan’ refers to the classic Trojan horse from the Iliad. In this story, after giving up on sieging the fortified city of Troy, the Greeks left behind a present. This consisted of a large wooden horse left at the outskirts of the town. After seeing the Greeks sail off, the citizens brought the wooden horse into town. The horse contained Greek warriors, who promptly jumped out, killed a bunch of people, and opened the city gates, letting in the Greek army who had actually been hiding rather than sailing off with the ships. In a similar way, hackers send Trojan programs through e-mails and by such means. Trojans are one of the leading causes of breaking into machines. If you pull down a program from a chat room, news group, or even from unsolicited e-mail, then the program is likely trojaned (infected with a Trojan) with some subversive purpose. It might contain a virus, a password-grabber, or consist of a remote admin Trojan designed to allow remote control over your machine. Back Orifice is such a famous remote access Trojan released in 1998 by the Cult of the Dead Cow group. By promulgating this through their well-oiled propaganda machine, they succeeded in making Back Orifice the archetype for all such programs. In 1999, they released a newer version called BO2K - Back Orifice 2000 (Available from http://www.bo2k.com). 

Once a Trojan is installed in the system, it will open a port and may act as a server, to host hacking attempts. A hacker may use a port scanner to find such a vulnerable port. In hacker reconnaissance, a port scan attempts to connect to all 65536 ports on a machine (the maximum number of ports possible) in order to see if anybody is listening on those ports. Ports scans are not illegal in many places; those laws have yet to be written on the subject. Full port scans of all 65536 ports are rarely seen, especially since they are so obvious. Instead, hackers will strobe for just the ports he/she is interested in. These strobes are for typically fewer than 10 ports. Also, the hacker will often sweep thousands (or millions) of machines rather than a single machine looking for any system that might be vulnerable. The best tool for doing port scans is ‘nmap’ from http://www.insecure.org/nmap (In the last film of the Matrix Trilogy, ‘Trinity’ uses nmap to scan and find a vulnerable SSH server). If a port is found open, then the hacker may detect the program running on this port, and test whether this program has any known vulnerability with it. If so, this vulnerability is used for intruding in to the system.

Another common type of hacking method is the ‘trial and error’ method. In this technique, the hacker connects to a server through various means like Telnet and NetBIOS, and tries to log in to the system by guessing the username and password. Often, utility programs are used to help the hacker to do this. The hackers use jargon ‘grind’ for continuously guessing passwords to find the right one. In hacker’s chat rooms, you will often hear about ‘grinding a box’ (read ‘trying to get in to a computer’). Secure systems (UNIX, Windows NT) lock out accounts (deny further log in attempts) after a certain number of unsuccessful tries. These lockouts can either be temporary (and restore themselves automatically), or permanent until an administrator intervene and unlocks the account. Non-secure systems (Win9x and many software applications) do not lock out accounts. For example, if you have Win9x "File and Print Sharing" turned on and protected with a password, a hacker can try continuously and invisibly to gain access to your machine. 

Top ^

4. Exploits


Hackers learn about exploits from other hackers and from various security sites. An exploit just found is termed as 0th day exploit. The term 0-day exploit describes an exploit that is not publicly known. It describes tools by elite hackers who have discovered a new bug and shared it only with close friends. It also describes some new exploit for compromising popular services (the usual suspects: BIND, FTP services, Linux distros, Microsoft IIS, Solaris servers). Many 0-day exploits are discovered by the victims when hackers use them, or by honey pots. 

The term "0-day" describes the fact that the value of exploits quickly goes down as soon as they are announced. The next day they are half as valuable. The 2nd day they are a 1/4 as valuable. Ten days later they are 1/1000 as valuable as on day 0. This is because script-kiddies quickly use the exploits on computers throughout the Internet, compromising systems before anybody else can get to them. Once an exploit is made public, it will be announced in various security sites for alerting the administrators to fix the problems of their systems. Some sites even provide scripts to check the problem (which may be miss-used by script kiddies) and updates or patches (programs for administrators to fix the problem). Here are few sites that keep various ‘hot lists’ of recent exploits.

Top ^

5. Finding Backdoors


Hacking techniques vary much, based on the operating system used by the victim, tools available etc. Hackers commonly refer finding a channel to the victim system as ‘opening a back door’. A back door is a secret entry to a computer, often challenging its security settings. Finding back doors by using the known security exploits is the common method. The story of how hackers find these exploits is very interesting. Some times it happens by accident, and some times, it will be a guess made by an intelligent brain. For instance, let us have a look at an appealing real world example. Microsoft Internet Information Server is Microsoft’s web server (for hosting web sites). Whenever you pay a reputed Internet Service Provider to host your website, chances are that they are using Microsoft IIS for hosting your website.

Interestingly, IIS has a famous exploit named the Unicode exploit. . As we know computers just deal with numbers. It stores letters and other characters by assigning a number for each one. Unicode provides a unique number for every character. Unicode forms a single character set across all languages. Unicode is a character-coding scheme, much like ASCII. ASCII is eight bit while Unicode is 16 bit. As it can accommodate more character codes, Unicode has support for more languages, while ASCII supports only English language. Unicode extensions are installed by default with Microsoft Internet Information Server (IIS) version 4.0 and 5.0. This is to allow characters that are not used in the English language to be recognized by web servers. The IIS Unicode Exploit allows users to run arbitrary commands on the web server. IIS servers with the Unicode extensions loaded are vulnerable unless they are running current patches

The IIS Unicode exploit uses malformed URLs to traverse directories and execute arbitrary commands on the vulnerable web servers. A URL (Uniform Resource Locator) is a string, which tells the browser the server name, and file name it should access. For instance, ‘http://www.yahoo.com’ (with out quotes) is the URL of Yahoo website, and ‘http://www.yahoo.com/index.html’ represents a file named ‘index.html’ in the root directory of Yahoo’s web server. The IIS Unicode exploit uses a Unicode representation of a directory delimiter (/) to fool IIS. Because the exploit uses http, it works right from the address bar of a browser. In other words, a hacker can use his browser to hack into the server!!

For example, consider a site www.somesite.com is running IIS as its web server. To understand the actual attack we will closely examine a sample of the exploit. The user can type the following URL to the location bar of his browser (with out quotes), to enable IIS to execute cmd.exe (command shell for Windows) to list the directory of C drive.

“http://www.somesite.com/scripts/..%c0%af../winnt/system32/cmd.exe?/c+dir+c:\”

We notice that the URL calls something from the /scripts directory on the server www.somesite.com. For this particular version of exploit the scripts directory must exist and the path to the executable cmd.exe must be correct. The next string we see is “..%c0%af ”. This string of characters “%c0%af” is an overlong Unicode representation for ' / '. If this Unicode exploit is loaded on the server, the URL will be interpreted to be: 

“http://www.somesite.com/scripts/../../winnt/system32/cmd.exe?/c+dir+c: ” 

The URL backs out of the web root, to the root directory of the server, then calls winnt\system32\cmd.exe. We are using the command interpreter (cmd.exe) to execute the command 'dir c:\' You can also try running other commands too. Thus, a hacker can execute his own commands in the remote system. Various hackers and script kiddies uses this security problem of IIS to steal data and to deface websites. Windows, Unix and Linux boxes all around the world have various such known and unknown backdoors. 

Another infamous back door in Windows XP is the UPNP back door. If you are running Windows XP, chances are that you are already vulnerable due to the UPNP (Universal Plug and Play) service, which can be used to detect and integrate with UPNP aware devices. Windows XP comes with default UPNP installation. UPNP has several issues, which causes the hacker to intrude in to the system running UPNP services. By sending a malicious spoofed UDP packet containing an SSDP (Simple Service Discovery Protocol) advertisement, an attacker can force the XP/ME client to connect back to a specified IP address and pass on a specified HTTP/HTTPS request.

An example session:

NOTIFY * HTTP/1.1
HOST: 239.255.255.250:1900
CACHE-CONTROL: max-age=1
LOCATION: URL
NT: urn: schemas-upnp-org:device:InternetGatewayDevice:1
NTS: ssdp:alive
SERVER: ANOOP/2001 UPnP/1.0 PASSITON/1.1
USN: uuid:ANOOP


The above packet data needs to be sent as a UDP packet to port 1900 of the XP/ME machine. UDP (Universal Datagram Protocol) is essentially just a lightweight version of TCP. Whereas TCP will automatically retransmit lost packets, UDP doesn't care about lost packets. An easy way to do send UDP packet is by writing a simple shell script to send the data to the 1900th port of the victim. When the XP machine receives this request, it will interpret the URL following the LOCATION header entity. With no sanitizing of the URL it is passed on to the functions in the Windows Internet Services API. The string is broken down and the new session is created.

Top ^

6. Defending Hacking Attempts



These days, most hacking attempts can be easily traced (theoretically). No matter whether the hacker is using a Dial-up connection or a wireless connection, either the computer the hacker used or the exact position of the hacker can be detected. But often, this is of no use because hackers has better methods to fool the authorities, like using third party systems (like a computer in a Cyber Café) for intruding into other systems. In case of wireless connections, the hacker’s physical position can be easily traced. But wise hackers who use the wireless connections often change their locations (like attempting intrusions while he is in a moving train).

Defending hacking is a tough job even for experienced administrators, because various hackers and third parties discover new exploits in existing programs frequently. Known vulnerabilities should be ‘patched’ (or fixed) rapidly, in order to prevent hackers from using them to intrude in to the system. To prevent intrusion attempts, organizations may use intrusion detection systems and firewalls. A firewall is a device or software that isolates a network from the Internet. The word is derived from construction, where "firewalls" isolate areas of a building in order to stop a fire from spreading. All packets between the organization and the Internet flow through the firewall. It acts as a "gate" with virtual guards that examines the traffic, and decided whether to allow it or block it. Some organizations use Intrusion detection systems that pretend to be valid systems, possibly even one that can easily be exploited in order to break into the system. Such systems for detecting hackers are termed as ‘honey pots’.

A common misunderstanding is that firewalls recognize attacks and block them. This is not true. It simply restricts access to the designated points. In contrast an IDS (Intrusion Detection System) is much more of that dynamic system. An ‘IDS’ does recognize attacks against the network that firewalls are unable to see. Some handy ways to prevent Intrusion to the Windows systems include.

  • Install the latest patches from Microsoft – See http://www.microsoft.com/security/
  • Install some firewalls, like the Zone Lab ( http://www.zonelabs.com)
  • Turn off print sharing. When print sharing is turned on, the system creates a PRINTER$ share that allows remote systems to access printer drivers from the local system32 directory. Unfortunately, this allows remote systems to access non-driver files, such as the Win9x password file (combined with other Win9x bugs). 
  • Turn off file sharing. If you must share files, make sure that you choose a strong password, and only turn it on for brief moments while you need to share the files, then turn it off again. 
  • Rename ‘administrator’ account and disable the "guest" account from control panel for Windows NT systems
  • Enable lockout of the "administrator" account for remote access
  • For Windows XP systems, disable Remote Assistant Service and UPNP service from the administration section in control panel.

Top ^

7. References


VB.NET Tutorial - Learning VB.NET in a very easy manner.

VB.NET is completely object oriented. This article uncovers some basic Object Oriented Programming features of Visual Basic. NET. The whole article is divided into ten lessons. The source code for these lessons is provided with the article.

Contents

Introduction

This tutorial is designed with the following objectives:

  1. To provide a sound knowledge about Object Oriented Programming in VB.NET.
  2. To educate how Object Oriented techniques are used in VB.NET.
  3. To explain the following concepts in an easy and simple way:
    • Creating and using classes and objects in VB.NET.
    • Encapsulation, Abstraction, Inheritance and Polymorphism.
    • Overloading and Overriding.
    • Constructors and Destructors.
    • Static functions.

Go through this tutorial and you will start making sense of almost any .NET code. Also, Java/CPP programmers can use this to understand OOPs in VB.NET.

Using the code

The source code for each lesson is available as a .vb source code file. You need Microsoft .NET framework SDK installed in your system to compile and execute the exercises in this article. You can download it from the Microsoft website. The VB.NET compiler (vbc.exe) normally resides in your FrameworkSDK\bin folder.

To manually compile a source code file, you may use the command prompt to type: vbc filename.vb /out:"filename.exe" /r:"System.Windows.Forms.dll","System.dll"

Lesson 1: Namespaces, Classes & Objects, Modules

  • A Namespace

    In VB.NET, classes and other data structures for a specific purpose are grouped together to form a namespace. You can use the classes in a namespace, by simply importing the namespace. The Imports keyword is used to import a namespace to your project. .NET framework provides a rich set of built in classes, grouped together to various namespaces. In this lesson, we are using the System namespace. Import the System namespace (already available in .NET).

    Imports System
  • A Class

    Probably, you are already familiar with classes and objects. Simply speaking, a Class is a definition of a real life object. For example, Human is a class for representing all human beings. Dog is a class to represent all Dogs. Classes can contain functions too. Animals is a namespace.

    Namespace Animals

    Dog is a class in the namespace Animals:

    Class Dog

    Bark is a function in this Class:

        Function Bark()
            Console.Writeline ("Dog is barking")
        End Function
    End Class
    End Namespace
  • An Object

    An object is an instance of a Class. For example, Jimmy is an object of type Dog. We will create an object in the next section. Read on.

  • Modules

    You can use modules to write common functions. A Module is a group of functions. Unlike functions in classes, Public functions in modules can be called directly from anywhere else. VB provides Functions and Subroutines. Functions and Subroutines are almost the same, but the difference is that a subroutine can't return a value.

    Public Module modMain

    Execution will start from the Main() subroutine:

    Sub Main()
           'Call our function. See below
           OurFunction()    
    End sub

    OurFunction: Our own little function to use the class Dog:

    Function OurFunction()    
           'Here is how we declare a variable Jimmy of type Dog.
           'We use Animals.Dog because, the class Dog is in the
           'namespace Animals (see above).
        
           Dim Jimmy as Animals.Dog
        
           'Create an object. Unlike in VB 6, it is not required to use
           'the 'set' keyword.
               
           Jimmy = new Animals.Dog()
        
           'Another way to create an object is
           'Dim Jimmy as new Dog
        
           'Call Jimmy's Main Function     
           Jimmy.Bark()
    End Function
    End module

Lesson 2: Access Types

The major access types are Public, Private, Friend and Protected. A Class may contain functions, variables etc., which can be either Public or Private or Protected or Friend. If they are Public, they can be accessed by creating objects of the Class. Private and Protected members can be accessed only by the functions inside the Class. Protected members are much like Private members, but they have some special use while inheriting a Class. We will see this later, in Inheritance (Lesson 5). Friend members can be accessed only by elements of the same project, and not by the ones outside the current project. Let us expand our dog class.

Import the System namespace (already available in .NET).

Imports System

Animals is a namespace.

Namespace Animals

Dog is a class in the namespace Animals.

Public Class Dog
    'A public variable    
    Public AgeOfDog as Integer

Bark is a function in this class. It is Public:

    Public Function Bark()
        Console.Writeline ("Dog is barking")
    End Function

Walk is a function in this class. It is Private.

    Private Function Walk()
        Console.Writeline ("Dog is walking")
    End Function
End Class
End Namespace

Our Module:

Public Module modMain

Execution will start from the Main() subroutine:

Sub Main()
       'Call our function. See below
       OurFunction()    
End sub
    'OurFunction: Called from Main()
    Function OurFunction()
        Dim Jimmy as Animals.Dog
        Jimmy=new Animals.Dog()
        'This will work, because Bark & Ageofdog are public
        Jimmy.Bark
        Jimmy.AgeOfDog=10
         'Calling the Walk function will not work here, because
        'Walk() is outside the class Dog        
        'So this is wrong. Uncomment this and try to compile, it will
        'cause an error.
        'Jimmy.Walk
    End Function        
End Module

Additional Notes:

  • Encapsulation

    Putting all the data and related functions in a Class is called Encapsulation.

  • Data Hiding or Abstraction:

    Normally, in a Class, variables used to hold data (like the age of a dog) is declared as Private. Functions or property routines are used to access these variables. Protecting the data of an object from outside functions is called Abstraction or Data Hiding. This prevents accidental modification of data by functions outside the class.

Lesson 3: Shared Functions

The shared members in a class (both functions and variables) can be used without creating objects of a class as shown. The Shared modifier indicates that the method does not operate on a specific instance of a type and may be invoked directly from a type rather than through a particular instance of a type.

Import the System namespace (already available in .NET).

Imports System

Animals is a namespace.

Namespace Animals

Dog is a class in the namespace Animals.

Class Dog

Bark is a now a Public, shared function in this class.

    Public Shared Function Bark()
        Console.Writeline ("Dog is barking")
    End Function

Walk is a Public function in this class. It is not shared.

    Public Function Walk()
        Console.Writeline ("Dog is walking")
    End Function
End Class
End Namespace

Our Module:

Public Module modMain

Execution will start from the Main() subroutine.

Sub Main()
        'We can call the Bark() function directly,
        'with out creating an object of type Dog -
        'because it is shared.
        Animals.Dog.Bark()
        'We can call the Walk() function only
        'after creating an object, because
        'it is not shared.
        Dim Jimmy as Animals.Dog
        Jimmy=new Animals.Dog()
        Jimmy.Walk()
        'Now Guess? The WriteLine() function we used so far
        'is a shared function in class Console :)
        'Also, we can write the Main() function itself as a shared
        'function in a class. i.e Shared Sub Main(). Try
        'moving Main() from this module to the above class
End sub
End Module

Lesson 4: Overloading

Overloading is a simple technique, to enable a single function name to accept parameters of different type. Let us see a simple Adder class. Import the System namespace (already available in .NET).

Imports System
Class Adder

Here, we have two Add() functions. This one adds two integers. Convert.ToString is equivalent to the good old CStr.

    Overloads Public Sub Add(A as Integer, B as Integer)
        Console.Writeline ("Adding Integers: " + Convert.ToString(a + b))
    End Sub

This one adds two strings.

    Overloads Public Sub Add(A as String, B as String)
        Console.Writeline ("Adding Strings: " + a + b)
    End Sub
    'And both have the same name. This is possible because, we used the
    'Overloads keyword, to overload them.
    'Here, we have the Main Function with in this class. When you write.
    'your main function inside the class, it should be a shared function.
    Shared Sub Main()
        Dim AdderObj as Adder
        'Create the object
        AdderObj=new Adder
        'This will invoke first function
        AdderObj.Add(10,20)
        'This will invoke second function
        AdderObj.Add("hello"," how are you")
    End Sub
End Class

Lesson 5: Inheritance

Inheritance is the property in which, a derived class acquires the attributes of its base class. In simple terms, you can create or 'inherit' your own class (derived class), using an existing class (base class). You can use the Inherits keyword for this.

Let us see a simple example. Import the System namespace (already available in .NET).

Imports System

Our simple base class:

Class Human
    'This is something that all humans do
    Public Sub Walk()
        Console.Writeline ("Walking")
    End Sub
End Class

Now, let us derive a class from Human.

A Programmer is a Human.

Class Programmer
    Inherits Human
    'We already have the above Walk() function
    'This is something that all programmers do ;)
    Public Sub StealCode()
        Console.Writeline ("Stealing code")
    End Sub
End Class

Just a MainClass.

Class MainClass
    'Our main function
    Shared Sub Main()
        Dim Tom as Programmer
        Tom=new Programmer
        
        'This call is okie because programmer got this function
        'from its base class
        Tom.Walk()
        
        'This is also correct because Tom is a programmer
        Tom.StealCode()
    End Sub
End Class

Additional Notes:

  • MustInherit

    The MustInherit keyword specifies that a class cannot be instantiated and can be used only as a base class. I.e., if you declare our Human class as "MustInherit Class Human", then you can't create objects of type Human without inheriting it.

  • NotInheritable

    The NotInheritable keyword specifies that a class cannot be inherited. I.e., if you specify 'NotInheritable Class Human', no derived classes can be made from the Human class.

Lesson 6: Overriding

By default, a derived class Inherits methods from its base class. If an inherited property or method needs to behave differently in the derived class it can be overridden; that is, you can define a new implementation of the method in the derived class. The Overridable keyword is used to mark a function as overridable. The keyword Overrides is used to mark that a function is overriding some base class function. Let us see an example.

Import the System namespace (already available in .NET).

Imports System

Our simple base class:

Class Human
    'Speak() is declared Overridable
    Overridable Public Sub Speak()
        Console.Writeline ("Speaking")
    End Sub
End Class

Now, let us derive a class from Human:

An Indian is a Human:

Class Indian
    Inherits Human
    'Let us make Indian speak Hindi, the National Language
    'in India
    'Speak() is overriding Speak() in its base class (Human)
    Overrides Public Sub Speak()
        Console.Writeline ("Speaking Hindi")
    'Important: As you expect, any call to Speak() inside this class
    'will invoke the Speak() in this class. If you need to
    'call Speak() in base class, you can use MyBase keyword.
    'Like this
    'Mybase.Speak()
    End Sub
End Class

Just a class to put our Main().

Class MainClass
    'Our main function
    Shared Sub Main()
        'Tom is a generic Human
        Dim Tom as Human
        Tom=new Human
        'Tony is a human and an Indian
        Dim Tony as Indian
        Tony=new Indian
        'This call will invoke the Speak() function
        'in class Human
        Tom.Speak()
        'This call will invoke the Speak() function
        'in class Indian
        Tony.Speak()
    End Sub
End Class

Lesson 7: Polymorphism

Polymorphism is the property in which a single object can take more than one form. For example, if you have a base class named Human, an object of Human type can be used to hold an object of any of its derived type. When you call a function in your object, the system will automatically determine the type of the object to call the appropriate function. For example, let us assume that you have a function named speak() in your base class. You derived a child class from your base class and overloaded the function speak(). Then, you create a child class object and assign it to a base class variable. Now, if you call the speak() function using the base class variable, the speak() function defined in your child class will work. On the contrary, if you are assigning an object of the base class to the base class variable, then the speak() function in the base class will work. This is achieved through runtime type identification of objects. See the example.

Import the System namespace (already available in .NET).

Imports System

This example is exactly the same as the one we saw in the previous lesson. The only difference is in the Shared Sub Main() in the class MainClass. So scroll down and see an example:

Our simple base class:

Class Human
    'Speak() is declared Overridable
    Overridable Public Sub Speak()
        Console.Writeline ("Speaking")
    End Sub
End Class

Now, let us derive a class from Human.

An Indian is a Human.

Class Indian
    Inherits Human
    'Let us make Indian speak Hindi, the National Language
    'in India
    'Speak() is overriding Speak() in its base class (Human)
    Overrides Public Sub Speak()
        Console.Writeline ("Speaking Hindi")
    'Important: As you expect, any call to Speak() inside this class
    'will invoke the Speak() in this class. If you need to
    'call Speak() in base class, you can use MyBase keyword.
    'Like this
    'Mybase.Speak()
    End Sub
End Class

Carefully examine the code in Main():

Class MainClass
    'Our main function
    Shared Sub Main()
        'Let us define Tom as a human (base class)
        Dim Tom as Human
        'Now, I am assiging an Indian (derived class)
        Tom=new Indian
        'The above assignment is legal, because
        'Indian IS_A human.
        'Now, let me call Speak as
        Tom.Speak()
        'Which Speak() will work? The Speak() in Indian, or the
        'Speak() in human?
        'The question arises because, Tom is declared as a Human,
        'but an object of type Indian is assigned to Tom.
        'The Answer is, the Speak() in Indian will work. This is because,
        'most object oriented languages like Vb.net can automatically
        'detect the type of the object assigned to a base class variable.
        'This is called Polymorphism
    End Sub
End Class

Lesson 8: Constructors & Destructors

Import the System namespace (already available in .NET).

Imports System

A Constructor is a special function which is called automatically when a class is created. In VB.NET, you should use useNew() to create constructors. Constructors can be overloaded (see Lesson 4), but unlike the functions, the Overloads keyword is not required. A Destructor is a special function which is called automatically when a class is destroyed. In VB.NET, you should use useFinalize() routine to create Destructors. They are similar to Class_Initialize and Class_Terminate in VB 6.0.

Dog is a class:

Class Dog
    'The age variable
    Private Age as integer

The default constructor:

    Public Sub New()
        Console.Writeline ("Dog is Created With Age Zero")
        Age=0
    End Sub

The parameterized constructor:

    Public Sub New(val as Integer)
        Console.Writeline ("Dog is Created With Age " + Convert.ToString(val))
        Age=val
    End Sub

This is the destructor:

    Overrides Protected Sub Finalize()
        Console.Writeline ("Dog is Destroyed")
    End Sub
    'The Main Function
    Shared Sub Main()
        Dim Jimmy, Jacky as Dog
        'Create the objects
        'This will call the default constructor
        Jimmy=new Dog
        'This will call the parameterized constructor
        Jacky=new Dog(10)
    End Sub
    'The Destruction will be done automatically, when
    'the program ends. This is done by the Garbage
    'Collector.
End Class

Lesson 9: Property Routines

You can use both properties and fields to store information in an object. While fields are simply Public variables, properties use property procedures to control how values are set or returned. You can use the Get/Set keywords for getting/setting properties. See the following example. Import the System namespace (already available in .NET).

Imports System

Dog is a class.

Public Class Dog
    'A private variable    to hold the value
    Private mAgeOfDog as Integer

This is our property routine:

Public Property Age() As Integer
    'Called when someone tries to retreive the value
Get
    Console.Writeline ("Getting Property")
    Return mAgeOfdog
End Get
Set(ByVal Value As Integer)
    'Called when someone tries to assign a value     
    Console.Writeline ("Setting Property")
    mAgeOfDog=Value
End Set
End Property
End Class

Another class:

Class MainClass
    'Our main function. Execution starts here.
    Shared Sub Main()
    'Let us create an object.
    Dim Jimmy as Dog
    Jimmy=new Dog        
    'We can't access mAgeofDog directly, so we should
    'use Age() property routine.
    'Set it. The Age Set routine will work
    Jimmy.Age=30
    'Get it back. The Age GEt routine will work
    Dim curAge=Jimmy.Age()
    End Sub
End Class

Lesson 10: A simple program

Let us analyze a simple program. First, let us import the required namespaces:

Imports System
Imports System.ComponentModel
Imports System.Windows.Forms
Imports System.Drawing
    'We are inheriting a class named SimpleForm, from the
    'class System.Windows.Forms.Form
    '
    'i.e, Windows is a namespace in system, Forms is a
    'namespace in Windows, and Form is a class in Forms.
Public Class SimpleForm
Inherits System.Windows.Forms.Form
        'Our constructor
Public Sub New()
    'This will invoke the constructor of the base
    'class
MyBase.New()

Set the text property of this class. We inherited this property from the base class:

Me.Text = "Hello, How Are You?"
End Sub
End Class
Public Class MainClass
    Shared Sub Main()
        'Create an object from our SimpleForm class
        Dim sf as SimpleForm
        sf=new SimpleForm
        
        'Pass this object to the Run() function to start
         System.Windows.Forms.Application.Run(sf)
    End Sub
End Class

That is it. Now you can atleast read and understand most of those VB.NET source code, and probably implement more OOP features in your VB.NET programs. Now, in my next article, I'll try to cover the patterns and practices in VB.NET.

History

  • Nov 13th, 2004
    • Prepared this article for publishing.

Tech Bits, Tech News, Emerging Trends