cybertech

Tuesday, 25 March 2014

In depth VB.NET guide

The Basics of Visual Basic .NET (VB.NET)
  • Table of Contents
    • Introduction to VB.NET
    • Getting to know your way around the IDE
    • Handling Errors in VB.NET
    • Basic Syntax
    • Various Statements
Visual Basic .NET (VB.NET), is an object-oriented computer programming language that can be viewed as an evolution of the classic Visual Basic (VB), which is implemented on the .NET Framework. Microsoft currently supplies two major implementations of Visual Basic: Microsoft Visual Studio 2010, which is commercial software and Visual Basic Express Edition 2010, which is free of charge.



System Requirements

Software Requirements
  • Visual Studio 2010 can be installed on the following operating systems:
    • Windows XP (x86) with Service Pack 3 - all editions except Starter Edition
    • Windows Vista (x86 & x64) with Service Pack 2 - all editions except Starter Edition
    • Windows 7 (x86 & x64)
    • Windows Server 2003 (x86 & x64) with Service Pack 2
    • Windows Server 2003 R2 (x86 & x64)
    • Windows Server 2008 (x86 & x64) with Service Pack 2
    • Windows Server 2008 R2 (x64)

Hardware Requirements

  • Computer that has a 1.6GHz or faster processor
  • 1 GB (32 Bit) or 2 GB (64 Bit) RAM (Add 512 MB if running in a virtual machine)
  • 3GB of available hard disk space
  • DirectX 9 capable video card running at 1024 x 768 or higher-resolution display
  • DVD-ROM Drive



Downloading an IDE

The first thing we're going to need to do is download an IDE (Integrated Development Environment) for Visual Basic.

There are not that many that I could find except for the one that ICSharpCode has developed and the one that Microsoft provides (recommended).


Namespaces and Classes

Let's think of all these things like a toolbox. Inside this tool box you have all your various tools to fix your problems, in this case, to make your application accomplish what you need it too.

Take a look at this diagram:


[Image: namespacesandclasses.png]

As you can see the namespace is the actual toolbox, which holds your various classes, subs, and functions. (I know everyone is jelly of my mad paint skillz, I offer lessons, of course. ;3)

Namespaces are the actual container, which offers nothing but organization for everything else. While your classes, subs and functions are your actual 'tools' to 'fix' your 'problems'.

Here is an example of a namespace:

Code:
Namespace YourNamespace

End Namespace

That is how you declare a namespace. Pretty simple.

Now we'll get down to the classes. Here is how you declare a class within your namespace:

Code:
Namespace YourNamespace

  <Public/Private Keyword> Class YourClass

  End Class

End Namespace

A class is somewhat like a...mini-namespace I guess you could say, except some classes actually have a purpose and can be used to call other various items.

When you declare a class, unlike a namespace, you will notice in the IDE how it changes to a specific color:

[Image: pcpsXDwBlLbEhfBDGqGD_zps64404d2f.png]

That just makes it easier on the developer to quickly find classes. You can also change the colors of various items by viewing the end of this article where miscellaneous items are classified.

There are 2 different keywords you can use while declaring a class, one is "Public" and the other is "Private". The "Public" keyword allows your class(es) to be called anywhere in your project. There are no limits to where they can be called if it is declared as public. On the other hand, the "Private" keyword makes elements only accessible from within their declaration context. So, if I declare a class in the namespace "YourNamespace" -- I cannot call it from "YourOtherNamespace" if it is declared Private -- but if it is declared Public, I could.




Subs and Functions


Now lets take the previous diagram we used and add in the subs and functions:

[Image: namespacediagramvbnet.png]

You may notice how some of the boxes are bigger than the others, that is because, obviously, some subs and functions are larger than the others (code wise).

Now, you might be asking yourself, "What is the difference between subs and functions?", if you're not, then you just did. ;3

The main difference is Functions, while they don't necessarily have to, usually return a value. Subs are just for carrying out different tasks and they do not, and cannot, return a value.

This is how you declare a Function:

Code:
Namespace YourNamespace

  <Public/Private Keyword> Class YourClass
    <Public/Private Keyword> Function TheFuntionsName(<ByVal/ByRef> SomeArgumentName As <Object/Variable Type>)
  'Do Something
  Return "SomeThing"
    End Function
  End Class

End Namespace

You might've noticed something new in their that we have not gone over yet, that would be the ByVal and ByRef keyword. These keywords are specifically used for declaring arguments in Subs and Functions. The different between the 2 is that ByVal will not allow you to change the value of the argument within the body of the Function while ByRef will.


Getting to know your way around the IDE

The IDE for VB is very big, and if you're just opening it up it might seem like an impossible task to know how to work this giant machine; but let me reassure you that it is not as difficult as it seems.

Go ahead and create a new Windows Form Application and notice how the IDE changes:


Without a project opened 


With a project opened 

[Image: FrqyBWQyMwLWobTHARrb_zpsa6644075.png]

Let's take a look at the most notable changes; these will also be the things you use the most:
Big picture
[Image: changeswhenprojectopened.png]

The toolbox has been populated with all the various components and controls that you can add to your project, the "Properties" box has become visible (pay attention how it changes depending on what you click on, component wise.) and the solution explorer has also become visible.

The Toolbox

The toolbox is what holds all your various components for WFA's (Windows Form Applications). They are all catagorized based on certain things, take a look at this picture:
[Image: lePdXqPstjCnipYApwoH_zps6745f830.png]
  • All Windows Forms
    • This is as straight up as it gets, everything in all the other sub-sections is in this one massive section.
  • Common Controls
    • The things that people use the most have been put under this section. Some things include the: TextBox, RichTextBox, Button, CheckBox, RadioButton, and Label. This is usually the only thing that I keep "opened". Everything else just clutters my space, in my opinion.
  • Reporting
    • Personally, I have never used anything under this section. Then again, I downloaded VB to make l33t ub3r h3ck3r shit so that could be why. Under this category there is only one thing; ReportViewer. Like I said I've never used it before so I myself cannot give any insights to what it might be helpful for.
  • Containers
    • FlowLayoutPanel
      • This control will give you a display like your desktop, literally.
    • GroupBox
      • The GroupBox serves no purpose really except to provide some organization of a mass of various controls. It definitely makes your UI look better if you have a fuck ton of CheckBox's everywhere to just add one of these and place them all in there.
    • Panel
      • The Panel control is somewhat like the GroupBox, except the GroupBox offers the ability to add a caption to the top of it.
    • SplitContainer
      • The SplitContainer is basically 2 Panels but together and separated in the center. You can then use the separator in the center to re-size the control either to the Right or Left by default.
    • TabControl
      • This offers something to where you can add tabs and then organize your controls on the various TabPages that you add to the TabControl. Very helpful for Document editors or large projects.
    • TableLayoutPanel
      • This is the only control that I have not used under this section. Read more about it here.
  • Menus & Toolbars
    • ContextMenuStrip
      • The ContextMenuStrip is something that you can set for specific controls or a mass of controls and it will act as the "Right Click Menu". In other words, when you "Right Click" on the control you set the ContextMenuStrip for it will pop up with all the options that you added to it.
    • MenuStrip
      • The MenuStrip is just like the ContextMenuStrip except the MenuStrip will be docked at the top of your application, and can have multiple "Menus" within this one control.
    • StatusStrip
      • The StatusStrip is docked at the bottom of your application, and only certain controls can be added to it. These include: A mini-progress bar, Label(s), A DropDownMenu (DropDownButton), and a SplitButton.
    • ToolStrip
      • A ToolStrip is somewhat like a MenuStrip except it also supports buttons that can have images as backgrounds instead of text.
    • ToolStripContainer
      • A ToolStripContainer is exactly what is sounds like; a container for ToolStrips.
  • Data
    • Read more about everything under the Data section here.
  • Components
    • Read more about everything under the Components section here.
  • Dialogs
    • ColorDialog
      • The color dialog is a dialog that will be shown when calling ShowDialog and will return the color that the user selected.
    • FolderBrowserDialog
      • The FolderBrowserDialog is a dialog that will be shown when calling ShowDialog, like any other Dialog, and will return a number that corresponds to the Directory they selected. You can then use Environment.GetFolderPath(.SelectedPath) and it will return the absolute address of the Folder the user selected.
    • FontDialog
      • The FontDialog is a dialog, and like every other dialog can be called by using ShowDialog and will return a font that the user selected. You could use this dialog to change the font of a TextBox, for example.
    • OpenFileDialog
      • The OpenFileDialog can be called, like every other dialog, by using ShowDialog. This will return the path of a file that the user selected and you can then use the IO.File.ReadAllText function to get the Text of that file or ReadAllBytes if it is an assembly.
    • SaveFileDialog
      • This will create a new file in the path that the user selected and you can then proceed to use WriteAllText to write text to that file or WriteAllBytes to write bytes to create an assembly.

The Solution Explorer

The Solution Explorer is like a built in Windows Explorer specifically for your project.

There are several different buttons on the solution explorer, let's go over them.
  • The "Home" button. [Image: KdFPcNScATXgRGZPXiUi_zps6e9a841e.png]
    • The "Home" button will take you back to where you were as soon as the Solution Explorer was opened.
  • "Collapse All". [Image: evYhitRipDRWsXyPJCnT_zpsb0e87c7f.png]
    • Collapse all will take everything like this: [Image: ewEZOsotLNmatiiYhGWR_zps05d19ad9.png]
    • And turn it into this: [Image: JlnGsNOWoUWsMnahRpmE_zps8fb1e47e.png]
  • "Properties" (Shortcut: ALT + ENTER) [Image: SytWPStduQMbUgJlfUfc_zps509c7f57.png]
    • This button will jump to the "Properties Box" for the selected component/control.
  • "Show All Files" [Image: jqscFjvmQBsIOWPawxPt_zps4b89bce6.png]
    • This button toggles whether or not to show files that are not part of your project but are in the directory of your project.

The Properties "Box"

The reason "Box" is in quotes is because I couldn't think of something more accurate to call it, lol. Rolleyes

This is what it looks like:
Properties box (Click to View)

This shows you most of the settings applicable to the control/component that you're focused on. Some things are not changeable via the properties box and you must manually set them. I cannot give you any insights to what these are because they vary so heavily based on components/controls.


Handling Errors in VB.NET
Errors are easy to get and sometimes tedious to fix

Errors; they piss you off, they piss ME off. You're eventually going to get that error that you think is going to be impossible to fix. Let me tell you this: You're wrong. VB.NET has a statement called the Try...Catch...Finally statement that is made specifically for error handling. I've devoted this post specifically for Error Handling instead of adding this to the Statements section because I feel as if this is one of the most important statements that you should learn to use.

Let's go over it


Try...Catch...Finally
"Provides a way to handle some or all possible errors that may occur in a given block of code, while still running code."
This is how one of these statements would look:
Try
[ tryStatements ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ] ]
[ Exit Try ]
...
[ Finally
[ finallyStatements ] ]
End Try


The break down
(Courtesy of MSDN)
  • tryStatements
    • This is optional but it's pointless if you do not include these. This is the code where you think an error will occur. There can be multiple statements within for checking.
  • Catch
    • Optional. Multiple Catch blocks permitted. If an exception occurs while processing the Try block, each Catch statement is examined in textual order to determine if it handles the exception. Exception represents the exception that has been thrown.
  • exception
    • Optional. Any variable name. The initial value of exception is the value of the thrown error. Used with Catch to specify the error caught.
  • type
    • Optional. Specifies the type of class filter. If the value of exception is of the type specified by type or of a derived type, the identifier becomes bound to the exception object.
  • When
    • Optional. A Catch statement with a When clause will only catch exceptions when expression evaluates to True. A When clause is only applied after checking the type of the exception, and expression may refer to the identifier representing the exception.
  • expression
    • Optional. Must be implicitly convertible to Boolean. Any expression that describes a generic filter. Typically used to filter by error number. Used with When keyword to specify circumstances under which the error is caught.
  • catchStatements
    • Optional. Statement(s) to handle errors occurring in the associated Try block. Can be a compound statement.
  • ExitTry
    • Optional. Keyword that breaks out of the Try...Catch...Finally structure. Execution resumes with the Finally block if present, otherwise with the code immediately following the End Try statement. Not allowed in Finally blocks.
  • Finally
    • Optional. A Finally block is always executed when execution leaves any part of the Try statement.
  • finallyStatements
    • Optional. Statement(s) that are executed after all other error processing has occurred.
  • End Try
    • Terminates the Try...Catch...Finally structure.


Variables
String, Integers, Booleans and More

Next, we're going to work on all the syntax in VB.NET, building up to creating your first application.

Visual Basic's syntax is created to be more...logical I guess you could say. It could probably be read by anyone with common sense.

Now let's take a look at what we'll use the most...

Variables can be a variety of things. Mainly they're going to be strings, integers, booleans, and declaring objects. (Like WebClients (System.Net namespace) and other things)

Declaring Variables

The following image will show you how to declare variables:


[Image: 7nREJer.gif]

Why there are more data types of variables you can declare for things that suite your need, these are the most common ones and will be the most used. Here is a list of all the different data types:

Data Types 
Boolean - True of False Values

Byte - 8 bit unsigned integer

Char - 16 bit Unicode character

DateTime - Date and time of the current day.

Decimal - Decimal number

Double - 64 bit floating-point number

Int16 - 16 bit signed integer

Int32 - 32 bit signed integer

Int64 - 64 bit signed integer

SByte - 8 bit signed integer

Single - 32 bit floating-point number

UInt16 - 16 bit unsigned integer

UInt32 - 32 bit unsigned integer

UInt64 - 64-bit unsigned integer

using one of these data types:
Dim <LocalName> As [New] <DataType/Object>

Example:
Dim Abc123 As String = "This is an example string. ;)"

Example with the 'New' keyword:
Dim wC As New System.Net.WebClient()

Declaring Variable Arrays

Arrays use indices to stored multiple data types, and let you use a number to tell them apart because they will use the same name. It is basically like declaring, for instance, 5 strings in one. This is how you declare an array for a string:

Code:
Dim str As String() ' notice the () at the end. That is how you know if it is an array.

str = {"One string", "Two strings", "Etc."} ' These strings are enclosed in brackets and separated by commas.

'This is how you call "One string":
MsgBox(str(0)) ' would output in a message box: "One string"

'this is how you call "Two strings":
MsgBox(str(1)) ' would output in a message box: "Two strings"

'This is how you call "Etc.":
MsgBox(str(2)) ' would output in a message box: "Etc."

See how that works? Take a look at this GIF if you're having some trouble...


[Image: M8Nhy5c.gif]



Declaring Objects

Objects can be a wide range of things. In this example we're going to be using a WebClient. A WebClient "provides common methods for sending data to and receiving data from a resource identified by a
URI." - MSDN

While a WebClient has to be declared like this:
Dim wc As New WebClient()

Some things like the XMLReader and XMLWriter in the System.Xml namespace have to be declared like this:
Dim xml As XMLWriter = XMLWriter.Create(Arguments+)
or
Using xml As XMLWriter = XMLWriter.Create(Arguments+)
You can see all the arguments that something requires by going to MSDN.
Using Google Dorks will limit the results, example: some function site:msdn.microsoft.com

Anyways, continuing with the WebClient example.
Once you have declared your WebClient():

Code:
Namespace YourNamespace

  <Public/Private Keyword> Class YourClass
    Dim wc As New WebClient() 'now it is declared
  End Class

End Namespace

Let's go over some of the various and most commonly used functions for a WebClient()

DownloadFile(Uri, String) -- Downloads a file from a Uri and saves it to the file path aka the second argument.
DownloadString(Uri) -- Downloads a string from a Uri and then returns that string.

Now to call these functions we would use the name of the Object we created that is the WebClient, in this case, wc and then add the function we want after that; i.e.:
wc.DownloadFile("http://www.somesite.com/file.exe", "C:\Users\Shit\Fuck\File.exe")

For the other one, since it returns a value, we would have to declare a string in order to "capture" that value. Like so:
Dim str As String = wc.DownloadString("http://www.somesite.com/file.txt")

Now the String that we declared will be the contents of the Text File that we downloaded.


Statements

If...Then...Else - Do { While | Until } - For Each...Next - For...Next
If...Then...Else
"Conditionally executes a group of statements, depending on the value of an expression."

Now let us say that you have more than one variable (Which 99.99 % of the time, you are going to), and you want to see what that variable is equal to or maybe compare it to another variable. This would be accomplished by using an If statement. First let's declare our variables...


Code:
Dim str As String = "123"
Dim anotherStr As String = "1234"

Next let's have a brief overview of the If statement.

This is how it will look (without all the brackets):

Code:
If condition [ Then ]
   [ statements  ]
[ ElseIf elseifcondition [ Then ]
   [ elseifstatements ] ]
[ Else
   [ elsestatements ] ]
End If

As you can tell the If statement contains 2 other things within it. These are Else and ElseIf, then of course you have the End If which ends the If statement.

This is how you would compare the 2 previous variables that we declared:

Code:
If str = anotherStr Then
MsgBox("Holy shit! They're the same!")
Else
Application.Exit()
End If

In this case since str = 123 and anoterStr = 1234 it would not pop up the MsgBox, it would close the application because the strings are not the same.

Now, in this case, we really only need Else, but say that you wanted to see if str = "abc" and if it did it would execute something instead of Application.Exit()...that is when ElseIf comes into play. This is how we could to that:

Code:
If str = anotherStr Then
MsgBox("Holy shit! They're the same!")
ElseIf str = "abc" Then
MsgBox("OMFG str = abc.")
Else
Application.Exit()
End If

here is the thing when using If statements though. If the initial check is true it will not check the ElseIf or execute the Else.




Do { While | Until }...
"Repeats a block of statements while a Boolean condition is True or until the condition becomes True."

This is how one of these statements would look:
Do { While | Until } condition
[ statements ]
[ Exit Do ]
[ statements ]
Loop


-or-

Do
[ statements ]
[ Exit Do ]
[ statements ]
Loop { While | Until } condition


The break down

  • While
    • This is required unless you use Until. While will repeat the Loop until the condition that you supplied becomes False.
  • Until
    • This is required unless you use While. Until will repeat the Loop until the condition that you supplied becomes True.
  • condition
    • This is an optional Boolean variable that will be used to evaluate the expression for True or False.
  • statements
    • This is also optional and would be one or more statements that would repeat while or until the condition becomes True or False.

Optional Remarks for the Do { Until | While } statement
Courtesy or MSDN.
The Exit Do statement transfers control immediately to the statement following the Loop statement. Any number of Exit Do statements can be placed anywhere in the Do loop. Exit Do is often used after evaluating some condition, for example with If...Then...Else.



For Each...Next
"Repeats a group of statements for each element in a collection."

This is how one of these statements would look:
For Each element [ As datatype ] In group
[ statements ]
[ Exit For ]
[ statements ]
Next [ element ]


The break down
  • element
    • Any type of variable that is used to iterate, or, loop through the elements of the collection that you supplied. Please note: the datatype of element must be an element that the data type of the elements in the group that you supplied can be converted too. Basically you cannot use a String for something that returns an Integer.
  • datatype
    • Required if element is not declared. If element is declared you cannot re-declare it using the As clause.
  • group
    • This is required and should be an Object variable that must refer to an object collection or an array.
  • statements
    • You can optionally add in various statements that will be executed while the loop is in progress. This will be executed for each element in the group.

Optional remarks for For Each...Next
Courtesy of MSDN
If element has not been declared outside this loop, you can declare it within the For Each statement. In this case, the scope of element is the body of the loop. However, you cannot declare element both outside and inside the loop.

The For Each...Next loop is entered if there is at least one element in group. Once the loop has been entered, the statements are executed for the first element in group; if there are more element(s) in group, the statements in the loop continue to execute for each element (That's why this os called a For Each loop.). When there are no more element(s), the loop is terminated and execution continues with the statement following the Next statement.

Any number of Exit For statements may be placed anywhere in the loop as an alternative way to exit. Exit For is often used after evaluating some condition, for example with an If...Then...Else statement, and transfers control to the statement immediately following Next.

You can nest For Each...Next loops by placing one loop within another. Each loop must have a unique element variable.



For...Next
"Repeats a group of statements a specified number of times."

This is how one of these statements would look:
For counter [ As datatype ] = start To end [ Step step ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ counter ]


The break down
  • counter
    • This expression is required. The counter variable has to be a numeric datatype that supports the greater-than or equal to (>=), less-than or equal to (<=), and the addition (+) operators.
  • datatype
    • This is required if counter is not already declared. This expression is the datatype of counter. (Ex: Integer) If datatype is already declared then you cannot use the As clause to re-declare it.
  • start
    • This expression is required and is the initial value of counter. The start expression is usually an Integer but can be any data type as long as it widens to the type of counter.
  • end
    • This expression is required and is the final value of counter. The end expression is usually an Integer but can be any data type as long as it widens to the type of counter.
  • step
    • This expression is optional. step would be the value to increase the counter by each time it passes through the loop. The step expression is usually an Integer but can be any data type as long as it widens to the type of counter. If step's value is not declared; the default is one (1).
  • statements
    • You can optionally add in various statements that will be executed while the loop is in progress. These statements will be executed a specific number of times.

Optional remarks for the For...Next statement
Courtesy of MSDN
If counter has not been declared outside this loop, you can declare it within the For statement. In this case, the scope of counter is the body of the loop. However, you cannot declare counter both outside and inside the loop.

The step argument can be either positive or negative. The value of the step argument determines loop processing as follows:
  • Step value
    • Positive (1 and up) or Zero (0)
      • Loop executes if counter <= end.
    • Negative (0 and down)
      • Loop executes if counter >= end
CREDITS:-  SomeWhiteGuy (hackforums) !!

No comments:

Post a Comment