VB.net Tips-I

The Dot Net factor: It gets better

Visual Basic is like an ocean. Whenever I stumble on a tip I hate myself! It makes me feel very humble and many times very insecure. Whenever I see a new tip, I know there exists another thousand that is also new to me. 

Visual Basic developers have a new lease of life with the Dot Net 2.0 Beta and the new Whidbey edition. Hence I will focus first on the Visual Basic 2005 Beta Edition based tips.

The New Continue statement in VB.NET 2005


The New feature in Visual Basic .net 2005 is Continue statement. This new feature of the Continue statement is to allow for the Continue to be on an outer loop. For example, if you were iterating a loop for 10 times and you want to skip the loop when it becomes 5th time, you can use the continue statement to skip the 5th time. This feature is available in the new Visual Basic edition only.

Using For loop with Continue statement in Visual Basic.net 2005 you can write a simple program that demonstrates to you the use of VB’s new continue statement.. Add the following code in button event and test the result.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For i As Integer = 0 To 10

' If i = 5 then it will skip and it will show the number 6 on message box
If i = 5 Then Continue For

MsgBox(i.ToString)

Next
End Sub

Using While loop with Continue statement in Visual Basic.net 2005

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

        'While using Continue statement.
        Dim a As Integer = 1
        While a < 10
            a += 1
           ' If i = 5 then it will skip and it will show the number 6 on message box

           
If a = 5 Then Continue While
            MsgBox(a.ToString)
        End While


DO While using Continue statement in Visual Basic.net 2005

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

       
' Do While using Continue statement.
         Dim k As Integer = 1
        Do While k < 10
            k += 1
          ' If i = 5 then it will skip and it will show the number 6 on message box
            If k = 5 Then Continue Do
            MsgBox(k.ToString)
       Loop
    End Sub
End Sub


You can use this continue statement for three loop constructs, While, For and Do loops. You can mix and match these loops with continue statement. Have fun with Continue….

Encrypting & Decrypting in Visual Basic .net 2005



This tip comes from MuthuSelvam from Madurai. He explains how you can use VB to encrypt and decrypt the data. Muthu says he used the Express editions supplied with November edition of the magazine
Encryption is nothing but an algorithm used to scramble data, which makes it unreadable to everyone except the recipient. Decryption is the restoration of encrypted data to their original text.

For example when you are working with your registration form when the user enter the password and you want to store the data in a database with encryption manner with out reading the password from database. In this situation you can encrypt the data and store in and database. In similar way while storing data in a file or while transfer the data from client to server etc you can use encrypt and decrypt methods. .

Now in this example we will explain you how you can encrypt the plain text and decrypt the test back to normal text with few lines of code.

Add the following code to your code window.

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

        Dim Assigned_text As String
        ' Encrypting  the text
        Assigned_text = "Encrypting and Decrypting example"
        Assigned_text = encrypt_decrypt(Assigned_text)
        MessageBox.Show(Assigned_text)
        ' Decrypting the Text
        Assigned_text = encrypt_decrypt(Assigned_text)
        MessageBox.Show(Assigned_text)
    End Sub

   
Public Function encrypt_decrypt( _
          ByVal Text As String) As String
        ' Encrypts/decrypts the passed string using 
        ' a simple ASCII value swapping algorithm
        Dim sampletext As String, a As Integer
        For a = 1 To Len(Text)
            If Asc(Mid$(Text, a, 1)) < 128 Then
                sampletext = _
          CType(Asc(Mid$(Text, a, 1)) + 128, String)
            ElseIf Asc(Mid$(Text, a, 1)) > 128 Then
                sampletext = _
          CType(Asc(Mid$(Text, a, 1)) - 128, String)
            End If
            Mid$(Text, a, 1) = _
                Chr(CType(sampletext, Integer))
        Next a
        Return Text
    End Function


When you click on the button you can notice a message with the encrypted text as well as decrypted text.


Using Statement in Visual Basic .net 2005

The Using statement is a shortcut way to acquire an object, execute code with it, and immediately release it. A number of framework objects such as graphics, file handles, communication ports, and SQL Connections require you to release objects you create to avoid memory leaks in your applications. Assume that you want to write a text in the hello.txt file. Use the Streamwrite class to create a text file and add the text into that file. Add the below code to your class module.

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

        usting_write()

    End Sub

    Public Sub usting_write()
        Using swriter As IO.StreamWriter = New IO.StreamWriter("C:\helloworld.txt")
            swriter.Write("helloworld")
        End Using
    End Sub

The Using statement is much cleaner than using Try / Catch and releasing the object in the Finally block as you have to in Visual Basic .NET. 

In Visual Basic .NET 2002 or 2003, you can get the results in this way.

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

        Dim afile As System.IO.File
        Dim swriter As New System.IO.StreamWriter("C:\hello.txt")
        Try
            swriter.Write("Hello World")
        Finally
            swriter.Close()
        End Try
    End Sub

Now you must of noticed the difference between Using and Try / Catch statements in visual studio.net.

App.Path in Visual Basic.Net:

Kunal Mukherjee has won my heart with not just one top but three. I borrow some of hios explanation in the next few paragraphs. VB6 programmers are well aware of the "app.path" code. But in Dot Net we don't have the app term anymore, instead we now have to use the "Application" Keyword. Now this quick know section provides you the knowledge how to do the same (app.path) in VB.Net.

first way:

System.Reflection.Assembly.GetExecutingAssembly.Location -> Gives you the full path + the exe name

Advantage:
You don't need to know the app name.

Actually since System namespace is imported by default you wouldn’t need to declare the system part you could just do Reflection.Assembly.GetExecutingAssembly .Location But the most beneficial way of doing it would be to use ( Imports System.Reflection.Assembly )then all you would call in your application is msgbox(GetExecutingAssembly.Location) 

second way:

Dim fiExecAndPath As New FileInfo(Application.ExecutablePath)
fiExecAndPath.ToString -> path with exec file. ie: c:\temp\file.exe 

third Way :

Dim strExecPath As String = fiExecAndPath.DirectoryName
strExecPath.ToString -> full path without exe. ie: c:\tem 

fourth way:
Application.ExecutablePath.ToString -> Gives you the full path + the exe name

fifth way:
Application.StartupPath.ToString -> Gives you the full path - the exe name

I am sure above all those most of you will like the last two. But believe me there are cases where you may need the others also. 

How to check null values when doing database applications:

If you try the old fashioned way of checking for null:

If IsNull(rsCompany("Name")) Then

Visual Studio will tell you that IsNull is not supported and to use DBNull instead.
The Visual Studio help was its usual cryptic self ("The DBNull class is for handling NULL values"...accurate by not a lot of help). After some fumbling around, I stumbled on the answer, and thought I'd share it to hopefully save someone 5 minutes of having to research it:

If rsCompany("Name") is DBNull.Value then
Here "name" is the field name. Replace it with your own field names.
Hope this saves you some time!

A great way (the only right way) to check for previous instances:

The following traditional way is not always safe and reliable. It’s also a slow process.

Dim AlreadyRunning As Boolean = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1

But the following example is much faster and much more reliable:

'-------code starts here-------

'Put the next line of code at the very top
Imports System.Runtime.InteropServices

Public Const ERROR_ALREADY_EXISTS As Integer = 183

Public Declare Function CreateMutexA Lib "Kernel32.dll" (ByVal lpSecurityAttributes As Integer, ByVal bInitialOwner As Boolean, ByVal lpName As String) As Integer

Public Declare Function GetLastError Lib "Kernel32.dll" () As Integer

Public Function IsProcessAlreadyRunning() As Boolean
'Attempt to create defualt mutex owned by process, MyApp can e.g. be the name of the executable
CreateMutexA(0, True, "MyApp")
Return (GetLastError() = ERROR_ALREADY_EXISTS)
End Function

'----------code ends here-----------
now check at the load event of your form:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If IsProcessAlreadyRunning() Then
MsgBox("Sorry! another instance already exists!")'giva a suitable message to the user
Application.Exit()'exit the application
End If
End sub

The Text Property of the Masked Edit Control Does Not Work at Run Time in Microsoft Visual Basic .NET:

In Visual Basic .NET, you cannot access the text that you type in the Masked Edit control by using the Text property. The text that you assign to the Masked Edit control by using the Text property is not visible on the control. However, you can access the text by using the Text property if the text is assigned by using the Text property. 

Because, the Text Property is a non-browsable property of the Masked Edit control. The Masked Edit control is a Component Object Model (COM) control that you can only access through a COM Interop Wrapper. The Text property does not read the text that you type in the Masked Edit control, because the Text property is not hooked to the underlying OCX control. You cannot access the Text property in Microsoft Visual C# .NET. 

To work around this problem, use the CtlText property instead of the Text property. The Masked Edit control uses the CtlText property to set the text that you type in the Masked Edit control. For example, you can use AxMaskEdBox1.CtlText = "0123" instead of AxMaskEdBox1.Text = "0123". 

Displaying the Form anywhere in the screen.

Nayan Tara from Raipur has sent this tip. When you are working in a project sometimes you want to display the form according to your requirements. You can achieve the result easily in visual studio.net. In case you want to display the form in the lower center of the screen, you can follow the steps to get the results.

It uses the SystemInformation object's Operational_region property to 
get the area that is available for use. It then moves the form so it sits in the lower center of the screen.

Add the following code in the form load event and run the application.

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

        Dim Operational_region As Rectangle = SystemInformation.WorkingArea
        Dim x As Integer = Operational_region.Left + Operational_region.Left + Me.Width()
        Dim y As Integer = Operational_region.Top + Operational_region.Height - Me.Height

       Me.Location = New Point(x, y)
    End Sub

Now you can notice the form. It must have changed the position on the screen.




Added on December 17, 2007 Comment

Comments

Post a comment

Your name:

Comment: