Upload
seenivasan-sr
View
218
Download
0
Embed Size (px)
Citation preview
7/31/2019 DOTNET Technologies Monograph
1/158
Page | 1
10377MC403 - .Net Technologies
10377MC403 - .NET TECHNOLOGIES
UNIT-I
DISTRIBUTED APPLICATION
A distributed application is an application whose processing is distributed across
multiple networked computers.
Distributed applications are able to concurrently serve multiple users.
Distributed applications are typically implemented as client/server systems that are
organized according to the
User Interface (web browser)
Information Processing
Information Storage Layer.
Types of Application Architectures
Applications are developed to support organizations in their business operations.
Applications accept input, process the data based on business rules and provide
data as output.
The functions performed by an application can be divided into three categories
User services
Business services
Data services
These three layers form the base of the models or architectures used in application
development.
Applications may vary from single tier architecture to multitier architecture.
1. Single Tier Architecture:
Single executable files handles all functions relating to the user, business
and data service layers.
Such an application is called as monolithic application.
KLNCIT Department of ComputerApplications (MCA)
Monolithic Application
User
services
Business
services
Data
services
7/31/2019 DOTNET Technologies Monograph
2/158
Page | 2
10377MC403 - .Net Technologies
2. Two Tier Architecture:
The two tier architecture divides an application into the following two
components
1. Client: implements the user interface.
2. Server: stores data.
In case of 2-tier architecture the user and data services located separately
either on the same machine or on separate machine.
In the two tier architecture, the business service layer may be implemented in
one of the following ways.
i. By using fat client
ii. By using fat server
iii. By dividing the business services between the user services and the
data services.
FAT CLIENT:
In case of fat clients,
The business services layer is combined with the user services layer.
Client executes the presentation logic and enforces business rules.
The server stores data and processes transactions.
The fat client model is used when the server is overloaded.
FAT SERVER:
In case of fat server,
The business service layer is combined with the data service layer.
As business services are stored on the server, most of the process takes place on
the server.
KLNCIT Department of ComputerApplications (MCA)
CLIENT
Usertier
Business
Logic
Server
Datatier
7/31/2019 DOTNET Technologies Monograph
3/158
Page | 3
10377MC403 - .Net Technologies
Dividing business services between the user and data services.
3. Three Tier Architecture:
Three layers reside separately either on the same machine or on different
machine.
The user interface interacts with the business logic. The business logic
validates the data sent by the interfaces and forwards it to the database if it
conforms to the requirements.
The front end only interacts with the business logic, which in turns, interact
with the database.
4. N-Tier Architecture:
Uses business objects for handling business rules and data access.
It has multiple servers handling business services.
Provides advantages like
o Extensibility
o Resilience to change
o Maintainability
o Scalability of the application
Most modern enterprise applications are based on the n-tier architecture.
COM/DCOM
COM is a binary interface standard introduced by Microsoft in 1993.
It is used to enable inter-process communication and dynamic creation of
objects in large range of programming languages.
The term COM is often used by the Microsoft as an umbrella term that
encompasses OLE, ACTIVE X CONTROL, DCOM TECHNOLOGIES.
KLNCIT Department of ComputerApplications (MCA)
Client
User
Services
Businesslogic
Business
Services
Data store
Data
Services
7/31/2019 DOTNET Technologies Monograph
4/158
Page | 4
10377MC403 - .Net Technologies
COM is a binary interface technology which uses interfaces and it can reuses
the object with no knowledge of their implementation.
There is no direct interaction between client and server. They interact through
the interface.
COM is similar to the other technologies like CORBA, JAVABEANS.
Although each has its own advantages and disadvantages.
History
Dynamic data exchange:
The first method of inter-process communication in windows is Dynamic Data
Exchange introduced by Microsoft in 1987.
DDE allows windows applications to communicate with each other.
Two window programs can carry on DDE conversation by posting messages to
each other.
Two programs are known as the Server and Client.
A DDE server is the program that has access to the data that may be useful to other
windows program.
A DDE client is the program that obtains this data from the server.
Application that support DDE:
MS Word
MS Excel
SQL
Word Pro etc.
FOR EXAMPLE:
A cell in Microsoft Excel could be linked to a value in another application and when the
value changed, it would be automatically updated in the Excel spreadsheet.
OBJECT LINKING AND EMBEDDING
Microsoft first object based framework.
Built on the top of DDE
Designed specifically for compound documents.
Object Linking means references to a data in another file.
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
5/158
Page | 5
10377MC403 - .Net Technologies
Object Embedding means embed the data into file.(animation, video, audio )
ACTIVE X CONTROLS:
Is a framework for defining reusable components in a programming language
independent way.
Introduced in 1996 as a development of COM and OLE.
Applications are
Internet explorer.
MS office
MS visual Studio
Windows Media Player
NOTE: ACTIVE X CONTROLS can be written in any programming languages like VB,
C#, C++, ATL and MFC.
THE COM:
The COM is a component software architecture that allows application and
systems to be built from components supplied by different software vendors.
COM provides higher level software services like
o Reusable, programmable controls.
o Compound documents
o Automation and data transfer
o Storage and naming.
These services are distinctly different functionality to the user however shares
fundamental requirements that allows binary software component supplied by
various vendors to communicate with each other in a well defined manner.
COM provides
Binary standard for component interoperability.
Is programming language independent
Is extensible
Communications between component
Shared memory management between components.
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
6/158
Page | 6
10377MC403 - .Net Technologies
Dynamic loading of components.
COM has
Interfaces:
A base interface provides a way for components to dynamically discover the
interface implemented by other components.
Applications are interact with each other through collections of functions called
interfaces.
An interface is the definition of an expected behavior and expected
responsibilities.
Reference Counting:
To allow components to track their own time and delete themselves when
appropriate.
GUID:
Global Unique Identifier.
Uniquely identifies components and their interfaces.
DCOM
Extensions to the COM environment.
Competitor of CORBA.
Provides distributed component communication.
Network OLE.
The main aim is to intercept all the local interprocess communication messages
and substitute them with a network based on the DCE.
The protocol must be responsible for routing the request through a network
environment.
Advantages of DCOM:
Providing shared memory management
Interact with network regard to interoperability
Marshalling
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
7/158
7/31/2019 DOTNET Technologies Monograph
8/158
Page | 8
10377MC403 - .Net Technologies
All unwanted complexities are eliminated and a pure object oriented model was
introduced.
.NET Framework comes with a single class library. The code written in c#, VB
.NET or J# can use the .NET class library.
.NET FRAMEWORK
Microsoft wanted to make WWW applications more vibrant by enabling individual
devices, computers and web services to work together.
The .NET Framework is designed as integrated environment for developing and
running applications on the internet, on the desktop as windows form and even on
the mobile devices.
It integrates Presentation technologies, Component technologies and Data
technologies on a single platform so as to enable the users to develop a Internet
applications as easily as they do on desktop.
.NET Framework is a layer between the OS and Programming Languages.
Components of .NET FRAMEWORK
The .NET Framework consists of three main components
1. CLR
2. .NET Framework Base Classes
3. The User and the program interfaces
1. COMMON LANGUAGE RUNTIME:
The CLR is the heart and soul of the .NET framework
.NET framework supports multiple languages and instead of giving separate
runtime environment for each languages it provide a common environment to
execute the program.
The CLR provides number of services that includes,
Loading and executing the program
Compile the Intermediate Language (IL) code to native machine code.
Memory allocation
Garbage Collection
Type Safety
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
9/158
Page | 9
10377MC403 - .Net Technologies
Security
Interoperability with other systems
Managing exceptions and errors.
Components of CLR: Class Loader - loads classes into the runtime.
MSIL to native code compiler -this converts the IL code to Managed native code.
Code Manager - this manages the code during execution.
Garbage Collector -provides automatic memory management and avoids
memory leaks.
Security Engine this enforces security restrictions and code access security.
Type Check this enforces strict type checking.
Thread support this provides a mechanism multi threading support to
applications.
Exception Manager this provides a mechanism to handle runtime exceptions.
Debug engine allow you to debug differenttype of applications
COM Marshaller - this allows .net applications to exchange data with COM
applications.
Base class library thisprovide a type of applications needed at the runtime.
Compilation and execution of a .net application
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
10/158
Page | 10
10377MC403 - .Net Technologies
Steps to run a program in CLR
1. Write a source code in a .NET complaint language.
2. Using the specific compiler compile the source code into Microsoft Intermediate
Language code. (MSIL or IL) MSIL code contains CPU independent set of
instructions, which describes how to load, store, initialize and call.
3. To execute the code, the runtime requires information about the program called
metadata. The metadata describes the code and defines the types that the code
contains as well as references to other types that the code uses at run time. The
MSIL code and metadata both are located in PE file (Portable Executable).
4. The PE files and all other relevant information from the base class library are sent
to the class loader. The class loader loads the code into the memory. The
execution starts from the entry point which is main method.5. The garbage collector performs periodic checks on the managed heap to identify
the object no longer required by the program and removes from the memory
6. The applications running within the CLR can utilize the managed multithreading
support. The .net framework allows a single process to be divided into one or
more sub-process called application domain. Each application domain can contain
KLNCIT Department of ComputerApplications (MCA)
Source Code
DevelopmentMachineCompiler
Exe/DLL (IL)
Class Loader
JIT Compiler
Managed native code
ExecutionSecurity check
Class libraries
Target Machine
7/31/2019 DOTNET Technologies Monograph
11/158
Page | 11
10377MC403 - .Net Technologies
one or more processes. The runtime monitors all the threads that have executed a
code within its process.
7. The CLR allows the managed code to interoperate with unmanaged code which
is done by the COM Marshaller.
8. With the help of JIT compiler the IL code is converted into native code. Which we
can say that the IL set of instructions is converted into CPU specific instructions.
9. After translation the code is sent to the .NET runtime manager.
10. The .NET runtime manger runs executes the code. While executing security check
is performed to ensure that the code has the appropriate permissions for accessing
the available resources.
UNDERSTANDING MANAGED CODE:
Managed code is a code that executed directly by the CLR.
The applications created using managed code automatically include the CLR
services such as type checking, security, automatic garbage collection.
These services provide platform and language independence for managed code
applications.
In the .NET Framework, the managed code is executed in the following sequential
manner:
Selecting a language compiler.
Compiling the code to MSIL
Compile the MSIL to native code.
Executing the code.
UNDERSTANDING 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
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
12/158
Page | 12
10377MC403 - .Net Technologies
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.
Wrapper classes are of two types: CCW (COM Callable Wrapper) and RCW
(Runtime Callable Wrapper).
CCW is the Com Callable Wrapper: This will built a bridge between the Com
Component and the .NET Component
RCW is the Runtime Callable Wrapper: This will built a bridge between .NET
Component and Com Component converts the .NET data type to Com Data type
COMMON TYPE SYSTEM (CTS):
The .NET Framework provides multiple language support using the feature known
as COMMON TYPE SYSTEM that is built into the CLR.
CTS define a common set of types that can be used with several language syntaxes
supported by the .NET Framework.
Programming languages is a collection of a specific syntax with a set of keywords.
The syntax of every programming language may differ however the underlying
idea of all programming language is same.
Though idea behind the programming language is general, it is better approach is
to keep the syntax and semantics as separate entity allowing different languages to
be used with the same set of underlying idea.
The same approach is handled by the CTS which is a fundamental part of the CLR.
The CTS does not specify any particular syntax or keyword, rather it defines how
the data of different types are going to be declared and managed in runtime.
For Example: in c# an integer variable is written as int and in VB.NET an integer
is written as Integer. The .NET framework provides a single class called
System.Int32 to work with these variables.
COMMON LANGUAGE SPECIFICATION
The CLS is a subset of CTS.
Defines set of rules to enable interoperability on the .NET platform.
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
13/158
Page | 13
10377MC403 - .Net Technologies
Guides the third-party compiler designers and library builders.
The languages supporting the CLS can use each others class libraries as if they are
their own.
API that is designed following the rules of CLS can be used by all the .NETlanguages.
2. FRAMEWORK BASE CLASSES:
.NET supplies library of classes that we cab use to implement the application
quickly.
We can use them by simply instantiating them and invoking their methods or by
inheriting them through derived classes, thus extending their functionalities
Much of the functionality in the base framework classes is in the namespace called
System.
We can use the base classes in the system namespace for many different tasks
including
3. USER AND PROGRAM INTERFACES
The .NET Framework provides the following tools for managing user and
application interface
Window forms
Console applications
Web forms
Web services
These tools enable users to develop user friendly desktop based as well as web
based applications using a wide variety of languages on the .NET platform.
.NET Languages
The .NET framework is language neutral.
We can use a number of languages for developing .NET applications.
They include
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
14/158
Page | 14
10377MC403 - .Net Technologies
ASSEMBLIES:
An assembly contains name, version, types (classes and others) created in it and
details about other assemblies it references.
An assembly may be either an executable file - .EXE or a dynamic link library -
.DLL
Assemblies can be
Static assemblies:
Includes interfaces, classes, structures and resources.
These assemblies are stored in PE file
Dynamic assemblies:
Which run directly from the memory without being saved to disk
before execution.
However, after execution they can be saved on the disk.
ELEMENTS OF ASSEMBLY
The assemblies contain four elements. They are
1. Assembly Manifest
2. MSIL code
3. Type Metadata
4. Resources
1. ASSEMBLY MANIFEST:
Every assembly contains collections of data that describes how the elements in
an assembly are related to each other.
Assembly Manifest includes the following information
Assembly Name: the text string specifying a assembly name.
Version: major, minor, revision, build number. This number was used by
the CLR to enforce version policy.
Culture:Information on the culture or language the assembly supports
Strong Name Information:The public key from the publisher if the
assembly has been given a strong name.
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
15/158
Page | 15
10377MC403 - .Net Technologies
Type Reference Information:Information used by the runtime to map a
type reference to the file that contains its declaration and implementation.
This is used for types that are exported from the assembly.
List of files in the assembly: An assembly can be made up of multiple
files
Information about referenced assemblies - Contains list of other
assemblies referenced by this assembly. For each assembly referenced
we have assembly name, version, culture and public key (if assembly is a
global assembly)
2. MSIL CODE:
MSIL code is Microsoft intermediate language.
The source code is compiled by .NET compiler that will convert the source code
into the IL code or MSIL code that is intermediate code and then this MSIL code
that resides on PE file i.e. portable executable code convert into machine code
using JIT with the help of CLR.
3. Type Metadata:
The other component of assembly is type metadata.
Metadata can be defined as data about the data; this means the metadata
contains all the information about the assembly.
Metadata defines the contents of the assembly.
Metadata contains information such as:
Classes that are there in the assembly.
Interfaces, Events, Indexers that are used in the assembly.
Structs and all the types' information.
4. Resources:
Set of resources such as bitmaps, jpeg, files.
These four elements can be in single file or in various file
TYPES OF ASSEMBLIES:
1. Private Assemblies
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
16/158
Page | 16
10377MC403 - .Net Technologies
2. Shared Assemblies
1. PRIVATE ASSEMBLIES:
The assemblies that can be used by single application.
For Example:
If you have DLL file containing information about your business logic then
this DLL can be used by your client application.
In order to run the application, the DLL should be included in the same
folder in which the client application is installed.
How to create an assembly:
The following are the steps to create a private assembly (by default all assemblies are
private) using Visual C# 2005 Express Edition.
1. Select File->New Project
2. From Templates, select Class Library
3. Enter name AdditionLibrary
4. A class library is created using a single class Class1
5. Rename class to Addition and add the following code.
using System;namespace AdditionLibrary
{
public class Addition
{protected int a, b, c;
public int addi(int a, int b)
{this.a = a;
this.b = b;
c = a + b;
return c; } } }
6. Save project using File->Save All. When prompted to enter location for project,
select the folder where you want to save your project.
7. Build (not run) the project using Build->Build Solution
Using a private assembly in a console application developed in C#
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
17/158
Page | 17
10377MC403 - .Net Technologies
1. Start Visual C# 2005 Express Edition
2. Create a new console application using File -> New Project
3. From template select Console Application as type of project
4. Give name AdditionConsole for application.
A new application is created with a single class with Main () method.
5. Go to Solution Explorer and select project
6. Right click on it and select Add References from the context menu.
7. From dialog box, select Browse tab and select
c:\csharp\AddtionLibrary\bin\release\AdditionLibrary.dll
8. Solution explorer displays AdditionLibrary as one of the references under
references node in solution explorer
9. Add the following code in Main() method ofProgram.cs
using System;
using System.Reflection;
namespace AdditionConsole
{ class Program{ static void Main(string[] args)
{AdditionLibrary.Addition aa = new AdditionLibrary.Addition();
Console.WriteLine(aa.addi(10, 20));Assembly a = Assembly.Load("AdditionLibrary");
Type t = a.GetType("AdditionLibrary.Addition");
MethodInfo[] m = t.GetMethods();foreach (MethodInfo mi in m)
Console.WriteLine(mi.Name); } } }
SHARED ASSEMBLIES
Shared assemblies are those assemblies that are placed in the GAC so that they can
be used by multiple applications.
For instance, suppose a DLL file needs to be reused in different applications.
In this scenario instead of downloading a copy of DLL file to each and every client
application, the DLL file can be placed in the GAC.
Can be done by using gacutil.exe tool.
So that any application can be accessed that DLL application.
Making a private assembly a global assembly
In order to convert a private assembly to global assembly, we have to take the following
steps.
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
18/158
Page | 18
10377MC403 - .Net Technologies
11 Create a strong name
11 Associate strong name with assembly
11 Place assembly in GAC
1. Creating a strong name Any assembly that is to be placed in GAC must have a strong name. Strong name
is a combination ofpublic key and private key.
The relationship between public and private keys are such, given one you cannot
get the other, but any data that is encrypted with private key can be decrypted only
with the corresponding public key.
Take the following steps to invoke SN (Strong Name) tool to create strong name.
1. Go to command prompt using Microsoft .NET Framework SDK v2.0 -> SDK
Command prompt
2. Go to c:\csharp\AdditionLibrary folder and enter the following command.
3. sn -k addkeyfile.snk
4. The above command writes private and public key pair into addkeyfile.snkfile.
2. Associate strong name with assembly
Once private and public keys are generated using SN tool, use the following procedure to
sign AdditionLibrary with the key file.
1. Open AdditionLibrary project.
2. Select project properties using Project -> AdditionLibrary properties
3. Select Signing tab in project properties window
4. Check Sign the assembly check box
5. Select addkeyfile.snkfile using Choose a strong name key file combo box
6. Close properties window
7. Build the solution again using Build->Build Solution
Now, AdditionLibrary.dll is associated with a public key and also digitally signedwith private key.
This ensures no one can modify this assembly as any change to assembly should re-
sign the assembly with private key of the user who created it first.
This protects the assembly from getting tampered with by others. A global assembly
needs this projection as it is placed in common place.
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
19/158
Page | 19
10377MC403 - .Net Technologies
You can verify whether the assembly is associated with public key using ILDASM (IL
Disassembler) program provided by .NET Framework.
Start ILDASM using .NET Framework SDK v2.0->Tools->MSIL Disassembler
Select AdditionLibrary.dll using File->Open
Once assembly is opened, double click on Manifest section of the assembly to see
the public key associated with the assembly.
3. Place assembly in GAC
In order to make an assembly a global assembly, the assembly must be associated
with a strong name and then placed in GlobalAssemblyCache (GAC).
GAC is a folder with name Assembly in windows folder of your system. So, place
AdditionLibrary.dll in GAC using GACUTIL tool as follows.
c:\csharp\ AdditionLibrary \bin\Release>gacutil -i AdditionLibrary.dll
After you install global assembly into GAC, you can see AdditionLibrary.dll in
windows/assembly folder.
Once, you place an assembly in GAC, any reference to the assembly will not
create a copy of the assembly in BIN directory of the application. Instead all
application that reference the assembly use the same copy that is placed in GAC.
GOBALIZATION:
The Globalization process basically includes,
1. Internationalizing the application code
2. Followed by localizing the application to other languages and cultures
11 Internationalization: This includes translate, store, retrieve, and present
application content for any locale. This means identify all parts of our application
that need to be different from respective languages.
11 Localization: adapting your application to other locales by translating and
formatting content according to culture. This involves configuring the application
for the specific languages.
11 Culture: This is the combination of Language and the location. For
example
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
20/158
Page | 20
10377MC403 - .Net Technologies
En-US - indication English spoken at United States.
En-GB - indication English spoken at Great Briton.
GARBAGE COLLECTION:
The .NET Framework's garbage collector manages the allocation and release of
memory for your application.
Each time you create a new object, the common language runtime allocates
memory for the object from the managed heap.
As long as address space is available in the managed heap, the runtime continues
to allocate space for new objects. However, memory is not infinite.
In the common language runtime (CLR), the garbage collector serves as an
automatic memory manager. It provides the following benefits:
Enables you to develop your application without having to free memory.
Allocates objects on the managed heap efficiently.
Reclaims objects that are no longer being used, clears their memory, and
keeps the memory available for future allocations. Managed objects
automatically get clean content to start with, so their constructors do not
have to initialize every data field.
Provides memory safety by making sure that an object cannot use the
content of another object.
Conditions for a Garbage Collection
Garbage collection occurs when one of the following conditions is true:
The system has low physical memory.
The memory that is used by allocated objects on the managed heap
surpasses an acceptable threshold. This means that a threshold of
acceptable memory usage has been exceeded on the managed heap. This
threshold is continuously adjusted as the process runs.
The GC.Collectmethod is called. In almost all cases, you do not have to
call this method, because the garbage collector runs continuously. This
method is primarily used for unique situations and testing.
Managed Heap:
KLNCIT Department of ComputerApplications (MCA)
http://msdn.microsoft.com/en-us/library/system.gc.collect.aspxhttp://msdn.microsoft.com/en-us/library/system.gc.collect.aspxhttp://msdn.microsoft.com/en-us/library/system.gc.collect.aspx7/31/2019 DOTNET Technologies Monograph
21/158
Page | 21
10377MC403 - .Net Technologies
After the garbage collector has been initialized by the CLR it allocates a segment
of memory called as heap to store and manage the objects.
There are managed heap for each process.
All threads in the process allocate objects on the same heap.
To reserve a memory, the garbage collector calls theVirtualAlloc function and
allocate one segment of memory.
To release a memory VirtualFree function is called
When you allocate objects it should not exceed the needed space. Such as
allocating an array of 32 bytes when you need only 15 bytes.
When a GC is triggered, it reclaims the memory from the dead objects.
Generations:
The heap is organized into generations so it can handle long-lived and short-lived
objects.
There are three generations of objects on the heap:
Generation 0:
Short lived objects. Eg: temporary variables.
GC occurs most frequently in this generation to reclaim a memory
and not survive to the next generation 1.
Newly allocated objects form a new generation collection unless
they are large objects, in which case they go on the large object
heap in a generation 2 collection.
Generation 1. This generation contains short-lived objects and serves as a
buffer between short-lived objects and long-lived objects.
Generation 2. This generation contains long-lived objects. An example of
a long-lived object is an object in a server application that contains static
data that is live for the duration of the process.
VERSIONING:
Versioning is the creation and management of multiple releases of a product, all of
which has the same general function but is improved, upgraded or customized.
KLNCIT Department of ComputerApplications (MCA)
http://go.microsoft.com/fwlink/?LinkId=179047http://go.microsoft.com/fwlink/?LinkId=179047http://go.microsoft.com/fwlink/?LinkId=179050http://go.microsoft.com/fwlink/?LinkId=179047http://go.microsoft.com/fwlink/?LinkId=1790507/31/2019 DOTNET Technologies Monograph
22/158
Page | 22
10377MC403 - .Net Technologies
In versioning, subsequent releases of a specific product receive numerical
identifiers consisting of two or three numbers separated by periods.
ver 1:0:0:0
The first number, called the major number, is increased when there are significant
improvements or changes in functionality.
The second number, called the minor number, is incremented when there are minor
feature changes or significant fixes.
The third number, if it exists, is called the revision number. It is added or increased
when minorbugs are eliminated.
UNIT 2
C# Language FundamentalsCSharp is a strongly typed language also it is an elegant and type-
safe Object Oriented Language that enables developers to build awide range of secure and robust applications that run on the .NETFramework.
An Introduction to C#
CSharp is an Object Oriented Language , introduced in the.NET Framework.
C# is a professional programming language and is very similar toC++ in many ways.
We can implement the Object Oriented concepts likeencapsulation, inheritance, and polymorphism in C#programming development.
C# is a Simple, Powerful, general-purpose and Type-Safelanguage also Case Sensitive. We can develop C# projects inVisual Studio Environment, a powerful tool-rich programmingenvironment from Microsoft.
We can create console based applications as well aswindows based applications from C# environment.
C# Coding style is very similar to C++ and JAVA , so thedevelopers who are familiar with those languages can pick up C#coding quickly.
C# Console based Application
KLNCIT Department of ComputerApplications (MCA)
http://whatis.techtarget.com/definition/0,289893,sid9_gci211714,00.htmlhttp://whatis.techtarget.com/definition/0,289893,sid9_gci211714,00.htmlhttp://whatis.techtarget.com/definition/0,289893,sid9_gci211714,00.html7/31/2019 DOTNET Technologies Monograph
23/158
7/31/2019 DOTNET Technologies Monograph
24/158
Page | 24
10377MC403 - .Net Technologies
C# command line argumentsWe can pass command line arguments to C# programs. The
program accept arguments in the order ofargs[0], args[1] etc.
The following program shows how to pass command line arguments tothe c# program.using System;class NewProg{static void Main(string[] args){Console.WriteLine("Arguments-1 " + args[0]+" Argument-2 "+args[1]);Console.ReadLine();}}
Go to the command prompt and issue the following command forcompilation.csc NewProg.cs
After the successful compilation you will get NewProg.exe file
When we execute this C# program you have to pass twoarguments with the filename.
NewProg test1 test2
We will get the output like Arguments-1 test1 Argument-2 test2
.Net Namespaces
Namespaces are the way to organize .NET Framework Class Libraryinto a logical grouping according to their functionality, usability as wellas category they should belong to, or Namespaces are logical groupingof types for the purpose of identification.
The .NET Framework Class Library (FCL ) is a large collection ofthousands of
Classes. These Classes are organized in a hierarchical tree. The System Namespaces is the root for types in the .NET
Framework. We can uniquely identify any Class in the .NET Framework Class
Library (FCL ) by using the full Namespaces of the class. In .Net languages every program is created with a default
Namespaces.
Programmers can also create their own Namespaces in .Net languages
C# Types
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
25/158
Page | 25
10377MC403 - .Net Technologies
A Type is defined as a set of data and the operations performed onthem. CSharp is a strongly typed language.The CSharp type system contains two Type categories.
Value Types
Reference Types
Value Type The Value Types store the data.
The Value Types derived from System.ValueType.
A Value Type holds its actual value in memory allocated on theStack
Reference Type
The Reference Types store references to the actual data.
Reference Types derived from System.Object.
Reference Types referred to as objects, store references to the
actual data and are managed on the heap. In C# it is possible to convert a value of one type into a value of
another type.
The operation of Converting a Value Type to a Reference Type iscalled Boxing and the reverse operation is called Unboxing.
C# boxing and unboxingC# Type System contains three Types , they are Value Types ,
Reference Types and Pointer Types. C# allows us to convert a ValueType to a Reference Type, and back again to Value Types . Theoperation of Converting a Value Type to a Reference Type is called
Boxing and the reverse operation is called Unboxing.
Boxing1: int Val = 1;2: Object Obj = Val; //Boxing
The first line we created a Value Type Val and assigned a value to Val.The second line, we created an instance of Object Obj and assign thevalue of Val to Obj. From the above operation (Object Obj = i ) we sawconverting a value of a Value Type into a value of a correspondingReference Type. These types of operation is called Boxing.
UnBoxing1: int Val = 1;2: Object Obj = Val; //Boxing3: int i = (int)Obj; //Unboxing
The first two line shows how to Box a Value Type . The next line (int i =(int) Obj) shows extracts the Value Type from the Object . That isconverting a value of a Reference Type into a value of a Value Type.This operation is called UnBoxing.
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
26/158
Page | 26
10377MC403 - .Net Technologies
Boxing and UnBoxing are computationally expensive processes. When avalue type is boxed, an entirely new object must be allocated andconstructed , also the cast required for UnBoxing is also expensivecomputationally.
C# DataTypesData Types in a programming language describes that what type ofdata a variable can hold . CSharp is a strongly typed language,therefore every variable and object must have a declared type. TheCSharp type system contains three Type categories. They are ValueTypes , Reference Types and Pointer Types . In CSharp it ispossible to convert a value of one type into a value of another type. Theoperation of Converting a Value Type to a Reference Type is calledBoxing and the reverse operation is called Unboxing .
When we declare a variable, we have to tell the compiler about what
type of the data the variable can hold or which data type the variablebelongs to.
Syntax :DataType VariableName
DataType :The type of data that the variable can hold
VariableName :the variable we declare for hold the values.
Example:
int count;int : is the data typecount : is the variable name
The above example shows, declare a variable 'count' for holdingan integer values.
The following are the commonly using datatypes in C#.
BoolThe bool keyword is an alias of System.Boolean. It is used to declare
variables to store the Boolean values, true and false. In C# , there is noconversion between the bool type and other types.
C# Runtime type : System.Boolean
CSharp declaration : bool flag;
CSharp Initialization : flag = true;
CSharp default initialization value : false
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
27/158
Page | 27
10377MC403 - .Net Technologies
Intint variables are stored signed 32 bit integer values in the range of-2,147,483,648 to +2,147,483,647
C# Runtime type : System.Int32
CSharp declaration : int count; CSharp Initialization : count = 100;
CSharp default initialization value : 0
DecimalThe decimal keyword denotes a 128-bit data type.The approximate
range and precision for the decimal type are -1.0 X 10-28 to 7.9 X 1028
C# Runtime type : System.Decimal
CSharp declaration : decimal val;
CSharp Initialization : val = 0.12;
CSharp default initialization value : 0.0M
StringThe string type represents a string of Unicode characters. string
variables are stored any number of alphabetic, numerical, and specialcharacters.
C# Runtime type : System.String CSharp declaration : string str; CSharp Initialization : str = "csharp string";
C# type conversions
Conversion is the process of changing the value of one Type toanother.System.Convert class provides a complete set of methods forsupported conversions.In CSharp type conversions are divided into two, Implicit Conversionsand Explicit Conversions . Conversions declared as implicit occurautomatically, when required and Conversions declared as explicitrequire a cast to be called.
1:int ctr = 999;2:long count = ctr;
// implicit conversion from int type to long type
From the above statements, first line declares an integer type variablectr and assigned 999 to it. Second line declare a long type variablecount and assign the value of ctr to count. Here the conversionoccurred automatically. Because we converted an integer type to longtype. This type of conversion is called Implicit Conversion .
1:int ctr = 999;2:long count = ctr;
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
28/158
Page | 28
10377MC403 - .Net Technologies
// implicit conversion from int type to long type
3:int cnt = (int)count;
// explicit conversion from long type to int type
We already saw the Implicit Conversion happened in the second line.The third line again we converted long Type to an integer type. Here weexplicitly convert long type to integer (int cnt = (int)count), otherwisethe compiler will show compiler error - Error
1 Cannot implicitly convert type 'long' to 'int'. An explicitconversion exists (are you missing a cast?). This type ofconversion is called Explicit Conversion.
The following C# source code shows how to use System.Convert classC# Access Modifiers , C# Access Specifiers Access Modifiers(Access Specifiers) describes as the scope of accessibility of anObject and its members. All C# types and type members have anaccessibility level. We can control the scope of the member object of aclass using access specifiers. We are using access modifiers forproviding security of our applications. When we specify the accessibilityof a type or member we have to declare it by using any of the accessmodifiers provided by CSharp language.
C# provide five access specifiers, they are as follows:
public private
protected
internal
protected internal.public :
public is the most common access specifier in C# . It can beaccess from anywhere, that means there is no restriction onaccessibility. The scope of the accessibility is inside class as well asoutside. The type or member can be accessed by any other code in the
same assembly or another assembly that references it.private :The scope of the accessibility is limited only inside the classes or
struct in which they are declared. The private members cannot beaccessed outside the class and it is the least permissive access level.protected :
The scope of accessibility is limited within the class or struct andthe class derived (Inherited) from this class.
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
29/158
Page | 29
10377MC403 - .Net Technologies
internal :The internal access modifiers can access within the program that
contain its declarations and also access within the same assembly levelbut not from another assembly.protected internal :
Protected internal is the same access levels of both protected andinternal. It can access anywhere in the same assembly and in the sameclass also the classes inherited from the same class .C# Statements
Statements are program instructions. Except as described,statements are executed in sequence.
C# if else statements
The conditional statement if.. else in C# is using for check theconditions that we provided in the head of if statement and
making decision based on that condition. The conditional statement examining the data using comparison
operators as well as logical operators. The else statement isoptional , so we can use the statement in two ways ;
if (condition)statement;
if (condition)statement;
elsestatement; If the condition is true then the control goes to the body of if
block, that is the program will execute the code inside if block. If the condition is false then the control goes to next level, that is
if we provide else block the program will execute the code blockof else statement, otherwise the control goes to next line of code.
If we want to check more than one conditions at the same time ,we can use else
ifstatement .if (condition)statement;else if (condition)
statement;else
statement;Just take a real-time example - We have a mark list and we want toanalyze the grading of each student. In this case we can use if..elseconational statements.
Following are the grading rule of the student:
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
30/158
Page | 30
10377MC403 - .Net Technologies
1) If the marks is greater than 80 then the student get higher first class2) If the marks less than 80 and greater than 60 then the student getfirst class3) If the marks less than 60 and greater than 40 then the student getsecond class
4) If all the above conditions failed and the marks less than 40 then thestudent is failed.Now here implementing these conditions in a C# program.1: if (totalMarks >= 80) {2: Console.WriteLine("Got Higher First Class ");3: }4: else if (totalMarks >= 60) {5: Console.WriteLine ("Got First Class ");6: }7: else if (totalMarks >= 40){8: Console.WriteLine ("Just pass only");
9: }10: else {11: Console.WriteLine ("Failed");12: }Line 1: Checking the total marks greater than or equal to 80Line 2: If total marks greater than 80 show message - "Got Higher FirstClass "Line 4: Checking the total marks greater than or equal to 60Line 5: If total marks greater than 60 show message - "Got First Class "Line 6: Checking the total marks greater than or equal to 40Line 7: If total marks greater than 40 show message - "Just pass only"
Line 9: If those three conditions failed program go to the next codingblock .Line 10: If all fails, it will show message "Failed"
C# for loopThe for loop in C# is useful for iterating over arrays and for
sequential processing. That is the statements within the code block of afor loop will execute series of statements as long as a specific conditionremains true.Syntax:
for(initialization; condition; step)
statement
initialization : Initialize the value of variable.
condition : Evaluate the condition
step : Step taken for each execution of loop body
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
31/158
Page | 31
10377MC403 - .Net Technologies
The for loop initialize the value before the first step. Then checking thecondition against the current value of variable and execute the loopstatement and then perform the step taken for each execution of loopbody.Example:
int count = 4;for (int i = 1; i < = count; i++){Console.WriteLine("Current value of i is - " + i);}
The output of the code as follows:Current value of i is - 1Current value of i is - 2Current value of i is - 3Current value of i is 4
The loop will execute four times because we set the condition i is lessthan or equal to count.for (int i = 1; i < = count; i++)initialization : int i = 1Initialize the variable i as 1, that is when the loop starts the value of i isset as 1
condition : i < = countSet the condition i < =count , that is the loop will execute up to whenthe value of i < = 4 (four times)
step : i++Set the step for each execution of loop block as i++ ( i = i +1)All of the expressions of the for loop statements are optional. Thefollowing statement is used to write an infinite loop.for (; ; ){// statements}Here the loop will execute infinite times because there is noinitialization , condition and steps.
C# while loopThe C# while statement continually executes a block of statements
until a specified expression evaluates to false .Syntax:
while (expression) statement
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
32/158
Page | 32
10377MC403 - .Net Technologies
Like if statement the while statement evaluates the expression, whichmust return a boolean value. If the expression evaluates to true, thewhile statement executes the statement(s) in the while block. The whilestatement continues testing the expression and executing its block untilthe expression evaluates to false.
using System;class WhileLoopInsteadOfFor{public static void Main (){int i ; i = 1 ; while ( i < 11 ){Console.WriteLine ( "Hello mom" ) ;i = i + 1 ;}
}}The C# while statement executes a statement or a block of statementsuntil a specified expression evaluates to false. The above program theloop will execute the code block 4 times.We can implement an infinite loop using the while statement as follows:while (true){// statements}
C# do while loopThe C# while statement executes a statement or a block of
statements until a specified expression evaluates to false. In somesituation we may want to execute the loop at least one time and thencheck the condition. In this case we can use do..while loop.The difference between do..while and while is that do..while evaluatesits expression at the bottom of the loop instead of the top. Therefore,the statements within the do block are always executed at least once.From the following example you can understand howdo..while loop function
C# switch case statementsThe C# switch statement allows us to choose from many
statements based on multiple selections by passing control to one ofthe case statements within its body. The switch statement executes thecase corresponding to the value of the expression . The switchstatement can include any number of case instances.Syntax:switch (expression)
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
33/158
Page | 33
10377MC403 - .Net Technologies
{case expression://our code herejump-statementdefault:
//your code herejump-statement}
expression : An integral or string type expression.
jump-statement : A jump statement that transfers control out ofthe case body.
If any of the expression passed to switch case does not match with casestatement the control will go to default: statement. If there is nodefault: statement control will go outside of the switch statement.
C# foreach loop
The foreach loop in C# executes a block of code on each element inan array or a collection of items. When executing foreach loop ittraversing items in a collection or an array. The foreach loop is usefulfor traversing each items in an array or a collection of items anddisplayed one by one.Syntax:foreach (variable type in collection){// code block}
variable type : The variable used for collect the item fromCollection
collection : Collection of itemsExample:string[] days = { "Sunday", "Monday", "TuesDay"};foreach (string day in days){Console.WriteLine ("The day is : " + day);}The above C# example first declared a string array 'days' and initializethe days in a week to that array. In the foreach loop declare a string'day' and pull out the values from the array one by one and displayed it.
Object Oriented programming in C#
Classes1. Implementation of code and data2. Represents semantic unit3. Implement interfaces
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
34/158
Page | 34
10377MC403 - .Net Technologies
4. Inherit from single base class5. Classes contain:6. Fields: member variables7. Properties: values accessed through get/set method pairs8. Methods: functionality for object or class
9. Specials: events, indexers, delegates
public class Person :IPersonAge{private int YOB;public Person(){}public int YearOfBirth{get { return YOB; };
set { YOB = value; };}public int GetAgeToday(){return Today()-YearOfBirth};
Constructors
Constructors are class methods that are executed when an object
of a given type is created. Constructors have the same name as the class, and usually
initialize the data members of the new object.
Eg.
public class Taxi{public bool isInitialized;public Taxi(){isInitialized = true;}}class TestTaxi{static void Main(){
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
35/158
7/31/2019 DOTNET Technologies Monograph
36/158
Page | 36
10377MC403 - .Net Technologies
// instance constructor is invoked or member is accessed.static SimpleClass(){baseline = DateTime.Now.Ticks;}
} Static constructors have the following properties:
A static constructor does not take access modifiers or haveparameters.
A static constructor is called automatically to initialize the classbefore the first instance is created or any static members arereferenced.
A static constructor cannot be called directly.
The user has no control on when the static constructor isexecuted in the program.
A typical use of static constructors is when the class is using a logfile and the constructor is used to write entries to this file.
Static constructors are also useful when creating wrapper classesfor unmanaged code, when the constructor can call theLoadLibrary method.
If a static constructor throws an exception, the runtime will notinvoke it a second time, and the type will remain uninitialized forthe lifetime of the application domain in which your program isrunning.
Destructors
Destructors are used to destruct instances of classes.
Destructors cannot be defined in structs. They are only used withclasses.
A class can only have one destructor.
Destructors cannot be inherited or overloaded.
Destructors cannot be called. They are invoked automatically.
A destructor does not take modifiers or have parameters.
For example, the following is a declaration of a destructor for the classCar:class Car{~Car() // destructor{// cleanup statements...}}
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
37/158
Page | 37
10377MC403 - .Net Technologies
The destructor implicitly calls Finalize on the base class of the object.Therefore, the previous destructor code is implicitly translated to thefollowing code:protected override void Finalize(){
try{// Cleanup statements...}finally{base.Finalize();}}This means that the Finalize method is called recursively for allinstances in the inheritance chain, from the most-derived to the least-
derived.
Operator overloadingIt is the process of assigning new meaning to the existing operators.
The overloadable unary operators are:
+ - ! ~ ++ -- true false
The overloadable binary operators are:
+ - * / % & | ^ > == != > < >=
7/31/2019 DOTNET Technologies Monograph
38/158
Page | 38
10377MC403 - .Net Technologies
y = b;z = c;}public void display(){
Console.WriteLine("x={0}", x);Console.WriteLine("y={0}", y);Console.WriteLine("z={0}", z);}public unary(){ }public static unary operator -(unary u){unary obj = new unary();obj.x = -u.x;obj.y = -u.y;
obj.z = -u.z;return obj;}}}
Exception HandlingPractically any program including c# .net can have some amount of
errors. They can be broadly classified as compile-time errors andruntime errors. Compile-time errors are errors that can be found during
compilation process of source code. Most of them are syntax errors.Runtime errors happen when program is running. It is very difficult tofind and debug the run-time errors. These errors also calledexceptions.
Exceptions are the occurrence of some conditions that changes thenormal flow of execution . Exceptions are occurred in situations likeour program run out of the memory, file does not exist in the givenpath, network connections are dropped etc. More specifically for betterunderstanding, we can say it as Runtime Errors occurs during theexecution of a program that disrupts the normal flow of instructions
In .NET languages , Structured Exceptions handling is a fundamentalpart of Common Language Runtime . All exceptions in the CommonLanguage Runtime are derived from a single base class , also we cancreate our own custom exception classes.We can create an exception class that inherits from Exception class .Creating an exception object and handing it to the runtime system iscalled throwing an exception.
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
39/158
Page | 39
10377MC403 - .Net Technologies
C# Exception handling uses the try, catch, and finally keywords toattempt actions that may not succeed, to handle failures, and to cleanup resources afterwards.try{
//your code here}Catch (exception type){//your code here}finallyThe code in the finally block will execute even if there is no Exceptions.That means if we write a finally block, the code should execute after theexecution of try block or catch block.try
{'your code block}catch (Exception){'exception handling block}finally{'final cleanup block}
From the following CSharp code , we can understand how to usetry..catch statements.Here we are going to divide a number by zero..
Arrays Arrays are using for store similar data types grouping as a single
unit.
We can access Array elements by its numeric index.
The array indexes start at zero.
The default value of numeric array elements are set to zero, and
referenceelements are set to null.string[] week = new string[7];week[0] = "Sunday";week[1] = "Monday";
The above C# code declare a string array of 7 strings and assign somevalues to it.
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
40/158
Page | 40
10377MC403 - .Net Technologies
string[] week = new string[] {"Sunday","Monday","Tuesday"};The above code declare and initialize a string array with values.string str = week[1];
We can access the Arrays elements by providing its numerical
index, the above statement we access the second value from theweek Array.
In the following program, we declare an Array "week" capable ofseven String values and assigns the seven values as days in aweek.
Next step is to retrieve the elements of the Array using a for loop.
For finding the end of an Array we used the Length function ofArray Object.
Public void main(string[], args){string[] week = new string[7];week[0] = "Sunday";week[1] = "Monday";week[2] = "Tuesday";week[3] = "Wednsday";week[4] = "Thursday";week[5] = "friday";week[6] = "Saturday";for (int i = 0; i < = week.Length-1; i++){Console.WriteLine(week[i]);}}for each loop in C# ArrayRetrieve a single item from Array.string str = week[1];It is very convenient to retrieve the Array elements using foreach loop .The following C# program shows how to retrieve the elements in anArray using foreach loop.
Public void main(string[], args){string[] week = new string[7];week[0] = "Sunday";week[1] = "Monday";week[2] = "Tuesday";week[3] = "Wednsday";week[4] = "Thursday";week[5] = "friday";week[6] = "Saturday";
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
41/158
Page | 41
10377MC403 - .Net Technologies
foreach (string day in week){Console.WriteLine(i);}}
Properties Properties are named members of classes, structs, and interfaces.
They provide a flexible mechanism to read, write, or compute thevalues of private fields through accessors.
Property Declaration
Properties are an extension of fields and are accessed using thesame syntax.
Unlike fields, properties do not designate storage locations.
Instead, properties have accessors that read, write, or computetheir values.
Syntax:[modifiers] type identifier {accessor-declaration}where:
modifiers (Optional)The allowed modifiers are new, static, virtual, abstract, override, and
a valid combination of the four access modifiers.
type
The property type, which must be at least as accessible as theproperty itself. For more information on accessibility levels, see AccessModifiers.
identifierThe property name. For more information on interface member
implementation,see interface.
accessor-declarationDeclaration of the property accessors, which are used to read and
write the property. A property declared using the static modifier is
classified as a static property; otherwise, it is classified as aninstance property. Like other static members, a static property is notassociated with a specific instance and cannot be referenced throughan instance. Instead, it is associated with the type and can only bereferenced through the type name.
Example
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
42/158
Page | 42
10377MC403 - .Net Technologies
This example demonstrates instance, static, and read-onlyproperties. It accepts the name of the employee from the keyboard,increments numberOfEmployees by 1, and displays the Employee nameand number.
// Propertiesusing System;public class Employee{public static int numberOfEmployees;private static int counter;private string name;// A read-write instance property:public string Name{get
{return name;}set{name = value;}}// A read-only static property:public static int Counter{
get{return counter;}}// Constructor:public Employee(){
// Calculate the employee's number:
counter = ++counter + numberOfEmployees;}}public class MainClass{public static void Main(){Employee.numberOfEmployees = 100;
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
43/158
Page | 43
10377MC403 - .Net Technologies
Employee e1 = new Employee();e1.Name = "Claude Vige";Console.WriteLine("Employee number: {0}", Employee.Counter);Console.WriteLine("Employee name: {0}", e1.Name);}
}OutputEmployee number: 101Employee name: Claude Vige
Accessors
The accessor of a property contains the executable statementsassociated with getting (reading or computing) or setting (writing)the property.
The accessor declarations can contain a get accessor, a setaccessor, or both. The declarations take the following forms:
set {accessor-body}get {accessor-body}where:accessor-bodyThe block that contains the statements to be executed when theaccessor is invoked.
The get AccessorThe body of the get accessor is similar to that of a method. It must
return a value of the property type. The execution of the get accessoris equivalent to reading the value of the field.
The following is a get accessor that returns the value of a private fieldname:
private string name; // the name fieldpublic string Name // the Name property{get{return name;}}When you reference the property, except as the target of anassignment, the get accessor is invoked to read the value of theproperty. For example:
Employee e1 = new Employee();Console.Write(e1.Name); // The get accessor is invoked here
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
44/158
Page | 44
10377MC403 - .Net Technologies
The get accessor must terminate in a return or throw statement, andcontrol cannot flow off the accessor body.
The set AccessorThe set accessor is similar to a method that returns void. It uses an
implicit parameter called value, whose type is the type of the property.In the following example, a set accessor is added to the Nameproperty:
public string Name{get{return name;}set
{name = value;}}A property is classified according to the accessors used as follows:
A property with a get accessor only is called a read-onlyproperty. You cannot assign a value to a read-only property.
A property with a set accessor only is called a write-onlyproperty. You cannot reference a write-only property except as atarget of an assignment.
A property with both get and set accessors is a read-writeproperty.
In a property declaration, both the get and set accessors must bedeclared inside the body of the property.
Indexers Indexers permit instances of a class or struct to be indexed in the
same way as arrays.
Indexers are similar to properties except that their accessors takeparameters.
Indexer DeclarationIndexers allow us to index a class or a struct instance in the same wayas an array.
syntax[modifiers] indexer-declarator {accessor-declarations}where:
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
45/158
Page | 45
10377MC403 - .Net Technologies
modifiers (Optional)
Allowed modifiers are new, virtual, sealed, override, abstract,extern, and avalid combination of the four access modifiers. For details, see Access
Modifiers.indexer-declarator
Includes the type of the element introduced by the indexer, this, andthe formalindex- parameter-list. If the indexer is an explicit interfacemember implementation, the interface-type is included.
At least one parameter must be specified. The parameter modifiers outand refare not allowed.
accessor-declarationsThe indexer accessors, which specify the executable statements
associated with reading and writing indexer elements.
get AccessorThe get accessor body of an indexer is similar to a method body. It
returns the type of the indexer. The get accessor uses the sameformal-index-parameter-listas the indexer.
For example:get
{return myArray[index];}set AccessorThe set accessor body of an indexer is similar to a method body. It usesthe same formalindex-parameter-listas the indexer, in addition to thevalue implicit parameter. For
example:set{
myArray[index] = value;}Rules
The type of an indexer and each of the types referenced in theformal-indexparameter-listmust be at least as accessible as theindexer itself.
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
46/158
Page | 46
10377MC403 - .Net Technologies
The signature of an indexer consists of the number and types ofits formal parameters. It does not include the indexer type or thenames of the formal parameters.
if you declare more than one indexer in the same class, theymust have different signatures.
An indexer value is not classified as a variable; therefore, it is notpossible to pass an indexer value as a refor out parameter.
To provide the indexer with a name that other languages can usefor the default indexed property, use a name attribute in thedeclaration. For example:
[System.Runtime.CompilerServices.CSharp.IndexerName("MyItem")]public int this [int index] // Indexer declaration{}This indexer will have the name MyItem. Without providing the nameattribute, thedefault name will be Item.
Comparison Between Properties and IndexersIndexers are similar to properties. Except for the differences shown
in the following table, all of the rules defined for property accessorsapply to indexer accessors as well.Property IndexersIdentified by its name. Identified by its signature.Accessed through a simple nameor amember access.
Accessed through an elementaccess.
Can be a static or an instancemember.
Must be an instance member.
A get accessor of a property hasnoparameters.
A get accessor of an indexer hasthe same formal parameter list asthe indexer.
A set accessor of a propertycontainsthe implicit value parameter.
A set accessor of an indexer hasthe same formal parameter list asthe indexer, in addition to thevalue parameter.
Delegate A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a
reference to a method inside a delegate object.
The delegate object can then be passed to code which can callthe referenced method, without having to know at compile timewhich method will be invoked delegates are object-oriented, type-safe, and secure.
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
47/158
Page | 47
10377MC403 - .Net Technologies
A delegate declaration defines a type that encapsulates a methodwith a particular set of arguments and return type.
The method may be static or instance method.
For static methods, a delegate object encapsulates the method tobe called.
For instance methods, a delegate object encapsulates both aninstance and a method on the instance.
An interesting and useful property of a delegate is that it does notknow or care about the class of the object that it references
A delegate declaration defines a class that is derived from theclass System.Delegate.
Advantages
Encapsulating the method's call from caller
Effective use of delegate improves the performance of application
Used to call a method asynchronously There are three steps in defining and using delegates:
Declaration
Instantiation
Invocationdelegate-declaration:[delegate-modifier] delegate return-type identifier( formal-parameter-listopt) ;delegate-modifier:
public
protected
internal
private.
The public, protected, internal, and private modifiers control theaccessibility of the delegate type. The delegate's type name isidentifier.The optional formal-parameter-listspecifies the parameters of thedelegate, and returntype indicates the return type of the delegate. Amethod and a delegate type are compatible if both of the following aretrue:
They have the same number or parameters, with the same types,in the same order, with the same parameter modifiers.
Their return types are the same.
Delegate instantiationAn instance of a delegate is created by a delegate-creation-
expression.The newly created delegate instance then refers to either:
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
48/158
Page | 48
10377MC403 - .Net Technologies
The static method referenced in the delegate-creation-expression, or The target object (which cannot be null) andinstance method referenced in the delegate-creation-expression,or Another delegate using System;
Delegate invocation C# provides special syntax for invoking a delegate. When a non-
null delegate instance whose invocation list contains one entry isinvoked, it invokes the one method with the same arguments itwas given, and returns the same value as the referred to method
Eg.namespace BasicDelegate{// Declarationpublic delegate void SimpleDelegate();class TestDelegate
{public static void MyFunc(){Console.WriteLine("I was called by delegate ...");}public static void Main(){// InstantiationSimpleDelegate simpleDelegate = newSimpleDelegate(MyFunc);// Invocation
simpleDelegate();}}}OutputI was called by delegate ...
Multicast DelegateIt is a delegate which holds the reference of more than one method.Multicast delegates must contain only methods that return void, elsethere is a runtime exception.Eg.delegate void Delegate_Multicast(int x, int y);Class Class2{static void Method1(int x, int y){Console.WriteLine("You r in Method 1");
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
49/158
Page | 49
10377MC403 - .Net Technologies
}static void Method2(int x, int y){Console.WriteLine("You r in Method 2");}
public static void "on" />Main(){Delegate_Multicast func = new Delegate_Multicast(Method1);func += new Delegate_Multicast(Method2);func(1,2);// Method1 and Method2 are calledfunc -= new Delegate_Multicast(Method1);func(2,3);// Only Method2 is called}}
Explanation
In the above example, you can see that two methods are definednamed method1 and method2 which take two integer parameters andreturn type as void.In the main method, the Delegate object is created using the followingstatement:Delegate_Multicast func = new Delegate_Multicast(Method1);
Then the Delegate is added using the += operator and removed usingthe -= operator.
Events An eventin C# is a way for a class to provide notifications to clients of
that class when some interesting thing happens to an object
The basic foundation behind this programming model is the ideaof "publisher and subscribers."
In this model, we havepublishers who will do some logic andpublish an "event."
Publishers will then send out their event only to subscribers who havesubscribed to receive the specific event.
In C#, any object can publish a set of events to which otherapplications can subscribe. When the publishing class raises anevent, all the subscribed applications are notified. The followingfigure shows this mechanism.
Events are declared using delegates. If you have not yet studiedthe Delegates Tutorial, you should do so before continuing. Recallthat a delegate object encapsulates a method so that it can be
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
50/158
Page | 50
10377MC403 - .Net Technologies
called anonymously. An event is a way for a class to allow clientsto give it delegates to methods that should be called when theevent occurs. When the event occurs, the delegate(s) given to itby its clients are invoked The following steps must be taken inorder to create and use,
C# events:1. Create or identify a delegate. If you are defining your own event, youmust also ensure that there is a delegate to use with the eventkeyword. If the event ispredefined, in the .NET Framework for example, then consumers of theevent
need only know the name of the delegate.2. Create a class that contains:a. An event created from the delegate.b. (optional) A method that verifies that an instance of the delegatedeclared with the event keyword exists. Otherwise, this logic must beplaced in the code that fires the event.c. Methods that call the event. These methods can be overrides of somebase
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
51/158
7/31/2019 DOTNET Technologies Monograph
52/158
Page | 52
10377MC403 - .Net Technologies
{static private void f(){Console.WriteLine("This is called when the event fires.");}
static public void Main (){I i = new MyClass();i.MyEvent += new MyDelegate(f);i.FireAway();}}
CompositionCompose objects into tree structures to represent part-whole
hierarchies. Composite lets clients treat individual objects andcompositions of objectsuniformly.
UML class diagram
participantsThe classes and/or objects participating in this pattern are:
1. Component (DrawingElement)
declares the interface for objects in the composition.
implements default behavior for the interface common to allclasses, as
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
53/158
Page | 53
10377MC403 - .Net Technologies
appropriate.
declares an interface for accessing and managing its childcomponents.
(optional) defines an interface for accessing a component'sparent in the recursive structure, and implements it if that's
appropriate.2. Leaf (PrimitiveElement)
represents leaf objects in the composition. A leaf has no children.
defines behavior for primitive objects in the composition.3. Composite (CompositeElement)
defines behavior for components having children.
stores child components.
implements child-related operations in the Component interface.4. Client (CompositeApp)
manipulates objects in the composition through the Component
interface.
As we know, inheritance gives us an 'is-a' relationship. To make theunderstanding of composition easier, we can say that composition givesus a 'part-of' relationship.Composition is shown on a UML diagram as a filled diamond (see Figure1).
If we were going to model a car, it would make sense to say that anengine is part-of a car. Within composition, the lifetime of the part(Engine) is managed by the whole (Car), in other words, when Car isdestroyed, Engine is destroyed along with it. So howdo we express this in C#?public class Engine{. . .}
public class Car{Engine e = new Engine();.......}
As we can see in the example code above, Car manages the lifetime ofEngine.
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
54/158
Page | 54
10377MC403 - .Net Technologies
UNIT-3
GenericsGenerics introduce to the .NET Framework the concept of typeparameters, which make it possible to design classes and methods thatdefer the specification of one or more types until the class ormethod is declared and instantiated by client code.
Use generic types to maximize code reuse, type safety, andperformance.
The most common use of generics is to create collection classes.
The .NET Framework class library contains several new genericcollection classes in the System.Collections.Generic namespace.These should be used whenever possible in place of classes suchas ArrayList in the System.Collections namespace.
We can create your own generic interfaces, classes, methods,events and delegates.
Generic classes may be constrained to enable access to methodson particular datatypes.
Benefits of generics
Improves performance
Type safety and quality
Reduce repetitive programming tasks
Simplify the overall programming model,
Gives elegant, readable syntax
// Declare the generic classpublic class GenericList{void Add(T input) { }}class TestGenericList{private class ExampleClass { }static void Main()
{// Declare a list of type intGenericList list1 = new GenericList();// Declare a list of type stringGenericList list2 = new GenericList();// Declare a list of type ExampleClassGenericList list3 = new GenericList();}
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
55/158
Page | 55
10377MC403 - .Net Technologies
} Generic classes and methods combine reusability, type safety
and efficiency in a way that their non-generic counterpartscannot.
Generics are most commonly used with collections and the
methods that operate on them. .
NETFrameworkclasslibraryprovidesanewnamespace,System.Collections.Generic, which contains several new generic-basedcollection classes.
Generic MethodsIn C#, a method can define generic type parameters, specific to itsexecution scope:public class MyClass{
public void MyMethod(X x){...}}
This is an important capability because it allows us to call themethod with a different type every time, which is very handy forutility classes.
We can define method-specific generic type parameters even ifthe containing class does not use generics at all:
public class MyClass{public void MyMethod(T t)
{...}}This ability is for methods only. Properties or indexers can only usegeneric typeparameters defined at the scope of the class.When calling a method that defines generic type parameters, we canprovide the type to use at the call site:
MyClass obj = new MyClass();obj.MyMethod(3);
That said, when the method is invoked the C# compiler is smart enoughto infer the correct type based on the type of parameter passed in, andit allows omitting the type specification altogether:MyClass obj = new MyClass();obj.MyMethod(3);This ability is called generic type inference.public class MyClass{public T MyMethod()
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
56/158
7/31/2019 DOTNET Technologies Monograph
57/158
Page | 57
10377MC403 - .Net Technologies
}}And then, you can extend the class to other type of numbers like int ordouble, asshown in the following example:
public class DecimalNumber : Number {public DecimalNumber() {}}The advantage is that it will give you the exact object type, thuseliminating the type casting.Generic Class with Multiple Generic Types
We can even create a class with multiple generic types. This willbenefit us when we want to create a collection ofgeneric types in asingle base class.
Generic Interfaces It is often useful to define interfaces either for generic
collection classes, or for the generic classes that representitems in the collection.
With generic classes it is preferable to use generic interfaces,such as IComparable rather than IComparable, in orderto avoid boxing and unboxing operations on value types.
When an interface is specified as a constraint on a type parameter, onlytypes that implement the interface can be used. The following codeexample shows aSortedList class that derives from the GenericList class.
Generic interfaces can inherit from non-generic interfaces if the genericinterface is contra-variant, which means it only uses its type parameteras a return value. In the .NET Framework class library, IEnumerableinherits from IEnumerable because IEnumerable only uses T in thereturn value of GetEnumerator and in the Current property getter.
Concrete classes can implement closed constructed interfaces, asfollows:interface IBaseInterface { }class SampleClass : IBaseInterface { }
Generic classes can implement generic interfaces or closed constructedinterfaces as long as the class parameter list supplies all argumentsrequired by the interface, as follows:
interface IBaseInterface1 { }
interface IBaseInterface2 { }
class SampleClass1 : IBaseInterface1 { } //No error
class SampleClass2 : IBaseInterface2 { } //Noerror
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
58/158
Page | 58
10377MC403 - .Net Technologies
Generic DelegatesA delegate can define its own type parameters. Code that references
the generic delegate can specify the type argument to create a closedconstructed type, just like when instantiating a generic class or calling ageneric method, as shown in the following example:
public delegate void Del(T item);public static void Notify(int i) { }Del m1 = new Del(Notify);
Delegates defined within a generic class can use the generic class typeparameters in the same way that class methods do.class Stack{T[] items;int index;public delegate void StackDelegate(T[] items);}
C# CollectionCSharp Collections are data structures that holds data in different
ways for flexible operations . C# Collection classes are defined as partof the System.Collections or System.Collections.Generic namespace.Most collection classes implement the same interfaces, and theseinterfaces may be inherited to create new collection classes that fitmore specialized data storage needs. The following tutorial shows howto implement collection classes in C# programming.
HashTable ClassHashtable in C# represents a collection of key/value pairs which
maps keys to value. Any non-null object can be used as a key but avalue can. We can retrieve items from hashTable to provide the key .Both keys and values are Objects.The commonly used functions inHashtable are :
Add : To add a pair of value in HashTable ContainsKey : Check if a specified key exist or not
ContainsValue : Check the specified Value exist in HashTable
Remove : Remove the specified Key and corresponding Value
Add :
To add a pair of value in HashTableSyntax : HashTable.Add(Key,Value)
Key :The Key value
Value :The value of corresponding keyHashtable ht;ht.Add("1", "Sunday");
KLNCIT Department of ComputerApplications (MCA)
7/31/2019 DOTNET Technologies Monograph
59/158
Page | 59
10377MC403 - .Net Technologies
ContainsKey :Check if a specified key exist or notSynatx : bool HashTable.ContainsKey(key)
Key :The Key value for search in HahTable
Returns :
return true if item exist else falseht.Contains("1");
ContainsValue :Check the specified Value exist in HashTableSynatx : bool HashTable.ContainsValue(Value)
Value :Search the specified Value in HashTableReturns : return true if item exist else false
Ht.ContainsValue("Sunday")
Remove :
Remove the specified Key and corresponding ValueSyntax : HashTable.Remove(Key)Key : The key of