Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 139

MCA-501: ADVANCED TECHNOLOGY

Unit-I
Basic of the .net framework: Microsoft .net platform, Design goals and
overview,.net architecture, managed code, assemblies, CLR, execution of
assemblies code, IL, JIT, .NET framework class library, common type
system, common language specification, interoperability with unmanaged
code.

.Net Framework basics:


.NET Framework Design Goals

Inherent within the Microsoft .NET Framework are many design goals that are practical
yet extremely ambitious. In this section, we discuss the main design goals of the
Microsoft .NET Framework, including better support for components, language
integration, application interoperation across cyberspace, simple development and
deployment, better reliability, and greater security.

Component Infrastructure

Prior to the existence of COM technology, Microsoft developers had no simple way to
integrate binary libraries without referring to or altering their source code. With the
advent of COM, programmers were able to integrate binary components into their
applications, similar to the way we plug-and-play hardware components into our desktop
PCs. Although COM was great, the grungy details of COM gave developers and
administrators many headaches.

While COM permits you to integrate binary components developed using any language, it
does require you to obey the COM identity, lifetime, and binary layout rules. You must
also write the plumbing code that is required to create a COM component, such as
DllGetClassObject, CoRegisterClassObject, and others.

Realizing that all of these requirements result in frequent rewrites of similar code, .NET
sets out to remove all of them. In the .NET world, all classes are ready to be reused at
the binary level. You don’t have to write extra plumbing code to support
componentization in the .NET Framework. You simply write a .NET class, which then
becomes a part of an assembly (to be discussed in Chapter 2), and it will support plug-
and-play.[1]

In addition to providing such a framework to make development easier, .NET also


removes the pain of developing COM components. Specifically, .NET removes the use of
the registry for component registration and eliminates the requirements for extraneous
plumbing code found in all COM components, including code to support IUnknown, class
factories, component lifetime, registration, dynamic binding, and others.

Tip

“Component” is a nasty word because one person may use it to refer to an object and
another may use it to refer to a binary module. To be consistent, this book uses the term
“COM component” (or simply “component”) to refer to a binary module, such as a DLL or
an EXE.

Language Integration
COM supports language independence, which means that you can develop a COM
component in any language you want. As long as your component meets all the rules
spelled out in the COM specification, it can be instantiated and used by your applications.
While this supports binary reuse, it doesn’t support language integration . In other
words, you can’t reuse the code in the COM components written by someone else; you
can’t extend a class hosted in the COM component; you can’t catch exceptions thrown by
code in the COM component; and so forth.
Microsoft .NET supports not only language independence, but also language integration.
This means that you can inherit from classes, catch exceptions, and take advantage of
polymorphism across different languages. The .NET Framework makes this possible with
a specification called the Common Type System (CTS), which all .NET components must
support. For example, everything in .NET is an object of a specific class that derives from
the root class called System.Object. The CTS supports the general concepts of classes,
interfaces, delegates (which support callbacks), reference types, and value types. The
.NET base classes provide most of the base system types, such as ones that support
integer, string, and file manipulation. Because every language compiler must meet a
minimum set of rules stipulated by the Common Language Specification (CLS) and
generate code to conform to the CTS, different .NET languages can intermingle with one
another. We will examine the CTS and CLS in Chapter 2.
Internet Interoperation

COM supports distributed computing through its Distributed COM (DCOM) wire protocol.
A problem with DCOM is that it embeds the host TCP/IP address inside the Network Data
Representation (NDR) buffer, such that it will not work through firewalls and Network
Address Translation (NAT) software. In addition, the DCOM dynamic activation, protocol
negotiation, and garbage-collection facilities are proprietary, complex, and expensive.
The solution is an open, simple, and lightweight protocol for distributed computing.
The .NET Framework uses the new industry-supported SOAP protocol, which is based on
the widely accepted XML and HTTP standards.

Simple Development

If you have developed software for the Windows platforms since their appearance, you
have seen everything from the Windows APIs to the Microsoft Foundation Classes (MFC),
the Active Template Library (ATL), the system COM interfaces, and the countless other
environments, such as Visual Interdev, Visual Basic, JScript, and other scripting
languages. Each time you set out to develop something in a different compiler, you had
to learn a new API or a class library, because there is no consistency or commonality
among these different libraries or interfaces.

The .NET solution provides a set of framework classes and lets every language use it.
Such a framework removes the need for learning a new API each time you switch
languages. Put differently, it’s certainly easier to go through ten methods of a particular
class than to go through a thousand API functions.

Simple Deployment
Imagine this scenario: your Windows application, which uses three shared DLLs, works
just fine for months, but stops working one day after you’ve installed another software
package that overwrites the first DLL, does nothing to the second DLL, and adds an
additional copy of the third DLL into a different directory. If you have ever encountered
such a brutal—yet entirely possible—problem, you have entered DLL Hell. And if you ask
a group of seasoned developers whether they have experienced DLL Hell, they will
grimace at you in disgust, not because of the question you’ve posed, but because they
have indeed experienced the pain and suffering.

To avoid DLL Hell on Windows 2000 (at least for system DLLs), Windows 2000 stores
system DLLs in a cache. If you install an application that overwrites system DLLs,
Windows 2000 will overwrite the added system DLLs with the original versions from the
cache.

Microsoft .NET further diminishes DLL Hell. In the .NET environment, your executable will
use the shared DLL with which it was built. This is guaranteed, because a shared DLL
must be registered against something similar to the Windows 2000 cache, called
the Global Assembly Cache (GAC). In addition to this requirement, a shared DLL must
have a unique hash value, public key, locale, and version number. Once you’ve met
these requirements and registered your shared DLL in the GAC, its physical filename is
no longer important. In other words, if you have two versions of a DLL that are both
called MyDll.dll , both of them can live and execute on the same system without causing
DLL Hell. Again, this is possible because the executable that uses one of these DLLs is
tightly bound to the DLL during compilation.
In addition to eradicating DLL Hell, .NET also removes the need for component-related
registry settings. A COM developer will tell you that half the challenge of learning COM is
understanding the COM-specific registry entries for which the developer is responsible.
Microsoft .NET stores all references and dependencies of .NET assemblies within a
special section called a manifest (see Chapter 2). In addition, assemblies can be either
private or shared. Private assemblies are found using logical paths or XML-based
application configuration files, and public assemblies are registered in the GAC; in both
cases the system will find your dependencies at runtime. If they are missing, you get an
exception telling you exactly what happened.

Finally, .NET brings back the concept of zero-impact installation and removal. This
concept is the opposite of what you have to deal with in the world of COM. To set up a
COM application, you have to register all your components after you have copied them
over to your machine. If you fail to perform this step correctly, nothing will work and
you’ll pull your hair out. Likewise, to uninstall the application, you should unregister your
components (to remove the registry entries) prior to deleting your files. Again, if you fail
to perform this step correctly, you will leave remnants in the registry that will be forever
extant.

Unlike COM, but like DOS, to set up an application in .NET, you simply xcopy your files
from one directory on a CD to another directory on your machine, and the application
will run automatically.[2] Similarly, you can just delete the directory to uninstall the
application from your machine.
Reliability

There are many programming languages and platforms in the commercial software


industry, but few of them attempt to provide both a reliable language and a robust
runtime or infrastructure. The most successful language that we have seen in the
commercial software industry is the Java™ language and the Java Virtual Machine™,
which have brought the software-development community much satisfaction. Microsoft is
positioning .NET as the next big thing.

Microsoft .NET requires type safety. Unlike C++, every class in .NET is derived from the
mother of all classes, Object, which supports runtime type-identification features,
content-dumping features, and so on. The CLR must recognize and verify types before
they can be loaded and executed. This decreases the chances for rudimentary
programming errors and prevents buffer overruns, which can be a security weakness.

Traditional programming languages don’t provide a common error- handling mechanism.


C++ and Java support exception handling, but many others leave you in the dust,
forcing to invent your own error-handling facilities. Microsoft .NET supports exceptions in
the CLR, providing a consistent error-handling mechanism. Put another way: exceptions
work across all .NET-compatible languages.

When you program in C++, you must deallocate all heap-based objects that you have
previously allocated. If you fail to do this, the allocated resources on your system will
never be reclaimed even though they are no longer needed. And if this is a server
application, it won’t be robust because the accumulation of unused resources in memory
will eventually bring down the system. Similar to Java, the .NET runtime tracks
and garbage-collects all allocated objects that are no longer needed.
Security

When developing applications in the old days of DOS, Microsoft developers cared little
about security because their applications ran on a single desktop with a single thread of
execution. As soon as developers started developing client and server applications,
things got a bit complicated: multiple users might then have accessed the servers, and
sensitive data might be exchanged between the client and the server. The problem
became even more complex in the web environment, since you could unknowingly
download and execute malicious applets on your machine.

To mitigate these problems, .NET provides a number of security features. Windows NT


and Windows 2000 protect resources using access-control lists and security identities,
but don’t provide a security infrastructure to verify access to parts of an executable’s
code. Unlike traditional security support whereby only access to the executable is
protected, .NET goes further to protect access to specific parts of the executable code.
For example, to take advantage of declarative security checks, you can prefix your
method implementations with security attributes without having to write any code. To
take advantage of imperative security checks, you write the code in your method to
explicitly cause a security check. There are many other security facilities that .NET
provides in an attempt to make it harder to penetrate your applications and system.

Overview of .NET Framework

.NET Framework is a technology that supports building and running Windows apps and
web services. .NET Framework is designed to fulfill the following objectives:

 Provide a consistent, object-oriented programming environment whether object


code is stored and executed locally, executed locally but web-distributed, or
executed remotely.

 Provide a code-execution environment that:

o Minimizes software deployment and versioning conflicts.

o Promotes safe execution of code, including code created by an unknown or


semi-trusted third party.

o Eliminates the performance problems of scripted or interpreted


environments.

 Make the developer experience consistent across widely varying types of apps,
such as Windows-based apps and Web-based apps.
 Build all communication on industry standards to ensure that code based on .NET
Framework integrates with any other code.

 Note

.NET Framework 4.8 is the last version of .NET Framework, and no further versions will
be released. However, .NET Framework will continue to be serviced with monthly
security and reliability bug fixes. Additionally, it will continue to be included with
Windows, with no plans to remove it. You don't need to migrate your .NET Framework
apps, but for new development, use .NET 5.0 or later.

.NET Framework consists of the common language runtime (CLR) and the .NET
Framework class library. The common language runtime is the foundation of .NET
Framework. Think of the runtime as an agent that manages code at execution time,
providing core services such as memory management, thread management, and
remoting, while also enforcing strict type safety and other forms of code accuracy that
promote security and robustness. In fact, the concept of code management is a
fundamental principle of the runtime. Code that targets the runtime is known as
managed code, while code that doesn't target the runtime is known as unmanaged code.
The class library is a comprehensive, object-oriented collection of reusable types that
you use to develop apps ranging from traditional command-line or graphical user
interface (GUI) apps to apps based on the latest innovations provided by ASP.NET, such
as Web Forms and XML web services.

.NET Framework can be hosted by unmanaged components that load the common
language runtime into their processes and initiate the execution of managed code,
thereby creating a software environment that exploits both managed and unmanaged
features. .NET Framework not only provides several runtime hosts but also supports the
development of third-party runtime hosts.

For example, ASP.NET hosts the runtime to provide a scalable, server-side environment
for managed code. ASP.NET works directly with the runtime to enable ASP.NET apps and
XML web services, both of which are discussed later in this article.

Internet Explorer is an example of an unmanaged app that hosts the runtime (in the
form of a MIME type extension). Using Internet Explorer to host the runtime enables you
to embed managed components or Windows Forms controls in HTML documents. Hosting
the runtime in this way makes managed mobile code possible, but with significant
improvements that only managed code offers, such as semi-trusted execution and
isolated file storage.

The following illustration shows the relationship of the common language runtime and
the class library to your apps and to the overall system. The illustration also shows how
managed code operates within a larger architecture.
The following sections describe the main features of .NET Framework in greater detail.

Features of the common language runtime

The common language runtime manages memory, thread execution, code execution,
code safety verification, compilation, and other system services. These features are
intrinsic to the managed code that runs on the common language runtime.

Regarding security, managed components are awarded varying degrees of trust,


depending on a number of factors that include their origin (such as the Internet,
enterprise network, or local computer). This means that a managed component might or
might not be able to perform file-access operations, registry-access operations, or other
sensitive functions, even if it's used in the same active app.

The runtime also enforces code robustness by implementing a strict type-and-code-


verification infrastructure called the common type system (CTS). The CTS ensures that
all managed code is self-describing. The various Microsoft and third-party language
compilers generate managed code that conforms to the CTS. This means that managed
code can consume other managed types and instances, while strictly enforcing type
fidelity and type safety.

In addition, the managed environment of the runtime eliminates many common software
issues. For example, the runtime automatically handles object layout and manages
references to objects, releasing them when they are no longer being used. This
automatic memory management resolves the two most common app errors, memory
leaks and invalid memory references.
The runtime also accelerates developer productivity. For example, programmers write
apps in their development language of choice yet take full advantage of the runtime, the
class library, and components written in other languages by other developers. Any
compiler vendor who chooses to target the runtime can do so. Language compilers that
target the .NET Framework make the features of the .NET Framework available to
existing code written in that language, greatly easing the migration process for existing
apps.

While the runtime is designed for the software of the future, it also supports software of
today and yesterday. Interoperability between managed and unmanaged code enables
developers to continue to use necessary COM components and DLLs.

The runtime is designed to enhance performance. Although the common language


runtime provides many standard runtime services, managed code is never interpreted. A
feature called just-in-time (JIT) compiling enables all managed code to run in the native
machine language of the system on which it's executing. Meanwhile, the memory
manager removes the possibilities of fragmented memory and increases memory
locality-of-reference to further increase performance.

Finally, the runtime can be hosted by high-performance, server-side apps, such as


Microsoft SQL Server and Internet Information Services (IIS). This infrastructure enables
you to use managed code to write your business logic, while still enjoying the superior
performance of the industry's best enterprise servers that support runtime hosting.

.NET Framework class library

The .NET Framework class library is a collection of reusable types that tightly integrate
with the common language runtime. The class library is object oriented, providing types
from which your own managed code derives functionality. This not only makes the .NET
Framework types easy to use but also reduces the time associated with learning new
features of the .NET Framework. In addition, third-party components integrate
seamlessly with classes in the .NET Framework.

For example, the .NET Framework collection classes implement a set of interfaces for
developing your own collection classes. Your collection classes blend seamlessly with the
classes in the .NET Framework.

As you would expect from an object-oriented class library, the .NET Framework types
enable you to accomplish a range of common programming tasks, including string
management, data collection, database connectivity, and file access. In addition to these
common tasks, the class library includes types that support a variety of specialized
development scenarios. You can use .NET Framework to develop the following types of
apps and services:

 Console apps. See Building Console Applications.

 Windows GUI apps (Windows Forms). See Windows Forms.

 Windows Presentation Foundation (WPF) apps. See Windows Presentation


Foundation.

 ASP.NET apps. See Web Applications with ASP.NET.

 Windows services. See Introduction to Windows Service Applications.


 Service-oriented apps using Windows Communication Foundation (WCF).
See Service-Oriented Applications with WCF.

 Workflow-enabled apps using Windows Workflow Foundation (WF). See Windows


Workflow Foundation.

The Windows Forms classes are a comprehensive set of reusable types that vastly
simplify Windows GUI development. If you write an ASP.NET Web Form app, you can use
the Web Forms classes.

Common Language Runtime (CLR): The heart of the .Net Framework. It is


also called the .Net runtime. It resides above the operating system and handles
all .Net applications. It handles garbage collection, Code Access Security (CAS)
etc.

Microsoft Intermediate Language (MSIL) Code: When we compile our .Net


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

Just in Time Compilers (JIT): It compiles IL code into native executable code
(exe or dlls). Once code is converted to IL then it can be called again by JIT
instead of recompiling that code.
What is Just-In-Time(JIT) Compiler in .NET
Just-In-Time compiler(JIT) is a part of Common Language Runtime
(CLR) in .NET which is responsible for managing the execution
of .NET programs regardless of any .NET programming language. A
language-specific compiler converts the source code to the intermediate
language. This intermediate language is then converted into the machine
code by the Just-In-Time (JIT) compiler. This machine code is specific to
the computer environment that the JIT compiler runs on.

Working of JIT Compiler: The JIT compiler is required to speed up the


code execution and provide support for multiple platforms. Its working is
given as follows:
The JIT compiler converts the Microsoft Intermediate Language(MSIL) or
Common Intermediate Language(CIL) into the machine code. This is done
before the MSIL or CIL can be executed. The MSIL is converted into
machine code on a requirement basis i.e. the JIT compiler compiles the
MSIL or CIL as required rather than the whole of it. The compiled MSIL or
CIL is stored so that it is available for subsequent calls if required.
Type
s of Just-In-Time Compiler: There are 3 types of JIT compilers which are
as follows:

1. Pre-JIT Compiler: All the source code is compiled into the machine


code at the same time in a single compilation cycle using the Pre-JIT
Compiler. This compilation process is performed at application
deployment time. And this compiler is always implemented in
the Ngen.exe (Native Image Generator).
2. Normal JIT Compiler: The source code methods that are required at
run-time are compiled into machine code the first time they are called
by the Normal JIT Compiler. After that, they are stored in the cache
and used whenever they are called again.
3. Econo JIT Compiler: The source code methods that are required at
run-time are compiled into machine code by the Econo JIT Compiler.
After these methods are not required anymore, they are removed.
Advantages of JIT Compiler:
 The JIT compiler requires less memory usage as only the methods
that are required at run-time are compiled into machine code by the
JIT Compiler.
 Page faults are reduced by using the JIT compiler as the methods
required together are most probably in the same memory page.
 Code optimization based on statistical analysis can be performed by
the JIT compiler while the code is running.
Disadvantages of JIT compiler:
 The JIT compiler requires more startup time while the application is
executed initially.
 The cache memory is heavily used by the JIT compiler to store the
source code methods that are required at run-time.
Note: Much of the disadvantages of the JIT compiler can be handled using
the Ahead-of-time (AOT) compilation. This involves compiling the MSIL into
machine code so that runtime compilation is not required and the machine
code file can be executed natively.
Framework class library: The .Net Framework provides a huge class library
called FCL for common tasks. It contains thousands of classes to access
Windows APIs and common functions like string manipulations, Data structures,
stream, IO, thread, security etc.

.NET Framework Class Library


.NET Framework Class Library is the collection of classes, namespaces, interfaces and
value types that are used for .NET applications.

It contains thousands of classes that supports the following functions.

o Base and user-defined data types

o Support for exceptions handling

o input/output and stream operations

o Communications with the underlying system

o Access to data

o Ability to create Windows-based GUI applications

o Ability to create web-client and server applications

o Support for creating web services

The Framework Class Library or FCL provides the system functionality in


the .NET Framework as it has various classes, data types, interfaces, etc.
to perform multiple functions and build different types of applications such
as desktop applications, web applications, mobile applications, etc. The
Framework Class Library is integrated with the Common Language
Runtime (CLR) of the .NET framework and is used by all the .NET
languages such as C#, F#, Visual Basic .NET, etc.

Categories in the Framework Class Library

The functionality of the Framework Class Library can be broadly divided


into three categories i.e utility features written in .NET, wrappers around the
OS functionality and frameworks. These categories are not rigidly defined
and there are many classes that may fit into more than one category.
Details about the Categories in the Framework Class Library are given as
follows:
 Utility Features: The
utility features in the FCL includes various
collection classes such as list, stack, queue, dictionary, etc. and also
classes for more varied manipulations such as Regex class for regular
expressions.
 Wrappers Around OS functionality: Some of the features in the FCL are
wrappers around the underlying Windows OS functionality. These
include the classes for using the file system, the classes to handle the
network features, the classes to handle I/O for console applications,
etc.
 Frameworks: There are various frameworks available in the FCL to
develop certain applications. For example, ASP.NET is used to
develop web applications, Windows Presentation Foundation (WPF) is
used to render user interfaces in Windows applications and so on.
Namespaces in the Framework Class Library

Namespaces in the Framework Class Library are a group of related classes


and interfaces that can be used by all the .NET framework languages.

Namespaces Description

System It includes all


common datatypes,
string values, arrays
and methods for
data conversion.

System.Data, System.Data.Common, These are used to


System.Data.OleDb, System.Data.SqlClient, access a database,
System.Data.SqlTypes perform commands
on a database and
retrieve database.

System.IO, System.DirectoryServices, These are used to


System.IO.IsolatedStorage access, read and
write files.

System.Diagnostics It is used to debug


and trace the
execution of an
application.

System.Net, System.Net.Sockets These are used to


communicate over
the Internet when
creating peer-to-
peer applications.
System.Windows.Forms, These namespaces
System.Windows.Forms.Design are used to create
Windows-based
applications using
Windows user
interface
components.

System.Web, System.WebCaching, These are used to


System.Web.UI, System.Web.UI.Design, create ASP. NET
System.Web.UI.WebControls, Web applications
System.Web.UI.HtmlControls, that run over the
System.Web.Configuration, web.
System.Web.Hosting, System.Web.Mail,
System.Web.SessionState

System.Web.Services, These are used to


System.Web.Services.Description, create XML Web
System.Web.Services.Configuration, services and
System.Web.Services.Discovery, components that can
System.Web.Services.Protocols be published over
the web.

System.Security, System.Security.Permissions, These are used for


System.Security.Policy, System.WebSecurity, authentication,
System.Security.Cryptography authorization, and
encryption purpose.

System.Xml, System.Xml.Schema, These namespaces


System.Xml.Serialization, System.Xml.XPath, are used to create
System.Xml.Xsl and access XML files.
.NET Framework Base Class Library
o .NET Base Class Library is the sub part of the Framework that provides
library support to Common Language Runtime to work properly. It
includes the System namespace and core types of the .NET framework.

Common Language Runtime (CLR) in C#

CLR is the basic and Virtual Machine component of the .NET Framework. It is the run-
time enviornment in the .NET Framework that runs the codes and helps in making
the development process easier by providing the various services. Basically, it is
responsible for managing the execution of .NET programs regardless of
any .NET programming language. Internally, CLR implements the VES(Virtual Execution
System) which is defined in the Microsoft’s implementation of the CLI(Common
Language Infrastructure).
The code that runs under the Common Language Runtime is termed as the Managed
Code. In other words, you can say that CLR provides a managed execution enviornment
for the .NET programs by improving the security, including the cross language
integration and a rich set of class libraries etc. CLR is present in every .NET framework
verison. Below table illustrate the CLR version in .NET framework.
Below diagram illustrate how CLR is associated with the operating system/hardware
along with the class libraries. Here, the runtime is actually CLR.
Role of CLR in the execution of a C# program

 Suppose you have written a C# program and save it in a file which is known as
the Source Code.
 Language specific compiler compiles the source code into the MSIL(Microsoft
Intermediate Language) which is also know as the CIL(Common
Intermediate Language) or IL(Intermediate Language) along with its
metadata. Metadata includes the all the types, actual implementation of each
function of the program. MSIL is machine independent code.
 Now CLR comes into existence. CLR provides the services and runtime
environment to the MSIL code. Internally CLR includes the JIT(Just-In-Time)
compiler which converts the MSIL code to machine code which further executed by
CPU. CLR also uses the .NET Framework class libraries. Metadata provides
information about the programming language, environment, version, and class
libraries to the CLR by which CLR handles the MSIL code. As CLR is common so it
allows an instance of a class that written in a different language to call a method of
the class which written in another language.
Main Components of CLR

As the word specify, Common means CLR provides a common runtime or execution
environment as there are more than 60 .NET programming languages.

Main components of CLR:

 Common Language Specification (CLS)


 Common Type System (CTS)
 Garbage Collection (GC)
 Just In – Time Compiler (JIT)

Common Language Specification (CLS):


It is responsible for converting the different .NET programming language syntactical
rules and regulations into CLR understandable format. Basically, it provides the
Language Interoperability. Language Interoperability means to provide the execution
support to other programming languages also in .NET framework.

Language Interoperability can be achieved in two ways :


i. Managed Code: The MSIL code which is managed by the CLR is known as the
Managed Code. For managed code CLR provides three .NET facilities:

 CAS(Code Access Security)


 Exception Handling
 Automatic Memory Management.
ii. Unmanaged Code: Before .NET development the programming language like
.COM Components & Win32 API do not generate the MSIL code. So these are not
managed by CLR rather managed by Operating System.

Common Type System (CTS):


Every programming language has its own data type system, so CTS is responsible for
understanding all the data type systems of .NET programming languages and converting
them into CLR understandable format which will be a common format.
There are 2 Types of CTS that every .NET programming language have :
1. Value Types: Value Types will store the value directly into the memory location.
These types work with stack mechanism only. CLR allows memory for these at
Compile Time.
2. Reference Types: Reference Types will contain a memory address of value
because the reference types won’t store the variable value directly in memory.
These types work with Heap mechanism. CLR allots memory for these at Runtime.
Garbage Collector:
It is used to provide the Automatic Memory Management feature. If there was no
garbage collector, programmers would have to write the memory management codes
which will be a kind of overhead on programmers.

JIT(Just In Time Compiler):


It is responsible for converting the CIL(Common Intermediate Language) into machine
code or native code using the Common Language Runtime environment.
Benefits of CLR:
 It improves the performance by providing a rich interact between programs at
run time.
 Enhance portability by removing the need of recompiling a program on any
operating system that supports it.
 Security also increases as it analyzes the MSIL instructions whether they are safe
or unsafe. Also, the use of delegates in place of function pointers enhance the type
safety and security.
 Support automatic memory management with the help of Garbage Collector.
 Provides cross-language integration because CTS inside CLR provides a common
standard that activates the different languages to extend and share each other’s
libraries.
 Provides support to use the components that developed in other .NET
programming languages.
 Provide language, platform, and architecture independence.
 It allows easy creation of scalable and multithreaded applications, as the
developer has no need to think about the memory management and security
issues.

Common Language Specification (CLS): What makes a language to be .Net


compliant? Answer is CLS. Microsoft has defined some specifications that each
.Net language has to follow. For e.g.: no pointer, no multiple inheritances etc.

Common Type System (CTS): CTS defines some basic data types that IL can
understand. Each .Net compliant language should map its data types to these
standard data types. This makes it possible for two .Net compliant languages to
communicate by receiving parameters to and from each other. For example CTS
defines Int32 for C# int and VB integer data types.

The .Net Framework: Is a combination of CLR, FCL, ADO.Net and XML classes,
Web/Window applications and Web services.
.NET Framework Architecture

.NET is tiered, modular, and hierarchal. Each tier of the .NET Framework
is a layer of abstraction. .NET languages are the top tier and the most
abstracted level. The common language runtime is the bottom tier, the
least abstracted, and closest to the native environment. This is important
since the common language runtime works closely with the operating
environment to manage .NET applications. The .NET Framework is
partitioned into modules, each with its own distinct responsibility. Finally,
since higher tiers request services only from the lower tiers, .NET is
hierarchal. The architectural layout of the .NET Framework is illustrated in
given fig.
What Is ManagedCode?
Managed code is code written in one of over twenty high-level
programming languages that are available for use with the Microsoft .NET
Framework, including C#, J#, Microsoft Visual Basic .NET, Microsoft
JScript .NET, and C++. All of these languages share a unified set of class
libraries and can be encoded into an Intermediate Language (IL). A
runtime-aware compiler compiles the IL into native executable code
within a managed execution environment that ensures type safety, array
bound and index checking, exception handling, and garbage collection.
By using managed code and compiling in this managed execution
environment, you can avoid many typical programming mistakes that
lead to security holes and unstable applications. Also, many unproductive
programming tasks are automatically taken care of, such as type safety
checking, memory management, and destruction of unneeded objects.
You can therefore focus on the business logic of your applications and
write them using fewer lines of code. The result is shorter development
time and more secure and stable applications.

The code, which is developed in .NET framework, is known as


managed code. This code is directly executed by CLR with help of
managed code execution. Any language that is written in .NET
Framework is managed code.
 
Managed code uses CLR which in turns looks after your applications by
managing memory, handling security, allowing cross - language
debugging, and so on.

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.
 
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).
 
CLR
The full form of CLR is Common Language Runtime.A runtime is an
environment in which programs are executed.CLR is a nothing but the
runtime environment.CLR is the heart of .NET. It executes MSIL
code.Another key feature of the .NET CLR is garbage collection.It is
responsible for destroying objects which are no longer in use. The CLR's
garbage collector checks the heap for unreferenced objects and frees the
memory used by these objects.

Benefits of CLR
The runtime provides the following features:

 The ability to easily use components developed in other languages.


 Extensible types provided by a class library.
 Language features such as inheritance, interfaces, and overloading for object-
oriented programming.
 Support for threads that allows creation of multithreaded, scalable
applications.
 Support for structured exception handling.
 Support for custom attributes.
 Garbage collection.
 Use of delegates instead of function pointers for increased type safety and
security.

What is a .Net Assembly?

The .NET assembly is the standard for components developed with the Microsoft.NET.
Dot NET assemblies may or may not be executable, i.e., they might exist as the
executable (.exe) file or dynamic link library (DLL) file. All the .NET assemblies contain
the definition of types, versioning information for the type, meta-data, and manifest. The
designers of .NET have worked a lot on the component (assembly) resolution.

There are two kind of assemblies in .NET;

 private 
 shared

Private assemblies are simple and copied with each calling assemblies in the calling
assemblies folder.

Shared assemblies (also called strong named assemblies) are copied to a single


location (usually the Global assembly cache). For all calling assemblies within the same
application, the same copy of the shared assembly is used from its original location.
Hence, shared assemblies are not copied in the private folders of each calling assembly.
Each shared assembly has a four part name including its face name, version, public key
token and culture information. The public key token and version information makes it
almost impossible for two different assemblies with the same name or for two similar
assemblies with different version to mix with each other.

An assembly can be a single file or it may consist of the multiple files. In case of multi-
file, there is one master module containing the manifest while other assemblies exist as
non-manifest modules. A module in .NET is a sub part of a multi-file .NET assembly.
Assembly is one of the most interesting and extremely useful areas of .NET architecture
along with reflections and attributes, but unfortunately very few people take interest in
learning such theoretical looking topics.

What are the basic components of .NET platform?

The basic components of .NET platform (framework) are:  

                  .Net Applications

        (Win Forms,Web Applications,Web Services)


         Data(ADO.Net) and XML Library

          FrameWork Class Library(FCL)      

        (IO,Streams,Sockets,Security,Reflection,UI)

       Common Language Runtime(CLR)

             (Debugger,Type Checker,JITer,GC)

                    Operating System

          (Windows,Linux,UNIX,Macintosh,etc.,)

Common Language Runtime (CLR):

Discussed above

MSIL (Microsoft Intermediate Language) Code:

Discussed above

Just In Time Compilers (JITers):

When our IL compiled code needs to be executed, CLR invokes JIT compilers which
compile the IL code to native executable code (.exe or .dll) for the specific machine and
OS. JITers in many ways are different from traditional compilers as they, as their name
suggests, compile the IL to native code only when desired e.g., when a function is called,
IL of function's body is converted to native code; just in time of need. So, the part of
code that is not used by particular run is not converted to native code. If some IL code is
converted to native code then the next time when its needed to be used, the CLR uses
the same copy without re-compiling. So, if a program runs for sometime, then it won't
have any just in time performance penalty. As JITers are aware of processor and OS
exactly at runtime, they can optimize the code extremely efficiently resulting in very
robust applications. Also, since JITer knows the exact current state of executable code,
they can also optimize the code by in-lining small function calls (like replacing body of
small function when its called in a loop, saving the function call time). Although,
Microsoft stated that C# and .Net are not competing with languages like C++ in
efficiency, speed of execution, JITers can make your code even faster than C++ code in
some cases when program is run over extended period of time (like web-servers).

Framework Class Library (FCL):

Discussed above

Common Language Specification (CLS):

Discussed above

Common Type System (CTS):


.NET also defines a Common Type System (CTS). Like CLS, CTS is also a set of
standards. CTS defines the basic data types that IL understands. Each .NET compliant
language should map its data types to these standard data types. This makes it possible
for the 2 languages to communicate with each other by passing/receiving parameters
to/from each other. For example, CTS defines a type Int32, an integral data type of 32
bits (4 bytes) which is mapped by C# through int and VB.Net through its Integer data
type.

Garbage Collector (GC):

CLR also contains Garbage Collector (GC) which runs in a low-priority thread and checks
for un-referenced dynamically allocated memory space. If it finds some data that is no
more referenced by any variable/reference, it re-claims it and returns the occupied
memory back to the Operating System; so that it can be used by other programs as
necessary. The presence of standard Garbage Collector frees the programmer from
keeping track of dangling data.

Advantages using Managed Code

1. Memory management
2.  Thread management
3.  Exception handling
4.  Garbage collection
5.  Security
6.  Base Library for code reusability.
7.  Able to write code in multiple languages.
8.  Performance improvement.
9. Type safety and security.   
10.  Reusability of Code

Disadvantages:
1.  New and changing technology it takes time for people to learn that technology
2.  Multi-platform support isn't available from MS and isn't available straight after
installing Visual Studio, but with VS 2015 supporting Multi-platform.
3.   Managed code can be slower than native code
4.  NET framework is free to download but Code Editor is costly.
5.  Not suitable for High End Application

Interoperability with Unmanaged Code

The .NET Framework offers a ton of advantages over other development platforms. However,
very few companies can afford to redesign and reimplement all of their existing code.
Microsoft realizes this and has constructed the CLR so that it offers mechanisms that
allow an application to consist of both managed and unmanaged parts. Specifically, the
CLR supports three interoperability scenarios:
Managed code calling unmanaged DLL functions Let's say your application
needs to interface to a C-like DLL and the company that wrote the DLL isn't
adopting .NET as quickly as your company is. In this case, you still need to call
into that DLL from a .NET application.

Managed code using COM components For the same reason that you might
need to continue supporting the ability to call a C-like DLL's functions from
your .NET application, you might also need to continue supporting COM
components. You do this by creating a .NET wrapper for the COM component so
that the managed client thinks it's working with a .NET class.

Unmanaged code using .NET services This is exactly the reverse problem-


you want to access .NET from unmanaged code. It's solved using a reciprocal
approach: a COM client is fooled into thinking it's using a COM server, which is
actually a .NET service of some sort. 

Unit-II

Introduction to VB.Net and C#: .Net features, Data Types, OOPS Concepts:
Constructor, Destructor, and Abstraction, interface, polymorphism (Over loading and
over ridding).

VB.Net: Net features, Data Types

C#: Data Types, Operators, Garbage Collection, Jagged Array, Collection


(Array list, Hash table), Indexer(One Dimension) and property, Delegates
and events (Multicasting, Multicasting Event), Exception Handling.

Explain the features of .NET

Microsoft .NET provides a framework that facilitates designing and developing


applications that are portable, scalable, and robust, and that can be executed in a
distributed environment. It presents a platform and device-independent computing
model in a managed environment.

The Microsoft .NET framework provides a lot of features. Microsoft has designed the
features of the .NET framework by using the technologies that are required by software
developers to develop applications for modern as well as future business needs. The key
features of .NET are:

1. Common Executive Environment:-

All .NET applications run under a common execution environment, called the Common
Language Runtime. The CLR facilitates the interoperability between different .NET
languages such as C#, Visual Basic, Visual C++, etc. by providing a common
environment for the execution of code written in any of these languages.

2. Common Type System:-


The .NET framework follows types of systems to maintain data integrity across the code
written in different .NET compliant programming languages. CTS ensures that objects of
the programs that are written in different programming languages can communicate with
each other to share data.

CTS prevents data loss when a type in one language transfers data to its equivalent type
in one language transfer data to its equivalent type in other languages. For example,
CTS ensures that data is not lost while transferring an integer variable of visual basic
code to an integer variable of C# code.

The common type system CTS defines a set of types and rules that are common to all
languages targeted at the CLR. It supports both value and reference types. Value types
are created in the stack and include all primitive types, structs, and enums. In contrast,
reference types are created in the managed heap and include objects, arrays,
collections, etc.

3. Multi-language support:-

.NET provides multi-language support by managing the compilers that are used to
convert the source to intermediate language (IL) and from IL to native code, and it
enforces program safety and security.

The basis for multiple language support is the common type system and metadata. The
basic data types used by the CLR are common to all languages. There are therefore no
conversion issues with the basic integer, floating-point and string types.

All languages deal with all data types in the same way. There is also a mechanism for
defining and managing new types.

4. tool Support:-

The CLR works hand-in-hand with tools like visual studio, compilers, debuggers, and
profilers to make the developer's job much simpler.

5. Security:-

The CLR manages system security through user and code identity coupled with
permission checks. The identity of the code can be known and permission for the use of
resources granted accordingly. This type of security is a major feature of .NET. The .NET
framework also provides support for role-based security using windows NT accounts and
groups.

6. Automatic Resource Management:-

The .NET CLR provides efficient and automatic resource management such as memory,
screen space, network connections, database, etc. CLR invokes various built-in functions
of .NET framework to allocate and de-allocate the memory of .NET objects.

Therefore, programmers need not write the code to explicitly allocate and de-allocate
memory to the program.

7. Easy and rich debugging support:-

The .NET IDE (integrated development environment) provides an easy and rich
debugging support. Once an exception occurs at run time, the program stops and the
IDE marks the line which contains the error along with the details of that error and
possible solutions. The runtime also provides built-in stack walking facilities making it
much easier to locate bugs and error.
8. Simplified development:-

With .NET installing or uninstalling, a window-based application is a matter of copying or


deleting files. This possible because .NET components are not referenced in the registry.

9. Framework class library:-

The framework class library (FCL) of the .NET framework contains a rich collection of
classes that are available for developers to use these classes in code Microsoft has
developed these classes to fulfill various tasks of applications, such as working with files
and other data storages, performing input-output operations, web services, data access,
and drawing graphics.

The classes in the FCL are logically grouped under various namespaces such as system,
System.collections, system.diagnostics, system.Globalization, system.IO, system.text
etc.

10. Portability:-

The application developed in the .NET environment is portable. When the source code of
a program written in a CLR compliant language complies, it generates a machine-
independent and intermediate code. This was originally called the Microsoft Intermediate
Language (MSIL) and has now been renamed as the common Intermediate Language
(CIL). CIL is the key to portability in .NET.

C# - Data Types
C# - Data Types

C# is a strongly-typed language. It means we must declare the type of a


variable that indicates the kind of values it is going to store, such as integer,
float, decimal, text, etc

C# mainly categorized data types in two types: Value types


and Reference types. Value types include simple types (such
as int, float, bool, and char), enum types, struct types, and
Nullable value types. Reference types include class types,
interface types, delegate types, and array types. Learn
about value types and reference types in detail in the next
chapter.
The variables in C#, are categorized into the following types:

 Value types

 Reference types

 Pointer types

Value Type
Value type variables can be assigned a value directly. They are derived
from the class System.ValueType.

The value types directly contain data. Some examples are int, char, and
float, which stores numbers, alphabets, and floating point numbers,
respectively. When you declare an int type, the system allocates
memory to store the value.

The following table lists the available value types in C# 2010:

Type Represents Range Default


Value

bool Boolean value True or False False

byte 8-bit unsigned integer 0 to 255 0


char 16-bit Unicode U +0000 to U +ffff '\0'
character

decimal 128-bit precise decimal (-7.9 x 1028 to 7.9 x 1028) / 100 to 28 0.0M
values with 28-29
significant digits

double 64-bit double-precision (+/-)5.0 x 10-324 to (+/-)1.7 x 10308 0.0D


floating point type

float 32-bit single-precision -3.4 x 1038 to + 3.4 x 1038 0.0F


floating point type

int 32-bit signed integer -2,147,483,648 to 2,147,483,647 0


type

long 64-bit signed integer -9,223,372,036,854,775,808 to 0L


type 9,223,372,036,854,775,807

sbyte 8-bit signed integer -128 to 127 0


type

short 16-bit signed integer -32,768 to 32,767 0


type

uint 32-bit unsigned integer 0 to 4,294,967,295 0


type

ulong 64-bit unsigned integer 0 to 18,446,744,073,709,551,615 0


type

ushort 16-bit unsigned integer 0 to 65,535 0


type

To get the exact size of a type or a variable on a particular platform, you


can use the sizeof method. The expression sizeof(type) yields the
storage size of the object or type in bytes.
Reference Type
The reference types do not contain the actual data stored in a variable,
but they contain a reference to the variables.

In other words, they refer to a memory location. Using multiple


variables, the reference types can refer to a memory location. If the data
in the memory location is changed by one of the variables, the other
variable automatically reflects this change in value. Example of built-
in reference types are: object, dynamic, and string.

Object Type
The Object Type is the ultimate base class for all data types in C#
Common Type System (CTS). Object is an alias for System.Object class.
The object types can be assigned values of any other types, value types,
reference types, predefined or user-defined types. However, before
assigning values, it needs type conversion.

When a value type is converted to object type, it is called boxing and on


the other hand, when an object type is converted to a value type, it is
called unboxing.

object obj;
obj =100;// this is boxing

Dynamic Type
You can store any type of value in the dynamic data type variable. Type
checking for these types of variables takes place at run-time.

Syntax for declaring a dynamic type is:

dynamic<variable_name>= value;

For example,

dynamic d =20;

Dynamic types are similar to object types except that type checking for
object type variables takes place at compile time, whereas that for the
dynamic type variables takes place at run time.

String Type
The String Type allows you to assign any string values to a variable.
The string type is an alias for the System.String class. It is derived from
object type. The value for a string type can be assigned using string
literals in two forms: quoted and @quoted.

For example,

String str ="C# Corner";

A @quoted string literal looks as follows:

@"C# Corner";

The user-defined reference types are: class, interface, or delegate. We


will discuss these types in later chapter.

Pointer Type
Pointer type variables store the memory address of another type.
Pointers in C# have the same capabilities as the pointers in C or C++.

Syntax for declaring a pointer type is:

type* identifier;

For example,

char* cptr;
int* iptr;

C# - Operators
An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations. C# has rich set of built-in
operators and provides the following type of operators:

 Arithmetic Operators

 Relational Operators

 Logical Operators

 Bitwise Operators
 Assignment Operators

 Misc Operators

This tutorial explains the arithmetic, relational, logical, bitwise,


assignment, and other operators one by one.

Arithmetic Operators
Following table shows all the arithmetic operators supported by C#.
Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example

+ Adds two operands A+B=


30

- Subtracts second operand from the first A-B=


-10

* Multiplies both operands A*B=


200

/ Divides numerator by de-numerator B/A=2

% Modulus Operator and remainder of after an integer B%A=


division 0

++ Increment operator increases integer value by one A++ =


11

-- Decrement operator decreases integer value by one A-- = 9

Relational Operators
Following table shows all the relational operators supported by C#.
Assume variable A holds 10 and variable B holds 20, then:

Operator Description Example


== Checks if the values of two operands are equal or not, if (A == B)
yes then condition becomes true. is not
true.

!= Checks if the values of two operands are equal or not, if (A != B)


values are not equal then condition becomes true. is true.

> Checks if the value of left operand is greater than the (A > B)
value of right operand, if yes then condition becomes true. is not
true.

< Checks if the value of left operand is less than the value of (A < B)
right operand, if yes then condition becomes true. is true.

>= Checks if the value of left operand is greater than or equal (A >= B)
to the value of right operand, if yes then condition is not
becomes true. true.

<= Checks if the value of left operand is less than or equal to (A <= B)
the value of right operand, if yes then condition becomes is true.
true.

Logical Operators
Following table shows all the logical operators supported by C#. Assume
variable A holds Boolean value true and variable B holds Boolean value
false, then:

Operator Description Example

&& Called Logical AND operator. If both the operands are non (A && B)
zero then condition becomes true. is false.

|| Called Logical OR Operator. If any of the two operands is (A || B)


non zero then condition becomes true. is true.

! Called Logical NOT Operator. Use to reverses the logical !(A &&
state of its operand. If a condition is true then Logical NOT B) is
operator will make false. true.
Bitwise Operators
Bitwise operator works on bits and perform bit by bit operation. The truth
tables for &, |, and ^ are as follows:

p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume if A = 60; and B = 13; then in the binary format they are as
follows:

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A  = 1100 0011

The Bitwise operators supported by C# are listed in the following table.


Assume variable A holds 60 and variable B holds 13, then:

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists (A & B) =
in both operands. 12, which is
0000 1100
| Binary OR Operator copies a bit if it exists in either (A | B) =
operand. 61, which is
0011 1101

^ Binary XOR Operator copies the bit if it is set in one (A ^ B) =


operand but not both. 49, which is
0011 0001

~ Binary Ones Complement Operator is unary and has the (~A ) = 61,
effect of 'flipping' bits. which is
1100 0011
in 2's
complement
due to a
signed
binary
number.

<< Binary Left Shift Operator. The left operands value is A << 2 =
moved left by the number of bits specified by the right 240, which
operand. is 1111
0000

>> Binary Right Shift Operator. The left operands value is A >> 2 =
moved right by the number of bits specified by the right 15, which is
operand. 0000 1111

Assignment Operators
There are following assignment operators supported by C#:

Operator Description Example

= Simple assignment operator, Assigns values from right C=A+B


side operands to left side operand assigns
value of A
+ B into C

+= Add AND assignment operator, It adds right operand to C += A is


the left operand and assign the result to left operand equivalent
to C = C
+A

-= Subtract AND assignment operator, It subtracts right C -= A is


operand from the left operand and assign the result to equivalent
left operand to C = C -
A

*= Multiply AND assignment operator, It multiplies right C *= A is


operand with the left operand and assign the result to left equivalent
operand to C = C
*A

/= Divide AND assignment operator, It divides left operand C /= A is


with the right operand and assign the result to left equivalent
operand to C = C /
A

%= Modulus AND assignment operator, It takes modulus C %= A is


using two operands and assign the result to left operand equivalent
to C = C
%A

<<= Left shift AND assignment operator C <<= 2


is same
as C = C
<< 2

>>= Right shift AND assignment operator C >>= 2


is same
as C = C
>> 2

&= Bitwise AND assignment operator C &= 2 is


same as C
=C&2

^= bitwise exclusive OR and assignment operator C ^= 2 is


same as C
=C^2

|= bitwise inclusive OR and assignment operator C |= 2 is


same as C
=C|2

Miscellaneous Operators
There are few other important operators including sizeof,
typeof and ?:supported by C#.

Operator Description Example

sizeof() Returns the size of a data type. sizeof(int), returns 4.

typeof() Returns the type of a class. typeof(StreamReader);

& Returns the address of an variable. &a; returns actual


address of the
variable.

* Pointer to a variable. *a; creates pointer


named 'a' to a
variable.

?: Conditional Expression If Condition is true ?


Then value X :
Otherwise value Y

is Determines whether an object is of a certain If( Ford is Car) //


type. checks if Ford is an
object of the Car class.

as Cast without raising an exception if the cast Object obj = new


fails. StringReader("Hello");

StringReader r = obj
as StringReader;

Operator Precedence in C#
Operator precedence determines the grouping of terms in an expression.
This affects evaluation of an expression. Certain operators have higher
precedence than others; for example, the multiplication operator has
higher precedence than the addition operator.

For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because


operator * has higher precedence than +, so the first evaluation takes
place for 3*2 and then 7 is added into it.

Here, operators with the highest precedence appear at the top of the
table, those with the lowest appear at the bottom. Within an expression,
higher precedence operators are evaluated first.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift <<>> Left to right

Relational <<= >>= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right


Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

Namespace aliases
The using directive can be also used to create namespace aliases. For example:
using col = System.Collections;

To reference aliased namespace you need to use ::


col::SortedList list2;

You can also create alias to a class.


using console = System.Console;

Class alias should be used with .  instead of ::


console.WriteLine();

Global namespace alias


Let’s assume you have System class defined in your code:
namespace MyFirstApplication
{
classProgram
{
publicclassSystem{}

staticvoidMain(string[] args)
{
System.Console.WriteLine("Hello, World!");// Error
}
}
}

The code won’t compile as System namespace is hidden by System class declaration. So, is
there a way to call hidden namespace? Yes, there is special global alias.
namespace MyFirstApplication
{
classProgram
{
publicclassSystem{}

staticvoidMain(string[] args)
{
global::System.Console.WriteLine("Hello, World!");// No error this time :)
}
}
}

But what will happen if one would like to make it’s life more difficult and will define own global
alias?
usingglobal= System;

It’s pointless. As it will generate a warning saying that global::  will always reference global
namespace and not the alias.
Let’s consider next example:
usingglobal= System.Console;

This time you can use the alias as it references a class and is used with .  instead of ::
global.WriteLine("Test");

But anyway the alias declaration will generate the same warning. So just be aware of that
possibility but please never do it yourself – in general, it’s just a bad practice.

What is Garbage Collection and Why We


Need It?
When you create any object in C#, CLR (common language runtime) allocates memory for the
object from heap. This process is repeated for each newly created object, but there is a limitation
to everything, Memory is not un-limited and we need to clean some used space in order to make
room for new objects, Here, the concept of garbage collection  is introduced, Garbage
collector  manages allocation and reclaiming of memory. GC (Garbage collector) makes a trip to
the heap and collects all objects that are no longer used by the application and then makes them
free from memory.
How GC Works?
GC works on managed heap, which is nothing but a block of memory to store objects, when
garbage collection process is put in motion, it checks for dead objects and the objects which are
no longer used, then it compacts the space of live object and tries to free more memory.

Basically, heap is managed by different 'Generations', it stores and handles long-lived and short-
lived objects, see the below generations of Heap:

 0 Generation (Zero): This generation holds short-lived objects, e.g., Temporary objects.
GC initiates garbage collection process frequently in this generation.
 1 Generation (One): This generation is the buffer between short-lived and long-lived
objects.
 2 Generation (Two): This generation holds long-lived objects like a static and global
variable, that needs to be persisted for a certain amount of time. Objects which are not collected
in generation Zero, are then moved to generation 1, such objects are known as survivors, similarly
objects which are not collected in generation One, are then moved to generation 2 and from
there onwards objects remain in the same generation.

How GC Decides If Objects Are Live?


GC checks the below information to check if the object is live:

 It collects all handles of an object that are allocated by user code or by CLR
 Keeps track of static objects, as they are referenced to some other objects
 Use stack provided by stack walker and JIT

When GC Gets Triggered?


There are no specific timings  for GC to get triggered, GC automatically starts operation on the
following conditions:
1. When virtual memory is running out of space.
2. When allocated memory is suppressed acceptable threshold (when GC found if the
survival rate (living objects) is high, then it increases the threshold allocation).
3. When we call GC.Collect()  method explicitly, as GC runs continuously, we actually do
not need to call this method.
4. Managed objects are created, managed and under scope of CLR, pure .NET code
managed by runtime, Anything that lies within .NET scope and under .NET framework
classes such as string, int, bool variables are referred to as managed code.
5. UnManaged objects are created outside the control of .NET libraries and are not
managed by CLR, example of such unmanaged code is COM objects, file streams,
connection objects, Interop objects. (Basically, third party libraries that are referred in
.NET code.)
Clean Up Unmanaged Resources
When we create unmanaged objects, GC is unable to clear them and we need to release such
objects explicitly  when we finished using them. Mostly unmanaged objects are wrapped/hide
around operating system resources  like file streams, database connections, network related
instances, handles to different classes, registries, pointers etc. GC is responsible to track the life
time of all managed and unmanaged objects but still GC is not aware of releasing unmanaged
resources

There are different ways to cleanup unmanaged resources:

 Implement IDisposable interface and Dispose method
 'using' block is also used to clean unmanaged resources

There are couple of ways to implement Dispose method:

 Implement Dispose using 'SafeHandle' Class (It is inbuilt abstract class which has


'CriticalFinalizerObject' and 'IDisposable' interface has been implemented)
 Object.Finalize method to be override (This method is clean unmanaged resources
used by particular object before it is destroyed)

using' Statement
using statement ensures object dispose, in short, it gives a comfort way of use
of IDisposable objects. When an Object goes out of scope, Dispose method will get called
automatically, basically using block does the same thing as 'TRY...FINALLY' block. To
demonstrate it, create a class with IDisposable implementation (it should
have Dispose() method), 'using' statement calls 'dispose' method even if exception occurs.

See the below snippet:

class testClass : IDisposable


{
publicvoid Dispose()
{
// Dispose objects here
// clean resources
Console.WriteLine(0);
}
}

//call class
class Program
{
staticvoid Main()
{
// Use using statement with class that implements Dispose.
using (testClass objClass = new testClass())
{
Console.WriteLine(1);
}
Console.WriteLine(2);
}
}

//output
1
0
2

//it is same as below TRY...Finally code


{
clsDispose_Fin objClass = new clsDispose_Fin();
try
{
//code goes here
}
finally
{
if (objClass != null)
((IDisposable)objClass).Dispose();
}
}

C# manages the memory dynamically and uses a garbage collector,


running on a separate thread, to execute all destructors on exit. The
Process of calling a destructor when an object is reclaimed by the garbage
collector is called finalization.

C# - Jagged Arrays

Jagged array is a array of arrays such that member arrays can be


of different sizes. In other words, the length of each array index
can differ. The elements of Jagged Array are reference types and
initialized to null by default. Jagged Array can also be mixed with
multidimensional arrays. Here, the number of rows will be fixed
at the declaration time, but you can vary the number of columns.
A Jagged array is an array of arrays. You can declare a jagged array
named scores of type int as:

int[][] scores;

Declaring an array, does not create the array in memory. To create the
above array:

int[][] scores =newint[5][];


for(int i =0; i <scores.Length; i++)
{
scores[i]=newint[4];
}

You can initialize a jagged array as:

int[][] scores =newint[2][]{newint[]{92,93,94},newint[]{85,66,87,88}};

Where, scores is an array of two arrays of integers - scores[0] is an


array of 3 integers and scores[1] is an array of 4 integers.

Example
The following example illustrates using a jagged array:

usingSystem;
namespaceArrayApplication
{
classMyArray
{
staticvoidMain(string[] args)
{
/* a jagged array of 5 array of integers*/
int[][] a =newint[][]{newint[]{0,0},newint[]{1,2},newint[]{2,4},newint[]
{3,6},newint[]{4,8}};
int i, j;

/* output each array element's value */


for(i =0; i <5; i++)
{
for(j =0; j <2; j++)
{
Console.WriteLine("a[{0}][{1}] = {2}", i, j, a[i][j]);
}
}
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following
result:

a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8

C# - Collections

Collection classes are specialized classes for data storage and retrieval.
These classes provide support for stacks, queues, lists, and hash tables.
Most collection classes implement the same interfaces.

Collection classes serve various purposes, such as allocating memory


dynamically to elements and accessing a list of items on the basis of an
index etc. These classes create collections of objects of the Object class,
which is the base class for all data types in C#.

Collections are defined in System.Collection namespace.

C# - ArrayList Class
It represents an ordered collection of an object that can be indexed
individually. It is basically an alternative to an array. However, unlike array
you can add and remove items from a list at a specified position using
an indexand the array resizes itself automatically. It also allows dynamic
memory allocation, adding, searching and sorting items in the list.

Methods and Properties of ArrayList


Class
The following table lists some of the commonly used properties of
the ArrayList class:

Property Description
Capacity Gets or sets the number of elements that the ArrayList can
contain.

Count Gets the number of elements actually contained in the


ArrayList.

IsFixedSize Gets a value indicating whether the ArrayList has a fixed size.

IsReadOnly Gets a value indicating whether the ArrayList is read-only.

Item Gets or sets the element at the specified index.

The following table lists some of the commonly used methods of


the ArrayList class:

Sr.No. Methods

1 public virtual int Add(object value);

Adds an object to the end of the ArrayList.

2 public virtual void AddRange(ICollection c);


Adds the elements of an ICollection to the end of the ArrayList.

3 public virtual void Clear();


Removes all elements from the ArrayList.

4 public virtual bool Contains(object item);


Determines whether an element is in the ArrayList.

5 public virtual ArrayList GetRange(int index, int count);


Returns an ArrayList which represents a subset of the elements in the
source ArrayList.

6 public virtual int IndexOf(object);


Returns the zero-based index of the first occurrence of a value in the
ArrayList or in a portion of it.

7 public virtual void Insert(int index, object value);


Inserts an element into the ArrayList at the specified index.

8 public virtual void InsertRange(int index, ICollection c);


Inserts the elements of a collection into the ArrayList at the specified
index.

9 public virtual void Remove(object obj);


Removes the first occurrence of a specific object from the ArrayList.

10 public virtual void RemoveAt(int index);


Removes the element at the specified index of the ArrayList.

11 public virtual void RemoveRange(int index, int count);


Removes a range of elements from the ArrayList.

12 public virtual void Reverse();


Reverses the order of the elements in the ArrayList.

13 public virtual void SetRange(int index, ICollection c);


Copies the elements of a collection over a range of elements in the
ArrayList.

14 public virtual void Sort();


Sorts the elements in the ArrayList.

15 public virtual void TrimToSize();


Sets the capacity to the actual number of elements in the ArrayList.

Example
The following example demonstrates the concept:

usingSystem;
usingSystem.Collections;

namespaceCollectionApplication
{
classProgram
{
staticvoidMain(string[] args)
{
ArrayList al =newArrayList();

Console.WriteLine("Adding some numbers:");


al.Add(45);
al.Add(78);
al.Add(33);
al.Add(56);
al.Add(12);
al.Add(23);
al.Add(9);

Console.WriteLine("Capacity: {0} ",al.Capacity);


Console.WriteLine("Count: {0}",al.Count);

Console.Write("Content: ");
foreach(int i in al)
{
Console.Write(i +" ");
}

Console.WriteLine();
Console.Write("Sorted Content: ");
al.Sort();
foreach(int i in al)
{
Console.Write(i +" ");
}
Console.WriteLine();
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following
result:

Adding some numbers:


Capacity: 8
Count: 7
Content: 45 78 33 56 12 23 9
Content: 9 12 23 33 45 56 78

C# - Hashtable Class

The Hashtable class represents a collection of key-and-value pairs that


are organized based on the hash code of the key. It uses the key to
access the elements in the collection.

A hash table is used when you need to access elements by using key,


and you can identify a useful key value. Each item in the hash table has
a key/value pair. The key is used to access the items in the collection.

Methods and Properties of the Hashtable


Class
The following table lists some of the commonly used properties of
the Hashtable class:

Property Description

Count Gets the number of key-and-value pairs contained in the


Hashtable.

IsFixedSize Gets a value indicating whether the Hashtable has a fixed


size.

IsReadOnly Gets a value indicating whether the Hashtable is read-only.


Item Gets or sets the value associated with the specified key.

Keys Gets an ICollection containing the keys in the Hashtable.

Values Gets an ICollection containing the values in the Hashtable.

The following table lists some of the commonly used methods of


the Hashtable class:

Sr.No. Method

1 public virtual void Add(object key, object value);

Adds an element with the specified key and value into the Hashtable.

2 public virtual void Clear();

Removes all elements from the Hashtable.

3 public virtual bool ContainsKey(object key);

Determines whether the Hashtable contains a specific key.

4 public virtual bool ContainsValue(object value);

Determines whether the Hashtable contains a specific value.

5 public virtual void Remove(object key);

Removes the element with the specified key from the Hashtable.

Example
The following example demonstrates the concept:

usingSystem;
usingSystem.Collections;

namespaceCollectionsApplication
{
classProgram
{
staticvoidMain(string[] args)
{
Hashtable ht =newHashtable();

ht.Add("001","Zara Ali");
ht.Add("002","Abida Rehman");
ht.Add("003","Joe Holzner");
ht.Add("004","Mausam Benazir Nur");
ht.Add("005","M. Amlan");
ht.Add("006","M. Arif");
ht.Add("007","Ritesh Saikia");

if(ht.ContainsValue("Nuha Ali"))
{
Console.WriteLine("This student name is already in the list");
}
else
{
ht.Add("008","Nuha Ali");
}

// Get a collection of the keys.


ICollection key =ht.Keys;

foreach(string k in key)
{
Console.WriteLine(k +": "+ ht[k]);
}

Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following
result:

001: Zara Ali


002: Abida Rehman
003: Joe Holzner
004: Mausam Benazir Nur
005: M. Amlan
006: M. Arif
007: Ritesh Saikia
008: Nuha Ali

C# - Indexers

An indexer allows an object to be indexed such as an array. When you


define an indexer for a class, this class behaves similar to a virtual
array. You can then access the instance of this class using the array
access operator ([ ]).

Syntax
A one dimensional indexer has the following syntax:

element-type this[int index]


{
// The get accessor.
get
{
// return the value specified by index
}

// The set accessor.


set
{
// set the value specified by index
}
}
Use of Indexers
Declaration of behavior of an indexer is to some extent similar to a
property. similar to the properties, you use get and set accessors for
defining an indexer. However, properties return or set a specific data
member, whereas indexers returns or sets a particular value from the
object instance. In other words, it breaks the instance data into smaller
parts and indexes each part, gets or sets each part.

Defining a property involves providing a property name. Indexers are not


defined with names, but with the this keyword, which refers to the
object instance. The following example demonstrates the concept:

usingSystem;
namespaceIndexerApplication
{
classIndexedNames
{
privatestring[] namelist =newstring[size];
staticpublicint size =10;
publicIndexedNames()
{
for(int i =0; i < size; i++)
namelist[i]="N. A.";
}

publicstringthis[int index]
{
get
{
string tmp;

if( index>=0&& index <= size-1)


{
tmp = namelist[index];
}
else
{
tmp ="";
}

return( tmp);
}
set
{
if( index>=0&& index <= size-1)
{
namelist[index]= value;
}
}
}

staticvoidMain(string[] args)
{
IndexedNames names =newIndexedNames();
names[0]="Zara";
names[1]="Riz";
names[2]="Nuha";
names[3]="Asif";
names[4]="Davinder";
names[5]="Sunil";
names[6]="Rubic";
for(int i =0; i <IndexedNames.size; i++)
{
Console.WriteLine(names[i]);
}

Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following
result:

Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic
N. A.
N. A.
N. A.

Overloaded Indexers
Indexers can be overloaded. Indexers can also be declared with multiple
parameters and each parameter may be a different type. It is not
necessary that the indexes have to be integers. C# allows indexes to be
of other types, for example, a string.

The following example demonstrates overloaded indexers:

usingSystem;
namespaceIndexerApplication
{
classIndexedNames
{
privatestring[] namelist =newstring[size];
staticpublicint size =10;
publicIndexedNames()
{
for(int i =0; i < size; i++)
{
namelist[i]="N. A.";
}
}

publicstringthis[int index]
{
get
{
string tmp;

if( index>=0&& index <= size-1)


{
tmp = namelist[index];
}
else
{
tmp ="";
}

return( tmp);
}
set
{
if( index>=0&& index <= size-1)
{
namelist[index]= value;
}
}
}
publicintthis[string name]
{
get
{
int index =0;
while(index < size)
{
if(namelist[index]== name)
{
return index;
}
index++;
}
return index;
}

staticvoidMain(string[] args)
{
IndexedNames names =newIndexedNames();
names[0]="Zara";
names[1]="Riz";
names[2]="Nuha";
names[3]="Asif";
names[4]="Davinder";
names[5]="Sunil";
names[6]="Rubic";

//using the first indexer with int parameter


for(int i =0; i <IndexedNames.size; i++)
{
Console.WriteLine(names[i]);
}

//using the second indexer with the string parameter


Console.WriteLine(names["Nuha"]);
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following
result:

Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic
N. A.
N. A.
N. A.
2

C# - Properties

Properties are named members of classes, structures, and interfaces.


Member variables or methods in a class or structures are called Fields.
Properties are an extension of fields and are accessed using the same
syntax. They use accessors through which the values of the private
fields can be read, written or manipulated.

Properties do not name the storage locations. Instead, they


have accessorsthat read, write, or compute their values.

For example, let us have a class named Student, with private fields for
age, name, and code. We cannot directly access these fields from outside
the class scope, but we can have properties for accessing these private
fields.

Accessors
The accessor of a property contains the executable statements that
helps in getting (reading or computing) or setting (writing) the property.
The accessor declarations can contain a get accessor, a set accessor, or
both. For example:

// Declare a Code property of type string:


publicstringCode
{
get
{
return code;
}
set
{
code = value;
}
}
// Declare a Name property of type string:
publicstringName
{
get
{
return name;
}
set
{
name = value;
}
}

// Declare a Age property of type int:


publicintAge
{
get
{
return age;
}
set
{
age = value;
}
}

Example
The following example demonstrates use of properties:

usingSystem;
namespace tutorialspoint
{
classStudent
{
privatestring code ="N.A";
privatestring name ="not known";
privateint age =0;

// Declare a Code property of type string:


publicstringCode
{
get
{
return code;
}
set
{
code = value;
}
}

// Declare a Name property of type string:


publicstringName
{
get
{
return name;
}
set
{
name = value;
}
}

// Declare a Age property of type int:


publicintAge
{
get
{
return age;
}
set
{
age = value;
}
}
publicoverridestringToString()
{
return"Code = "+Code+", Name = "+Name+", Age = "+Age;
}
}

classExampleDemo
{
publicstaticvoidMain()
{

// Create a new Student object:


Student s =newStudent();

// Setting code, name and the age of the student


s.Code="001";
s.Name="Zara";
s.Age=9;
Console.WriteLine("Student Info: {0}", s);

//let us increase age


s.Age+=1;
Console.WriteLine("Student Info: {0}", s);
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following
result:
Student Info: Code = 001, Name = Zara, Age = 9
Student Info: Code = 001, Name = Zara, Age = 10

Abstract Properties
An abstract class may have an abstract property, which should be
implemented in the derived class. The following program illustrates this:

usingSystem;
namespace tutorialspoint
{
publicabstractclassPerson
{
publicabstractstringName
{
get;
set;
}
publicabstractintAge
{
get;
set;
}
}

classStudent:Person
{

privatestring code ="N.A";


privatestring name ="N.A";
privateint age =0;

// Declare a Code property of type string:


publicstringCode
{
get
{
return code;
}
set
{
code = value;
}
}

// Declare a Name property of type string:


publicoverridestringName
{
get
{
return name;
}
set
{
name = value;
}
}

// Declare a Age property of type int:


publicoverrideintAge
{
get
{
return age;
}
set
{
age = value;
}
}
publicoverridestringToString()
{
return"Code = "+Code+", Name = "+Name+", Age = "+Age;
}
}

classExampleDemo
{
publicstaticvoidMain()
{
// Create a new Student object:
Student s =newStudent();

// Setting code, name and the age of the student


s.Code="001";
s.Name="Zara";
s.Age=9;
Console.WriteLine("Student Info:- {0}", s);

//let us increase age


s.Age+=1;
Console.WriteLine("Student Info:- {0}", s);
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following
result:

Student Info: Code = 001, Name = Zara, Age = 9


Student Info: Code = 001, Name = Zara, Age = 10
C# - Delegates

C# delegates are similar to pointers to functions, in C or C++.


A delegate is a reference type variable that holds the reference to a
method. The reference can be changed at runtime.

Delegates are especially used for implementing events and the call-back
methods. All delegates are implicitly derived from
the System.Delegateclass.

Declaring Delegates
Delegate declaration determines the methods that can be referenced by
the delegate. A delegate can refer to a method, which has the same
signature as that of the delegate.

For example, consider a delegate:

publicdelegateintMyDelegate(string s);

The preceding delegate can be used to reference any method that has a
single string parameter and returns an int type variable.

Syntax for delegate declaration is:

delegate<return type><delegate-name><parameter list>

Instantiating Delegates
Once a delegate type is declared, a delegate object must be created with
the new keyword and be associated with a particular method. When
creating a delegate, the argument passed to the new expression is
written similar to a method call, but without the arguments to the
method. For example:

publicdelegatevoidprintString(string s);
...
printString ps1 =new printString(WriteToScreen);
printString ps2 =new printString(WriteToFile);
Following example demonstrates declaration, instantiation, and use of a
delegate that can be used to reference methods that take an integer
parameter and returns an integer value.

usingSystem;

delegateintNumberChanger(int n);
namespaceDelegateAppl
{
classTestDelegate
{
staticint num =10;
publicstaticintAddNum(int p)
{
num += p;
return num;
}

publicstaticintMultNum(int q)
{
num *= q;
return num;
}
publicstaticintgetNum()
{
return num;
}

staticvoidMain(string[] args)
{
//create delegate instances
NumberChanger nc1 =newNumberChanger(AddNum);
NumberChanger nc2 =newNumberChanger(MultNum);

//calling the methods using the delegate objects


nc1(25);
Console.WriteLine("Value of Num: {0}",getNum());
nc2(5);
Console.WriteLine("Value of Num: {0}",getNum());
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following
result:

Value of Num: 35
Value of Num: 175

Multicasting of a Delegate
Delegate objects can be composed using the "+" operator. A composed
delegate calls the two delegates it was composed from. Only delegates of
the same type can be composed. The "-" operator can be used to remove
a component delegate from a composed delegate.

Using this property of delegates you can create an invocation list of


methods that will be called when a delegate is invoked. This is
called multicasting of a delegate. The following program demonstrates
multicasting of a delegate:

usingSystem;

delegateintNumberChanger(int n);
namespaceDelegateAppl
{
classTestDelegate
{
staticint num =10;
publicstaticintAddNum(int p)
{
num += p;
return num;
}
publicstaticintMultNum(int q)
{
num *= q;
return num;
}

publicstaticintgetNum()
{
return num;
}

staticvoidMain(string[] args)
{
//create delegate instances
NumberChanger nc;
NumberChanger nc1 =newNumberChanger(AddNum);
NumberChanger nc2 =newNumberChanger(MultNum);
nc = nc1;
nc += nc2;

//calling multicast
nc(5);
Console.WriteLine("Value of Num: {0}",getNum());
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following
result:

Value of Num: 75

Using Delegates
The following example demonstrates the use of delegate. The
delegate printString can be used to reference method that takes a string
as input and returns nothing.
We use this delegate to call two methods, the first prints the string to the
console, and the second one prints it to a file:

usingSystem;
usingSystem.IO;

namespaceDelegateAppl
{
classPrintString
{
staticFileStream fs;
staticStreamWriter sw;

// delegate declaration
publicdelegatevoidprintString(string s);

// this method prints to the console


publicstaticvoidWriteToScreen(string str)
{
Console.WriteLine("The String is: {0}", str);
}

//this method prints to a file


publicstaticvoidWriteToFile(string s)
{
fs =newFileStream("c:\\message.txt",
FileMode.Append,FileAccess.Write);
sw =newStreamWriter(fs);
sw.WriteLine(s);
sw.Flush();
sw.Close();
fs.Close();
}

// this method takes the delegate as parameter and uses it to


// call the methods as required
publicstaticvoidsendString(printString ps)
{
ps("Hello World");
}
staticvoidMain(string[] args)
{
printString ps1 =new printString(WriteToScreen);
printString ps2 =new printString(WriteToFile);
sendString(ps1);
sendString(ps2);
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following
result:

The String is: Hello World

C# - Events

Events are user actions such as key press, clicks, mouse movements,


etc., or some occurrence such as system generated notifications.
Applications need to respond to events when they occur. For example,
interrupts. Events are used for inter-process communication.

Using Delegates with Events


The events are declared and raised in a class and associated with the
event handlers using delegates within the same class or some other
class. The class containing the event is used to publish the event. This is
called the publisherclass. Some other class that accepts this event is
called the subscriber class. Events use the publisher-
subscriber model.
A publisher is an object that contains the definition of the event and the
delegate. The event-delegate association is also defined in this object. A
publisher class object invokes the event and it is notified to other
objects.

A subscriber is an object that accepts the event and provides an event


handler. The delegate in the publisher class invokes the method (event
handler) of the subscriber class.

Declaring Events
To declare an event inside a class, first a delegate type for the event
must be declared. For example,

publicdelegatestringMyDel(string str);

Next, the event itself is declared, using the event keyword:

eventMyDelMyEvent;

The preceding code defines a delegate named BoilerLogHandler and an


event named BoilerEventLog, which invokes the delegate when it is
raised.

Example
usingSystem;

namespaceSampleApp{
publicdelegatestringMyDel(string str);

classEventProgram{
eventMyDelMyEvent;

publicEventProgram(){
this.MyEvent+=newMyDel(this.WelcomeUser);
}

publicstringWelcomeUser(string username){
return"Welcome "+ username;
}

staticvoidMain(string[] args){
EventProgram obj1 =newEventProgram();
string result = obj1.MyEvent("Tutorials Point");
Console.WriteLine(result);
}

}
}

When the above code is compiled and executed, it produces the following
result:

Welcome Tutorials Point

 What is a delegate and where to use it?


 What are multicast delegates?
 When to use Delegate VS Event

So in this article we will try to attempt to answer the above three queries.

Answering in short
Below is a simple diagram which explains how delegates, multicast delegates and events
are connected.

 Delegates are pointer to functions and used for call back.


 Multicast delegates help to invoke multiple callbacks.
 Events encapsulate delegate and implement publisher and subscriber model.
 Events and Multicast are types of delegates. So delegate is the base for events
and multicast.

In the rest of the article we will try to understand the above statements in more detail.

Summarizing
So if we summarize delegate is a call back , multicast delegate is for multiple call backs
while events do multicast callback but client has no control on the delegate. In case of
event clients can only subscribe to the delegate.

C# - Exception Handling

An exception is a problem that arises during the execution of a program.


A C# exception is a response to an exceptional circumstance that arises
while a program is running, such as an attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a program


to another. C# exception handling is built upon four
keywords: try, catch, finally, and throw.

 try: A try block identifies a block of code for which particular exceptions is
activated. It is followed by one or more catch blocks.
 catch: A program catches an exception with an exception handler at the
place in a program where you want to handle the problem. The catch
keyword indicates the catching of an exception.
 finally: The finally block is used to execute a given set of statements,
whether an exception is thrown or not thrown. For example, if you open a
file, it must be closed whether an exception is raised or not.
 throw: A program throws an exception when a problem shows up. This is
done using a throw keyword.

Syntax
Assuming a block raises an exception, a method catches an exception
using a combination of the try and catch keywords. A try/catch block is
placed around the code that might generate an exception. Code within a
try/catch block is referred to as protected code, and the syntax for using
try/catch looks like the following:

try
{
// statements causing exception
}
catch(ExceptionName e1 )
{
// error handling code
}
catch(ExceptionName e2 )
{
// error handling code
}
catch(ExceptionName eN )
{
// error handling code
}
finally
{
// statements to be executed
}
You can list down multiple catch statements to catch different type of
exceptions in case your try block raises more than one exception in
different situations.

Exception Classes in C#
C# exceptions are represented by classes. The exception classes in C#
are mainly directly or indirectly derived from
the System.Exception class. Some of the exception classes derived
from the System.Exception class are
the System.ApplicationException and System.SystemException cla
sses.

The System.ApplicationException class supports exceptions generated


by application programs. Hence the exceptions defined by the
programmers should derive from this class.

The System.SystemException class is the base class for all predefined


system exception.

The following table provides some of the predefined exception classes


derived from the Sytem.SystemException class:

Exception Class Description

System.IO.IOException Handles I/O errors.

System.IndexOutOfRangeException Handles errors generated when a method


refers to an array index out of range.

System.ArrayTypeMismatchExceptio Handles errors generated when type is


n mismatched with the array type.

System.NullReferenceException Handles errors generated from referencing


a null object.

System.DivideByZeroException Handles errors generated from dividing a


dividend with zero.
System.InvalidCastException Handles errors generated during
typecasting.

System.OutOfMemoryException Handles errors generated from insufficient


free memory.

System.StackOverflowException Handles errors generated from stack


overflow.

Handling Exceptions
C# provides a structured solution to the exception handling in the form
of try and catch blocks. Using these blocks the core program statements
are separated from the error-handling statements.

These error handling blocks are implemented using the try, catch,


and finally keywords. Following is an example of throwing an exception
when dividing by zero condition occurs:

usingSystem;
namespaceErrorHandlingApplication
{
classDivNumbers
{
int result;
DivNumbers()
{
result =0;
}
publicvoiddivision(int num1,int num2)
{
try
{
result = num1 / num2;
}
catch(DivideByZeroException e)
{
Console.WriteLine("Exception caught: {0}", e);
}
finally
{
Console.WriteLine("Result: {0}", result);
}
}
staticvoidMain(string[] args)
{
DivNumbers d =newDivNumbers();
d.division(25,0);
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following
result:

Exception caught: System.DivideByZeroException: Attempted to divide by zero.


at ...
Result: 0

Creating User-Defined Exceptions


You can also define your own exception. User-defined exception classes
are derived from the Exception class. The following example
demonstrates this:

usingSystem;
namespaceUserDefinedException
{
classTestTemperature
{
staticvoidMain(string[] args)
{
Temperature temp =newTemperature();
try
{
temp.showTemp();
}
catch(TempIsZeroException e)
{
Console.WriteLine("TempIsZeroException: {0}",e.Message);
}
Console.ReadKey();
}
}
}

publicclassTempIsZeroException:Exception
{
publicTempIsZeroException(string message):base(message)
{
}
}

publicclassTemperature
{
int temperature =0;
publicvoidshowTemp()
{
if(temperature ==0)
{
throw(newTempIsZeroException("Zero Temperature found"));
}
else
{
Console.WriteLine("Temperature: {0}", temperature);
}
}
}

When the above code is compiled and executed, it produces the following
result:
TempIsZeroException: Zero Temperature found

Throwing Objects
You can throw an object if it is either directly or indirectly derived from
the System.Exception class. You can use a throw statement in the
catch block to throw the present object as:

Catch(Exception e)
{
...
Throw e
}

Unit-III

ADO.Net & Object Oriented Concepts (Using VB.Net or C#): Basic


window control, Architecture of ADO.Net, Comparison with ADO,
.Net Data provider, Data Adapter, Data Set, Data Row, Data
Column, Data Relation, command, Data Reader, Data Grid
Constructor, Destructor, Abstraction, interface, polymorphism (Over
loading and over ridding)

What is ADO.NET?

 ADO stands for ActiveX Data Objects


 ADO.NET is a database technology of .NET Framework used to connect
application system and database server.
 ADO.NET is a part of the .NET Framework
 ADO.NET consists of a set of classes used to handle data access
 ADO.NET uses XML to store and transfer data among applications, which is not
only an industry standard but also provide fast access of data for desktop and
distributed applications.
 ADO.NET is scalable and interoperable.

ADO.NET Architecture
Advantages of ADO.NET

ADO.NET offers several advantages over previous Microsoft data access technologies,
including ADO. Few advantages are listed below:

Single Object-oriented API


 

ADO.NET provides a single object-oriented set of classes. There are different data
providers to work with different data sources but the programming model for all these
data providers work in the same way. You should be aware of only one data provider.
You just need to change class names and connection strings.

The ADO.NET classes are easy to use and understand, as they are object-oriented in
nature.

 
Managed Code
 

The ADO.NET classes are managed classes. CLR takes care of language independency
and automatic resource management.

Deployment
 

Microsoft uses MDAC (Microsoft Data Access Component), which is used as ActiveX
component in .NET Framework (X is extensible component, when X is written after a
term means extensible). .NET components takes care of deployment which was difficult
previous technologies used in deployment.

XML Support
 

ADO.NET data is cached and transferred in XML (EXtensible Markup Language) format.
XML provide fast access of data for desktop and distributed applications. XML is plain
text designed to transport and store data and is self-descriptive.

Visual Data Components


 

.NET offers ADO.NET components and data-bound control to work in visual form.  You
can use these components without writing long codes and can achieve result in no time.

Performance and scalability


 

Performance and scalability are two major factors when developing web-based
application and services. Disconnected cached data in XML help in performance and
scalability.

Difference between ADO and ADO.NET


ADO ADO.NET
ADO.NET provides objects that allow you to access
ADO has one main object that is data in various ways. The DataSetobject allows
used to reference data, called the you to store the relational model of
RecordSet object. your database.  MARS (Multiple Active Result
Sets) is implemented in ADO.NET
You can only work on connected ADO.NET uses data in a disconnected fashion.
manner. This means that when you When you access data, ADO.NET makes a copy of
access data, such as viewing and the data using XML. ADO.NET only holds the
updating data, it is real-time, with a connection open long enough to either pull down
connection being used all the time. the data or to make any requested updates. This
This is barring, of course, you makes ADO.NET efficient to use
programming special routines to pull for Web applications. It's also decent for desktop
all your data into temporary tables. applications.
   
In connected model you always get You can work on connected and disconnected
manner.
 
In disconnected model you will get old data as you
are editing it. Outlook is an example of
disconnected model. We work on offline object
refreshed data. model and when connection is required it is
connected.
 
Connected object can be used on disconnected
object.
 
ADO.NET allows you to manipulate your data
using XML as the primary means. This is nice
Whereas ADO allows you to persist when you are working with other business
records in XML format. applications and also helps when you are working
with firewalls because data is passed as HTML and
XML.
ADO.NET gives you the choice of either using
client-side or server-side cursors. In ADO.NET,
ADO allows you to create client-side classes actually handle the work of cursors. The
cursors only. developer has the freedom of choice
in internet development, for creating efficient
applications.

The following are a few of the .NET applications that use ADO.NET to connect to a database,
execute commands and retrieve data from the database.

 ASP.NET Web Applications


 Console Applications
 Windows Applications.

Various Connection Architectures

There are the following two types of connection architectures:

1. Connected architecture: the application remains connected with the database


throughout the processing.

2. Disconnected architecture: the application automatically connects/disconnects during


the processing. The application uses temporary data on the application side called a
DataSet.

Understanding ADO.NET and its class library


In this diagram, we can see that there are various types of applications (Web Application,
Console Application, Windows Application and so on) that use ADO.NET to connect to
databases (SQL Server, Oracle, OleDb, ODBC, XML files and so on).

Important Classes in ADO.NET

We can also observe various classes in the preceding diagram. They are:

1. Connection Class
2. Command Class
3. DataReader Class
4. DataAdaptor Class
5. DataSet.Class

1. Connection Class

In ADO.NET, we use these connection classes to connect to the database. These connection
classes also manage transactions and connection pooling.

2. Command Class

The Command class provides methods for storing and executing SQL statements and Stored
Procedures. The following are the various commands that are executed by the Command Class.

 ExecuteReader: Returns data to the client as rows. This would typically be an SQL


select statement or a Stored Procedure that contains one or more select statements. This
method returns a DataReader object that can be used to fill a DataTable object or used
directly for printing reports and so forth.
 ExecuteNonQuery: Executes a command that changes the data in the database, such
as an update, delete, or insert statement, or a Stored Procedure that contains one or
more of these statements. This method returns an integer that is the number of rows
affected by the query.
 ExecuteScalar: This method only returns a single value. This kind of query returns a
count of rows or a calculated value.
 ExecuteXMLReader: (SqlClient classes only) Obtains data from an SQL Server 2000
database using an XML stream. Returns an XML Reader object.

3. DataReader Class

The DataReader is used to retrieve data. It is used in conjunction with the Command class to
execute an SQL Select statement and then access the returned rows.

4. DataAdapter Class

The DataAdapter is used to connect DataSets to databases. The DataAdapter is most useful
when using data-bound controls in Windows Forms, but it can also be used to provide an easy
way to manage the connection between your application and the underlying database tables,
views and Stored Procedures.

5. DataSet Class

The DataSet is the heart of ADO.NET. The DataSet is essentially a collection of DataTable
objects. In turn each object contains a collection of DataColumn and DataRow objects. The
DataSet also contains a Relations collection that can be used to define relations among Data
Table Objects.

How to Connect to a Database using ADO.NET

Now let us learn how to connect to a database using ADO.NET. To create a connection, you
must be familiar with connection strings. A connection string is required as a parameter to
SQLConnection. A ConnectionString is a string variable (not case sensitive).

This contains key and value pairs, like provider, server, database, userid and word as in the
following:

Server="nameof the server or IP Address of the server"

Database="name of the database"

userid="user name who has permission to work with database"

word="the word of userid"

Example

SQL Authentication

String constr="server=.;database=institute;user id=rakesh;word=abc@123";

Or:

String constr="data source=.;initial catalog=institute;uid=rakesh;pwd=abc@213";

Windows Authentication

String constr="server=.;database=institute;trusted_connection=true" 
Or:

String constr="server=.;initial catalog=institute;integrated security=true"

How to retrieve and display data from a database

Procedure:

1. Create a SqlConnection object using a connection string.

2. Handle exceptions.

3. Open the connection.

4. Create a SQLCommand. To represent a SQLCommand like (select * from studentdetails)


and attach the existing connection to it. Specify the type of SQLCommand
(text/storedprocedure).

5. Execute the command (use executereader).

6. Get the Result (use SqlDataReader). This is a forwardonly/readonly dataobject.

7. Close the connection


8. Process the result
9. Display the Result

Code for connecting to Oracle Database

If you want to connect to an Oracle database, all you need to do is to change the connection
class name from SqlConnection to OracleConnection Command class name from SqlCommand
to OracleCommand and SqlDataReader to OracleDataReader and also in the beginning use
the namespace System.Data.OralceClient.

.NET Data Provider

Definition - What does .NET Data Provider mean?


A .NET data provider is a software library consisting of classes that provide data
access services such as connecting to a data source, executing commands at a data
source and fetching data from a data source with support to execute commands
within transactions. It resides as a lightweight layer between data source and code,
providing data access services with increased performance. 

The .NET data provider is a component of ADO.NET, a subset of the .NET


framework class library.
A .NET data provider consists of the following core objects:

 The Connection object is used to connect to a specific data source


 The Command object executes a command against a data source
 DataReader reads data from the data source in read-only, forward-only mode
 DataAdapter populates a data set and resolves an update with the data
source

DataReader

DataReader is used to read the data from database and it is a read and forward only connection
oriented architecture during fetch the data from database. DataReader will fetch the data very
fast when compared with dataset. Generally we will use ExecuteReader object to bind data to
datareader.

To bind DataReader data to GridView we need to write the code like as shown below: 

1. Protected void BindGridview() {  
2.     using(SqlConnection conn = new SqlConnection("Data Source=abc;Integrated Securi
ty=true;Initial Catalog=Test")) {  
3.         con.Open();  
4.         SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Locat
ion FROM Users", conn);  
5.         SqlDataReader sdr = cmd.ExecuteReader();  
6.         gvUserInfo.DataSource = sdr;  
7.         gvUserInfo.DataBind();  
8.         conn.Close();  
9.     }  
10. }   

 Holds the connection open until you are finished (don't forget to close it!).
 Can typically only be iterated over once
 Is not as useful for updating back to the database

DataSet

DataSet is a disconnected orient architecture that means there is no need of active connections
during work with datasets and it is a collection of DataTables and relations between tables. It is
used to hold multiple tables with data. You can select data form tables, create views based on
table and ask child rows over relations. Also DataSet provides you with rich features like saving
data as XML and loading XML data. 

1. protected void BindGridview() {  
2.     SqlConnection conn = new SqlConnection("Data Source=abc;Integrated Security=tru
e;Initial Catalog=Test");  
3.     conn.Open();  
4.     SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location 
FROM Users", conn);  
5.     SqlDataAdapter sda = new SqlDataAdapter(cmd);  
6.     DataSet ds = new DataSet();  
7.     da.Fill(ds);  
8.     gvUserInfo.DataSource = ds;  
9.     gvUserInfo.DataBind();  
10. }   

DataAdapter

DataAdapter will acts as a Bridge between DataSet and database. This dataadapter object is
used to read the data from database and bind that data to dataset. Dataadapter is a
disconnected oriented architecture. Check below sample code to see how to use DataAdapter in
code: 

1. protected void BindGridview() {  
2.     SqlConnection con = new SqlConnection("Data Source=abc;Integrated Security=true
;Initial Catalog=Test");  
3.     conn.Open();  
4.     SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location 
FROM Users", conn);  
5.     SqlDataAdapter sda = new SqlDataAdapter(cmd);  
6.     DataSet ds = new DataSet();  
7.     da.Fill(ds);  
8.     gvUserInfo.DataSource = ds;  
9.     gvUserInfo.DataBind();  
10. }   

 Lets you close the connection as soon it's done loading data, and may even close it for
you automatically
 All of the results are available in memory
 You can iterate over it as many times as you need, or even look up a specific record by
index
 Has some built-in faculties for updating back to the database.

DataTable 

DataTable represents a single table in the database. It has rows and columns. There is no much
difference between dataset and datatable, dataset is simply the collection of datatables. 

1. protected void BindGridview() {  
2.     SqlConnection con = new SqlConnection("Data Source=abc;Integrated Security=true
;Initial Catalog=Test");  
3.     conn.Open();  
4.     SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location 
FROM Users", conn);  
5.     SqlDataAdapter sda = new SqlDataAdapter(cmd);  
6.     DataTable dt = new DataTable();  
7.     da.Fill(dt);  
8.     gridview1.DataSource = dt;  
9.     gvidview1.DataBind();  
10. }   

. DataRelation in ADO.NET..
To provide data integrity and consistency, you should use relationships between two tables. You
achieve this relationship by defining a primary key in one table and using a foreign key in the other
table. Say a customer has multiple orders; the Customers table stores the customer details, and the
Orders table stores all the order details. To avoid the redundancy of data, you define the primary key
of the Customers table as a foreign key in the Orders table.

Note: In general this relationship is called the customer/order relationship parent/child, or sometimes
master/ details. 

In this example, the Customers table is also the parent table, and the Orders table is also the child
table. The ParentRelations property of DataTable represents the parent relationship, and
ChildRelations represents the child relationship. 

CAUTION: The data type of both columns, which you're linking through a relationship in the
customers and the Order Table, must be identical.

You can also access this relationship through a DataSet using its Relations property. To create a
relationship between two columns, you create two DataColumn objects and pass them as
DataRelation arguments.

Listing below shows you how to create a customer/order relationship between the Customers and
Orders table through the Customers table's id column, referenced as CustId in the orders table. The
DataRelation constructor takes three arguments: the name of the relationship, the first DataColumn
and the second DataColumn. After that you call DataTable's ParentRelation.Add method with
DataRelation as an argument. 

Listing: Creating a customer/order relationship using DataRelation 

private void BindData()
        {
            DataRelation dtRelation;
            DataColumn CustCol = dtSet.Tables["Customers"].Columns["id"];
            DataColumn orderCol = dtSet.Tables["Orders"].Columns["CustId"];
 
            dtRelation = new DataRelation("CustOrderRelation", CustCol, orderCol);
            dtSet.Tables["Orders"].ParentRelations.Add(dtRelation);

            dataGrid1.SetDataBinding(dtSet, "Customers");
        }

C# DataGridView

The DataGridView control makes it easy to define the basic


appearance of cells and the display formatting of cell values. The
cell is the fundamental unit of interaction for the DataGridView.
All cells derive from the DataGridViewCell base class. Each cell
within the DataGridView control can have its own style, such as
text format, background color, foreground color, and font.
Typically, however, multiple cells will share particular style
characteristics. The data type for the cell's Value property by
default is of type Object.

The following chapters explain the basics of DataGridView control


and steps through an example that builds simple C# programs.
All the source code in the following examples ,we chose the Pubs
database, which comes with SQL Server , as our target database.
Constructor and Destructors in C#
A constructor can be used, where every time an object gets created and if we want
some code to be executed automatically. The code that we want to execute must be
put in the constructor. The general form of a C# constructor is as follows 

modifier constructor_name (parameters)


{
//constructor body
}

The modifiers can be private,public, protected or internal.The name of a constructor


must be the name of the class, where it is defined. A constructor can take zero or
more arguments. A constructor with zero arguments (that is no-argument) is known
as default constructor. Remember that there is not return type for a constructor. 

The following class contains a constructor, which takes two arguments. 

class Complex
{
private int x;
private int y;
public Complex (int i, int j)
{
x = i;
y = j;
}
public void ShowXY ()
{
Console.WriteLine(x + "i+" + y);
}

The following code segment will display 20+i25 on the command prompt.  

Complex c1 = new Complex (20,25);


c1.ShowXY (); // Displays 20+i25

That is when we create the object of the class Complex, it automatically calls the
constructor and initializes its data members x and y. We can say that constructor is
mainly used for initializing an object. Even it is possible to do very complicated
calculations inside a constructor. The statement inside a constructor can throw
exceptions also. 

If we don't provide a constructor with a class, the C# provides a default constructor


with an empty body to create the objects of the class. Remember that if we provide
our own constructor, C# do not provide the default constructor. 

The complete program is given below


// C# constructor example
// Author: rajeshvs@msn.com
using System;
class Complex
{
private int x;
private int y;
public Complex(int i, int j) // constructor with 2 arguments
{
x = i;
y = j;
}
public void ShowXY()
{
Console.WriteLine(x +"i+" + y);
}
}
class MyClient
{
public static void Main()
{
Complex c1 = new Complex(20,25);
c1.ShowXY();
}

Constructor Overloading  

Just like member functions, constructors can also be overloaded in a class. The
overloaded constructor must differ in their number of arguments and/or type of
arguments and/or order of arguments. 

The following program shows the overloaded constructors in action. 

// C# constructor overloading
// author: rajeshvs@msn.com
using System;
class Complex
{
public Complex(int i, int j) 
{
Console.WriteLine("constructor with 2 integer arguemets");
}
public Complex(double i, double j) 
{
Console.WriteLine("constructor with 2 double arguments");
}
public Complex()
{
Console.WriteLine("no argument constructor"); 
}
}
class MyClient
{
public static void Main()
{
Complex c1 = new Complex(20,25);// displays 'constructor with 2 integer arguments'
Complex c2 = new Complex(2.5,5.9); // displays 'constructor with 2 double arguments'
Complex c3 = new Complex(); displays 'no argument constructor'
}
}

Private Constructors

We already see that, in C#, constructors can be declared as public, private,


protected or internal. When a class declares only private constructors, it is not
possible other classes to derive from this class or create an instance of this class.
Private constructors are commonly used in classes that contain only static members.
However a class can contain both private and public constructor and objects of such
classes can also be created, but not by using the private constructor.

The following is a valid program in C# 

// C# constructor both private & public


// Author: rajeshvs@msn.com
using System;
class Complex
{
private Complex(int i, int j) 
{
Console.WriteLine("constructor with 2 integer arguments");
}
public Complex()
{
Console.WriteLine("no argument constructor"); 
}
}
class MyClient
{
public static void Main()
{
Complex c3 = new Complex();
}
}

However the following program do not compile since it contain only private
constructors 

// C# constructor only private. Will show compilation error.


// Author: rajeshvs@msn.com
using System;
class Complex
{
private Complex()
{
Console.WriteLine("no argument constructor"); 
}
}
class MyClient
{
public static void Main()
{
Complex c3 = new Complex();
}
}
public void Method1()
{
Console.WriteLine("Method of a non-abstract class");
}

Constructor Chaining

The entire above program shows that C# supports constructor overloading. In C#,
even one constructor can invoke another constructor in the same class or in the
base class of this class. This is what is known as constructor chaining.A special type
of syntax is used for constructor chaining as follows. 

// C# constructor chaining 
// Author: rajeshvs@msn.com
using System;
class Complex
{
private Complex()
{
Console.Write("1"); 
}
private Complex(int x):this()
{
Console.Write("2"); 
}
public Complex(int x, int y):this(10)
{
Console.Write("3"); 
}
}
class MyClient
{
public static void Main()
{
Complex c = new Complex(10,20); // Displays 123
}

In the above program the Complex(int x, int y) invokes the Complex(int x)


constructor by using a special syntax ':' this(arguments), which in turn invokes the
Complex() constructor.

Static Constructors 

The normal constructors, which we explained till now, can be used for the
initialization of both static and non-static members. But C# provides a special type
of constructor known as static constructor to initialize the static data members when
the class is loaded at first. Remember that, just like any other static member
functions, static constructors can't access non-static data members directly. 

The name of a static constructor must be the name of the class and even they don't
have any return type. The keyword static is used to differentiate the static
constructor from the normal constructors. The static constructor can't take any
arguments. That means there is only one form of static constructor, without any
arguments. In other way it is not possible to overload a static constructor.

We can't use any access modifiers along with a static constructor. 

For example

// C# static constructor
// Author: rajeshvs@msn.com
using System;
class Complex
{
static Complex()
{
Console.WriteLine("static constructor");
}
}
class MyClient
{
public static void Main()
{
Complex c;
Console.WriteLine("RAJESH");
c = new Complex();
}

The output of the above program is 


RAJESH
static constructor  

Note that static constructor is called when the class is loaded at the first time.
However we can't predict the exact time and order of static constructor execution.
They are called before an instance of the class is created, before a static member is
called and before the static constructor of the derived class is called. 

Like non-static constructors, static constructors can't be chained with each other or
with other non-static constructors. The static constructor of a base class is not
inherited to the derived class. 

Constructors & Inheritance 

Both static and non-static constructors are not inherited to a derived class from a
base class. However, a derived class non-static constructor can call a base class
non-static constructor by using a special function base(). It is possible to invoke
both default and parameterized constructors of the base class from the derived
class. If we don't call the base class constructor explicitly, the derived class
constructor will call the default constructor of the base class implicitly when an
object of the derived class is created. This is shown in the program given below. 

// C# Implicit call of base class default constructor


// Author: rajeshvs@msn.com 
using System; 
class Base
{
public Base()
{
Console.WriteLine("base constructor");
}
}
class Derived : Base
{
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();//Displays 'base constructor'
}

We can also call a base class constructor explicitly by using base() as shown below.  

// C# Implicit call of base class default constructor 


// Author: rajeshvs@msn.com 
using System; 
class Base
{
public Base()
{
Console.WriteLine("BASE 1");
}
public Base(int x)
{
Console.WriteLine("BASE 2");
}
}
class Derived : Base
{
public Derived():base(10)
{
Console.WriteLine("DERIVED CLASS");
}
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();//Displays 'base constructor'
}
}

This program outputs


BASE2
DERIVED CLASS  

The base() can be used for chaining constructors in a inheritance hierarchy.

Destructors 

The .NET framework has an in built mechanism called Garbage Collection to de-
allocate memory occupied by the un-used objects. The destructor implements the
statements to be executed during the garbage collection process. A destructor is a
function with the same name as the name of the class but starting with the
character ~.

Example: 

class Complex
{
public Complex()
{
// constructor
}
~Complex()
{
// Destructor
}
}

Remember that a destructor can't have any modifiers like private, public etc. If we
declare a destructor with a modifier, the compiler will show an error.Also destructor
will come in only one form, without any arguments. There is no parameterized
destructor in C#. 

Destructors are invoked automatically and can't be invoked explicitly. An object


becomes eligible for garbage collection, when it is no longer used by the active part
of the program. Execution of destructor may occur at any time after the instance or
object becomes eligible for destruction. 

In C# all classes are implicitly derived from the super base class object. The object
class contains one special method, Finalize(), which every class can override. The
Garbage Collection mechanism in .NET will call this method prior to the garbage
collection of the objects this class. Remember when we provide a destructor in a
class, during the compilation time, the compiler automatically generates the
Finalize() method. That means that a destructor and overridden Finalize() method
can't co-exist in a class. The following code will generate a compilation error because
of the above program 

class Complex 
{
~Complex()
{
}
protected override void Finaliz()
{
}
}
Abstraction in C#
Abstraction

The word abstract means a concept or an idea not associated with any specific instance.

In programming we apply the same meaning of abstraction by making classes not associated with any
specific instance.

The abstraction is done when we need to only inherit from a certain class, but not need to instantiate
objects of that class. In such case the base
class can be regarded as "Incomplete". Such classes are known as an "Abstract Base Class".

Abstract Base Class

There are some important points about Abstract Base Class :

1. An Abstract Base class can not be instantiated; it means the object of that class can not be
created.

2. Class having abstract keyword and having, abstract keyword with some of its
methods (not all) is known as an Abstract Base Class.

3. Class having Abstract keyword and having abstract keyword with all of its
methods is known as pure Abstract Base Class.

4. The method of abstract class that has no implementation is known as


"operation". It can be defined as abstract void method ();

5. An abstract class holds the methods but the actual implementation of those
methods is made in derived class.

Lets have a look of this code!

    abstract class animal
    {
        public abstract void eat();
        public void sound()
        {
            Console.WriteLine("dog can sound");
        }
    } 
This is the Abstract Base Class, if I make both of its methods abstract then this class
would become a pure Abstract Base Class.

Now we derive a class of 'dog' from the class animal.

    abstract class animal
    {
        public abstract void eat();
        public void sound()
        {
            Console.WriteLine("dog can sound");
        }
    }
    class dog : animal
    {
        public override void eat() { Console.WriteLine("dog can eat"); }
    }

Here you can see we have 2 methods in the Abstract Base Class, the method eat()
has no implementation; that is why it is being declared as 'abstract' while the method
sound() has its own body so it is not declared as 'abstract'.

In the derived class we have the same name method but this method has it's body.

We are doing abstraction here so that we can access the method of derived class
without any trouble.

Let's have a look!

    class program
    {
        abstract class animal
        {
            public abstract void eat();
            public void sound()
            {
                Console.WriteLine("dog can sound");
            }
        }
        class dog : animal
        {
            public override void eat() { Console.WriteLine("dog can eat"); }
        }
        static void Main(string[] args)
        {
            dog mydog = new dog();
            animal thePet = mydog;
            thePet.eat();
            mydog.sound();
        }
    }

Finally we created an Object 'mydog' of class dog, but we didn't instantiate any object of Abstract
Base Class 'animal'.

According to "Ivor Horton" (a programmer of Java) an object can not be instantiated, but we can
declare a variable of the Abstract Class type. If this statement is true then it could be possible:

animal thePet;

This is an object which is declared as thePet and its data type is the abstract base class 'animal'.

We can use this Object to store Objects of the subclass.


In the above code we declare an Object 'thePet', of the type animal (the Abstract Base Class) and
simply copied the object of another object (only the reference is copied as they belong to reference
type). Now we can use object 'thePet' just as object 'mydog'. 

The output of this code would be as 

dog can eat


dog can sound 

C# - Polymorphism

The word polymorphism means having many forms. In object-oriented


programming paradigm, polymorphism is often expressed as 'one
interface, multiple functions'.

Polymorphism can be static or dynamic. In static polymorphism, the


response to a function is determined at the compile time. In dynamic
polymorphism, it is decided at run-time.

Static Polymorphism
The mechanism of linking a function with an object during compile time
is called early binding. It is also called static binding. C# provides two
techniques to implement static polymorphism. They are:

 Function overloading

 Operator overloading

We discuss operator overloading in next chapter.

Function Overloading
You can have multiple definitions for the same function name in the
same scope. The definition of the function must differ from each other by
the types and/or the number of arguments in the argument list. You
cannot overload function declarations that differ only by return type.

The following example shows using function print() to print different


data types:

usingSystem;
namespacePolymorphismApplication
{
classPrintdata
{
voidprint(int i)
{
Console.WriteLine("Printing int: {0}",i );
}

voidprint(double f)
{
Console.WriteLine("Printing float: {0}", f);
}

voidprint(string s)
{
Console.WriteLine("Printing string: {0}", s);
}
staticvoidMain(string[] args)
{
Printdata p =newPrintdata();

// Call print to print integer


p.print(5);

// Call print to print float


p.print(500.263);

// Call print to print string


p.print("Hello C++");
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following
result:
Printing int: 5
Printing float: 500.263
Printing string: Hello C++

Dynamic Polymorphism
C# allows you to create abstract classes that are used to provide partial
class implementation of an interface. Implementation is completed when
a derived class inherits from it. Abstract classes contain abstract
methods, which are implemented by the derived class. The derived
classes have more specialized functionality.

Here are the rules about abstract classes:

 You cannot create an instance of an abstract class


 You cannot declare an abstract method outside an abstract class
 When a class is declared sealed, it cannot be inherited, abstract classes
cannot be declared sealed.

The following program demonstrates an abstract class:

usingSystem;
namespacePolymorphismApplication
{
abstractclassShape
{
publicabstractintarea();
}
classRectangle:Shape
{
privateint length;
privateint width;
publicRectangle(int a=0,int b=0)
{
length = a;
width = b;
}
publicoverrideint area ()
{
Console.WriteLine("Rectangle class area :");
return(width * length);
}
}

classRectangleTester
{
staticvoidMain(string[] args)
{
Rectangle r =newRectangle(10,7);
double a =r.area();
Console.WriteLine("Area: {0}",a);
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following
result:

Rectangle class area :


Area: 70

When you have a function defined in a class that you want to be


implemented in an inherited class(es), you use virtual functions. The
virtual functions could be implemented differently in different inherited
class and the call to these functions will be decided at runtime.

Dynamic polymorphism is implemented by abstract classes and virtual


functions.

The following program demonstrates this:

usingSystem;
namespacePolymorphismApplication
{
classShape
{
protectedint width, height;
publicShape(int a=0,int b=0)
{
width = a;
height = b;
}
publicvirtualintarea()
{
Console.WriteLine("Parent class area :");
return0;
}
}
classRectangle:Shape
{
publicRectangle(int a=0,int b=0):base(a, b)
{

}
publicoverrideint area ()
{
Console.WriteLine("Rectangle class area :");
return(width * height);
}
}
classTriangle:Shape
{
publicTriangle(int a =0,int b =0):base(a, b)
{

}
publicoverrideintarea()
{
Console.WriteLine("Triangle class area :");
return(width * height /2);
}
}
classCaller
{
publicvoidCallArea(Shape sh)
{
int a;
a =sh.area();
Console.WriteLine("Area: {0}", a);
}
}
classTester
{

staticvoidMain(string[] args)
{
Caller c =newCaller();
Rectangle r =newRectangle(10,7);
Triangle t =newTriangle(10,5);
c.CallArea(r);
c.CallArea(t);
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following
result:

Rectangle class area:


Area: 70
Triangle class area:
Area: 25

C# - Interfaces

An interface is defined as a syntactical contract that all the classes


inheriting the interface should follow. The interface defines
the 'what' part of the syntactical contract and the deriving classes define
the 'how' part of the syntactical contract.
Interfaces define properties, methods, and events, which are the
members of the interface. Interfaces contain only the declaration of the
members. It is the responsibility of the deriving class to define the
members. It often helps in providing a standard structure that the
deriving classes would follow.

Abstract classes to some extent serve the same purpose, however, they
are mostly used when only few methods are to be declared by the base
class and the deriving class implements the functionalities.

Declaring Interfaces
Interfaces are declared using the interface keyword. It is similar to class
declaration. Interface statements are public by default. Following is an
example of an interface declaration:

publicinterfaceITransactions
{
// interface members
voidshowTransaction();
doublegetAmount();
}

Example
The following example demonstrates implementation of the above
interface:

usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem;

namespaceInterfaceApplication
{
publicinterfaceITransactions
{
// interface members
voidshowTransaction();
doublegetAmount();
}

publicclassTransaction:ITransactions
{
privatestring tCode;
privatestring date;
privatedouble amount;
publicTransaction()
{
tCode =" ";
date =" ";
amount =0.0;
}

publicTransaction(string c,string d,double a)


{
tCode = c;
date = d;
amount = a;
}

publicdoublegetAmount()
{
return amount;
}

publicvoidshowTransaction()
{
Console.WriteLine("Transaction: {0}", tCode);
Console.WriteLine("Date: {0}", date);
Console.WriteLine("Amount: {0}",getAmount());
}
}
classTester
{
staticvoidMain(string[] args)
{
Transaction t1 =newTransaction("001","8/10/2012",78900.00);
Transaction t2 =newTransaction("002","9/10/2012",451900.00);
t1.showTransaction();
t2.showTransaction();
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following
result:

Transaction: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900

Polymorphism means “Many Forms”. In Polymorphism, poly means “Many” and morph means
“Forms” Polymorphism is one of the main pillar in Object Oriented Programming. You can
create multiple methods with same name but different signature in same class or derived class
for modifying the functionality of base class. It provides different implementation of method that is
implemented with same name.

There are two types of Polymorphism:

1. Method Overloading
2. Method Overriding

In this article, I will explain about method overloading and method overriding concept in C#. I will
try to demonstrate step by step differences between these.

Method Overloading

Method Overloading is a type of polymorphism. It has several names like sometime you say
“Compile Time Polymorphism” or “Static Polymorphism” and sometimes it is called “Early
Binding”. So, all are same with different name.

Method Overloading means creating multiple methods in the class having same name but
different signatures (Parameters). It permits a class, struct, or interface to declare multiple
methods with the same name with unique signatures.

Compiler automatically calls required method to check number of parameters and their type
which are passed into that method.
1. using System;  
2. namespace DemoCsharp  
3. {  
4.     class Program  
5.     {  
6.         public int Add(int num1, int num2)  
7.         {  
8.             return (num1 + num2);  
9.         }  
10.         public int Add(int num1, int num2, int num3)  
11.         {  
12.             return (num1 + num2 + num3);  
13.         }  
14.         public float Add(float num1, float num2)  
15.         {  
16.             return (num1 + num2);  
17.         }  
18.         public string Add(string value1, string value2)  
19.         {  
20.             return (value1 + " " + value2);  
21.         }  
22.         static void Main(string[] args)  
23.         {  
24.             Program objProgram = new Program();  
25.             Console.WriteLine("Add with two int parameter :" + objProgram.Add(3, 2)
);  
26.             Console.WriteLine("Add with three int parameter :" + objProgram.Add(3, 
2, 8));  
27.             Console.WriteLine("Add with two float parameter :" + objProgram.Add(3 f
, 22 f));  
28.             Console.WriteLine("Add with two string parameter :" + objProgram.Add("h
ello", "world"));  
29.             Console.ReadLine();  
30.         }  
31.     }  
32. }  

In the above example, you can see that there are four methods with same name but type of
parameter or number of parameter is different.
When you call Add(4,5), complier automatically call the method which has two integer
parameters and when you call Add(“hello”,”world”), complier call the method which has two
string parameters. So basically in method overloading complier check which method should be
called at the time of compilation.

Note: Changing the return type of method does not make the method overloaded. You cannot
create method overloaded vary only by return type.

Method Overriding

Method Overriding is a type of polymorphism. It has several names like sometime you say “Run
Time Polymorphism” or “Dynamic Polymorphism” and sometime it is called “Late Binding”.
So, all are same with different name.

Method Overriding means having two methods with same name and same signature
[parameters], one should be in base class and other method should be in derived class [child
class]. You can override the functionality of base class to create a same name method with same
signature in derived class. You can achieve method overriding using inheritance. Virtual and
Override keywords are used to achieve method overriding.

1. using System;  
2. namespace DemoCsharp  
3. {  
4.     class BaseClass  
5.     {  
6.         public virtual int Add(int num1, int num2)  
7.         {  
8.             return (num1 + num2);  
9.         }  
10.     }  
11.     class ChildClass: BaseClass  
12.     {  
13.         public override int Add(int num1, int num2)  
14.         {  
15.             if (num1 <= 0 || num2 <= 0)  
16.             {  
17.                 Console.WriteLine("Values could not be less than zero or equals to 
zero");  
18.                 Console.WriteLine("Enter First value : ");  
19.                 num1 = Convert.ToInt32(Console.ReadLine());  
20.                 Console.WriteLine("Enter First value : ");  
21.                 num2 = Convert.ToInt32(Console.ReadLine());  
22.             }  
23.             return (num1 + num2);  
24.         }  
25.     }  
26.     class Program  
27.     {  
28.         static void Main(string[] args)  
29.         {  
30.             BaseClass baseClassObj;  
31.             baseClassObj = new BaseClass();  
32.             Console.WriteLine("Base class method Add :" + baseClassObj.Add(-3, 8)); 
 
33.             baseClassObj = new ChildClass();  
34.             Console.WriteLine("Child class method Add :" + baseClassObj.Add(-2, 2))
;  
35.             Console.ReadLine();  
36.         }  
37.     }  
38. }  

In the above example, I have created two same name methods in BaseClass as well as
ChildClass. When you call the BaseClass Add method with less than zero value as parameter
then it adds successfully. But when you call ChildClass Add method with less than zero value
then it checks for negative value. And the passing values are negative then it asks for new value.

So, here it is clear that we can modify the base class method in derived or child class as per our
requirement.

Points to be remembered  

1. Method cannot be private.


2. Only abstract or virtual method can be overridden.
3. Which method should be called, it decides on run time.

Anatomy of ASP.NET Page


..\..\Downloads\IS360PageAnatomy.ppt

Validation Controls in ASP.NET


Why we use validation controls?

Validation is important part of any web application. User's input must always be validated before
sending across different layers of the application.

Validation controls are used to:

 Implement presentation logic.


 To validate user input data.
 Data format, data type and data range is used for validation.

Validation is of two types:

1. Client Side
2. Serve Side

Client side validation is good but we have to be dependent on browser and scripting language
support.

Client side validation is considered convenient for users as they get instant feedback. The main
advantage is that it prevents a page from being postback to the server until the client validation is
executed successfully.

For developer point of view serve side is preferable because it will not fail, it is not dependent on
browser and scripting language.

You can use ASP.NET validation, which will ensure client, and server validation. It work on both end;
first it will work on client validation and than on server validation. At any cost server validation will
work always whether client validation is executed or not. So you have a safety of validation check.

For client script .NET used JavaScript. WebUIValidation.js file is used for client validation by .NET

Validation Controls in ASP.NET

An important aspect of creating ASP.NET Web pages for user input is to be able to check that the
information users enter is valid. ASP.NET provides a set of validation controls that provide an easy-to-
use but powerful way to check for errors and, if necessary, display messages to the user.

There are six types of validation controls in ASP.NET

1. RequiredFieldValidation Control
2. CompareValidator Control
3. RangeValidator Control
4. RegularExpressionValidator Control
5. CustomValidator Control
6. ValidationSummary
The below table describes the controls and their work:

Validation Control Description

RequiredFieldValidation Makes an input control a required field

CompareValidator Compares the value of one input control to the value


of another input control or to a fixed value

RangeValidator Checks that the user enters a value that falls between
two values

RegularExpressionValidator Ensures that the value of an input control matches a


specified pattern

CustomValidator Allows you to write a method to handle the validation


of the value entered

ValidationSummary Displays a report of all validation errors occurred in a


Web page

All validation controls are rendered in form as <span> (label are referred as <span> on client by
server)

Important points for validation controls

 ControlToValidate property is mandatory to all validate controls.


 One validation control will validate only one input control but multiple validate control can be
assigned to a input control.

Validation Properties 
Usually, Validation is invoked in response to user actions like clicking submit button or entering data.
Suppose, you wish to perform validation on page when user clicks submit button. 

Server validation will only performed when CauseValidation is set to true.

When the value of the CausesValidation property is set to true, you can also use the ValidationGroup
property to specify the name of the validation group for which the Button control causes validation.

Page has a Validate() method. If it is true this methods is executed. Validate() executes each
validation control.

To make this happen, simply set the CauseValidation property to true for submit button as shown
below:

<asp:Button ID="Button2" runat="server" Text="Submit" CausesValidation=true />


Lets understand validation controls one by one with practical demonstration:

RequiredFieldValidation Control

The RequiredFieldValidator control is simple validation control, which checks to see if the data is
entered for the input control. You can have a RequiredFieldValidator control for each form element on
which you wish to enforce Mandatory Field rule.

<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" Style="top: 98px;
        left: 367px; position: absolute; height: 26px; width: 162px" ErrorMessage="password required"
        ControlToValidate="TextBox2"></asp:RequiredFieldValidator>

CompareValidator Control

The CompareValidator control allows you to make comparison to compare data entered in an input
control with a constant value or a value in a different control.

It can most commonly be used when you need to confirm password entered by the user at the
registration time. The data is always case sensitive. 

<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" Style="top: 145px;
        left: 367px; position: absolute; height: 26px; width: 162px" ErrorMessage="password required"
        ControlToValidate="TextBox3"></asp:RequiredFieldValidator>

RangeValidator Control

The RangeValidator Server Control is another validator control, which checks to see if a control value
is within a valid range. The attributes that are necessary to this control are: MaximumValue,
MinimumValue, and Type.

<asp:RangeValidator ID="RangeValidator1" runat="server" Style="top: 194px; left: 365px;
            position: absolute; height: 22px; width: 105px" 
        ErrorMessage="RangeValidator" ControlToValidate="TextBox4" MaximumValue="100" 
        MinimumValue="18" Type="Integer"></asp:RangeValidator>

RegularExpressionValidator Control

A regular expression is a powerful pattern matching language that can be used to identify simple and
complex characters sequence that would otherwise require writing code to perform.

Using RegularExpressionValidator server control, you can check a user's input based on a pattern
that you define using a regular expression. 

It is used to validate complex expressions. These expressions can be phone number, email address,
zip code and many more. Using Regular Expression Validator is very simple. Simply set the
ValidationExpression property to any type of expression you want and it will validate it. 

If you don't find your desired regular expression, you can create your custom one.

In the example I have checked the email id format:

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" Style="top: 234p
x;
        left: 366px; position: absolute; height: 22px; width: 177px" 
        ErrorMessage="RegularExpressionValidator" ControlToValidate="TextBox5" 
        ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+
([-.]\w+)*"></asp:RegularExpressionValidator>
CustomValidator Control

You can solve your purpose with ASP.NET validation control. But if you still don't find solution you can
create your own custom validator control.

The CustomValidator Control can be used on client side and server side. JavaScript is used to do
client validation and you can use any .NET language to do server side validation.

I will explain you CustomValidator using server side. You should rely more on server side validation. 

To write CustomValidator on server side you override ServerValidate event.

ValidationSummary

ASP.NET has provided an additional control that complements the validator controls.

The ValidationSummary control is reporting control, which is used by the other validation controls on a
page. 

You can use this validation control to consolidate errors reporting for all the validation errors that
occur on a page instead of leaving this up to each and every individual validation control.

The validation summary control will collect all the error messages of all the non-valid controls and put
them in a tidy list. 

<asp:ValidationSummary ID="ValidationSummary1" runat="server" 
        style="top: 390px; left: 44px; position: absolute; height: 38px; width: 625px" />

Both ErrorMessage and Text properties are used to display error messages. Text error message have
precedence.

If you are using ValidationSummary than only ErrorMessage and Text property is used.
State Management in ASP.Net

Types of state management  

There are two types of state management techniques: client side and server side.

Client side
1. Hidden Field
2. View State
3. Cookies
4. Control State
5. Query Strings
Server side
1. Session
2. Application

Levels of state management 

1. Control level: In ASP.NET, by default controls provide state management automatically.


2. Variable or object level: In ASP.NET, member variables at page level are stateless and thus
we need to maintain state explicitly.
3. Single or multiple page level: State management at single as well as multiple page level
i.e., managing state between page requests.
4. User level: State should be preserved as long as a user is running the application.
5. Application level: State available for complete application irrespective of the user, i.e.,
should be available to all users.
6. Application to application level: State management between or among two or more
applications.
Client side methods
1. Hidden field

Hidden field is a control provided by ASP.NET which is used to store small amounts of data on
the client. It store one value for the variable and it is a preferable way when a variable's value is
changed frequently. Hidden field control is not rendered to the client (browser) and it is invisible
on the browser. A hidden field travels with every request like a standard control’s value.

Let us see with a simple example how to use a hidden field. These examples increase a value by 1
on every "No Action Button" click. The source of the hidden field control is. 

Hide   Copy Code

<asp:HiddenField ID="HiddenField1" runat="server"/>

In the code-behind page:

Hide   Copy Code

protectedvoid Page_Load(object sender, EventArgs e)


{
if (HiddenField1.Value != null)
{
int val= Convert.ToInt32(HiddenField1.Value) + 1;
HiddenField1.Value = val.ToString();
Label1.Text = val.ToString();
}
}
protectedvoid Button1_Click(object sender, EventArgs e)
{
//this is No Action Button Click
}

2. View state

View state is another client side state management mechanism provided by ASP.NET to store
user's data, i.e., sometimes the user needs to preserve data temporarily after a post back, then
the view state is the preferred way for doing it. It stores data in the generated HTML using
hidden field not on the server. 

View State provides page level state management i.e., as long as the user is on the current page,
state is available and the user redirects to the next page and the current page state is lost. View
State can store any type of data because it is object type but it is preferable not to store a
complex type of data due to the need for serialization and deserilization on each post back. View
state is enabled by default for all server side controls of ASP.NET with a
property EnableviewState set to true.

Let us see how ViewState is used with the help of the following example. In the example we try to
save the number of postbacks on button click.
Hide   Copy Code

protectedvoid Page_Load(object sender, EventArgs e)


{
if (IsPostBack)
{
if (ViewState["count"] != null)
{
int ViewstateVal = Convert.ToInt32(ViewState["count"]) + 1;
Label1.Text = ViewstateVal.ToString();
ViewState["count"]=ViewstateVal.ToString();
}
else
{
ViewState["count"] = "1";
}
}
}
protectedvoid Button1_Click(object sender, EventArgs e)
{
Label1.Text=ViewState["count"].ToString();
}

3. Cookies

Cookie is a small text file which is created by the client's browser and also stored on the client
hard disk by the browser. It does not use server memory. Generally a cookie is used to identify
users.

A cookie is a small file that stores user information. Whenever a user makes a request for a page
the first time, the server creates a cookie and sends it to the client along with the requested page
and the client browser receives that cookie and stores it on the client machine either permanently
or temporarily (persistent or non persistence). The next time the user makes a request for the
same site, either the same or another page, the browser checks the existence of the cookie for
that site in the folder. If the cookie exists it sends a request with the same cookie, else that
request is treated as a new request. 

Types of  Cookies


1. Persistence Cookie: Cookies which you can set an expiry date time are called persistence
cookies. Persistence cookies are permanently stored till the time you set.

Let us see how to create persistence cookies. There are two ways, the first one is:   

Hide   Copy Code

Response.Cookies["nameWithPCookies"].Value = "This is A Persistance Cookie";


Response.Cookies["nameWithPCookies"].Expires = DateTime.Now.AddSeconds(10);

And the second one is:  

Hide   Copy Code

HttpCookie aCookieValPer = new HttpCookie("Persistance");


aCookieValPer.Value = "This is A Persistance Cookie";
aCookieValPer.Expires = DateTime.Now.AddSeconds(10);
Response.Cookies.Add(aCookieValPer);

2. Non-Persistence Cookie: Non persistence cookies are not permanently stored on the user
client hard disk folder. It maintains user information as long as the user accesses the same
browser. When user closes the browser the cookie will be discarded. Non Persistence cookies are
useful for public computers.

Let us see how to create a non persistence cookies. There are two ways, the first one is:

Hide   Copy Code

Response.Cookies["nameWithNPCookies"].Value = "This is A Non Persistance Cookie";

And the second way is:

Hide   Copy Code

HttpCookie aCookieValNonPer = new HttpCookie("NonPersistance");


aCookieValNonPer.Value = "This is A Non Persistance Cookie;
Response.Cookies.Add(aCookieValNonPer);how to create cookie :

How to read a cookie:

Hide   Copy Code

if (Request.Cookies["NonPersistance"] != null)
Label2.Text = Request.Cookies["NonPersistance"].Value;

Let's understand persistence and non persistence cookies more clearly with a diagram:

Limitation of cookies: The number of cookies allowed is limited and varies according to the
browser. Most browsers allow 20 cookies per server in a client's hard disk folder and the size of a
cookie is not more than 4096 bytes or 4 KB of data that also includes name and value data. 

4. Control State

Control State is another client side state management technique. Whenever we develop a custom
control and want to preserve some information, we can use view state but suppose view state is
disabled explicitly by the user, the control will not work as expected. For expected results for the
control we have to use Control State property. Control state is separate from view state.
How to use control state property: Control state implementation is simple. First override
the OnInit()method of the control and add a call for
the Page.RegisterRequiresControlState()  method with the instance of the control to
register. Then override LoadControlState and SaveControlState in order to save the
required state information.

Server side
1. Session   

Session management is a very strong technique to maintain state. Generally session is used to
store user's information and/or uniquely identify a user (or say browser). The server maintains the
state of user information by using a session ID. When users makes a request without a session ID,
ASP.NET creates a session ID and sends it with every request and response to the same user.

How to get and set value in Session:

Hide   Copy Code

Session["Count"] = Convert.ToInt32(Session["Count"]) + 1;//Set Value to The Session


Label2.Text = Session["Count"].ToString(); //Get Value from the Sesion

Let us see an example where we save the count of button clicks in a session, and save the
“number of redirects to the same page” button click in a query string. Here I have set the expiry
to 10 minutes. After starting the application, the application variable exists till the end of the
application. A session variable will expire after 10 minutes (if it is idle). A query string contains the
value in URL so it won’t depend on the user idle time and could be used by the server anytime it
is passed with a request.  

Session Events in ASP.NET   


To manage a session, ASP.NET provides two events: session_start and session_end that is
written in a special file called Global.asax in the root directory of the project. 
Session_Start: The Session_start event is raised every time a new user makes a request
without a session ID, i.e., new browser accesses the application, then a session_start event
raised. Let's see the Global.asax file.  
Hide   Copy Code

void Session_Start(object sender, EventArgs e)


{
Session["Count"] = 0; // Code that runs when a new session is started
}
Session_End: The Session_End event is raised when session ends either because of a time out
expiry or explicitly by using Session.Abandon(). The Session_End event is raised only in the
case of In proc mode not in the state server and SQL Server modes. 

There are four session storage mechanisms provided by ASP.NET:

 In Proc mode 
 State Server mode   
 SQL Server mode 
 Custom  mode  
In Process mode: In proc mode is the default mode provided by ASP.NET. In this mode, session
values are stored in the web server's memory (in IIS). If there are more than one IIS servers then
session values are stored in each server separately on which request has been made. Since the
session values are stored in server, whenever server is restarted the session values will be lost. 
Hide   Copy Code

<configuration>
<sessionstate mode="InProc" cookieless="false" timeout="10"

stateConnectionString="tcpip=127.0.0.1:80808"

sqlConnectionString="Data Source=.\SqlDataSource;User ID=userid;Password=password"/>


</configuration>

In State Server mode: This mode could store session in the web server but out of the application
pool. But usually if this mode is used there will be a separate server for storing sessions,
i.e., stateServer. The benefit is that when IIS restarts the session is available. It stores session in
a separate Windows service. For State server session mode, we have to configure it explicitly in
the web config file and start the aspnet_state service.
Hide   Copy Code

<configuration><sessionstate mode="stateserver" cookieless="false"

timeout="10" stateConnectionString="tcpip=127.0.0.1:42424"

sqlConnectionString="Data Source=.\SqlDataSource;User
ID=userid;Password=password"/></configuration>

In SQL Server mode: Session is stored in a SQL Server database. This kind of session mode is
also separate from IIS, i.e., session is available even after restarting the IIS server. This mode is
highly secure and reliable but also has a disadvantage that there is overhead from serialization
and deserialization of session data. This mode should be used when reliability is more important
than performance. 
Hide   Copy Code

<configuration>
<sessionstate mode="sqlserver" cookieless="false" timeout="10"

stateConnectionString="tcpip=127.0.0.1:4 2424"

sqlConnectionString="Data Source=.\SqlDataSource;User ID=userid;Password=password"/>


</configuration>

Custom Session mode: Generally we should prefer in proc state server mode or SQL Server
mode but if you need to store session data using other than these techniques then ASP.NET
provides a custom session mode. This way we have to maintain everything customized even
generating session ID, data store, and also security. 
Attributes   Description 

Indicates that the session is used with or without


cookie. cookieless set to true indicates sessions without cookies is
Cookieless true/false  
used and cookieless set to false indicates sessions with cookies is
used. cookieless set to false is the default set. 

timeout  Indicates the session will abound if it is idle before session is


abounded explicitly (the default time is 20 min).

StateConnectionStrin Indicates the session state is stored on the remote computer (server).
g This attribute is required when session mode is StateServer

SqlConnectionString Indicates the session state is stored in the database. This attribute is
required when session mode is SqlServer. 

2. Application

Application state is a server side state management technique. The date stored in application
state is common for all users of that particular ASP.NET application and can be accessed
anywhere in the application. It is also called application level state management. Data stored in
the application should be of small size.  

How to get and set a value in the application object:


Hide   Copy Code

Application["Count"] = Convert.ToInt32(Application["Count"]) + 1; //Set Value to The


Application Object
Label1.Text = Application["Count"].ToString(); //Get Value from the Application Object

Application events in ASP.NET


There are three types of events in ASP.NET. Application event is written in a special file
called Global.asax. This file is not created by default, it is created explicitly by the developer in the
root directory. An application can create more than one Global.asax file but only the root one is
read by ASP.NET.
Application_start: The Application_Start event is raised when an app domain starts.
When the first request is raised to an application then the Application_Start event is raised.
Let's see the Global.asax file. 
Hide   Copy Code

void Application_Start(object sender, EventArgs e)


{
Application["Count"] = 0;
}

Application_Error: It is raised when an unhandled exception occurs, and we can manage the
exception in this event.
Application_End: The Application_End event is raised just before an application domain
ends because of any reason, may IIS server restarting or making some changes in an application
cycle.  
So we have talked about various types of state management techniques in this article. I have tried
to touch several topics in this article but the main intention for this article was to get the
user familiar with the various state management techniques that exist in ASP.NET. The details for
all these techniques will make a complete article by itself which I will try to post in future. 

Caching

Caching is one of the most interesting concepts and operations in ASP.NET. If you can handle it,
you can run any web application by applying the caching concept depending on the
requirements.

Currrently a majority of websites/portals (or I can say simply web pages) are dynamic (if I do talk
about a dynamic website, then it doesn't mean all the pages of that website is dynamic or will be.
The probability of happening this is dependent on the user's perspective and the requirements).

In veru common words I can define dynamic pages as including the following:

- Pages that directly interact with people


- Communication (on page)
- Any media content
- Any type of graphic interaction

So, generally these types of pages or webs are called dynamic. Now let's find why we really
need caching.

Why Caching

Caching is for providing solutions or the results to the users depending on their requested
request, admin needs to recreate the pages often depending on user requests…STOP!!!

The process

The process is quite bulky and time-consuming. So to overcoming that problem some websites
have a page creation engine that automatically creates all the pages in one action and directly
saves those pages as a HTML structured page. These HTML pages serve the user depending
on their requirements.

Multiple sorts of pages

But, do you still think this will be enough? If your answer is yes, then please think some more!

Actually, the preceding solution will only work if and only if the requested pages are of the same
type. Now think, what will happen if the users request a different sort of page?

In that case your web will be stuck again.

So for dealing with that kind of complex but necessary requirements, ASP.NET provides support
for caching. Caching is the hero/heroine in this context that will help us to a great extent. 

What a Cache does

What a cache does, in the most simple words I can say is:
"A cache simply stores the output generated by a page in the memory and this saved output
(cache) will serve us (users) in the future." That's it.

Types

Page Caching

Let's explore the caching of an entire page, first.

To cache an entire page's output we need to specify a directive at the top of our page, this
directive is the @ OutputCache.

Let's figure out a simple demo of it. 

1. <%@ OutputCache Duration = 5 VaryByParam = "ID" %>  

Here, in that statement Duration and VarByParam are the two attributes of


the OutputCachedirective. Now let's explore how they work. 

 Duration Attribute

This attributes represents the time in seconds of how long the output cache should be
stored in memory. After the defined duration the content stored in the memory will be
cleared automatically.

 VarByParam Attribute

This is the most important attributes; you can't afford to miss that in the OutputCache
directory statement. It generally defines the query string parameters to vary the cache (in
memory).

You can also multiple parameter names too, but for that you need to separate them using a
semicolon (;).

You can also specify it as "*". In this case the cached content is varied for all the parameters ed
using the querysrting.

For example:
1. <%@ OutputCache Duration = 5 VaryByParam = "*"%>  

In case of caching a page, some pages can generate different content for different browsers. In
that scenario we need to add an additional attribute to our statement for overcoming the
preceding problem.

For example:

1. <%@ OutputCache Duration = 5 VaryByParam = "ID" VaryByCustom = "Browser" %>  

Or:

1. <%@ OutputCache Duration = 5 VaryByParam = "*" VaryByCustom = "Browser" %>  

Fragment caching 

In some scenarios we only need to cache only a segment of a page. For example a contact us
page in a main page will be the same for all the users and for that there is no need to cache the
entire page.
 
So for that we prefer to use fragment caching option. 

For example:

1. <%@ OutputCache Duration = 10 VaryByParam = "None" %>  

Or:

1. <%@ OutputCache Duration = 5 VaryByParam = "None" VaryByCustom = "Browser" %>  

Data Caching

Data caching is slightly different from the 2 other caching types. It's much more interesting to see
how data caching actually works.

As we know in C# everything is about classes and objects. So ASP.NET supports data caching
by treating them as small sets of objects. We can store objects in memory very easily and use
them depending on our functionality and needs, anywhere across the page. 

Now you must be thinking where is the class in that entire scenario?

Actually, this feature is implemented using the Cache class and data is treated as its object. Let's
see how it works using a demo.

I am inserting a string value in the cache as:

1. Cache["Website"] = "CSharpCorner";  

Now, for inserting the cache into the objects, the insert method of the Cache class can be used.
This insert method is used as follows:

1. Cache.Insert("Website", strName,  
2. new CacheDependency(Sever.MapPath("Website.txt"));  
What we are missing something

We missed the Time for the cache (don't forget to use it), let's provide it:

1. Cache.Insert("Website", strName,  
2. new CacheDependency(Sever.MapPath("Website.txt")  

DateTime.Now.Addminutes(5), TimeSpan.Zero);  Authentication in ASP.NET

There are two closely interlinked concepts at the heart of security for distributed
applications - authentication and authorization. Authentication is the process of
obtaining some sort of credentials from the users and using those credentials to
verify the user's identity. Authorization is the process of allowing an authenticated
user access to resources. Authentication is always precedes to Authorization; even if
your application lets anonymous users connect and use the application, it still
authenticates them as being anonymous. 
ASP.net provides flexible set of alternatives for authentication. You can perform
authentication yourself in code or delegate authentication to other authorities (such
as Microsoft Passport). In fact sometimes it seems ASP.net authentication is a bit
too flexible; it can be difficult for a new developer to know just where to start. In
this article, we review the settings in ASP.net and Internet Information Services
(IIS) that control authentication and authorization in ASP.net applications.

An ASP.net application has two separate authentication layers. That is because


ASP.net is not a standalone product. Rather it is a layer on top of IIS. All requests
flow through IIS before they are handed to ASP.net. As a result, IIS can decide to
deny access without the ASP.net process even knowing that someone requested a
particular page. Here is an overview of the steps in the joint IIS and ASP.net
authentication process.

1. IIS first checks to make sure the incoming request comes from an IP address
that is allowed access to the domain. If not it denies the request.
2. Next IIS performs its own user authentication if it configured to do so. By
default IIS allows anonymous access, so requests are automatically
authenticated, but you can change this default on a per - application basis
with in IIS.
3. If the request is passed to ASP.net with an authenticated user, ASP.net
checks to see whether impersonation is enabled. If impersonation is enabled,
ASP.net acts as though it were the authenticated user. If not ASP.net acts
with its own configured account.
4. Finally the identity from step 3 is used to request resources from the
operating system. If ASP.net authentication can obtain all the necessary
resources it grants the users request otherwise it is denied. Resources can
include much more than just the ASP.net page itself you can also use .Net's
code access security features to extend this authorization step to disk files,
Registry keys and other resources.

As you can see several security authorities interact when the user requests and
ASP.net page. If things are not behaving the way you think they should, it can be
helpful to review this list and make sure you have considered all the factors involved

Authentication providers

Assuming IIS passes a request to ASP.net, what happens next? The answer depends
on the configuration of ASP.net itself. The ASP.net architecture includes the concept
of and authentication provider a piece of code whose job is to verify credentials and
decide whether a particular request should be considered authenticated. Out of the
box ASP.net gives you a choice of three different authentication providers.

 The windows Authentication provider lets you authenticates users based on


their windows accounts. This provider uses IIS to perform the authentication
and then passes the authenticated identity to your code. This is the default
provided for ASP.net.
 The passport authentication provider uses Microsoft's passport service to
authenticate users.
 The forms authentication provider uses custom HTML forms to collect
authentication information and lets you use your own logic to authenticate
users. The user's credentials are stored in a cookie for use during the session.

Selecting an authentication provider is as simple as making an entry in the


web.config file for the application. You can use one of these entries to select the
corresponding built in authentication provider:

<authentication mode="windows">
authentication mode="passport">
<authentication mode="forms">

ASP.net also supports custom authentication providers. This simply means that you
set the authentication mode for the application to none, then write your own custom
code to perform authentication. For example, you might install an ISAPI filter in IIS
that compares incoming requests to list of source IP addresses, and considers
requests to be authenticated if they come from an acceptable address. In that case,
you would set the authentication mode to none to prevent any of the .net
authentication providers from being triggered.

The fig below illustrates the authorization and authentication mechanisms provided
by ASP.NET and IIS.
Windows authentication and IIS

If you select windows authentication for your ASP.NET application, you also have to
configure authentication within IIS. This is because IIS provides Windows
authentication. IIS gives you a choice for four different authentication methods:

Anonymous, basic digest, and windows integrated

If you select anonymous authentication, IIS doesn't perform any authentication, Any
one is allowed to access the ASP.NET application.

If you select basic authentication, users must provide a windows username and
password to connect. How ever this information is sent over the network in clear
text, which makes basic authentication very much insecure over the internet.

If you select digest authentication, users must still provide a windows user name
and password to connect. However the password is hashed before it is sent across
the network. Digest authentication requires that all users be running Internet
Explorer 5 or later and that windows accounts to stored in active directory.

If you select windows integrated authentication, passwords never cross the network.
Users must still have a username and password, but the application uses either the
Kerberos or challenge/response protocols authenticate the user. Windows-integrated
authentication requires that all users be running internet explorer 3.01 or later
Kerberos is a network authentication protocol. It is designed to provide strong
authentication for client/server applications by using secret-key cryptography.
Kerberos is a solution to network security problems. It provides the tools of
authentication and strong cryptography over the network to help to secure
information in systems across entire enterprise

Passport authentication
Passport authentication lets you to use Microsoft's passport service to authenticate
users of your application. If your users have signed up with passport, and you
configure the authentication mode of the application to the passport authentication,
all authentication duties are offloaded to the passport servers.

Passport uses an encrypted cookie mechanism to indicate authenticated users. If


users have already signed into passport when they visit your site, they'll be
considered authenticated by ASP.NET. Otherwise they'll be redirected to the
passport servers to log in. When they are successfully log in, they'll be redirected
back to your site

To use passport authentication you have to download the Passport Software


Development Kit (SDK) and install it on your server. The SDK can be found at
http://msdn.microdoft.com/library/default.asp?url=/downloads/list/websrvpass.aps.
It includes full details of implementing passport authentication in your own
applications.

Forms authentication

Forms authentication provides you with a way to handle authentication using your
own custom logic with in an ASP.NET application. The following applies if you choose
forms authentication.

1. When a user requests a page for the application, ASP.NET checks for the
presence of a special session cookie. If the cookie is present, ASP.NET assumes
the user is authenticated and processes the request.
2. If the cookie isn't present, ASP.NET redirects the user to a web form you provide
3. You can carry out whatever authentication, checks you like in your form. When
the user is authenticated, you indicate this to ASP.NET by setting a property,
which creates the special cookie to handle subsequent requests.

Configuring Authorization

After your application has authenticated users, you can proceed to authorize their
access to resources. But there is a question to answer first: Just who is the user to
whom your are grating access? It turns out that there are different answers to that
question, depending on whether you implement impersonation. Impersonation is a
technique that allows the ASP.NET process to act as the authenticated user, or as an
arbitrary specified user

ASP.NET impersonation is controlled by entries in the applications web.config file.


The default setting is "no impersonation". You can explicitly specify that ASP.NET
shouldn't use impersonation by including the following code in the file

<identity impersonate="false"/>

With this setting ASP.NET does not perform impersonation. It means that ASP.NET
will runs with its own privileges. By default ASP.NET runs as an unprivileged account
named ASPNET. You can change this by making a setting in the processModel
section of the machine.config file. When you make this setting, it automatically
applies to every site on the server. To user a high-privileged system account instead
of a low-privileged, set the userName attribute of the processModel element to
SYSTEM. Using this setting is a definite security risk, as it elevates the privileges of
the ASP.NET process to a point where it can do bad things to the operating system.
When you disable impersonation, all the request will run in the context of the
account running ASP.NET: either the ASPNET account or the system account. This is
true when you are using anonymous access or authenticating users in some fashion.
After the user has been authenticated, ASP.NET uses it own identity to request
access to resources.

The second possible setting is to turn on impersonation.

<identity impersonate="true"/>

In this case, ASP.NET takes on the identity IIS passes to it. If you are allowing
anonymous access in IIS, this means ASP.NET will impersonate the
IUSR_ComputerName account that IIS itself uses. If you aren't allowing anonymous
access,ASP.NET will take on the credentials of the authenticated user and make
requests for resources as if it were that user. Thus by turning impersonation on and
using a non-anonymous method of authentication in IIS, you can let users log on
and use their identities within your ASP.NET application.

Finally, you can specify a particular identity to use for all authenticated requests

<identity impersonate="true" username="DOMAIN\username" password="password"/>

With this setting, all the requests are made as the specified user (Assuming the
password it correct in the configuration file). So, for example you could designate a
user for a single application, and use that user's identity every time someone
authenticates to the application. The drawback to this technique is that you must
embed the user's password in the web.config file in plain text. Although ASP.NET
won't allow anyone to download this file, this is still a security risk if anyone can get
the file by other means.

3.

Introduction to Web Service with


Example in ASP.NET

Background

In this article we will learn about web service using the scenario when Our applications often
require code to determine the number of days, such as how long the customer is associated with
us, also to convert from a date of present days into days or years and so on.

In a normal application I need to write the Business logic repeatedly for the same requirements
so due to the requirements you can write a single web service for Multiple applications that allow
an access method on any platform used, so let us start with the basics.

Per-requirement to Understand this application

If you are a beginner and you need to understand what a web service is then you can read the
article of the author Vidya Vrat Agarwal sir; the article is .NET Web Services.

I hope you read it if you are unfamiliar with web services.


What is web services ?

A "web service is the communication platform between two different or same platform
applications that allows to use their web method."

In the preceding definition you observed that I used the two main points in the definition of web
service; they are different or same platform application and the second is web method.

so let us learn some basic about it .

What does different or same application and platform mean

It means that I can create a web service in any language, such as Java or other languages and
that the language web service can be used in a .Net based application and also a .Net web
service or in another application to exchange the information. 

What does web method mean

The method in web services always start with [webMethod] attributes, it means that it is a web
method that is accessible anywhere, the same as my web application.

to understand more clear let us ,I represent all above given definitions explanation in
following diagram

In the above diagram,I have shown,how the Asp.net Web Service is used in different types of
applications means i am trying to explain that I can create a web service in any language, such
as Java or other languages and that the language web service can be used in a .Net based
application as wel as java or other applications and you can also use .Net based web application
in Java applications means web Services dont have a any platform restrictions.

I hope you understand the basics of a web service.

So let us start to create the web service.

Note

If you closely observe that ,there is no separate web service template in .Framework 2010 as you
see in 2008 while adding a project or web site it might be because of WCF.

So let us start using a different way to add a web service using a template

1. "Start" - "All Programs" - "Microsoft Visual Studio 2010"


2. "File" - "New Project" - "C#" - "Empty Web Application" (to avoid adding a master page)
3. Provide the web site a name such as "agetodays" or another as you wish and specify the
location
4. Then right-click on Solution Explorer - "Add New Item" - you see the web service
templates

Select Web Service Template and click on add button. then after that the Solution Explorer look
like as follows.
Then open the Webservice.cs class and write the following method followed by [webMethod]
attribute as in.

1. [WebMethod]  
2. public int converttodaysweb(int day, int month, int year) {  
3.     DateTime dt = new DateTime(year, month, day);  
4.     int datetodays = DateTime.Now.Subtract(dt).Days;  
5.     return datetodays;  
6. }  

In the code above I have declared a one integer method named converttodaysweb with the three
parameters day, month and year for accepting day, month and year from the user.

Then after that I created an object of date time and ed the those variables that I get from the
users. I declared another variable in the method that is age today to store the number of days
remaining from the user's input date to the current date and finally I return that variable..

The webservice.cs file will then look as in the following

1. using System;  
2. using System.Collections.Generic;  
3. using System.Web;  
4. using System.Web.Services;  
5. ///<summary>  
6. /// Summary description for UtilityWebService  
7. ///</summary>  
8. [WebService(Namespace = "http://tempuri.org/")]  
9. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
10. // To allow this Web Service to be called from script, using ASP.NET AJAX, uncommen
t the following line.   
11. // [System.Web.Script.Services.ScriptService]  
12. public class WebService: System.Web.Services.WebService   
13. {  
14.     public WebService()   
15.     {  
16.         //Uncomment the following line if using designed components   
17.         //InitializeComponent();   
18.     }  
19.     [WebMethod]  
20.     public int converttodaysweb(int day, int month, int year)  
21.     {  
22.         DateTime dt = new DateTime(year, month, day);  
23.         int datetodays = DateTime.Now.Subtract(dt).Days;  
24.         return datetodays;  
25.   
26.     }  
27.   
28. }  
Now run the application that look like as follows.

Now in the above we see our method that we are created in the webservice.cs file, so click on
that method and provide input values and click on the "invoke" link as in.
The output will be as follows

In the screen above you see that the output is 8671,that is the days from the input date.

Note

 For detailed code please download the zip file attached above.

Difference between authentication and authorization.

Authentication Authorization

It is the process of verifying the identity of a user. It is the process of checking whether the user
has the access rights to the system.

It always proceeds to authorization. It is the process of allowing an authenticated


user access to resources.

It has two separate levels because all the requests coming It allows two ways to authorize the access to a
through the IIS before it is handled. given resources.

They have additional schemes like windows authentication, The two ways are URL authorization and File
forms authentication and passport authentication. authorization.

You might also like