This blog is targeted at beginning / novice programmers for the Visual Basic (VB) language.

Friday, May 23, 2008

Recent Review: C# & VB.Net Conversion

I wanted to write this quick blog entry to let you know I recently performed a review on a book called, "C# & VB.NET Conversion". This book basically acts as a reference to help in the process of converting from C# to VB.Net (or vice versa).

For under $6 (for used versions) it's well worth the read. It was written quite some time ago, but still very much applies in today's uses.

You can read my blog entry, "Review: C# & VB.Net Conversion" at: http://codingchat.blogspot.com/2008/05/review-c-vbnet-conversion.html

Until next time, Happy Coding!

Friday, March 21, 2008

Introduction to LINQ in VB

Overview:

By now, most of us have heard of LINQ and have a general concept of what it is and what can be done with it. For the few that don't I'll lightly skim over it. The remainder of this post will discuss what the major differences are between LINQ in VB and LINQ in C# and also offer some resources to get technical information, practical examples, and some very helpful videos. Best of all; ALL of these resources are FREE!!!

What is LINQ? How do I use it?

"LINQ" is an acronym formed from the .Net 3.5 framework named "Language INtegrated Query". The LINQ framework is composed of LINQ enabled data sources (also commonly referred to as data providers). There is a subset of data providers that are ADO.Net enabled; these are: LINQ To Datasets, LINQ to SQL, and LINQ To Entities (LINQ To Entities is currently in development and has been confirmed to be included in Service Pack 1 update for Visual Studio 2008). There are 2 other included data providers for LINQ called: LINQ To Objects, and LINQ To XML. You can also make your own data providers to be used; there are even data providers already created by 3rd party vendors, such as LINQ To Amazon that you can obtain (some may have associated costs; these are determined by each vendor and are typically not supported by Microsoft).

LINQ is automatically enabled, to some extent, with Visual Studio 2008. Your only real requirement is to use the .Net 3.5 framework. Conceptually you could use Visual Studio 2005 and LINQ; however, there are many additional features/enhancements included with Visual Studio 2008 that can leverage LINQ in a more powerful manner than you would be able to with Visual Studio 2005 (such as Type Inference and XML literals). To use LINQ you simply set your references to the appropriate namespace of the framework class you want to use (VS 2008 includes some namespaces automatically) and then you can use the 'Imports' keyword to enable local declarations at the class level.

Example of enabling at the class level would be:

'System Namespaces
Imports System.Data.Linq

Public Class Form1
'Insert your LINQ code here
End Class

As you can see, enabling LINQ at the class level is quite simple to perform.

What can I do with LINQ?

Well, that is a very broad answer. Basically anything that could be considered a collection or data collection can be used by LINQ. In fact you can even use LINQ for many documents that are created by Office 2007; this is because Office 2007 documents are actually a collection in a zip file of XML and other items. You can actually rename any Word document with a ".zip" extension and then easily view and modify the content within the document. This means you could literally create or modify a Word 2007 document without having Word 2007 installed on the machine!

Why you might ask would someone want to do this? That's quite simple; let's say you have specific information you want to create a set of documents for (similar to using MailMerge in Word); well, if you already have a template or base document created, you could actually use VB to modify the document.xml file within the docx file collection and create the merged document. A great example would be to notify a list of customers that may not have placed an order with your company within the past year. You could use LINQ To SQL (assuming the data is in an SQL database) and iterate through the customer information looking for last activity or order date of more than 1 year ago..take this information and use LINQ To XML to insert the data into your custom created docx file, then save each file created as a new docx filename (such as the customer's account name). Since you don't have to have Word installed to work with an existing docx file, you could leverage the power of your server machine to do the processing work for this task. This means, although not recommended, you could literally create your files right on your SQL Server machine and store the documents within your SQL Server database that could later be used to be sent out to your 'inactive' customers to see if you can drum up some repeat business! How cool is that?!

That's only the tip of the iceberg. Remember, LINQ is designed to easily iterate through a collection of data and to work with that iterations. You can probably already think of a whole bunch of data that it would be great to go through quickly and seamlessly. Because LINQ was designed to use a "standard" query language this means you can create a LINQ query that can be used on SQL, XML, Entities, Objects, and any other data provider you get access to.

This all translates to one wonderful meaning...Once you learn LINQ regardless of the way you use it, you can use LINQ with any other data provider; but, do be aware that there are a few data providers that have a few extended uses that can't be interchanged...but with very little ingenuity you can quickly figure out how to leverage these powerful extensions, such as XML Literals, with the other Data Providers. You can even seamlessly use multiple LINQ query structures within a single query!

What is different in LINQ for VB than in LINQ for C#?

The biggest difference is what is called XML Literals and XML Axis, these can ONLY be used in VB; they are not supported in declarative languages.

First, the big one is XML Literals. With XML Literals you can create XML code that resembles what the output of your XML document will look like. This allows for a true representation of the XML code and document; it's basically the XML WYSIWYG in VB editor! Here's an example of a very simple XML Literal that would have an output that is exactly the same as the code:

Dim myBloxXML = _
           
<Blog>
               
<Name>Visual Basic Helper Blog</Name>
               
<URL>http://visualbasichelper.blogspot.com</URL>
               
<LastPostingName>Introduction to LINQ in VB</LastPostingName>
           
</Blog>

The output would look like this:

<Blog>
     <Name>Visual Basic Helper Blog</Name>
     <URL>http://visualbasichelper.blogspot.com</URL>
     <LastPostingName>Introduction to LINQ in VB</LastPostingName>
</Blog>

As you can see, this is very powerful and allows you to easily determine if something is out of place and how your final document will look like; without ever running the code..and you get the benefits of the type-safety and declaration checking.

But, it doesn't stop there. You can also use embedded expressions; this is both C# and VB enabled. An embedded expression is triggered by using a <%= > enclosure. Here's an example of a simple expression that would retrieve all of the customers from a database table called "Authors". I'm not going to cover the entire method to connect to the database, that'll get covered another time...mainly just look at how I can insert a LINQ query right into my LINQ To XML constructor...and notice that I am mixing the two forms of querying...I'm using LINQ to XML to make the XML tree; but I'm also using LINQ to SQL to get the data to put in the tree...never having to stop my train of thought or change any coding declarations; I just type and go. Here's an example:

Dim myCustXML As XElement = _
           
<Customers>
               
<Customer>
                   
<%= From c In dbcntx.Authors _
                       
Where c.Auth_LName Like "*A*" _
                       
Select _
                       
<Name>
                           
<%= c.Auth_FName %> <%= c.Auth_LName %>
                       
</Name> %>
               
</Customer>
           
</Customers>

The ouput would be:

<Customers>
      <Customer>
            <Name>Stephen Allway</Name>
            <Name>Robert Alonzo</Name>
            <Name>Tom Anand</Name>
            <Name>John Arnold</Name>
            <Name>Alfred Axel</Name>
      </Customer>
</Customers>

As you can see here, I easily went between the two LINQ data providers and formed a very simple tree; I'm only showing a few returned results due to space consumption, but you should get the idea.

This now leaves us with XML Axis; this is basically a shortcut method to tell your code what part of XML to look in. Example would be you could use the trigger "@" to tell your code that you are looking for an XML Attribute. You could use the trigger "..." to tell your code that you are looking for any descendent within the branches of your tree; or you could use "<>.<>" to tell your code where the specific child element is located.

Here are some very quick examples:

'XML calls are based on this XML tree
        Dim myCustomers = _
       
<Customers>
           
<Customer>
               
<Name id="1" age="30">Stephen Allway</Name>
               
<Name id="2" age="55">Robert Alonzo</Name>
               
<Name id="3" age="17">Tom Anand</Name>
               
<Name id="4" age="25">John Arnold</Name>
               
<Name id="5" age="75">Alfred Axel</Name>
           
</Customer>
       
</Customers>

       
'Get age for first name element
        Console.WriteLine("Age: " & myCustomers...<Name>.@<age>)
       
'Get name for first customer by using decendants
        Console.WriteLine("Name: " & myCustomers...<Name>.Value)
       
'Get name for first customer by using child
        Console.WriteLine("Name: " & myCustomers.<Customer>.<Name>.Value)

The entire output would be:

Age: 30
Name: Stephen Allway
Name: Stephen Allway

The other worthwhile note is that the major difference between descendants and child methods is performance. The child method will perform better than the descendants method; this is because the descendants method will search all parts of the element and return ANY and ALL that match it...so if you were to have the following tree:

<Family>
    <Pets>
        <Name>Fluffy</Name>
        <Age>3</Age>
    </Pets>
    <Children>
        <Name>Alexis</Name>
        <Age>10</Age>
    </Children>
</Family>

If you were to use the <Family> as the root node, and call the descendants method looking for <Name> you'd get "Fluffy" and "Alexis" returned; this is because the method only limits it's search to the root node and all child nodes.

If you were to use the same scenario as above and use the child method you could specify if you want to return the Children or Pets node. An example would be:

Console.WriteLine("Name: " & myFamily.<Family>.<Children>.<Name>.Value)

As you can see to call each trigger is simple; these are included with the XML Intellisense by default. All you need to do is to have a variable that is of the XML data type.

Conclusion

This was just an introductory to LINQ in VB; this topic is huge and probably one of the largest (if not the largest) addition to the .Net 3.5 Framework and also for Visual Studio 2008.

As you saw this framework is not limited to Visual Studio 2008; however, if you want to leverage all aspects of LINQ you will have to use Visual Studio 2008 then. You also saw that LINQ was developed to be interchangeable in your code, and there are a few subtle differences between the C# implementation and VB's implementation.

Hopefully, I've been able to get you to a starting point that can the primer for learning more about LINQ. Once you play around with it, you'll probably find yourself constantly finding new ways to use it and it will be one of your most desired tools when working with any sort of data collection.

Additional Resources:

MSDN Language Integrated Query (LINQ) - (http://msdn2.microsoft.com/en-us/library/bb397926.aspx)
The LINQ Project - (http://msdn2.microsoft.com/en-us/netframework/aa904594.aspx)
Beth Massi - Sharing the Goodness that is VB - (http://blogs.msdn.com/bethmassi/)
LINQ 'How Do I' Videos - (http://msdn2.microsoft.com/en-us/vbasic/bb466226.aspx?wt.slv=topsectionsee#linq)

Until next time...Happy Coding!

Tuesday, March 11, 2008

Processing a string into groups of 3

Today, I was browsing the vb.general.discussion newsgroup and came across a person who had wanted to take a textbox input and group the text into groups of 3 using a space to separate the groups. Example being:

Input: 1234567

Output: 1 234 567

Because I was unsure if they were dealing strictly with numbers I found the easiest method was to use the System.String namespace and create a function that would take the input and figure out the total number of groups within the input. It would then separate the groups into a group of 3 and while doing so insert a blank space between each group.

I thought those of you that are new to VB and, especially, new to the System.String namespace may want to see the power that is literally at your fingertips!

This example I had made within about 30 minutes; and was all made on the fly (I know, I know..I didn't plan it out; I was a bad programmer!...shhhh...don't tell anyone!). This is the 'complete' coding:

Setup: I had created a visual basic windows form. I inserted the following controls (left everything at the default settings/names):

2 x Buttons
2 x Labels
2 x Textboxes

Here's the coding I used:

Imports System.String

Public Class Form1
   
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
       
Application.Exit()
   
End Sub

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

       
'Call custom function
        strNewText = Create3by3(TextBox1.Text.ToString)

       
'Assign results to textbox
        TextBox2.Text = strNewText
   
End Sub

   
Private Function Create3by3(ByVal strToProcess As String) As String
       
'Declare local variables
        Dim intLength, intNumGroups, intPosition As Short
       
Dim strTemp As String = ""
       
Dim intCount As Integer = 0

       
'Test if value is being passed, if not then notify end-user
        If strToProcess.Length = 0 Then
           
MessageBox.Show("Please enter a value to be processed before continuing.", _
                            "Missing value"
, MessageBoxButtons.OK, MessageBoxIcon.Stop)
           
TextBox1.Focus()
       
End If

       
'Set empty string; avoids warning message of variable not being assigned
        Create3by3 = ""
       
Try
           
'Check if value being passed is more than 3; if not then don't need
            'to go through complexity of processing the string
            If strToProcess.Length <= 3 Then
               
Create3by3 = strToProcess
               
Exit Function
           
End If

           
'Get total length we are working with
            intLength = strToProcess.Length

           
'Important to use the \ NOT the /; because we only want to deal with 
            'whole numbers, no decimals!
            intNumGroups = (intLength \ 3)

           
'This is used to determine the index position of the string we are
            'working with.
            intPosition = intLength - (intNumGroups * 3)

           
'This is a late declaration because it is dependant on how many
            'items we will want in our array which is how many groups we are
            'working with total (our division results + 1 for odd number of
            'the last group (first part of the string)
            Dim sSubStr(intNumGroups + 1) As String

           
'First we insert the odd number of characters; we start at index
            'position 0 and only move until we reach our first group
            sSubStr(intCount) = strToProcess.Substring(0, intPosition) + " "
           
'Don't forget to increase our array index since we filled our first
            'item in the array
            intCount += 1
           
'Now we just loop through the groups and add each one to the array
            For i = 0 To intNumGroups - 1
               
sSubStr(intCount) = strToProcess.Substring(intPosition, 3) + " "
               
'We increase the index position of the string by 3 since we are
                'working with a group of 3
                intPosition += 3
               
'We increase our array index to move to the next item in the array.
                intCount += 1
           
Next
           
'Now we simply just add the entire array into 1 large string
            'with our spaces we placed during our processing
            Create3by3 = String.Concat(sSubStr)
           
'Now we just remove the final spacing; because we don't need it and
            'we have the opportunity to do it now, instead of later.
            Create3by3 = Create3by3.TrimEnd(" ".ToCharArray)
       
Catch ex As Exception
           
'Catch any exceptions; biggest worry is the DivideByZero; but, we are
            'already testing for that at the beginning of this function
            MessageBox.Show("An exception was encountered." & vbCrLf & ex.Message)
       
End Try
       
'Return the results of our processed string!
        Return Create3by3
   
End Function
End Class

As you can see; this is actually not all the difficult of a task and most of the complex parts are already built into Visual Basic. How cool is that? All I needed to do was the split the string, keep track of how many groups there were; then just a matter of building a new string based on this information.

If you or anyone else has a question about this please do not hesitate to post a comment; I'd be happy to clarify it further!

Until next time....Happy Coding!!!

Friday, February 29, 2008

Coding and Naming Conventions

This will be a quick blog. This is a topic that you should already know, and if you don't, you should stop everything and learn as much as you can about it. I'm not kidding either!

Coding Conventions:

Coding conventions is really simple. These are a set of conventions that help the programmer that is coming into a project, handing over a project, or simply returning to their own project to be able to easily read and identify what a block of code is doing and to identify properties, methods, and variables.

Here's a very simple analogy. Let's say you talked to your friend "John" and he said he was flying into JFK tonight and would like for you to pick him up. Let's even go as far to say that you don't have an idea of what he looks like, what is last name is, or what airline he flew in on. Do you think you could find him? If so, do you think it would've been a lot easier to know his last name at the minimum, or have all the information such as flight #, origination, airline, etc?

Believe it or not, programming is the same way. Think of each time you create a variable, method, or property that you were to use only 1 letter and nothing else. So, you obviously start with 'a' then go to 'b', then 'c', etc. Imagine doing an application that contains 500,000 lines of code, do you think you could easily determine what 'q' was used for? I don't think it would be simple; and the amazing part is that there are people out there doing this sort of thing.

Another common practice is to name your method with something simple like "getID", or "setName". Well, this might be ok in a small application. But what if you make an enterprise application that uses employee IDs, vendor IDs, contractor IDs…and whose name are you setting? What if the name is: Angel Flowers? Do you know if you are setting a company's name or a person's name? Can you tell later what method of 'setName' you had used? Or what 'getID' you had incorporated?

How do you stop this? Easily, use a 'best practice' and follow coding conventions. Microsoft had gone through all the trouble for you and put together a nice basic summary of suggested conventions. You can view this document at: http://msdn2.microsoft.com/en-us/library/h63fsef3(VS.80).aspx.

Naming Conventions:

This is covered briefly in the URL I provided for 'coding conventions'. But, I would like to put an emphasis on this one in particular. You'd be surprised at how this is easy to follow, requires very little memory of rules (there are only 9 rules!), and will save you hours upon hours of headache and confusion.

The emphasis I would give you are:

  • Begin each separate word in an element with a capital letter (example: ThisBasicElementUsesCapitals)
  • Begin interfaces with a capital i ("I") followed by a noun or adjective (example: IDataAdapter <or> ISession)
  • Use abbreviations when absolutely necessary and ONLY when the abbreviation is commonly known (example: "TV" instead of "Television", do NOT use "ASAU"…instead use the full name "AnotherSimpleAbbreviationUsed"…think about it, did you have a clue was ASAU was..even though I knew it, I know you probably didn't know it, nor ever would know it)

You can find additional guidelines and information at: http://msdn2.microsoft.com/en-us/library/0b283bse(VS.80).aspx.

Conclusion:

Coding conventions are great things that usually are under used and rarely emphasized (unless you work in an enterprise atmosphere). These can make your life and all those around you much easier today, tomorrow and many, many years from now.

As an everyday coder, I beg you to please look at both of these links. I'm including them once more below for easier convenience.

Additional Links:

MSDN Article – Visual Basic Coding Conventions: http://msdn2.microsoft.com/en-us/library/h63fsef3(VS.80).aspx

MSDN Article – Visual Basic Naming Conventions: http://msdn2.microsoft.com/en-us/library/0b283bse(VS.80).aspx

Wednesday, February 27, 2008

Blog’n Again…

Well, it's been a little over 6 months since my last entry for this blog. Life's been a challenge and required my absence from this blog (and my other blogs).

Now things have settled down. My health is stable, my career has become stable. Now, it's time to get this blog back to being stable! I hope to be able to continue along the path I was headed with this blog.

You may, or may not, know that Microsoft is in process of releasing its 2008 versions of SQL Server, Windows Server, and Visual Studio. I will remain focused on the 2005 version for the most part; however, I will try to touch upon some 2008 new features and enhancements. This blog may evolve to covering the 2008 version as they become more main stream…and as I evolve to using those versions primarily. As with any new products being released, I will go through rigorous testing and validating before I convert over.

My current objective is to write an entry for this blog about once a week; however, it could be more or less. I hope to not go any longer than two weeks between entries from here forth.

Until next time…Happy Coding!

Friday, June 1, 2007

Variables…what are they? How do I use them?

This is quite a broad area of topic; I will do my best to keep this blog concise and cover the essential basics for the beginning programmer. Intermediate programmers will most likely find this to be a refresher course, if anything at all.

I think the best thing to start with is Microsoft's definition, this is a snippet of the definition (you can read the full definition by reading the MSDN article called, "Representing Words, Numbers, and Values with Variables"):

"A variable is a letter or name that can store a value. When you create computer programs, you can use variables to store numbers, such as the height of a building, or words, such as a person's name. Simply put, you can use variables to represent any kind of information your program needs."

As you can see from the above quote, this is a rather broad description. So let's get a little further into the idea behind what a variable does. The first thing to keep in mind; is that a variable is simply just a place-holder of something else. If you are familiar with Algebra then think of a variable as what "X" is for a number in mathematics. If you're not familiar with algebra then think of a variable as a box that can adjust in size and shape as needed. The purpose behind this container (box) is to simply provide the developer a quick word (or set of letters) that can represent anything they have stored within it. A developer could create a variable that stores a number in it (similar to "x" in mathematics), or the developer can have a single letter stored in it (such as the letter "G"), or the developer can have a complex mathematic expression stored in it (such as "52*2/16+12*32/4-2+16*48). A variable could even store a list of names (such as John, Samantha, Angelina, George, James, Jane)!

Now that you know what can be stored in a variable, the next question is what do you name a variable? Well, the simple answer is anything you want. The more complicated answer is ALMOST anything you want, there are a few set of reserved words in the programming language that you cannot use as a variables name (such as "END", "FOR", "NEXT", "ADD" as some examples). So what happens if you use one of these reserved words? You will receive a compile time error. This error will not allow your program to execute in most cases, in some cases you may still compile the application. However, should you choose to ignore this error then there is a strong possibility the application will fail when this name variable is used. This is because the computer language will not know if you are intending to use the reserved keyword or if you are intending to store something inside that word.

Since you know have a grasp on what a variable is and why you would use it, you can get a better understanding of the benefits of using variables through examples. First I will discuss how to declare a variable.

Declaring a variable is where you write a statement that says you want to use a specific word (or set of characters) to represent a specific type (such as an Integer, String, Object, List, etc). An example of declaring a variable would be to write the following statement:

    Dim testVariable as String

The above variable statement is read as "testVariable" is the variable name and "String" is the variable type. I will cover some of the different variable types available to you in a later blog. Here are some more examples of declaring variables (writing variable decleration statements):

    Dim integerVaraible as Integer

    Dim longVariable as Long

    Dim listVariable as List

    Dim arrayVariable as Array

So now that you have declared your variable, the question is how do you get what you want into that variable? That is a great question! The answer just depends on what type of variable you are declaring; this is where the MSDN website will come in very handy. Some variable declarations have certain requirements to be met prior to being used, and some have limitations on what can be placed in them. First I will start off with a very simple, and commonly used, variable assignment. We will assign a string pattern (such as this blog's name) to the variable "testVariable" (which was declared previously). Here is how you would do that:

    testVariable = "Visual Basic Helper Blog"

As you can see it was quite simple to assign the string. Now I can reference this variable throughout the project by using the word "testVariable" (which will save me a lot of typing…instead of typing out "Visual Basic Helper Blog").

I mentioned just a minute ago that some variables have pre-requisites and some have limitations. Let's take a quick look at a variable that would have a limitation. The variable types of integers are limited to storing only whole numbers, which means no letters (obviously) but also no decimal points (such as 1.86). If you try to store a letter within an integer the application will produce an error stating this is an illegal action (hence the limitation to integers). Now an example of a pre-requisite with an integer is the whole number, if you try to insert a decimal value (such as 4.79) then it will automatically get rounded off to 5.

As I mentioned previously, variables are a rather large topic and I am just brushing the basics of it. If you still need further help with understanding this concept then I strongly urge for you to get any book about Visual Basic.NET (2005) that is for the beginner. It will go into more detail than I can in this blog.

Hopefully you have a general understanding, and a solid one at that, to use variables. Remember to consult the MSDN website when you want to use a variable type that you are not familiar with!

Until next time….Happy Coding!!!

James

Tuesday, April 10, 2007

Why is Garbage Collection uncontrollable?

This is partially true. The Garbage Collection is a set of classes that is a part of .NET Framework’s Common Language Runtime (CLR). The reason it is percieved as being uncontrollable is because Microsoft uses the Garbage Collection classes at unknown times. Thus, it is unpredictable. The part that is untrue of this class being uncontrollable is that the developer can call its methods at anytime and force the Garbage Collection to occur.


If you would like to read more detail of how to do this and how the Garbage Collection class works you can read a detailed summary I have prepared of the Garbage Collection class in another blog called “A brief look at Garbage Collection”. I would recommend reading the blog because the Garbage Collection class affects each developer regardless of chosen programming language.

Wednesday, April 4, 2007

How do you use the .NET Framework?

If you are unsure of what the .NET Framework is; you can read a brief discription in our blog (located at: http://codingchat.blogspot.com/2007/04/what-is-net.html).

 

Accessing the .NET Framework from within a programming language is actually a very simple task to accomplish. The reason it is so simple is that during the development of the framework Microsoft had created what is called Namespaces.

 

Namespaces are basically the logical location of a class. Namespaces are a structured system. It all starts with 3 primary namespaces: Microsoft, System, <Your Application Name>. The namespace can be increased to include any outside classes you reference into your application ( i.e. Custom classes you previously created, 3rd party classes, etc). Namespaces are then logically grouped inside 1 of the previous primary namespaces. Example is the 'Security' class is located inside the System name space; it would be accessed by importing the System.Security namespace.

 

Microsoft has listed all of the currently supported namespaces on their MSDN website. You can view it at: http://msdn2.microsoft.com/en-us/library/ms306608(VS.80).aspx. You should periodically review the Microsoft MSDN website to ensure you are correctly importing your desired namespace. Keep in mind this is for .NET 2.0. The .NET 1.0, 1.1 and 3.0 may have different namespace locations and/or arguments used to access them.

 

This brings us to the next gap filled by Microsoft that was plagued when using the API interfaces. The developer didn't have a clear, concise method to know how to call the API correctly. In other words if you didn't have all the arguments correctly referenced then you would possibly produce errors, or worse yet, possibly not even have a working application. There are three things Microsoft did to fix this problem. First, they had made their IDE provide tooltips on what the expected arguments are. Second, they had made the namespaces available for review offline and online through usage of the MSDN website and documentation. Third, and this could be the largest benefiting factor, is that Microsoft had made it so that some classes could be overloaded.

 

What is overloading a class? How do you do it? The basic principal is that you can redefine the class and its arguments; thus 'overloading' the class. You then would call the 'overloaded' class and the MSIL would interpret what you want to use and use the appropriate class method. This will be explained in better detail in a future blog.

There is one most common practiced method; the developer will call a line of coding to initiate the desired class from the framework. In most cases this is done prior to all other lines of coding. An example in Visual Basic to initiate the SQL class would be calling the "Imports" keyword prior to all other lines of coding in the class. An example would look like this:

 

            Imports System.Data.SQL

 

                Public Class Form1

 

                'Coding utilizing the class goes here

 

                End Class

 

You will notice in this example the first line of coding uses the keyword "Imports" and then attached to the syntax is the desired class. You may be asking yourself; since ODBC is also within the System.Data class, then why not just reference the System.Data class instead. Well, the reason is that the sub-classes (i.e. SQL, ODBC) are not visible to the parent class. Another way to put it is comparing the question to reading a book. How come you can't just read the first page of a book and claim you read the whole book, after all the remaining pages are under the first page. Well, it's simple really, it's because the top pages cover the pages under it. You have to specifically tell your application that you want to use the code under the parent class.

 

Most programming languages will operate in a similar instance to initiate a class from the framework; you will want to verify with your reference material the exact statements/syntax to use in your desired programming language.

 

This will conclude how to use the .NET framework; as I have stated previously it is not intended to be a complete resource of the subject. The starting point is the MSDN website (See the links in the links sidebar of this blog). There are many books and other websites that will cover this subject in much more detail and probably provide more thorough information. The objective of this blog was to introduce you to how to use the framework and give you resources to expand your knowledge. Always keep in mind there are three ways to program:

 

  1. The most logical way (logical to you, the developer).
  2. The most commonly accepted way (typically will include a 'best practice').
  3. The practical way (this is the way you can get it done, rather good or bad practices).

 

Regardless of the method of development, regardless of the knowledge you have; always keep plugging away and always keep expanding your knowledge. The more you learn will mean the better your programs will be and the faster you can develop them. Never be afraid to ask a question to someone more experienced than you and never be afraid to try things out and see what happens (do always be careful when using any commands that will alter and/or delete files!).

 

Happy programming!
James

Saturday, March 24, 2007

What is Object-Oriented Programming (OOP) and why do you need it?

Object-Oriented Programming (OOP) is a concept used for programming. It is like a different way to look at things. The basic principle of OOP is that everything is either an object, a property to the object, or a method of the object. Before we can get into why you need OOP, you need to know a few other things first.

OOP originally was designed to provide an answer to a "software development crisis" in the 1960s. The problem was as the software was beginning to become more and more complex there was no methods around to ensure the quality was maintained. Introduce Object-Oriented programming concept. The concept is that every program contains "objects" and these "objects" would have properties and/or methods. (Notice the use of "and/or"; some objects can have both, or just one or the other). Objects would also be able to 'inherit', 'polymorph', and 'encapsulate' to and from other objects.

Visual Basic was originally based on the "BASIC" language. "BASIC" is a linear language; meaning that the line of code read only moved downwards (forwards). What made Visual Basic so popular in the beginning, and set it aside from its competitors, was it had an easy method to create forms and place controls on the forms; namely the programmer would drag-and-drop the controls and provide a few lines of code to make a working program. This is great as long as the program was simple and did not require mass lines of coding. As the programmer's needs had evolved so had Visual Basic; such as the introduction of Modules, COM and many other features. (Interestingly enough, with the advancements of Visual Basic you could create a complete application without having to type one line of code. Don't expect a lot out of performance out of the application though!)

The one thing Visual Basic had lacked was the OOP concepts and abilities, because of the non-existent support of OOP, many businesses looking for enterprise solutions (as well as the developers creating them) had moved onto other languages that supported OOP concepts, regardless of the caveats of not having a simplistic drag-and-drop development environment. Most companies had determined that the ability to create code that was easier to manage, and more importantly could harness the full power of their servers with multiple CPUs, large RAM, and many other features would be worth leaving behind the ease of Rapid Application Development (RAD) that VB had offered.

Visual Basic 5 was the first 'introduction' of OOP concepts, targeted to draw in developers who had left the VB scene; however, this was hardly the worth of any enterprise solution developer's time to invest in. Visual Basic 5 had just merely scratched the surface of supporting OOP and this had still left its user base in a tough position when trying to develop an enterprise-level application. Visual Basic 6 was a better effort; however, the advancements still did not warrant an serious consideration of time that would need to be invested to switch languages, as well as the investment costs in re-training all employees (rather it be an internal developer for an enterprise or a private software consultant).

Microsoft had finally decided that they had to make a serious effort to be competitive in the enterprise software development market. Their first major step in this effort was a huge improvement; it was the introduction of .NET! The reason this was a huge improvement was because the .NET architecture is based on OOP concepts. A prime example of this is that the entire .NET architecture is a collection of classes. Classes are the foundation of OOP! (.NET will be further explored in a future blog)

You can see examples of it just from looking at a website that offers dynamic information (such as New York Times, Microsoft, Google, Yahoo, etc). Most dynamic websites use OOP principles; this benefits the web visitor, as well as the web hosting company. The visitor gets to have an interactive experience, up-to-date information, and/or instant access to information. The web hosting company gets to offer more features, require less bandwidth and CPU power, and can instantly change information with minimizing the amount of time (if any) the website is down.

Now that we know what OOP is and we also know how Microsoft had made a full dive into the OOP world, it is worth discussing why you need to know and understand OOP. The first thing I can say is that if you use Visual Basic .NET (2003 or 2005), or any other ".NET Language" (i.e. C#, J#, etc) then you are already using OOP! Another reason that you should know and use OOP is that this is the way, like it or not, the software industry is moving towards.

You will find in your endeavors that you don't need to know and understand every little thing about OOP. You will also find that the more you learn about it, the easier it will get to create your applications. Another prime reason you should learn OOP concepts is that the more you know will result in the more power your applications will be, the safer your coding will be, the easier it will be to scale your application, and most importantly the more reliable your application will be!

Please take a few minutes and read-up on the concepts of OOP and how to use them. If you are unsure of where to begin then there are two resources I would recommend. Wikipedia and Google. In both cases do a search for "Object-Oriented Programming"; if you want more in-depth information than head out to your local bookstore that carries programming reference materials and pick up a book on the subject; you will find many titles available, and you will see just how vast the subject is and quickly realize the importance to learn this.

OOP will be the cornerstone of all of your programming needs and answers.

Saturday, March 10, 2007

Get at least 1 book for referencing

I frequent message boards and find that there are so many questions posted that can be answered by simply reading a book. I write this posting not to discourage you from posting a question on a message board; or from someone answering simple questions. We all have been there at one time or another; and I'm a strong believer in there is no such thing as a stupid
question.

I suggest to each and everyone who is in the near beginning of learning a programming language to read one of the 100’s of books out there that are specific to helping the beginners. There are two main reasons this is beneficial to the beginner. The first main reason is that the book is always readily available and has a very useful index of keywords that can provide the answer with in-depth description of why that is the answer. The second reason, and this may be more prevalent than the first one, is that it will cover a huge span of topics and give insight in areas that the beginning programmer may not have ever known about.

Message boards can be great in getting the immediate answer to the new programmer; however, they typically lack a thorough explanation of how the answer was created.

An example would be a new user might ask how to make their application to confirm a request by the user to exit the application. A typical answer might be: to use a statement or method that will pose the question and return the results to the application and then to handle the returned results appropriately. While this is an acceptable answer for the new user to
continue plugging away at creating their application, it is not beneficial to the user because it doesn’t explain on how to determine the best method to pose the question; it also doesn’t delve into the best method to handle the returned results. A more in-depth answer may include providing exact coding to be used, such as:

Create a button to be clicked for exiting the application (assuming the button is labeled “Button1”; use the following code):

Private Sub CmdButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdButton1.Click

Dim
dlgExitAppResults As DialogResult

dlgExitAppResults = MessageBox.Show _
(
"Are you sure you would like to exit?, _
"Exit Application",_
MessageBoxButtons.YesNo, MessageBoxIcon.Question, _
MessageBoxDefaultButton.Button2)

If dlgExitAppResults = Windows.Forms.DialogResult.No Then
Exit Sub
Else
End
End If

End Sub

While this is a little better of an answer; it again doesn’t explain to the user how it was determined to use a dialog result and a message box. It also doesn’t explain how the application is determining what the user’s input is or what the best practice is in a situation such as exiting the application. An arguable problem with this solution would be that it doesn’t ensure the application is properly disposed and especially if the application is properly released from the computer’s memory resources. The first arguable problem would easily be discussed in the most common beginning VB books; the second arguable problem would definitely NOT be discussed on most message boards answering this question. A book would definitely brush upon the subject of releasing the application from the memory, if not going in to detail of the subject it would at the minimum ensure the reader was aware of the importance in doing this.

My best suggestion is that even with the vast amount of resources available to the new and experienced user to still pick up at minimum 1 book that covers a broad spectrum of topics in the programming language. It will typically offer better ability to help understand why certain aspects of the language are important to accomplish and typically what downfalls are related to using other aspects of the language in certain ways. The other reason I cannot stress enough is that while thumbing through the table of contents you will typically find topics you are not as strong in and possibly not even know anything about. These books will provide insight into how, when and why to use certain methods / techniques for a programming language.

What are the advantages and disadvantages of using VB.Net?

MSDN has a fairly decent comparison of VB.Net and C#. I would recommend checking out this link if you are torn between which languages to choose. http://blogs.msdn.com/csharpfaq/archive/2004/03/11/87816.aspx

Advantages

  • Option Strict – Prevents unintended type conversions. This means that you cannot accidentally assign an ‘Integer’ value to a ‘String’ variable; however, this is not always foolproof. VB.Net does allow some unintended type conversions, such as an integer value could be placed in a ‘Long’ variable.

  • Named Indexers support – Examples would be properties with parameters.

  • Support of legacy keywords – Although some keywords have either been discontinued or their usages completely changed there still remains a huge amount of support of legacy keywords; this is useful for converting legacy projects to the current language specifications. Many will say that the VB.Net conversion wizard has many pitfalls; this is true, however, it does provide a starting point in the conversion process that many other languages do not provide.

  • Handling Pointers indirectly – This provides less opportunity of instability in the produced application; aka produced applications are more secure and stable.
    Cannot handle unmanaged code – This provides a more stable and secure production of code.

  • Easy to use Rapid Application Design (RAD) interface – Within a matter of minutes a complete Graphical User Interface (GUI) can be produced; thus requiring less programming time and less design time.

  • Project wizards – When creating a new project, or just adding a new form or button, the environment will automatically generate the default coding to have the objects appear; in some cases there are wizards that can provide default coding to have some functionality within the application. This translates to a working application can be designed and coded in a fraction of time than some other languages.

  • Large Talent Pool – Since there are so many programmers that know VB you can have a fairly easy time discussing obstacles you run across in your programming and find ideas on how to bypass them; in the same token you may also find a larger number of books that cover a wide variety of topics (general and specialty) and there are an enormous number of websites that cover a wide variety of topics and other means of support.


Disadvantages
  • Cannot handle pointers directly – This can be a disadvantage because there is more required coding and thought to handle a pointer. Additional coding results in additional CPU cycles; which in turn requires additional processing time; which results in slower applications.

  • Large Talent Pool – Since VB is so easy to learn there is a significantly larger pool of competition; thus, there can be more programmers applying for the same employment or project and this can ultimately drive the market value of the programmer’s services down.

  • Intermediate Language (IL) compilation – These types of compilers can be easily decompiled (aka Reverse Engineered); there is little that can be done to deter decompiling of the application, and nearly nothing that can be done to prevent it.

  • Just-In-Time (JIT) compiler – JIT compiling is the way the computer can interpret the IL compilation. This is essential to running the application. This means the target computer will be required to have JIT and that the application can receive performance degradation because of the extra CPU cycles required to use JIT.

  • Large Libraries – Because VB is an IL there is a large number of libraries required for the JIT compiler to interpret the application. Large libraries require more hard drive space, more computing time and most of all it can be a nuisance if the application is being deployed over the internet and the user must obtain these libraries in addition to the files of the compiled application.


These are just some of the advantages and disadvantages of using VB. You will find during your course of time in the programming world there are many opinions and each will have strong cases as to why to use or not use VB. I think the MSDN web article, before mentioned, says it best in that when comparing C# with VB.Net that it is a personal preference. In particular you should keep in mind that both languages have access to the same libraries and .Net structures. It will ultimately come down to syntax choices and in some cases what resources are available to you to learn the language. In both case commit to the language and look to learn others in the future to compliment what you already know.

What is the difference between VB.Net and Visual C#.Net?

You will find that there is not all that much distinguishing differences from Visual C# and Visual Basic. These languages are known as Intermediate Languages (IL). This becomes an important factor in that this can have a limitation in what systems may run the applications that are designed with these languages. The limitation falls from the code being interpreted by the Common Language Runtime (CLR). VB.Net is also a language that uses a Just-In-Time (JIT) compiler. This means that an application that is ran for the first time may take a few extra CPU cycles to execute because it is loading for the first time; however, the benefit therein lies when the application runs the code again it will be faster in execution because the JIT compiler had already compiled the coding.

If this is all confusing then don’t worry; as you do more learning about the advantages and disadvantages of VB this will become clear. The main part to keep in the back of your mind is that using these languages will not always provide the most efficient CPU processing times; however, you will also want to keep in mind that most applications spend more time waiting on user input than on CPU cycles; so typically there is no huge advantage to using a language that uses a ‘true’ compiler.

The major difference is program language specifications and a few other minor features / options. A prime example is that Visual C# can handle pointers directly, where as VB must use an API reference to do this. This may confuse the crap out of you now while you are still learning these terms, don’t worry about not understanding. This all basically means that C# can do something better than VB; however, with every Yin is a Yang. Handling a pointer directly can cause application instability, therefore VB can be considered a safer programming language since it will not be as instable when it comes to a pointer. As mentioned before, this all comes down to a preference. You will find throughout your journey as a programmer that there will be many, many non-VB programmers who will think they are using a superior language to VB and you will find many, many VB programmers who will point out where VB handles things better than other languages.

If you talk to an experienced programmer who has used VB and C# on a regular basis for many years, then you are likely to hear that the programming languages are nearly identical, except for syntax usage. To further confirm this you will find software applications available that can readily convert coding from VB to C#, or vice-versa. Now these conversions may not be accurate; but you will find there is very little error in them. The other thing that will be apparent to you, is once you learn VB you will find that if you view coding from C# you will understand quite a great deal of it; you may not be able to convert line for line, but you will definitely be able to look at a block of coding and determine what it is attempting to do and the method in which it is doing it.

Why choose VB.Net as your programming language

Quite simply put....choose it because it fits your personal preference. In order to answer this question there are a few things that must be understood.

There are a multitude of programming languages to choose from. It is important to understand the advantages, as well as the disadvantages of your chosen programming language. In most of my postings I will refer to designing applications; it is very important to understand that there are many different definitions in the programming world for the word “application”. In my references I will default to the definition of a software program that is intended for either productivity or informational purposes. This is very important to understand that these references are not aimed at designing games. Game programming has a whole different set of rules, methods and terminology.

You will find when talking with experienced programmers, most will have an opinion on why their chosen language is the ‘best’ language to use. From my past experiences I have found that most programming languages have its strong points for specific types of software programs. The one constant thing I have found is that just about all of the programming languages can be used to make at least 85% of the applications you will design (read the above paragraph for my definition / use of ‘applications’). I can say this with the utmost confidence because 85% of the software applications released do not require a complex set of graphics coding. You will find that Visual Basic.Net, Visual C#, C++, Delphi, and many other languages can accomplish the same ending results. The real differences in these languages are in specific features, methods of accomplishment, ease of Rapid Application Design (RAD), and coding language specifications.

You will also find that game programming has a much more distinct choice of programming language. Game programming will require a thorough understanding of the advantages vs. disadvantages of each possible language. This isn’t to say that using a program such as VB.Net isn’t suitable for creating the next top-end game; I am simply stating that you will find many more disadvantages to using a language such as VB over C++ for this type of programming.

There are no easy ways in determining what the best language is to learn; I suggest getting proficient in one at first and then slowly add on other languages that compliment your primary language. I cannot stress enough that you will find each language to have its advantages and disadvantages. I will provide a posting that will discuss these advantages / disadvantages for VB.

The major thing to keep in mind when choosing a language is your personal preference and what you feel will best suit your wanted results, rather it be to learn a language that has a smaller talent-pool to increase your market value as an employee, or you simple want to choose the language that has a huge support system (meaning many experienced programmers to talk to, many self-teaching books, etc) or you just want to choose a language that you feel is simpler to learn.

I would encourage learning VB as your first language because it is a verbose language. Once you have the basic understanding of the VB language you will find that you can read the language as though it were written as a book.

Friday, March 9, 2007

Welcome to Visual Basic Helper Blog

This blog is intended to focus on helping the beginning Visual Basic programmer. This blog will cover topics such as what a keyword is, how to use a keyword, how to declare a variable, etc. This blog will not cover topics in-depth that are beyond the capability of a beginning / novice Visual Basic programmer. This blog will not cover topics that are unrelated to VB.

If you are looking to read a blog that covers additional topics and languages please read my Program / Coding Chat blog (http://codingchat.blogspot.com).

If you are looking to read a blog that will help you to learn how to program in the C# (pronounced C-Sharp) language, please read my C# Helper blog (http://csharphelper.blogspot.com).

Thank you,
James