C# Unit - I
C# Unit - I
UNIT-I 2 Marks
1. What is .NET?
The .NET Framework comprises:
Converting a value type to a reference type object is called boxing. A value type is stored on
stack memory and requires conversion—boxing—to an object on the heap memory before it can be
treated as an object. The members of the new object can be invoked on the value, e.g.,
converting a double to a string. Boxing may be performed implicitly at runtime by the CLR.
Int m = 10;
objectom = m;
m = 20;
Console.WirteLine (m); // m = 20
Console.WriteLine (om); //om = 10
6. What is Unboxing? (Apr’13)
Conversion of a reference typed object to the associated value type instance. Usually,
unboxing is performed explicitly by a cast operation.
Int m = 10;
objectom = m;
int n = (int) om;
7. Define Common Language Runtime (CLR) (May’14)
CLR is the .NET runtime environment responsible for program execution management
and for providing container services—debugging, exception management, memory
management, profiling, and security. The CLR is a major subsystem in the .NET Framework
which implements the Common Type System. Also this is called as Virtual Execution System
(VES).
8. What are the services provided by the CLR?
CLS is a subset of the Common Type System and a set of conventions for promoting
interoperability between programming languages and the .NET Framework. CLS details
conventions that must be followed by class library authors and by programming language
designers.
12. Define Common Type System (CTS) (APR-22)
CTS is the .NET Framework specification for defining, declaring, and managing types
in .NET languages for the Common Language Runtime (CLR). All .NET components must
comply with the CTS specification.
13. What is Framework Class Library (FCL)? (Nov’18)
FCL comprises the thousands of classes constituting the foundation of the .NET Framework.
FCL services include core functionality collections, file and network I/O, system service access,
value types, etc., database interaction, desktop‐based application support Windows Forms, Web‐
based application support Web Forms, Web services support, and XML support.
14. What is Just‐In‐Time (JIT)? (May’14)
JIT is the process of compiling MSIL code units just when needed at runtime. The JIT
compiler in the Common Language Runtime (CLR) compiles MSIL instructions to native
machine code as a .NET application is being executed. Compilation occurs when a method is
called and is not compiled more than once during program execution; because, JIT‐compiled code is
cached in memory.
15. What is Managed code?
Code that is executed by the Common Language Runtime (CLR) is called managed code.
Managed code provides metadata to enable the CLR to handle exceptions, locate methods
encoded in assembly modules, and manage security information. Managed code can access
both managed data and unmanaged data.
16. What is unmanaged code?
It is, also called unsafe code, code that executes outside of the control of the Common Language
Runtime (CLR). Unmanaged code may perform unsafe operations such as pointer arithmetic.
Unmanaged code is used for accessing unmanaged memory, calling Windows APIs, interfacing
to COM components, and coding performance‐critical methods which avoid the overhead of the
CLR.
17. What is Managed data?
Data in memory allocated and deallocated by the Common Language Runtime (CLR).
Managed data can be accessed only by managed code.
18. What is unmanaged data?
Data allocated outside of the control of the Common Language Runtime (CLR). Unmanaged data
is accessible by both managed and unmanaged code.
19. What is Microsoft Intermediate Language (MSIL)? (Dec’14)
.NET language compilers—e.g., C# and VB.NET— compile source code into MSIL—a
machine‐ independent, 7ntermediate language. MSIL is subsequently compiled by the Just‐In‐Time
(JIT) compiler into machine language just prior to execution. The Native Image Generator Tool can
also be used to convert MSIL into machine language.
20. What is Abstract IL?
ILX is a toolkit for accessing the contents of .NET Common IL binaries. Features
include transforming binaries into structured abstract syntax trees to be manipulated.
21. Define Virtual Execution System (VES)?
VES is the environment for executing managed code. VES defines a virtual machine.
Thus, VES supports execution of the Common Intermediate Language instruction set. Also, VES
provides support for built‐in data types, a set of control flow constructs, and a model for exception
handling.
22. What are the components included in the .NET platform? (Nov’13)
.NET infrastructure and tools
.NET user experience
OLE (Object Linking and Embedding) technology was developed by Microsoft in the early
1990s to enable easy interprocess communications.
OLE provided support to achieve the following:
To embed documents from one application into another application.
To enable one application to manipulate objects located in another application.
Ex: interoperability between MS‐Excel and MS‐Word
24. What are Web Services used for?
28. Write down some of the namespaces available in the .NET framework?(NOV 2012 ) (Or)
Discuss .NET Namespaces (NOV 2018)
Microsoft.Csharp
Contains classes that support compilation and code generation using the C# language.
Microsoft.Jscript
Contains classes that support compilation and code generation using the Jscript language.
Microsoft.VisualBasic
Contains classes that support compilation and code generation using the Visual Basic .NET
language.
System.CodeDom
Contains classes that can be used to represent the elements and structure of a source code
document.
29. What are the uses of managed code?
Just – in – Time (JIT) compiler, which compiles MSIL into native code that is specific to the
OS and machine architecture being targeted.
31. Explain the managed code execution process?
Serialization can be defined as the process of storing the state of an object instance 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, is 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.
In .Net Framework applications, files that make up a logical unit of Functionality are
grouped into an assembly. An assembly is one or more files that comprise a logical unit. Assemblies
are fundamental to developing, deploying, and running .Net Framework applications.
36. Name any four applications that are supported by .NET Platform (Apr’16)
37. Distinguish between the .NET Framework and Java Environment (Dec’14)
Java .Net
+ Platform Independent - Programs written in .Net runs on
Windows only
Programs written in Java runs on any
OS.
+ Java is free and there are many third - .Net framework is also free but its
party good open source free IDEs for official development IDE (Microsoft
development of java applications. Visual Studio) is paid.
Applications written in any .NET Languages can use the code in the .NET Framework class
Library. Among the most important technologies provided in this library are the following:
ASP.NET: Classes focused on building browser- accessible applications.
Windows Forms: Classes for building Windows graphical user interfaces (GUI) in any CLR – based
programming Language.
ASP.NET Web Services (also called ASMX): Classes for creating applications that communicate with
other applications using Web Services.
Enterprise Services: Classes that provide distributed transactions, object instance control, and other
services useful for building reliable, scalable applications.
ADO.NET: Classes focused on accessing data stored in relational database management system (DBMS)
Software that uses .NET Framework is referred to as managed code.
The figure shows, an application can be built solely from managed code, relying entirely on the
CLR and the relevant parts of the .NET Framework class Library. An application can also be built from a
combination of managed code and ordinary unmanaged code, with the two interacting as necessary. This
second option, shown on the right side of the figure, is especially important for existing applications.
Most new Windows applications created today are built wholly in managed code.
Managed code is typically object oriented, so the objects it creates and uses are known as
managed objects. A managed object can use and inherit from another managed object even if the two are
written in different languages. This fact is a key part of what makes the .Net Framework class library an
effective foundation. Understanding .Net Framework begins with understanding this runtime
environment.
The Common Language Runtime:
Each language commonly has its own unique syntax, its own set of how classes inherit from one another
and much more. The choices a language designer makes are driven by the target applications for
language, which its users are meant to be, and the designer’s own sensibilities.
The CLR provides this standard implementation. By providing a common set of data types such
as integers, strings, classes, and interfaces, specifications for how inheritance works, and how much more,
it defines a common set of semantics for languages built on it.
The CLR says nothing about syntax however. How a language looks, whether it contains curly
braces or semicolons or anything else, is entirely up to the language designer. While it is possible to
implement languages with varying behaviors on top of the CLR, the CLR itself provides a consistent,
modern set of semantics for a language designer to build on.
Along with its standard types, the CLR provides other fundamental services. Those services
include the following:
Garbage Collection, which automatically frees managed objects that are no longer referenced.
A Standard format for metadata, information about each type that’s stored with the complied code
for that type.
A common format, called assemblies, for organizing complied code. An assembly can consists of
one or more Dynamic Link Libraries (DLLs) and\or executables (EXEs), and it includes the metadata for
the classes it contains.
A single application might use code from one or more assemblies, and so each assembly can
specify other assemblies on which it depends.
Using the CLR
The CLR was not defined with any particular programming language in mind. Instead, its features
are derived largely from popular existing languages, such as C++, the pre-.Net version of VB, and Java.
Today, Microsoft provides several CLR- based languages, including C#, the .Net version of VB, an
extended version of C++, and others. Third parties also provide languages built on the CLR.
No matter what language it’s written in, all managed code is complied into Microsoft
Intermediate Language (MSIL) rather than a machine-specific binary. MSIL (also referred to as just IL) is
a set of CPU- independent instructions for performing typical operations such as loading and storing
information and calling methods. Each DLL and EXE in an assembly contains MSIL rather than
processor specific. Installing .Net Framework application on your system really means copying to your
disk files that contain MSIL rather than a machine specific binary. When the application is executed,
MSIL is transformed into native code before it’s executed.
The figure illustrates the process of compiling and executing managed code. Source code written
in VB, C#, or another language that targets the CLR is first transformed into MSIL by the appropriate
language complier, as the figure shows; the compiler also produces metadata that’s stored in the same file
as the MSIL. Before execution, this MSIL is compiled into native code for the processor on which the
code will run. By default, each method in a running application is compiled the first time that method is
called. Because the method is compiled just in time to execute it, this approach is called just in time (JIT)
compilation.
One point worth nothing is that any language built on the CLRs should exhibit roughly the same
performance as any other CLR-based language. The CLR is the foundation of everything else in the .Net
Framework. All code in the .Net Framework class library depends on it, as do all Framework-based
applications.
The figure shows a very small part of the .Net Framework class library’s namespace tree. The
namespaces shown include the following:
System:
The root of the tree, this namespace contains all of the other namespaces in the .Net Framework
class library. System also contains the core data types used by the CLR. These types include several
varieties of integers, a string type, and many more.
System. Web:
This namespace contains types useful for creating Web applications, and like many namespaces,
it has subordinate namespaces. Developers can use the types in System.Web.UI to built Asp.NET browser
applications, for example, while those in System. Web. Services are used to build ASP.NET Web
Services.
System. Data:
The types in this namespace comprise ADO.NET. For Example, the connection class is used to
establish connections to database management system (DBMS), while an instance of the DataSet class
can be used to cache and examine the results of a query issued against that DBMS.
System.Windows.Forms:
The types in this namespace make up Windows Forms, and they are used to build Windows
GUIs. Rather than relying on language-specific mechanisms, such as the older Microsoft Foundation
Classes (MFC) in C++, .Net Framework applications written in any programming language use this
common set of types to build graphical interfaces for Windows.
System.EnterpriseServices:
The types in this namespace provide services required for some kinds of enterprise applications.
Implemented by COM+ in the pre-NET world, these services include distributed transactions, object
instance lifetime management, and more. The most important in this namespace, one from which classes
must inherit to use Enterprise Services, is the ServicedComponent class.
System.XML:
Types in this namespace provide support for creating and working with XML-defined data. The
XmlDocument class, for instance, allows accessing an XML document using the Document Object Model
(DOM). This namespace also XML Schema definition language (XSD) and XPath.
Many more namespaces are defined, providing support for file access, serializing an object’s
state, remote access to objects, and much more. The biggest task facing developers who wish to build on
the .Net Framework is learning to use the many services that the library provides. There’s no requirement
to learn everything, however, so a developer is free to focus on only those things relevant to his or her
world.
2. Explain the common language runtime in detail (Nov’14)(Nov 2018)
The common Language Runtime (CLR) is the foundation everything else in the .NET
Framework. To understand .NET Languages such as C# and Visual Basic (VB), we must understand the
CLR. To understand the .Net Framework class Library – ASP.NET, ADO.NET, and the rest we must
understand the CLR.
Software built on the CLR is referred to as managed code, and the CLR provides a range of
things that support creating and running this code. The CLR also provides technologies for packaging
managed code and a runtime environment for executing managed code.
The CLR supports the creation and execution of managed code.
COMPONENTS OF THE CLR:
Managed code uses CLR which in turns looks after your applications by managing memory,
handling security, allowing cross - language debugging, and so on.
Unmanaged Code
The code, which is developed outside .NET, Framework is known as unmanaged code.
Applications that do not run under the control of the CLR are said to be unmanaged, and certain
languages such as C++ can be used to write such applications, which, for example, access low - level
functions of the operating system. Background compatibility with code of VB, ASP and COM are
examples of unmanaged code.
Unmanaged code can be unmanaged source code and unmanaged compile code. Unmanaged
code is executed with help of wrapper classes.
The Common Language Runtime includes the following things to be analyzed.
1. Building Managed Code. - CTS
2. Compiling Managed Code. - MSIL
3. Organizing Managed Code. - Assemblies
4. Executing Managed Code.
1. Building Managed Code: The Common Type System (Nov’12) (APR-22)
A programming language usually defines both syntax and semantics. When a new programming
language is defined, the usual approach is to define underlying abstractions such as key aspects of the
language’s semantics.The CTS specifies no particular syntax or keywords, but instead defines a common
set of types that can be used with many different language syntaxes. Each language has its own syntax,
but if that language is built on the CLR, it will use at least some of the types defined by the CTS. The
Common Type System defines core semantics but not syntax.Typesare fundamental to any programming
language. One simple but concrete way to think a type is a set of rules for interpreting the value stored in
some memory location, such as the value of a variable.
Introducing the Common Type System:
A Substantial subset of the types defined by the CTS is shown in the figure below.
The CTS defines reference and value types, all of which inherit from a common Object
type.
The first thing to note is that every type inherits either directly or indirectly from a type called
Object. The second thing to note is that every type defined by the CTS is either a reference type or a value
type. As the name suggest, an instance of a reference type always contains the value itself. Reference
types inherit directly from Object, while all value types inherit directly from a type called ValueType,
which in turn inherits from Object.
Value types tend to be simple. The types in this category include Byte, Char, signed and unsigned
integers of various lengths, single- and double-precision floating point, Decimal, Boolean, and more.
Reference types, by contrast, are typically more complex. As shown in the figure, for instance, Class,
Interface, Array, and String are reference types. To understand the difference between value types and
reference type we must understand how memory is allocated for instances of each type. In managed code,
values can have their memory allocated in one of two main ways, both managed by the CLR: on the stack
or on the heap. Variables allocated on the managed stack are typically created when a method is called or
when a running method creates them. In either case, the memory used by stack variables is automatically
freed when the method in which they were created returns. Variables allocated on the managed heap,
however, don’t have their memory freed when the method that created them ends. Instead, the memory
used by these variables is freed via a process called garbage collection.
A basic difference between value types and reference types is that a standalone instance of a
value type is allocated on the stack, while an instance of a reference type has only a reference to its actual
value allocated on the stack. The value itself is allocated on the heap.
Instances of value types are allocated on the managed stack, while instances of reference types are
allocated on the managed heap.
The figure shows the abstract picture of how this looks. In the case shown here, three instances of
value types – Int16, Char, and Int32 – have been created on the managed stack, while one instance of the
reference type instance has an entry on the stack – it’s a reference to the memory on the heap – but the
instance’s contents are stored on the heap. Understanding the distinction between value types and
reference types is essential in understanding the CTS type system and, ultimately, the types used by CLR-
based languages.
A Closer Look at CTS Types
The CTS defines a large set of types. The most fundamental of these is Object, from which every
CTS type inherits directly or indirectly. In the object oriented world of the CLR, having a common base
for all the types is useful. For one thing, since everything inherits from the same root type, an instance of
this type can potentially contain any value. Object also implements several methods, and since every CTS
type inherits from Object, these methods can be called on an instance of any type. Among the methods
Object provides are Equals, which determines whether two objects are identical, and GetType, which
returns the type of the object it’s called on.
Value Types
All value types inherit from ValueType. Like Object, ValueType provides an Equals method.
Value types cannot act as a parent type for inheritance, however, so it’s not possible to say, define a new
type that inherits from Int32.
Many of the value types are defined by the CTS. Those types are as follows:
Byte: An 8-bit unsigned integer
Char: A 16 – bit Unicode character.
Int16, Int32, and Int64: 16-, 32-, and 64- bit unsigned Integers.
Single and Double: Single-precision (32-bit) and double-precision (64-bit) floating-point numbers.
Decimal: 96-bit decimal numbers.
Enum: A way to name a group of values of some integer type. Enumerated types inherit from
System.Enum and are used to define types whose values have meaningful names rather than just numbers.
Boolean: True or False
Reference Types:
Compared with most value types, the reference types defined by the CTS are relatively
complicated. Before describing some of the more important reference types, it’s useful to look first at a
few elements, officially known as type members that are common to several types. Those elements are as
follows:
Methods:
Executable code that carries out some kind of operation. Methods can be overloaded,
which means that a single type can define two or more methods with the same name. To distinguish
among them, each of these identical named methods must differ somehow in its parameter list. Another
way to say this is to state that each method must have a unique signature. If a method encounters an error,
it can throw an exception, which provides some indication of what has gone wrong, provides some
indication of what has gone wrong.
Fields: A value of some type.
Events: A mechanism for communicating with other types. Each event includes methods for subscribing
and unsubscribing and for sending the event to subscribers.
Properties: In effect, a value together with specified methods to read and/or write that value.
Nested Types: A type is defined inside another type. A common example of this is defining a class that is
nested inside another class.
Given this basic understanding of type members, we can now look at the types themselves. Among the
most important are the following:
Class: A CTS class can have methods, events, and properties; it can maintain its state in one or more
fields; and it can contain nested types. A class’s visibility can be public, which means it’s available to any
other type, or assembly, which means it’s available only to other classes in the same assembly. Classes
have one or more constructors, which are initialization methods that execute when a new instance of this
class is created. A class can directly inherit from at most one other class and can act as the direct parent
for at most one inheriting child class.
Interface: AN Interface can include methods, properties, and events. Unlike classes, interfaces do
support multiple inheritance, so an interface can inherit from one or more other interfaces simultaneously.
An interface does not actually implement anything, however. Instead, it provides a way to group type
definition together; leaving the implementation to whatever type supports the interface.
Array: An array is a group of values of the same type. Arrays can have one or more dimensions, and their
upper bounds and lower bounds can be set more or less arbitrarily. All arrays inherit from a common
System.Array type.
Delegate: A delegate is effectively a pointer to a method. All delegates inherit from a common
System.Delegate type, and they are commonly used for event handling and callbacks. Each delegate has a
set of associated members called an invocation list. When the delegate is invoked, each member on this
list gets called; with each one passed the parameters that the delegate received.
Converting Value Types to Reference Types: Boxing
There are cases when an instance of a value type needs to be treated as an instance of a
reference type. For example, suppose we would like to pass an instance of a value type as a parameter to
some method, but that parameter is defined to be a reference to a value rather than the value itself. For
situations like this, a value type instance can be converted into reference type instance through a process
called Boxing. When a value type instance is boxed, storage is allocated on the heap, and the instance’s
value is copied into that space. A Reference to this storage is placed on the stack, as shown in the figure.
A boxed value type instance can also be converted back to its original form, a process called unboxing.
The Common Language Specification
The CTS defines a large and fairly complex set of types. Not all of them make sense for
all languages. Yet one of the key goals of the CLR is to allow creating code in one language, then calling
that code from another. Unless both languages support the same types in the same way, doing this is
problematic. Still, requiring every language to implement every CTS type would burden some to language
developers.
The solution to this problem, a compromise called the Common Language Specification (CLS). The CLS
defines a subset of the CTS that a language must obey if it wishes to interoperate with other CLS-
compliant languages. The CLS defines a subset of the CTS to enable cross-language interoperability. One
important thing to note about the rules laid down by the CLS is that they apply only to externally visible
aspects of a type. A language is free to do anything it wants within its own world, but whatever it exposes
to the outside world and thus potentially to other languages it is constrained by the CLS.
2. Compiling Managed Code: MSIL
When source code written in a CLR-based language is compiled, two things are produced:
instructions expressed in Microsoft Intermediate Language (MSIL), and metadata, information about
those instructions and the data they manipulate.
Compiling managed code written in any language produces MSIL and metadata describing that
MSIL.
The figure illustrates this process. The code being compiled contains three CTS types, all of them
classes. When this code is compiled using whatever compiler is appropriate for the language it’s written
in, the result is an equivalent set of MSIL code for each class along with metadata describing those
classes. Both the MSIL and the metadata are stored in a standard Windows portable executable (PE) file.
This can be either a DLL or an EXE file.
The figure shows an abstract view of a module produced by a CLR-based compiler. The file
contains the MSIL code generated from the types in the original program, which once again are the types
in the original program, which once again are the three classes X, Y and Z. Along with the code for the
methods in each class, the file contains metadata describing these classes and any other types defined in
this file. This information is loaded into memory when the file itself is loaded, making the metadata
accessible when the file itself is loaded, making the metadata accessible at runtime. Metadata can also be
read directly from the file contains it, making information available even when code isn’t loaded into
memory. The process of reading metadata is known as reflection.
What Metadata Contains
Metadata describes the types contained in a module. Among the information it stores for a type
are the following things.
The type’s name
The type’s visibility, which can be public or assembly
What type this type inherits from, if any
Any interfaces the type implements
Any methods the type implements
Any properties the type exposes
Any events the type provides.
More detailed information is also available. For example, the description of each method includes
the method’s parameter and their types, along with the type of the method’s return value.
Attributes:
Metadata also includes attributes. Attributes are values that are stored in the metadata and can
be read and used to control various aspects of how this code executes. Attributes can be added to types,
such as classes, and to fields, methods, and properties of those types.
Developers can also create custom attributes used to control behavior in an application-
specific way. To create a custom attribute, a developer using a CLR-based programming languages such
as C# or VB can define a class that inherits from System.Attribute. An instance of the resulting class will
automatically have its value stored in metadata when it is compiled.
3. Organizing Managed Code: Assemblies
In .Net Framework applications, files that make up a logical unit of Functionality are
grouped into an assembly. An assembly is one or more files that comprise a logical unit. Assemblies are
fundamental to developing, deploying, and running .Net Framework applications.
Metadata for Assemblies: Manifests
An assembly’s manifest, by contrast, contains information about all of the modules and
other files in an assembly. A manifest is metadata about an assembly. The manifest is contained in one of
the assembly’s files, and it includes information about the assembly and the files that comprise it.
An Assembly is often just a single DLL, but it can also include more than one file.
The figure shows, an assembly can be built from a single file or a group of files. With a single-
file assembly, the manifest is stored in the file itself. With a multiple assembly, the manifest is stored in
one of the files in the assembly. In either case, the manifest describes the entire assembly, while the
metadata in a particular module describes the types in that module. Among the things an assembly’s
manifest includes are the following:
The name of the assembly:
All assemblies have a text name and can optionally have a strong name.
The assembly’s version number: This number has the form <major version>.<minor version>.<build
version>.<revision>. The versioning is per assembly, not per the module.
The assembly’s culture: indicating the culture or language an assembly supports.
A list of all files contained in this assembly, together with a hash value that’s been computed from those
files.
What other assemblies this one depends on and the version number of each of those dependent
assemblies.
Most assemblies consist of just a single DLL. Whether it contains one file or multiple files, however, an
assembly is logically an indivisible unit.
Categorizing Assemblies:
There are various ways to categorize assemblies. One distinction is between static and
dynamic assemblies. Static assemblies are produced by a tool such as Visual Studio, and their contents are
stored on disc. Most developers will create static assemblies, since the goal is usually to build an
application that can be installed one or more machines and then executed. It’s also possible to create
dynamic assemblies, however. The code (and metadata) for a dynamic assembly is created directly in
U20CSCM02- C# AND .NET PPROGRAMMING 23
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
memory and can be executed immediately upon creation. Once it has been created, a dynamic assembly
can be saved to disk, then loaded and executed again. Probably the most common examples of dynamic
assemblies are those created by ASP.NET when it processes .aspx pages.
Another way to categorize assemblies is by how they are named. Completely naming any
assembly requires specifying three things: the assembly’s name; its version number; and if one is
provided, the culture it supports. All assemblies have simple text names, such as “Account Access”, but it
also includes the usual three parts of an assembly name. A strong name includes the usual three parts of
an assembly name, but it also includes a digital signature computed on the assembly and the public key
that corresponds to the private key used to create that signature. Strong names are unique and so can be
used to identify a particular assembly unambiguously. If desired, it’s also possible to embed the certificate
of the entity creating an assembly’s digital signature in the assembly itself. This allows anyone using the
assembly to decide whether they trust this entity and so are willing to execute the assembly. The CLR
performs version checking on assemblies with strong names.
4. Executing Managed Code:
Assemblies provide a way to package modules containing MSIL and metadata into
units for deployment. Assemblies are loaded into memory only when they are needed.
Loading Assemblies:
When an application built using the .NET Framework is executed, the assemblies that
make up that application must be found and loaded into memory. Assemblies aren’t loaded until they’re
needed, so if an application never calls any methods in a particular assembly, that assembly won’t be
loaded.
If the assemblies are not loaded automatically, the CLR determines what version of a
particular assembly it’s looking for. By default, it will look only for the exact version specified for this
assembly in the manifest of the assembly from which the call originated.
Once it has determined exactly which version it needs, the CLR checks whether the
desired assembly is already loaded. If it is, the search is over; this loaded version will be used. If the
desired assembly is not already loaded, the CLR will begin searching in various places to find it. The first
place the CLR looks is usually the global assembly cache (GAC), a special directory intended to hold
assemblies that are used by more than one application.
If the assembly it’s hunting for isn’t in the global assembly cache, the cache continues its
search by checking for a codebase element in one of the configuration files for this application. If one is
found, the CLR looks in the location this element specifies, such as a directory, for the desired assembly.
Finding the right assembly in this location means the search is over and this assembly will be loaded and
used. Even if the location pointed to by a codebase element does not contain the desired assembly,
however, the search is nevertheless over. A codebase element is meant to specify exactly where the
assembly can be found. If the assembly is not at that location, something has gone wrong, the CLR gives
up, and the attempt to load the new assembly fails.
If there is no codebase element, however, the CLR will begin its last-ditch search for the
desired assembly, a process called probing, in what’s known as the application base. This can be either
the root directory in which the application is installed or a URL, perhaps on some other machine. If the
elusive assembly isn’t found here, the CLR continues searching in several other directories based on the
name of the assembly, its culture, and more.
Compiling MSIL
A compiler that produces managed code always generates MSIL. Yet MSIL can’t be
executed by any real processor. Before it can be run, MSIL code must be compiled yet again into native
code that targets the processor on which it will execute. Two options exist for doing this: MSIL code can
be compiled one method at a time during execution, or it can be compiled into native code all at once
before an assembly is executed.
JIT Compilation
The most common way to compile MSIL into native code is to let the CLR load an assembly
and then compile each method the first time that method is invoked. Because each method is compiled
only when it’s first called, the process is called just-in-time (JIT) compilation.
The first time class Z’s method 1 is called, the JIT compiler is invoked to translate the method’s
MSIL into native code
When Class Y’s method 4 is called, the JIT compiler is once again used to translate the method’s
MSIL into native code.
in an executable form. The CLR invokes the JIT compiler, which class Z’s method 1 and redirects calls
made to that method to this compiled native code. The method can now execute.
Similarly in figure 2 class Y’s method 1 calls its own method 4. As before, this method is
still in MSIL, so the JIT compiler is automatically invoked, and the method is compiled. Once again, a
reference to the MSIL code for the method is replaced with one to the newly created native code, and the
method executes.
Figure 3 shows what happens when class Y’s method 1 again calls method 1 in class Z.
This method has already been JIT compiled, so there’s no need to do any more work. The native code has
been saved in memory, so it just executes. The JIT compiler isn’t involved. The process continues in this
same way, with each method compiled the first time it is invoked.
When a method is JIT compiled, it’s also checked for type safety. This process, called
verification, examines the method’s MSIL and metadata to ensure that the code makes no illegal accesses.
Creating a Native Image: NGEN
Instead of JIT compiling, an assembly’s MSIL code can be translated into native code for
a particular processor all at once using the Native Image Generator contained in the file Ngen.exe, this
command-line tool can be run on an assembly to produce a directly executable image. Rather than being
JIT compiled one method at a time, the assembly will now be loaded as native code. This makes the
initial phase of the application faster.
It’s probably fair to say that ordinary JIT compilation is the right choice in the majority of cases.
Securing Assemblies:
An assembly defines a scope for types, a unit of versioning, and a logical deployment unit. An
assembly also defines a security boundary. The CLR implements two different types of security for
assemblies: Code access security and role-based security.
Code Access Security
Now most machines are connected to a global network. It’s often useful to download code
from the internet and run it locally, but the potential security risks in doing this can be huge. A malicious
developer can create an application that looks useful but in fact erases your files or floods your friends
with e-mail or performs some other destructive act. CLR-based code is allowed to do depend on the
intersection of two things: what permissions that code requests and what permissions are granted to that
code by the security policy in effect when the code executes. To indicate what kinds of access it needs, an
assembly can specify exactly what permissions it requires from the environment in which it’s running.
Some examples of permissions an assembly can request are the following:
UIPermission: Allows access to the user interface.
FileIOPermission: Allows access to files or directories
FileDialogPermission: Allows access only to files or directories that the user opens in a dialog box.
PrintingPermission: Allows access to printers.
EnvironmentPermission: Allows access to environment variables.
RegistryPermission: Allows access to an assembly’s metadata
When an assembly is loaded, the CLR examines the evidence it provides. It looks at the
permissions this assembly request and compares them with the security policy established for the machine
on which the assembly is being loaded. The assembly is granted any requested permissions that are
allowed by the security policy.
Role Based Security
Code access security allows the CLR to limit what a particular assembly is allowed to do
based on the assembly’s name, who published it, and where it came from. But the code access security
provides no way to control what an assembly is allowed to do based on the identity of the user on whose
behalf the assembly is running. Providing this kind of control is the goal of role-based security.
U20CSCM02- C# AND .NET PPROGRAMMING 28
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
The foundation for role based security is a principal object. This object contains both the
identity of a user and the roles to which they belong. A user’s identity is indicated by an identity object,
which contains both the user’s identity, expressed as a name or an account, and an indication of how that
identity has been authenticated. In an all-Windows environment, for example, authentication might be
done with Kerberos, while some other mechanism might be used on the Internet. The user’s role typically
identifies some kind of group the user belongs to that is useful for deciding what that user is allowed to
access.
Code in an assembly can demand that only users with a specific identity or a specific role be
allowed to access it. This demand can be made for a class as a whole or for a specific method, property, or
event. Whatever granularity is chosen, the demand can be made either imperatively or declaratively. For
imperative demands, the code must make an explicit call to cause a check, while in declarative demands,
the code contains attributes that are stored in metadata and then used by the CLR to check the user’s
identity automatically. In either case, the result is the same: The user will be granted access to this class,
method, property, or event only if their identity or role matches what the assembly specifies.
Garbage Collection
The managed heap plays an important role in the execution of a .NET framework
application. Every instance of a reference type-every class, every string, and more-is allocated on the
heap. As the application runs, the memory allotted to the heap fills up. Before new instances can be
created, more space must be made available. The process of doing this is called garbage collection.
Describing Garbage collection
When the CLR notices that the heap is full, it will automatically run the garbage collector.
To understand how garbage collection works, we must know about the way reference types are allocated.
string “Hello”, the integer value 14, and a reference to the boxed integer value 169. The two reference
types – the string and the boxed integer – have their values stored on the heap.
When the garbage collector runs, it scans the heap looking for this kind of garbage. Once it
knows which part of the heap is garbage, it rearranges the heap’s contents, packing more closely together
those values that are still being used.
The CLR garbage Collector examines first the most recent generation of objects and reclaiming
any unused space occupied by garbage.
Finalizers
Every object on the heap has a special method called a finalizer. By default, however, this method
does nothing. If a type needs to perform some final clean-up operations before it is destroyed, the
developer creating it can override the default finalizer, adding code to do whatever is required. Before an
object with a finalizer is freed, it is placed on the finalize list. Eventually, each object on this list will have
its finalizer run.
Application Domain
A runtime host can provide this function. The runtime host loads and initializes the CLR and then
typically transfers control to managed code. ASP.NET provides a runtime host, as does SQL Server 2005,
Internet Explorer, and other applications.
A runtime host creates one or more application domains within its process. Each process contains
a default application domain, and each assembly is loaded into some application domain within a
particular process. Application domains are commonly called app domains, and they’re quite a bit like a
traditional operating system process. Like a process, an app domain isolates the application it contains
from those in all other app domains. But because multiple app domain can exist inside a single process,
communication between them can be much more efficient than communication between different
processes.
App domains can be used in a variety of ways. For example, ASP.NET runs each Web
Application in its own app domain. This allows the application to remain isolated from each other.
The figure shows App domain 1, the default app domain, contains assemblies A, B and C.
Assemblies D and E have been loaded into app domain 2, while assembly F is running in app domain 3.
Even though all of those assemblies are running in a single process, each app domain’s assemblies are
completely independent from those in the other app domains.
App domains also serve another purpose. Different systems have quite different process models,
especially systems used on small devices. By defining its own “process” model with app domains, the
.NET Framework can provide a consistent environment across all these platforms.
Conclusion
The CLR introduces many new ideas for Windows developers.
Managed Code, software built on the .NET Framework, relies on the CLR to provide many
different services.
The figure shows a process running a CLR – based application. The process includes a runtime
host, a single app domain, and the CLR itself. Some of the CLR’s most important components are shown,
including the loader, the JIT compiler, and the garbage collector. Within the app domain, there’s a single
loaded assembly containing the three classes X, Y and Z along with their metadata. Some methods in the
classes have already been JIT-compiled, while others have not. And as the figure shows, variables of
various value and reference types are in use by this running code. There’s even some garbage on the heap
waiting to be collected.
Every .NET Framework developer needs a basic knowledge of the class library
Fundamental services such as performing basic input and output, serializing an object’s state, accessing
metadata via reflection, working with XML, using transactions, interoperability with other Windows
software, and building native Windows GUIs.
Services for creating Web application that interact with people. This critically important area is addressed
by the browser – oriented aspects of ASP.NET.
Services for working with data. This mostly means support for working with data in DBMSs, such as that
provided by ADO.NET, but XML data is also important.
Services for creating distributed applications. This includes the Web Services aspects of ASP.NET, along
with .NET Remoting and Enterprise Services.
Fundamental Namespaces:
The .Net Framework class library provides so many services that it’s challenging to decide which ones
are most fundamental.
1. Input and Output: System.IO
Like most software, .Net Framework applications need some way to input and
output data. These operations are most commonly done against some kind of disk storage, but there are
other possibilities too. The .Net framework class library’s System.IO namespace contains a group of types
that developers can use to read and write files, work with directories in a file system, and do other kinds
of straightforward data access.
Among the most important of these types is the stream class. This defines the useful abstraction of a
stream, which is a sequence of bytes together with the methods to read the stream’s contents, write those
contents, perhaps seek a specific location in the stream, and perform other operations. Stream is an
abstract from it. The goal is to let developers work with various kinds of information in a consistent way.
Information stored in files can be accessed using the file class. While an instance of File provides familiar
methods for working with files such as Create, Delete, and Open, it doesn’t provide methods for reading
and writing a file’s contents. Instead, a file objects create and Open methods return an instance of a
FileStream that can be used to get at the file’s contents. Like all streams, a FileStream objects provides
Read and Write methods for synchronous access to a file’s data, that is, for calls that block waiting for
data to be read or written. Also like other streams, FileStreams objects allow asynchronous access using
the paired BeginRead/EndRead and BeginWrite/EndWrite methods. These methods allow a .Net
Framework application to begin a read or write operation and then check later to get the result. Each
FileStream also provides a Seek method to move to designated point in the file, a Flush method to write
data to the underlying device, a Close method to close the FileStream, any more.
FileStream works only with the binary data, however, which isn’t always what’s needed. System.IO
provides other standard classes to work with file data in other formats. For example, a class called
FileInfo can be used to create FileStreams, but it can also be used to create instances of the classes
StreamReader and StreamWriter. Unlike File, whose methods are mostly static, an instance of a FileInfo
class must be explicitly created before its methods can be used. Once a FileInfo object exist, its OpenText
method can be used to create a new StreamReader object. This StreamReader can then be used to read
characters from whatever file is associated with the FileInfo object.
C # Example that illustrates how these classes can be used:
Using System;
Using System.IO;
Class FileIOExample
{
Static void main ()
{
FileStreamfs;
FileInfo f;
StreamReadersr;
byte [ ] buf = new byte [10];
string s;
int i;
for (i=0; i<10; i++)
buf [i] = (byte) (65 +i);
fs = File.Create (“test.dat”);
fs.Write (buf, 0, 10);
fs.Close ( );
f = new FileInfo (“test.dat”);
sr = f.OpenText ( );
s = sr.ReadToEnd ( );
Console.WriteLine (“{0}”, s);
}
}
The class contains only a Main method, which begins with several declarations. After this, the 10-
byte buffer buf is populated with the characters, “A” though “J”. Because buf can accept only bytes, this
is done by explicitly calculating each character’s value and then forcing the result to be of type byte.
File’s Create method is then used to create a file, followed by a call to file’s Write method. This method
writes buf’s ten characters into that file and is followed by a Close call that closes the file. Because the
File class declares all of these methods to be static, they can be invoked without explicitly creating a File
instance.
The example opens next opens the same file using an instance of the FileInfo class. Calling the
FileInfo Object’s OpenText method returns a StreamReader object whose ReadToEnd method can be
Readers also provide methods to read single characters, blocks of characters, and lines of characters.
Finally, the characters read from the file are written to the console, yielding the result
ABCDEFGHIJ
System.IO also defines several other useful types. The Directory class, for instance, provides
methods such as CreateDirectory to create a new directory, delete to destroy an existing directory and its
contents, and several more. The MemoryStream class allows the typical operations defined for a stream,
such as Read, Write, and Seek, to be carried out on an arbitrary set of bytes in memory. StringWriter and
StringReader provide analogous functions to StreamWriter and StreamReader, except that instead of
working with files, they work with in-memory strings. BinaryReader and BinaryWriter allow reading and
writing values of types such as integers, decimals, and characters from a stream. While information stored
in relational databases is more important for many applications, data stored in files still matters. The
classes in System.IO provide a flexible set of options for working with that data.
2. Serialization: System.Runtime.Serialization(Nov 2018)
Objects commonly have state. An instance of a class for example, can have one or more fields,
each of which contains some value. It’s often useful to extract this state from an object, either to store the
state somewhere or to send it across a network. Performing this extraction is called serializing an object,
while the reverse process, recreating an object from serialized state, is known as deserializing. Somewhat
confusingly, the term serialization is commonly used to refer to the ability to do both.
The .Net Framework class library provides support for serialization. The work of serialization is
done by a particular formatter, each of which provides a Serialize and Deserialize method. The .NET
Framework class library provides two varieties of formatter. The binary formatter, implemented by the
BinaryFormatter class in the System.RunTime.Serialization.Formatters.Binary namespace, serializes an
object into a straightforward binary form designed to be compact and quick to parse. The SOAP
formatter, implemented by the SoapFormatter class in the System.RunTime.Serialization.Formatters.Soap
namespaces, serializes an object into a SOAP message.
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary
Module SerializationExample
<Serializable ( ) > Class Employee
Public Name As String
Public Age As Integer
End Class
Sub Main ( )
Dim E1 As Employee = New Employee ( )
Dim E2 As Employee = New Employee ( )
Dim FS AsFileStream
Dim BinFormAsBinaryFormatter = _New BinaryFormatter ( )
E1. Name =”Bob”
E1.Age =36
FS = File.Create (“test.dat”)
BinForm.Serializable (FS, E1)
FS.Close ( )
FS = File.Open (“test.dat”, FileMode.Open)
E2 = BinForm.Deserialize (FS)
Console.WriteLine (“E2 Name: {0}”, E2.Name)
Console.WriteLine (“E2 Age: {0}”, E2.Age)
End Sub
End Module
3. XML: System.Xml
XML is certainly among the most important new technologies to emerge in the last few years.
Recognizing this, Microsoft has chosen to use XML in many different ways throughout the .NET
Framework. The .NET Framework class library includes a substantial amount of support for working with
XML technologies, most of it contained in System.Xml namespace.
The XML Technology Family
To get a sense of what. the System.Xml namespace provides requires understanding a bit about
the family of XML technologies The familiar angle bracket form of XML implies a logical hierarchy of
related information. This abstract set of information and relationships is known as the XML document’s
Information Set, a term that’s usually shortened to just Infoset. An Infoset consists of some number of
information items, each of which represents some aspect of the XML document from which this Infoset
was derived. For example, every Infoset has document information item that acts as the root of the tree,
with a single root element information item just beneath it. Most Infosets have some number of child
element information items below this root element.
For example, consider this simple XML document:
<employees>
<employee>
<name> Bob </name>
<age> 36 </age>
</employee>
<employee>
<name> Casey </name>
</employee>
</employees>
The Infoset for this document can be represented as shown in the figure.
/employee/employee/name
This simple XPath request first identifies each employee element below the root employees
element and then identifies the values of each name element in each of those employee elements. Far
more complex queries are also possible, including queries that use comparison operators, compute sums,
include wildcards, and much more. With XPath, a developer need not write their own code to search
through information. Instead, this standard language can be used to find information represented as an in-
memory XML document.
Another technology built on the abstract foundation provided by XML Infosets is the Extensible
Stylesheet Language Transformations, universally referred to as XSLT. XSLT is a mechanism for
specifying transformations of XML documents using an XSLT Stylesheet. For instance, a set of ASLT
rules that transforms an XML document from one schema to another can be defined, XSLT also relies on
the abstract form of an XML document represented by its Infoset, and it relies on XPath for some of its
functionality.
defined to work against the Infoset, allowing them to remain independent itself. The data need not
necessarily come from a traditional XML document as long as it can be represented as an Infoset.
The XML standards don’t mandate any particular approach to processing the information in an XML
document. As it happens, two styles of APIs have come into common use. In one approach, the
information in an XML document is read sequentially, traversing a document’s tree in a depth-first
search. An API that supports this kind of access is referred to as a streaming API and one common choice
for this simple API for XML (SAX). SAX was created by a group of volunteers independent of the W3C
or other formal standard groups, but it is supported by many vendors today.
In the second approach, the entire document is represented as an in-memory data structure, which allows
an application to navigate through it, moving back and forth as needed. The most commonly used API for
this option is an implementation of the Document Object Model (DOM) defined by the W3C. Because of
the style of access it allows, the DOM is an example of a navigational API.
What System.Xml Provides
The System.Xml namespaces has a variety of support for working with XML. Among the features
available is support for both streaming and navigational APIs, the ability to use XPath queries, the ability
to perform XSLT transformations, and more.
The most fundamental types for handling XML-defined data are contained directly in System.Xml itself.
Among these fundamental types is the class XmlReader, which provides a streaming interface for reading
the information in an XML document sequentially. This is the fastest option for reading XML-defined
data, but it’s also somewhat limited in that no navigation is possible through the document.
The XmlReader class provides a Create method that can be passed an instance of the XmlReaderSettings
class. Based on the properties specified in XmlReaderSettings, the newly created XmlReader instance can
behave in different ways. The properties that can be specified via XmlReaderSettings include the
following:
ConformanceLevel: Indicates whether this XML document should be checked for conformance. This
means making sure that document is well formed by ensuring that elements are properly nested and
performing other checks. Conformance checking of the entire document is the default.
ValidationType: Indicates whether this XML document should be validated, i.e., verified for correctness,
when it is read. The document can be validated against either an XML schema or a document type
definition (DTD), which is an older way of defining the structure of XML documents. By default, no
validation is done.
CheckCharacters: Indicates whether this XML document should be checked for characters that aren’t
legal in XML and for invalid XML names. This property’s default value is true.
IgnoreComments: Indicates whether comments should be ignored when this XML document is read. The
default is false.
System.Xml also includes an XmlWriter class. The methods in this class allow writing XML information,
angle brackets and all, to a stream. The .Net Framework provides a create method on the XmlWriter class,
along with an XmlWriterSettings class that can be passed in when a new XmlWriter instance is created.
Some example properties that can be specified using XmlWriterSettings are:
Encoding: Determines how characters in the XML document will be encoded. The default is UTF8, but
the choices include ASCII, Unicode, and others.
Indent: Determines whether elements in the XML document are indented. The default is false.
IndentChars: If the indent is true, determines the characters used to indent, such as a tab or three spaces.
The default is two spaces.
System.Xml also includes the XMLDocument class. The methods and properties provided by
XmlDocument give some idea of the kinds of operations the DOM allows. Those methods include the
following:
Load: Loads an Xml document and parses it into its abstract tree form.
Save: Saves as in-memory document to a stream, file, or some other location.
InsertBefore: Inserts a new node, represented as an instance of a class called XmlNode, in front of the
currently referenced node in the tree.
InsertAfter: Inserts a new node, once again an XmlNode instance, in back of the currently referenced
node in the tree.
SelectNodes: Allows selecting nodes using an XPath expression.
XmlDocument also exposes a number of properties that allow navigation through the tree. They include
the following:
HasChildNodes: Indicates whether the current node has any nodes beneath it
FirstChild: Returns the first child of the current node.
LastChild: Returns the last child of the current node.
ParentNode: Returns the parent, that is, the node immediately above the current node.
Several other namespaces are defined beneath System.Xml:
System.Xml.Schema: Contains classes for creating and working with XML Schema definitions. Because
this language is quite complex, this namespace contains a large set of classes, including a class for each of
the elements in the XML Schema language. Microsoft refers to these classes collectively as the schema
Object Model (SOM)
System.Xml.XPath: Contains types that support using XPath expression to query hierarchical data.
Among them is the XPathDocument class, which allows read only access to an XML document via an
instance of the XPathNavigator class.
System.Xml.Xsl: Contains types that support using XSLT. The most important of these is the
XslCompiledTransformed class, which allows transforming data using an XLST style sheet.
System.Xml.Serialization: Contains types that allow serializing data into an XML format. This is another
large namespaces, but a key type within it is the XmlSerializer class. This class provides serialize and
Deserialize methods that write and read an object’s state in XML. The System.Xml.Serialization
namespaces also contains many other classes that allow customizing the serialization process and other
aspects of converting between state information stored in a language object and the XML form of that
information.
XML has become an essential part of modem computing. By providing a standard way to describe
information, it fills an important hole in the complex, multivendor world we live in. The .NET
Framework’s large set of namespaces and types devoted to XML are intended to make this important
technology significantly easier to use.
4. Interoperability: System.Runtime.InteropServices
Before the release of .NET Framework, the world of Windows development was
dominated by the Windows DNA technologies. Lots of applications were built using COM, Active Server
Pages, COM+, and the rest of the DNA family, and those applications still exists. Many of them play an
important role in running businesses, so they’re certain to remain in use for at least the next few years.
.NET Framework must provide some way for new applications to connect with them.
Accessing COM Objects:
Interoperability with COM objects requires mapping between the CLR’s types system and that defined by
COM. System.Runtime.InteropServices provide very fine grained control over how the mapping is done
as well as many, many options. The fundamental model for interoperation between managed code and
COM-based code is that each side sees the other in the form it expects: Managed code sees COM – based
code as managed types, while COM-based code sees managed code as managed types, while COM-based
code sees managed code as COM objects.
The .Net Framework’s COM interoperability services can make a COM object look like managed
code and managed code look like a COM object.
To provide this illusion, the .NET Framework relies on two kinds of wrappers. One known as a runtime
callable wrapper (RCW), allows managed code to call a COM object. The other, a COM callable wrapper
(CCW), allows COM code to access managed code.
Managed code sees the world in terms of assemblies, so to access a COM object as a managed code; an
assembly that mimics the COM class must exist. Furthermore, this assembly must contain metadata that
accurately reflects the COM class’s interfaces. To create this interoperability assembly, the .NET
Framework provides a tool called Tlbimp, also known as the Type Library Importer. The input to this tool
U20CSCM02- C# AND .NET PPROGRAMMING 42
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
is a COM type library, and the output is an assembly that contains metadata for the CLR analogs of the
COM types in the type library.
Once this assembly has been created, managed code can treat the library’s COM classes just any other
managed code. When the managed code creates an instance of the class, the RCW actually creates the
COM object. When the managed code invokes a method, the RCW makes a corresponding method
invocation on the COM object. If an error occurs and the COM method returns an error HRESULT, as
COM requires, the RCW automatically turns this into an exception that can be caught by the managed
code. And when the managed code is finished using the object, it can behave just as it does when using
any other managed object. The RCW will decrement the COM object’s reference count before it is itself
destroyed by the CLR’s garbage collector.
When a COM client uses a managed class, the same kinds of things happen in the opposite directions.
Rather than producing as an assembly from an assembly. The type Library Exporter tool, known as
Tlbexp, provides a way to do this. Also, because COM uses the registry to determine which code should
be loaded for a particular class, assemblies that will be accessed by COM clients must have appropriate
registry entries. The Assembly Registration tool, Regasm, can be used to do this and optionally to register
the assembly’ generated type library as well. When a COM client creates and uses an instance of a
managed class, translations between the two worlds are performed as before, but this time they’re done by
the CCW rather than the RCW.
All of this sounds simple and straightforward, and it often is. Yet what’s not been addressed so far is the
process of converting between the CLR type system and the COM type system. To do this, the wrappers
must translate data between the two environments. Default mappings are defined, and if those defaults
work, using code from the other world is simple. Marshalling an integer, for example, is straightforward,
since a value of this type is the same in both environments. If the default mappings aren’t appropriate,
however, a developer’s life gets more complex. COM has more than one string format, and it’s not always
obvious which one should be used. To control this and other marshalling choices, a developer can use the
MarshalAs attribute to indicate the choice they prefer.
One last point worth noting is that making calls across the boundary between managed and unmanaged
code is noticeably more expensive than making calls solely within either environment. In simple words,
calls between managed and unmanaged code are expensive. To access the Non COM DLLs the developer
must specify the name of some DLL they wish to use, the entry point to be called, the parameter list, and
possibly other information.
System.Runtime.InteropServices is a critically important part of .NET Framework class library. If a new
code written on the .NET Framework had no way to communicate with the installed base, this new
platform would have been much less attractive. The Framework’s strong support for interoperability with
existing code recognizes this reality.
5. Windows GUIs: System.Windows.Forms
Most applications interact with the people in some way. To allow this, the .NET
Framework provides three primary approaches to creating user interfaces:
Console applications that interact with the user one line at a time. This class provides
methods such as WriteLine and ReadLine to interact with users through a simple line-at-a-time approach.
Even though it’s convenient for simple examples, console applications aren’t common today- real
Windows software seldom uses this approach.
Windows forms applications that interact with users via a windows graphical user interface (GUI). Mostly
defined by the types in the System.Windows.Forms namespace, this technology lets developers create
applications that interact directly with a local user’s display, mouse, and keyboard. Especially for
standalone applications, Windows Forms is a common choice for creating user interfaces today.
ASP.NET: Applications that interact with users via a web browser. Relying primarily on the types in the
System.Web.UI namespace, ASP.NET lets developers build applications that interact with users via a
web browser such as Internet Explorer or Firefox. The web is a staple of modern life, and so it’s fair to
say that a majority of new .NET Framework applications interact with users through ASP.NET.
Building Application with Windows Forms:
It can sometimes seem as if browser-based applications have taken over the world. Many developers who
once focused on getting the Windows GUI right now focus HTML and JavaScript. Browsers have
become the new default interface for a whole generation of software. But Windows GUIs still matter. The
ascendancy of browsers not withstanding, applications that access pixels on a local screen are not going
away. Recognizing this fact, the designers of the .NET Framework provided Windows Forms, a full set of
classes that allow CLR-based applications to build Windows GUIs.
In window forms, every form is an instance of the Form class, while the message loop that accepts and
distributes events is provided by a class called Application. Using these and other classes in
System.Windows.Forms, a developer can create a single-document interface (SDI) application, able to
display only one document at a time, or a multiple-document interface (MDI) application, able to display
more than one document simultaneously.
Each instance of the form class has a large set of properties that control how that form looks on the
screen. Among them are Text, which indicates what caption should be displayed in the title bar; Size,
which controls the form’s initial on-screen size; DesktopLocation, which determines where on the screen
the form appears; and many more. Developers set these properties to customize a form’s appearance and
behavior.
Forms commonly contain other classes called Windows Forms Controls. Each of these controls typically
displays some kind of output, accepts some input from the user, or both. The System.Windows.Forms
namespace provides a large set of controls, many of which will be familiar to anyone who’s built or even
used a GUI. The control classes available in this namespace include Button, TextBox, CheckBox,
RadioButton, ListBox, ComboBox, and many more. Also provided are more complex controls such as
OpenFileDialog, which encapsulates the operations that let a user open a file; SaveFileDialog, which
encapsulates the operations that let a user save a file; PrintDialog, which encapsulates the operations that
let a user print a document; and several others.
Like a form, each control has properties that can be set to customize its appearance and behavior. Many of
these properties are inherited from System.Window.Forms.Control, the base class for every control. The
Button control, for example, has a location property that determines where the button will appear relative
to its container and a size property that determines how big the on-screen button will be, both of which
are directly inherited from the parent Control class. Button also has properties that aren’t directly
inherited from this parent, such as a Text property that controls what text will appear in the button.
Forms and controls also support events. Some examples of common events include Click, indicating that
a mouse click has occurred; GotFocus, indicating that the form or control has been selected by the user;
and KeyPress, indicating that a key has been pressed. All of these events and several more are defined in
the base Control class from which all forms and controls inherit. As with properties, a control can also
support unique events that have meaning only to it. A developer can create code to handle events received
by a form or control. Called an event handler, this code determines what happens when the event occurs.
Windows Forms Controls:
Windows Form controls are useful way to package reusable chunks of functionality. Although the .NET
Framework class library provides a large set of controls, the inventiveness of developers knows no
bounds. Accordingly, the .NET Framework makes it straightforward to write custom Window Forms
controls. As already mentioned, every Windows Forms control must inherit either directly or indirectly
from the class control. It’s also possible to inherit from one of the standard controls provided with the
.NET Framework class library, basing a new control on existing functionality, or to combine two controls
into one new one. Whatever choice the control’s creator makes, a good chunk of the work is done.
Windows applications built before the .NET era relied on COM-based components known as ActiveX
controls. Despite being fairly complicated to create, huge numbers of these were created by third parties.
Many containers capable of running ActiveX controls also exist, such as Internet Explorer. Given this
large installed base of both ActiveX controls and containers for those controls, Microsoft needed to
provide someway for Windows Forms controls to interoperate with this world.
Windows Forms controls can emulate ActiveX controls. Windows Forms provide a common mechanism
for creating GUIs in any CLR-based language.
USES OF WEB FORMS & WEB SERVICES
Interoperability has Highest Priority
When all major platforms could access the Web using Web browsers, different platforms could
interact. For these platforms to work together, Web-applications were developed. Web-applications are
simple applications that run on the web. These are built around the Web browser standards and can be
used by any browser on any platform.
Web Services take Web-applications to the Next Level
By using Web services, your application can publish its function or message to the rest of the world.
Web services use XML to code and to decode data, and SOAP to transport it (using open protocols).
With Web services, your accounting department's Win 2k server's billing system can connect with
your IT supplier's UNIX server. Web Services have Two Types of Uses
Reusable application-components.
There are things applications needs very often. Web services can offer application-components like:
currency conversion, weather reports, or even language translation as services.
Connect existing software.
Web services can help to solve the interoperability problem by giving different applications a way to link
their data. With Web services you can exchange data between different applications and different
platforms.
6. .NET Remoting: System.Runtime.Remoting
Given that Web Services provide a quite general mechanism for communication between software on
different machines, a simple minded view might suggest that Web services are all that’s required. After
all, this technology can be used on both intranets and the Internet, and it potentially allows the client and
server to be written using software from different vendors. Mapping from the CLR’s type system into the
one defined by XML can be problematic, and depending on how it’s done, this translation might lose
some information. Web services are necessary but not sufficient.
Another problem is that the XML-based serialization used in Web Services is not very efficient. We may
have to live with this for Internet-based communication, since XML and SOAP are becoming the world’s
common mechanisms for exchanging information. In simple words, serializing data into XML isn’t
always the best choice. It’s sometimes useful for the same object instance to handle multiple calls.
.NET Remoting addresses these concerns. While it is possible to expose SOAP-based Web Services using
.NET Remoting, it’s typical to use this part of the class library when both ends of the communication are
using the .NET Framework. Whether they are communicating across an intranet or over the Internet
through firewalls, the communicating systems will then have the same type system, a common set of
available communication protocols, and even the same implementation of those protocols.
.NET remoting provides traditional RPC functionality, allowing a client to invoke a method in a remote
object and have some result returned. It can also be used for asynchronous calls, however, as well as one-
way calls that have no result. The mission of .NET Remoting is to make all of these interactions as simple
yet as flexible as possible.
An Overview of the Remoting Process:
Although the word remoting implies communication between different machines, it’s
used a bit more broadly in the .NET Framework. Here, remoting refers to any communication between
objects in different application domains, whether those app domains are on the same machine or on
machines connected by a network.
Calls to remote objects rely on a proxy object in calling app domain and channel objects in both
app domains.
The figure shows a very high-level view of the major components of the remoting process.When a client
calls a method on an object in another app domain, that call is first handled by a proxy object running in
the client’s app domain. The proxy represents the remote object in the client’s app domain. The proxy by
using reflection to access the metadata of the remote object being accessed.
A proxy eventually hands a call’s information to a channel object. The channel object is responsible for
using some appropriate mechanism, such as a TCP connection, to convey the client’s request to the
remote app domain. Once the request arrives in that app domain, a channel object running there locates
the object for which this call is destined, perhaps creating it if the object isn’t already running. The call is
then passed to the object, which executes it and passes any results back through the same path.
At a high level, the process is simple. In fact, however, there’s much more going on than this description
shows. It’s possible, for instance, to insert code that intercepts and customizes the in-progress call at
several points in the path between caller and the object. In fact, the details of .NET Remoting can fairly
involved-remote access is never simple to implement well-but thankfully, most of the complexity can
remain invisible to developers.
Passing Information to Remote Objects
Calling a method in an object is straightforward when both the client and the object are in
the same app domain. Parameters of value types such as integers are passed by value, which means that
their contents are simply copied from client to object. Parameters of reference types, such as classes, are
passed by reference, which means that a reference types, such as classes, are passed by reference, which
means that a reference to the instance itself is passed- no separate copy is made. Calling a method in an
object gets more complicated when the two are in different app domain, however, and so .NET Remoting
must address these complications. For one thing, accessing a remote object’s properties or fields require
some way to transfer information across an app domain boundary. The process of packaging values for
transfer to another app domain is called marshalling, and there are several options for how it gets done.
One option is marshal by value (MBV). As the name suggest, transferring an instance of some type using
this option copies its value to remote app domain. For this to work; a user-defined type must be
serializable, that is, its definition must be marked with the serializable attribute. When an instance of that
type is passed as a parameter in a remote call, the object’s state is automatically serialized and passed to
the remote app domain. Once it arrives, a new instance of that type is created and initialized using the
serialized state of the original. An MBV object should usually be reasonably simple, or the cost of
serializing and transferring the entire object to the remote app domain will be very high.
It’s also possible to pass an instance of a reference type across an app domain boundary by reference.
This option, called marshal by reference (MBR), is possible only with reference types that inherit from
MarshalByRefObject, a class contained in the System namespace. When an MBR object is passed across
an app domain boundary; only a reference to the object is passed. This reference, which is more complex
than the one used to construct a proxy back to the original object in its home app domain, is used to
construct a proxy back to the original instance of this object. Passing MBR objects as parameters make
sense in cases where the overhead of accessing the object remotely is less than the cost of making a copy
of the object.
Marshal by value objects are copied when passed across an app domain boundary, while marshal
by reference objects have a proxy created for them in remote app domain.
The figure illustrates the difference between MBV and MBR objects. When object X, an MBV object in
app domain 1, is passed to app domain 2 as a parameter on a call to object O, a copy of X is created in the
remote app domain. Passing object Y, however, does not result in a copy of Y being created in app
domain 2 because Y is an MBR object. Instead, a proxy to Y is created, and all accesses to objects Y are
sent back to the instance of Y in app domain 1.
Finally, if a user-defined type isn’t serializable and doesn’t inherit from MarshalByRefObject, it neither
an MBV nor an MBR object. In this case, instances of that type can’t be marshaled across an app domain
U20CSCM02- C# AND .NET PPROGRAMMING 48
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
boundary at all. In other words, any instance of this type can be used only within the app domain in which
it is created.
Choosing a Channel:
Applications using .NET Remoting ultimately rely on channels to convey calls and responses between
app domains. Three standard channels are provided: a TCP channel, an HTTP channel, and an
interprocess communication option called the IPC channel. It’s also possible to build custom channels
when necessary. While not especially simple to create, a custom channel might provide special security
services, use a nonstandard protocol, or perform some other function in a unique way. It’s safe to assume,
however, that most applications will work happily with one of the three choices built into the .NET
Framework.
The TCP channel is the best choice for fast machine-to-machine communication. By default, it serializes
and deserializes a call’s parameters using the binary formatter, although SOAP formatter can be used
instead. Once the parameters have been serialized, they’re transmitted directly in TCP packets. The TCP
channel can also provide authentication and data encryption if required.
The second option, the HTTP channel, uses the SOAP formatter by default to serialize a call’s
parameters. Rather than sending those parameters directly over TCP, they’re sent as SOAP request and
responses embedded in HTTP. It’s also possible to use the binary formatter with the HTTP channel,
which can be useful for communication through firewalls. The binary formatter is more efficient than the
SOAP formatter, so if the .NET Framework is on both sides of the communication, this option makes
sense. For applications that need distributed security, the HTTP channel can use the security options
provided by Internet Information Services (IIS) protocol with HTTP, an option sometimes referred to as
HTTPS.
The third choice is the IPC channel. Rather than allowing communications between applications on
different machines, the IPC channel is intended for communication between applications in different
processes on the same machine. It uses named pipes, a standard Windows mechanism for interprocess
communication.
Deciding which channel to use depends on your goals. If the communication is across-machine and
entirely within an organization’s intranet – if no firewalls will be traversed – used the fast and simple TCP
channel. If a cross machine communication must go through firewalls, however, as do most packets sent
on the Internet, use the HTTP channel. Although it’s a bit less efficient, riding on HTTP means passing
through port 80, the only port that virtually all firewalls leave open. Also, if the goal is to provide a
standard Web Service whose clients might not be based on the .NET Framework, the HTTP channel is the
only .NET Remoting option we can use. And for communication between processes on the same machine,
the IPC channel is the obvious choice.
It’s also possible for a single application to use different kinds of channels simultaneously. This allows
clients to communicate with remote objects using the mechanism that’s most appropriate for each one. A
client, for instance, might use the more efficient TCP channel to talk to an object inside the firewall while
also invoking methods in an object across the Internet via the HTTP channel.
details of the exposed type, such as the URL at which it can be found, without recompiling the server
code. However it’s done, registering a type doesn’t actually create an instance of that type.
Once a server is running and has registered an appropriate type for a single-call object, a client can invoke
method on that object. A client has two choices for how it does this. The first lets the client use the
standard new operator provided by CLR-based languages such as C# and visual base (VB). With this
option, the client application first tells the .NET Framework’s remoting infrastructure various things, such
as what channel to use, the type of the remote object, and a URL at which that object can be found. As
with the server, this can be done either by using explicit calls or by referencing a configuration file. Note
that to access a remote object, the client must know the URL at which it can be found (there’s no built-in
support for using a directory service such as Active Directory to learn this information). Alternatively,
rather than explicitly passing the remoting infrastructure the information required to access the remote
object, a client can specify this information in a configuration file, just like the server. Whichever
approach a developer chooses, the client code can now create instances of the remote object using the new
operator.
If a developer is willing to forgo the relative convenience of using the standard new operator, she can use
another approach for accessing a remote single-call object. Rather than setting up for accessing a remote
single-call object. Rather than setting up the configuration information and then calling new, a client can
instead call the Activator class’s GetObject method. The parameters to this call include the type of the
object to be accessed and the URL at which the object can be found. Instead of specifying these
separately, as in the previous case, they’re passed directly on this call.
Whichever choice is used, however, neither one actually creates an instance of the remote object. Instead,
single-call objects are server-activated, which means that the server creates an instance of the object only
when a method call actually arrives. And because they’re single-call objects, the object is destroyed after
the call completes.
Singleton Objects:
Like single-call objects, singleton objects are activated by the server. Accordingly, the steps required for
the server to register and the client to access a singleton object are similar to those just described for a
single-call object. The only difference is that the server specifies a mode of singleton instead of
SingleCall on its call to RemotingConfiguration. RegisterWellKnownServiceType or in the configuration
file. On the client, the code is exactly the same as with single-call object.
The behavior of the object is not the same, however. Unlike a single-call object, which gets destroyed
after each method call, a singleton object stays active until its lifetime expires. Since a singleton object
isn’t destroyed between calls, it can maintain state internally. Yet because the same instance is accessed
by all clients that use this singleton, that state is potentially accessible by any of these clients.
If another client makes a call on a singleton class after the running instance of that class has died, a new
instance will be created. This new instance will handle all calls from all clients until its lifetime expires.
However, that for a singleton object accessible at a given URL, there is never more than one instance of
the class active at any time.
Client-Activated Objects:
Even though a client can use the new operator to “create” an instance of a single-call or singleton object,
the server doesn’t really create this instance until the first method call from the client arrives. This is why
these two choices are called server-activated: The server is in charge of determining when activation
occurs. Client-activated objects, by contrast, are explicitly created when the client requests it. The server
still does the actual creation, of course, since that’s where the object is running – the name is something
of a misnomer. Still, the distinction between client activated objects is significant. The most important
difference is that with client-activated objects, each client gets its own object instance, and each object
can maintain internal state specific to its client between method calls – the object isn’t destroyed after
call. Instead, each client activated object has a lease that determines when the object is destroyed.
Just as with the first two types of remotely accessible objects, the server must register the type before the
client can access it. As before, this can be done either through explicit calls or via a configuration file. To
create the object, the client can also make explicit calls, much like the previous cases, or rely on a
configuration file. In either case, the client can use either the new operator or make an explicit call to the
CreateInstance method provided by the Activator class. Both of these directly contact the server, which
then creates an instance of the specified client-activated type. All calls made by the client to this object
will be handled by the instance, and each client that creates a client activated object of this type will have
its own instance.
A client-activated object is destroyed when its lease expires. .Net Remoting provides a diverse group of
options. Remotely activating and accessing objects is inherently nontrivial. Is it better to provide many
options, running the risk of making the technology too complex to use? Or should the design stay simple,
supporting only the most common scenarios? .Net Remoting aims for a middle ground, offering built-in-
services for common situations while still allowing enough complexity to address more advanced
applications. Pleasing everybody is hard, but .Net Remoting offers enough choice to please at least most
of the people most of the time.
7. Enterprise Services: System.EnterpriseServices
Prior to .NET, the Microsoft technology that provided these services was known as COM+. With the
advent of the .NET Framework, those applications are still available to CLR-based applications. In fact,
the services themselves haven’t changed much at all, but two things about them have: how they’re
accessed and what they’re called. Now known as Enterprise Services, all of the traditional COM+
services for building robust, scalable applications are usable by applications written on the .NET
Framework.
What Enterprise Services Provides:
For a class to use Enterprise Services, that class must inherit from
EnterpriseServices.ServicedComponent. Because of this, a class using services is referred to as serviced
component. Serviced components have access to the full range of what Enterprise Services provides,
including the following:
Support for transactions.
Object pooling, which allows instances of a class to be pooled and reused rather than
being destroyed and recreated.
Role-based authorization services that allow Enterprise Services to verify a client’s role
and then grant services only to clients in specific roles.
One of the innovations brought by COM+ was the ability to control what services a
component received by setting attributes in a configuration file. In the .NET Framework, however,
attributes are supported directly. Every assembly can have extra metadata represented as attributes, and
attributes values can be set in the source code of a CLR-based application. This built-in support for
attributes matches well with how COM+ provides its services, and so an Enterprise Services developer
specifies in his code. And because it’s sometimes useful to be able to change a component’s attributes
after the assembly that contains it has been installed, it’s still possible to set or modify a deployed
component’s attributes if desired.
Enterprise Services and COM+
Unlike most of the .NET Framework, the code that provides COM+ services was not
rewritten as managed code. Instead, the classes in System.EnterpriseServices provide a wrapper around
the existing implementation that allows managed objects access to these services. In spite of this, serviced
components are able to use those services without leaving the managed environment.
COM+ maintains context information for serviced components, allowing it to provide services
across the managed/unmanaged boundary.
In the figure, the key COM+ services such as transactions are provided using context
information maintained by COM+ itself in unmanaged code. When this context is accessed, such as when
a serviced component votes to commit or abort a transaction that request flows across the boundary
between managed and unmanaged code. Interactions among serviced components, however, remain
completely within the managed environment provided by the CLR. Since crossing into unmanaged code
incurs a slight performance penalty, this ability to remain almost entirely within the managed space is a
good thing.
An important part of the standard COM+ is an interface called IObjectContext that
contains fundamental methods for components to use. Perhaps the most important of these are
SetComplete and SetAbort, the two methods that allow a component to explicitly cast its vote in a
transaction. In Enterprise Services, these same methods are available through a class called ContextUtil.
If a transactional method wishes to control its commitment behavior directly, it can do so by calling these
methods.
Enterprise services also have a few more artifacts of its foundation in unmanaged code.
For example, when a serviced component is accessed remotely, that access relies on DCOM rather than
on .NET Remoting. Similarly, serviced components must have entries in the Windows registry, like
traditional COM+ components but unlike other .NET Classes. These entries can be created and updated
automatically by the Enterprise Services infrastructure-there’s no need to create them manually- but
requiring them at all betrays this technology’s COM foundations.
Enterprise Services is an important part of the .NET Framework. While it’s used by only
a minority of applications, the services it provides significantly simplify the lives of the people who create
those applications. And while its implementation as a veneer on the old COM+ introduces some
messiness, this technology nevertheless succeeds in bringing these essential services into the .NET world.
The high level programming languages that need to be compiled require a runtime, so that the
architecture on which the language runs is provided with details on how to execute its code. All the
programming languages use its corresponding runtime to run the application. For example, to run an
application developed using Visual Basic, the computer on which the application will be run must be
installed with the Visual Basic runtime. The Visual Basic runtime can run only the applications developed
with Visual Basic and not the ones developed with any other programming language like Java.
In the .NET Framework, all the Microsoft .NET languages use a common language runtime, which
solves the problem of installing separate runtime for each of the programming languages. Microsoft .NET
Common Language Runtime installed on a computer can run any language that is Microsoft .NET
compatible.
The main advantage of the .NET Framework is the interoperability between different languages. As
all the Microsoft .NET languages share the same common runtime language, they all work well together.
For example, you can use an object written in C# from Visual Basic.NET. The same applies for all the
other Microsoft .NET languages.
When you compile a Microsoft.NET language, the complier generates code written in the Microsoft
Intermediate Language (MSIL). MSIL is a set of instructions that can quickly be translated into native
code.
A Microsoft.NET application can be run only after the MSIL code is translated into native machine
code. In .NET Framework, the intermediate language is complied "just in time" (JIT) into native code
when the application or component is run instead of compiling the application at development time. The
Microsoft.NET runtime consists of two JIT compilers. They are standard JIT compiler and the EconoJIT
compiler. The EconoJIT compiler compiles faster than the standard JIT compiler, but the code it produces
is not as optimized as the code obtained from the standard JIT compiler.
sml.net
SML.NET is a compiler for the functional programming language Standard ML that targets the .NET
Common Language Runtime and which supports language interoperability features for easy access to
.NET libraries.
Much more accurate and reliable Intelligence; hovering over a keyword reports the type of its
smallest enclosing expression; hovering over a pattern reports the types of its bindings.
Bindings in the Locals window now enter and exit scope appropriately. The values of sub-
expressions, not just identifiers, are reported as locals in Locals window. Most constructed values now
have symbolic tags derived from the constructor name. Values of heap-allocated SML datatypes now
support ToString () and ToString (int depth) methods that can be invoked in the VS Immediate window to
inspect values at runtime. Improved stepping behavior. SML.NET stack frames now typically have
meaningful, not mangled, source names.
The distribution has been updated to support the current 2.0 release of the Microsoft .NET
Framework and Microsoft Visual Studio .NET 2005. SML.NET remains compatible with the initial 1.0
and 1.1 releases. NB: Although SML.NET fully supports SML polymorphism, it does not yet produce or
consume .NET generics (we hope to in future): this release just allows you to continue working with your
existing SML.NET code on the Whidbey platform.
SML.NET now makes much better use of locals and the stack; pattern matching is compiled as a
switch when appropriate.
Including: the annoying (but benign) overflow error when persisting compilation units has been fixed;
SML.NET now exploits some previously missed opportunities for tail-recursion.
Features
Support for all of Standard ML
Support for the Basis library
Seamless interoperability with other languages
SML.NET extends the SML language to support safe, convenient use of the .NET Framework
libraries and code written in other languages for the CLR, such as C# or VB. SML.NET can both
consume and produce .NET classes, interfaces, delegates etc.
Command-line compilation
SML.NET supports traditional compilation from the command-line.
Interactive compilation environment
Automatic dependency analysis
In either mode of compilation, the compiler requires only the names of root modules and a place
to look for source code. It then does dependency analysis to determine which files are required and which
need recompilation.
Produces verifiable CLR IL
The output of the compiler is verifiable MSIL (Microsoft Intermediate Language) for the CLR.
Whole program optimization
SML.NET performs optimizations on a whole program (or library) at once. It usually produces
small executables with fairly good performance.
Integration with Visual Studio .NET
A binary distribution includes an experimental package for Microsoft Visual Studio .NET 2002, 2003 and
& 2005 that allows you to edit, build and debug SML.NET projects from within the development
environment
5. Describe in detail the architecture of Asp.Net (Apr’16)
ASP.NET works on three tier architecture. This architecture is extremely popular because they
increase application performance, scalability, flexibility, and code reuse. In three tier
architecture, applications are divided into three major areas of functionality:
- The data layer manages the data storage and retrieval.
- The business layer maintains business rules and logic
- The presentation layer manages the user interface and related presentation code.
The presentation Layer
Presentation layer provides the interface to the users of website or application. It contains
pages like .aspx or Windows forms where data is presented to the user or user enters the
information. This layer communicates with business layer. In ASP.NET the code behind file and
HTML file are separate file. The HTML file defines the look and layout of the web form and the
code behind file contains the presentation logic. This separation helps designers and developers.
Designers don't have to worry about business logic to make user interface changes, and
developers don't have to worry about to update code.
The business Layer
Business layer or Application layer acts between Application layer and Data Access Layer. This
layer contains our logic, validating the data and other functions. In this layer programmer access
U20CSCM02- C# AND .NET PPROGRAMMING 56
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE
the data access layer (also known as the DAL), functionality. As example suppose any user
wants to register and he fills all the detail and click the submit button on presentation layer then
call goes to business layer. In business layer programmers only access the function and pass the
parameter that is provided by the end user as example.
InserUserDetails(string Username, string Password, string Email, string Firstname, string
Lastname, string Address, float Salary);
The data Layer
All the code related to database is written in this layer. It contains methods to connect with
database. It also contains the methods to perform insert, update, delete, select data according to
the SQL query.
6. Describe in detail the steps involved in writing a simple web service (Nov’15)
Web service:
A Web Service is a reusable piece of code used to communicate among Heterogeneous
Applications.
Once a web service is created and hosted on the server in the internet it can be consumed
by any kind of application developed in any technology.
to create a Web Service
Step 1
Go to Visual Studio then click on "File" -> "Website" -> "ASP.NET empty website template".
Then provide the website name (for example: WebServiceSample).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
/// <summary>
/// used for Airthmatic calculation
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the
following line.
// [System.Web.Script.Services.ScriptService]
public class Airthmatic : System.Web.Services.WebService
{
public Airthmatic() {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public int Add(int x, int y)
{
return x + y;
}
[WebMethod]
public int Sub(int x, int y)
{
return x - y;
}
[WebMethod]
public intMul(int x, int y)
{
return x * y;
}
[WebMethod]
public intDiv(int x, int y)
{
return x / y;
}
}
Attaching the WebMethod attribute to a Public method indicates that you want the method
exposed as part of the XML Web service. You can also use the properties of this attribute to
further configure the behavior of the XML Web service method. The WebMethod attribute
provides the following properties:
BufferResponse
CacheDuration
Description
EnableSession
MessageName
TransactionOption
To see the WSDL format click on the service description link or add "?WSDL" to the URL.
Example: http://localhost:65312/WebServiceSample/Airthmatic.asmx?WSDL
It will show the WSDL.
To determine whether the functions are working, click on one of the functions (for example:
"Add").
Now you will see two TextBoxes for checking. Enter the value for x and y and click on the
"Invoke" button.
Now you will see the result in an open standard form (XML).
int a, b, c;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAdd_Click(object sender, EventArgs e)
{
a = Convert.ToInt32(txtFno.Text);
b = Convert.ToInt32(txtSno.Text);
c = obj.Add(a, b);
lblResult.Text = c.ToString();
}
protected void btnSub_Click(object sender, EventArgs e)
{
a = Convert.ToInt32(txtFno.Text);
b = Convert.ToInt32(txtSno.Text);
c = obj.Sub(a, b);
lblResult.Text = c.ToString();
}
protected void BtnMul_Click(object sender, EventArgs e)
{
a = Convert.ToInt32(txtFno.Text);
b = Convert.ToInt32(txtSno.Text);
c = obj.Mul(a, b);
lblResult.Text = c.ToString();
}
protected void btnDiv_Click(object sender, EventArgs e)
{
a = Convert.ToInt32(txtFno.Text);
b = Convert.ToInt32(txtSno.Text);
c = obj.Div(a, b);
lblResult.Text = c.ToString();
}
}
2 MARKS
1. What is NET Framework? (Nov’13) (Ref.Qn.No.3, Pg.no.4)
2. Draw the diagram the .NET Framework (or) What are the main components of
.NET? (Nov’13) (Ref.Qn.No.4, Pg.no.4)
3. What is boxing? (Apr’13) (Ref.Qn.No.5, Pg.no.4)
4. What is Unboxing? (Apr’13) (Ref.Qn.No.6, Pg.no.5)
5. Define Common Language Runtime (CLR) (May’14) (Ref.Qn.No.7, Pg.no.5)
6. What is Just‐In‐Time (JIT)? (May’14) (Ref.Qn.No.14, Pg.no.6)
7. What is Microsoft Intermediate Language (MSIL)? (Dec’14) (Ref.Qn.No.19, Pg.no.7)
8. What are the components included in the .NET platform? (Nov’13) (Ref.Qn.No.22,
Pg.no.7)
9. Write about the type variables (NOV 2013) (Ref.Qn.No.26, Pg.no.8)
10. Write down some of the namespaces available in the .NET framework? (NOV 2012 )
(Or) Discuss .NET Namespaces (Ref.Qn.No.28, Pg.no.8)
11. What is Remoting? (NOV’12) (Ref.Qn.No.33, Pg.no.10)
12. Name any four applications that are supported by .NET Platform (Apr’16)
(Ref.Qn.No.36, Pg.no.11)
13. Distinguish between the .NET Framework and Java Environment (Dec’14)
(Ref.Qn.No.37, Pg.no.11)
14. Differentiate between classes and objects (Nov’14) (Ref.Qn.No.38, Pg.no.12)
11 Marks
1. Discuss the two elements of .NET Framework (NOVEMBER 2013) (Ref.Qn.No.1,
Pg.no.13)
2. Explain how to organizing and executing managed code. (NOVEMBER 2013)
(Ref.Qn.No.2(4), Pg.no.27)
3. Explain in detail about Namespace/Class and its purpose in .NET Framework.
(APRIL 2012) (Ref.Qn.No.1 & 3, Pg.no.13 & 35)
4. Briefly explain Common type system. (Nov’12) (Ref.Qn.No.2(1), Pg.no.19)
5. Describe about the components of .NET framework. (APRIL 2013)
(Nov’15)(Apr’16)(Ref.Qn.No.1, Pg.no.13)
6. Discuss about the following: (APRIL 2013) (Ref.Qn.No.3(3), Pg.no.25)
a. Web Services
b. Assemblies.
7. Explain .net framework in detail (Nov’13) (Nov’15) (Apr’16) (Ref.Qn.No.1, Pg.no.13)
8. Explain the .NET Framework Class Library: (Apr’15) (Nov’14) (Ref.Qn.No.3,
Pg.no.35)
9. Explain the common language runtime in detail (Nov’14) ) (Ref.Qn.No.2, Pg.no.17)
10. Write about Garbage collection (Nov’14) ) (Ref.Qn.No.2, Pg.no.18)
11. Explain Microsoft Intermediate Language (MSIL) (May’14) (Ref.Qn.No.2, Pg.no.24)
12. Describe in detail the architecture of Asp.Net (Apr’16) (Ref.Qn.No.5, Pg.no.59)
13. Describe in detail the steps involved in writing a simple web service (Nov’15)
(Ref.Qn.No.6, Pg.no.60)