.Net Framework is a Windows component that supports building, deploying, and running the next generation of applications and XML Web services. It provides a highly productive, standards-based, multilanguage environment for integrating existing investments with next generation applications and services, as well as the ability to solve the challenges of deployment and operation of Internet-scale applications.
The .NET Framework is Microsoft’s managed code programming model for building applications that have visually stunning user experiences, seamless and secure communication, and the ability to model a range of business processes.
The .NET Framework consists of three main parts: the Common Language Runtime, a hierarchical set of unified class libraries, and a componentized version of ASP called ASP.NET.
.NET Framework class library
A library of classes, interfaces, and value types that are included in the Microsoft .NET Framework SDK. This library provides access to system functionality and is designed to be the foundation on which .NET Framework applications, components, and controls are built.
Common Language Runtime (CLR)
The common language runtime is the execution engine for .NET Framework applications. It provides a number of services, including the following:
• Code management (loading and execution)
• Application memory isolation
• Verification of type safety
• Conversion of IL to native code
• Access to metadata (enhanced type information)
• Managing memory for managed objects
• Enforcement of code access security
• Exception handling, including cross-language exceptions
• Interoperation between managed code, COM objects, and pre-existing DLLs (unmanaged code and data)
• Automation of object layout
• Support for developer services (profiling, debugging, and so on)
Common Type System (CTS)
The common type system is a rich type system, built into the common language runtime, that supports the types and operations found in most programming languages. The common type system supports the complete implementation of a wide range of programming languages. Example, “Integer” datatype in VB and “int” datatype in C++ are not compatible, so the interfacing between them is very complicated. In order that two different languages can communicate, “Integer” in VB6 and “int” in C++ will convert to System.int32 which is datatype of CTS.
Common Language Specification (CLS)
The CLS is a set of constructs and constraints that serves as a guide for library writers and compiler writers. It is the set of guidelines for the language supporting the CLS to follow, so that it can communicate with other .NET languages in a seamless manner. It allows libraries to be fully usable from any language supporting the CLS, and for those languages to integrate with each other. The CLS is a subset of the common type system (CTS). The CLS is also important to application developers who are writing code that will be used by other developers. When developers design publicly accessible APIs following the rules of the CLS, those APIs are easily used from all other programming languages that target the common language runtime.
Microsoft Intermediate Language (MSIL) or Intermediate Language (IL)
MSIL, or simply IL, is the CPU-independent instruction set into which .NET Framework programs are compiled. It contains instructions for loading, storing, initializing, and calling methods on objects. Combined with metadata and the common type system, MSIL allows for true cross-language integration. Prior to execution, MSIL is converted to machine code at run-time by a Just-In-Time (JIT) compiler. It is not interpreted.
• Assembly is unit of deployment like EXE or a DLL.
• An assembly consists of one or more files (dlls, exe’s, html files etc.), and represents a group of resources, type definitions, and implementations of those types. An assembly may also contain references to other assemblies. These resources, types and references are described in a block of data called a manifest. The manifest is part of the assembly, thus making the assembly self-describing.
• An assembly is completely self-describing.An assembly contains metadata information, which is used by the CLR for everything from type checking and security to actually invoking the components methods.As all information is in assembly itself it is independent of registry.This is the basic advantage as compared to COM where the version was stored in registry.
• Multiple versions can be deployed side by side in different folders. These different versions can execute at the same time without interfering with each other.Assemblies can be private or shared. For private assembly deployment,the assembly is copied to the same directory as the client program that references it.No registration is needed, and no fancy installation program is required. When the component is removed, no registry cleanup is needed,and no uninstall program is required. Just delete it from the hard drive.
• In shared assembly deployment, an assembly is installed in the Global Assembly Cache (or GAC). The GAC contains shared assemblies that are globally accessible to all .NET applications on the machine.
Managed code runs inside the environment of CLR i.e. .NET runtime. In short all IL are managed code.But if you are using some third party software example VB6 or VC++ component they are unmanaged code as .NET runtime (CLR) does not have control over the source code execution of the language.
Assembly metadata is stored in Manifest. Manifest contains all the metadata needed to do the following things:
• Version of assembly
• Security identity
• Scope of the assembly
• resolve references to resources and classes.
• The assembly manifest can be stored in either a PE file (an .exe or .dll) with Microsoft intermediate language (MSIL) code or in a stand-alone PE file that contains only assembly manifest information.
Different types of Assembly
There are two types of assembly Private and Public assembly. A private assembly is normally used by a single application, and is stored in the application’s directory, or a sub-directory beneath. A shared assembly is normally stored in the global assembly cache, which is a repository of assemblies maintained by the .NET runtime. Shared assemblies are usually libraries of code which many applications will find useful, e.g. Crystal report classes which will be used by all application for Reports.
It’s a .NET Framework assembly containing resources specific to a given language. Satellite assemblies are often used to deploy language-specific resources for an application. The correct assembly is loaded into memory depending on the user’s choice or by setting CurrentUICulture property on a per-application to view the application in that language.
A namespace is a logical group of classes. Namespaces provide scope: Two classes with the same name can be used in your program as long as they are in different namespaces and as long as you qualify the names to the namespaces. The namespace name is part of the fully qualified name of the type (namespace.typename). Namespaces cannot be instantiated because they are not types.
Global Assembly Cache (GAC)
GAC is the repository of .Net assemblies meant for sharing. In other words, the GAC stores assemblies specifically designated to be shared by several applications on the computer. It is recommended to keep assembly dependencies private, and locate assemblies in the application directory unless sharing an assembly is explicitly required. In addition, it is not necessary to install assemblies into the global assembly cache to make them accessible to COM interop or unmanaged code.
GAC is used in the following situations:
• If the application has to be shared among several application.
• If the assembly has some special security requirements like only administrators can remove the assembly. If the assembly is private then a simple delete of the assembly file will remove the assembly.
A name that consists of an assembly’s identity, its simple text name, version number, and culture information (if provided) strengthened by a public key and a digital signature generated over the assembly. Because the assembly manifest contains file hashes for all the files that constitute the assembly implementation, it is sufficient to generate the digital signature over just the one file in the assembly that contains the assembly manifest. Assemblies with the same strong name are expected to be identical.
During development process you will need strong name keys (public and private key pair) to be exposed to developer. Though the public key is available to all developer, the private key cannot be shared with everyone because of security reason. In such situations you can use delayed or partial signing to provide the public key, deferring the addition of the private key until the assembly is handed off.
The following steps outline the process to delay sign an assembly:
• Obtain the public key portion of the key pair created using the Strong Name tool (Sn.exe)
• Annotate the source code for the assembly with two custom attributes from System.Reflection:
o AssemblyKeyFileAttribute, which passes the name of the file containing the public key as a parameter to its constructor.
o AssemblyDelaySignAttribute, which indicates that delay signing is being used by passing true as a parameter to its constructor.
• The compiler inserts the public key into the assembly manifest and reserves space in the PE file for the full strong name signature. The real public key must be stored while the assembly is built so that other assemblies that reference this assembly can obtain the key to store in their own assembly reference.
• Because the assembly does not have a valid strong name signature, the verification of that signature must be turned off. You can do this by using the –Vr option with the Strong Name tool.
• Just before shipping sign the assembly using the –R option with the Strong Name tool.
Garbage Collection is a CLR feature which automatically manages memory. Programmers forget to release the objects while coding. CLR automatically releases objects when they are no longer referenced and in use. CLR runs on non-deterministic to see the unused objects and cleans them. One side effect of this non-deterministic feature is that we cannot assume an object is destroyed when it goes out of the scope of a function. Therefore, we should not put code into a class destructor to release resources.
Application Domain or AppDomain
The primary purpose of the AppDomain is to isolate an application from other applications. Win32 processes provide isolation by having distinct memory address spaces. This is effective, but it is expensive and doesn’t scale well. The .NET runtime enforces AppDomain isolation by keeping control over the use of memory – all memory in the AppDomain is managed by the .NET runtime, so the runtime can ensure that AppDomains do not access each other’s memory. Objects in different application domains communicate either by transporting copies of objects across application domain boundaries, or by using a proxy to exchange messages. MarshalByRefObject is the base class for objects that communicate across application domain boundaries by exchanging messages using a proxy. Objects that do not inherit from MarshalByRefObject are implicitly marshal by value. When a remote application references a marshal by value object, a copy of the object is passed across application domain boundaries.
Serialization is the process of converting an object into a stream of bytes. Deserialization is the opposite process of creating an object from a stream of bytes. Serialization/Deserialization is mostly used to transport objects (e.g. during remoting), or to persist objects (e.g. to a file or database). Serialization can be defined as the process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly containing the class, are converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created.
Types of Serialization
There are two types of serialization available:
• Binary serialization preserves type fidelity, which is useful for preserving the state of an object between different invocations of an application. For example, you can share an object between different applications by serializing it to the clipboard. You can serialize an object to a stream, disk, memory, over the network, and so forth. Remoting uses serialization to pass objects “by value” from one computer or application domain to another.
• XML serialization serializes only public properties and fields and does not preserve type fidelity. This is useful when you want to provide or consume data without restricting the application that uses the data. Because XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is an open standard, which makes it an attractive choice.
Ways to control serialization
There are two separate mechanisms provided by the .NET class library – XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code. XmlSerializer will refuse to serialize instances of any class that implements IDictionary, e.g. Hashtable. SoapFormatter and BinaryFormatter do not have this restriction.
All .NET assemblies have metadata information stored about the types defined in modules.This metadata information can be accessed by mechanism called as ‘Reflection’. System.Reflection can be used to browse through the metadata information. Using reflection you can also dynamically invoke methods using System.Type.Invokemember.
Boxing and Unboxing
Boxing permits any value type to be implicitly converted to type object or to any interface type implemented by value type.Boxing is process in which a object instances created and copying value types value in to that instance. Unboxing is vice versa of boxing operation where the value is copied from the instance in to appropriate storage location.
Runtime Callable Wrapper (RCW)
A .Net component communicates to a COM component through a .Net object that acts as a proxy to the COM component. This object is called RCW. When the .NET client activates the COM object, the runtime generates an instance of the runtime callable wrapper (RCW) to wrap the COM type. Although the RCW appears to be an ordinary object to .NET clients, its primary function is to marshal calls between a .NET client and a COM object. The wrapper marshals data according to the rules established by the interop marshaling service.
RCW can be generated in one of the following ways:
• Adding reference to the .Net project through Visual Studio.net.
• Using Type library import tool Tlbimp.exe.
• Using interopservices.System.runtime.
Create an AppDomain
AppDomains are usually created by hosts. Examples of hosts are the Windows Shell, ASP.NET and IE. When you run a .NET application from the command-line, the host is the Shell. The Shell creates a new AppDomain for every application. AppDomains can also be explicitly created by .NET applications.
View a Assembly contents
One can use the MSIL Disassembler (ILDASM.exe) to view Microsoft intermediate language (MSIL) information in a file. ILDASM.exe can be run over an .exe or .dll file to determine whether the file is managed. If the file is not managed, the tool displays a message stating that the file has no valid common language runtime header and cannot be disassembled. If the file is managed, the tool runs successfully. If the file being examined is a .NET assembly, this information can include the assembly’s attributes, as well as references to other modules and .Net assemblies. Hence it helps in determining whether a file is an assembly or part of an assembly, and whether the file has references to other modules or assemblies.
ILDASM tool can be found at [Visual Studio .NET Installation Path]\SDK\[VS Version]\Bin folder of the box where Visual Studio .Net is installed.
Generate strong names
Strong Name is only needed when we need to deploy assembly in GAC. Strong Names helps GAC to differentiate between two versions. Strong names use public key cryptography (PKC) to ensure that no one can spoof it. PKC use public key and private key concept.
Following are the step to generate a strong name and sign a assembly:
• Go to ‘Visual Studio Command Prompt’.
• After you are in command prompt type sn.exe -k ‘c:\test.snk’.
• After generation of the file you can view the SNK file in notepad.
Apply strong names to assembly
• After the SNK file is generated its time to sign the project with this SNK file.
• Click on project — properties and the browse the SNK file to the respective folder and compile the project.
Add/Remove an assembly from GAC
There are two ways to install .NET assembly in GAC:
• Using Microsoft Installer Package.You can get download of installer from http://www.microsoft.com.
• Using Gacutil. Goto ‘Visual Studio Command Prompt’ and type ‘gacutil –i (assembly_name)’.
Where (assembly_name) is the DLL name of the project.
Use COM Components in .NET
.NET components communicate with COM using Runtime Callable Wrapper (RCW). Following are the ways with which one can generate RCW:
• Adding reference in Visual Studio.net. Wrapper class is generated and placed in the ‘BIN’ directory.
• Using Type library import tool. Tlbimp.exe yourname.dll.
• Using interopservices.System.runtime.Interopservices namespace contains class TypeLib Converter which provides methods to convert COM classes and interface in to assembly metadata.
• Make your custom wrappers.If your COM component does not have type library then the only way to communicate is writing custom wrappers. That means communicating directly with COM components.
Forms authentication ticket and Forms authentication cookie
Forms authentication cookie is nothing but the container for forms authentication ticket. The ticket is passed as the value of the forms authentication cookie with each request and is used by forms authentication, on the server, to identify an authenticated user.
However, if we choose to use cookieless forms authentication, the ticket will be passed in the URL in an encrypted format. Cookieless forms authentication is used because sometimes the client browsers block cookies. This feature is introduced in the Microsoft .NET Framework 2.0.
Sequence of events fired when a page is requested • Page_Init: Occurs only once when the page is requested first time. On subsequent post-backs this does not occur.
• Page_Load: Occurs everytime when the page is posted back including the first time when the page is requested.
• Control events
Server controls like Datagrid, DataList, Repeater can have other child controls inside them. Eg., a DataGrid can have combobox inside it. These child controls do not raise their events by themselves, rather they pass the event to the container parent (which can be a datagrid, datalist, repeater), which passed to the page as ‘ItemCommand’ event. As the child control send their events to parent this is termed as event bubbling.
Use of @Register directive
@Register directive informs the compiler of any custom server control added to the page.
Use of SmartNavigation property
It’s a feature provided by ASP.NET to prevent flickering and redrawing when the page is posted back. This works only in IE.
AppSetting Section in ‘Web.Config’ file
Web.config file defines configuration for a webproject. Using ‘AppSetting’ section we can define user defined values.Example below defined is ‘ConnectionString’ section which will be used through out the project for database connection.
Value types and Reference types
A data type is a value type if it holds the data within its own memory allocation. Value types are either allocated on the stack or in-line in a structure. Variables that are value types each have their own copy of the data, and therefore operations on one variable do not affect other variables. Examples of value types:
• All numeric data types
• Boolean, Char, and Date
• All structures, even if their members are reference types
• Enumerations, since their underlying type is always SByte, Short, Integer, Long, Byte, UShort, UInteger, or ULong
A reference type contains a pointer to another memory location that holds the data. reference types are allocated on the heap. Reference types can be self-describing types, pointer types, or interface types. Variables that are reference types can refer to the same object; therefore, operations on one variable can affect the same object referred to by another variable.
Examples of reference types:
• All arrays, even if their elements are value types
• Class types, such as Form
NOTE: You can assign either a reference type or a value type to a variable of the Object data type. You can find out whether an Object variable is acting as a reference type or a value type by passing it to the IsReference method of the Microsoft.VisualBasic.Information class. Eg. Microsoft.VisualBasic.Information.IsReference(System.Object)
VB.NET and C#
Both VB.NET and C# are languages that are supported by .Net Framework. .Net applications are developed using these languages like other .Net compatible languages. The obvious difference between these two languages is the syntax. Both use the same framework and performance wise also both are almost same. Here is the list of some major differences between them:
Advantages VB.NET :
• Has support for optional parameters which makes COM interoperability much easier.
• Late binding is supported with ‘Option Strict Off’.
• Legacy VB functionalities can be used by using Microsoft.VisualBasic namespace.
• Has the WITH construct which is not in C#.
• While using Visual Studio .NET for development, VB.NET code is compiled in the background, making it useful for the developer to catch some of the quick errors. This may slows down IDE considerably as the project gets larger.
• Support for named indexers.
Advantages of C#:
• Optional parameters are not supported. Alternate to this is to have overloaded methods though.
• The using statement, which makes unmanaged resource disposal simple.
• Access to Unsafe and unmananged code. This allows pointer arithmetic etc, and can improve performance in some situations, though it comes with a cost of loosing the normal safety of C#.
System exceptions and Application exceptions
All exception derives from Exception Base class. Exceptions can be generated programmatically or can be generated by system. Application Exception serves as the base class for all application specific exception classes. It derives from Exception but does not provide any extended functionality. You should derive your custom application exceptions from Application Exception. Application exception are used when we want to define user defined exception. While system exception are all which are defined by .NET.
NameSpace and Assembly
Following are the differences between namespace and assembly:
• Assembly is physical grouping of logical units.
• Namespace logically groups classes. Namespace can span multiple assembly.
Dataset and Data Reader
Following are the major difference between Dataset and Data Reader:
• Dataset is a disconnected architecture. So if we want to cache data and pass to a different tier Dataset forms the best choice.
• It has decent XML support.
• It can have one or more tables and relation between tables. So if application access data from more than one datasource, Dataset forms the best choice.
• Dataset support move back and forward between records/rows.
• As Dataset carries considerable overhead because of relations, multiple tables etc speed is slower than DataReader.
• Data Reader has live connection while reading data.
• Points to one record at a time.
• Has Forward only support.
• Has readonly access.
• Data Reader meant specially for speed performance.
Constant and Readonly
Readonly and const both are same they can never be modified. But readonly allows initializing variables at run time. const must be initialized to a compile time constant. For example,
public readonly DateTime dt = DateTime.Now
public const int i = 2;
Constant and Static Readonly
The value of a static readonly field is set at run time, and can thus be modified by the containing class, whereas the value of a const field is set to a compile time constant. Static Readonly is typically used if the type of the field is not allowed in a const declaration, or when the value is not known at compile time.