Archive | August, 2008

Coding How-to #2: Find the largest value in an Integer Array

26 Aug

So how do you programmatically get the largest number in an integer array? Well I have two simple ways of doing it – as usual, you can kill a bird with two stones right? or is it the other way round? you can kill two birds with one stone, no wait, you can kill two stones with one bird…you can kill two…..CUT!! anyway, let’s write some code.

Using built in array methods ( Sort and Reverse)

Now this is a dirty trick. Short and concise and gets the work done, though it might have some drawbacks. First I sort the array, it’ll sort the integers from the minimum to the largest. Then I reverse the array and capture the first element. Ahaa!

Private Function GetLargeInt(ByVal data() As Integer) As Integer

      Array.Sort(data)

      Array.Reverse(data)   

      Return data(0)

 End Function

Just try it and see for yourself. Works fine.

Standard way

Now here I wrote a “better” algorithm, that doesn’t rely on the in-built array functions. Get the minimum value for the integer data type (You could actually modify this code to work with the numeric data type you want to) and iterate through the array with a simple for each loop comparing each element with my value. If it is larger than my value, I assign it as my new value and move to the next. Well the code will explain more.

 

Private Function GetLargeInt(ByVal data() As Integer) _
                           As Integer
   Dim res As Integer = Integer.MinValue

   For Each i As Integer In data
      If i>res Then res = i
   Next
 Return res
 End Function

 

You can create a simple console app to try this out. Or you can try it anywhere in your project. I tried it with this array..

Dim arr As Integer() = _
{-1,132,1121,3,15,6,17,8,9,10,12,14,157,75}

 

 Console.Writeline(GetLargeInt(arr).ToString)

..and it returned 1121.

Till next time, I’m out for now.

Coding How-to #1: Reverse a String

20 Aug

Okay, welcome to the Coding How-to section or category, wherein I’ll be giving some code tips on how to solve simple problems that you encounter in your daily life, writting code. You may ask isn’t this what I have been doing all along in this blog, well yes and no. This section will focus entirely on that specific problem, will be concise and to the point. No yada yada :-) {guaranteed.}

Okay enough yada yada already. Let’s see some code. So today I’m going to show how to reverse a string, and we’ll see if there’s more than one way to do it, and which way is more efficient etc.

Array.Reverse
This is simple, we are going to break the string into single characters and put them into a char array, call the array.reverse function which takes a char array as an argument, and build a new string from the reversed array. Here’s the code I wrote

Public Function Reverse(ByVal input As String) _
                         As String
        Dim res As Char() = input.TocharArray
        array.reverse(res)
        Return New String(res)
End Function

Wouldn’t it be lovely if someone asked MS to include this in the string class? and you would call it like String.Reverse(“yada yada”) ? :-)

To try it call Reverse(“welcome again”) and the output will be niaga emoclew. Thats it, we are done with this.

Do not use in-built libraries.
So, how will you go about it if you are not to use inbuilt libraries?Like array.reverse? Well it’s simple again. Iterate through the string from the end to the beggining, inserting each character to another string. How? Here’s the code I came up with again.

Public Function Reverse(ByVal input As String) _
                        As String
        Dim result As String = ""
        Dim Last As Integer = input.length - 1

        For i As Integer = Last To 0 Step -1
            result += input.Substring(i, 1)
        Next
    Return result
End Function

… and you are done. To try it call Reverse(“welcome again”) and the output will be niaga emoclew. It works like magic. Now it is up to you to choose which one is more convenient. If I get time, I’ll definitely run them against timers, with large strings to see which one if faster, and will update this post accordingly.

Comments are welcome, if you have a simpler way of reversing a string, or a shorter piece of code, or anything realy.

Till next time…yours truly.

 

 

Using a Single EventHandler for events from multiple controls.

18 Aug

In windows forms application development, you can use a single method to handle events from multiple controls. Here is a simple definition of events from MSDN.

An event is an action which you can respond to, or “handle,” in code. Events can be generated by a user action, such as clicking the mouse or pressing a key; by program code; or by the system.

 Let’s say you need to change the backcolor of a textbox or a listbox to light blue when the control gets the focus or when a user selects it. To do that you would normally write code to change the backcolor when the Control.Enter event fires as shown in this code below.

Private Sub TextBox1_Enter(ByVal sender As _ System.Object, ByVal e As_ System.EventArgs) Handles TextBox1.Enter
TextBox1.BackColor = Color.LightBlue
End Sub

 And of course you will also need to write code for the Control.Leave event as shown below to restore the default background color when the attention leaves the control (this is because if you do not create the event handler for the leave event, the control will remain with the same background color even after the user has exited.

 Private Sub TextBox1_Leave(ByVal sender As _
System.Object, ByVal e As _
System.EventArgs) Handles TextBox1.Leave
TextBox1.BackColor = SystemColors.Window 
End Sub

 So now imagine you have a form with 50 controls. How much code are you going to write? That’s 100 event handlers to perform almost the same task. A lot of unnecessary code right? Well fortunately enough there is an easy way to help you from writing all those unnecessary, repeating lines of code.

 A single Event Handler

The easy way to go around this issue is to create a single event handler, which will handle the same event for any number of controls. We’ll create a simple windows forms application with a four textbox controls and use one event handler  to change the backcolor of the controls when they get the focus.

1. Open your IDE and create a windows forms application. Give it the name of your choice.

2. Add four textbox controls and change their names to  txtFirst, txtLast, txtGender and txtBirth

3. Right click on an empty space on the form and select View Code.

4. Inside the class, Type the following piece of code.

 Private Sub Control_Enter(ByVal sender As _
System.Object, ByVal e As System.EventArgs)
Dim ctr As Control = CType(sender, Control)
ctr.BackColor = Color.LightBlue
End Sub 

There is our event handler, I’ll explain a little. What we did here is create a control, make sure we cast (or change the type of) the object (sender) that fired the event to a control, and then add some code to manipulate the control. In this case, change the backcolor to light blue. 

 

Handles.
In windows forms we use the keyword Handles to indicate that this specific method (event handler) handles (or takes care of) a certain event. You use it to indicate the name of the control and the event that the method handles.  You probably have seen this several times in windows forms development.

 Private Sub Button1_Click(ByVal sender As _
System.Object, ByVal e As _ System.EventArgs) Handles Button1.Click 
'add some code here
End Sub 

 This means that the Button1_Click method handles the Button1.Click event. The event itself is at the end of the line. You can include multiple events here, from multiple controls; this is to say you can use the same event handler to handle multiple events from different controls. 

Now go back to our Control_Enter event handler and add the following changes.

 

 Private Sub Control_Enter(ByVal sender As _
System.Object, ByVal e As _ System.EventArgs) _ 
Handles txtFirst.Enter, txtLast.Enter, _ 
txtGender.Enter, txtBirth.Enter 
Dim ctr As Control = CType(sender, Control)
ctr.BackColor = Color.LightBlue
End Sub 

 

What we have done here is use the same event handler to handle the .Enter event from multiple controls, and we are changing the back color to light blue.

Now go back to the form designer, select each control and under the properties panel, click the lightning bolt button to display the events for the control. Click the arrow next to the Enter event, and select Control_Enter.

 

Control's properties
Control

Run the form and click on the controls separately to see that the back color changes when you enter the control.

 

Backcolor changes on enter
Backcolor changes on enter

Now we will create another event handler to handle the leave event, so we can restore the control’s backcolor to its default color when the attention moves to a different control. Go to the form’s code, and paste the following code within the class to create the contor_leave event handler.

 Private Sub Control_Leave(ByVal sender As _
System.Object,ByVal e As System.EventArgs) _
Handles txtFirst.Leave, txtLast.Leave, txtGender.Leave, txtBirth.Leave
Dim ctr As Control = CType(sender, Control)
ctr.BackColor = Color.White
End Sub 

 Again as you did for the Enter event, go to the forms designer, select the properties for each controls, go to the events and under the Leave event. Click the arrow to display available event handlers, select Control_Leave and run the form to see that the backcolor is reset to the default white when you leave the control. 

As you can see, it is as simple as that. You can use this technique to perform various tasks using single event handlers, to take care of events firing from multiple controls and of course you can do this according to your different specific needs. Again this post is just a scratch at the top, and your comments are welcome. 

 

 

 

 

Running a Visual Basic program with Command Line Arguments

12 Aug

In .Net you can easily write full and powerful programs using a simple text editor like notepad, and execute the programs without any problems.You can also easily run the programs with command line arguments.In this post I will show you how to configure your system, and the command prompt, so that you can write your programs in Notepad, compile and run them at the command prompt, and additionally how you can run the programs with command line arguments.

Since I haven’t completely moved to C# yet (still getting my feet wet with the language), the code samples will be in VB.Net. But for the C# programmers, you can easily convert the code and make it work.

Some advantages of using command line aruments are first you write fewer lines of code, and second it saves you the time, from say program start > UserInput > execute to program start with input >execute.
For example to run a simple addition program.You click start>run> C:\Add.exe 12 12 

Configuring the compiler.
The compiler used to create Visual Basic applications is called vbc.exe and it is installed by default in the path, Drive:\Windows\Microsoft.Net\Framework, however you can’t just use it from there. To use it for all your programs, you need to include it in your system path.I will show you how to include it below.This works for Windows 2000/XP/2003. I haven’t tested it against Vista.

  •  
    • In windows explorer, locate the folder where the compiler is installed, example, mine is C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727
    • If you have different .Net Frameworks installed, you will see all of them in the folder ..\Framework. Choose the appropriate framework and double click to open its folder. For this post we’ll use . Net Framework 2.0
    • Copy the path.
    • Click Start>Control Panel and then Double Click on System.
    • Click the advanced tab on the System Properties dialog box, and then click Environment Variables.
    • Under the System Variables Section, click Path and then click Edit.
    • Check if the path C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727 already exists.If it doesn’t, move to the end of the string, type ;  then paste the path you copied earlier in step 3.
    • After this step, mine looks like this
      %SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727
    • Click OK to close the dialog box, and click OK to the remaining of the dialog boxes.
    • Congratulations, you are done.

Now we are going to write our program , compile it using the compiler we just configured and execute it. The program will display some text to the console window.

Let’s write some code.
Start Notepad and type in the following code

Imports System
Module Sample
Sub main()
Console.Writeline("Hello there, welcome!")
Console.Write("Press Enter to close the program")
Console.Read()
End Sub
End Module

 

Click File>Save As and type Sample.vb
Under the Save in box, browse to the C:\ directory
Under Save as Type, make sure to select All Files.
Right Click in the window and select New>Folder. Type Test and then Double click to open the new folder. Click Save to save the program in this folder.

How to Compile and run the program
Now we are going to compile and run our program. Click Start > Run then type cmd and click OK to open the windows command prompt.
We need to change the directory to the location of our .vb file in order to compile it. To change the directory, under the command prompt type cd\ and press Enter.
Type again cd Test and press enter.You are now in the directory with our program.
To compile the program type the following: vbc Sample.vb and then press enter. If the program compiles without any errors you will see the following text displayed and a command prompt. If an error message is displayed, go back to Notepad and make sure you wrote the code correctly.

C:\Test>vbc sample.vb
Microsoft (R) Visual Basic Compiler version 8.0.50727.1433
for Microsoft (R) .NET Framework version 2.0.50727.1433
Copyright (c) Microsoft Corporation.  All rights reserved.

C:\Test>

Now at the command prompt, type sample and press enter.You will see output as in the image below.

Congratulations. You have successfully created, compiled and executed a simple application by just using Notepad and the command prompt. If you browse to the Test folder, you will see that a new file has been created with the name sample.exe.That is our executable program. To call it from the command prompt, you can ommit the .exe and just type sample.

Command Line Arguments
Now we are going to modify our program to accept command line arguments, and do something with them.
Change the source code as shown below.

Imports System
Module Sample
Sub Main(Byval args() As String)
Dim data As String = args(0)
Console.Writeline("Your input was: {0}", data)
Console.Write("Press Enter to close the program")
Console.Read()
End Sub
End Module

 

Let me explain the basics. The programs accepts arguments as an array – args() of strings. This args() parameter is handled by the system, and it accepts any arguments you will need to supply to the program. All you have to do is add some code to work with the string parameters or parse them into integers or other data types that you may want to work with.
Save the changes you made to the sample.vb file.

Go back to the command prompt and type vbc sample.vb and then press Enter.(You need to re-compile the program every time you make any changes.)
At the command prompt, type sample.exe “Hello there” and press enter. The program will run and you will see the output in the window.

Your input was: Hello there
Press Enter to close the program

The easy way.
Now click Start > Run
Type C:\Test\Sample.exe “Hello and welcome”
Click ok
The program will run and show your input to the console window.

Multiple arguments.
Now let us modify the program to accept two arguments. First we will create a simple procedure that adds two numbers, and then launch our program with the two numbers to be added as arguments. Modify the code to the following.

 

Imports System
Module Sample
Sub main(Byval args() As String)
Dim first As Integer = Cint(args(0))
Dim second As Integer = Cint(args(1))
Total(first,second)
Console.Write("Press Enter to close the program")
Console.Read()
End Sub
Sub Total(Byval first As Integer, Byval second As Integer)
Console.Writeline("The total is: {0}", first+second)
End Sub
End Module

Save the file, switch to the command prompt, compile the program and then minimize the command prompt.
Click Start > Run and type C:\Test\sample.exe 12 12
The program will run and display the following output to the console window.

Note that if you have written code to work on two or more parameters, you must supply all the parameters otherwise your program will generate an error at runtime. For simplicity in this sample I did not add any error handling code. You can add try catch blocks to display appropriate error messages when you write your programs.

There are many things you can achieve by launching a program with command line arguments. You can supply a file path and perform some action against the file etc.This post only scratches the top, giving you the basics and showing you that like with C/C++ even with VB.Net, you can successfully create programs that accept command line arguments.

Well again that is it for now. I hope you got the idea on how to create VB.Net programs that accept command line arguments. If you have any questions or need any additional info, please add your comments below or email me through n i c l i v e @ g m a i l  dot c o m.

Follow

Get every new post delivered to your Inbox.