Tuesday, December 4, 2007

.Net architecture & core concepts


.Net Framework basics

When we speak about .Net, we mean by .NET framework. .NET Framework is made up of the Common Language Runtime (CLR), the Base Class Library (System Classes). This allows us to build our own services (Web Services or Windows Services) and Web Applications (Web forms Or Asp .Net), and Windows applications (Windows forms). We can see how this is all put together.?


Above Picture shows overall picture, demonstrating how the .NET languages follows rules provided by the Common Language Specifications (CLS). These languages can all be used?Independently to build application and can all be used with built-in data describers (XML) and data assessors (ADO .NET and SQL). Every component of the .NET Framework can take advantage of the large pre- built library of classes called the Framework Class Library (FCL). Once everything is put together, the code that is created is executed in the Common Language Runtime. Common Language Runtime is designed to allow any .NET-compliant language to execute its code. At the time of writing, these languages included VB .Net, C# and C++ .NET, but any language can become .NET- compliant, if they follow CLS rules. The following sections will address each of the parts of the architecture.

.Net Common Language Specifications (CLS):

In an object-oriented environment, everything is considered as an object. (This point is explained in this article and the more advanced features are explained in other articles.) You create a template for an object (this is called the class file), and this class file is used to create multiple objects.
TIP: Consider a Rectangle. You may want to create many Rectangle in your lifetime; but each Rectangle will have certain characteristics and certain functions. For example, each rectangle will have a specific width and color. So now, suppose your friend also wants to create a Rectangle. Why reinvent the Rectangle? You can create a common template and share it with others. They create the Rectangle based on your template. This is the heart of object-oriented programming?the template is the class file, and the Rectangle is the objects built from that class. Once you have created an object, your object needs to communicate with many other Objects.

Even if it is created in another .NET language doesn?t matter, because each language follows the rules of the CLS. The CLS defines the necessary things as common variable types (this is called the Common Type System CTS ), common visibility like when and where can one see these variables, common method specifications, and so on. It doesn?t have one rule which tells how C# composes its objects and another rule tells how VB .Net does the same thing . To steal a phrase, there is now ?One rule to bind them all.? One thing to note here is that the CLS simply provides the bare rules. Languages can adhere to their own specification. In this case, the actual compilers do not need to be as powerful as those that support the full CLS.
The Common Language Runtime (CLR):

The heart of .net Framework is Common Language Runtime (CLR). All .NET-compliant languages run in a common, managed runtime execution environment. With the CLR, you can rely on code that is accessed from different languages. This is a huge benefit. One coder can write one module in C#, and another can access and use it from VB .Net. Automatic object management, the .NET languages take care of memory issues automatically. These are the few listed?benefits which you get from CLR.
Microsoft Intermediate Language (MSIL):

So how can many different languages be brought together and executed together??Microsoft Intermediate Language (MSIL) or, as it?s more commonly known, Intermediate Language (IL). In its simplest terms, IL is a programming language.?If you wanted to, you could write IL directly, compile it, and run it. But why would want to write such low level code? Microsoft has provided with higher-level languages, such as C#, that one can use. Before the code is executed, the MSIL must be converted into platform-specific code. The CLR includes something called a JIT compiler in which the compiler order is as follows.

Source Code => Compiler => Assembley =>Class Loader =>Jit Compiler =>Manged Native Code=>Execution.

The above is the order of compilation and execution of programs. Once a program is written in a .Net compliant language, the rest all is the responsibility of the frame work.

--------------------------------------------------

ASSEMBLIES

Assemblies are basically the compiled code in .Net which contains the code in Microsoft Intermediate Langauge and one more thing that assembiles do for us as compared to dlls is they can maintain versioning with the help of the manifest.
You dont need to register the assemblies after compiling like we needed in dlls. you can put the assemblies in the bin folder and refer the namespaces from there.
In short find the assembly description as :
Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime with the information it needs to be aware of type implementations. To the runtime, a type does not exist outside the context of an assembly.

Differences Between Shared and Private Assemblies and how to use them.

Shared and Private Assembly: A private assembly is a assembly that is available to particular applications where they are kept. And cannot be references outside the scope of the folder where they are kept.
In contrast, Shared Assemblies are the assemblies that are accessible globally/shared across the machine to all the applications. For using the shared assemblies you need to register the assembly with a strong name in the global assembly cache(GAC) using gacutil.exe. GAC can be found on all the computers with .Net framework installed.

----------------------------------
Assembly vs DLL

1.Dot NET assembly is the component standard specified by the .NET, so dot net assemblies are understandable to only Microsoft.NET and can be used only in .NET managed applications.

DLL contains library code to be used by any program running on Windows. A DLL may contain either structured or object oriented libraries.

2. assembly :

An assembly is the smallest unit that you use to define the version of an application. The version of an assembly determines the version of the types and the other resources that it contains. The .NET Framework allows the execution of multiple versions of the same assembly on the same machine. The side-by-side execution of assemblies overcomes the problem known as "DLL hell," which is one of the major problems associated with COM applications.

DLL:

A Dynamic Link Library (DLL) is a file that is loaded at runtime, and its functions linked
dynamically at that time. This allows for multiple applications that use the same library functions to all share one DLL, and if the code in the DLL needs to be fixed, the DLL can be replaced, and all applications that use it will get the benefit of the update. Static libraries are different from DLLs in that each application gets its own copy of the functions, and they are embedded into the Exe at compile/link time. If the library functions need to be fixed, every application that uses them must be recompiled to get the fixes.

Assembly ..... concept ... :-)

http://www.dnzone.com/ShowDetail.asp?NewsId=698

OOPS concepts .....

Constructor

C# supports two types of constructor, a class constructor (static constructor) and an instance constructor (non-static constructor).

Static constructor is used to initialize static data members as soon as the class is referenced first time, whereas an instance constructor is used to create an instance of that class with keyword. A static constructor does not take access modifiers or have parameters and can't access any non-static data member of a class.

Since static constructor is a class constructor, they are guaranteed to be called as soon as we refer to that class or by creating an instance of that class.

You may say, why not initialize static data members where we declare them in the code. Like this :

private static int id = 10;
private static string name = "jack";

Static data members can certainly be initialized at the time of their declaration but there are times when value of one static member may depend upon the value of another static member. In such cases we definitely need some mechanism to handle conditional initialization of static members. To handlesuch situation, C# provides static constructor.

Let me explain you with examples :

//File Name : Test.cs
using System;
namespace Constructor
{
class Test
{
//Declaration and initialization of static data member
private static int id = 5;
public static int Id
{
get
{
return id;
}
}
public static void print()
{
Console.WriteLine("Test.id = " + id);
}
static void Main(string[] args)
{
//Print the value of id
Test.print();
}
}
}

In the above example, static data member is declared and initialized in same line. So if you compile and run this program your output would look similar to this :

Test.id = 5

Lets create one more class similar to class Test but this time the value of its static data member would depend on the value of static data member of class Test.id.

//File Name : Test1.cs
using System;
namespace Constructor
{
class Test1
{
private static int id ;
//Static constructor, value of data member id is set conditionally here.
//This type of initialization is not possible at the time of declaration.
static Test1()
{
if( Test.Id < id =" 20;">
{
id = 100;
}
Console.WriteLine("Static Constructor for Class Test1 Called..");
}
public static void print()
{
Console.WriteLine("Test1.id = " + id);
}
static void Main(string[] args)
{
//Print the value of id
Test1.print();
}
}
}

As you can see in the above static constructor, static data member is initialized conditionally. This type of initialization is not possible at the time of declaration. This is where static constructor comes in picture. So if you compile and run this program your output would look similar to this :

Static Constructor for Class Test1 Called..
id = 20

Since in class Test was initialized with a value of 5, therefore in class Test1 got initialized to a value of 20.

Some important point regarding static constructor from C# Language Specification and C# Programmer's Reference :

1) The static constructor for a class executes before any instance of the class is created.
2) The static constructor for a class executes before any of the static members for the class are referenced.
3) The static constructor for a class executes after the static field initializers (if any) for the class.
4) The static constructor for a class executes at most one time during a single program instantiation
5) A static constructor does not take access modifiers or have parameters.
6) A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
7) A static constructor cannot be called directly.
8) The user has no control on when the static constructor is executed in the program.
9) A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

Hopefully, this would clear the confusion some of developers have about static constructor.

Friday, November 30, 2007

What is Garbage Collection(GC) ?

One of the major causes of program failure today, particularly in applications that run for long time is due to manual memory management. Which leads two main problems

First one is, a programmer allocates a block of memory in a data storage area Of operating system (i.e. in Random Accesses Memory) intending to Free it latter, some time he mistakenly forget to release memory it No longer needs, this condition known as ‘Memory leak’

If this application run long enough, these leaks accumulate and the application runs out of memory, that is not big deal in a programs like ‘notepad’, that user runs for a few minutes an then shutdown. But a fatal application like web server that are supposed to run continuously for days or week this will leads accumulation of memory leaks and which leads to application fail.

Second one is programmer manually delete an object but then mistakenly or other objects try to access this memory location later. This will leads to hanging of application, and more over some times transistor that had make up the deleted object memory would still contain ‘Plausible’ values, and program continue to run with corrupted data.

These two above mentioned bugs are worse than most other application bugs because what the consequences will be and when those consequences will occur are typically unpredictable. That is making our application perform in unpredictable ways at unpredictable times. For other bugs, when we see our application misbehaving, we can just fix it

Microsoft.NET Made solution for above mentioned bugs. That is Microsoft made automatic memory management has part of .Net common language runtime (CLR), which allows it is to be used in any .Net language. That is in .Net application if CLR detects that, a Application is no longer using the memory and that it no longer needed. Then CLR release that memory. (i.e. Application does not have to explicitly free Memory that allocated). This mechanism runs automatically in background and is known as Garbage Collection

It solves the problem of manual memory management with out having to write any single line of code. You can’t forget to delete an object because the system cleans it for you when it is not required and you can’t access deleted object through an invalid reference because the object won’t be deleted as long as you hold a reference it

This Garbage Collection is like an automatic seat belt. The passengers couldn’t forget to buckle it. More over we know that automatic belt require more space and mechanism than manual one. Similarly .net application Require more system resources than ordinary application.

Really the garbage collection changes programming. we don't have all that Free What we Create overhead, so our code is smaller and clearer and easier to write. Garbage collection also makes programming even more object oriented.

Main aim of .Net is that faster development with fewer bugs That is we want programmer only think about program logic. Not any other Things like memory management or else.

NOTE: The memory used by heap variables is freed via a process garbage collection. Stack variables is automatically freed when the method in which they were created returns( ie Grabage collection is applied only for Heap Variable)

Thursday, November 29, 2007

Generics in VB.NET

Generics are very useful if you know what they are and how to use them. C++ was one of the first languages, which used some types of generics, however they were called “templates”. C# uses a similar syntax as the C++ templates, however in C# they are much easier to use. <> is used in C# to define a generic. However in VB.NET we use the keyword “Of”. In this article we will only discuss the VB.NET syntax.

What are Generics?

The term “generic” means not to be bound to any specific type regardless of whether we are referring it to any programming language or not! Just think of a “glass”, which can be filled with the following types: water, juice, soda etc. As you can see it is not bound to one type. It can be filled with any type. In the same way we can refer it to VB.NET. We could create a class called “Glass” which could store any of these types depended on the users choice.

Generics can be used to store collections, which are not bound to any data type.
Why should I use Generics?

ust imagine that you are working in a class where you would need to store different data types in a collection. Of course you could use an array, but don’t forget that you will need to create different arrays for different data types. Furthermore your code will be unnecessary longer than needed. In that case we can use generics. We could use one generic class that could handle all of data types, without requiring writing the code again and again. This will increase the performance, because the user would not need to cast the data types. In summary we can say that generics are used for the following reasons:

* Performance
* Type Safe
* Code Reuse

Performance:
How can generics help the developer to get a better performance? This is simple. The data-types are checked in the compile-timer rather than in run-time. Simply this change will improve the performance. No type casting necessary at run-time. However you should know that performance and speed are not the main aspects to use generics, but in maintainability and cleaner code.

Type Safe:
This means that whenever you add an object to the collection it is checked at compile time. That means that the data type should be safe and if you pass a wrong data-type to the collection, it will throw an error during the compile time and not in the run time. This way you can make sure to handle all errors so that they don’t appear at run time, when the client is using the application.

Code Reuse:
If you want to store different data types in a (non-generic) collection, than you won’t have any other option than declaring different collections for that. For example: You will need to declare a collection for integers, another for strings and another for double data types. When using generics you just need to set the data type as a parameter and viola you can use it with whatever type you like.

Simple Example

We have read a lot by now. It’s time to see some code. To demonstrate how simple it is to use we have chosen a simple example. Lets see how it looks like:

Our Gen Class:

Public Class Gen(Of T)
Dim dataType As T
Public Property Val() As T
Get
Return dataType
End Get
Set(ByVal value As T)
dataType = value
End Set
End Property
End Class

Our Main:

Sub Main()
' This one accepts strings
Dim mystring As New Gen(Of String)
mystring.Val = "hello world"
System.Console.WriteLine(mystring.Val)
' Change the declaration so that it accepts now an integer
Dim myInt As New Gen(Of Integer)
myInt.Val = 5
System.Console.WriteLine(myInt.Val)
Console.WriteLine("Press Enter to finish ... ")
Console.Read()
End Sub

Our Output:

hello world
5

How it works:
As you can see above we have only two main parts. The first is the class “Gen” and the second is the main function. The “Gen” class is generic. As already described in the introduction we need the “Of” keyword to declare it as generic. In C# and C++ we can use <> to create generic classes.

The “T” next right to the “Of” represents our data-type which we will pass when we create a new instance of that class. The rest of the code should be familiar to you.

The interesting part is going on in the main function where we create two instances of the “Gen” class. In the first instance we are using a String. This will allow passing string values to the class variables.

Dim mystring As New Gen(Of String)
mystring.Val = "hello world"
System.Console.WriteLine(mystring.Val)

In the second instance we are using an Integer. Here we can use integer values to pass to the class variables.

Dim myInt As New Gen(Of Integer)
myInt.Val = 5
System.Console.WriteLine(myInt.Val)

As you can see this was our first simple generic example. To get the same result without using generic, will cost you two classes. The first one would need a string and the second one could use an integer, but what if you decide to create a third data-type, lets say a double? Well then you will need to create a third class, which will again make your code longer than it already is. While using generics you only need one class for any data-type.

CLI, CLR, MSIL, JIT, .NET, C#, CLS and CTS ....


To most .NET programmers, there will be nothing new in this particular post. But, it only seems fitting that the initial post to this blog should be this simplified overview, just to make sure we're all on the same page.

The Common Language Infrastructure (CLI) is an international standard defined in ECMA-335. The CLI specifies the common mechanics for high-level, CLI-compliant programming languages. This standard is neither language specific nor platform specific.

The Common Language Runtime (CLR) is Microsoft's implementation of the CLI standard. The CLR executes a type of bytecode known as the Microsoft Intermediate Language (MSIL). At run-time, that MSIL bytecode is turned into native, executable code by the Just-In-Time compiler (JIT compiler). In theory, any CLI-compliant programming language is supported on any platform with the appropriate compiler and runtime.

The term ".NET" refers to a Microsoft product that includes the CLR, JIT compiler, source code compilers, and an entire framework of CLI-compliant components targetted for the Windows platform.

C# is a CLI-compliant programming language defined by the C# Language Specification (C#LS) known as ECMA-334. C#.NET is Microsoft's implementation of the C#LS for use with the Microsoft CLR, JIT compiler and framework components on Windows platforms. Since C#.NET is the only real implementation of the C# programming language (aside from the Mono open source project), the terms "C#" and "C#.NET" are often used interchangeably.

There are several .NET languages, including C#.NET and VB.NET. Even though both of those languages are CLI-compliant, the languages themselves have different capabilities. The Common Language Specification (CLS) is a Microsoft specification that defines the guaranteed subset of common functionality that is useable by all .NET programming languages. For example, the CLS defines the Common Type System (CTS), and the CTS does not include unsigned integers because the VB.NET programming language does not support unsigned integers.

Wednesday, November 28, 2007