Friday 5 February 2016

Some Features of .NET and Common Language Runtime (CLR)

What Is .NET & CLR?

.NET is a platform for distributed Web/Desktop/Database applications. Distributed applications are composed of disparate resources in multiple locations—the database might be in India, the inventory control software in Singapore, and the data entry software in Bangladesh. It offers a new model for sharing components. The Common Language Runtime is at the heart of the .NET framework and consists of infrastructure and services to enable global-scale hosting.

Common Language Runtime(CLR) diagram
.NET offers a multi-language platform that gives the freedom to choose a language. All features of a .NET platform are available to any .NET programming language, and application components can be written in multiple languages. It has highly leveraged tools. Debuggers, profilers, code coverage analyzers, and so on work for all languages.
It simplifies deployment and management. Applications are grouped into assemblies, which are the units of deployment, versioning, and security. Assemblies are like DLLs, but self-describing through a manifest. .NET has a system of zero-impact install. Applications and Language components can be shared or private, and applications enjoy side-by-side execution. Multiple versions of the same component can co-exist, even in the same process.

Common Language Runtime (CLR) features

The Common Language Language Runtime is robust and secure because it includes the following features:
  • Automatic lifetime management
  • Garbage collection for all .NET objects, Multi-generational mark-and-compact garbage collection (GC)
  • No stray pointers, no circular references
  • Self-configuration, dynamic tuning
  • Exception handling, Error handling as a first-class concept (not Boolean or HRESULTs), Dramatically improved error reporting
  • Windows Language SEH integration
  • Several compilation models: Native (for example, Managed C++) and Microsoft Intermediate Language (MSIL or IL) (for example, VB and C#)
  • Lack of an interpreter as the code compiles at install-time or runtime
  • Code correctness and type safety, Verifiable IL that guarantees type safety
  • No unsafe casts, no uninitialized variables, no out-of-bounds array indexing
  • Evidence-based security, Both code- and user-based security
  • Extensible permissions

Simplicity to Develop in .NET

The simplicity that .NET provides is based on some careful design, including the following features:
  • Code is organized in hierarchical namespaces and classes.
  • A unified type system is in use.
  • Everything is an object—no variants, one string type—and all character data is Unicode.
  • All development is component oriented.
  • Properties, methods, events, and attributes are first class constructs.
  • Developing with .NET provides design-time functionality.
  • The entire system is factored and extensible.
  • Any .NET class is available for you to extend through inheritance.
  • Unlike COM, you’re using and extending the class itself, not a “wrapper.”
  • Plug-and-play components and subsystems are constructed into the infrastructure.
  • There is pervasive cross-language inheritance.

CLR Features and Benefits

CLR Features and Benefits

Common Language Runtime is a heart of the .net framework. It actually manages the code during Execution. The Code that runs under the CLR is called “Managed Code”. The code that is executed under .net runtime gets benefits like cross language inheritance, cross language exception handling, enhanced Security, Versioning and development support, a simplified model for component interaction, debugging and Profiling services.
CLR Managed Code Execution Process
  • The Process of Compiling and executing managed code is given below
    When you compile a program written in any of language that target CLR., the compiler translate it into Microsoft Intermediate Language (MSIL) or Intermediate Language (IL). It does not depend on Language and always get translated to IL, This ensures language Interoperability.
  • In addition to translating the code into IL, Compiler also produces metadata about the program during the process of compilation. Metadata contains the description of the program such as Classes and interfaces, the dependencies etc.
  • The IL and the metadata are linked in an assembly.
  • The Compiler creates .EXE or .Dll File.
  • When you execute the .exe or .dll file, the code and all the other relevant information from the base class library is sent to the class Loader, who loads the code in memory.
  • Before code gets executed, The Just-in-Time (JIT) compiler translates the code from IL to native code (machine code). CLR supplies a JIT compiler for each supports CPU architecture. During the process of compilation, the JIT compiler compiles only the code that is required during execution instead of compiling the complete IL code.
  • During JIT Compilation, the code is also checked for type safety. Type Safety ensures that object are accessed in a compatible way. Type Safety also ensures that objects are isolated from each other and are therefore safe from any malicious corruption.
  • After Converted to native code, converted code is sent to .net runtime manager.
  • The .net runtime manager executed the code, while executed the code, a security check is performed to ensure that the code has the appropriate permission for accessing the available resources.

Features provided by CLR

Some of the features provided by the CLR are as follows:
  • Automatic memory management: - The CLR provides the Garbage Collection feature for managing the life time of object. This relives a programmer from memory management task.
  • Standard Type System: - The CLR Implement a formal Specification called the Common Type System (CTS). CTS is important part of rules that ensures that objects written in different language can interact with each other.
  • Language interoperability: - It is the ability of an application to interact with another application written in a different programming language. Language interoperability helps maximum code reuse. The CLR provides support for language interoperability by specifying and enforcing CTS and by providing metadata.
  • Platform Independence: - The Compiler compiles code language, which is CPU-independent. This means that the code can be executed from any platform that supports the .Net CLR.
  • Security Management: - In .net platform, Security is achieved through the code access Security (CAS) model. In
    the model, CLR enforces the restriction an managed code through the object called “permissions”. The CLR allows the code to perform only that task for which it has permissions. In other words, the CAS model specifies what the code can access instead of specifies who can access resources.
  • Type Safety: - This feature ensures that object is always accessed in compatible ways. Therefore the CLR will prohibit a code from assign a 10-byte value to an object that occupies 8 bytes.


    Benefits of CLR
Followings are some of benefits of the CLR
  • Performance improvement
  • The ability to easily use components developed in other languages.
  • Extensible types provided by library.
  • New Language features such as inheritance, interfaces etc.
  • Complete Object-Oriented design.
  • Very Strong Type Safety.
  • A good blend of Visual Basic simplicity and c++ power.
  • Syntax and keywords similar to c and c++.
  • Use of delegates rather than function pointers for increased type safety and security.

Code Execution Process

Code Execution Process

Code Execution Process
http://www.c-sharpcorner.com/UploadFile/8911c4/code-execution-process/

Code Execution Process

The Code Execution Process involves the following two stages:


  1. Compiler time process.
  2. Runtime process.

Code-Execution-Process.jpg

1. Compiler time process

  1. The .Net framework has one or more language compliers, such as Visual Basic, C#, Visual C++, JScript, or one of many third-party compilers such as an Eiffel, Perl, or COBOL compiler.
  2. Any one of the compilers translate your source code into Microsoft Intermediate Language (MSIL) code.
  3. For example, if you are using the C# programming language to develop an application, when you compile the application, the C# language compiler will convert your source code into Microsoft Intermediate Language (MSIL) code.
  4. In short, VB.NET, C# and other language compilers generate MSIL code. (In other words, compiling translates your source code into MSIL and generates the required metadata.)
  5. Currently "Microsoft Intermediate Language" (MSIL) code is also known as "Intermediate Language" (IL) Code or "Common Intermediate Language" (CIL) Code.

    SOURCE CODE -----.NET COMLIPER------> BYTE CODE (MSIL + META DATA)

2. Runtime process.

  1. The Common Language Runtime (CLR) includes a JIT compiler for converting MSIL to native code.
  2. The JIT Compiler in CLR converts the MSIL code into native machine code that is then executed by the OS.
  3. During the runtime of a program the "Just in Time" (JIT) compiler of the Common Language Runtime (CLR) uses the Metadata and converts Microsoft Intermediate Language (MSIL) into native code.

    BYTE CODE (MSIL + META DATA) ----- Just-In-Time (JIT) compiler------> NATIVE CODE

Notes:

When you compile a C# application or any application written in a CLS-compliant language, the application is compiled into MSIL. This MSIL is then further compiled into native CPU instructions when the application is executed for the first time by the CLR. (Actually, only the called functions are compiled the first time they are invoked.)


  1. You write source code in C#.
  2. You then compile it using the C# compiler (csc.exe) into an EXE.
  3. The C# compiler outputs the MSIL code and a manifest into a read-only part of the EXE that has a standard PE (Win32-portable executable) header.
  4. When the compiler creates the output, it also imports a function named "_CorExeMain" from the .NET runtime.
  5. When the application is executed, the operating system loads the PE, as well as any dependent dynamic-link libraries (DLLs), such as the one that exports the "_CorExeMain" function (mscoree.dll), just as it does with any valid PE.
  6. However, since the operating system obviously can't execute the MSIL code, the entry point is just a small stub that jumps to the "_CorExeMain" function in mscoree.dll.
  7. The "_CorExeMain" function starts the execution of the MSIL code that was placed in the PE.
  8. Since MSIL code cannot be executed directly, because it's not in a machine-executable format, the CLR compiles the MSIL using the Just-In-Time (JIT) compiler (or JITter) into native CPU instructions as it processes the MSIL. The JIT compiling occurs only as methods in the program are called. The compiled executable code is cached on the machine and is recompiled only if there's some change to the source code.

Monday 1 February 2016

.NET Architecture

http://www.c-sharpcorner.com/UploadFile/8ef97c/interview-question-on-net-framework-or-clr/


Question 1. What is the .NET Framework?

Answer: The .NET is a Framework, which is a collection of classes of reusable libraries given by Microsoft to be used in other .NET applications and to develop, build and deploy many types of applications on the Windows platform including the following:
  • Console Applications
  • Windows Forms Applications
  • Windows Presentation Foundation (WPF) Applications
  • Web Applications
  • Web Services
  • Windows Services
  • Services-oriented applications using Windows Communications Foundation (WCF)
  • Workflow-enabled applications using Windows Workflow Foundation(WF)
That primarily runs on the Microsoft Windows Operating System.

Microsoft Windows operating system
Question 2. What is CLR?

Answer: The CLR stands for Common Language Runtime and it is an Execution Environment. It works as a layer between Operating Systems and the applications written in .NET languages that conforms to the Common Language Specification (CLS). The main function of Common Language Runtime (CLR) is to convert the Managed Code into native code and then execute the program. The Managed Code compiled only when it is needed, that is it converts the appropriate instructions when each function is called. The Common Language Runtime (CLR)’s just in time (JIT) compilation converts Intermediate Language (MSIL) to native code on demand at application run time.

When a .NET application is executed at that time the control will go to Operating System, then Operating System create a process to load CLR.
The program used by the operating system for loading CLR is called runtime host, which are different depending upon the type of application that is desktop or web based application i.e.

The runtime host for desktop applications is API function called CorbinToRuntime.

The runtime host for web based applications is ASP.NET worker process (aspnet-wp.exe).

process to load CLR

CLR runtime engine comes with set of services, which are classified as follows


  • Automatic memory management
  • Security Management
  • Language interoperability
  • Type Safety
  • Exception Manager
  • Garbage Collector
  • IL to Native compiler
  • Debug Manager



CLR services
  • Assembly Resolver
  • Assembly Loader
  • Type Checker
  • COM marshalled
  • Debug Manager
  • Thread Support
  • IL to Native compiler
  • Exception Manager
  • Garbage Collector
To know more about them follow the link:
Question 3. What is CTS?

Answer: The Common Type System (CTS) standardizes the data types of all programming languages using .NET under the umbrella of .NET to a common data type for easy and smooth communication among these .NET languages.

CTS

To implement or see how CTS is converting the data type to a common data type, for example, when we declare an int type data type in C# and VB.NET, then they are converted to int32. In other words, now both will have a common data type that provides flexible communication between these two languages.

For more details follow the link:
Question 4. What is CLS?

Answer: One of the important goals of .NET Framework is to support Multiple Languages. This is achieved by CLS. For multiple languages to interoperate, it is necessary that they should go on in common in certain features such as Types that are used. For example, every language has its own size and range for different data types. Thus CLS is the agreement among language designers and class library designers concerning these usage conventions.

CLS

Follow the link for more details:
Question 5. What is managed code?

Answer: The resource, which is within your application domain is, managed code. The resources that are within domain are faster.

The code, which is developed in .NET framework, is known as managed code. This code is directly executed by CLR with help of managed code execution. Any language that is written in .NET Framework is managed code.

Managed code uses CLR which in turn looks after your applications by managing memory, handling security, allowing cross - language debugging, and so on.

CLR

For more details follow the link:
Question 6. What is MSIL?

Answer: When we compile our .NET code then it is not directly converted to native/binary code; it is first converted into intermediate code known as MSIL code which is then interpreted by the CLR. MSIL is independent of hardware and the operating system. Cross language relationships are possible since MSIL is the same for all .NET languages. MSIL is further converted into native code.

MSIL

For more details follow the link:
Question 7. What is JIT?

Answer: A Web Service or Web Forms file must be compiled to run within the CLR. Compilation can be implicit or explicit. Although you could explicitly call the appropriate compiler to compile your Web Service or Web Forms files, it is easier to allow the file to be complied implicitly. Implicit compilation occurs when you request the .asmx via HTTP-SOAP, HTTP-GET, or HTTP-POST. The parser (xsp.exe) determines whether a current version of the assembly resides in memory or in the disk. If it cannot use an existing version, the parser makes the appropriate call to the respective compiler (as you designated in the Class property of the .asmx page).

When the Web Service (or Web Forms page) is implicitly compiled, it is actually compiled twice. On the first pass, it is compiled into IL. On the second pass, the Web Service (now an assembly in IL) is compiled into machine language. This process is called Just-In-Time JIT compilation because it does not occur until the assembly is on the target machine.

JIT Types:

JIT Types

Follow the link for more details:
Question 8. What is portable executable (PE)?

Answer: Every .NET program first compiles with an appropriate compiler like if we write a program in C# language then it gets compiled by C# compiler (i.e. csc.exe).

In .NET framework every program executes (communicate) in an operating system by using CLR (Common Language Runtime).

portable executable

Managed module is standard windows Portable Executable (PE) file which contains the following parts.
  • PE Header

    It is similar to common object file format.
  • CLR Header

    This contains CLR version required to run this managed module, location & metadata. This also contains entry point of function i.e. the address of entry point of function.
  • Metadata

    This contains table information means variable with its data types and default values, functions / methods which are declared & defined in our program.
Follow the link for more details:
Question 9. What is an application domain?

Answer: An Application Domain is a logical container for a set of assemblies in which an executable is hosted. As you have seen, a single process may contain multiple Application Domains, each of which is hosting a .NET executable. The first appdomain created when the CLR is initialized is called the default AppDomain and this default one is destroyed when the Windows process is terminated.
  • An AppDomain can be independently secured.
  • An AppDomain can be unloaded.
  • Independently configured.
  • No mutual intervention by multiple appdomains.
  • Performance
Windows process

How does an AppDomain get created


The AppDomain class is used to create and terminate Application Domains, load and unload assemblies and types and enumerates assemblies and threads in a domain. The following table shows some useful methods of the AppDomain class:
Methods Description
CreateDomain()It allows us to create a new Application Domain.
CreateInstance()Creates an instance of type in an external assembly.
ExecuteAssembly()It executes an *.exe assembly in the Application Domain.
Load()This method dynamically loads an assembly into the current app domain.
UnLoad()It allows us to unload a specified AppDomain within a given process.
GetCurrentThread()Returns the ID of the active thread in the current Application Domain.
In addition, the AppDomain class also defined as a set of properties that can be useful when you wish to monitor the activity of a given Application Domain.
Properties Description
CurrentDomain Gets the Application Domain for the currently executing thread.
FriendlyName Gets the friendly name of the current Application Domain.
SetupInformation Get the configuration details for a given Application Domain.
BaseDirectory Gets the directory path that the assembly resolver uses to probe for assemblies.
Follow the link for more details:
Question 10. What is an assembly?

Answer: An Assembly is a basic building block of .NET Framework applications. It is basically compiled code that can be executed by the CLR. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An Assembly can be a DLL or exe depending upon the project that we choose.

Assemblies are basically the following two types:
  1. Private Assembly
  2. Shared Assembly
Follow the link for more details:
Question 11. What are the contents of assembly?

Answer: Assembly
  • An Assembly is a basic unit of application deployment and versioning.
  • An Assembly is also called the building block of a .NET application.
  • An Assembly is either a .exe or .dll file.
An Assembly structure consists of the following parts:
  • Assembly manifest (name, language and version).
  • CIL code (logic part).
  • Type information (Datatype).
  • Resources.
Follow the link for more details:
Question 12. What are the different types of assembly?

Answer: An Assembly contains metadata and manifest information. The reason for the emergence of assembly concept was to overcome the common "DLL Hell" problem in COM. The assembly contains all the code, resources, metadata and even version information. Metadata contains the details of every "type" inside the assembly. In addition to metadata, assemblies also have a special file called Manifest. It contains information about the current version of the assembly, culture information, public key token if available and other related information.

There are in all 3 different types of assemblies:
  1. Private Assembly
  2. Shared or Strong named assembly
  3. Satellite assembly
Follow the link for more details:
Question 13. What is a dynamic assembly?

Answer: Technically, the act of loading external assemblies on demand is known as Dynamic Loading. Using the Assembly class, we can dynamically load both private and shared assemblies from the local location to a remote location as well as, explore its properties.

To illustrate dynamic loading, we are creating a console based application that loads an external TestLib.dll assembly. During the execution, the application asks the user to specify the dynamic loading assembly name and that reference is passed to the helper method that is responsible for loading the assembly.

Follow the link for more details:
Question 14. What is GAC?

Answer: The GAC is a shared location of computer where we can put an assembly so that it will be accessible from many locations, I mean it is accessible from another project or application. It's always a good practice to provide a strong name to a public assembly, I mean the assembly to be registered in the GAC,  otherwise the DLL hell problem may occur.

Problems that occurred
I have seen DLLs added to the GAC that you can't remove - very frustrating. I have seen registered DLLs into the cache - verified everything is there ok using ILDASM only to find the DLLs are no longer in the GAC.

Strongly naming the assembly
When doing this make sure you get the directory slashes \\ correct within the assembly file (assembly.cs). - if not, you will get errors whilst the code is looking for the .snk file. If you get errors which leave you scratching your head - best bet is to remove the .snk file and start over.

Project References
Also be careful and watch where you build projects as the referenced DLLs can easily be built to the development instead of the release folder - sometimes even when you specify the release folder. This can be very, very frustrating.

Conclusion
My conclusion on using the GAC was only use it if you really need to as it isn't the 'end of DLL hell' as first thought. Also only use it if you are using a DLL that is shared by other projects. Don't put it in the GAC if you don't have to.

For more details follow the link:
Question 15. What is a garbage collector?

Answer: The Garbage Collector (GC) is the part of the .NET Framework that allocates and releases memory for your .NET applications. The Common Language Runtime (CLR) manages allocation and deallocation of a managed object in memory. C# programmers never do this directly, there is no delete keyword in the C# language. It relies on the garbage collector.

Example
Assume the managed heap contains a set of objects named A, B, C, D, E, F and G. During garbage collection, these objects are examined for active roots. After the graph has been constructed, unreachable objects (that we will assume are objects C and F) are marked as garbage in reddish color in the following diagram.

manage heap

For more details follow the link:
Question 16. What are generations and how are they used by the garbage collector?

Answer: Basically the generation of Garbage Collection (GC) shows the life of objects, it means it defines how long an object will stay in the memory. It's categorized into the following three generations:
  • Generation 0
  • Generation 1
  • Generation 2
generations

For more details follow the link: