You are on page 1of 20

Namespaces A namespace is a collection of different classes. All VB applications are developed using classes from the .

NET System namespace. The namespace with all the built-in VB functionality is the System namespace. All other namespaces are based on this System namespace. Some Namespaces and their use: System: Includes essential classes and base classes for commonly used data types, events, exceptions and so on. System.Collections: Includes classes and interfaces that define various collection of objects such as list, queues, hash tables, arrays, etc. System.Data: Includes classes which lets us handle data from data sources System.Data.OleDb: Includes classes that support the OLEDB .NET provider System.Data.SqlClient: Includes classes that support the SQL Server .NET provider System.Diagnostics: Includes classes that allow to debug our application and to step through our code System.Drawing: Provides access to drawing methods System.Globalization: Includes classes that specify culture-related information System.IO: Includes classes for data access with Files System.Net: Provides interface to protocols used on the internet System.Reflection: Includes classes and interfaces that return information about types, methods and fields System.Security: Includes classes to support the structure of common language runtime security system System.Threading: Includes classes and interfaces to support multithreaded applications System.Web: Includes classes and interfaces that support browser-server communication System.Web.Services: Includes classes that let us build and use Web Services System.Windows.Forms: Includes classes for creating Windows based forms System.XML: Includes classes for XML support Assemblies An assembly is the building block of a .NET application. It is a self describing collection of code, resources, and metadata (data about data, example, name, size, version of a file is metadata about that file). An Assembly is a complied and versioned collection of code and metadata that forms an atomic functional unit. Assemblies take the form of a dynamic link library (.dll) file or executable program file (.exe) but they differ as they contain the information found in a type library and the information about everything else needed to use an application or component. All .NET programs are constructed from these Assemblies. Assemblies are made of two parts: manifest, contains information about what is contained within the assembly and modules, internal files of IL code which are ready to run. When programming, we don't directly deal with assemblies as the CLR and the .NET framework takes care of that behind the scenes. The assembly file is visible in the Solution Explorer window of the project. An assembly includes:

o o o o o o

Information for each public class or type used in the assembly information includes class or type names, the classes from which an individual class is derived, etc Information on all public methods in each class, like, the method name and return values (if any) Information on every public parameter for each method like the parameter's name and type Information on public enumerations including names and values Information on the assembly version (each assembly has a specific version number) Intermediate language code to execute A list of types exposed by the assembly and list of other assemblies required by the assembly of a Assembly file is displayed below.

Image

The System.Net namespace provides a simple programming interface for many of the protocols used on networks today. The WebRequest and WebResponse classes form the basis of what are called pluggable protocols, an implementation of network services that enables you to develop applications that use Internet resources without worrying about the specific details of the individual protocols. An assembly is a collection of types and resources that forms a logical unit of functionality. All types in the .NET Framework must exist in assemblies; the common language runtime does not support types outside of assemblies. Each time you create a Microsoft Windows Application, Windows Service, Class Library, or other application with Visual Basic .NET, you're building a single assembly. Each assembly is stored as an .exe or .dll file. Note Although it's technically possible to create assemblies that span multiple files, you're not likely to

use this technology in most situations. The .NET Framework uses assemblies as the fundamental unit for several purposes:

Security Type Identity Reference Scope Versioning Deployment

Security
An assembly is the unit at which security permissions are requested and granted. Assemblies are also the level at which you establish identity and trust. The .NET Framework provides two mechanisms for this level of assembly security: strong names and Signcode.exe. You can also manage security by specifying the level of trust for code from a particular site or zone. Signing an assembly with a strong name adds public key encryption to the assembly. This ensures name uniqueness and prevents substituting another assembly with the same name for the assembly that you provided. The signcode.exe tool embeds a digital certificate in the assembly. This allows users of the assembly to verify the identity of the assembly's developer by using a public or private trust hierarchy. You can choose to use either strong names, Signcode.exe, or both, to strengthen the identity of your assembly. The common language runtime also uses internal hashing information, in conjunction with strong names and signcode, to verify that the assembly being loaded has not been altered after it was built.

Type Identity
The identity of a type depends on the assembly where that type is defined. That is, if you define a type named DataStore in one assembly, and a type named DataStore in another assembly, the .NET Framework can tell them apart because they are in two different assemblies. Of course you can't define two different types with the same name in the same assembly.

Reference Scope
The assembly is also the location of reference information in general. Each assembly contains information on references in two directions:

The assembly contains metadata that specifies the types and resources within the assembly that are exposed to code outside of the assembly. For example, a particular assembly could expose a public type named Customer with a public property named AccountBalance.

The assembly contains metadata specifying the other assemblies on which it depends. For example, a particular assembly might specify that it depends on the System.Windows.Forms.dll assembly.

Versioning
Each assembly has a 128-bit version number that is presented as a set of four decimal pieces: Major.Minor.Build.Revision For example, an assembly might have the version number 3.5.0.126.By default, an assembly will only use types from the exact same assembly (name and version number) that it was built and tested with. That is, if you have an assembly that uses a type from version 1.0.0.2 of another assembly, it will (by default) not use the same type from version 1.0.0.4 of the other assembly. This use of both name and version to identify referenced assemblies helps avoid the "DLL Hell" problem of upgrades to one application breaking other applications.

Deployment
Assemblies are the natural unit of deployment. The Windows Installer Service 2.0 can install individual assemblies as part of a larger setup program. You can also deploy assemblies in other ways, including by a simple xcopy to the target system or via code download from a web site. When you start an application, it loads other assemblies as a unit as types and resources from those assemblies are needed.

The Assembly Manifest


Every assembly contains an assembly manifest, a set of metadata with information about the assembly. The assembly manifest contains these items: The assembly name and version

The culture or language the assembly supports (not required in all assemblies) The public key for any strong name assigned to the assembly (not required in all assemblies) A list of files in the assembly with hash information Information on exported types Information on referenced assemblies

The Global Assembly Cache


Assemblies can be either private or shared. By default, assemblies are private, and types contained within those assemblies are only available to applications in the same directory as the assembly. But every computer with the .NET Framework installed also has a global assembly cache (GAC) containing assemblies that are designed to be shared by multiple applications. There are three ways to add an assembly to the GAC:

Install them with the Windows Installer 2.0 Use the Gacutil.exe tool Drag and drop the assemblies to the cache with Windows Explorer

Note that in most cases you should plan to install assemblies to the GAC on end-user computers by using the Windows Installer. The gacutil.exe tool and the drag and drop method exist for use during the development cycle. You can view the contents of your global assembly cache by using Windows Explorer to navigate to the WINNT\assembly folder, as shown in Figure 1.

Assembly Info.vb
When you create a new project using Visual Basic .NET, one of the components of the project will be a file named AssemblyInfo.vb. This file contains all of the assembly attributes that describe the assembly. To characterize your assembly, you should customize this information. You can edit the AssemblyInfo.vb file just like any other Visual Basic .NET source file. The default contents of this file look like this:

' Version information for an assembly consists of the following four values: ' ' ' ' ' Major Version Minor Version Build Number Revision and Revision Numbers ' by using the '*' as shown below: <Assembly: AssemblyVersion("1.0.*")>

' You can specify all the values or you can default the Build

pFigure 1. Viewing the Global Assembly Cache in Windows Explorer

Create the Class Library


Follow these steps to create the class library that will raise the events: 1. 2. 3. 4. 5. 6. Open Microsoft Visual Studio .NET, click Start, and then click New Project. In the left pane tree view, select Visual Basic Project. Select Class Library as the project template. Set the name of the application to PowerLib and click OK. In Solution Explorer, highlight the class called Class1.vb and rename it to Button.vb. Select the code for Class1 in Button.vb (this be an empty class definition) and replace it with the following code:

Public Class Button

Private mfState As Boolean Public Sub Toggle() mfState = Not mfState End Sub Public Property State() As Boolean Get State = mfState End Get Set(ByVal Value As Boolean) mfState = Value End Set End Property End Class
Customize the Assembly
Follow these steps to customize the Assembly attributes: 1. 2. In Solution Explorer, double-click the AssemblyInfo.vb file to open it in the code editor. Select the first block of assembly attributes and modify them as follows:

<Assembly: AssemblyTitle("PowerPlant")> <Assembly: AssemblyDescription("Power plant user interface")> <Assembly: AssemblyCompany("Your Company")> <Assembly: AssemblyProduct("PowerLib")> <Assembly: AssemblyCopyright("Copyright 2002")> <Assembly: AssemblyTrademark("")> <Assembly: CLSCompliant(True)>
3. Select the version attribute and modify it as follows:

<Assembly: AssemblyVersion("1.0.0.0")> Memory Management-: Resource Allocation The Microsoft .NET common language runtime requires that all resources be allocated from the managed heap. Objects are automatically freed when they are no longer needed by the application. When a process is initialized, the runtime reserves a contiguous region of address space that initially has no storage allocated for it. This address space region is the managed heap. The heap also maintains a pointer. This pointer indicates where the

next object is to be allocated within the heap. Initially, the pointer is set to the base address of the reserved address space region. An application creates an object using the new operator. This operator first makes sure that the bytes required by the new object fit in the reserved region (committing storage if necessary). If the object fits, then pointer points to the object in the heap, this object's constructor is called, and the new operator returns the address of the object.

Above fig shows a managed heap consisting of three objects: A, B, and C. The next object to be allocated will be placed where NextObjPtr points (immediately after object C). When an application calls the new operator to create an object, there may not be enough address space left in the region to allocate to the object. The heap detects this by adding the size of the new object to NextObjPtr. If NextObjPtr is beyond the end of the address space region, then the heap is full and a collection must be performed. In reality, a collection occurs when generation 0 is completely full. Briefly, a generation is a mechanism implemented by the garbage collector in order to improve performance. The idea is that newly created objects are part of a young generation, and objects created early in the application's lifecycle are in an old generation. Separating objects into generations can allow the garbage collector to collect specific generations instead of collecting all objects in the managed heap. The Garbage Collection Algorithm The garbage collector checks to see if there are any objects in the heap that are no longer being used by the application. If such objects exist, then the memory used by these objects can be reclaimed. (If no more memory is available for the heap, then the new operator throws an OutOfMemoryException.) Every application has a set of roots. Roots identify storage locations, which refer to objects on the managed heap or to objects that are set to null. For example, all the global and static object pointers in an application are considered part of the application's roots. In addition, any local variable/parameter object pointers on a thread's stack are considered part of the application's roots. Finally, any CPU

registers containing pointers to objects in the managed heap are also considered part of the application's roots. The list of active roots is maintained by the just-in-time (JIT) compiler and common language runtime, and is made accessible to the garbage collector's algorithm. When the garbage collector starts running, it makes the assumption that all objects in the heap are garbage. In other words, it assumes that none of the application's roots refer to any objects in the heap. Now, the garbage collector starts walking the roots and building a graph of all objects reachable from the roots. For example, the garbage collector may locate a global variable that points to an object in the heap. Following fig shows a heap with several allocated objects where the application's roots refer directly to objects A, C, D, and F. All of these objects become part of the graph. When adding object D, the collector notices that this object refers to object H, and object H is also added to the graph. The collector continues to walk through all reachable objects recursively. Once this part of the graph is complete, the garbage collector checks the next root and walks the objects again. As the garbage collector walks from object to object, if it attempts to add an object to the graph that it previously added, then the garbage collector can stop walking down that path. This serves two purposes. First, it helps performance significantly since it doesn't walk through a set of objects more than once. Second, it prevents infinite loops should you have any circular linked lists of objects. Once all the roots have been checked, the garbage collector's graph contains the set of all objects that are somehow reachable from the application's roots; any objects that are not in the graph are not accessible by the application, and are therefore considered garbage. The garbage collector now walks through the heap linearly, looking for contiguous blocks of garbage objects (now considered free space). The garbage collector then shifts the non-garbage objects down in memory (using the standard memcpy function), removing all of the gaps in the heap. Of course, moving the objects in memory invalidates all pointers to the objects. So the garbage collector must modify the application's roots so that the pointers point to the objects' new locations. In addition, if any object contains a pointer to another object, the garbage collector is responsible for correcting these pointers as well. Following fig shows the managed heap after a collection.

After all the garbage has been identified, all the non-garbage has been compacted, and all the non-garbage pointers have been fixed-up, the NextObjPtr is positioned just after the last non-garbage object. At this point, the new operation is tried again and the resource requested by the application is successfully created. GC generates a significant performance hit, and this is the major downside of using a managed heap. However, keep in mind that GCs only occur when the heap is full and, until then, the managed heap is significantly faster than a C-runtime heap. The runtime's garbage collector also offers some optimizations using Generations that greatly improve the performance of garbage collection. You no longer have to implement any code that manages the lifetime of any resources that your application uses. Now it is not possible to leak resources, since any resource not accessible from your application's roots can be collected at some point. Also it is not possible to access a resource that is freed, since the resource won't be freed if it is reachable. If it's not reachable, then your application has no way to access it. Following code demonstrates how resources are allocated and managed: class Application { public static int Main(String[] args) { // ArrayList object created in heap, myArray is now in root ArrayList myArray = new ArrayList(); // Create 10000 objects in the heap for (int x = 0; x < 10000; x++) { myArray.Add(new Object()); // Object object created in heap } // Right now, myArray is a root (on the thread's stack). So, // myArray is reachable and the 10000 objects it points to are also reachable.

Console.WriteLine(myArray.Count); // After the last reference to myArray in the code, myArray is not a root. // Note that the method doesn't have to return, the JIT compiler knows // to make myArray not a root after the last reference to it in the code. // Since myArray is not a root, all 10001 objects are not reachable // and are considered garbage. However, the objects are not // collected until a GC is performed. } } If GC is so great, you might be wondering why it isn't in ANSI C++. The reason is that a garbage collector must be able to identify an application's roots and must also be able to find all object pointers. The problem with C++ is that it allows casting a pointer from one type to another, and there's no way to know what a pointer refers to. In the common language runtime, the managed heap always knows the actual type of an object, and the metadata information is used to determine which members of an object refer to other objects.

Generations One feature of the garbage collector that exists purely to improve performance is called generations. A generational garbage collector (also known as an ephemeral garbage collector) makes the following assumptions: The newer an object is, the shorter its lifetime will be. The older an object is, the longer its lifetime will be. Newer objects tend to have strong relationships to each other and are frequently accessed around the same time. Compacting a portion of the heap is faster than compacting the whole heap.

When initialized, the managed heap contains no objects. Objects added to the heap are said to be in generation 0, as you can see in following fig. Stated simply, objects in generation 0 are young objects that have never been examined by the garbage collector.

Now, if more objects are added to the heap, the heap fills and a garbage collection must occur. When the garbage collector analyzes the heap, it builds the graph of garbage (shown here in Green) and non-garbage objects. Any objects that survive the collection are compacted into the left-most portion of the heap. These objects have survived a collection, are older, and are now considered to be in generation 1.

As even more objects are added to the heap, these new, young objects are placed in generation 0. If generation 0 fills again, a GC is performed. This time, all objects in generation 1 that survive are compacted and considered to be in generation 2 (see following fig). All survivors in generation 0 are now compacted and considered to be in generation 1. Generation 0 currently contains no objects, but all new objects will go into generation 0.

Currently, generation 2 is the highest generation supported by the runtime's garbage collector. When future collections occur, any surviving objects currently in generation 2 simply stay in generation 2. Disadvantages of Win32 heap: Most heaps (like the C runtime heap) allocate objects wherever they find free space. Therefore, if I create several objects consecutively, it is quite possible that these objects will be separated by megabytes of address space. However, in the managed heap, allocating several objects consecutively ensures that the objects are contiguous in memory. When memory is allocated from a Win32 heap, the heap must be examined to find a block of memory that can satisfy the request. This is not required in managed heap, since here objects are contiguous in memory. In Win32 heap, data structures that the heap maintains must be updated. The managed heap, on the other hand, only needs to increment the heap pointer.

Finalization The garbage collector offers an additional feature that you may want to take advantage of: finalization. Finalization allows a resource to gracefully clean up after itself when it is being collected. By using finalization, a resource representing a file or network connection is able to clean itself up properly when the garbage collector decides to free the resource's memory.

When the garbage collector detects that an object is garbage, the garbage collector calls the object's Finalize method (if it exists) and then the object's memory is reclaimed. For example, let's say you have the following type (in C#): public class BaseObj { public BaseObj() { } protected override void Finalize() { // Perform resource cleanup code here // Example: Close file/Close network connection Console.WriteLine("In Finalize."); } } Now you can create an instance of this object by calling: BaseObj bo = new BaseObj(); Some time in the future, the garbage collector will determine that this object is garbage. When that happens, the garbage collector will see that the type has a Finalize method and will call the method, causing "In Finalize" to appear in the console window and reclaiming the memory block used by this object. Many developers who are used to programming in C++ draw an immediate correlation between a destructor and the Finalize method. However, object finalization and destructors have very different semantics and it is best to forget everything you know about destructors when thinking about finalization. Managed objects never have destructors. When designing a type it is best to avoid using a Finalize method. There are several reasons for this: Finalizable objects get promoted to older generations, which increases memory pressure and prevents the object's memory from being collected when the garbage collector determines the object is garbage. In addition, all objects referred to directly or indirectly by this object get promoted as well. Finalizable objects take longer to allocate. Forcing the garbage collector to execute a Finalize method can significantly hurt performance. Remember, each object is finalized. So if I have an array of 10,000 objects, each object must have its Finalize method called. Finalizable objects may refer to other (non-finalizable) objects, prolonging their lifetime unnecessarily. In fact, you might want to consider breaking a type into two different types: a lightweight type with a Finalize method that doesn't refer to any other objects, and a separate type without a Finalize method that does refer to other objects. You have no control over when the Finalize method will execute. The object may hold on to resources until the next time the garbage collector runs.

When an application terminates, some objects are still reachable and will not have their Finalize method called. This can happen if background threads are using the objects or if objects are created during application shutdown or AppDomain unloading. In addition, by default, Finalize methods are not called for unreachable objects when an application exits so that the application may terminate quickly. Of course, all operating system resources will be reclaimed, but any objects in the managed heap are not able to clean up gracefully. You can change this default behavior by calling the System.GC type's RequestFinalizeOnShutdown method. However, you should use this method with care since calling it means that your type is controlling a policy for the entire application. The runtime doesn't make any guarantees as to the order in which Finalize methods are called. For example, let's say there is an object that contains a pointer to an inner object. The garbage collector has detected that both objects are garbage. Furthermore, say that the inner object's Finalize method gets called first. Now, the outer object's Finalize method is allowed to access the inner object and call methods on it, but the inner object has been finalized and the results may be unpredictable. For this reason, it is strongly recommended that Finalize methods not access any inner, member objects.

If you determine that your type must implement a Finalize method, then make sure the code executes as quickly as possible. Avoid all actions that would block the Finalize method, including any thread synchronization operations. Also, if you let any exceptions escape the Finalize method, the system just assumes that the Finalize method returned and continues calling other objects' Finalize methods. When the compiler generates code for a constructor, the compiler automatically inserts a call to the base type's constructor. Likewise, when a C++ compiler generates code for a destructor, the compiler automatically inserts a call to the base type's destructor. Finalize methods are different from destructors. The compiler has no special knowledge about a Finalize method, so the compiler does not automatically generate code to call a base type's Finalize method. If you want this behavior-and frequently you do-then you must explicitly call the base type's Finalize method from your type's Finalize method: public class BaseObj { public BaseObj() { } protected override void Finalize() { Console.WriteLine("In Finalize."); base.Finalize(); // Call base type's Finalize } } Note that you'll usually call the base type's Finalize method as the last statement in the derived type's Finalize method. This keeps the base object alive as long as possible. Since calling a base type Finalize method is common, C# has a syntax that simplifies your work. In C#, the following code:

class MyObject { MyObject() { } } causes the compiler to generate this code: class MyObject { protected override void Finalize() { base.Finalize(); } } Note that this C# syntax looks identical to the C++ language's syntax for defining a destructor. But remember, C# doesn't support destructors. Don't let the identical syntax fool you. Finalization Internals When an application creates a new object, the new operator allocates the memory from the heap. If the object's type contains a Finalize method, then a pointer to the object is placed on the finalization queue. The finalization queue is an internal data structure controlled by the garbage collector. Each entry in the queue points to an object that should have its Finalize method called before the object's memory can be reclaimed. Following fig shows a heap containing several objects. Some of these objects are reachable from the application's roots, and some are not. When objects C, E, F, I, and J were created, the system detected that these objects had Finalize methods and pointers to these objects were added to the finalization queue.

When a GC occurs, objects B, E, G, H, I, and J are determined to be garbage. The garbage collector scans the finalization queue looking for pointers to these objects. When a pointer is found, the pointer is removed from the finalization queue and appended to the freachable queue (pronounced "F-reachable"). The freachable queue is another internal data structure controlled by the garbage collector. Each pointer in the freachable queue identifies an object that is ready to have its Finalize method called. After the collection, the managed heap looks like following fig. Here, you see that the memory occupied by objects B, G, and H has been reclaimed because these objects did not have a Finalize method that needed to be called. However, the memory occupied by objects E, I, and J could not be reclaimed because their Finalize method has not been called yet.

There is a special runtime thread dedicated to calling Finalize methods. When the freachable queue is empty (which is usually the case), this thread sleeps. But when entries appear, this thread wakes, removes each entry from the queue, and calls each object's Finalize method. Because of this, you should not execute any code in a Finalize method that makes any assumption about the thread that's executing the code. For example, avoid accessing thread local storage in the Finalize method. The interaction of the finalization queue and the freachable queue is quite fascinating. First, let me tell you how the freachable queue got its name. The f is obvious and stands for finalization; every entry in the freachable queue should have its Finalize method called. The "reachable" part of the name means that the objects are reachable. To put it another way, the freachable queue is considered to be a root just like global and static variables are roots. Therefore, if an object is on the freachable queue, then the object is reachable and is not garbage. In short, when an object is not reachable, the garbage collector considers the object garbage. Then, when the garbage collector moves an object's entry from the finalization queue to the freachable queue, the object is no longer considered garbage and its memory is not reclaimed. At this point, the garbage collector has finished identifying garbage. Some of the objects identified as garbage have been reclassified as not garbage. The garbage collector compacts the reclaimable memory and the special runtime thread empties the freachable queue, executing each object's Finalize method.

The next time the garbage collector is invoked, it sees that the finalized objects are truly garbage, since the application's roots don't point to it and the freachable queue no longer points to it. Now the memory for the object is simply reclaimed. The important thing to understand here is that two GCs are required to reclaim memory used by objects that require finalization. In reality, more than two collections may be necessary since the objects could get promoted to an older generation. Above fig shows what the managed heap looks like after the second GC. Dispose Method Use this method to close or release unmanaged resources such as files, streams, and handles held by an instance of the class that implements this interface. This method is, by convention, used for all tasks associated with freeing resources held by an object, or preparing an object for reuse.When implementing this method, objects must seek to ensure that all held resources are freed by propagating the call through the containment hierarchy. For example, if an object A allocates an object B, and object B allocates an object C, then A's Dispose implementation must call Dispose on B, which must in turn call Dispose on C. Objects must also call the Dispose method of their base class if the base class implements IDisposable. If an object's Dispose method is called more than once, the object must ignore all calls after the first one. The object must not throw an exception if its Dispose method is called multiple times. Dispose can throw an exception if an error occurs because a resource has already been freed and Dispose had not been called previously.Because the Dispose method must be called explicitly, objects that implement IDisposable must also implement a finalizer to handle freeing resources when Dispose is not called. By default, the garbage collector will automatically call an object's finalizer prior to reclaiming its memory. However, once the Dispose method

has been called, it is typically unnecessary for the garbage collector to call the disposed object's finalizer. To prevent automatic finalization, Dispose implementations can call the GC.SuppressFinalize method. Direct Control with System.GC The System.GC type allows your application some direct control over the garbage collector. You can query the maximum generation supported by the managed heap by reading the GC.MaxGeneration property. Currently, the GC.MaxGeneration property always returns 2. It is also possible to force the garbage collector to perform a collection by calling one of the two methods shown here: void GC.Collect(Int32 Generation) void GC.Collect() The first method allows you to specify which generation to collect. You may pass any integer from 0 to GC.MaxGeneration, inclusive. Passing 0 causes generation 0 to be collected; passing 1 cause generation 1 and 0 to be collected; and passing 2 causes generation 2, 1, and 0 to be collected. The version of the Collect method that takes no parameters forces a full collection of all generations and is equivalent to calling: GC.Collect(GC.MaxGeneration);

You might also like