Adnace Technology
Adnace 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.
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]
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
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.
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.
.NET Framework is a technology that supports building and running Windows apps and
web services. .NET Framework is designed to fulfill the following objectives:
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.
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.
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 .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:
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.
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.
o Access to data
Namespaces Description
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.
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.
Benefits of CLR
The runtime provides the following features:
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.
private
shared
Private assemblies are simple and copied with each calling assemblies in the calling
assemblies folder.
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.
.Net Applications
(IO,Streams,Sockets,Security,Reflection,UI)
(Windows,Linux,UNIX,Macintosh,etc.,)
Discussed above
Discussed above
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).
Discussed above
Discussed above
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.
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
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.
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).
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:
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.
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.
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.
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:-
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
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.
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
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.
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.
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,
@"C# Corner";
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++.
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
Arithmetic Operators
Following table shows all the arithmetic operators supported by C#.
Assume variable A holds 10 and variable B holds 20 then:
Relational Operators
Following table shows all the relational operators supported by C#.
Assume variable A holds 10 and variable B holds 20, then:
> 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:
&& Called Logical AND operator. If both the operands are non (A && B)
zero then condition becomes true. is false.
! 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:
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
-----------------
& 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 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#:
Miscellaneous Operators
There are few other important operators including sizeof,
typeof and ?:supported by C#.
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.
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.
Namespace aliases
The using directive can be also used to create namespace aliases. For example:
using col = System.Collections;
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.
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.
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
Implement IDisposable interface and Dispose method
'using' block is also used to clean unmanaged resources
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.
//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
C# - Jagged Arrays
int[][] scores;
Declaring an array, does not create the array in memory. To create the
above array:
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;
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.
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.
Property Description
Capacity Gets or sets the number of elements that the ArrayList can
contain.
IsFixedSize Gets a value indicating whether the ArrayList has a fixed size.
Sr.No. Methods
Example
The following example demonstrates the concept:
usingSystem;
usingSystem.Collections;
namespaceCollectionApplication
{
classProgram
{
staticvoidMain(string[] args)
{
ArrayList al =newArrayList();
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:
C# - Hashtable Class
Property Description
Sr.No. Method
Adds an element with the specified key and value into the Hashtable.
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");
}
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:
C# - Indexers
Syntax
A one dimensional indexer has the following syntax:
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;
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.
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;
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";
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
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:
Example
The following example demonstrates use of properties:
usingSystem;
namespace tutorialspoint
{
classStudent
{
privatestring code ="N.A";
privatestring name ="not known";
privateint age =0;
classExampleDemo
{
publicstaticvoidMain()
{
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
{
classExampleDemo
{
publicstaticvoidMain()
{
// Create a new Student object:
Student s =newStudent();
When the above code is compiled and executed, it produces the following
result:
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.
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.
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);
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.
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);
When the above code is compiled and executed, it produces the following
result:
C# - Events
Declaring Events
To declare an event inside a class, first a delegate type for the event
must be declared. For example,
publicdelegatestringMyDel(string str);
eventMyDelMyEvent;
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:
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.
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
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.
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.
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:
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
What is ADO.NET?
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:
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.
.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 are two major factors when developing web-based
application and services. Disconnected cached data in XML help in performance and
scalability.
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.
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.
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.
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:
Example
SQL Authentication
Or:
Windows Authentication
String constr="server=.;database=institute;trusted_connection=true"
Or:
Procedure:
2. Handle exceptions.
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.
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.
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
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.
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.
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.
// C# constructor overloading
// author: [email protected]
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
However the following program do not compile since it contain only private
constructors
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: [email protected]
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
}
}
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.
For example
// C# static constructor
// Author: [email protected]
using System;
class Complex
{
static Complex()
{
Console.WriteLine("static constructor");
}
}
class MyClient
{
public static void Main()
{
Complex c;
Console.WriteLine("RAJESH");
c = new Complex();
}
}
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.
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.
We can also call a base class constructor explicitly by using base() as shown below.
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#.
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".
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.
5. An abstract class holds the methods but the actual implementation of those
methods is made in derived class.
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.
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.
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'.
C# - Polymorphism
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
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.
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();
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.
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:
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:
C# - Interfaces
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;
}
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.
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
Validation is important part of any web application. User's input must always be validated before
sending across different layers of the application.
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
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.
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:
RangeValidator Checks that the user enters a value that falls between
two values
All validation controls are rendered in form as <span> (label are referred as <span> on client by
server)
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.
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:
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.
<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.
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
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
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
Hide Copy Code
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
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.
Let us see how to create persistence cookies. There are two ways, the first one is:
Hide Copy Code
Hide Copy Code
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
Hide Copy Code
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.
Hide Copy Code
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.
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"
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
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"
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
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.
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:
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.
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?
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, 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
To cache an entire page's output we need to specify a directive at the top of our page, this
directive is the @ OutputCache.
1. <%@ OutputCache Duration = 5 VaryByParam = "ID" %>
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.
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.
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.
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.
<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:
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.
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
<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.
<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.
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.
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.
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.
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.
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.
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
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..
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.
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 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.