Your SlideShare is downloading. ×
  • Like
  • Save
Dotnet ch1
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Now you can save presentations on your phone or tablet

Available for both IPhone and Android

Text the download link to your phone

Standard text messaging rates apply
Published

Basic about .net platform

Basic about .net platform

Published in Education , Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
1,525
On SlideShare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
1
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Chapter 1 The .NET Platform1.1 Introduction:The current programmer could perform the self-inflicted knowledge to the current technology that isthe software developments. The languages (C++,Visual Basic 6.0, Java), frameworks (OWL, MFC,ATL, STL), architectures (COM, CORBA, EJB), and APIs (such as .NET’s Windows Forms andGDI+ libraries) that were touted as the silver bullets of software development eventually becomeovershadowed by something better or at the very least something new. Regardless of thefrustration you can feel when upgrading your internal knowledge base, it is frankly unavoidable.To this end, the goal of this book is to examine the details of Microsoft’s current offering withinthe landscape of software engineering: the .NET platform and the C# programming language.The .net platform is related to the assembly, CIL (common intermediate language) and thecompilation.The key features of C# programming language are the relationship between the various .netframework i.e. CLR – common language runtime CTS – common type system CLS – common language specificationDue to these reason .net platform is independent and language-agnostic.1.2 Understanding the Previous State of AffairsThere are numerous limitations of the previous state of affairs (after all, admittingyou have a problem is the first step toward finding a solution).1.2.1 Life As a C/Windows API ProgrammerThe first obvious problem is that C is a very terse language. C developers are forced toContend with manual memory management, ugly pointer arithmetic, and ugly syntacticalconstructs. furthermore, given that C is a structured language, it lacks the benefits provided bythe object-oriented approach. When you combine the thousands of global functions and datatypes defined by the Win32 API to an already formidable language, it is little wonder thatthere are so many buggy applications floating around today.1.2.2 Life As a C++/MFC ProgrammerIn many ways, C++ can be thought of as an object-oriented layer on top of C. Thus, eventhough C++ programmers benefit from the famed “pillars of OOP” (encapsulation,inheritance, and polymorphism), they are still at the mercy of the painful aspects of the Clanguage (e.g., manual memory management, ugly pointer arithmetic, and ugly syntacticalconstructs). Despite complexity many C++ frame work exist today. Example: Microsoft FoundationClasses (MFC) provides the developer with a set of C++ classes that facilitate the construction ofWin 32 applications. Main role of MFC is to wrap a sane subset of the raw Win 32 API behind anumber of classes, magic macros, and numerous code- generation tools.1.2.3 Life As a Visual Basic 6.0 ProgrammerVB 6 is popular due to its ability to build complex user interfaces, code libraries (egg COM servers)and data access login with minimal fuss and bother.VB6 hides the complexities of the raw win32 API from view using a number of integrated code
  • 2. wizards, intrinsic data types, classes and VB-specific functions.There are numerous Disadvantages:1. VB6 is not fully object oriented rather it is object aware.2. VB6 doesn’t allow the programmer to establish is-a relationship between classes and has nointrinsic support for parameterized class construction.3. VB6 doesn’t provide the ability to build multithreaded applications unless you are willing todrop down to low-level API calls (which is complex at best and dangerous at worst).The Visual Basic language used within the .NET platform(which is often referred to asVB.NET), has very little relationship to VB6. For example, modern day VB supports operatoroverloading, classical inheritance, type constructors and generics.1.2.4 Life As a Java/J2EE ProgrammerJava programming language is completely object oriented, hence supports platform independence. Asa language, Java cleans up many unsavory syntactical aspects of C++. As a platform, Javaprovides programmers with a large number of predefined packages that contain various typedefinitions. Using these types, Java programmers are able to build “Pure Java” applicationscomplete with database connectivity, messaging support, web-enabled front ends, and a richdesktop user interface (among other services).Java supports with large number of predefinedpackages.one potential problem is that using Java typically means that you must use Java front to backduring the development cycle.Java is not appropriate for much graphical or numerical application;therefore better approach is used to use the lower level language such as C++.While Java doesprovide a limited ability to access non-Java APIs, there is little support for true cross-languageintegration.1.2.5 Life As a COM DeveloperCOM (component object model) module as apiece of software which has been written so that it isproperly encapsulated and can used by other class without them knowing how the COM object isimplemented internally.A COM object is microsoft version of javabeans.it is reuse through interface.One benifit is a binary COM server is that it can be accesed in a language- independent in manner.Another benifit of COM is its location-transparent nature.Some of the complexity of COM is due to the simple fact that applications that are woventogether using diverse languages are completely unrelated from a syntactic point of view. Forexample, JScript has a syntax much like C, while VBScript is a subset of VB6.Given that each language has its own unique type system, COM programmers typically neededto be very careful with building public methods on public COM classes. For example, if a C++developer needed to create a method that returned an array of integers to a VB6 application, theywould be up to their eyeballs in complex COM API calls to construct a SAFEARRAY structure,which could easily require dozens of line of code. In the COM world, the SAFEARRAY datatype is the only way to build an array that all COM frameworks understand. If the C++ developersimply returned a native C++ array, VB6 would have no clue what to do with it.Similarcomplexities could be found when building methods that manipulate simple string data,references to other COM objects, or even a trivial BOOLEAN value! To put it politely, COMprogramming is a very asymmetrical discipline.1.2.6 Life As a Windows DNA Programmer
  • 3. The programmer can build web based applications using Windows DNA(Distributed iNternetArchitecture). Distributed interNet Applications Architecture (DNA) is also quite complex. Someof this complexity is due to the simple fact that Windows DNA requires the use of numeroustechnologies and languages (ASP, HTML, XML, JScript, VBScript, and COM[+], as well as a dataaccess API such as ADO). One problem is that many of these technologies are completelyunrelated from a syntactic point of view. For example, JScript has a syntax much like C, whileVBScript is a subset of VB6. The COM servers that are created to run under the COM+ runtimehave an entirely different look and feel from the ASP pages that invoke them. The result is a highlyconfused mish- mash of technologies.1.3 The .NET Solution.net framework provides a solution and a model for the system. Core features of .NET solutions are(A) Comprehensive interoperability with existing code: This is (of course) a good thing.Existing COM binaries can commingle (i.e., interop) with newer .NET binaries and vice versa.(B) Support for numerous programming languages: .NET applications can be created usingany number of programming languages (C#, Visual Basic, F#, S#, and so on).(C) A common runtime engine shared by all .NET-aware languages: The engine is a well-defined set of types that each .net language understands and this engine is common to all the crossLanguages.(D)Complete and total language integration:.NET supports cross language inheritance,crosslanguage exception handling,and cross language debugging of code.(E)Base Class Library: The Base Class Library (BCL), part of the Framework Class Library (FCL),is a library of functionality available to all languages using the .NET Framework. The BCL providesclasses which encapsulate a number of common functions, including file reading and writing, graphicrendering, database interaction, XML document manipulation and so on.(F) No more COM plumbing: IClassFactory,IUnknown, IDispatch, IDL code, and the evilvariant- compliant data types (e.g. ,BSTR, SAFEARRAY) have no place in a .NET binary.Because of variance in data types .net binaries are not generated properly hence COM is not required.(G) A truly simplified deployment model: Under .NET, there is no need to register a binaryUnit into the system registry. Furthermore, .NET allows multiple versions of the same *.dll toExist in harmony on a single machine.The .NET Framework includes design features and tools that help manage the installation ofcomputer software to ensure that it does not interfere with previously installed software, and that itconforms to security requirements.1.4 The Building Blocks Of .Net platform (the CLR, CTS, and CLS)1.4.1.NET platformThe Microsoft .NET platform consist of five main components shows in Figure 1.1 Visual studio .NET
  • 4. .NET Enterprise .NET Framework .NET Building Block service Service Operating System Figure1.1:MS .NET PlatformVisual studio .NET application work by using service of the .NET framework. The .NETframework ,in turn access the operating system and computer hardware.On top of the operating system is a collection of specialized server product that shorten the timerequired large scale business systems. these server product include application center ,internetsecurity and acceleration server and SQL server.Microsoft provide number of building block services(officially called .NET services) thatapplication developer can used for example .NET passport and .NET Alert..Net passport allows you to use a single username and password at all website that supportpassport authentication..NET alert providers, such as a business, to alert their consumers withimportant or to up-to-the minute information.Enterprise service includes some new features for .NET components that are not available toCOM component .its support allow you to export a plain .NET object as .NET remote object.Plain .NET object we means class that do not inherit from a specific infrastructure base classsuch as service component.Top layer of .NET architecture is a development tool called VisualStudio .NET which makes possible the rapid developments of the Web services and otherapplication1.4.2 .NET FrameworkThe .NET Framework is an environment for building, deploying, and running Web Services andother applications. The key components of the .NET Framework are the CLR and the .NETFramework class library. The .NET Framework is a managed, type safe, multi-languageenvironment for application development and execution.With .NET, you can develop various types of applications as follows: • Windows Form based applications (Rich client applications). • Console based applications. • ASP.NET Web applications (Browser based applications). • Web services (Programmable application component that provides some useful functionality, such as application logic, and is available to any number of potentially incongruent systems through the use of Internet standards such as XML and HTTP). • Component Libraries (Components which encapsulate some business logic). • Windows Custom Controls (Your own windows controls). • Web Custom Controls (Your own web controls). • Windows Services (Applications that run as services in the background).
  • 5. Figure 1.2: .NET FrameworkThree key entities are CLS, CTS and CLR.1.4.3 CLR(Common Language Runtime) The Common Language Runtime is the underpinning of the .NET Framework. CLR takes careof code management at program execution and provides various beneficial services such asmemory management, thread management, security management, code verification, compilation,and other system services. The managed code that targets CLR benefits from useful features suchas cross-language integration, cross-language exception handling, versioning, enhanced security,deployment support, and debugging.1.4.4 Common Type System (CTS)Common Type System (CTS) describes how types are declared, used and managed in theruntime and facilitates cross-language integration, type safety, and high performance codeexecution.The common types system supports two general categories of types.(a)value types :value types contains their data ,and instance of value types are either allocated on thestack or allocated inline in a structure. Value types can be built-in (implemented by the runtime),user-defined or enumerations.(b)Reference types: reference types store a reference to the value’s memory address, and allocatedon the heap. Reference types can be self-describing types, pointer types or interface types.1.4.5 Common Language Specification (CLS)“CLS is the collection of rules and constrains that every language (that seeks to achieve .NETcompatibility) must follow.”One of the important goals of .NET Framework is to support Multiple Languages. This isachieved by CLS. For multiple languages to interoperate, it is necessary that they should go on incommon in certain features such as Types that are used. For e. g. Every Language has its ownSize and range for different data types. Thus CLS is the agreement among language designersand class library designers concerning these usage conventions.
  • 6. 1.5 Role of Base Class LibrariesIn addition to the CLR and CTS/CLS specifications, the .NET platform provides a base class library(Figure 1.3)that is available to all .NET programming languages. Not only does this base classlibrary encapsulate various primitives such as threads, file input/output (I/O), graphical rendering,and interaction with various external hardware devices, but it also provides support for a number ofservices required by most real-world applications. Figure 1.3:base class library1.6 Various C# features: C# is a hybrid of numerous languages, the result is a product thatis as syntactically clean—if not cleaner—as Java, is about as simple as VB6, and provides justabout as much power and flexibility as C++ (without the associated ugly bits). Here is a partiallist of core C# features that are found in all versions of the language. • No pointers required! C# programs typically have no need for direct pointer manipulation. • Automatic memory management through garbage collection. C# does not support delete keyword. • Formal syntactic constructs for classes, interfaces, structures, enumerations, and delegates. • The C++-like ability to overload operators for a custom type, without the complexity. • Support for attribute-based programming. This brand of development allows us to annotate types and their members to further qualify their behavior. • The ability to build generic types and generic members. Using generics, we are able to build very efficient and type-safe code that defines numerous placeholders specified at the time we interact with the generic item. • Support for anonymous methods, which allow us to supply an inline function anywhere a delegate type is required.With the release of .NET 2.0 (circa 2005), the C# programming language was updated to support
  • 7. numerous following features:•The ability to build generic types and generic members. Using generics, you are able to buildvery efficient and type-safe code that defines numerous placeholders specified at the time youinteract with the generic item.• Support for anonymous methods, which allow you to supply an inline function anywhere adelegate type is required.• Numerous simplifications to the delegate/event model, including covariance,contravariance,and method group conversion•The ability to define a single type across multiple code files (or if necessary, as an in-memoryrepresentation) using the partial keyword..NET 3.5 (released circa 2008) added even more functionality to the C# programming language,including the following features:•Support for strongly typed queries (e.g., LINQ) used to interact with various forms of data.• Support for anonymous types that allow you to model the shape of a type rather than itsbehavior.• The ability to extend the functionality of an existing type (without sub-classing) usingextension methods.• Inclusion of a lambda operator (=>), which even further simplifies working with .NET delegatetypes.• A new object initialization syntax, which allows you to set property values at thetime of object creation.The current release of the.NET platform version 4.0 updates C# yet again with a handful offeatures.• Support for optional method parameters, as well as named method arguments.• Support for dynamic lookup of members at runtime via the dynamic keyword.• Related to the previous point, .NET 4.0 greatly simplifies how C# applications can interact withlegacy COM servers by removing the dependency on interop assemblies and support for optionalref arguments.• Working with generic types is much more intuitive, given that you can easily map generic datato and from general System.Object collections via covariance and contravariance.Perhaps the most important point to understand about the C# language is that it can only producecode that can execute within the .NET runtime (you could never use C# to build a native COMserver or an unmanaged C/C++ API application). Officially speaking, the term used to describethe code targeting the .NET runtime is managed code. The binary unit that contains the managedcode is termed an assembly (more details on assemblies in just a bit). Conversely, code thatcannot be directly hosted by the .NET runtime is termed unmanaged code.1.7 Additional .NET-Aware Programming LanguagesUnderstand that C# is not the only language that can be used to build .NET applications. Whenyou install the freely downloadable Microsoft .NET 4.0 Framework Software Development Kit(SDK), as well as when you install Visual Studio 2010, you will be given five managedlanguages out of the box: C#,Visual Basic, C++/CLI, JScript .NET, and F#.In addition to the managed languages provided by Microsoft, there are .NET compilers forSmalltalk, COBOL, and Pascal (to name a few).1.7.1 Life in a Multi-Language World: The .NET platform is language agnostic nature
  • 8. Because the .NET runtime couldn’t care less which language was used to build a blockof managed code, .NET programmers can stay true to their syntactic preferences and share thecompiled code among teammates, departments, and external organizations (regardless ofwhich .NET language others choose to use).The .NET supports multiple language itegration For example, some programming languagesoffer excellent intrinsic support for advanced mathematical processing. Others offer superiorsupport for financial calculations, logical calculations,interaction with mainframe computers, andso forth. When you take the strengths of a particular programming language and then incorporatethe benefits provided by the .NET platform, everybody wins.Of course, in reality the chances are quite good that you will spend much of your time buildingsoftware using your .NET language of choice. However, once you master the syntax of one .NETlanguage, it is very easy to learn another. This is also quite beneficial, especially to the softwareconsultants of the world. If your language of choice happens to be C# but you are placed at aclient site that has committed to Visual Basic, you are still able to leverage the functionality ofthe .NET Framework, and you should be able to understand the overall structure of the code basewith minimal fuss and bother.1.8 Overview of .net binaries (aka assemblies): These are a grouping of typesn resources that work together as a logical unit (Figure 1.4). It consists ofMSIL (the Intermediate Language)Meta Data (describing the types used in the program)Manifest (relation ship between the elements listed in the assembly)NOTE: IL (Intermediate Language), CIL (Common Intermediate Language), and MSIL(Microsoft Intermediate Language) are all describing the same thing. Figure 1.4:.NET assemblyWhen a *.dll or *.exe has been created using a .NET-aware compiler, the resulting module isbundled into an assembly.An assembly contains CIL code, which is conceptually similar to Java byte code in that is notcompiled into platform specific instructions until absolutely necessary such as CIL is referenced
  • 9. for use by the .NET runtime.The CIL code is housed in .NET assemblies. As mandated by specification, assemblies are storedin the Portable Executable (PE) format, common on the Windows platform for all dll and exefiles.In addition to CIL instructions, assemblies also contain metadata that describes thecharacteristics of every type within the binary. In other words, all CIL is self-describingthrough .NET metadata. The CLR checks the metadata to ensure that the correct method iscalled. Metadata is usually generated by language compilers but developers can create their ownmetadata through custom attributes. Metadata contains information about the assembly, and isalso used to implement the reflective programming capabilities of .NET Framework..NET metadata is always present and is automatically generated by a given .NET awarecompilers.Figure 1.5: ALL .NET-aware compilers emit IL instructions and metadata.In addition to CIL and type metadata, assemblies(Figure 1.6) themselves are also described usingmetadata, which is officially termed a manifest. The manifest contains information about thecurrent version of the assembly, culture information (used for localizing string and imageresources), and a list of all externally referenced assemblies that are required for properexecution. You can use the ildasm.exe tool to disassemble an assembly.1.8.1 Single-File and Multi-file Assemblies:Single File Assembly :- If an assembly is composed of a single *.dll or *.exe module then it’s asingle file assembly. This file contains all the necessary CIL, metadata, manifested in anautonomous well- defined package. A single file assembly is the simplest form of anassembly . The following are features of a A single file assembly1)A single file assembly is loaded in to a single application2)A single file assembly does not implement version checking3)Assemblies that are located out side the application in to which the single file assembly isloaded can not be reference it.
  • 10. 4)A single file assembly can be uninstalled by simply deleting the folder in which the assemblyplaced.Multiple File Assemblies :-A multi file assembly is created from multiple resource files and code modules. These arevarious options for grouping resources and code modules in to assemblies. These options arebased on the following factors.Grouping modules have the same version information.Group resources and code modulessupport the manner of deployment that you are using Versioning Reuse Deployment.We can create a shared assembly if we want an assembly that can be accessed by multipleapplication. In this case the assembly can be deployed in the global assembly cache.Figure1.7: Single File Assembly Figure 1.8: Multiple File AssembliesMulti – File: These are composed of many binaries each of Single File assembly Multiple File assembly Figure 1.6:single and multifile assemblies.1.9 common intermediate Language (CIL): In .NET, CIL means Common IntermediateLanguage and is the name for Object Code produced by .NET compilers. It is usually found in ssemblies.At runtime when the application loads, the CIL is converted into native Machine Code.1.9.1 Role of common intermediate Language (CIL):(i) The .NET compiler always emits or generates CIL instructions.(ii) The CIL is a language that is above any platform specific instruction set ,for example , theC# code doesn’t concern with exact syntax.//calc.cs Using System; namespace CalculatorExample {//this class contains the app’s entry point. public class CalcApp { static void Main( ) { Calc c= new Calc( ); int ans= c.Add ( 10, 87); Console.WriteLine (“10 + 87 is {0}.” , ans);
  • 11. //Wait for user to press the Enter key before shutting Down. Console.ReadLine ( ); } }//the C# calculator public class Calc{ public int Add(int x, int y){ return x+y ; } } }Once you compile this code file using the C# compiler (csc.exe), you end up with a single-file*.exe assembly that contains a manifest, CIL instructions, and metadata describing eachaspect of the Calc and Program classes.For example, if you were to open this assembly using ildasm.exe. Figure1.7: ildasm.exe ildasm.exe(Figure 1.7) allows you to see the CIL code, manifest, and metadata(ctrl+m) withina .NET assembly.you would find that the Add() method is represented using CIL such as thefollowing:.method public hidebysig instance int32 Add(int32 x,int32 y) cil managed{// code size 8 (0 X 8).maxstack 2.locals init ([0] int32 CS$1$0000)IL_0000: ldarg.1IL_0001: ldarg.2IL_0002: addIL_0003: stloc.0IL_0004: br.s IL_0006IL_0006: ldloc.0IL_0007: ret}//end of method Calc::Add
  • 12. Now, recall that this is true of all .NET-aware compilers. To illustrate, assume you created thissame application using Visual Basic .NET, rather than C#:‘ Calc.vb Imports System Namespace CalculatorExample‘A VB.NET ‘Module’ is a class that only contains‘ static members. Module CalcApp Sub Main( ) Dim ans As Integer Dim c As New Calc ans = c.Add(10,84) Console.WriteLine(“10+84 is {0}.” ,ans) Console.ReadLine( ) End SubEnd ModuleClass Calc Public Function Add(ByVal x As Integer, ByVal y As Integer) As Integer Return x+y End Function End ClassEnd NamespaceIf you examine the CIL for the Add() method, you find similar instructions (slightly tweakedby the VB .NET compiler, vbc.exe):.method public instance int32 Add(int32 x,int32 y) cil managed{// code size 8 (0 X 8).maxstack 2.locals init ([0] int32 CS$1$0000) IL_0000: ldarg.1IL_0001: ldarg.2IL_0002: addIL_0003: stloc.0IL_0004: br.s IL_0006IL_0006: ldloc.0IL_0007: ret}//end of method Calc::Add1.9.2 Benefits of CIL (Common Intermediate Language)One benefit is language integration. Since each .NET-aware compiler produces nearly identicalCIL instructions, all languages are able to interact within a well-defined binary arena.Given thatCIL is platform-agnostic, the .NET Framework itself is platform-agnostic, providing the samebenefits Java developers have accustomed to: single code base running on several OS. Actually,there is an international standard for the C# language, and a large subset of the .NET platformand implementation already exist for many non-Windows OS.
  • 13. 1.9.3 CIL Compile to Platform-Specific InstructionsSince assemblies contain CIL instructions, rather than platform-specific instructions, CIL codemust be compiled on the fly before use. The entity that compiles CIL code into meaningful CPUinstructions is termed a just-in-time (JIT) compiler, which sometimes referred as Jitter. The .NETruntime environment leverages a JIT compiler for each CPU targeting the runtime, eachoptimized for the underlying platform.As a given Jitter compiles CIL instructions into corresponding machine code, it will cache theresults in memory in a manner suited to the target OS. In this way, if a call is made to a methodnamed PrintDocument(), the CIL instructions are compiled into platform-specific instructions onthe first invocation and retained in memory for later use. Therefore, the next timePrintDocument() is called, there is no need to recompile the CIL.1.10 Role of .NET Type MetadataThere are following role of .NET Type Metadata* IDL is a Meta language that is used to describe the type contained within the COM server.*The IDL is compiled into the binary format which can be used to manipulate the contained types. Therefore .net assembly contains full, complete & accurate Meta data.* In addition to CIL instructions, a .NET assembly contains metadata. It describes each and everytype (class, structure, enumeration, etc.) defined in the binary, as well as the members of eachtype (properties, methods, events, etc.). It is always the job of the compiler (not the programmer)to emit the latest type metadata. Because .NET metadata is so meticulous, assemblies arecompletely self-describing entities.MethodName : Add(06000003)Flags : [Public] [HideBySig] [ReuseSlot] (00000086) RVA : 0X00002090ImplFlags : [IL] [Managed] (00000000) CallCnvntn : [DEFAULT}hasThisReturnType : I42 ArgumentsArgument #1 : I4Argument #2 : I42 parameters(1) ParamToken : (08000001) Name : x flags : [none] (00000000)(2) ParamToken : (08000002) Name : y flags : [none] (00000000)• RVA is a relative virtual address; the RVA of size specifies the size of metadata directory.• The C# compiler of the add method; return type & method arguments are described in the Meta information window.• Metadata is used by numerous aspects of the .NET runtime environment, as well as by variousdevelopment tools. For instance, the IntelliSense feature provided by tools such as Visual Studiois made possible by reading an assemblys metadata at design time. Metadata is also used byvarious object browsing utilities, debugging tools, and the C# compiler itself. To be sure,metadata is the backbone of numerous .NET technologies including Windows CommunicationFoundation (WCF), XML web services, the .NET remoting layer, reflection, late binding, andobject serialization.
  • 14. 1.11 The Role of Assembly ManifestA manifest describes the relationship between the elements in the assembly and to the externalelements.You can use the ildasm.exe tool to disassemble an assembly..NET assembly also contains metadata that describes the assembly itself (technically termed amanifest). Among other details, the manifest documents all external assemblies required by thecurrent assembly to function correctly, the assembly’s version number,copyright information, andso forth. Like type metadata, it is always the job of the compiler to generate the assembly’smanifest. Here are some relevant details of the manifest generated when compiling the Calc.cscode file (assume we instructed the compiler to name our assembly Calc.exe)..assembly extern mscorlib{.publickeytoken = (B7 7A 5C 56 19 34 E0 89).ver 2:0:0:0}The .net runtime can ensure correct version is loaded & using the key information, verify that thebinary has not been tampered.Example: for the C# calc program the compiler generates the assembly manifest as follows.assembly CSharpCalculator{.hash algorithm 0X00008004.ver 0:0:0:0}.module CSharpCalculator.exe.imagebase 0X00400000.subsystem 0X00000003.file alignment 512.corflags 0X000000001The C# compiler has an assembly by default, many compilers do the similar things & this will besubject of change over that of time the assembly manifest also includes metadata document &list of external assemblies referred by the C# calculator.exe & the characteristics of the binarysuch as the version, module & the directives.1.12 Understanding Common Type System:In The .NET platform , type is simply a general term used to refer to a member from the set{class, interface, structure, enumeration, delegate}.When you build solutions using a .NET-awarelanguage, you will most likely interact with many of these types. For example, your assemblymay define a single class that implements some number of interfaces.the CTS is a formal specification that documents how types must be defined in order tobe hosted by the CLR. Typically, the only individuals who are deeply concerned with the innerworkings of the CTS are those building tools and/or compilers that target the .NET platform. It isimportant,however, for all .NET programmers to learn about how to work with the five typesdefined by the CTS in their language of choice. Here is a brief overview.
  • 15. 1.12.1 CTS Class TypesEvery .NET-aware language supports, at the very least, the notion of a class type, which is thepart of OOP. A class may be composed of any number of members (such as constructors,properties, methods, and events) and data points (fields). In C#, classes are declared using theclass keyword.// A C# class type with 1 method.class Calc{public int Add(int x, int y){ return x + y; }}• The keyword class type is supported by .net aware languages which follows the object orientedapproach.• The class is composed of any number of members which includes properties, methods, events&operators & the data points.• CTS class may be derived from a single base class.• The multiple inheritances are not supported for a class type.1.12.2 CTS structure Types:• It can be defined as a structure that is derived from a common base class System. Value Type• CTS permit the structure to implement any number of interfaces.• A CTS can be created, a structure can have fields, constructors, methods.• The structure may not function as a base type to another class or a structure then it’s explicitlydefined to be sealed.//A C# structure typestruct Point{//structures contain fields public int xPos, yPos;//structures contain parameterized constructors public Point (int x, int y){ xPos = x ; yPos = y;}//structures define methods.public void Display( ){Concsole.WriteLine(“ {0}, {1} “, xPos , yPos );}}1.12.3 CTS interface types:• Interface is a collection of abstract member’s definition, implemented by class or astructure.• Interfaces are the only .net type that do not derive from common base type.• When we create a custom interface using .net aware programming language .• CTS permits interface to be derived from multiple interfaces.
  • 16. // A C# interface type public interface IDraw{ void Draw( ); }1.12.4 CTS enumeration types:The enumerators are the programming constructs that are allowed to be grouped under thename /value pair for a specific name. CTS that are enumerated types derive from a common baseclass System.Enum.//a C# enumeration types public enum CharacterType { Wizard=100; Fighter=100; }By default, the storage used to hold each item is a 32-bit integer; however, it is possible to alterthis storage slot if needed. Also, the CTS demands that enumerated types derive from a commonbase class, System.Enum.1.12.5 CTS delegates type:• Delegates are .net equivalent of the function pointer.• .net delegate is a class that is derived from System.MulticastDelegate.• Delegates are useful for one entity to forward call to other entity.• Delegates also provide the intrinsic support for multicasting & the asynchronous method invocation. //this C# delegate type can point to any method returning an integer & taking two integers as //input public delegate int BinaryOp(int x, int y);Delegates are useful when you wish to provide a way for one entity to forward a call to anotherentity, and provide the foundation for the .NET event architecture.1.12.6 CTS Type Members:Types formalized by the CTS, that most types take any number of members. Formally speaking,a type member is constrained by the set {constructor, finalizer, static constructor, nested type,operator, method, property, indexer, field, read only field, constant, event}.Each member has a given visibility trait (e.g., public, private, protected, and so forth). Somemembers may be declared as abstract to enforce a polymorphic behavior on derived types as wellas virtual to define a canned (but overridable) implementation. Also, most members may beconfigured as static (bound at the class level) or instance (bound at the object level).1.12.7 CTS Datatypes:• A language has a unique keyword use to declare an intrinsic data type, all languages resolve to the same type defined by mscorlib.dll.• CTS data types are representations in various .net languages.• Therefore we can create a well-known subset of CTS that define a common, shared set ofprogramming constructs for all the .net aware languages.1.12.8 Intrinsic CTS Data TypesAlthough a given language typically has a unique keyword used to declare an intrinsic CTS data
  • 17. type, all language keywords ultimately resolve to the same type defined in an assembly namedmscorlib.dll. Consider Table , which documents how key CTS data types are expressed invarious .NET languages.CTS data type VB.net keyword C# keyword Managed extensions for C++ keywordSystem.Byte Byte byte unsigned charSystem.SByte SByte sbyte signed charSystem.Int16 Short short shortSystem.Int32 Integer int int or longSystem.Int64 Long long _int64System.UInt16 UShort ushort unsigned shortSystem.UInt32 UInteger uint unsigned int or unsigned longSystem.UInt64 Long ulong unsigned_int64System.Single Single float FloatSystem.Double Double double DoubleSystem.Object Object object Object^System.Char Char char wchar_tSystem.String String string String^System.Decimal Decimal decimal DecimalSystem.Boolean Boolean bool Bool1.13 Common Language Specification:The different language express the same programming constructs in unique, language specificterms. For example, in C# the string concatenation is denoted by + operator. In VB stringconcatenation operator is denoted by &.The two distinct languages express same programmaticsyntax in different forms of appearance.In the .net runtime these compilers such as csc.exe orvbc.exe are configured to emit the same CIL set of instructions.Therefore CLS provides theguidelines that describes the complete set of features the .net aware compiler must support toproduce the code emitted by the runtime and at the same time it can be accessed in a uniformway by all the languages of .net platform. Therefore CLS is a physical subset of functionalitydefined by the CTS.CLS consists of set of rules that the compiler builds & it must conform forthese rules.Each rule is assigned a name & it describes hoe the rule effects & how the compilerinteracts with them.1.14 Understanding the common Language runtime (CLR):The managed execution process includes the following steps:1.Choosing a proper compiler,2.Generating MSIL code,3.Compiling MSIL to CPU specific native code using JIT and4.Executing the processor specific code.it’s a collection of external services that are required to execute a compiled unit of code.Example: MFC to create a new application, their binary is required to link with the MFC runtimelibrary mfc42.dll.Choosing a CompilerEvery constructs (such as class, struct etc) in every .NET languages must compile to CLRcompatible types to qualify as .NET managed code. You can choose compilers such as VisualBasic, C#, Visual C++, JScript, or one of many third-party compilers like Eiffel, Perl, or COBOL
  • 18. compiler.MSIL Code GenerationThis is the first level of .NET compilation in which the high-level compiled in to a languagecalled intermdeiate language (IL). The IL code look more like machine code than high-levellanguage, but the IL does contain some abstract concepts such as base classes and exceptionhandling, which is why the language is called intermediate.MSIL includes instructions for loading, storing, initializing, and calling methods on objects, aswell as instructions for arithmetic and logical operations, control flow, direct memory access,exception handling, and other operations.When a compiler produces MSIL, it also produces metadata. Metadata describes the types inyour code, including the definition of each type, the signatures of each types members, themembers that your code references, and other data that the runtime uses at execution time. Figure1.8: mscoree.dll in actionMSIL to Native code
  • 19. CPU-independent MSIL code can be efficiently converted to native code using Just-in-Time(JIT) compiler, only when that portion of IL code is required for exectuion. JIT generatedmachine code is CPU-specific code that runs on the same computer architecture as the JITcompiler and it takes advantage of the added instruction sets offered by each CPU type.Figure 1.8 shows the workflow between the source code, .net compiler & .net runtime engine i.e.the mscoree.dll.The .net runtime provides a single well defined layer that is shared by all the language andplatforms that are .net aware here the .net runtime is termed as CLR.The CLR physically represents by an assembly named as mscoree.dll(Figure 1.8)CodeExecutionWhen CLR executes a .NET method for the first time; it generates a processor specific nativecode from MSIL using the JIT compiler. The next time the method is run, the existing JIT-compiled native code is run. The process of JIT-compiling and then executing the code isrepeated until execution is complete.CLR provides myriad set of services to managed components like garbage collection, versioning,interoperability with unmanaged code etc.physical representation of base class library is mscorlib.dll(microsoft object runtime library).1.15 .NET namespaces:Namespace is a logical naming schema which provides a way to group the semantically relatedtypes such as class, structure, interface, delegate & so on in one root.Namespace exist for data access, web development, threading & security we cannot build anysort of functionality C# application. Without making a reference to the system namespace System (fundamental namespace) system namespace is root for numerous other .netnamespaces. System which describes: within the system they are numerous low level classes with primitivetype, mathematical manipulation, garbage collection, number of commonly used exception &predefined attributes.System.Collection: this defines a number of objects such as an array queue & the base types,interfaces that allow you to build the customized collection. System.Data, System.Data.Oledb, System.Data.SqlClient: used for database manipulation.System.Drawing, System.Drawing.Drawing2D, System.Drawing.Painting: primitivesincluded for bitmap, fonts, icons, printing & advanced graphical rendering support.System.Io: includes all files I/O, I/O buffering.System.Net: this contains the type related to network programming such as the requestresponse, socket programming etc.System.Web : includes for development of all .net web applications System.Windows.Forms: the .net platform contains the namespace that is required for thewindow, dialogue boxes &widgets.System.security: this type includes the permissions, cryptography; it’s an integrated aspectof .net universe which includes user permissions.Accessing the namespace programmatically is done by System.Console where Console is aclass contained within the namespace system.The .net runtime engine checks for the keyword using which we can declare through a particularnamespace. The keyword using this will generate all the base class library types for a particular
  • 20. namespace.1.16.NET namespace nomenclature:It includes following techniques that are used for .net library:(1) .net SDK online documentation(2) .exe utility(3) Class viewer web application(4) Winev.exe - a desktop application(5) VS.net integrated object browserThe .net runtime includes the .net assemblies which have to be loaded & executed on themachine which is supposed to be configured to the host .net runtime.The Microsoft has created the specific re distribution package named dotnetfx.exe is installedwith the software so that it can be configured to execute the .net assembly as long as it isflavored with MS-Windows.Therefore the target machine will have the base class libraries, the dl lie mscoree.dll, and thecomplete .net infrastructure.1.17 Deploying the .NET RuntimeIt should come as no surprise that .NET assemblies can be executed only on a machine thathas the .NET Framework installed. For an individual who builds .NET software, this shouldnever be an issue, as your development machine will be properly configured at the timeyou install the freely available .NET Framework 3.5 SDK (as well as commercial .NETdevelopment environments such as Visual Studio 2008 or 2010).However, if you deploy an assembly to a computer that does not have .NET installed, it willfail to run. For this reason, Microsoft provides a setup package named dotnetfx3setup.exe thatcan be freely shipped and installed along with your .NET software. This installation programcan be freely downloaded from Microsoft from their .NET download area(http://msdn.microsoft.com/ netframework). Once dotNetFx35setup.exe is installed, the targetmachine will now contain the .NET base class libraries, .NET runtime (mscoree.dll), andadditional .NET infrastructure (such as the GAC).SummaryThe point of this chapter was to layout the conceptual framework. I began by examining anumber of limitations and complexities found within the technologies prior to .NET, andfollowed up with an overview of how .NET and C# attempt to simplify the current state ofaffairs. .NET basically boils down to a runtime execution engine (mscoree.dll) and base classlibrary (mscorlib.dll and associates). The common language runtime (CLR) is able to hostany .NET binary (a.k.a. assembly).As you have seen, assemblies contain CIL instructions (inaddition to type metadata and the assembly manifest) that are compiled to platform-specificinstructions using a just-in-time ( JIT) compiler. In addition, you explored the role of theCommon Language Specification (CLS) and Common Type System (CTS).This was followedby an examination of the ildasm.exe and reflector.exe object browsing utilities, as well ascoverage of how to configure a machine to host .NET applications using dotnetfx3setup.exe.
  • 21. Questions 1. Explain with a neat diagram, the relationship between .NET runtime layer and base class library. 2. What is the role of .NET Type Metadata? Give Example. 3. List and Explain intrinsic CTS datatype and .NET namespace in C#. 4. What is .Net assembly? What does it contain? Explain each of-them. 5. What are the building blocks of .Net frame work? Show their relationship, with a neat block diagram? 6. Explain with a neat diagram, the workflow that. takes place between your source code, a given .Net compiler and the .Net execution engine. 7. Explain the features of CLR. 8. What is ILDASM in NET? 9. What is Assembly manifest? Describe the parts of assembly. 10. Describe the .Net base class library. 11. What are the building blocks of .Net frame work? Show their relationship, with a neat block diagram. Explain CTS, in detail. 12. What is .Net assembly? What does it contain? Explain each of-them. 13. Explain with a neat diagram, the workflow that. Takes place between your source code, a given .Net compiler and the .Net execution engine..NET Framework objective questions and answers1. Which of the following statements are TRUE about the .NET CLR?1. It provides a language-neutral development & execution environment.2. It ensures that an application would not be able to access memory that it is not authorized to access.3. It provides services to run "managed" applications.4. The resources are garbage collected.5. It provides services to run "unmanaged" applications.A. Only 1 and 2B. Only 1, 2 and 4C. 1, 2, 3, 4D. Only 4 and 5E. Only 3 and 4Answer : Option C2. Which of the following are valid .NET CLR JIT performance counters?1. Total memory used for JIT compilation2. Average memory used for JIT compilation3. Number of methods that failed to compile with the standard JIT4. Percentage of processor time spent performing JIT compilation5. Percentage of memory currently dedicated for JIT compilationA. 1, 5
  • 22. B. 3, 4C. 1, 2D. 4, 5Answer : Option B3. Which of the following statements is correct about Managed Code?A. Managed code is the code that is compiled by the JIT compilers.B. Managed code is the code where resources are Garbage Collected.C. Managed code is the code that runs on top of Windows.D. Managed code is the code that is written to target the services of the CLR.E. Managed code is the code that can run on top of Linux.Answer: Option D4. Which of the following utilities can be used to compile managed assemblies into processor-specific nativecode?A. gacutil B. ngenC. sn D. dumpbinE. ildasmAnswer : Option B5. Which of the following are NOT true about .NET Framework?1. It provides a consistent object-oriented programming environment whether object code is stored andexecuted locally, executed locally but Internet-distributed, or executed remotely.2. It provides a code-execution environment that minimizes software deployment and versioning conflicts.3. It provides a code-execution environment that promotes safe execution of code, including code created byan unknown or semi-trusted third party.4. It provides different programming models for Windows-based applications and Web-based applications.5. It provides an event driven programming model for building Windows Device Drivers.A. 1, 2B. 2, 4C. 4, 5D. 1, 2, 4Answer: Option C6. Which of the following components of the .NET framework provide an extensible set of classes that can beused by any .NET compliant programming language?A. .NET class librariesB. Common Language RuntimeC. Common Language InfrastructureD. Component Object ModelE. Common Type SystemAnswer : Option A7. Which of the following jobs are NOT performed by Garbage Collector?1. Freeing memory on the stack.2. Avoiding memory leaks.3. Freeing memory occupied by unreferenced objects.4. Closing unclosed database collections.5. Closing unclosed files.A. 1, 2, 3B. 3, 5C. 1, 4, 5
  • 23. D. 3, 4Answer: Option C8. Which of the following .NET components can be used to remove unused references from the managedheap?A. Common Language InfrastructureB. CLRC. Garbage CollectorD. Class LoaderE. CTSAnswer: Option C9. Which of the following statements correctly define .NET Framework?A. It is an environment for developing, building, deploying and executing Desktop Applications, WebApplications and Web Services.B. It is an environment for developing, building, deploying and executing only Web Applications.C. It is an environment for developing, building, deploying and executing Distributed Applications.D. It is an environment for developing, building, deploying and executing Web Services.E. It is an environment for development and execution of Windows applications.Answer: Option A10. Which of the following constitutes the .NET Framework?1. ASP.NET Applications2. CLR3. Framework Class Library4. WinForm Applications5. Windows ServicesA. 1, 2B. 2, 3C. 3, 4D. 2, 5Answer: Option B11. Which of the following assemblies can be stored in Global Assembly Cache?A. Private AssembliesB. Friend AssembliesC. Shared AssembliesD. Public AssembliesE. Protected AssembliesAnswer: Option C12. Code that targets the Common Language Runtime is known asA. UnmanagedB. DistributedC. LegacyD. Managed CodeE. Native CodeAnswer: Option D13. Which of the following statements is correct about the .NET Framework?A. .NET Framework uses DCOM for achieving language interoperability.B. .NET Framework is built on the DCOM technology.
  • 24. C. .NET Framework uses DCOM for making transition between managed and unmanaged code.D. .NET Framework uses DCOM for creating unmanaged applications.E. .NET Framework uses COM+ services while creating Distributed Applications.Answer: Option C14. Which of the following is the root of the .NET type hierarchy?A. System.ObjectB. System.TypeC. System.BaseD. System.ParentE. System.RootAnswer: Option A15. Which of the following benefits do we get on running managed code under CLR?1. Type safety of the code running under CLR is assured.2. It is ensured that an application would not access the memory that it is not authorized to access.3. It launches separate process for every application running under it.4. The resources are Garbage collected.A. Only 1 and 2B. Only 2, 3 and 4C. Only 1, 2 and 4D. Only 4E. All of the aboveAnswer: Option E16. Which of the following security features can .NET applications avail?1. PIN Security2. Code Access Security3. Role Based Security4. Authentication Security5. Biorhythm SecurityA. 1, 4, 5B. 2, 5C. 2, 3D. 3, 4Answer: Option C17. Which of the following jobs are done by Common Language Runtime?1. It provides core services such as memory management, thread management, and remoting.2. It enforces strict type safety.3. It provides Code Access Security.4. It provides Garbage Collection Services.A. Only 1 and 2B. Only 3, 4C. Only 1, 3 and 4D. Only 2, 3 and 4E. All of the aboveAnswer: Option E18. Which of the following statements are correct about a .NET Assembly?1. It is the smallest deployable unit.2. Each assembly has only one entry point - Main(), WinMain() or DLLMain().3. An assembly can be a Shared assembly or a Private assembly.
  • 25. 4. An assembly can contain only code and data.5. An assembly is always in the form of an EXE file.A. 1, 2, 3B. 2, 4, 5C. 1, 3, 5D. 1, 2Answer & ExplanationAnswer: Option A19. Which of the following statements are correct about JIT?1. JIT compiler compiles instructions into machine code at run time.2. The code compiler by the JIT compiler runs under CLR.3. The instructions compiled by JIT compilers are written in native code.4. The instructions compiled by JIT compilers are written in Intermediate Language (IL) code.5. The method is JIT compiled even if it is not calledA. 1, 2, 3B. 2, 4C. 3, 4, 5D. 1, 2Answer: Option A20. Which of the following are parts of the .NET Framework?1. The Common Language Runtime (CLR)2. The Framework Class Libraries (FCL)3. Microsoft Published Web Services4. Applications deployed on IIS5. Mobile ApplicationsA. Only 1, 2, 3B. Only 1, 2C. Only 1, 2, 4D. Only 4, 5E. All of the aboveAnswer:option A