SlideShare a Scribd company logo
1 of 150
History
.NET is the Microsoft Web services strategy to connect information, people, systems, and
devices through software.
Integrated across the Microsoft platform, .NET technology provides the ability to quickly
build, deploy, manage, and use connected, security-enhanced solutions with Web services.
.NET was originally called NGWS (Next Generation Windows Services).
Web services are self-describing software modules, semantically encapsulating discrete
functionality, wrapped in and accessible via standard Internet communication protocols such
as XML and SOAP.
.NET framework also includes versions for mobile and embedded devices.
1
Basics
.NET is a programming framework created by Microsoft that developers can use to create
applications more easily. Framework provides libraries commonly used by the developers.
.NET Base Class Libraries (BCL) serves that purpose.
.NET provides language interoperability across several programming languages. Programs
written for .NET framework execute in a software environment called Common Language
Runtime (CLR).
CLR is the foundation of .NET framework which provides services like type safety, memory
management, garbage collection, and exception handling.
CLR manages execution of code. Code that is managed by CLR is called managed code.
Unmanaged code doesn’t get managed by CLR. CLR’s interoperability helps to interact
between managed and unmanaged code.
Common Language Specification(CLS) and Common Type System (CTS) as part of CLR. CTS is
responsible for interpreting the data types into common format. Ex: number of bytes for an
integer. CLS provides ability of code to interact with code that is written using a different
programming language.
2
Architecture
3
Lifecycle
Microsoft started creating .NET framework in 1990s. By late2000 the first version on .NET 1.0
was released.
Since then Microsoft has released .NET 1.1, 2.0, 3.0, 3.5, 4.0, & 4.5 versions of the framework.
Microsoft added additional features and functionality in every release to make development
easier using Visual Studio IDE.
4
Content - .Net
Features of .Net
Rich Functionality out of the box
Easy development of web applications
OOPs Support
Multi-Language Support
Multi-Device Support
Automatic memory management
Compatibility with COM and COM+
No more DLL Hell
Strong XML support
Ease of deployment and configuration
Security
6
Content - .Net
The .NET Class Framework
7
Content - .Net
Just-In-Time Complilation (JIT)
The MSIL is the language that all of the .NET languages compile down to. After they are
in this intermediate language, a process called Just-In-Time (JIT) compilation occurs
when resources are used from your application at runtime
Metadata - Metadata describes every type and member defined in your code in a
Multilanguage form. Metadata stores the following information:
• Description of the assembly
• Identity (name, version, culture, public key).
• The types that are exported.
• Other assemblies that this assembly depends on.
• Security permissions needed to run
Assembly - Assemblies are the building blocks of .NET Framework applications; they form the
fundamental unit of deployment, version control, reuse, activation scoping, and security
permissions
8
Content - .Net
Managed Code / Methods - Machine instructions in MSIL format and located in Assemblies
will be executed by the CLR, will have the following intrinsic advantages, Memory
management to prevent memory leaks in the program code,
Thread execution,
Code safety verification,
Compilation,
Unmanaged Code / Methods - Unmanaged codes are the instructions, which are targeted for
specific platforms. Unmanaged code will exist in any of the format, A code instructions in
managed C++ with “#pragma unmanaged”
COM/COM+ Components
Win32 Dlls/System Dlls
As these codes are in native format of OS, these instructions will be executed faster
compared with JIT compilation and execution of Managed code
9
Content - What is DLL HELL in .NET
10
1. I have 2 applications, A1 and A2 installed on my computer.
2. Both of these applications use shared assembly shared.dll
3. Now, I have a latest version of Application - A2 available on the internet.
4. I download the latest version of A2 and install it on my machine.
5. This new installation has over written Shared.dll, which is also used by Application - A1.
6. Application - A2 works fine, but A1 fails to work, because the newly installed Shared.dll is not backward compatible.
So, DLL HELL is a problem where one application will install a new version of the shared component that is not backward
compatible with the version already on the machine, causing all the other existing applications that rely on the shared
component to break. With .NET versioning we donot have DLL HELL problem any more.
Content - How is the DLL HELL problem solved in .NET
11
In dot net all the shared assemblies are usually in the GAC. GAC stands for Global Assembly Cache. The path
for GAC is C:[OperatingSystemDirectory]assembly. For example on my computer the path
is C:WINDOWSassembly. The image below shows the shared assemblies in the GAC.
Only strong named assemblies can be copied into GAC. Strong named assemblies in .NET has 4 pieces in its
name as listed below.
1. Simple Textual Name
2. Version Number
3. Culture
4. Public Key Token
All these four pieces put together, is called as the fully qualified name of the assembly. In the GAC image
above Accessibility assembly has a version of 2.0.0.0.
Content - How is the DLL HELL problem solved in .NET
12Copyright©Sharma. All rights reserved.
Now consider the example below:
1. I have 2 applications, Application - A1 and Application - A2 which relies on the shared assembly Accessibility.dll
(Version 2.0.0.0) as shown in the image below.
2. Now, I have a latest version of Application - A2 available on the internet.
3. I download the latest version of A2 and install it on my machine.
4. This new installation copies a newer version of Accessibility.dll into the GAC with version 3.0.0.0.
5. So, in the GAC we now have 2 versions of Accessibility.dll.
6. Application - A1 continues to use Accessibility.dll (version 2.0.0.0) and Application - A2 uses Accessibility.dll
(version 3.0.0.0)
7. So, now the assemblies are able to reside side by side in the GAC. For this reason dot net assemblies are also
said to be supporting side by side execution.
If you can improve this answer further, please feel free to do so by submitting the form below. Thank you very
much for your contribution.
Content – C# Language Fundamentals
13Copyright©Sharma. All rights reserved.
What is C#
C# (pronounced "see sharp" or "C Sharp") is one of many .NET programming languages. It is object-oriented and allows
you to build reusable components for a wide variety of application types Microsoft introduced C# on June 26th, 2000
and it became a v1.0 product on Feb 13th 2002.
C# is an evolution of the C and C++ family of languages. However, it borrows features from other programming
languages, such as Delphi and Java. If you look at the most basic syntax of both C# and Java, the code looks very similar,
but then again, the code looks a lot like C++ too, which is intentional. Developers often ask questions about why C#
supports certain features or works in a certain way. The answer is often rooted in it's C++ heritage.
How Does a C# Application Run?
An important point is that C# is a "managed" language, meaning that it requires the .NET Common Language Runtime
(CLR) to execute. Essentially, as an application that is written in C# executes, the CLR is managing memory, performing
garbage collection, handling exceptions, and providing many more services that you, as a developer, don't have to write
code for. The C# compiler produces Intermediate Language (IL) , rather than machine language, and the CLR understands
IL. When the CLR sees the IL, it Just-In-Time (JIT) compiles it, method by method, into compiled machine code in memory
and executes it. As mentiond previously, the CLR manages the code as it executes.
Because C# requires the CLR, you must have the CLR installed on your system. All new Windows operating systems ship
with a version of the CLR and it is available via Windows Update for older systems. The CLR is part of the .NET, so if you
see updates for the .NET Framework Runtime, it contains the CLR and .NET Framework Class Library (FCL). It follows that
if you copy your C# application to another machine, then that machine must have the CLR installed too.
Content – C# Language Fundamentals
14Copyright©Sharma. All rights reserved.
Content – C# Language Fundamentals
15Copyright©Sharma. All rights reserved.
Program Structure
Namespaces
Contain types and other namespaces
Type declarations
Classes, structs, interfaces, enums,
and delegates
Members
Constants, fields, methods, properties,
indexers, events, operators, constructors,
destructors
Organization
No header files, code written “in-line”
No declaration order dependence
Content – C# Language Fundamentals
16Copyright©Sharma. All rights reserved.
A Simple Welcome Program: Welcome.cs
// Namespace Declaration
using System;
// Program start class
class WelcomeCSS
{
// Main begins program execution.
static void Main()
{
// Write to console
Console.WriteLine("Welcome to the C# Station Tutorial!");
}
}
Content – C# Language Fundamentals
Constants & Variables
"Variables" are simply storage locations for data. You can place data into them and
retrieve their contents as part of a C# expression. The interpretation of the data in a
variable is controlled through "Types".
C# is a "Strongly Typed" language. Thus all operations on variables are performed with
consideration of what the variable's "Type" is. There are rules that define what
operations are legal in order to maintain the integrity of the data you put in a variable.
The C# simple types consist of the Boolean type and three numeric types - Integrals,
Floating Point, Decimal, and String.
Constants are very similar to variables. The main difference is that the value contained in
memory cannot be changed once the constant is declared. When you declare a constant
its value is also specified and this value cannot be changed during program execution.
17Copyright©Sharma. All rights reserved.
Content – C# Language Data Types
The Boolean Type
Boolean types are declared using the keyword, bool. They have two values: true or false. In
other languages, such as C and C++, boolean conditions can be satisfied where 0 means false
and anything else means true. However, in C# the only values that satisfy a boolean condition
is true and false, which are official keywords.
using System;
class Booleans
{
public static void Main()
{
bool content = true;
bool noContent = false;
Console.WriteLine("It is {0} that C# Station provides C# programming language content.",
content);
Console.WriteLine("The statement above is not {0}.", noContent);
}
}
18Copyright©Sharma. All rights reserved.
Content – C# Language Data Types
Integral Types
In C#, an integral is a category of types. For anyone confused because the word Integral
sounds like a mathematical term, from the perspective of C# programming, these are actually
defined as Integral types in the C# programming language specification. They are whole
numbers, either signed or unsigned, and the char type. The char type is a Unicode character,
as defined by the Unicode Standard.
19Copyright©Sharma. All rights reserved.
Type Size (in bits) Range
sbyte 8 -128 to 127
byte 8 0 to 255
short 16 -32768 to 32767
ushort 16 0 to 65535
int 32 -2147483648 to 2147483647
uint 32 0 to 4294967295
long 64
-9223372036854775808 to
9223372036854775807
ulong 64 0 to 18446744073709551615
char 16 0 to 65535
Content – C# Language Data Types
Floating Point and Decimal Types
A C# floating point type is either a float or double. They are used any time you need to
represent a real number, as defined by IEEE 754. For more information on IEEE 754, visit
the IEEE Web Site. Decimal types should be used when representing financial or money
values. The Table shows the floating point and decimal types, their size, precision, and range
20Copyright©Sharma. All rights reserved.
Type Size (in bits) precision Range
float 32 7 digits 1.5 x 10-45 to 3.4 x 1038
double 64 15-16 digits
5.0 x 10-324 to 1.7 x
10308
decimal 128 28-29 decimal places 1.0 x 10-28 to 7.9 x 1028
Content – C# Language Data Types
The string Type
A string is a sequence of text characters. You typically create a string with a string literal, enclosed in
quotes: "This is an example of a string”. Some characters aren't printable, but you still need to use them in
strings. Therefore, C# has a special syntax where characters can be escaped to represent non-printable
characters.
For example, it is common to use newlines in text, which is represented by the 'n' char. The backslash, '',
represents the escape. When preceded by the escape character, the 'n' is no longer interpreted as an
alphabetical character, but now represents a newline.
21Copyright©Sharma. All rights reserved.
Escape Sequence Meaning
' Single Quote
" Double Quote
 Backslash
0
Null, not the same as the
C# null value
a Bell
b Backspace
f form Feed
n Newline
r Carriage Return
t Horizontal Tab
v Vertical Tab
Content – C# Operators
Results are computed by building expressions. These expressions are built by combining variables and
operators together into statements. The following table describes the allowable operators, their
precedence, and associativity.
22Copyright©Sharma. All rights reserved.
Category (by precedence) Operator(s) Associativity
Unary + - ! ~ ++x --x (T)x right
Multiplicative * / % left
Additive + - left
Shift << >> left
Relational < > <= >= is as left
Equality == != right
Logical AND & left
Logical XOR ^ left
Logical OR | left
Conditional AND && left
Conditional OR || left
Null Coalescing ?? left
Ternary ?: right
Assignment
= *= /= %= += -
= <<= >>= &= ^= |= =>
right
Content – C# Operators
Unary Operators: Unary.cs
using System;
class Unary
{
public static void Main()
{
int unary = 0;
int preIncrement;
int preDecrement;
int postIncrement;
int postDecrement;
int positive;
int negative;
sbyte bitNot;
bool logNot;
preIncrement = ++unary;
Console.WriteLine("pre-Increment: {0}", preIncrement);
preDecrement = --unary;
Console.WriteLine("pre-Decrement: {0}", preDecrement);
postDecrement = unary--;
Console.WriteLine("Post-Decrement: {0}", postDecrement);
postIncrement = unary++;
Console.WriteLine("Post-Increment: {0}", postIncrement);
Console.WriteLine("Final Value of Unary: {0}", unary);
positive = -postIncrement;
Console.WriteLine("Positive: {0}", positive);
negative = +postIncrement;
Console.WriteLine("Negative: {0}", negative);
bitNot = 0;
bitNot = (sbyte)(~bitNot);
Console.WriteLine("Bitwise Not: {0}", bitNot);
logNot = false;
logNot = !logNot;
Console.WriteLine("Logical Not: {0}", logNot);
}
} 23Copyright©Sharma. All rights reserved.
Output
pre-Increment: 1
pre-Decrement 0
Post-Decrement: 0
Post-Increment: -1
Final Value of Unary: 0
Positive: 1
Negative: -1
Bitwise Not: -1
Logical Not: true
Content – C# Keywords
24
Copyright©Sharma. All rights reserved.
abstract event new struct
as explicit null switch
base extern object this
bool false operator throw
break finally out true
byte fixed override try
case float params typeof
catch for private uint
char foreach protected ulong
checked goto public unchecked
class if readonly unsafe
const implicit ref ushort
continue in return using
decimal int sbyte virtual
default interface sealed volatile
delegate internal short void
do is sizeof while
double lock stackalloc
else long static
enum namespace string
Keywords are predefined reserved identifiers that have special meanings to the compiler. They cannot be
used as identifiers in your program unless they include @ as a prefix. For example, @if is a legal identifier
but if is not because it is a keyword.
Content – C# Type Casting
25
Copyright©Sharma. All rights reserved.
Typecasting is a concept of converting one datatype into another datatype
C#.net supports 2 types of type casting
1)Implicit Type casting
2)Explicit Type casting
1) IMPLICIT TYPE CASTING
Converting from lower to higher type is called as implicit type casting. It is under control of clr
Ex:
int i = 10;
long l = i;
2) EXPLICIT TYPE CASTING
Converting from Higher to Lower type is called as explicit type casting. It is under control of
programmer
Ex:
int i=10;
byte b = (byte) i;
Content – C# Type Casting continued..
26
Copyright©Sharma. All rights reserved.
C# SUPPORTS 4 TYPES OF EXPLICIT TYPECASTING
Type:1 (C++ style of type casting)
int i=10;
byte b = (byte) i;
Type:2 (Converting)
int i=10;
char c = Convert.ToChar(i);
Type:3 (Parsing)
In c# all the predefined datatypes are structures. They contain set of methods. They are
1) ToString()
2) Parse()
3) Minvalue()
4) MaxValue()
Ex:
string s1=”10”;
string s1=”20”;
int a = int.Parse(s1);
int b = int.Parse(s2);
int c = a + b;
MessageBox.Show(c.ToString());
Type:4 (Boxing and UnBoxing)
Converting from Value types into Reference Types are called as Boxing and Converting from Reference Types into Value Types are called
UnBoxing.
Ex:
int a = 10;
string st = a.ToString(); //boxing
int b = Convert.ToInt32(st); //unboxing
MessageBox.Show(b);
Content – C# Statements
27
Copyright©Sharma. All rights reserved.
Statements are program instructions. Except as described, statements are executed in sequence. C# has the
following categories of statements.
Category C# keywords
Selection statements if, else, switch, case
Iteration statements do, for, foreach, in, while
Jump statements break, continue, default, goto, return
Exception handling
statements
throw, try-catch, try-finally, try-catch-finally
Checked and unchecked checked, unchecked
fixed Statement fixed
lock Statement lock
Content – C# Selection Statements
28
Copyright©Sharma. All rights reserved.
The if statement selects a statement for execution based on the value of a Boolean expression. It
takes the following form:
if (expression)
{
statement1
}
Else
{
statement2
}
Content – C# Selection Statements
29
Copyright©Sharma. All rights reserved.
switch (expression)
{
case constant-expression:
statement
jump-statement
[default:
statement
jump-statement]
}
The switch statement is a control statement that handles multiple selections by passing control to
one of the case statements within its body. It takes the following form:
Content – C# Iteration Statements
30
Copyright©Sharma. All rights reserved.
You can create loops by using the iteration statements. Iteration statements cause embedded statements to be
executed a number of times, subject to the loop-termination criteria. These statements are executed in order, except
when a jump statement is encountered.
The do statement executes a statement or a block of statements repeatedly until a specified expression evaluates
to false. It takes the following form:
do
{
statement
} while (expression);
Content – C# Iteration Statements
31
Copyright©Sharma. All rights reserved.
You can create loops by using the iteration statements. Iteration statements cause embedded statements to be
executed a number of times, subject to the loop-termination criteria. These statements are executed in order, except
when a jump statement is encountered.
The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false. It takes
the following form:
for ([initializers]; [expression]; [iterators])
{
statement
}
Content – C# Iteration Statements
32
Copyright©Sharma. All rights reserved.
You can create loops by using the iteration statements. Iteration statements cause embedded statements to be
executed a number of times, subject to the loop-termination criteria. These statements are executed in order, except
when a jump statement is encountered.
The while statement executes a statement or a block of statements until a specified expression evaluates to false. It takes the
following form:
while (expression)
{
Statement
}
Content – C# Statements & Comments
Statements and Comments
Case sensitive (myVar != MyVar)
Statement delimiter is semicolon ;
Block delimiter is curly brackets { }
Single line comment is //
Block comment is /* */
Save block comments for debugging!
33Copyright©Sharma. All rights reserved.
Content – C# Arrays
Array in the programming are required to do the following:
1) To reduce overhead the system
2) To reduce complexity in the program
•Arrays will reduce the overhead of the system By allocating sequential memory and Arrays will reduce
the complexity by storing many values with a single name
•Internally the system will automatically convert each Array element into the form of an object. It means,
according to the system an array is the collection of objects
•In c# Arrays are references to store similar type dynamic values. That means for this reference we should
allocate the memory dynamically using new operator.
34Copyright©Sharma. All rights reserved.
• The variables we have been working with so far have only been able to hold one value at a
time
• Example:
int lotteryNumber1 = 1;
int lotteryNumber2 = 2;
int lotteryNumber3 = 3;
:
• An Array allows you to use just one identifying name that refers to lots of values
Why use Arrays?
1. Declaration:
• int[] lotteryNumbers;
• float[] myFloatValues;
• string[] myStrings;
2. Size of array:
• lotteryNumbers = new int[4];
• myFloatValues = new float[10];
• myStrings = new string[5];
How to setup an Array
Declaration and setting the size in one line
• int[] lotteryNumbers = new int[4];
• float[] myFloatValues = new float[10];
• string[] myStrings = new string[5];
arrayName[position] = arrayValue;
int[] lotteryNumbers = new int[4];
lotteryNumbers[0] = 1; // first array
lotteryNumbers[1] = 2;
lotteryNumbers[2] = 3;
lotteryNumbers[3] = 4; // last (4th) array
Assigning values
int[] lotteryNumbers = new int[4];
lotteryNumbers[0] = 1;
lotteryNumbers[1] = 2;
lotteryNumbers[2] = 3;
lotteryNumbers[3] = 4;
First index is ZERO
int[] lotteryNumbers = new int[4];
lotteryNumbers[0] = 1;
lotteryNumbers[1] = 2;
lotteryNumbers[2] = 3;
lotteryNumbers[3] = 4;
Last index is (SIZE -1)
int[] lotteryNumbers = new int[4];
lotteryNumbers[0] = 1;
lotteryNumbers[1] = 2;
lotteryNumbers[2] = 3;
lotteryNumbers[3] = 4;
Total number of array =
SIZE
int[] lotteryNumbers = new int[4] {1, 2, 3, 4};
Declare, Set Array Size and Assign
Values in one line
Declare
int[] lotteryNumbers = new int[4] {1, 2, 3, 4};
Set Size of Array
int[] lotteryNumbers = new int[4] {1, 2, 3, 4};
Assign values
To loop through the following array:
lotteryNumbers[0]
lotteryNumbers[1]
lotteryNumbers[2]
lotteryNumbers[3]
for (int i = 0; i != lotteryNumbers.Length; i++)
{
lotteryNumber[i] ….. // not complete
}
Arrays and Loops
for (int i = 0; i != lotteryNumbers.Length; i++)
{
lotteryNumber[i] ….. // not complete
}
starts from 0
The first index is ZERO
for (int i = 0; i != lotteryNumbers.Length; i++)
{
lotteryNumber[i] ….. // not complete
}
Length is equal to the SIZE of array
The last index should be (Length – 1)
for (int i = 0; i != lotteryNumbers.Length; i++)
{
lotteryNumber[i] ….. // not complete
}
i < lotteryNumers.Length
for (int i = 0; i != lotteryNumbers.Length; i++)
{
lotteryNumber[i] ….. // not complete
}
i <= lotteryNumers.Length -1
Content – OOP’s in C#
Programming approaches
We have 2 types of programming approaches to develop the projects
1. Procedure Oriented Approach
2. Object Oriented Approach
Procedure Oriented Approach:
In Procedure Oriented Approach Main Task is divided into subtasks. Each task represented in
the form of functions or procedures. So a C program generally contains several functions
which are called and controlled from main() function. This approach is called Procedure
Oriented Approach.
The languages which follows Procedure Oriented Approach that languages are called
Procedure Oriented Language.
Ex: C, Pascal, Fortran etc.,
Object Oriented Approach:
In Object Oriented Approach Main Task is divided into several modules. Modules are
represented as Classes. Each class can perform some tasks for which several methods are
written in a class. This approach is called Object Oriented Approach.
A class is a module which itself contains data and methods to achieve the task.
Ex: c++, Java, smalltalk, All .Net languages etc.,
programming systems
We have 3 types of programming systems to develop the software based on their properties
or their characteristics.
1) POPS (PROCESS ORIENTED PROGRAMMING SYSTEM)
2) OBPS (OBJECT BASED PROGRAMMING SYSTEM)
3) OOPS (OBJECT ORIENTED PROGRAMMING SYSTEM)
50Copyright©Sharma. All rights reserved.
Content – OOP’s in C#
OOPS CHARACTERISTICS
1. Class
2. Object
3. Data Hiding
4. Data Abstraction
5. Encapsulation
6. Inheritance
7. Polymorphism
1) Class:
A group of Attributes with its relative behavior kept into a single unit with permitted accessibilities known
as a CLASS. A class is a model or blueprint for creating objects.
*A class is a user defined datatype in oops to define our own datatypes
* class is a blueprint for its objects which supports to create any no. of instances to store specific
information
* Class is a logical Entity which allows to keep attributes with its related methods in a single unit with
authorized accessing, with security
* Class allows 3 types of top level access specifiers to secure its members. They are
private, public and protected. But in C# 5 types of access specifiers are available.
They are private, public, protected, internal and internal protected.
51Copyright©Sharma. All rights reserved.
Content – OOP’s in C#
2) Object:
Object is a reference of its class blueprint. Which stores a specific data to perform specific
operations.
* Object has a physical reality.
* Members of an object are invoked with ‘.’ operator.
Syntax
<class_name> <ref_var> = new <class_Name>([args..]);
Ex:
Emp e = new Emp();
Object Properties
1. Its state (attributes)
2. Its behavior (methods)
3. Its identity (hashcode) //address of the object
3) Data Hiding:
Doesn’t provide the access attributes directly to others. Private keyword hides the attributes
and does not allow access to others.
Ex:
private int EmpNo;
4) Data Abstraction:
Doesn’t provide to access the methods directly to others and hiding the implementation of
the code.
Ex:
private float calcNetSal()
{
//statements
}
used in the operation. 52Copyright©Sharma. All rights reserved.
Content – OOP’s in C#
5) Encapsulation:
In the class declared variables called as attributes/Data Members/status and defined
functions are called as Member Functions/ behaviors. These both are called as Members.
These members are binding into a single class is called Data Encapsulation.
Encapsulation is a mechanism where the data (variables) and the code(methods) that act on
the data will bind together.
6) Inheritance:
Inheritance is the process by which objects can acquire the properties of objects of other
class. In OOP, inheritance provides reusability, like adding additional features to an existing
class without modifying it. This is achieved by deriving a new class from the existing one.
The new class will have combined features of both the classes.
7) Polymorphism:
Polymorphism came from the two greek words ‘poly’ and ‘morphos’. Poly means many and
morphos means forms. The ability to exist in different forms is called polymorphism.
An Operation may exhibit different behaviors in different instances. The behavior depends
on the datatypes
Advantages of OOPS
1. OOP provides a clear modular structure for programs which makes it good for dealing
abstract datatypes where implementation details are hidden and the unit has a clearly defined
interface
2. OOP makes it easy to maintain and modify existing code as new objects can created with
small differences to existing ones
3. OOP provides a good framework for code libraries where supplied software components can
be easily adapted and modified by the programmer. This is particularly useful for developing
graphical user interfaces
53Copyright©Sharma. All rights reserved.
Content – Polymorphism
Polymorphism came from the two greek words ‘poly’ and ‘morphos’. Poly means many and
morphos means forms. If the same method perform different tasks, then that method is said
to exhibit(show) polymorphism. If a method performs several tasks, it is called
Polymorphism.
Polymorphism also called as Overloading Types of OverLoading
C# supports 3 types of Overloading
1. Function Overloading
2. Constructor Overloading
3. Operator Overloading
54Copyright©Sharma. All rights reserved.
Content – Polymorphism
Constructors and Destructors
1. Constructors is a special type of function which will be executed automatically while an
object is creating
2. Destructor is special type of function which will be executed automatically while an object is
destroying
3. Constructors name must be same as class name without return type
4. Destructors name must be same as class name by preceding a ‘~‘(tild) operator and without
return type and access specifier
5. Constructors are overloadable but destructors are not overloadable
6. Generally constructors will be used to initialize the variables to open the connections etc.
7. Destructors will be used to close the connections or deallocate the memory
55Copyright©Sharma. All rights reserved.
Content – Inheritance
Inheritance is a concept where new classes can be produced from existing classes. The
newly created class acquires all the features of existing class from where it is derived. The
newly constructed class is called Derived and already existing class is called Base.
Syntax:
class Base
{
//base class members
}
class Derived : Base
{
//derived class members
}
Deriving new classes from existing classes such that the new classes acquire all the features
of existing classes is called Inheritance.
There are to ways in .NET to share the existing data
1. Aggregation
2. Inheritance
Aggregation:
Creating an instance of a class to use the code in another class known as Aggregation. Through aggregation we can
reuse/execute the code only. It said object-to –object communication. This relationship is called Has-A relationship.
Inheritance:
Defining a new class is-a type of existing class to reuse the data code without redefining. The inheritance makes the
family of classes with relations. This relationship is called Is-A relationship.
56Copyright©Sharma. All rights reserved.
Content – Inheritance
57Copyright©Sharma. All rights reserved.
Content – Inheritance
58Copyright©Sharma. All rights reserved.
Content – Inheritance
59Copyright©Sharma. All rights reserved.
Content – Inheritance
60Copyright©Sharma. All rights reserved.
Content – Properties ,Indexers , Static Members
Properties
The properties are used to control the behavior of an object like methods, but they can be accessible like variables.
A property can have 2 accessors
1)Get
2)Set
* If a property contain only “SET” accessor, then this property is called as WRITEONLY property.
•If a property contain only “GET” accessor, then this property is called as READONLY property.
INDEXERS
The indexers of a class allows accessing its objects like an Array. The indexers design is very
similar to property designing i.e. an indexer can contain one get accessor and one set
accessor.
Static Variable
If we define the variables as static that variables are called as static variables. That static variables data will be treated as
global. If we define the variables of the class as static that variables are called Class variables. That class variables data
can be shared to all the objects of that class. We can access the static variables directly using class name.
Ex: static int a;
* To make variables as a global for all its related class objects that variable should be defined
as static.
* The static variable defines only once, the moment we call the first method of the class, either
constructor or static method.
61Copyright©Sharma. All rights reserved.
Content – Types of Classes
Types of classes
In DOTNET six types of classes are available
1. General Classes
2. Static Classes
a) Sealed Classes
b) Abstract Classes
I. Partial Abstract(Abstract Classes)
II. Fully Abstract(Interfaces)
3. Partial Classes
4. Generic Classes
Sealed Classes:
1. Sealed is a keyword, sealed classes are not inheritable, sealed methods are not overridable. Whenever a class is
providing full functionality then recommended to declare that class as sealed.
2. The sealed modifier is used to prevent derivation from a class. An error occurs if a sealed class is specified as the
base class of another class. A sealed class can’t also be an abstract class.
Sealed Methods
In c# a method can be declared as sealed. However when we override a method in a
derived class, we can declare the overrided method as sealed by declaring it as sealed, We
can avoid further overriding of this method.
62Copyright©Sharma. All rights reserved.
Content – Types of Classes
Abstract Classes
If we define the method without definition that method is called Abstract method. If a
class contain even a single abstract method, then this class is called as an Abstract Class.
Abstract class can contain Concrete methods and also Abstract methods. So this class is
called Partial Abstract class. We can’t create the objects to Abstract Class. Which class will
implement the abstract class methods only that class will be instantiated. Abstract is a
behavioral modifier which is applicable to methods and classes.
A method without body is known as Abstract Method. A class which contains 0 or
more abstract methods that class is called Abstract Class. We can’t create the objects to
Abstract class.
Note:
An abstract class can contain abstract methods as well as concrete methods. It is the combination of abstract methods
and concrete methods.
63Copyright©Sharma. All rights reserved.
Content – Interfaces
An interface contains only abstract methods which are all incomplete methods. So it is not possible to create an object to
an interface. In this case, we can create separate classes where we can implement all the methods of the interface.
These classes are called implementation classes. Since, implementation classes will have all the methods with the body,
it is possible to create objects to the implementation classes.
The multiple inheritance is possible in .NET through the interfaces. i.e., one class can inherit only one class and can
implement any no. of interfaces. Interface is a pure abstract class which contains pure abstract methods.
Ex:
using System;
public interface MyInterface
{
void func1();
void func2();
};
class MyClass : MyInterface
{
public void func1()
{
MessageBox.Show("func1()");
}
public void func2()
{
MessageBox.Show("func2()");
}
};
private void button1_Click(object sender, EventArgs e)
{
MyClass mc = new MyClass();
mc.func1();
mc.func2();
}
64Copyright©Sharma. All rights reserved.
Note: Interface methods must be implemented in sub classes as public
The interface can refer the implementation class object
Content – Namespaces
65Copyright©Sharma. All rights reserved.
A namespace is designed for providing a way to keep one set of names separate from another. The
class names declared in one namespace will not conflict with the same class names declared in
another.
Defining a Namespace
A namespace definition begins with the keyword namespace followed by the namespace name as
follows:
namespace namespace_name
{
// code declarations
}
To call the namespace-enabled version of either function or variable, prepend the namespace name
as follows:
namespace_name.item_name;
Content – Namespaces
66Copyright©Sharma. All rights reserved.
Content – Exception Handling
A Developer may also commit several errors while designing the project or developing the
code. These errors are also called ‘bugs’ and the process of removing them is called
‘debugging’.
Types of Errors
There are basically 2 types of errors in c# program:
1. Compile-time errors
2. Run-time errors
1) Compile-time errors:
These errors are syntactical errors found in the code, due to which a program fails to compile.
For example, forgetting a semicolon at the end of the statement, or writing a statement
without proper syntax will result in compile-time error.
2) Run-time errors:
These errors represent inefficiency of the compiler system to execute a particular statement.
The errors which doesn’t understand by the compiler that errors displays only at the time of
runtime, these errors are detected by the CLR.
Importance of Exception Handling
To avoid the abnormal termination in a program we use Exception handlers that are try,
catch, throw, finally. This is called Exception Handling.
If the program has any runtime errors CLR proprogates an Exception during execution. This
exception is in the form of object. If we didn’t handle the propagated Exceptional objects
immediately CLR terminates the application by displaying the proper message of the raised
exception.
Exceptions which are not checked at compilation time which may rise in runtime by CLR
known as UnChecked Exceptions.
67Copyright©Sharma. All rights reserved.
Content – Exception Handling
68Copyright©Sharma. All rights reserved.
Exceptions provide a way to transfer control from one part
of a program to another. C# exception handling is built
upon four keywords: try, catch, finally and throw.
try: A try block identifies a block of code for which
particular exceptions will be activated. It's 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.
Content – Exception Handling
69Copyright©Sharma. All rights reserved.
Content – Exception Handling
70Copyright©Sharma. All rights reserved.
Content – Exception Handling
71Copyright©Sharma. All rights reserved.
Content – ASP.Net
ASP.NET provides services to allow the creation, deployment, and execution of
Web Applications and Web Services
Like ASP, ASP.NET is a server-side technology
Web Applications are built using Web Forms
Web Forms are designed to make building web-based applications as easy as building Visual
Basic applications
72Copyright©Sharma. All rights reserved.
Content – ASP.Net
Key Features:
Web Forms
Web Services
Built on .NET Framework
Simple programming model
Maintains page state
Multibrowser support
XCOPY deployment
XML configuration
Complete object model
Session management
Caching
Debugging
Extensibility
Separation of code and UI
Security
ASPX, ASP side by side
Simplified form validation
Cookieless sessions
73Copyright©Sharma. All rights reserved.
Content – ASP.Net
Page Syntax
The most basic page is just static text
Any HTML page can be renamed .aspx
Pages may contain:
Directives: <%@ Page Language=“VB” %>
Server controls: <asp:Button runat=“server”>
Code blocks: <script runat=“server”>…</script>
Data bind expressions: <%# %>
Server side comments: <%-- --%>
Render code: <%= %> and <% %>
Use is discouraged; use <script runat=server> with code in event handlers instead
74Copyright©Sharma. All rights reserved.
Content – ASP.Net
ASP.Net Page Life Cycle:
When a page is requested, it is loaded into the server memory, processed and sent to the
browser. Then it is unloaded from the memory. At each of this steps, methods and events are
available, which could be overridden according to the need of the application. In other words,
you can write your own code to override the default code.
The Page class creates a hierarchical tree of all the controls on the page. All the components
on the page, except the directives are part of this control tree. You can see the control tree by
adding trace= "true" to the Page directive. We will cover page directives and tracing under
'directives' and 'error handling'.
The page life cycle phases are:
•Initialization
•Instantiation of the controls on the page
•Restoration and maintenance of the state
•Execution of the event handler codes
•Page rendering
Understanding the page cycle helps in writing codes for making some specific thing happen at
any stage of the page life cycle. It also helps in writing custom controls and initializing them at
right time, populate their properties with view-state data and run control behavior code.
75Copyright©Sharma. All rights reserved.
76Copyright©Sharma. All rights reserved.
Content – ASP.Net
Following are the different stages of an ASP.Net page:
Page request . when ASP.Net gets a page request, it decides whether to parse and compile the page or there would be a
cached version of the page; accordingly the response is sent
Starting of page life cycle . at this stage, the Request and Response objects are set. If the request is an old request or
post back, the IsPostBack property of the page is set to true. The UICulture property of the page is also set.
Page initialization . at this stage, the controls on the page are assigned unique ID by setting the UniqueID property and
themes are applied. For a new request postback data is loaded and the control properties are restored to the view-state
values.
Page load . at this stage, control properties are set using the view state and control state values.
Validation . Validate method of the validation control is called and if it runs successfully, the IsValid property of the page
is set to true.
Postback event handling . if the request is a postback (old request), the related event handler is called.
Page rendering . at this stage, view state for the page and all controls are saved. The page calls the Render method for
each control and the output of rendering is written to the OutputStream class of the Page's Response property.
Unload . the rendered page is sent to the client and page properties, such as Response and Request are unloaded and all
cleanup done.
77Copyright©Sharma. All rights reserved.
Content – ASP.Net
Page Events
78Copyright©Sharma. All rights reserved.
Content – ASP.Net
79Copyright©Sharma. All rights reserved.
Content – ASP.Net
Controls and Control Events
HTML
Server
Intrinsic controls
List controls
Rich controls
Validation controls
Control Data Binding
80Copyright©Sharma. All rights reserved.
Content – ASP.Net Controls
81Copyright©Sharma. All rights reserved.
Content – ASP.Net Controls
82Copyright©Sharma. All rights reserved.
Content – ASP.Net Controls
83Copyright©Sharma. All rights reserved.
Content – ASP.Net Controls
84Copyright©Sharma. All rights reserved.
Content – ASP.Net Controls
85Copyright©Sharma. All rights reserved.
Content – ASP.Net Controls
86Copyright©Sharma. All rights reserved.
Content – ASP.Net - File Uploading
87Copyright©Sharma. All rights reserved.
Content – ASP.Net - File Uploading
88Copyright©Sharma. All rights reserved.
Content – ASP.Net – AdRotator
89Copyright©Sharma. All rights reserved.
<asp:AdRotator runat = "server" AdvertisementFile = "adfile.xml" Target = "_blank" />
The AdRotator control randomly selects banner graphics from a list, which is specified in an external XML schedule file. This external XML
schedule file is called the advertisement file.
The AdRotator control allows you to specify the advertisement file and the type of window that the link should follow in AdvertisementFile
and Target property respectively.
The basic syntax of adding an AdRotator is as follows:
Before going into details of the AdRotator control and its properties, let us look into the construction of the advertisement file.
Content – ASP.Net – AdRotator
90Copyright©Sharma. All rights reserved.
Content – ASP.Net – Validators
91Copyright©Sharma. All rights reserved.
ASP.Net validation controls validate the user input data to ensure that useless, unauthenticated or
contradictory data don’t get stored.
ASP.Net provides the following validation controls:
1. RequiredFieldValidator
2. RangeValidator
3. CompareValidator
4. RegularExpressionValidator
5. CustomValidator
6. ValidationSummary
Content – ASP.Net – Validators
92Copyright©Sharma. All rights reserved.
Content – ASP.Net – Validators
93Copyright©Sharma. All rights reserved.
Content – ASP.Net – Validators
94Copyright©Sharma. All rights reserved.
The RegularExpressionValidator
The RegularExpressionValidator allows validating the input text by matching against a pattern against a regular
expression. The regular expression is set in the ValidationExpression property.
The following table summarizes the commonly used syntax constructs for regular expressions:
Content – ASP.Net – Validators
95Copyright©Sharma. All rights reserved.
Content – ASP.Net – Validators
96Copyright©Sharma. All rights reserved.
Content – ASP.Net - Managing State
Maintaining State
View state
Control state
Hidden fields
Cookies
Query strings
Application state
Session state
Profile Properties
97Copyright©Sharma. All rights reserved.
ADO.NET Agenda
• ADO versus ADO.NET
• ADO.NET Architecture
• Connection Object
• Command Object
• DataReader Object
• DataAdapter Object
• DataSet Object
• DataView Object
• Use ADO.NET to access data in an application
ADO versus ADO.NET
Feature ADO ADO.NET
Primary Aim Client/server coupled Disconnected collection of
data from data server
Form of data in
memory
Uses RECORDSET object
(contains one table)
Uses DATASET object
(contains one or more
DATATABLE objects)
Disconnected
access
Uses CONNECTION object
and RECORDSET object with
OLEDB
Uses DATASETCOMMAND
object with OLEDB
Disconnected
access across
multi-tiers
Uses COM to marshal
RECORDSET
Transfers DATASET object via
XML. No data conversions
required
ADO versus ADO.NET (continued)
Feature ADO ADO.NET
XML
capabilities
XML aware XML is the native transfer
medium for the objects
Firewalls Firewalls block system-level
COM marshalling
XML flows through the firewall
via HTTP
Code Coupled to the language
used, various implementation
Managed code library – Uses
Common Language Runtime,
therefore, language agnostic
Agenda
• ADO versus ADO.NET
• ADO.NET Architecture
• Connection Object
• Command Object
• DataReader Object
• DataAdapter Object
• DataSet Object
• DataView Object
• Use ADO.NET to access data in an application
ADO.NET Architecture Diagram
ADO.NET Namespaces
System.data Core namespace, defines types that
represent data
System.Data.Common Types shared between managed providers
System.Data.OleDb Types that allow connection to OLE DB
compliant data sources
System.Data.SqlClient Types that are optimized to connect to
Microsoft® SQL Server
System.Data.SqlTypes Native data types in Microsoft® SQL
Server
Importing the ADO.NET Namespaces
Needed to build a data access application
• For OLE DB:
Imports System.Data
Imports System.Data.OleDB
• For SQL Server:
Imports System.Data
Imports System.Data.SQLClient
Agenda
• ADO versus ADO.NET
• ADO.NET Architecture
• Connection Object
• Command Object
• DataReader Object
• DataAdapter Object
• DataSet Object
• DataView Object
• Use ADO.NET to access data in an application
Connection object
• Connects to databases.
• Two provider-specific classes
o SqlConnection
o OleDbConnection.
• Connections can be opened in two ways:
o Explicitly by calling the Open method on the
connection
o Implicitly when using a DataAdapter.
• Connections handle transactions
Agenda
• ADO versus ADO.NET
• ADO.NET Architecture
• Connection Object
• Command Object
• DataReader Object
• DataAdapter Object
• DataSet Object
• DataView Object
• Use ADO.NET to access data in an application
Command Object
• Information submitted to a database as a query via a
Connection object
• Two provider-specific classes
o SqlCommand
o OleDbCommand
• Input and output parameters are supported, along with
return values as part of the command syntax
• Results are returned in the form of streams. Accessed
by:
o DataReader object
o DataSet object via a DataAdapter
Agenda
• ADO versus ADO.NET
• ADO.NET Architecture
• Connection Object
• Command Object
• DataReader Object
• DataAdapter Object
• DataSet Object
• DataView Object
• Use ADO.NET to access data in an application
DataReader Object
• Provides methods and properties that deliver
a forward-only stream of data rows from a
data source
• When a DataReader is used, parts of the
ADO.NET model are cut out, providing faster
and more efficient data access
Create DataReader Example
Agenda
• ADO versus ADO.NET
• ADO.NET Architecture
• Connection Object
• Command Object
• DataReader Object
• DataAdapter Object
• DataSet Object
• DataView Object
• Use ADO.NET to access data in an application
DataAdapter Object
• Provides a set of methods and properties to retrieve
and save data between a DataSet and its source data
store
• Allows the use of stored procedures
• Connects to the database to fill the DataSet and also
update the database
Agenda
• ADO versus ADO.NET
• ADO.NET Architecture
• Connection Object
• Command Object
• DataReader Object
• DataAdapter Object
• DataSet Object
• DataView Object
• Use ADO.NET to access data in an application
DataSet Object
• Replaces the ADO Recordset
• Represents a cache of data that contains tables,
columns, relationships, and constraints, just like a
database
• Regardless of where the source data comes from,
data can all be placed into DataSet objects
• Tracks changes that are made to the data it holds
before updating the source data
• DataSet are also fully XML-featured
• Works with all current models of data storage:
flat, relational, and hierarchical
Agenda
• ADO versus ADO.NET
• ADO.NET Architecture
• Connection Object
• Command Object
• DataReader Object
• DataAdapter Object
• DataSet Object
• DataView Object
• Use ADO.NET to access data in an application
DataView Object
• Provides methods and properties that enable
UI objects such as a DataGrid to bind to a
DataSet
• A view of the data contained in the DataSet
• Only used in conjunction with a DataSet
Agenda
• ADO versus ADO.NET
• ADO.NET Architecture
• Connection Object
• Command Object
• DataReader Object
• DataAdapter Object
• DataSet Object
• DataView Object
• Use ADO.NET to access data in an application
Create Data Access Windows Form
Create Multiple Table DataSet Example
Summary
• ADO versus ADO.NET
• ADO.NET Architecture
• Connection Object
• Command Object
• DataReader Object
• DataAdapter Object
• DataSet Object
• DataView Object
• Use ADO.NET to access data in an application
Content – Webservices
A simple definition:
“a Web Service is an application component accessible over open protocols”.
Web services evolved from previous technologies that served the same purpose such as RPC,
ORPC (DCOM, CORBA and JAVA RMI).
Web Services were intended to solve three main problems:
Interoperability
Firewall traversal
Complexity
122Copyright©Sharma. All rights reserved.
Content – Webservices
A more precise definition:
an application component that:
Communicates via open protocols (HTTP, SMTP, etc.)
Processes XML messages framed using SOAP
Describes its messages using XML Schema
Provides an endpoint description using WSDL
Can be discovered using UDDI
123Copyright©Sharma. All rights reserved.
Content – Webservices
XML – eXtensible Markup Language – A uniform data representation and exchange
mechanism.
SOAP – Simple Object Access Protocol – A standard way for communication.
UDDI – Universal Description, Discovery and Integration specification – A mechanism to
register and locate WS based application.
WSDL – Web Services Description Language – A standard meta language to described the
services offered.
124Copyright©Sharma. All rights reserved.
Content – Webservices
Example:
A buyer (which might be a simple client) is ordering goods from a seller service.
The buyer finds the seller service by searching the UDDI directory.
The seller service is a Web Service whose interface is defined using Web Services
Description Language (WSDL).
The buyer is invoking the order method on the seller service using Simple Object Access
Protocol (SOAP) and the WSDL definition for the seller service.
The buyer knows what to expect in the SOAP reply message because this is defined in
the WSDL definition for the seller service.
125Copyright©Sharma. All rights reserved.
Content – Webservices
The Web Services architecture is based upon the interactions between three roles:
Service provider
Service registry
Service requestor
The interactions involve the:
Publish operations
Find operation
Bind operations.
The Web Services model follows the publish, find, and bind paradigm.
126Copyright©Sharma. All rights reserved.
Content – Webservices
XML
XML stands for EXtensible Markup Language.
XML is a markup language much like HTML.
XML was designed to describe data.
XML tags are not predefined. You must define your own tags.
The prefect choice for enabling cross-platform data communication in Web Services.
127Copyright©Sharma. All rights reserved.
Content – Webservices
SOAP
SOAP originally stood for "Simple Object Access Protocol" .
Web Services expose useful functionality to Web users through a standard Web protocol
called SOAP.
Soap is an XML vocabulary standard to enable programs on separate computers to
interact across any network. SOAP is a simple markup language for describing messages
between applications.
Soap uses mainly HTTP as a transport protocol. That is, HTTP message contains a SOAP
message as its payload section.
SOAP has three major characteristics:
Extensibility – security and WS-routing are among the extensions under
development.
Neutrality - SOAP can be used over any transport protocol such as HTTP, SMTP or
even TCP.
Independent - SOAP allows for any programming model.
128Copyright©Sharma. All rights reserved.
Content – Webservices
A SOAP message is an ordinary XML document containing the following elements:
A required Envelope element that identifies the XML document as a SOAP message.
An optional Header element that contains header information.
A required Body element that contains call and response information.
An optional Fault element that provides information about errors that occurred while
processing the message.
SOAP uses HTTP as a transport protocol and hence can use HTTP security mainly HTTP over
SSL.
But, since SOAP can run over a number of application protocols (such as SMTP) security had
to be considered.
The WS-Security specification defines a complete encryption system.
129Copyright©Sharma. All rights reserved.
Content – Webservices
WSDL
WSDL stands for Web Services Description Language.
WSDL is an XML vocabulary for describing Web services. It allows developers to describe
Web Services and their capabilities, in a standard manner.
WSDL specifies what a request message must contain and what the response message
will look like in unambiguous notation. In other words, it is a contract between the XML
Web service and the client who wishes to use this service.
In addition to describing message contents, WSDL defines where the service is available
and what communications protocol is used to talk to the service.
A WSDL document is just a simple XML document.
It defines a web service using these major elements:
port type - The operations performed by the web service.
message - The messages used by the web service.
types - The data types used by the web service.
binding - The communication protocols used by the web service.
130Copyright©Sharma. All rights reserved.
Content – Webservices
UDDI
UDDI stands for Universal Description, Discovery and Integration.
UDDI is a directory for storing information about web services , like yellow pages.
UDDI is a directory of web service interfaces described by WSDL.
131Copyright©Sharma. All rights reserved.
FAQ - 1
Software development environments
What are the different environments in your development process or development life cycle
at your company?
This is a general interview question and not very specific to ASP.NET. Usually, the interviewer
asks this question to measure your understanding of the different environments and their
role in software development.
132Copyright©Sharma. All rights reserved.
1. Development
2. QA
3. Staging
4. UAT (User Acceptance Testing)
5. Production
1. Development Environment - All the developers check in their current work into development environment.
2. QA (Quality Assurance) Environment - This is the environment, where testers (QA) test the application. QA cannot test on
development environment, because developers are continuously checking in new code. So, if there is a bug, we don't know, if it's caused
by the old or new code. In short, if development is going on in the same environment it would be difficult to keep up with the current
state. There will be lot of confusion, if the developer is trying to fix in the same area as the tester is testing. Without development and
QA environment being seperate their is no way to do proper testing.
3. Staging Environment - Many organisations, try to keep their staging environment as identical as possible to the actual production
environment. The primary reason for this environment is to identify any deployment related issues. Also, if you are developing a B2B
(Business to Business) application, you may be interfacing with other service provider systems. Many organisations, usually setup their
staging environment to interface with the service providers as well, for complete end to end testing.
4. Production Environment - The actual live environment, that we use for day to day business.
Note: In general, the code flows from Development => QA => Staging => Production
FAQ – 2
Difference between EnableViewState and ViewStateMode properties
133Copyright©Sharma. All rights reserved.
1. Using EnableViewState property we only have 2 options
We can turn off view state altogether,
or
Enable viewstate for the entire page and then turn it off on a control-by-control basis.
2. If you want to turn of ViewState for the entire page and only enable it for specific controls on the page,
then we have to useViewStateMode property in conjunction with EnableViewState.
3. EnableViewState property only accepts true or false values and the default value is true, where
as ViewStateMode property can have a value of - Enabled, Disabled and inherit. Inherit is the default value
for ViewStateMode property.
4. ViewStateMode property is introduced in ASP.NET 4, where as EnableViewState exists from a long time.
5. If EnableViewState is to True, only then the ViewStateMode settings are applied, where as,
if EnableViewState is set to False then the control will not save its view state, regardless of
the ViewStateMode setting. In short if EnableViewState is set to False,ViewStateMode setting is not
respected.
6. To disable view state for a page and to enable it for a specific control on the page, set
the EnableViewState property of the page and the control to true, set the ViewStateMode property of the
page to Disabled, and set the ViewStateMode property of the control to Enabled.
FAQ – 3
ASP.NET Page is very slow. What will you do to make it fast
134Copyright©Sharma. All rights reserved.
1. Find out which is slow, is it the application or the database : If the page is
executing SQL queries or stored procedures, run those on the database and check
how long do they take to run. If the queries are taking most of the time, then you
know you have to tune the queries for better performance. To tune the queries,
there are several ways and I have listed some of them below.
a) Check if there are indexes to help the query
b) Select only the required columns, avoid Select *.
c) Check if there is a possiblity to reduce the number of joins
d) If possible use NO LOCK on your select statements
e) Check if there are cursors and if you can replace them with joins
2. If the queries are running fast, then we know it is the application code that is
causing the slowness. Isolate the page event that is causing the issue by turning
tracing on. To turn tracing on, set Trace="true" in the page directive. Once you
have tracing turned on you should see trace information at the bottom of the page
as shown in the image below. In this case Page Load event is taking the maximum
time. So we know, the code in Page_Load event is causing the issue. Once you look
at the code, you should be able to nail down the issue.
FAQ – 4
What are the best practices to follow to secure connection strings in an ASP.NET web
application?
1. Always store connection strings in the site's Web.config file. Web.config is very secure.
Users will not be able to access web.config from the browser.
2. Do not store connection strings as plain text. To help keep the connection to your database
server secure, it is recommended that you encrypt connection string information in the
configuration file.
3. Never store connection strings in an aspx page.
4. Never set connection strings as declarative properties of the SqlDataSource control or
other data source controls.Why is "Connecting to SQL Server using Integrated Security"
considered a best practice?Connecting to SQL Server using integrated security instead of
using an explicit user name and password, helps avoid the possibility of the connection string
being compromised and your user ID and password being exposed.
135Copyright©Sharma. All rights reserved.
FAQ – 5
What is Script injection?
A script injection attack attempts to send executable script to your application with the intent of having other users run
it. A typical script injection attack sends script to a page that stores the script in a database, so that another user who
views the data inadvertently runs the code.
What is SQL injection?
A SQL injection attack attempts to compromise your database by creating SQL commands that are executed instead of,
or in addition to, the commands that you have built into your application.
What are the best practices to keep in mind when accepting user input on a web application?
1. Always use validation controls whenever possible to limit user input to acceptable values.
2. Always check the IsValid property of the aspx page. Run the server side code only if the IsValid property value is true.
A value of false means that one or more validation controls have failed a validation check.
3. Always perform server side validation irrespective of client side validation being performed or not. This will protect
your web application even if the client has by passed the client side validation by disabling javascript in the web browser.
4. Also make sure to re validate user input in the business logic layer of your application.
What are the steps to follow to avoid Script Injection attacks?
1. Encode user input with the HtmlEncode method. This method turns HTML into its text representation.
2. If you are using the GridView control with bound fields, set the BoundField object's HtmlEncode property to true. This
causes the GridView control to encode user input when the row is in edit mode.
What are the steps to follow to avoid SQL Injection attacks?
Always use parameterized queries or stored procedures instead of creating SQL commands by concatenating strings
together.
136Copyright©Sharma. All rights reserved.
FAQ – 6
What are Master Pages in ASP.NET? or What is a Master Page?
ASP.NET master pages allow you to create a consistent layout for the pages in your application. A single master page
defines the look and feel and standard behavior that you want for all of the pages (or a group of pages) in your
application. You can then create individual content pages that contain the content you want to display. When users
request the content pages, they merge with the master page to produce output that combines the layout of the master
page with the content from the content page.
What are the 2 important parts of a master page?
The following are the 2 important parts of a master page
1. The Master Page itself
2. One or more Content Pages
Can Master Pages be nested?
Yes, Master Pages be nested.
What is the file extension for a Master Page?
.master
How do you identify a Master Page?
The master page is identified by a special @ Master directive that replaces the @ Page directive that is used for ordinary
.aspx pages.
Can a Master Page have more than one ContentPlaceHolder?
Yes, a Master Page can have more than one ContentPlaceHolder
137Copyright©Sharma. All rights reserved.
FAQ – 7
What is Passport Authentication?
Passport authentication identifies users via Microsoft Passport’s single sign-on service. Microsoft Passport is meant to provide Internet users
with a single identity that they can use to visit a wide variety of Web sites that require authentication. Information about the user is available
to your application through a profile that is stored with Microsoft.
What are the advantages of Passport authentication?
The advantages of Passport authentication are that the user doesn’t have to remember separate user names and passwords for various Web
sites and that the user can maintain his or her profile information in a single location. Passport authentication also provides access to other
Microsoft services, such as Passport Express Purchase.
What is passport software development kit (passport SDK)?
To use Passport authentication in your Web application, you must install the Passport SDK. The Passport SDK is free for preproduction
development and testing. To deploy a site for public use, you must obtain an annual license from Microsoft.
How does Passport authentication work?
When a user accesses an application that implements Passport authentication, ASP.NET checks the user’s machine for a current passport
authentication cookie. If none is found, ASP.NET directs the user to a Passport sign-on page. Once the user signs in, the Passport service
authenticates the user, stores an authentication cookie on the user’s computer, and directs the user back to the originally requested Web
page.
What are the steps to follow to use Passport authentication?
1. Install the Passport SDK. Passport is not included with Visual Studio, although the .NET Framework does include classes for working with
the Passport SDK once it is installed.
2. Set the application’s authentication mode to Passport in Web.config. Set authorization to deny unauthenticated users.
3. Use the PassportAuthentication_OnAuthenticate event to access the user’s Passport profile to identify and authorize the user.
4. Implement a sign-out procedure to remove Passport cookies from the user’s machine.
Where is PassportAuthentication_OnAuthenticate event present?
PassportAuthentication_OnAuthenticate event is present in Global.asax.
138Copyright©Sharma. All rights reserved.
FAQ – 8
What is the advantage of using Forms authentication?
The advantage of using Forms authentication is that users do not have to be member of a domain-based network to have access to your
application. Another advantage is that many Web applications, particularly commercial sites where customers order products, want to have
access to user information. Forms authentication makes these types of applications easier to create.
List the steps to use Forms authentication in a web application?
1.Set the authentication mode in Web.config to Forms.
2.Create a Web form to collect logon information.
3.Create a file or database to store user names and passwords.
4.Write code to add new users to the user file or database.
5.Write code to authenticate users against the user file or database.
What happens when someone accesses a Web application that uses Forms authentication?
When someone accesses a Web application that uses Forms authentication, ASP.NET displays the logon Web form specified in Web.config.
Once a user is authorized, ASP.NET issues an authorization certificate in the form of a cookie that persists for an amount of time specified by
the authentication settings in Web.config.
What is the difference between Windows authentication and Forms authentication?
The difference between Windows authentication and Forms authentication is that in Forms authentication your application performs all the
authentication and authorization tasks. You must create Web forms and write code to collect user names and passwords and to check those
items against a list of authorized users.
139Copyright©Sharma. All rights reserved.
FAQ – 9
What are ASP.NET Custom controls?
Custom controls extend the tools available to Web developers. Using custom controls, you can encapsulate key aspects of the visual interface
and program logic that you want to reuse throughout your application, or throughout your organization.
What are the 3 types of custom controls in ASP.NET?
Microsoft Visual Studio .NET provides three types of custom control for use on Web forms.
1. Web user controls
These combine existing server and HTML controls by using the Visual Studio .NET Designer to create functional units that encapsulate some
aspect of the user interface. User controls reside in content files, which must be included in the project in which the controls are used.
2. Composite custom controls
These create new controls from existing server and HTML controls. Although similar to user controls, composite controls are created in code
rather than visually, and therefore they can be compiled into an assembly (.dll), which can be shared between multiple applications and used
from the Toolbox in Visual Studio .NET.
3. Rendered custom controls
These create entirely new controls by rendering HTML directly rather than using composition. These controls are compiled and can be used
from the Toolbox, just like composite controls, but you must write extra code to handle tasks that are performed automatically in composite
controls.
How do you identify user controls?
User controls are identified by their .ascx file extensions.
What is the base class from which user controls derive?
User controls derive from System.Web.UI.UserControl base class. This base class provides the base set of properties and methods you use to
create the control.
140Copyright©Sharma. All rights reserved.
FAQ – 10
What are the 2 types of controls that you can use on a webform in ASP.NET?
Web Server Controls
HTML Controls
What’s the difference between Server controls and HTML controls?
1. Server controls can trigger control-specific events on the server.HTML controls can trigger only page- level events on server (postback).
2. Data entered in a server control is maintained across requests. Server controls retain state.Data is not maintained in an HTML control. Data
must be saved and restored using page-level scripts.
3. The Microsoft .NET Framework provides a set of properties for each server control. Properties allow you to change the server control’s
appearance and behavior within server-side code.HTML controls have HTML attributes only.
4. Server controls automatically detect browser and adapt display as appropriate.HTML controls do not adapt automatically. You must detect
browser in code or write for least common denominator.
What are the 2 Layouts supported by a Web form in ASP.NET?
Grid layout - Controls are placed exactly where you draw them, and they have absolute positions on the page. Use grid layout for Microsoft
Windows–style applications, in which controls are not mixed with large amounts of text. Pages using grid layout will not always display
correctly in non-Microsoft browsers.
Flow layout - This layout positions controls relative to other elements on the page. If you add elements at run time, the controls that appear
after the new element move down. Use flow layout for document-style applications, in which text and controls are intermingled.
When do you choose between GridLayout and Flow layout for Web forms?
You use GridLayout for Web forms that have a fixed appearance. You use FlowLayout for Web forms that incorporate text and controls.When
you create controls with GridLayout, Visual Studio adds style attributes to each control that set the position of the control.When you create
controls with FlowLayout, Visual Studio omits the style attribute.
141Copyright©Sharma. All rights reserved.
FAQ – 11
What are Cookies in ASP.NET?
Cookies are small pieces of information stored on the client computer.Use cookies to store small amounts of information on the client’s
machine. Web sites often use cookies to store user preferences or other information that is client-specific. Because cookies can be refused, it
is important to check whether the browser allows them before you try to create them.They are limited to storing only character data and
they are limited to 4K in size.
What are different types of Cookies?
Session Cookies
Persistent Cookies
What is the difference between Session Cookies and Persistent Cookies?
Persistent Cookies are same as Session Cookies except that, persistent cookies have an expiration date. The expiration date indicates to the
browser that it should write the cookie to the client's hard drive. Keep in mind that because a user can delete cookies from their machine
that there is no guarantee that a cookie you "drop" on a user machine will be there the next time they visit your site.
142Copyright©Sharma. All rights reserved.
FAQ – 12
What are the different levels at which events can occur in an ASP.NET web application?
Web application events occur at the application, page, and server control levels
Give some examples for application level events?
1. Application_Start
Occurs when the first user visits a page within your Web application.
2. Application_End
Occurs when there are no more users of the application.
3. Application_BeginRequest
Occurs when at the beginning of each request to the server. A request happens every time a browser navigates to any of the pages in the
application.
4. Application_EndRequest
Occurs when at the end of each request to the server.
5. Session_Start
Occurs when a new user visits a page within your application.
6. Session_End
Occurs when a user stops requesting pages from the Web application and their session times out. Sessions time out after a period specified
in the Web.config file.
7. Application_Error
Occurs when when there is an unhandled exception in an application.
Where are the application level event handlers present in an ASP.NET web application?
Application level event handlers are present in Global.asax of an ASP.NET web application
143Copyright©Sharma. All rights reserved.
FAQ – 13
What are Exceptions?
Exceptions are unusual occurrences that happen within the logic of an application.
What are the 3 approaches to handle exceptions in a Web application?
1. Use exception-handling structures to deal with exceptions within the scope of a procedure. This technique is called structured exception
handling (SEH) in the Visual Studio .NET documentation.
try
catch
finally
2. Use error events to deal with exceptions within the scope of an object.
Page_Error
Global_Error
Application_Error
3. Use custom error pages to display informational messages for unhandled exceptions within the scope of a Web application.
Where will the control flow if an exception occurs inside a try block?
If a statement in a try block causes an exception, control flow passes immediately to the next catch statement. When control flow passes to a
catch block, the statements contained in the catch block are processed to correct the error or otherwise handle the exception.
Will the finally block gets executed, if an exception occurs?
Yes, a finally block will always be executed irrespective of whether an exception has occured or not.
What is the main use of a finally block in exception handling?
Finally block is mainly used to free resources used within the try block.
How do you raise an exception?
Use the throw keyword to raise an exception. Use this keyword within your exception-handling structure to immediately pass control flow to
the catch statement.
144Copyright©Sharma. All rights reserved.
FAQ – 14
What are the different techniques to send data from one web form to another web form?
1. Query strings :
Use these strings to pass information between requests and responses as part of the Web address. Query strings are visible to the user, so
they should not contain secure information such as passwords.
2. Cookies :
Use cookies to store small amounts of information on a client. Clients might refuse cookies, so your code has to anticipate that possibility.
3. Session state :
Use Session state variables to store items that you want keep local to the current session (single user).
4. Application state :
Use Application state variables to store items that you want be available to all users of the application.
145Copyright©Sharma. All rights reserved.
FAQ – 15
What are ASP.NET Validation controls?
ASP.NET provides validation controls to help you check Web form data entries before the data is accepted and saved in the Database.
Validation controls can be used to address the following questions.
1. Did the user enter anything?
2. Is the entry the appropriate kind of data (For example, Date of Birth should be a valid Date, Name should be a string etc.)?
3. Is the data within a required range?(For example age cannot be greater than 100 years)
The validation controls check the validity of data entered in associated server controls on the client before the page is posted back to the
server.Most validity problems can be caught and corrected by the user without a round-trip to the server.
Where do the ASP.NET validation controls validate data, on the Client or on the Web Server?
ASP.NET validation controls validate data first on the client and then on the web server. If a client disables javascript on the browser then,
client side validations are bypassed and validations are performed on the web server.
Client-side validation is provided by a JScript library named WebUIValidation.js, which is downloaded separately to the client. Validation
controls also automatically provide server-side validation. Server-side validation is always performed, whether or not client-side validation
has occurred. This double-checking ensures that custom validations are performed correctly and that client-side validation has not been
circumvented.
What are the 6 different validation controls provided by ASP.NET?
RequiredFieldValidator:Checks whether a control contains data
CompareValidator:Checks whether an entered item matches an entry in another control
RangeValidator:Checks whether an entered item is between two values
RegularExpressionValidator:Checks whether an entered item matches a specified format
CustomValidator:Checks the validity of an entered item using a client-side script or a server-side code, or both
ValidationSummary:Displays validation errors in a central location or display a general validation error description
146Copyright©Sharma. All rights reserved.
FAQ – 16
What is ViewState?
Web forms have very short lifetimes.In ASP.NET, the data that is entered in controls is encoded and stored in a hidden field. This encoded
data is then sent with each request and restored to controls in Page_Init. The data in these controls is then available in the Page_Load
event.The data that ASP.NET preserves between requests is called the Web form’s view state.
How do you enable or disable a ViewState for a control on the page?
Every ASP.NET control has a property called EnableViewState. If EnableViewState is set to true ViewState is enabled for the control. If
EnableViewState is set to false ViewState is disabled for the control.
How do you enable or disable a ViewState at the page level?
At the page level you can enable or disable ViewState using EnableViewState property of the page.
What is the name of the hidden form field in which ViewState of the page is saved?
__ViewState
147Copyright©Sharma. All rights reserved.
FAQ – 17
What are the 2 build options for an ASP.NET web application?
1. Debug
2. Release
What are the 3 levels at which we can have a configuration file for an ASP.NET web application?
1. At the web server level : The Machine.config file located in the WindowsMicrosoft.NETFrameworkversionconfig directory. This sets the
base configuration for all .NET assemblies running on the server.
2. At the application or web site level : The Web.config file located in the IIS root directory.This sets the base configuration for all Web
applications and overrides settings in Machine.config.
3. In the sub directory of an application root folder : These settings override the settings in the root folder's web.config file.
What happens when you make changes to an application’s Web.config file?
When you make changes to an application’s Web.config file, IIS automatically restarts the application and applies the changes. This has the
side effect of resetting current Application or Session state variables, which can adversely affect users.
What happens when you access the Web.config file from a browser?
For security reasons, you can’t access the Web.config file from a browser. If a user requests the Web.config file from your Web site, he or she
will receive an "This type of page is not served" error message.
What happens when you access the Global.asax file from a browser?
For security reasons, you can’t access the Global.asax file from a browser. If a user requests the Global.asax file from your Web site, he or she
will receive an "This type of page is not served" error message.
148Copyright©Sharma. All rights reserved.
FAQ – 18
What are the 2 ways provided by ASP.NET to format output in a Web application?
1. Use cascading style sheets (CSS) to control the appearance of elements on a Web form.These styles can set the color, size, font, and
behavior of the HTML elements on a Web page.
2. Use Extensible Stylesheet Language Transformations (XSLT) to convert information from an Extensible Markup Language (XML) file to
HTML output and position that information on a Web form. XSLT puts data from the XML file into HTML elements and applies styles to those
elements.
What are Cascading style sheets?
Cascading style sheets (CSS) collect and organize all of the formatting information applied to HTML elements on a Web form. Because they
keep this information in a single location, style sheets make it easy to adjust the appearance of Web applications.
What are the 3 levels at which formatting can be applied with in a web application?
1. Styles can be defined in a style sheet file. Styles in a style sheet can be applied to all webforms referencing the style sheet.
2. You can also define styles in the page’s head element. These styles can be applied to all elements on the current page.
3. You can also define styles inline, in the HTML tag itself. Inline styles are applicable only to the HTML element in which these styles are
defined.
Inline formatting takes precedence over local formatting, which, in turn, takes precedence over global formatting. These precedence rules
are the reason style sheets are referred to as cascading.
149Copyright©Sharma. All rights reserved.
Thank you
150Copyright©Sharma. All rights reserved.

More Related Content

What's hot (20)

DOT Net overview
DOT Net overviewDOT Net overview
DOT Net overview
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NET
 
Introduction To C#
Introduction To C#Introduction To C#
Introduction To C#
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
 
Developing an ASP.NET Web Application
Developing an ASP.NET Web ApplicationDeveloping an ASP.NET Web Application
Developing an ASP.NET Web Application
 
C#.NET
C#.NETC#.NET
C#.NET
 
Introduction to ASP.NET Core
Introduction to ASP.NET CoreIntroduction to ASP.NET Core
Introduction to ASP.NET Core
 
.Net overview|Introduction Of .net
.Net overview|Introduction Of .net.Net overview|Introduction Of .net
.Net overview|Introduction Of .net
 
Vb.net class notes
Vb.net class notesVb.net class notes
Vb.net class notes
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core java
 
.net CLR
.net CLR.net CLR
.net CLR
 
Lecture 1 introduction to vb.net
Lecture 1   introduction to vb.netLecture 1   introduction to vb.net
Lecture 1 introduction to vb.net
 
C# language
C# languageC# language
C# language
 
Introduction to .net
Introduction to .netIntroduction to .net
Introduction to .net
 
ASP.NET Presentation
ASP.NET PresentationASP.NET Presentation
ASP.NET Presentation
 
ASP.NET Basics
ASP.NET Basics ASP.NET Basics
ASP.NET Basics
 
Introduction To C#
Introduction To C#Introduction To C#
Introduction To C#
 
C sharp
C sharpC sharp
C sharp
 
Swift Introduction
Swift IntroductionSwift Introduction
Swift Introduction
 

Similar to Dotnet Basics Presentation

Unit I- Introduction to .NET Framework.pdf
Unit I- Introduction to .NET Framework.pdfUnit I- Introduction to .NET Framework.pdf
Unit I- Introduction to .NET Framework.pdfUjwala Junghare
 
Dot net-interview-questions-and-answers part i
Dot net-interview-questions-and-answers part iDot net-interview-questions-and-answers part i
Dot net-interview-questions-and-answers part iRakesh Joshi
 
Dot net-interview-questions-and-answers part i
Dot net-interview-questions-and-answers part iDot net-interview-questions-and-answers part i
Dot net-interview-questions-and-answers part iRakesh Joshi
 
The seven pillars of aspnet
The seven pillars of aspnetThe seven pillars of aspnet
The seven pillars of aspnetNethaji Naidu
 
Introduction to .net
Introduction to .net Introduction to .net
Introduction to .net Jaya Kumari
 
.Net framework
.Net framework.Net framework
.Net frameworkRaghu nath
 
.Net introduction by Quontra Solutions
.Net introduction by Quontra Solutions.Net introduction by Quontra Solutions
.Net introduction by Quontra SolutionsQUONTRASOLUTIONS
 
Dot net interview_questions
Dot net interview_questionsDot net interview_questions
Dot net interview_questions9292929292
 
.Net framework by naveen kumar veligeti
.Net framework by naveen kumar veligeti.Net framework by naveen kumar veligeti
.Net framework by naveen kumar veligetiNaveen Kumar Veligeti
 
programming in c#.ppt
programming in c#.pptprogramming in c#.ppt
programming in c#.pptNalinaKumari2
 
Online lg prodect
Online lg prodectOnline lg prodect
Online lg prodectYesu Raj
 

Similar to Dotnet Basics Presentation (20)

Unit I- Introduction to .NET Framework.pdf
Unit I- Introduction to .NET Framework.pdfUnit I- Introduction to .NET Framework.pdf
Unit I- Introduction to .NET Framework.pdf
 
Dot net-interview-questions-and-answers part i
Dot net-interview-questions-and-answers part iDot net-interview-questions-and-answers part i
Dot net-interview-questions-and-answers part i
 
Dot net-interview-questions-and-answers part i
Dot net-interview-questions-and-answers part iDot net-interview-questions-and-answers part i
Dot net-interview-questions-and-answers part i
 
The seven pillars of aspnet
The seven pillars of aspnetThe seven pillars of aspnet
The seven pillars of aspnet
 
The Seven Pillars Of Asp.Net
The Seven Pillars Of Asp.NetThe Seven Pillars Of Asp.Net
The Seven Pillars Of Asp.Net
 
Introduction to .net
Introduction to .net Introduction to .net
Introduction to .net
 
Chapter1
Chapter1Chapter1
Chapter1
 
.Net framework
.Net framework.Net framework
.Net framework
 
dot NET Framework
dot NET Frameworkdot NET Framework
dot NET Framework
 
Asp.net new
Asp.net newAsp.net new
Asp.net new
 
.Net introduction by Quontra Solutions
.Net introduction by Quontra Solutions.Net introduction by Quontra Solutions
.Net introduction by Quontra Solutions
 
C# chap 2
C# chap 2C# chap 2
C# chap 2
 
Dotnet basics
Dotnet basicsDotnet basics
Dotnet basics
 
Dot net
Dot netDot net
Dot net
 
Dot net interview_questions
Dot net interview_questionsDot net interview_questions
Dot net interview_questions
 
c#.pptx
c#.pptxc#.pptx
c#.pptx
 
.Net framework by naveen kumar veligeti
.Net framework by naveen kumar veligeti.Net framework by naveen kumar veligeti
.Net framework by naveen kumar veligeti
 
programming in c#.ppt
programming in c#.pptprogramming in c#.ppt
programming in c#.ppt
 
Session i
Session iSession i
Session i
 
Online lg prodect
Online lg prodectOnline lg prodect
Online lg prodect
 

Recently uploaded

Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 

Recently uploaded (20)

Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 

Dotnet Basics Presentation

  • 1. History .NET is the Microsoft Web services strategy to connect information, people, systems, and devices through software. Integrated across the Microsoft platform, .NET technology provides the ability to quickly build, deploy, manage, and use connected, security-enhanced solutions with Web services. .NET was originally called NGWS (Next Generation Windows Services). Web services are self-describing software modules, semantically encapsulating discrete functionality, wrapped in and accessible via standard Internet communication protocols such as XML and SOAP. .NET framework also includes versions for mobile and embedded devices. 1
  • 2. Basics .NET is a programming framework created by Microsoft that developers can use to create applications more easily. Framework provides libraries commonly used by the developers. .NET Base Class Libraries (BCL) serves that purpose. .NET provides language interoperability across several programming languages. Programs written for .NET framework execute in a software environment called Common Language Runtime (CLR). CLR is the foundation of .NET framework which provides services like type safety, memory management, garbage collection, and exception handling. CLR manages execution of code. Code that is managed by CLR is called managed code. Unmanaged code doesn’t get managed by CLR. CLR’s interoperability helps to interact between managed and unmanaged code. Common Language Specification(CLS) and Common Type System (CTS) as part of CLR. CTS is responsible for interpreting the data types into common format. Ex: number of bytes for an integer. CLS provides ability of code to interact with code that is written using a different programming language. 2
  • 4. Lifecycle Microsoft started creating .NET framework in 1990s. By late2000 the first version on .NET 1.0 was released. Since then Microsoft has released .NET 1.1, 2.0, 3.0, 3.5, 4.0, & 4.5 versions of the framework. Microsoft added additional features and functionality in every release to make development easier using Visual Studio IDE. 4
  • 5.
  • 6. Content - .Net Features of .Net Rich Functionality out of the box Easy development of web applications OOPs Support Multi-Language Support Multi-Device Support Automatic memory management Compatibility with COM and COM+ No more DLL Hell Strong XML support Ease of deployment and configuration Security 6
  • 7. Content - .Net The .NET Class Framework 7
  • 8. Content - .Net Just-In-Time Complilation (JIT) The MSIL is the language that all of the .NET languages compile down to. After they are in this intermediate language, a process called Just-In-Time (JIT) compilation occurs when resources are used from your application at runtime Metadata - Metadata describes every type and member defined in your code in a Multilanguage form. Metadata stores the following information: • Description of the assembly • Identity (name, version, culture, public key). • The types that are exported. • Other assemblies that this assembly depends on. • Security permissions needed to run Assembly - Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions 8
  • 9. Content - .Net Managed Code / Methods - Machine instructions in MSIL format and located in Assemblies will be executed by the CLR, will have the following intrinsic advantages, Memory management to prevent memory leaks in the program code, Thread execution, Code safety verification, Compilation, Unmanaged Code / Methods - Unmanaged codes are the instructions, which are targeted for specific platforms. Unmanaged code will exist in any of the format, A code instructions in managed C++ with “#pragma unmanaged” COM/COM+ Components Win32 Dlls/System Dlls As these codes are in native format of OS, these instructions will be executed faster compared with JIT compilation and execution of Managed code 9
  • 10. Content - What is DLL HELL in .NET 10 1. I have 2 applications, A1 and A2 installed on my computer. 2. Both of these applications use shared assembly shared.dll 3. Now, I have a latest version of Application - A2 available on the internet. 4. I download the latest version of A2 and install it on my machine. 5. This new installation has over written Shared.dll, which is also used by Application - A1. 6. Application - A2 works fine, but A1 fails to work, because the newly installed Shared.dll is not backward compatible. So, DLL HELL is a problem where one application will install a new version of the shared component that is not backward compatible with the version already on the machine, causing all the other existing applications that rely on the shared component to break. With .NET versioning we donot have DLL HELL problem any more.
  • 11. Content - How is the DLL HELL problem solved in .NET 11 In dot net all the shared assemblies are usually in the GAC. GAC stands for Global Assembly Cache. The path for GAC is C:[OperatingSystemDirectory]assembly. For example on my computer the path is C:WINDOWSassembly. The image below shows the shared assemblies in the GAC. Only strong named assemblies can be copied into GAC. Strong named assemblies in .NET has 4 pieces in its name as listed below. 1. Simple Textual Name 2. Version Number 3. Culture 4. Public Key Token All these four pieces put together, is called as the fully qualified name of the assembly. In the GAC image above Accessibility assembly has a version of 2.0.0.0.
  • 12. Content - How is the DLL HELL problem solved in .NET 12Copyright©Sharma. All rights reserved. Now consider the example below: 1. I have 2 applications, Application - A1 and Application - A2 which relies on the shared assembly Accessibility.dll (Version 2.0.0.0) as shown in the image below. 2. Now, I have a latest version of Application - A2 available on the internet. 3. I download the latest version of A2 and install it on my machine. 4. This new installation copies a newer version of Accessibility.dll into the GAC with version 3.0.0.0. 5. So, in the GAC we now have 2 versions of Accessibility.dll. 6. Application - A1 continues to use Accessibility.dll (version 2.0.0.0) and Application - A2 uses Accessibility.dll (version 3.0.0.0) 7. So, now the assemblies are able to reside side by side in the GAC. For this reason dot net assemblies are also said to be supporting side by side execution. If you can improve this answer further, please feel free to do so by submitting the form below. Thank you very much for your contribution.
  • 13. Content – C# Language Fundamentals 13Copyright©Sharma. All rights reserved. What is C# C# (pronounced "see sharp" or "C Sharp") is one of many .NET programming languages. It is object-oriented and allows you to build reusable components for a wide variety of application types Microsoft introduced C# on June 26th, 2000 and it became a v1.0 product on Feb 13th 2002. C# is an evolution of the C and C++ family of languages. However, it borrows features from other programming languages, such as Delphi and Java. If you look at the most basic syntax of both C# and Java, the code looks very similar, but then again, the code looks a lot like C++ too, which is intentional. Developers often ask questions about why C# supports certain features or works in a certain way. The answer is often rooted in it's C++ heritage. How Does a C# Application Run? An important point is that C# is a "managed" language, meaning that it requires the .NET Common Language Runtime (CLR) to execute. Essentially, as an application that is written in C# executes, the CLR is managing memory, performing garbage collection, handling exceptions, and providing many more services that you, as a developer, don't have to write code for. The C# compiler produces Intermediate Language (IL) , rather than machine language, and the CLR understands IL. When the CLR sees the IL, it Just-In-Time (JIT) compiles it, method by method, into compiled machine code in memory and executes it. As mentiond previously, the CLR manages the code as it executes. Because C# requires the CLR, you must have the CLR installed on your system. All new Windows operating systems ship with a version of the CLR and it is available via Windows Update for older systems. The CLR is part of the .NET, so if you see updates for the .NET Framework Runtime, it contains the CLR and .NET Framework Class Library (FCL). It follows that if you copy your C# application to another machine, then that machine must have the CLR installed too.
  • 14. Content – C# Language Fundamentals 14Copyright©Sharma. All rights reserved.
  • 15. Content – C# Language Fundamentals 15Copyright©Sharma. All rights reserved. Program Structure Namespaces Contain types and other namespaces Type declarations Classes, structs, interfaces, enums, and delegates Members Constants, fields, methods, properties, indexers, events, operators, constructors, destructors Organization No header files, code written “in-line” No declaration order dependence
  • 16. Content – C# Language Fundamentals 16Copyright©Sharma. All rights reserved. A Simple Welcome Program: Welcome.cs // Namespace Declaration using System; // Program start class class WelcomeCSS { // Main begins program execution. static void Main() { // Write to console Console.WriteLine("Welcome to the C# Station Tutorial!"); } }
  • 17. Content – C# Language Fundamentals Constants & Variables "Variables" are simply storage locations for data. You can place data into them and retrieve their contents as part of a C# expression. The interpretation of the data in a variable is controlled through "Types". C# is a "Strongly Typed" language. Thus all operations on variables are performed with consideration of what the variable's "Type" is. There are rules that define what operations are legal in order to maintain the integrity of the data you put in a variable. The C# simple types consist of the Boolean type and three numeric types - Integrals, Floating Point, Decimal, and String. Constants are very similar to variables. The main difference is that the value contained in memory cannot be changed once the constant is declared. When you declare a constant its value is also specified and this value cannot be changed during program execution. 17Copyright©Sharma. All rights reserved.
  • 18. Content – C# Language Data Types The Boolean Type Boolean types are declared using the keyword, bool. They have two values: true or false. In other languages, such as C and C++, boolean conditions can be satisfied where 0 means false and anything else means true. However, in C# the only values that satisfy a boolean condition is true and false, which are official keywords. using System; class Booleans { public static void Main() { bool content = true; bool noContent = false; Console.WriteLine("It is {0} that C# Station provides C# programming language content.", content); Console.WriteLine("The statement above is not {0}.", noContent); } } 18Copyright©Sharma. All rights reserved.
  • 19. Content – C# Language Data Types Integral Types In C#, an integral is a category of types. For anyone confused because the word Integral sounds like a mathematical term, from the perspective of C# programming, these are actually defined as Integral types in the C# programming language specification. They are whole numbers, either signed or unsigned, and the char type. The char type is a Unicode character, as defined by the Unicode Standard. 19Copyright©Sharma. All rights reserved. Type Size (in bits) Range sbyte 8 -128 to 127 byte 8 0 to 255 short 16 -32768 to 32767 ushort 16 0 to 65535 int 32 -2147483648 to 2147483647 uint 32 0 to 4294967295 long 64 -9223372036854775808 to 9223372036854775807 ulong 64 0 to 18446744073709551615 char 16 0 to 65535
  • 20. Content – C# Language Data Types Floating Point and Decimal Types A C# floating point type is either a float or double. They are used any time you need to represent a real number, as defined by IEEE 754. For more information on IEEE 754, visit the IEEE Web Site. Decimal types should be used when representing financial or money values. The Table shows the floating point and decimal types, their size, precision, and range 20Copyright©Sharma. All rights reserved. Type Size (in bits) precision Range float 32 7 digits 1.5 x 10-45 to 3.4 x 1038 double 64 15-16 digits 5.0 x 10-324 to 1.7 x 10308 decimal 128 28-29 decimal places 1.0 x 10-28 to 7.9 x 1028
  • 21. Content – C# Language Data Types The string Type A string is a sequence of text characters. You typically create a string with a string literal, enclosed in quotes: "This is an example of a string”. Some characters aren't printable, but you still need to use them in strings. Therefore, C# has a special syntax where characters can be escaped to represent non-printable characters. For example, it is common to use newlines in text, which is represented by the 'n' char. The backslash, '', represents the escape. When preceded by the escape character, the 'n' is no longer interpreted as an alphabetical character, but now represents a newline. 21Copyright©Sharma. All rights reserved. Escape Sequence Meaning ' Single Quote " Double Quote Backslash 0 Null, not the same as the C# null value a Bell b Backspace f form Feed n Newline r Carriage Return t Horizontal Tab v Vertical Tab
  • 22. Content – C# Operators Results are computed by building expressions. These expressions are built by combining variables and operators together into statements. The following table describes the allowable operators, their precedence, and associativity. 22Copyright©Sharma. All rights reserved. Category (by precedence) Operator(s) Associativity Unary + - ! ~ ++x --x (T)x right Multiplicative * / % left Additive + - left Shift << >> left Relational < > <= >= is as left Equality == != right Logical AND & left Logical XOR ^ left Logical OR | left Conditional AND && left Conditional OR || left Null Coalescing ?? left Ternary ?: right Assignment = *= /= %= += - = <<= >>= &= ^= |= => right
  • 23. Content – C# Operators Unary Operators: Unary.cs using System; class Unary { public static void Main() { int unary = 0; int preIncrement; int preDecrement; int postIncrement; int postDecrement; int positive; int negative; sbyte bitNot; bool logNot; preIncrement = ++unary; Console.WriteLine("pre-Increment: {0}", preIncrement); preDecrement = --unary; Console.WriteLine("pre-Decrement: {0}", preDecrement); postDecrement = unary--; Console.WriteLine("Post-Decrement: {0}", postDecrement); postIncrement = unary++; Console.WriteLine("Post-Increment: {0}", postIncrement); Console.WriteLine("Final Value of Unary: {0}", unary); positive = -postIncrement; Console.WriteLine("Positive: {0}", positive); negative = +postIncrement; Console.WriteLine("Negative: {0}", negative); bitNot = 0; bitNot = (sbyte)(~bitNot); Console.WriteLine("Bitwise Not: {0}", bitNot); logNot = false; logNot = !logNot; Console.WriteLine("Logical Not: {0}", logNot); } } 23Copyright©Sharma. All rights reserved. Output pre-Increment: 1 pre-Decrement 0 Post-Decrement: 0 Post-Increment: -1 Final Value of Unary: 0 Positive: 1 Negative: -1 Bitwise Not: -1 Logical Not: true
  • 24. Content – C# Keywords 24 Copyright©Sharma. All rights reserved. abstract event new struct as explicit null switch base extern object this bool false operator throw break finally out true byte fixed override try case float params typeof catch for private uint char foreach protected ulong checked goto public unchecked class if readonly unsafe const implicit ref ushort continue in return using decimal int sbyte virtual default interface sealed volatile delegate internal short void do is sizeof while double lock stackalloc else long static enum namespace string Keywords are predefined reserved identifiers that have special meanings to the compiler. They cannot be used as identifiers in your program unless they include @ as a prefix. For example, @if is a legal identifier but if is not because it is a keyword.
  • 25. Content – C# Type Casting 25 Copyright©Sharma. All rights reserved. Typecasting is a concept of converting one datatype into another datatype C#.net supports 2 types of type casting 1)Implicit Type casting 2)Explicit Type casting 1) IMPLICIT TYPE CASTING Converting from lower to higher type is called as implicit type casting. It is under control of clr Ex: int i = 10; long l = i; 2) EXPLICIT TYPE CASTING Converting from Higher to Lower type is called as explicit type casting. It is under control of programmer Ex: int i=10; byte b = (byte) i;
  • 26. Content – C# Type Casting continued.. 26 Copyright©Sharma. All rights reserved. C# SUPPORTS 4 TYPES OF EXPLICIT TYPECASTING Type:1 (C++ style of type casting) int i=10; byte b = (byte) i; Type:2 (Converting) int i=10; char c = Convert.ToChar(i); Type:3 (Parsing) In c# all the predefined datatypes are structures. They contain set of methods. They are 1) ToString() 2) Parse() 3) Minvalue() 4) MaxValue() Ex: string s1=”10”; string s1=”20”; int a = int.Parse(s1); int b = int.Parse(s2); int c = a + b; MessageBox.Show(c.ToString()); Type:4 (Boxing and UnBoxing) Converting from Value types into Reference Types are called as Boxing and Converting from Reference Types into Value Types are called UnBoxing. Ex: int a = 10; string st = a.ToString(); //boxing int b = Convert.ToInt32(st); //unboxing MessageBox.Show(b);
  • 27. Content – C# Statements 27 Copyright©Sharma. All rights reserved. Statements are program instructions. Except as described, statements are executed in sequence. C# has the following categories of statements. Category C# keywords Selection statements if, else, switch, case Iteration statements do, for, foreach, in, while Jump statements break, continue, default, goto, return Exception handling statements throw, try-catch, try-finally, try-catch-finally Checked and unchecked checked, unchecked fixed Statement fixed lock Statement lock
  • 28. Content – C# Selection Statements 28 Copyright©Sharma. All rights reserved. The if statement selects a statement for execution based on the value of a Boolean expression. It takes the following form: if (expression) { statement1 } Else { statement2 }
  • 29. Content – C# Selection Statements 29 Copyright©Sharma. All rights reserved. switch (expression) { case constant-expression: statement jump-statement [default: statement jump-statement] } The switch statement is a control statement that handles multiple selections by passing control to one of the case statements within its body. It takes the following form:
  • 30. Content – C# Iteration Statements 30 Copyright©Sharma. All rights reserved. You can create loops by using the iteration statements. Iteration statements cause embedded statements to be executed a number of times, subject to the loop-termination criteria. These statements are executed in order, except when a jump statement is encountered. The do statement executes a statement or a block of statements repeatedly until a specified expression evaluates to false. It takes the following form: do { statement } while (expression);
  • 31. Content – C# Iteration Statements 31 Copyright©Sharma. All rights reserved. You can create loops by using the iteration statements. Iteration statements cause embedded statements to be executed a number of times, subject to the loop-termination criteria. These statements are executed in order, except when a jump statement is encountered. The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false. It takes the following form: for ([initializers]; [expression]; [iterators]) { statement }
  • 32. Content – C# Iteration Statements 32 Copyright©Sharma. All rights reserved. You can create loops by using the iteration statements. Iteration statements cause embedded statements to be executed a number of times, subject to the loop-termination criteria. These statements are executed in order, except when a jump statement is encountered. The while statement executes a statement or a block of statements until a specified expression evaluates to false. It takes the following form: while (expression) { Statement }
  • 33. Content – C# Statements & Comments Statements and Comments Case sensitive (myVar != MyVar) Statement delimiter is semicolon ; Block delimiter is curly brackets { } Single line comment is // Block comment is /* */ Save block comments for debugging! 33Copyright©Sharma. All rights reserved.
  • 34. Content – C# Arrays Array in the programming are required to do the following: 1) To reduce overhead the system 2) To reduce complexity in the program •Arrays will reduce the overhead of the system By allocating sequential memory and Arrays will reduce the complexity by storing many values with a single name •Internally the system will automatically convert each Array element into the form of an object. It means, according to the system an array is the collection of objects •In c# Arrays are references to store similar type dynamic values. That means for this reference we should allocate the memory dynamically using new operator. 34Copyright©Sharma. All rights reserved.
  • 35. • The variables we have been working with so far have only been able to hold one value at a time • Example: int lotteryNumber1 = 1; int lotteryNumber2 = 2; int lotteryNumber3 = 3; : • An Array allows you to use just one identifying name that refers to lots of values Why use Arrays?
  • 36. 1. Declaration: • int[] lotteryNumbers; • float[] myFloatValues; • string[] myStrings; 2. Size of array: • lotteryNumbers = new int[4]; • myFloatValues = new float[10]; • myStrings = new string[5]; How to setup an Array
  • 37. Declaration and setting the size in one line • int[] lotteryNumbers = new int[4]; • float[] myFloatValues = new float[10]; • string[] myStrings = new string[5];
  • 38. arrayName[position] = arrayValue; int[] lotteryNumbers = new int[4]; lotteryNumbers[0] = 1; // first array lotteryNumbers[1] = 2; lotteryNumbers[2] = 3; lotteryNumbers[3] = 4; // last (4th) array Assigning values
  • 39. int[] lotteryNumbers = new int[4]; lotteryNumbers[0] = 1; lotteryNumbers[1] = 2; lotteryNumbers[2] = 3; lotteryNumbers[3] = 4; First index is ZERO
  • 40. int[] lotteryNumbers = new int[4]; lotteryNumbers[0] = 1; lotteryNumbers[1] = 2; lotteryNumbers[2] = 3; lotteryNumbers[3] = 4; Last index is (SIZE -1)
  • 41. int[] lotteryNumbers = new int[4]; lotteryNumbers[0] = 1; lotteryNumbers[1] = 2; lotteryNumbers[2] = 3; lotteryNumbers[3] = 4; Total number of array = SIZE
  • 42. int[] lotteryNumbers = new int[4] {1, 2, 3, 4}; Declare, Set Array Size and Assign Values in one line Declare
  • 43. int[] lotteryNumbers = new int[4] {1, 2, 3, 4}; Set Size of Array
  • 44. int[] lotteryNumbers = new int[4] {1, 2, 3, 4}; Assign values
  • 45. To loop through the following array: lotteryNumbers[0] lotteryNumbers[1] lotteryNumbers[2] lotteryNumbers[3] for (int i = 0; i != lotteryNumbers.Length; i++) { lotteryNumber[i] ….. // not complete } Arrays and Loops
  • 46. for (int i = 0; i != lotteryNumbers.Length; i++) { lotteryNumber[i] ….. // not complete } starts from 0 The first index is ZERO
  • 47. for (int i = 0; i != lotteryNumbers.Length; i++) { lotteryNumber[i] ….. // not complete } Length is equal to the SIZE of array The last index should be (Length – 1)
  • 48. for (int i = 0; i != lotteryNumbers.Length; i++) { lotteryNumber[i] ….. // not complete } i < lotteryNumers.Length
  • 49. for (int i = 0; i != lotteryNumbers.Length; i++) { lotteryNumber[i] ….. // not complete } i <= lotteryNumers.Length -1
  • 50. Content – OOP’s in C# Programming approaches We have 2 types of programming approaches to develop the projects 1. Procedure Oriented Approach 2. Object Oriented Approach Procedure Oriented Approach: In Procedure Oriented Approach Main Task is divided into subtasks. Each task represented in the form of functions or procedures. So a C program generally contains several functions which are called and controlled from main() function. This approach is called Procedure Oriented Approach. The languages which follows Procedure Oriented Approach that languages are called Procedure Oriented Language. Ex: C, Pascal, Fortran etc., Object Oriented Approach: In Object Oriented Approach Main Task is divided into several modules. Modules are represented as Classes. Each class can perform some tasks for which several methods are written in a class. This approach is called Object Oriented Approach. A class is a module which itself contains data and methods to achieve the task. Ex: c++, Java, smalltalk, All .Net languages etc., programming systems We have 3 types of programming systems to develop the software based on their properties or their characteristics. 1) POPS (PROCESS ORIENTED PROGRAMMING SYSTEM) 2) OBPS (OBJECT BASED PROGRAMMING SYSTEM) 3) OOPS (OBJECT ORIENTED PROGRAMMING SYSTEM) 50Copyright©Sharma. All rights reserved.
  • 51. Content – OOP’s in C# OOPS CHARACTERISTICS 1. Class 2. Object 3. Data Hiding 4. Data Abstraction 5. Encapsulation 6. Inheritance 7. Polymorphism 1) Class: A group of Attributes with its relative behavior kept into a single unit with permitted accessibilities known as a CLASS. A class is a model or blueprint for creating objects. *A class is a user defined datatype in oops to define our own datatypes * class is a blueprint for its objects which supports to create any no. of instances to store specific information * Class is a logical Entity which allows to keep attributes with its related methods in a single unit with authorized accessing, with security * Class allows 3 types of top level access specifiers to secure its members. They are private, public and protected. But in C# 5 types of access specifiers are available. They are private, public, protected, internal and internal protected. 51Copyright©Sharma. All rights reserved.
  • 52. Content – OOP’s in C# 2) Object: Object is a reference of its class blueprint. Which stores a specific data to perform specific operations. * Object has a physical reality. * Members of an object are invoked with ‘.’ operator. Syntax <class_name> <ref_var> = new <class_Name>([args..]); Ex: Emp e = new Emp(); Object Properties 1. Its state (attributes) 2. Its behavior (methods) 3. Its identity (hashcode) //address of the object 3) Data Hiding: Doesn’t provide the access attributes directly to others. Private keyword hides the attributes and does not allow access to others. Ex: private int EmpNo; 4) Data Abstraction: Doesn’t provide to access the methods directly to others and hiding the implementation of the code. Ex: private float calcNetSal() { //statements } used in the operation. 52Copyright©Sharma. All rights reserved.
  • 53. Content – OOP’s in C# 5) Encapsulation: In the class declared variables called as attributes/Data Members/status and defined functions are called as Member Functions/ behaviors. These both are called as Members. These members are binding into a single class is called Data Encapsulation. Encapsulation is a mechanism where the data (variables) and the code(methods) that act on the data will bind together. 6) Inheritance: Inheritance is the process by which objects can acquire the properties of objects of other class. In OOP, inheritance provides reusability, like adding additional features to an existing class without modifying it. This is achieved by deriving a new class from the existing one. The new class will have combined features of both the classes. 7) Polymorphism: Polymorphism came from the two greek words ‘poly’ and ‘morphos’. Poly means many and morphos means forms. The ability to exist in different forms is called polymorphism. An Operation may exhibit different behaviors in different instances. The behavior depends on the datatypes Advantages of OOPS 1. OOP provides a clear modular structure for programs which makes it good for dealing abstract datatypes where implementation details are hidden and the unit has a clearly defined interface 2. OOP makes it easy to maintain and modify existing code as new objects can created with small differences to existing ones 3. OOP provides a good framework for code libraries where supplied software components can be easily adapted and modified by the programmer. This is particularly useful for developing graphical user interfaces 53Copyright©Sharma. All rights reserved.
  • 54. Content – Polymorphism Polymorphism came from the two greek words ‘poly’ and ‘morphos’. Poly means many and morphos means forms. If the same method perform different tasks, then that method is said to exhibit(show) polymorphism. If a method performs several tasks, it is called Polymorphism. Polymorphism also called as Overloading Types of OverLoading C# supports 3 types of Overloading 1. Function Overloading 2. Constructor Overloading 3. Operator Overloading 54Copyright©Sharma. All rights reserved.
  • 55. Content – Polymorphism Constructors and Destructors 1. Constructors is a special type of function which will be executed automatically while an object is creating 2. Destructor is special type of function which will be executed automatically while an object is destroying 3. Constructors name must be same as class name without return type 4. Destructors name must be same as class name by preceding a ‘~‘(tild) operator and without return type and access specifier 5. Constructors are overloadable but destructors are not overloadable 6. Generally constructors will be used to initialize the variables to open the connections etc. 7. Destructors will be used to close the connections or deallocate the memory 55Copyright©Sharma. All rights reserved.
  • 56. Content – Inheritance Inheritance is a concept where new classes can be produced from existing classes. The newly created class acquires all the features of existing class from where it is derived. The newly constructed class is called Derived and already existing class is called Base. Syntax: class Base { //base class members } class Derived : Base { //derived class members } Deriving new classes from existing classes such that the new classes acquire all the features of existing classes is called Inheritance. There are to ways in .NET to share the existing data 1. Aggregation 2. Inheritance Aggregation: Creating an instance of a class to use the code in another class known as Aggregation. Through aggregation we can reuse/execute the code only. It said object-to –object communication. This relationship is called Has-A relationship. Inheritance: Defining a new class is-a type of existing class to reuse the data code without redefining. The inheritance makes the family of classes with relations. This relationship is called Is-A relationship. 56Copyright©Sharma. All rights reserved.
  • 61. Content – Properties ,Indexers , Static Members Properties The properties are used to control the behavior of an object like methods, but they can be accessible like variables. A property can have 2 accessors 1)Get 2)Set * If a property contain only “SET” accessor, then this property is called as WRITEONLY property. •If a property contain only “GET” accessor, then this property is called as READONLY property. INDEXERS The indexers of a class allows accessing its objects like an Array. The indexers design is very similar to property designing i.e. an indexer can contain one get accessor and one set accessor. Static Variable If we define the variables as static that variables are called as static variables. That static variables data will be treated as global. If we define the variables of the class as static that variables are called Class variables. That class variables data can be shared to all the objects of that class. We can access the static variables directly using class name. Ex: static int a; * To make variables as a global for all its related class objects that variable should be defined as static. * The static variable defines only once, the moment we call the first method of the class, either constructor or static method. 61Copyright©Sharma. All rights reserved.
  • 62. Content – Types of Classes Types of classes In DOTNET six types of classes are available 1. General Classes 2. Static Classes a) Sealed Classes b) Abstract Classes I. Partial Abstract(Abstract Classes) II. Fully Abstract(Interfaces) 3. Partial Classes 4. Generic Classes Sealed Classes: 1. Sealed is a keyword, sealed classes are not inheritable, sealed methods are not overridable. Whenever a class is providing full functionality then recommended to declare that class as sealed. 2. The sealed modifier is used to prevent derivation from a class. An error occurs if a sealed class is specified as the base class of another class. A sealed class can’t also be an abstract class. Sealed Methods In c# a method can be declared as sealed. However when we override a method in a derived class, we can declare the overrided method as sealed by declaring it as sealed, We can avoid further overriding of this method. 62Copyright©Sharma. All rights reserved.
  • 63. Content – Types of Classes Abstract Classes If we define the method without definition that method is called Abstract method. If a class contain even a single abstract method, then this class is called as an Abstract Class. Abstract class can contain Concrete methods and also Abstract methods. So this class is called Partial Abstract class. We can’t create the objects to Abstract Class. Which class will implement the abstract class methods only that class will be instantiated. Abstract is a behavioral modifier which is applicable to methods and classes. A method without body is known as Abstract Method. A class which contains 0 or more abstract methods that class is called Abstract Class. We can’t create the objects to Abstract class. Note: An abstract class can contain abstract methods as well as concrete methods. It is the combination of abstract methods and concrete methods. 63Copyright©Sharma. All rights reserved.
  • 64. Content – Interfaces An interface contains only abstract methods which are all incomplete methods. So it is not possible to create an object to an interface. In this case, we can create separate classes where we can implement all the methods of the interface. These classes are called implementation classes. Since, implementation classes will have all the methods with the body, it is possible to create objects to the implementation classes. The multiple inheritance is possible in .NET through the interfaces. i.e., one class can inherit only one class and can implement any no. of interfaces. Interface is a pure abstract class which contains pure abstract methods. Ex: using System; public interface MyInterface { void func1(); void func2(); }; class MyClass : MyInterface { public void func1() { MessageBox.Show("func1()"); } public void func2() { MessageBox.Show("func2()"); } }; private void button1_Click(object sender, EventArgs e) { MyClass mc = new MyClass(); mc.func1(); mc.func2(); } 64Copyright©Sharma. All rights reserved. Note: Interface methods must be implemented in sub classes as public The interface can refer the implementation class object
  • 65. Content – Namespaces 65Copyright©Sharma. All rights reserved. A namespace is designed for providing a way to keep one set of names separate from another. The class names declared in one namespace will not conflict with the same class names declared in another. Defining a Namespace A namespace definition begins with the keyword namespace followed by the namespace name as follows: namespace namespace_name { // code declarations } To call the namespace-enabled version of either function or variable, prepend the namespace name as follows: namespace_name.item_name;
  • 67. Content – Exception Handling A Developer may also commit several errors while designing the project or developing the code. These errors are also called ‘bugs’ and the process of removing them is called ‘debugging’. Types of Errors There are basically 2 types of errors in c# program: 1. Compile-time errors 2. Run-time errors 1) Compile-time errors: These errors are syntactical errors found in the code, due to which a program fails to compile. For example, forgetting a semicolon at the end of the statement, or writing a statement without proper syntax will result in compile-time error. 2) Run-time errors: These errors represent inefficiency of the compiler system to execute a particular statement. The errors which doesn’t understand by the compiler that errors displays only at the time of runtime, these errors are detected by the CLR. Importance of Exception Handling To avoid the abnormal termination in a program we use Exception handlers that are try, catch, throw, finally. This is called Exception Handling. If the program has any runtime errors CLR proprogates an Exception during execution. This exception is in the form of object. If we didn’t handle the propagated Exceptional objects immediately CLR terminates the application by displaying the proper message of the raised exception. Exceptions which are not checked at compilation time which may rise in runtime by CLR known as UnChecked Exceptions. 67Copyright©Sharma. All rights reserved.
  • 68. Content – Exception Handling 68Copyright©Sharma. All rights reserved. Exceptions provide a way to transfer control from one part of a program to another. C# exception handling is built upon four keywords: try, catch, finally and throw. try: A try block identifies a block of code for which particular exceptions will be activated. It's 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.
  • 69. Content – Exception Handling 69Copyright©Sharma. All rights reserved.
  • 70. Content – Exception Handling 70Copyright©Sharma. All rights reserved.
  • 71. Content – Exception Handling 71Copyright©Sharma. All rights reserved.
  • 72. Content – ASP.Net ASP.NET provides services to allow the creation, deployment, and execution of Web Applications and Web Services Like ASP, ASP.NET is a server-side technology Web Applications are built using Web Forms Web Forms are designed to make building web-based applications as easy as building Visual Basic applications 72Copyright©Sharma. All rights reserved.
  • 73. Content – ASP.Net Key Features: Web Forms Web Services Built on .NET Framework Simple programming model Maintains page state Multibrowser support XCOPY deployment XML configuration Complete object model Session management Caching Debugging Extensibility Separation of code and UI Security ASPX, ASP side by side Simplified form validation Cookieless sessions 73Copyright©Sharma. All rights reserved.
  • 74. Content – ASP.Net Page Syntax The most basic page is just static text Any HTML page can be renamed .aspx Pages may contain: Directives: <%@ Page Language=“VB” %> Server controls: <asp:Button runat=“server”> Code blocks: <script runat=“server”>…</script> Data bind expressions: <%# %> Server side comments: <%-- --%> Render code: <%= %> and <% %> Use is discouraged; use <script runat=server> with code in event handlers instead 74Copyright©Sharma. All rights reserved.
  • 75. Content – ASP.Net ASP.Net Page Life Cycle: When a page is requested, it is loaded into the server memory, processed and sent to the browser. Then it is unloaded from the memory. At each of this steps, methods and events are available, which could be overridden according to the need of the application. In other words, you can write your own code to override the default code. The Page class creates a hierarchical tree of all the controls on the page. All the components on the page, except the directives are part of this control tree. You can see the control tree by adding trace= "true" to the Page directive. We will cover page directives and tracing under 'directives' and 'error handling'. The page life cycle phases are: •Initialization •Instantiation of the controls on the page •Restoration and maintenance of the state •Execution of the event handler codes •Page rendering Understanding the page cycle helps in writing codes for making some specific thing happen at any stage of the page life cycle. It also helps in writing custom controls and initializing them at right time, populate their properties with view-state data and run control behavior code. 75Copyright©Sharma. All rights reserved.
  • 77. Content – ASP.Net Following are the different stages of an ASP.Net page: Page request . when ASP.Net gets a page request, it decides whether to parse and compile the page or there would be a cached version of the page; accordingly the response is sent Starting of page life cycle . at this stage, the Request and Response objects are set. If the request is an old request or post back, the IsPostBack property of the page is set to true. The UICulture property of the page is also set. Page initialization . at this stage, the controls on the page are assigned unique ID by setting the UniqueID property and themes are applied. For a new request postback data is loaded and the control properties are restored to the view-state values. Page load . at this stage, control properties are set using the view state and control state values. Validation . Validate method of the validation control is called and if it runs successfully, the IsValid property of the page is set to true. Postback event handling . if the request is a postback (old request), the related event handler is called. Page rendering . at this stage, view state for the page and all controls are saved. The page calls the Render method for each control and the output of rendering is written to the OutputStream class of the Page's Response property. Unload . the rendered page is sent to the client and page properties, such as Response and Request are unloaded and all cleanup done. 77Copyright©Sharma. All rights reserved.
  • 78. Content – ASP.Net Page Events 78Copyright©Sharma. All rights reserved.
  • 80. Content – ASP.Net Controls and Control Events HTML Server Intrinsic controls List controls Rich controls Validation controls Control Data Binding 80Copyright©Sharma. All rights reserved.
  • 81. Content – ASP.Net Controls 81Copyright©Sharma. All rights reserved.
  • 82. Content – ASP.Net Controls 82Copyright©Sharma. All rights reserved.
  • 83. Content – ASP.Net Controls 83Copyright©Sharma. All rights reserved.
  • 84. Content – ASP.Net Controls 84Copyright©Sharma. All rights reserved.
  • 85. Content – ASP.Net Controls 85Copyright©Sharma. All rights reserved.
  • 86. Content – ASP.Net Controls 86Copyright©Sharma. All rights reserved.
  • 87. Content – ASP.Net - File Uploading 87Copyright©Sharma. All rights reserved.
  • 88. Content – ASP.Net - File Uploading 88Copyright©Sharma. All rights reserved.
  • 89. Content – ASP.Net – AdRotator 89Copyright©Sharma. All rights reserved. <asp:AdRotator runat = "server" AdvertisementFile = "adfile.xml" Target = "_blank" /> The AdRotator control randomly selects banner graphics from a list, which is specified in an external XML schedule file. This external XML schedule file is called the advertisement file. The AdRotator control allows you to specify the advertisement file and the type of window that the link should follow in AdvertisementFile and Target property respectively. The basic syntax of adding an AdRotator is as follows: Before going into details of the AdRotator control and its properties, let us look into the construction of the advertisement file.
  • 90. Content – ASP.Net – AdRotator 90Copyright©Sharma. All rights reserved.
  • 91. Content – ASP.Net – Validators 91Copyright©Sharma. All rights reserved. ASP.Net validation controls validate the user input data to ensure that useless, unauthenticated or contradictory data don’t get stored. ASP.Net provides the following validation controls: 1. RequiredFieldValidator 2. RangeValidator 3. CompareValidator 4. RegularExpressionValidator 5. CustomValidator 6. ValidationSummary
  • 92. Content – ASP.Net – Validators 92Copyright©Sharma. All rights reserved.
  • 93. Content – ASP.Net – Validators 93Copyright©Sharma. All rights reserved.
  • 94. Content – ASP.Net – Validators 94Copyright©Sharma. All rights reserved. The RegularExpressionValidator The RegularExpressionValidator allows validating the input text by matching against a pattern against a regular expression. The regular expression is set in the ValidationExpression property. The following table summarizes the commonly used syntax constructs for regular expressions:
  • 95. Content – ASP.Net – Validators 95Copyright©Sharma. All rights reserved.
  • 96. Content – ASP.Net – Validators 96Copyright©Sharma. All rights reserved.
  • 97. Content – ASP.Net - Managing State Maintaining State View state Control state Hidden fields Cookies Query strings Application state Session state Profile Properties 97Copyright©Sharma. All rights reserved.
  • 98. ADO.NET Agenda • ADO versus ADO.NET • ADO.NET Architecture • Connection Object • Command Object • DataReader Object • DataAdapter Object • DataSet Object • DataView Object • Use ADO.NET to access data in an application
  • 99. ADO versus ADO.NET Feature ADO ADO.NET Primary Aim Client/server coupled Disconnected collection of data from data server Form of data in memory Uses RECORDSET object (contains one table) Uses DATASET object (contains one or more DATATABLE objects) Disconnected access Uses CONNECTION object and RECORDSET object with OLEDB Uses DATASETCOMMAND object with OLEDB Disconnected access across multi-tiers Uses COM to marshal RECORDSET Transfers DATASET object via XML. No data conversions required
  • 100. ADO versus ADO.NET (continued) Feature ADO ADO.NET XML capabilities XML aware XML is the native transfer medium for the objects Firewalls Firewalls block system-level COM marshalling XML flows through the firewall via HTTP Code Coupled to the language used, various implementation Managed code library – Uses Common Language Runtime, therefore, language agnostic
  • 101. Agenda • ADO versus ADO.NET • ADO.NET Architecture • Connection Object • Command Object • DataReader Object • DataAdapter Object • DataSet Object • DataView Object • Use ADO.NET to access data in an application
  • 103. ADO.NET Namespaces System.data Core namespace, defines types that represent data System.Data.Common Types shared between managed providers System.Data.OleDb Types that allow connection to OLE DB compliant data sources System.Data.SqlClient Types that are optimized to connect to Microsoft® SQL Server System.Data.SqlTypes Native data types in Microsoft® SQL Server
  • 104. Importing the ADO.NET Namespaces Needed to build a data access application • For OLE DB: Imports System.Data Imports System.Data.OleDB • For SQL Server: Imports System.Data Imports System.Data.SQLClient
  • 105. Agenda • ADO versus ADO.NET • ADO.NET Architecture • Connection Object • Command Object • DataReader Object • DataAdapter Object • DataSet Object • DataView Object • Use ADO.NET to access data in an application
  • 106. Connection object • Connects to databases. • Two provider-specific classes o SqlConnection o OleDbConnection. • Connections can be opened in two ways: o Explicitly by calling the Open method on the connection o Implicitly when using a DataAdapter. • Connections handle transactions
  • 107. Agenda • ADO versus ADO.NET • ADO.NET Architecture • Connection Object • Command Object • DataReader Object • DataAdapter Object • DataSet Object • DataView Object • Use ADO.NET to access data in an application
  • 108. Command Object • Information submitted to a database as a query via a Connection object • Two provider-specific classes o SqlCommand o OleDbCommand • Input and output parameters are supported, along with return values as part of the command syntax • Results are returned in the form of streams. Accessed by: o DataReader object o DataSet object via a DataAdapter
  • 109. Agenda • ADO versus ADO.NET • ADO.NET Architecture • Connection Object • Command Object • DataReader Object • DataAdapter Object • DataSet Object • DataView Object • Use ADO.NET to access data in an application
  • 110. DataReader Object • Provides methods and properties that deliver a forward-only stream of data rows from a data source • When a DataReader is used, parts of the ADO.NET model are cut out, providing faster and more efficient data access
  • 112. Agenda • ADO versus ADO.NET • ADO.NET Architecture • Connection Object • Command Object • DataReader Object • DataAdapter Object • DataSet Object • DataView Object • Use ADO.NET to access data in an application
  • 113. DataAdapter Object • Provides a set of methods and properties to retrieve and save data between a DataSet and its source data store • Allows the use of stored procedures • Connects to the database to fill the DataSet and also update the database
  • 114. Agenda • ADO versus ADO.NET • ADO.NET Architecture • Connection Object • Command Object • DataReader Object • DataAdapter Object • DataSet Object • DataView Object • Use ADO.NET to access data in an application
  • 115. DataSet Object • Replaces the ADO Recordset • Represents a cache of data that contains tables, columns, relationships, and constraints, just like a database • Regardless of where the source data comes from, data can all be placed into DataSet objects • Tracks changes that are made to the data it holds before updating the source data • DataSet are also fully XML-featured • Works with all current models of data storage: flat, relational, and hierarchical
  • 116. Agenda • ADO versus ADO.NET • ADO.NET Architecture • Connection Object • Command Object • DataReader Object • DataAdapter Object • DataSet Object • DataView Object • Use ADO.NET to access data in an application
  • 117. DataView Object • Provides methods and properties that enable UI objects such as a DataGrid to bind to a DataSet • A view of the data contained in the DataSet • Only used in conjunction with a DataSet
  • 118. Agenda • ADO versus ADO.NET • ADO.NET Architecture • Connection Object • Command Object • DataReader Object • DataAdapter Object • DataSet Object • DataView Object • Use ADO.NET to access data in an application
  • 119. Create Data Access Windows Form
  • 120. Create Multiple Table DataSet Example
  • 121. Summary • ADO versus ADO.NET • ADO.NET Architecture • Connection Object • Command Object • DataReader Object • DataAdapter Object • DataSet Object • DataView Object • Use ADO.NET to access data in an application
  • 122. Content – Webservices A simple definition: “a Web Service is an application component accessible over open protocols”. Web services evolved from previous technologies that served the same purpose such as RPC, ORPC (DCOM, CORBA and JAVA RMI). Web Services were intended to solve three main problems: Interoperability Firewall traversal Complexity 122Copyright©Sharma. All rights reserved.
  • 123. Content – Webservices A more precise definition: an application component that: Communicates via open protocols (HTTP, SMTP, etc.) Processes XML messages framed using SOAP Describes its messages using XML Schema Provides an endpoint description using WSDL Can be discovered using UDDI 123Copyright©Sharma. All rights reserved.
  • 124. Content – Webservices XML – eXtensible Markup Language – A uniform data representation and exchange mechanism. SOAP – Simple Object Access Protocol – A standard way for communication. UDDI – Universal Description, Discovery and Integration specification – A mechanism to register and locate WS based application. WSDL – Web Services Description Language – A standard meta language to described the services offered. 124Copyright©Sharma. All rights reserved.
  • 125. Content – Webservices Example: A buyer (which might be a simple client) is ordering goods from a seller service. The buyer finds the seller service by searching the UDDI directory. The seller service is a Web Service whose interface is defined using Web Services Description Language (WSDL). The buyer is invoking the order method on the seller service using Simple Object Access Protocol (SOAP) and the WSDL definition for the seller service. The buyer knows what to expect in the SOAP reply message because this is defined in the WSDL definition for the seller service. 125Copyright©Sharma. All rights reserved.
  • 126. Content – Webservices The Web Services architecture is based upon the interactions between three roles: Service provider Service registry Service requestor The interactions involve the: Publish operations Find operation Bind operations. The Web Services model follows the publish, find, and bind paradigm. 126Copyright©Sharma. All rights reserved.
  • 127. Content – Webservices XML XML stands for EXtensible Markup Language. XML is a markup language much like HTML. XML was designed to describe data. XML tags are not predefined. You must define your own tags. The prefect choice for enabling cross-platform data communication in Web Services. 127Copyright©Sharma. All rights reserved.
  • 128. Content – Webservices SOAP SOAP originally stood for "Simple Object Access Protocol" . Web Services expose useful functionality to Web users through a standard Web protocol called SOAP. Soap is an XML vocabulary standard to enable programs on separate computers to interact across any network. SOAP is a simple markup language for describing messages between applications. Soap uses mainly HTTP as a transport protocol. That is, HTTP message contains a SOAP message as its payload section. SOAP has three major characteristics: Extensibility – security and WS-routing are among the extensions under development. Neutrality - SOAP can be used over any transport protocol such as HTTP, SMTP or even TCP. Independent - SOAP allows for any programming model. 128Copyright©Sharma. All rights reserved.
  • 129. Content – Webservices A SOAP message is an ordinary XML document containing the following elements: A required Envelope element that identifies the XML document as a SOAP message. An optional Header element that contains header information. A required Body element that contains call and response information. An optional Fault element that provides information about errors that occurred while processing the message. SOAP uses HTTP as a transport protocol and hence can use HTTP security mainly HTTP over SSL. But, since SOAP can run over a number of application protocols (such as SMTP) security had to be considered. The WS-Security specification defines a complete encryption system. 129Copyright©Sharma. All rights reserved.
  • 130. Content – Webservices WSDL WSDL stands for Web Services Description Language. WSDL is an XML vocabulary for describing Web services. It allows developers to describe Web Services and their capabilities, in a standard manner. WSDL specifies what a request message must contain and what the response message will look like in unambiguous notation. In other words, it is a contract between the XML Web service and the client who wishes to use this service. In addition to describing message contents, WSDL defines where the service is available and what communications protocol is used to talk to the service. A WSDL document is just a simple XML document. It defines a web service using these major elements: port type - The operations performed by the web service. message - The messages used by the web service. types - The data types used by the web service. binding - The communication protocols used by the web service. 130Copyright©Sharma. All rights reserved.
  • 131. Content – Webservices UDDI UDDI stands for Universal Description, Discovery and Integration. UDDI is a directory for storing information about web services , like yellow pages. UDDI is a directory of web service interfaces described by WSDL. 131Copyright©Sharma. All rights reserved.
  • 132. FAQ - 1 Software development environments What are the different environments in your development process or development life cycle at your company? This is a general interview question and not very specific to ASP.NET. Usually, the interviewer asks this question to measure your understanding of the different environments and their role in software development. 132Copyright©Sharma. All rights reserved. 1. Development 2. QA 3. Staging 4. UAT (User Acceptance Testing) 5. Production 1. Development Environment - All the developers check in their current work into development environment. 2. QA (Quality Assurance) Environment - This is the environment, where testers (QA) test the application. QA cannot test on development environment, because developers are continuously checking in new code. So, if there is a bug, we don't know, if it's caused by the old or new code. In short, if development is going on in the same environment it would be difficult to keep up with the current state. There will be lot of confusion, if the developer is trying to fix in the same area as the tester is testing. Without development and QA environment being seperate their is no way to do proper testing. 3. Staging Environment - Many organisations, try to keep their staging environment as identical as possible to the actual production environment. The primary reason for this environment is to identify any deployment related issues. Also, if you are developing a B2B (Business to Business) application, you may be interfacing with other service provider systems. Many organisations, usually setup their staging environment to interface with the service providers as well, for complete end to end testing. 4. Production Environment - The actual live environment, that we use for day to day business. Note: In general, the code flows from Development => QA => Staging => Production
  • 133. FAQ – 2 Difference between EnableViewState and ViewStateMode properties 133Copyright©Sharma. All rights reserved. 1. Using EnableViewState property we only have 2 options We can turn off view state altogether, or Enable viewstate for the entire page and then turn it off on a control-by-control basis. 2. If you want to turn of ViewState for the entire page and only enable it for specific controls on the page, then we have to useViewStateMode property in conjunction with EnableViewState. 3. EnableViewState property only accepts true or false values and the default value is true, where as ViewStateMode property can have a value of - Enabled, Disabled and inherit. Inherit is the default value for ViewStateMode property. 4. ViewStateMode property is introduced in ASP.NET 4, where as EnableViewState exists from a long time. 5. If EnableViewState is to True, only then the ViewStateMode settings are applied, where as, if EnableViewState is set to False then the control will not save its view state, regardless of the ViewStateMode setting. In short if EnableViewState is set to False,ViewStateMode setting is not respected. 6. To disable view state for a page and to enable it for a specific control on the page, set the EnableViewState property of the page and the control to true, set the ViewStateMode property of the page to Disabled, and set the ViewStateMode property of the control to Enabled.
  • 134. FAQ – 3 ASP.NET Page is very slow. What will you do to make it fast 134Copyright©Sharma. All rights reserved. 1. Find out which is slow, is it the application or the database : If the page is executing SQL queries or stored procedures, run those on the database and check how long do they take to run. If the queries are taking most of the time, then you know you have to tune the queries for better performance. To tune the queries, there are several ways and I have listed some of them below. a) Check if there are indexes to help the query b) Select only the required columns, avoid Select *. c) Check if there is a possiblity to reduce the number of joins d) If possible use NO LOCK on your select statements e) Check if there are cursors and if you can replace them with joins 2. If the queries are running fast, then we know it is the application code that is causing the slowness. Isolate the page event that is causing the issue by turning tracing on. To turn tracing on, set Trace="true" in the page directive. Once you have tracing turned on you should see trace information at the bottom of the page as shown in the image below. In this case Page Load event is taking the maximum time. So we know, the code in Page_Load event is causing the issue. Once you look at the code, you should be able to nail down the issue.
  • 135. FAQ – 4 What are the best practices to follow to secure connection strings in an ASP.NET web application? 1. Always store connection strings in the site's Web.config file. Web.config is very secure. Users will not be able to access web.config from the browser. 2. Do not store connection strings as plain text. To help keep the connection to your database server secure, it is recommended that you encrypt connection string information in the configuration file. 3. Never store connection strings in an aspx page. 4. Never set connection strings as declarative properties of the SqlDataSource control or other data source controls.Why is "Connecting to SQL Server using Integrated Security" considered a best practice?Connecting to SQL Server using integrated security instead of using an explicit user name and password, helps avoid the possibility of the connection string being compromised and your user ID and password being exposed. 135Copyright©Sharma. All rights reserved.
  • 136. FAQ – 5 What is Script injection? A script injection attack attempts to send executable script to your application with the intent of having other users run it. A typical script injection attack sends script to a page that stores the script in a database, so that another user who views the data inadvertently runs the code. What is SQL injection? A SQL injection attack attempts to compromise your database by creating SQL commands that are executed instead of, or in addition to, the commands that you have built into your application. What are the best practices to keep in mind when accepting user input on a web application? 1. Always use validation controls whenever possible to limit user input to acceptable values. 2. Always check the IsValid property of the aspx page. Run the server side code only if the IsValid property value is true. A value of false means that one or more validation controls have failed a validation check. 3. Always perform server side validation irrespective of client side validation being performed or not. This will protect your web application even if the client has by passed the client side validation by disabling javascript in the web browser. 4. Also make sure to re validate user input in the business logic layer of your application. What are the steps to follow to avoid Script Injection attacks? 1. Encode user input with the HtmlEncode method. This method turns HTML into its text representation. 2. If you are using the GridView control with bound fields, set the BoundField object's HtmlEncode property to true. This causes the GridView control to encode user input when the row is in edit mode. What are the steps to follow to avoid SQL Injection attacks? Always use parameterized queries or stored procedures instead of creating SQL commands by concatenating strings together. 136Copyright©Sharma. All rights reserved.
  • 137. FAQ – 6 What are Master Pages in ASP.NET? or What is a Master Page? ASP.NET master pages allow you to create a consistent layout for the pages in your application. A single master page defines the look and feel and standard behavior that you want for all of the pages (or a group of pages) in your application. You can then create individual content pages that contain the content you want to display. When users request the content pages, they merge with the master page to produce output that combines the layout of the master page with the content from the content page. What are the 2 important parts of a master page? The following are the 2 important parts of a master page 1. The Master Page itself 2. One or more Content Pages Can Master Pages be nested? Yes, Master Pages be nested. What is the file extension for a Master Page? .master How do you identify a Master Page? The master page is identified by a special @ Master directive that replaces the @ Page directive that is used for ordinary .aspx pages. Can a Master Page have more than one ContentPlaceHolder? Yes, a Master Page can have more than one ContentPlaceHolder 137Copyright©Sharma. All rights reserved.
  • 138. FAQ – 7 What is Passport Authentication? Passport authentication identifies users via Microsoft Passport’s single sign-on service. Microsoft Passport is meant to provide Internet users with a single identity that they can use to visit a wide variety of Web sites that require authentication. Information about the user is available to your application through a profile that is stored with Microsoft. What are the advantages of Passport authentication? The advantages of Passport authentication are that the user doesn’t have to remember separate user names and passwords for various Web sites and that the user can maintain his or her profile information in a single location. Passport authentication also provides access to other Microsoft services, such as Passport Express Purchase. What is passport software development kit (passport SDK)? To use Passport authentication in your Web application, you must install the Passport SDK. The Passport SDK is free for preproduction development and testing. To deploy a site for public use, you must obtain an annual license from Microsoft. How does Passport authentication work? When a user accesses an application that implements Passport authentication, ASP.NET checks the user’s machine for a current passport authentication cookie. If none is found, ASP.NET directs the user to a Passport sign-on page. Once the user signs in, the Passport service authenticates the user, stores an authentication cookie on the user’s computer, and directs the user back to the originally requested Web page. What are the steps to follow to use Passport authentication? 1. Install the Passport SDK. Passport is not included with Visual Studio, although the .NET Framework does include classes for working with the Passport SDK once it is installed. 2. Set the application’s authentication mode to Passport in Web.config. Set authorization to deny unauthenticated users. 3. Use the PassportAuthentication_OnAuthenticate event to access the user’s Passport profile to identify and authorize the user. 4. Implement a sign-out procedure to remove Passport cookies from the user’s machine. Where is PassportAuthentication_OnAuthenticate event present? PassportAuthentication_OnAuthenticate event is present in Global.asax. 138Copyright©Sharma. All rights reserved.
  • 139. FAQ – 8 What is the advantage of using Forms authentication? The advantage of using Forms authentication is that users do not have to be member of a domain-based network to have access to your application. Another advantage is that many Web applications, particularly commercial sites where customers order products, want to have access to user information. Forms authentication makes these types of applications easier to create. List the steps to use Forms authentication in a web application? 1.Set the authentication mode in Web.config to Forms. 2.Create a Web form to collect logon information. 3.Create a file or database to store user names and passwords. 4.Write code to add new users to the user file or database. 5.Write code to authenticate users against the user file or database. What happens when someone accesses a Web application that uses Forms authentication? When someone accesses a Web application that uses Forms authentication, ASP.NET displays the logon Web form specified in Web.config. Once a user is authorized, ASP.NET issues an authorization certificate in the form of a cookie that persists for an amount of time specified by the authentication settings in Web.config. What is the difference between Windows authentication and Forms authentication? The difference between Windows authentication and Forms authentication is that in Forms authentication your application performs all the authentication and authorization tasks. You must create Web forms and write code to collect user names and passwords and to check those items against a list of authorized users. 139Copyright©Sharma. All rights reserved.
  • 140. FAQ – 9 What are ASP.NET Custom controls? Custom controls extend the tools available to Web developers. Using custom controls, you can encapsulate key aspects of the visual interface and program logic that you want to reuse throughout your application, or throughout your organization. What are the 3 types of custom controls in ASP.NET? Microsoft Visual Studio .NET provides three types of custom control for use on Web forms. 1. Web user controls These combine existing server and HTML controls by using the Visual Studio .NET Designer to create functional units that encapsulate some aspect of the user interface. User controls reside in content files, which must be included in the project in which the controls are used. 2. Composite custom controls These create new controls from existing server and HTML controls. Although similar to user controls, composite controls are created in code rather than visually, and therefore they can be compiled into an assembly (.dll), which can be shared between multiple applications and used from the Toolbox in Visual Studio .NET. 3. Rendered custom controls These create entirely new controls by rendering HTML directly rather than using composition. These controls are compiled and can be used from the Toolbox, just like composite controls, but you must write extra code to handle tasks that are performed automatically in composite controls. How do you identify user controls? User controls are identified by their .ascx file extensions. What is the base class from which user controls derive? User controls derive from System.Web.UI.UserControl base class. This base class provides the base set of properties and methods you use to create the control. 140Copyright©Sharma. All rights reserved.
  • 141. FAQ – 10 What are the 2 types of controls that you can use on a webform in ASP.NET? Web Server Controls HTML Controls What’s the difference between Server controls and HTML controls? 1. Server controls can trigger control-specific events on the server.HTML controls can trigger only page- level events on server (postback). 2. Data entered in a server control is maintained across requests. Server controls retain state.Data is not maintained in an HTML control. Data must be saved and restored using page-level scripts. 3. The Microsoft .NET Framework provides a set of properties for each server control. Properties allow you to change the server control’s appearance and behavior within server-side code.HTML controls have HTML attributes only. 4. Server controls automatically detect browser and adapt display as appropriate.HTML controls do not adapt automatically. You must detect browser in code or write for least common denominator. What are the 2 Layouts supported by a Web form in ASP.NET? Grid layout - Controls are placed exactly where you draw them, and they have absolute positions on the page. Use grid layout for Microsoft Windows–style applications, in which controls are not mixed with large amounts of text. Pages using grid layout will not always display correctly in non-Microsoft browsers. Flow layout - This layout positions controls relative to other elements on the page. If you add elements at run time, the controls that appear after the new element move down. Use flow layout for document-style applications, in which text and controls are intermingled. When do you choose between GridLayout and Flow layout for Web forms? You use GridLayout for Web forms that have a fixed appearance. You use FlowLayout for Web forms that incorporate text and controls.When you create controls with GridLayout, Visual Studio adds style attributes to each control that set the position of the control.When you create controls with FlowLayout, Visual Studio omits the style attribute. 141Copyright©Sharma. All rights reserved.
  • 142. FAQ – 11 What are Cookies in ASP.NET? Cookies are small pieces of information stored on the client computer.Use cookies to store small amounts of information on the client’s machine. Web sites often use cookies to store user preferences or other information that is client-specific. Because cookies can be refused, it is important to check whether the browser allows them before you try to create them.They are limited to storing only character data and they are limited to 4K in size. What are different types of Cookies? Session Cookies Persistent Cookies What is the difference between Session Cookies and Persistent Cookies? Persistent Cookies are same as Session Cookies except that, persistent cookies have an expiration date. The expiration date indicates to the browser that it should write the cookie to the client's hard drive. Keep in mind that because a user can delete cookies from their machine that there is no guarantee that a cookie you "drop" on a user machine will be there the next time they visit your site. 142Copyright©Sharma. All rights reserved.
  • 143. FAQ – 12 What are the different levels at which events can occur in an ASP.NET web application? Web application events occur at the application, page, and server control levels Give some examples for application level events? 1. Application_Start Occurs when the first user visits a page within your Web application. 2. Application_End Occurs when there are no more users of the application. 3. Application_BeginRequest Occurs when at the beginning of each request to the server. A request happens every time a browser navigates to any of the pages in the application. 4. Application_EndRequest Occurs when at the end of each request to the server. 5. Session_Start Occurs when a new user visits a page within your application. 6. Session_End Occurs when a user stops requesting pages from the Web application and their session times out. Sessions time out after a period specified in the Web.config file. 7. Application_Error Occurs when when there is an unhandled exception in an application. Where are the application level event handlers present in an ASP.NET web application? Application level event handlers are present in Global.asax of an ASP.NET web application 143Copyright©Sharma. All rights reserved.
  • 144. FAQ – 13 What are Exceptions? Exceptions are unusual occurrences that happen within the logic of an application. What are the 3 approaches to handle exceptions in a Web application? 1. Use exception-handling structures to deal with exceptions within the scope of a procedure. This technique is called structured exception handling (SEH) in the Visual Studio .NET documentation. try catch finally 2. Use error events to deal with exceptions within the scope of an object. Page_Error Global_Error Application_Error 3. Use custom error pages to display informational messages for unhandled exceptions within the scope of a Web application. Where will the control flow if an exception occurs inside a try block? If a statement in a try block causes an exception, control flow passes immediately to the next catch statement. When control flow passes to a catch block, the statements contained in the catch block are processed to correct the error or otherwise handle the exception. Will the finally block gets executed, if an exception occurs? Yes, a finally block will always be executed irrespective of whether an exception has occured or not. What is the main use of a finally block in exception handling? Finally block is mainly used to free resources used within the try block. How do you raise an exception? Use the throw keyword to raise an exception. Use this keyword within your exception-handling structure to immediately pass control flow to the catch statement. 144Copyright©Sharma. All rights reserved.
  • 145. FAQ – 14 What are the different techniques to send data from one web form to another web form? 1. Query strings : Use these strings to pass information between requests and responses as part of the Web address. Query strings are visible to the user, so they should not contain secure information such as passwords. 2. Cookies : Use cookies to store small amounts of information on a client. Clients might refuse cookies, so your code has to anticipate that possibility. 3. Session state : Use Session state variables to store items that you want keep local to the current session (single user). 4. Application state : Use Application state variables to store items that you want be available to all users of the application. 145Copyright©Sharma. All rights reserved.
  • 146. FAQ – 15 What are ASP.NET Validation controls? ASP.NET provides validation controls to help you check Web form data entries before the data is accepted and saved in the Database. Validation controls can be used to address the following questions. 1. Did the user enter anything? 2. Is the entry the appropriate kind of data (For example, Date of Birth should be a valid Date, Name should be a string etc.)? 3. Is the data within a required range?(For example age cannot be greater than 100 years) The validation controls check the validity of data entered in associated server controls on the client before the page is posted back to the server.Most validity problems can be caught and corrected by the user without a round-trip to the server. Where do the ASP.NET validation controls validate data, on the Client or on the Web Server? ASP.NET validation controls validate data first on the client and then on the web server. If a client disables javascript on the browser then, client side validations are bypassed and validations are performed on the web server. Client-side validation is provided by a JScript library named WebUIValidation.js, which is downloaded separately to the client. Validation controls also automatically provide server-side validation. Server-side validation is always performed, whether or not client-side validation has occurred. This double-checking ensures that custom validations are performed correctly and that client-side validation has not been circumvented. What are the 6 different validation controls provided by ASP.NET? RequiredFieldValidator:Checks whether a control contains data CompareValidator:Checks whether an entered item matches an entry in another control RangeValidator:Checks whether an entered item is between two values RegularExpressionValidator:Checks whether an entered item matches a specified format CustomValidator:Checks the validity of an entered item using a client-side script or a server-side code, or both ValidationSummary:Displays validation errors in a central location or display a general validation error description 146Copyright©Sharma. All rights reserved.
  • 147. FAQ – 16 What is ViewState? Web forms have very short lifetimes.In ASP.NET, the data that is entered in controls is encoded and stored in a hidden field. This encoded data is then sent with each request and restored to controls in Page_Init. The data in these controls is then available in the Page_Load event.The data that ASP.NET preserves between requests is called the Web form’s view state. How do you enable or disable a ViewState for a control on the page? Every ASP.NET control has a property called EnableViewState. If EnableViewState is set to true ViewState is enabled for the control. If EnableViewState is set to false ViewState is disabled for the control. How do you enable or disable a ViewState at the page level? At the page level you can enable or disable ViewState using EnableViewState property of the page. What is the name of the hidden form field in which ViewState of the page is saved? __ViewState 147Copyright©Sharma. All rights reserved.
  • 148. FAQ – 17 What are the 2 build options for an ASP.NET web application? 1. Debug 2. Release What are the 3 levels at which we can have a configuration file for an ASP.NET web application? 1. At the web server level : The Machine.config file located in the WindowsMicrosoft.NETFrameworkversionconfig directory. This sets the base configuration for all .NET assemblies running on the server. 2. At the application or web site level : The Web.config file located in the IIS root directory.This sets the base configuration for all Web applications and overrides settings in Machine.config. 3. In the sub directory of an application root folder : These settings override the settings in the root folder's web.config file. What happens when you make changes to an application’s Web.config file? When you make changes to an application’s Web.config file, IIS automatically restarts the application and applies the changes. This has the side effect of resetting current Application or Session state variables, which can adversely affect users. What happens when you access the Web.config file from a browser? For security reasons, you can’t access the Web.config file from a browser. If a user requests the Web.config file from your Web site, he or she will receive an "This type of page is not served" error message. What happens when you access the Global.asax file from a browser? For security reasons, you can’t access the Global.asax file from a browser. If a user requests the Global.asax file from your Web site, he or she will receive an "This type of page is not served" error message. 148Copyright©Sharma. All rights reserved.
  • 149. FAQ – 18 What are the 2 ways provided by ASP.NET to format output in a Web application? 1. Use cascading style sheets (CSS) to control the appearance of elements on a Web form.These styles can set the color, size, font, and behavior of the HTML elements on a Web page. 2. Use Extensible Stylesheet Language Transformations (XSLT) to convert information from an Extensible Markup Language (XML) file to HTML output and position that information on a Web form. XSLT puts data from the XML file into HTML elements and applies styles to those elements. What are Cascading style sheets? Cascading style sheets (CSS) collect and organize all of the formatting information applied to HTML elements on a Web form. Because they keep this information in a single location, style sheets make it easy to adjust the appearance of Web applications. What are the 3 levels at which formatting can be applied with in a web application? 1. Styles can be defined in a style sheet file. Styles in a style sheet can be applied to all webforms referencing the style sheet. 2. You can also define styles in the page’s head element. These styles can be applied to all elements on the current page. 3. You can also define styles inline, in the HTML tag itself. Inline styles are applicable only to the HTML element in which these styles are defined. Inline formatting takes precedence over local formatting, which, in turn, takes precedence over global formatting. These precedence rules are the reason style sheets are referred to as cascading. 149Copyright©Sharma. All rights reserved.