Your Ad Here

Friday, August 14, 2009

Exception Handling in .Net

Exceptions are runtime errors that occur when a program is running and causes the program to abort without execution.
Such kind of situations can be handled using Exception Handling.
By placing specific lines of code in the application we can handle most of the errors that we may encounter and we can enable the application to continue running.
VB .NET supports two ways to handle exceptions,
Unstructured exception Handling using the on error goto statement and
Structured exception handling using Try....Catch.....Finally
Let's look at the new kind of exception handling introduced in VB .NET which is the Structured Exception Handling. VB .NET uses Try....Catch....Finally block type exception handling.
The syntax looks like this:
Module Module1
Sub Main()
Try
--
Catch e as Exception
--
Finally
End Try
End Sub
End Module

Example
Imports System.Console
Module Module1
Sub Main()
Dim a = 0, b = 1, c As Integer
Try
c = b / a'the above line throws an exception
WriteLine("C is " & c)
Catch e As Exception
WriteLine(e)'catching the exception
End Try
End Sub
End Module
The output of the above code displays a message stating the exception. The reason for the exception is because any number divided by zero is infinity.
When working with Structured exception handling you can have multiple Catch blocks to handle different types of exceptions differently. The code in the Finally block is optional. If there is a Finally block in the code then that code is executed last.

Arrays in .Net

Arrays are programming constructs that store data and allow us to access them by numeric index or subscript.
Arrays helps us create shorter and simpler code in many situations.
Arrays in Visual Basic .NET inherit from the Array class in the System namespace.
All arrays in VB as zero based, meaning, the index of the first element is zero and they are numbered sequentially.
You must specify the number of array elements by indicating the upper bound of the array.
The upper bound is the numder that specifies the index of the last element of the array.
Arrays are declared using Dim, ReDim, Static, Private, Public and Protected keywords.
An array can have one dimension (liinear arrays) or more than one (multidimensional arrays). The dimensionality of an array refers to the number of subscripts used to identify an individual element.
In Visual Basic we can specify up to 32 dimensions.
Arrays do not have fixed size in Visual Basic.
The following code demonstrates arrays.
Imports System.Console
Module Module1
Sub Main()
Dim sport(5) As String'declaring an array
sport(0) = "Soccer"
sport(1) = "Cricket"
sport(2) = "Rugby"
sport(3) = "Aussie Rules"
sport(4) = "BasketBall"
sport(5) = "Hockey" 'storing values in the array
WriteLine("Name of the Sport in the third location" & " " & sport(2))'displaying value from array
End Sub
End Module
Understanding the Code
The above code declared a sport array of type string like this: Dim sport(5) as String. This sport array has 6 elements starting from sport(0) to sport(5). The first element of an array is always referred by zero index.
You can also declare an array without specifying the number of elements on one line, you must provide values for each element when initializing the array.
The following lines demonstrate that:
Dim Test() as Integer'declaring a Test array
Test=New Integer(){1,3,5,7,9,}
Reinitializing Arrays
We can change the size of an array after creating them. The ReDim statement assigns a completely new array object to the specified array variable. You use ReDim statement to change the number of elements in an array.
The following lines of code demonstrate that.
This code reinitializes the Test array declared above.
Dim Test(10) as Integer
ReDim Test(25) as Integer'Reinitializing the array
When using the Redim statement all the data contained in the array is lost.
If you want to preserve existing data when reinitializing an array then you should use the Preserve keyword which looks like this:
Dim Test() as Integer={1,3,5}'declares an array an initializes it with three membersReDim Preserve Test(25)'resizes the array and retains the the data in elements 0 to 2
Multidimensional Arrays
All arrays which were mentioned above are one dimensional or linear arrays. There are two kinds of multidimensional arrays supported by the .NET framework: Rectangular arrays and Jagged arrays.
Rectangular arrays
Rectangular arrays are arrays in which each member of each dimension is extended in each other dimension by the same length. We declare a rectangular array by specifying additional dimensions at declaration. The following lines of code demonstrate the declaration of a multidimensional array.
Dim rectArray(4, 2) As Integer'declares an array of 5 by 3 members which is a 15 member arrayDim rectArray(,) As Integer = {{1, 2, 3}, {12, 13, 14}, {11, 10, 9}}'setting initial values
Jagged Arrays
Another type of multidimensional array, Jagged Array, is an array of arrays in which the length of each array can differ. Example where this array can be used is to create a table in which the number of columns differ in each row. Say, if row1 has 3 columns, row2 has 3 columns then row3 can have 4 columns, row4 can have 5 columns and so on. The following code demonstrates jagged arrays.
Dim colors(2)() as String'declaring an array of 3 arrays
colors(0)=New String(){"Red","blue","Green"}initializing the first array to 3 members and setting values
colors(1)=New String(){"Yellow","Purple","Green","Violet"}initializing the second array to 4 members and setting values
colors(2)=New String(){"Red","Black","White","Grey","Aqua"}
initializing the third array to 5 members and setting values

Operators in .Net

Visual Basic comes with many built-in operators that allow us to manipulate data.
An operator performs a function on one or more operands.
For example, we add two variables with the "+" addition operator and store the result in a third variable with the "=" assignment operator like this: int x + int y = int z. The two variables (x ,y) are called operands.
There are different types of operators in Visual Basic and they are described below in the order of their precedence.
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations that involve calculation of numeric values. The table below summarizes them:
Operator Use
^ Exponentiation
- Negation (used to reverse the sign of the given value, exp -intValue)
* Multiplication
/ Division
\ Integer Division
Mod Modulus Arithmetic
+ Addition
- Subtraction
Concatenation Operators
Concatenation operators join multiple strings into a single string.
There are two concatenation operators, + and & as summarized below:
Operator Use
+ String Concatenation
& String Concatenation
Comparison Operators
A comparison operator compares operands and returns a logical value based on whether the comparison is true or not.
The table below summarizes them:
Operator Use
= Equality
<> Inequality
<> Greater than
>= Greater than or equal to
<= Less than or equal to Logical / Bitwise Operators
The logical operators compare Boolean expressions and return a Boolean result. In short, logical operators are expressions which return a true or false result over a conditional expression.
The table below summarizes them:
Operator Use
Not Negation
And Conjunction
And AlsoConjunction
Or Disjunction
OrElse Disjunction
Xor Disjunction

Loops in .Net

For Loop
The For loop is the most popular loop. For loops enable us to execute a series of expressions multiple numbers of times.
The For loop in VB .NET needs a loop index which counts the number of loop iterations as the loop executes.
The syntax for the For loop looks like this:
For index=start to end[Step step]
[statements]
[Exit For]
[statements]
Next[index]
The index variable is set to start automatically when the loop starts. Each time in the loop, index is incremented by step and when index equals end, the loop ends.
Example on For loop
Module Module1
Sub Main()
Dim d As Integer
For d = 0 To 2
System.Console.WriteLine("In the For Loop")
Next d
End Sub
End Module

While loop
While loop keeps executing until the condition against which it tests remain true.
The syntax of while loop looks like this:
While condition[statements]End While
Example on While loop
Module Module1
Sub Main()
Dim d, e As Integer
d = 0
e = 6
While e > 4
e -= 1
d += 1
End While
System.Console.WriteLine("The Loop ran " & e & "times")
End Sub
End Module


Do Loop
The Do loop can be used to execute a fixed block of statements indefinite number of times. The Do loop keeps executing it's statements while or until the condition is true.

Two keywords, while and until can be used with the do loop. The Do loop also supports an Exit Do statement which makes the loop to exit at any moment.

The syntax of Do loop looks like this:
Do[{while Until} condition]

[statements]

[Exit Do]

[statements]

Loop


Example on Do loop
Module Module1

Sub Main()

Dim str As String

Do Until str = "Cool"

System.Console.WriteLine("What to do?")

str = System.Console.ReadLine()

Loop

End Sub

End Module

Conditional Statements in .Net

If....Else statement
If conditional expression is one of the most useful control structures which allows us to execute a expression if a condition is true and execute a different expression if it is False.
The syntax looks like this:
If condition Then
[statements]
Else If condition Then
[statements]
Else
[statements]
End If

Understanding the Syntax
If the condition is true, the statements following the Then keyword will be executed, else, the statements following the ElseIf will be checked and if true, will be executed, else, the statements in the else part will be executed.

Example
Imports System.Console
Module Module1
Sub Main()
Dim i As Integer
WriteLine("Enter an integer, 1 or 2 or 3")
i = Val(ReadLine())'ReadLine() method is used to read from console
If i = 1 Then
WriteLine("One")
ElseIf i = 2 Then
WriteLine("Two")
ElseIf i = 3 Then
WriteLine("Three")
Else
WriteLine("Number not 1,2,3")
End If
End Sub
End Module

Select....Case Statement
The Select Case statement executes one of several groups of statements depending on the value of an expression. If your code has the capability to handle different values of a particular variable then you can use a Select Case statement.
You use Select Case to test an expression, determine which of the given cases it matches and execute the code in that matched case.
The syntax of the Select Case statement looks like this:
Select Case testexpression
[Case expressionlist-n
[statements-n]] . . .
[Case Else elsestatements]
End Select
Example
Imports System.Console
Module Module1
Sub Main()
Dim keyIn As Integer
WriteLine("Enter a number between 1 and 4")
keyIn = Val(ReadLine())
Select Case keyIn
Case 1WriteLine("You entered 1")
Case 2WriteLine("You entered 2")
Case 3WriteLine("You entered 3")
Case 4WriteLine("You entered 4")
End Select
End Sub
End Module

Minimum System Requirements to Install and Use Visual Studio .NET

The minimum requirements are:
RAM: 256 MB (Recommended)
Processor: Pentium II 450 MHz
Operating System: Windows 2000 or Windows XP
Hard Disk Space: 3.5 GB (Includes 500 MB free space on disk)

.Net Framework

.NET is a "Software Platform". It is a language-neutral environment for developing rich .NET experiences and building applications that can easily and securely operate within it.
When developed applications are deployed, those applications will target .NET and will execute wherever .NET is implemented instead of targeting a particular Hardware/OS combination.
The components that make up the .NET platform are collectively called the .NET Framework.

The .NET Framework is a managed, type-safe environment for developing and executing applications. The .NET Framework manages all aspects of program execution, like, allocation of memory for the storage of data and instructions, granting and denying permissions to the application, managing execution of the application and reallocation of memory for resources that are not needed.

The .NET Framework is designed for cross-language compatibility. Cross-language compatibility means, an application written in Visual Basic .NET may reference a DLL file written in C# (C-Sharp). A Visual Basic .NET class might be derived from a C# class or vice versa.

The .NET Framework consists of two main components:
Common Language Runtime (CLR)
Class Libraries
Common Language Runtime (CLR)
The CLR is described as the "execution engine" of .NET. It provides the environment within which the programs run. It's this CLR that manages the execution of programs and provides core services, such as code compilation, memory allocation, thread management, and garbage collection. Through the Common Type System (CTS), it enforces strict type safety, and it ensures that the code is executed in a safe environment by enforcing code access security. The software version of .NET is actually the CLR version.
Working of the CLR
When the .NET program is compiled, the output of the compiler is not an executable file but a file that contains a special type of code called the Microsoft Intermediate Language (MSIL), which is a low-level set of instructions understood by the common language run time. This MSIL defines a set of portable instructions that are independent of any specific CPU. It's the job of the CLR to translate this Intermediate code into a executable code when the program is executed making the program to run in any environment for which the CLR is implemented. And that's how the .NET Framework achieves Portability. This MSIL is turned into executable code using a JIT (Just In Time) complier. The process goes like this, when .NET programs are executed, the CLR activates the JIT complier. The JIT complier converts MSIL into native code on a demand basis as each part of the program is needed. Thus the program executes as a native code even though it is compiled into MSIL making the program to run as fast as it would if it is compiled to native code but achieves the portability benefits of MSIL.
Class Libraries
Class library is the second major entity of the .NET Framework which is designed to integrate with the common language runtime. This library gives the program access to runtime environment.
The class library consists of lots of prewritten code that all the applications created in VB .NET and visualstudio.NET will use. The code for all the elements like forms, controls and the rest in VB .NET applications actually comes from the class library.
Common Language Specification (CLS)
If we want the code which we write in a language to be used by programs in other languages then it should adhere to the Common Language Specification (CLS). The CLS describes a set of features that different languages have in common. The CLS defines the minimum standards that .NET language compilers must conform to, and ensures that any source code compiled by a .NET compiler can interoperate with the .NET Framework.

Some reasons why developres are building applications using the .NET Framework:
Improved Reliability
Increased Performance
Developer Productivity
Powerful Security
Integration with existing Systems
Ease of Deployment
Mobility Support
XML Web service Support
Support for over 20 Programming Languages
Flexible Data Access

Namespace

Namespaces are a way to define the classes and other types of information into one hierarchical structure.
System is the basic namespace used by every .NET code. If we can explore the System namespace little bit, we can see it has lot of namespace uses the system namespace.
For example, System.Io, System.Net, System.Collections, System.Threading, etc.
A namespace can be created via the Namespace keyword.

Here is an example to create "Books" namespace in VB.NET and C#.
VB.NET Code:
Namespace Books

Class Authors
'Do something
End Class
End Namespace
C# Code:
namespace Books

{
class Authors
{
//Do something
}
}
This is simple namespace example. We can also build hierarchy of namespace. Here is an example for this.
VB.NET Code:
Namespace Books

Namespace Inventory
Imports System
Class AddInventory
Public Function MyMethod()
Console.WriteLine("Adding Inventory via MyMethod!")
End Function
End Class
End Namespace
End Namespace
C# Code:
namespace Books

{
namespace Inventory
{
using System;
class AddInventory
{
public void MyMethod()
{
Console.WriteLine("Adding Inventory via MyMethod!");
}}}}
That's all it takes to create namespace.

Let's look how we can use the namespaces in our code. I'm going to create a standalone program to use the namespaces.
VB.NET Code:
Imports System

Class HelloWorld
Public Sub Main()
Dim AddInv As Inventory.AddInventory = New AddInventory
AddInv.MyMethod()
End Sub
End Class
OR
Imports System.Inventory

Class HelloWorld
Public Sub Main()
Dim AddInv As AddInventory = New AddInventory
AddInv.MyMethod()
End Sub
End Class
C# Code:
using Books;

class HelloWorld
{
public static void Main()
{
Inventory.AddInventory AddInv = new AddInventory();
AddInv.MyMethod();}}
OR
using Books.Inventory;

class HelloWorld
{public static void Main()
{AddInventory AddInv = new AddInventory();
AddInv.MyMethod();}}
Note: When using Imports statement or Using statement we can use only the namespace names, we can't use the class names. For example, the following statements are invalid.
Imports Books.Inventory.AddInventory
using Books.Inventory.AddInventory;

Boxing & UnBoxing in .Net

Boxing is implicit conversion of value types to reference types.
Recall that all classes and types are derived from the Object class. Because they are derived from Object class they can be implicitly converted to that type.
The following sample shows that:
Dim x as Integer=20 'declaring an integer x
Dim o as Object 'declaring an object
o=x 'converting integer to object
Unboxing is the conversion of a boxed value back to a value type.

Scope of Variable in .Net

The scope of an element in code is all the code that can refer to it without qualifying it's name. Stated other way, an element's scope is it's accessibility in code.
Scope is normally used when writing large programs as large programs divide code into different classes, modules, etc. Also, scope prevents the chance of code referring to the wrong item.
The different kinds of scope available in VB .NET are as follows:
Block Scope: The element declared is available only within the code block in which it is declared.
Procedure Scope: The element declared is available only within the procedure in which it is declared.
Module Scope: The element is available to all code within the module and class in which it is declared.
Namespace Scope: The element declared is available to all code in the namespace.

With Statement

With statemnt is used to execute statements using a particular object. The syntax looks like this:
With

object[statements]

End With
Sample Code
The following code sets text and width for a button using the With Statement.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_Handles MyBase.Load

With Button1

.Text = "With Statement"

.Width = 150

End With

End Sub

Imports Statement

The Imports statement is used to import namespaces.

Using this statement prevents you to list the entire namespace when you refer to them.


Example of Imports Statement
The following code imports the namespace System.Console and uses the methods of that namespace preventing us to refer to it every time we need a method of this namespace.



Imports System.Console

Module Module1

Sub Main()

Write("Imports Statement")

WriteLine("Using Import")

End Sub

End Module


The above two methods without an imports statement would look like this: System.Console.Write("Imports Statement") and System.Console.WriteLine("Using Import")

Statements in .Net

A statement is a complete instruction.
It can contain keywords, operators, variables, literals, expressions and constants.
Each statement in Visual Basic should be either a declaration statement or a executable statement.
A declaration statement is a statement that can create a variable, constant, data type. They are the one's we generally use to declare our variables.
On the other hand, executable statements are the statements that perform an action. They execute a series of statements. They can execute a function, method, loop, etc.

Language Terminology

Briefly on some terminology when working with the language:
Module: Used to hold code


Variable: A named memory location of a specific data type used to hold some value

Procedure: A callable series of statements which may or may not return a value

Sub-Procedure: A procedure with no return value

Function: A procedure with return value

Methods: A procedure built into the class

Constructor: Special method used to initialize and customize the object. It has the same name as the class Class: An OOP class which contains data and code

Object: An instance of a class

Arrays: Programming constructs that lets us access data by numeric index

Attributes: They are the items that specify information about other items being used in VB. NET

Attributes

Attributes are those that lets us specify information about the items we are using in VB .NET. Attributes are enclosed in angle brackets(< >) and are used when VB .NET needs to know more beyond the standard syntax.

Data Type Conversion in .Net

Converting between Data types
In Visual Basic, data can be converted in two ways: implicitly, which means the conversion is performed automatically, and explicitly, which means you must perform the conversion.
Implict Conversions
Let's understand implicit conversions in code.
The example below declares two variable, one of type double and the other integer. The double data type is assigned a value and is converted to integer type. When you run the code the result displayed is an integer value, in this case the value displayed is 132 instead of 132.31223.
Imports System.Console
Module Module1
Sub Main()
Dim d=132.31223 as Double
Dim i as Integer
i=d
WriteLine("Integer value is" & i)
End Sub
End Module
Explicit Conversions
When types cannot be implicitly converted you should convert them explicitly. This conversion is also called as cast.
Explicit conversions are accomplished using CType function.
CType function for conversion
If we are not sure of the name of a particular conversion function then we can use the CType function.



The above example with a CType function looks like this:
Imports System.Console

Module Module1

Sub Main()

Dim d As Double

d = 132.31223

Dim i As Integer

i = CType(d, i)'two arguments, type we are converting from, to type desired

WriteLine("Integer value is" & i)

End Sub

End Module


Below is the list of conversion functions which we can use in VB .NET.
CBool - use this function to convert to Bool data type

CByte - use this function to convert to Byte data type

CChar - use this function to convert to Char data type

CDate - use this function to convert to Date type

CDbl - use this function to convert to Double data type

CDec - use this function to convert to Decimal data type

CInt - use this function to convert to Integer data type

CLng - use this function to convert to Long data type

CObj - use this function to convert to Object type

CShort - use this function to convert to Short data type

CSng - use this function to convert to Single data type

CString - use this function to convert to String data type

Variables in .Net

Variables are used to store data.
A variable has a name to which we refer and the data type, the type of data the variable holds.
VB .NET now needs variables to be declared before using them.
Variables are declared with the Dim keyword. Dim stands for Dimension.
Example
Imports System.Console
Module Module1
Sub Main()
Dim a,b,c as Integer'declaring three variables of type integer
a=10
b=20
c=a+b
Write("Sum of a and b is" & c)
End Sub
End Module

Access Specifiers in .Net

Access specifiers let's us specify how a variable, method or a class can be used. The following are the most commonly used one's:
Public: Gives variable public access which means that there is no restriction on their accessibility
Private: Gives variable private access which means that they are accessible only within their declaration content
Protected: Protected access gives a variable accessibility within their own class or a class derived from that class
Friend: Gives variable friend access which means that they are accessible within the program that contains their declaration
Protected Friend: Gives a variable both protected and friend access
Static: Makes a variable static which means that the variable will hold the value even the procedure in which they are declared ends
Shared: Declares a variable that can be shared across many instances and which is not associated with a specific instance of a class or structure
ReadOnly: Makes a variable only to be read and cannot be written

Data Types in VB .NET

Data Types in VB .NET
The Data types available in VB .NET, their size, type, description are summarized in the table below.
Data Type Size in Bytes Description Type
Byte 1 8-bit unsigned integer System.Byte
Char 2 16-bit Unicode characters System.Char
Integer 4 32-bit signed integer System.Int32
Double 8 64-bit floating point variable System.Double
Long 8 64-bit signed integer System.Int64
Short 2 16-bit signed integer System.Int16
Single 4 32-bit floating point variable System.Single
String Varies Non-Numeric Type System.String
Date 8 System.Date
Boolean 2 Non-Numeric Type System.Boolean
Object 4 Non-Numeric Type System.Object
Decimal 16 128-bit floating point variable System.Decimal

Data Types in MS.net

MS.net provides 2 kinds of Data types,
1)Value Types
2)Reference Types
Value type: Bool,byte,char,decimal,double,enum,float,int,sbyte,short,struct,uint,ulong,ushort.
Value types are stored in the stack.
Example:
dim x as Integer
x=10
Reference Type:class,delegate,interface,object,string.
Reference Types are stored in the Heap.
Example:
Dim Form1 as new System.Windows.Forms.Form
Form1=New System.Windows.Forms.Form

Thursday, July 30, 2009

Common Language Specification

Common Language Specification (CLS) is a set of basic language features that .Net Languages needed to develop Applications and Services , which are compatible with the .Net Framework. When there is a situation to communicate Objects written in different .Net Complaint languages , those objects must expose the features that are common to all the languages .

Common Language Specification (CLS) ensures complete interoperability among applications, regardless of the language used to create the application.

Common Type System

In order that two language communicate smoothly CLR has CTS (Common Type
System).
Example in VB you have “Integer” and in C++ you have “long” these datatypes are not
compatible so the interfacing between them is very complicated. In order that these two different languages communicate Microsoft introduced Common Type System. So “Integer” data type in VB6 and “int” data type in C++ will convert it to System.int32, which is data type of CTS.
CLS is subset of CTS.

Tuesday, July 28, 2009

Common Language Runtime

The Common Language Runtime is the runtime in the .Net environment that compiles the source code in to an intermediate language. This intermediate language is called the Microsoft Intermediate Language(MSIL).
During the execution of the program this MSIL is converted to the native code or the machine code. This conversion is possible through the Just-In-Time compiler. During compilation the end result is a Portable Executable file (PE).
This portable executable file contains the MSIL and additional information called the metadata. This metadata describes the assembly that is created. Class names, methods, signature and other dependency information are available in the metadata. Since the CLR compiles the source code to an intermediate language, it is possible to write the code in any language of your choice. This is a major advantage of using the .Net framework.
The other advantage is that the programmers need not worry about managing the memory themselves in the code. Instead the CLR will take care of that through a process called Garbage collection(GC). This frees the programmer to concentrate on the logic of the application instead of worrying about memory handling.
Your Ad Here